context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Buffers; using System.Collections.Generic; using System.Collections.Sequences; using System.Text; using Xunit; namespace System.Buffers.Tests { public partial class ReadOnlyBytesTests { [Fact] public void SingleSegmentBasics() { ReadOnlyBuffer<byte> buffer = new byte[] { 1, 2, 3, 4, 5, 6 }; var bytes = new ReadOnlyBytes(buffer); var sliced = bytes.Slice(1, 3); var span = sliced.First.Span; Assert.Equal((byte)2, span[0]); Assert.Equal(buffer.Length, bytes.Length.Value); Assert.Equal(buffer.Length, bytes.ComputeLength()); bytes = new ReadOnlyBytes(buffer, null, -1); Assert.False(bytes.Length.HasValue); Assert.Equal(buffer.Length, bytes.ComputeLength()); Assert.Equal(buffer.Length, bytes.Length.Value); } [Fact] public void MultiSegmentBasics() { var bytes = Parse("A|CD|EFG"); bytes = bytes.Slice(2, 3); Assert.Equal((byte)'D', bytes.First.Span[0]); bytes = Parse("A|CD|EFG"); Assert.False(bytes.Length.HasValue); Assert.Equal(6, bytes.ComputeLength()); Assert.Equal(6, bytes.Length.Value); } [Fact] public void SingleSegmentSlicing() { var array = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; ReadOnlyBuffer<byte> buffer = array; var bytes = new ReadOnlyBytes(buffer); ReadOnlyBytes sliced = bytes; ReadOnlySpan<byte> span; for(int i=1; i<=array.Length; i++) { sliced = bytes.Slice(i); span = sliced.First.Span; Assert.Equal(array.Length - i, span.Length); if(i!=array.Length) Assert.Equal(i, span[0]); } Assert.Equal(0, span.Length); } [Fact] public void MultiSegmentSlicing() { var array1 = new byte[] { 0, 1 }; var array2 = new byte[] { 2, 3 }; var totalLength = array1.Length + array2.Length; ReadOnlyBytes bytes = ReadOnlyBytes.Create(array1, array2); ReadOnlyBytes sliced = bytes; ReadOnlySpan<byte> span; for(int i=1; i<=totalLength; i++) { sliced = bytes.Slice(i); span = sliced.First.Span; Assert.Equal(totalLength - i, sliced.ComputeLength()); if(i!=totalLength) Assert.Equal(i, span[0]); } Assert.Equal(0, span.Length); } [Fact] public void SingleSegmentCopyToKnownLength() { var array = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; ReadOnlyBuffer<byte> buffer = array; var bytes = new ReadOnlyBytes(buffer, null, array.Length); { // copy to equal var copy = new byte[array.Length]; var copied = bytes.CopyTo(copy); Assert.Equal(array.Length, copied); Assert.Equal(array, copy); } { // copy to smaller var copy = new byte[array.Length - 1]; var copied = bytes.CopyTo(copy); Assert.Equal(copy.Length, copied); for(int i=0; i<copied; i++) { Assert.Equal(array[i], copy[i]); } } { // copy to larger var copy = new byte[array.Length + 1]; var copied = bytes.CopyTo(copy); Assert.Equal(array.Length, copied); for (int i = 0; i < copied; i++) { Assert.Equal(array[i], copy[i]); } } } [Fact] public void SingleSegmentCopyToUnknownLength() { var array = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; ReadOnlyBuffer<byte> buffer = array; var bytes = new ReadOnlyBytes(buffer, null, -1); { // copy to equal var copy = new byte[array.Length]; var copied = bytes.CopyTo(copy); Assert.Equal(array.Length, copied); Assert.Equal(array, copy); } { // copy to smaller var copy = new byte[array.Length - 1]; var copied = bytes.CopyTo(copy); Assert.Equal(copy.Length, copied); for (int i = 0; i < copied; i++) { Assert.Equal(array[i], copy[i]); } } { // copy to larger var copy = new byte[array.Length + 1]; var copied = bytes.CopyTo(copy); Assert.Equal(array.Length, copied); for (int i = 0; i < copied; i++) { Assert.Equal(array[i], copy[i]); } } } [Fact] public void MultiSegmentCopyToUnknownLength() { var array1 = new byte[] { 0, 1 }; var array2 = new byte[] { 2, 3 }; var totalLength = array1.Length + array2.Length; ReadOnlyBytes bytes = ReadOnlyBytes.Create(array1, array2); { // copy to equal var copy = new byte[totalLength]; var copied = bytes.CopyTo(copy); Assert.Equal(totalLength, copied); for (int i = 0; i < totalLength; i++) { Assert.Equal(i, copy[i]); } } { // copy to smaller var copy = new byte[totalLength - 1]; var copied = bytes.CopyTo(copy); Assert.Equal(copy.Length, copied); for (int i = 0; i < copied; i++) { Assert.Equal(i, copy[i]); } } { // copy to larger var copy = new byte[totalLength + 1]; var copied = bytes.CopyTo(copy); Assert.Equal(totalLength, copied); for (int i = 0; i < totalLength; i++) { Assert.Equal(i, copy[i]); } } } [Fact] public void MultiSegmentIndexOfSpan() { var bytes = ReadOnlyBytes.Create(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, new byte[] { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }); Assert.Equal(10, bytes.First.Length); Assert.Equal(9, bytes.First.Span[9]); Assert.NotEqual(null, bytes.Rest); var index = bytes.IndexOf(new byte[] { 2, 3 }); Assert.Equal(2, index); index = bytes.IndexOf(new byte[] { 8, 9, 10 }); Assert.Equal(8, index); index = bytes.IndexOf(new byte[] { 11, 12, 13, 14 }); Assert.Equal(11, index); index = bytes.IndexOf(new byte[] { 19 }); Assert.Equal(19, index); index = bytes.IndexOf(new byte[] { 0 }); Assert.Equal(0, index); index = bytes.IndexOf(new byte[] { 9 }); Assert.Equal(9, index); index = bytes.IndexOf(new byte[] { 10 }); Assert.Equal(10, index); } [Fact] public void MultiSegmentIndexOfByte() { var bytes = ReadOnlyBytes.Create(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, new byte[] { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }); Assert.Equal(10, bytes.First.Length); Assert.Equal(9, bytes.First.Span[9]); Assert.NotEqual(null, bytes.Rest); for(int i=0; i<20; i++){ var index = bytes.IndexOf((byte)i); Assert.Equal(i, index); } } [Fact] public void ReadOnlyBytesEnumeration() { var buffer = new byte[] { 1, 2, 3, 4, 5, 6 }; var bytes = new ReadOnlyBytes(buffer); var position = new Position(); int length = 0; ReadOnlyBuffer<byte> segment; while (bytes.TryGet(ref position, out segment)) { length += segment.Length; } Assert.Equal(buffer.Length, length); var multibytes = Parse("A|CD|EFG"); position = new Position(); length = 0; while (multibytes.TryGet(ref position, out segment)) { length += segment.Length; } Assert.Equal(6, length); } [Fact] public void ReadOnlyTailBytesEnumeration() { for (int i = 0; i < 6; i++) { var multibytes = Parse("A|CD|EFG"); multibytes = multibytes.Slice(i); var position = new Position(); var length = 0; ReadOnlyBuffer<byte> segment; while (multibytes.TryGet(ref position, out segment)) { length += segment.Length; } Assert.Equal(6 - i, length); } } [Fact] public void ReadOnlyFrontBytesEnumeration() { for (int i = 0; i < 7; i++) { var multibytes = Parse("A|CD|EFG"); multibytes = multibytes.Slice(0, i); var position = new Position(); var length = 0; ReadOnlyBuffer<byte> segment; while (multibytes.TryGet(ref position, out segment)) { length += segment.Length; } Assert.Equal(i, length); } } private ReadOnlyBytes Create(params string[] segments) { var buffers = new List<byte[]>(); foreach (var segment in segments) { buffers.Add(Encoding.UTF8.GetBytes(segment)); } return ReadOnlyBytes.Create(buffers.ToArray()); } private ReadOnlyBytes Parse(string text) { var segments = text.Split('|'); var buffers = new List<byte[]>(); foreach (var segment in segments) { buffers.Add(Encoding.UTF8.GetBytes(segment)); } return ReadOnlyBytes.Create(buffers.ToArray()); } } }
namespace Oscilloscope { using com.ibm.saguaro.system; using com.ibm.saguaro.logger; using Mac_Layer; using com.ibm.iris; /// <summary> /// The class that reads value from sensors and sends them with Mac to MasterOscilloscope. /// </summary> public class Oscilloscope { /// <summary> /// Instance of Mac used to send data. /// </summary> static Mac mac; #if SIM static Timer fake; #else static readonly uint MDA100_ADC_CHANNEL_MASK = 0x02; // Bit associated with the shared ADC // channel (channel 1 is shared between // temp and light sensor) // See ADC class documentation // See below // Sensors power pins internal static readonly byte TEMP_PWR_PIN = IRIS.PIN_PW0; // Temperature sensor power pin internal static readonly byte LIGHT_PWR_PIN = IRIS.PIN_INT5; // Temperature sensor power pin (on the doc is INT1 but is not available in com.ibm.iris) // To read sensor values static ADC adc ; // To power on the sensors static GPIO pwrPins; #endif /// <summary> /// Size of data to send MasterOscilloscope. /// </summary> const uint PAYLOAD_SIZE = 3; // 3 bytes flag + 2 bytes data internal static byte[] rpdu = new byte[PAYLOAD_SIZE]; // The read PDU /// <summary> /// The interval of readings. /// </summary> static long readInterval; // Read ADC every (Secs) // Payload flags /// <summary> /// Constant flag for temperature readings. /// </summary> const byte FLAG_TEMP = (byte)0x01; // Flag for temperature data /// <summary> /// Constant flag for light readings. /// </summary> const byte FLAG_LIGHT = (byte)0x02; // Flag for light data /// <summary> /// Initializes the <see cref="Oscilloscope.Oscilloscope"/> class. Prepares the mac associating to a PAN. /// </summary> static Oscilloscope () { mac = new Mac (); mac.enable (true); mac.setChannel (1); mac.setRxHandler (new DevCallback (onRxEvent)); mac.setTxHandler (new DevCallback (onTxEvent)); mac.setEventHandler (new DevCallback (onEvent)); mac.associate (0x0234); // convert 2 seconds to the platform ticks readInterval = Time.toTickSpan (Time.MILLISECS, 500); #if SIM fake = new Timer(); fake.setCallback (new TimerEvent(onFakeTimerEvent)); #else //GPIO, power pins pwrPins = new GPIO (); //ADC adc = new ADC (); adc.setReadHandler (new DevCallback (adcReadCallback)); adc.open (/* chmap */ MDA100_ADC_CHANNEL_MASK, /* GPIO power pin*/ GPIO.NO_PIN, /*no warmup*/0, /*no interval*/0); pwrPins.open (); pwrPins.configureOutput (TEMP_PWR_PIN, GPIO.OUT_SET); // power on the sensor rpdu [0] = FLAG_TEMP; // adc.read (Device.TIMED, 1, Time.currentTicks () + readInterval); #endif } #if SIM static void onFakeTimerEvent(byte param, long time){ Util.set16 (rpdu,1,Util.rand16 ()); mac.send(0x0002, 1, rpdu); // Logger.appendString(csr.s2b("Fake data sent")); // Logger.flush (Mote.INFO); fake.cancelAlarm (); fake.setAlarmTime (Time.currentTicks () + readInterval); } #else /// <summary> /// Method called when adc completes sensor reading. /// </summary> /// <returns> /// The read callback. /// </returns> /// </param> public static int adcReadCallback (uint flags, byte[] data, uint len, uint info, long time) { // if (len != 2 || ((flags & Device.FLAG_FAILED) != 0)) { // // Can't read sensors // LED.setState (IRIS.LED_RED, (byte)1); // return 0; // } else { // LED.setState (IRIS.LED_RED, (byte)0); // } Util.copyData (data, 0, rpdu, 1, 2); // Payload data bytes //Transmission LED.setState ((byte)2, (byte)1); mac.send (0x0002, 1, rpdu); // Schedule next read adc.read (Device.TIMED, 1, Time.currentTicks () + readInterval); return 0; } #endif //On transmission blink green led /// <summary> /// Mac tx event. /// </summary> /// <returns> /// An int with no meaning. /// </returns> /// <param name='flag'> /// Flag that indicates the event. /// </param> /// <param name='data'> /// Data transmitted /// </param> /// <param name='len'> /// Length of data. /// </param> /// <param name='info'> /// Info. /// </param> /// <param name='time'> /// The end of transmission. /// </param> public static int onTxEvent (uint flag, byte[] data, uint len, uint info, long time) { return 0; } /// <summary> /// Mac rx event. /// </summary> /// <returns> /// An int with no meaning. /// </returns> /// <param name='flag'> /// Flag that indicates the event. /// </param> /// <param name='data'> /// Data received. /// </param> /// <param name='len'> /// Length of data. /// </param> /// <param name='info'> /// Info. /// </param> /// <param name='time'> /// The end of reception. /// </param> public static int onRxEvent (uint flag, byte[] data, uint len, uint info, long time) { if (flag == Mac.MAC_DATA_RXED && data != null) { uint interval = Util.get16le (data, 2); readInterval = Time.toTickSpan (Time.MILLISECS, interval); Logger.appendString (csr.s2b ("Oscilloscope RX Event - ")); Logger.appendString (csr.s2b ("Interval: ")); Logger.appendLong (interval); Logger.flush (Mote.INFO); if (data [0] == FLAG_TEMP) { rpdu [0] = FLAG_TEMP; #if SIM #else Logger.appendString (csr.s2b (", FLAG_TEMP ")); // Powers ON temperature and ON light sensor pwrPins.configureOutput (TEMP_PWR_PIN, GPIO.OUT_SET); pwrPins.configureOutput (LIGHT_PWR_PIN, GPIO.OUT_CLR); #endif } else { rpdu [0] = FLAG_LIGHT; #if SIM #else // Powers ON light and OFF temperature sensor pwrPins.configureOutput (LIGHT_PWR_PIN, GPIO.OUT_SET); pwrPins.configureOutput (TEMP_PWR_PIN, GPIO.OUT_CLR); Logger.appendString (csr.s2b (", FLAG_LIGHT ")); #endif } if ((uint)data [1] == 1) { #if SIM fake.setAlarmBySpan (readInterval); #else if (adc.getState () == CDev.S_CLOSED) adc.open (/* chmap */ MDA100_ADC_CHANNEL_MASK, /* GPIO power pin*/ GPIO.NO_PIN, /*no warmup*/0, /*no interval*/0); if (pwrPins.getState () == CDev.S_CLOSED) pwrPins.open (); pwrPins.configureOutput (TEMP_PWR_PIN, GPIO.OUT_SET); adc.read (Device.TIMED, 1, Time.currentTicks () + readInterval); // Simulation #endif } else { #if SIM fake.cancelAlarm (); #else if (pwrPins.getState () != CDev.S_CLOSED) pwrPins.close (); if (adc.getState () != CDev.S_CLOSED) adc.close (); // adc.setState (CDev.S_OFF); #endif } Logger.flush (Mote.INFO); } else { Logger.appendString (csr.s2b ("DATA NULL")); Logger.flush (Mote.INFO); } return 0; } /// <summary> /// Handles Mac generic events. /// </summary> /// <returns> /// A value with no meaning. /// </returns> /// <param name='flag'> /// Flag that indicates the event. /// </param> /// <param name='data'> /// Data associated to event. /// </param> /// <param name='len'> /// Length of data. /// </param> /// <param name='info'> /// Info. /// </param> /// <param name='time'> /// The time when the event occurred. /// </param> public static int onEvent (uint flag, byte[] data, uint len, uint info, long time) { switch (flag) { case Mac.MAC_ASSOCIATED: // adc.read(Device.TIMED, 1, Time.currentTicks() + readInterval); break; case Mac.MAC_BEACON_RXED: break; default: return 0; } return 0; } } }
using Lucene.Net.Util; using System; using System.IO; using System.Text; namespace Lucene.Net.Index { /* * 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 Analyzer = Lucene.Net.Analysis.Analyzer; using Codec = Lucene.Net.Codecs.Codec; using IndexingChain = Lucene.Net.Index.DocumentsWriterPerThread.IndexingChain; using IndexReaderWarmer = Lucene.Net.Index.IndexWriter.IndexReaderWarmer; using InfoStream = Lucene.Net.Util.InfoStream; using TextWriterInfoStream = Lucene.Net.Util.TextWriterInfoStream; using Similarity = Lucene.Net.Search.Similarities.Similarity; /// <summary> /// Holds all the configuration that is used to create an <see cref="IndexWriter"/>. /// Once <see cref="IndexWriter"/> has been created with this object, changes to this /// object will not affect the <see cref="IndexWriter"/> instance. For that, use /// <see cref="LiveIndexWriterConfig"/> that is returned from <see cref="IndexWriter.Config"/>. /// /// <para/> /// LUCENENET NOTE: Unlike Lucene, we use property setters instead of setter methods. /// In C#, this allows you to initialize the <see cref="IndexWriterConfig"/> /// using the language features of C#, for example: /// <code> /// IndexWriterConfig conf = new IndexWriterConfig(analyzer) /// { /// Codec = Lucene46Codec(), /// OpenMode = OpenMode.CREATE /// }; /// </code> /// /// However, if you prefer to match the syntax of Lucene using chained setter methods, /// there are extension methods in the Lucene.Net.Support namespace. Example usage: /// <code> /// using Lucene.Net.Support; /// /// .. /// /// IndexWriterConfig conf = new IndexWriterConfig(analyzer) /// .SetCodec(new Lucene46Codec()) /// .SetOpenMode(OpenMode.CREATE); /// </code> /// /// @since 3.1 /// </summary> /// <seealso cref="IndexWriter.Config"/> #if FEATURE_SERIALIZABLE [Serializable] #endif public sealed class IndexWriterConfig : LiveIndexWriterConfig #if FEATURE_CLONEABLE , System.ICloneable #endif { // LUCENENET specific: De-nested OpenMode enum from this class to prevent naming conflict /// <summary> /// Default value is 32. Change using <see cref="LiveIndexWriterConfig.TermIndexInterval"/> setter. </summary> public static readonly int DEFAULT_TERM_INDEX_INTERVAL = 32; // TODO: this should be private to the codec, not settable here /// <summary> /// Denotes a flush trigger is disabled. </summary> public static readonly int DISABLE_AUTO_FLUSH = -1; /// <summary> /// Disabled by default (because IndexWriter flushes by RAM usage by default). </summary> public static readonly int DEFAULT_MAX_BUFFERED_DELETE_TERMS = DISABLE_AUTO_FLUSH; /// <summary> /// Disabled by default (because IndexWriter flushes by RAM usage by default). </summary> public static readonly int DEFAULT_MAX_BUFFERED_DOCS = DISABLE_AUTO_FLUSH; /// <summary> /// Default value is 16 MB (which means flush when buffered docs consume /// approximately 16 MB RAM). /// </summary> public static readonly double DEFAULT_RAM_BUFFER_SIZE_MB = 16.0; /// <summary> /// Default value for the write lock timeout (1,000 ms). /// </summary> /// <see cref="DefaultWriteLockTimeout"/> public static long WRITE_LOCK_TIMEOUT = 1000; /// <summary> /// Default setting for <see cref="UseReaderPooling"/>. </summary> public static readonly bool DEFAULT_READER_POOLING = false; /// <summary> /// Default value is 1. Change using <see cref="LiveIndexWriterConfig.ReaderTermsIndexDivisor"/> setter. </summary> public static readonly int DEFAULT_READER_TERMS_INDEX_DIVISOR = DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR; /// <summary> /// Default value is 1945. Change using <see cref="RAMPerThreadHardLimitMB"/> setter. </summary> public static readonly int DEFAULT_RAM_PER_THREAD_HARD_LIMIT_MB = 1945; /// <summary> /// The maximum number of simultaneous threads that may be /// indexing documents at once in <see cref="IndexWriter"/>; if more /// than this many threads arrive they will wait for /// others to finish. Default value is 8. /// </summary> public static readonly int DEFAULT_MAX_THREAD_STATES = 8; /// <summary> /// Default value for compound file system for newly written segments /// (set to <c>true</c>). For batch indexing with very large /// ram buffers use <c>false</c> /// </summary> public static readonly bool DEFAULT_USE_COMPOUND_FILE_SYSTEM = true; /// <summary> /// Default value for calling <see cref="AtomicReader.CheckIntegrity()"/> before /// merging segments (set to <c>false</c>). You can set this /// to <c>true</c> for additional safety. /// </summary> public static readonly bool DEFAULT_CHECK_INTEGRITY_AT_MERGE = false; /// <summary> /// Gets or sets the default (for any instance) maximum time to wait for a write lock /// (in milliseconds). /// </summary> public static long DefaultWriteLockTimeout { set { WRITE_LOCK_TIMEOUT = value; } get { return WRITE_LOCK_TIMEOUT; } } // indicates whether this config instance is already attached to a writer. // not final so that it can be cloned properly. private SetOnce<IndexWriter> writer = new SetOnce<IndexWriter>(); /// <summary> /// Gets or sets the <see cref="IndexWriter"/> this config is attached to. /// </summary> /// <exception cref="Util.AlreadySetException"> /// if this config is already attached to a writer. </exception> internal IndexWriterConfig SetIndexWriter(IndexWriter writer) { this.writer.Set(writer); return this; } /// <summary> /// Creates a new config that with defaults that match the specified /// <see cref="LuceneVersion"/> as well as the default /// <see cref="Analyzer"/>. If <paramref name="matchVersion"/> is &gt;= /// <see cref="LuceneVersion.LUCENE_32"/>, <see cref="TieredMergePolicy"/> is used /// for merging; else <see cref="LogByteSizeMergePolicy"/>. /// Note that <see cref="TieredMergePolicy"/> is free to select /// non-contiguous merges, which means docIDs may not /// remain monotonic over time. If this is a problem you /// should switch to <see cref="LogByteSizeMergePolicy"/> or /// <see cref="LogDocMergePolicy"/>. /// </summary> public IndexWriterConfig(LuceneVersion matchVersion, Analyzer analyzer) : base(analyzer, matchVersion) { } public object Clone() { IndexWriterConfig clone = (IndexWriterConfig)this.MemberwiseClone(); clone.writer = (SetOnce<IndexWriter>)writer.Clone(); // Mostly shallow clone, but do a deepish clone of // certain objects that have state that cannot be shared // across IW instances: clone.delPolicy = (IndexDeletionPolicy)delPolicy.Clone(); clone.flushPolicy = (FlushPolicy)flushPolicy.Clone(); clone.indexerThreadPool = (DocumentsWriterPerThreadPool)indexerThreadPool.Clone(); // we clone the infoStream because some impls might have state variables // such as line numbers, message throughput, ... clone.infoStream = (InfoStream)infoStream.Clone(); clone.mergePolicy = (MergePolicy)mergePolicy.Clone(); clone.mergeScheduler = (IMergeScheduler)mergeScheduler.Clone(); return clone; // LUCENENET specific - no need to deal with checked exceptions here } /// <summary> /// Specifies <see cref="Index.OpenMode"/> of the index. /// /// <para/>Only takes effect when <see cref="IndexWriter"/> is first created. /// </summary> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new public OpenMode OpenMode { get { return openMode; } set { // LUCENENET specific - making non-nullable, so we don't need to worry about this. //if (value == null) //{ // throw new System.ArgumentException("openMode must not be null"); //} this.openMode = value; } } /// <summary> /// Expert: allows an optional <see cref="Index.IndexDeletionPolicy"/> implementation to be /// specified. You can use this to control when prior commits are deleted from /// the index. The default policy is <see cref="KeepOnlyLastCommitDeletionPolicy"/> /// which removes all prior commits as soon as a new commit is done (this /// matches behavior before 2.2). Creating your own policy can allow you to /// explicitly keep previous "point in time" commits alive in the index for /// some time, to allow readers to refresh to the new commit without having the /// old commit deleted out from under them. This is necessary on filesystems /// like NFS that do not support "delete on last close" semantics, which /// Lucene's "point in time" search normally relies on. /// <para/> /// <b>NOTE:</b> the deletion policy cannot be <c>null</c>. /// /// <para/>Only takes effect when IndexWriter is first created. /// </summary> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new public IndexDeletionPolicy IndexDeletionPolicy { get { return delPolicy; } set { if (value == null) { throw new System.ArgumentException("indexDeletionPolicy must not be null"); } this.delPolicy = value; } } /// <summary> /// Expert: allows to open a certain commit point. The default is <c>null</c> which /// opens the latest commit point. /// /// <para/>Only takes effect when <see cref="IndexWriter"/> is first created. /// </summary> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new public IndexCommit IndexCommit { get { return commit; } set { this.commit = value; } } /// <summary> /// Expert: set the <see cref="Search.Similarities.Similarity"/> implementation used by this <see cref="IndexWriter"/>. /// <para/> /// <b>NOTE:</b> the similarity cannot be <c>null</c>. /// /// <para/>Only takes effect when <see cref="IndexWriter"/> is first created. /// </summary> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new public Similarity Similarity { get { return similarity; } set { if (value == null) { throw new System.ArgumentException("similarity must not be null"); } this.similarity = value; } } #if !FEATURE_CONCURRENTMERGESCHEDULER /// <summary> /// Expert: Gets or sets the merge scheduler used by this writer. The default is /// <see cref="TaskMergeScheduler"/>. /// <para/> /// <b>NOTE:</b> the merge scheduler cannot be <c>null</c>. /// /// <para/>Only takes effect when <see cref="IndexWriter"/> is first created. /// </summary> #else /// <summary> /// Expert: Gets or sets the merge scheduler used by this writer. The default is /// <see cref="ConcurrentMergeScheduler"/>. /// <para/> /// <b>NOTE:</b> the merge scheduler cannot be <c>null</c>. /// /// <para/>Only takes effect when <see cref="IndexWriter"/> is first created. /// </summary> #endif // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new public IMergeScheduler MergeScheduler { get { return mergeScheduler; } set { if (value == null) { throw new System.ArgumentException("mergeScheduler must not be null"); } this.mergeScheduler = value; } } /// <summary> /// Gets or sets the maximum time to wait for a write lock (in milliseconds) for this /// instance. You can change the default value for all instances by calling the /// <see cref="DefaultWriteLockTimeout"/> setter. /// /// <para/>Only takes effect when <see cref="IndexWriter"/> is first created. /// </summary> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new public long WriteLockTimeout { get { return writeLockTimeout; } set { this.writeLockTimeout = value; } } /// <summary> /// Gets or sets the <see cref="Codecs.Codec"/>. /// /// <para/> /// Only takes effect when <see cref="IndexWriter"/> is first created. /// </summary> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new public Codec Codec { get { return codec; } set { if (value == null) { throw new System.ArgumentException("codec must not be null"); } this.codec = value; } } /// <summary> /// Expert: <see cref="Index.MergePolicy"/> is invoked whenever there are changes to the /// segments in the index. Its role is to select which merges to do, if any, /// and return a <see cref="MergePolicy.MergeSpecification"/> describing the merges. /// It also selects merges to do for <see cref="IndexWriter.ForceMerge(int)"/>. /// /// <para/>Only takes effect when <see cref="IndexWriter"/> is first created. /// </summary> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new public MergePolicy MergePolicy { get { return mergePolicy; } set { if (value == null) { throw new System.ArgumentException("mergePolicy must not be null"); } this.mergePolicy = value; } } /// <summary> /// Expert: Gets or sets the <see cref="DocumentsWriterPerThreadPool"/> instance used by the /// <see cref="IndexWriter"/> to assign thread-states to incoming indexing threads. If no /// <see cref="DocumentsWriterPerThreadPool"/> is set <see cref="IndexWriter"/> will use /// <see cref="ThreadAffinityDocumentsWriterThreadPool"/> with max number of /// thread-states set to <see cref="DEFAULT_MAX_THREAD_STATES"/> (see /// <see cref="DEFAULT_MAX_THREAD_STATES"/>). /// <para> /// NOTE: The given <see cref="DocumentsWriterPerThreadPool"/> instance must not be used with /// other <see cref="IndexWriter"/> instances once it has been initialized / associated with an /// <see cref="IndexWriter"/>. /// </para> /// <para> /// NOTE: this only takes effect when <see cref="IndexWriter"/> is first created.</para> /// </summary> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new internal DocumentsWriterPerThreadPool IndexerThreadPool { get { return indexerThreadPool; } set { if (value == null) { throw new System.ArgumentException("threadPool must not be null"); } this.indexerThreadPool = value; } } /// <summary> /// Gets or sets the max number of simultaneous threads that may be indexing documents /// at once in <see cref="IndexWriter"/>. Values &lt; 1 are invalid and if passed /// <c>maxThreadStates</c> will be set to /// <see cref="DEFAULT_MAX_THREAD_STATES"/>. /// /// <para/>Only takes effect when <see cref="IndexWriter"/> is first created. /// </summary> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new public int MaxThreadStates { get { try { return ((ThreadAffinityDocumentsWriterThreadPool)indexerThreadPool).MaxThreadStates; } catch (System.InvalidCastException cce) { throw new InvalidOperationException(cce.Message, cce); } } set { this.indexerThreadPool = new ThreadAffinityDocumentsWriterThreadPool(value); } } /// <summary> /// By default, <see cref="IndexWriter"/> does not pool the /// <see cref="SegmentReader"/>s it must open for deletions and /// merging, unless a near-real-time reader has been /// obtained by calling <see cref="DirectoryReader.Open(IndexWriter, bool)"/>. /// this setting lets you enable pooling without getting a /// near-real-time reader. NOTE: if you set this to /// <c>false</c>, <see cref="IndexWriter"/> will still pool readers once /// <see cref="DirectoryReader.Open(IndexWriter, bool)"/> is called. /// /// <para/>Only takes effect when <see cref="IndexWriter"/> is first created. /// </summary> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new public bool UseReaderPooling { get { return readerPooling; } set { this.readerPooling = value; } } /// <summary> /// Expert: Gets or sets the <see cref="DocConsumer"/> chain to be used to process documents. /// /// <para/>Only takes effect when <see cref="IndexWriter"/> is first created. /// </summary> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new internal IndexingChain IndexingChain { get { return indexingChain; } set { if (value == null) { throw new System.ArgumentException("indexingChain must not be null"); } this.indexingChain = value; } } /// <summary> /// Expert: Gets or sets the maximum memory consumption per thread triggering a forced /// flush if exceeded. A <see cref="DocumentsWriterPerThread"/> is forcefully flushed /// once it exceeds this limit even if the <see cref="LiveIndexWriterConfig.RAMBufferSizeMB"/> has /// not been exceeded. This is a safety limit to prevent a /// <see cref="DocumentsWriterPerThread"/> from address space exhaustion due to its /// internal 32 bit signed integer based memory addressing. /// The given value must be less that 2GB (2048MB). /// </summary> /// <seealso cref="DEFAULT_RAM_PER_THREAD_HARD_LIMIT_MB"/> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new public int RAMPerThreadHardLimitMB { get { return perThreadHardLimitMB; } set { if (value <= 0 || value >= 2048) { throw new System.ArgumentException("PerThreadHardLimit must be greater than 0 and less than 2048MB"); } this.perThreadHardLimitMB = value; } } /// <summary> /// Expert: Controls when segments are flushed to disk during indexing. /// The <see cref="Index.FlushPolicy"/> initialized during <see cref="IndexWriter"/> instantiation and once initialized /// the given instance is bound to this <see cref="IndexWriter"/> and should not be used with another writer. /// </summary> /// <seealso cref="LiveIndexWriterConfig.MaxBufferedDeleteTerms"/> /// <seealso cref="LiveIndexWriterConfig.MaxBufferedDocs"/> /// <seealso cref="LiveIndexWriterConfig.RAMBufferSizeMB"/> // LUCENENET NOTE: We cannot override a getter and add a setter, // so must declare it new. See: http://stackoverflow.com/q/82437 new internal FlushPolicy FlushPolicy { get { return flushPolicy; } set { if (value == null) { throw new System.ArgumentException("flushPolicy must not be null"); } this.flushPolicy = value; } } // LUCENENT NOTE: The following properties would be pointless, // since they are already inherited by the base class. //public override InfoStream InfoStream //{ // get // { // return infoStream; // } //} //public override Analyzer Analyzer //{ // get // { // return base.Analyzer; // } //} //public override int MaxBufferedDeleteTerms //{ // get // { // return base.MaxBufferedDeleteTerms; // } //} //public override int MaxBufferedDocs //{ // get // { // return base.MaxBufferedDocs; // } //} //public override IndexReaderWarmer MergedSegmentWarmer //{ // get // { // return base.MergedSegmentWarmer; // } //} //public override double RAMBufferSizeMB //{ // get // { // return base.RAMBufferSizeMB; // } //} //public override int ReaderTermsIndexDivisor //{ // get // { // return base.ReaderTermsIndexDivisor; // } //} //public override int TermIndexInterval //{ // get // { // return base.TermIndexInterval; // } //} /// <summary> /// Information about merges, deletes and a /// message when maxFieldLength is reached will be printed /// to this. Must not be <c>null</c>, but <see cref="InfoStream.NO_OUTPUT"/> /// may be used to supress output. /// </summary> public IndexWriterConfig SetInfoStream(InfoStream infoStream) { if (infoStream == null) { throw new System.ArgumentException("Cannot set InfoStream implementation to null. " + "To disable logging use InfoStream.NO_OUTPUT"); } this.infoStream = infoStream; return this; } /// <summary> /// Convenience method that uses <see cref="TextWriterInfoStream"/> to write to the passed in <see cref="TextWriter"/>. /// Must not be <c>null</c>. /// </summary> public IndexWriterConfig SetInfoStream(TextWriter printStream) { if (printStream == null) { throw new System.ArgumentException("printStream must not be null"); } return SetInfoStream(new TextWriterInfoStream(printStream)); } // LUCENENET NOTE: These were only here for casting purposes, but since we are // using property setters, they are not needed //new public IndexWriterConfig SetMaxBufferedDeleteTerms(int maxBufferedDeleteTerms) //{ // return (IndexWriterConfig)base.SetMaxBufferedDeleteTerms(maxBufferedDeleteTerms); //} //new public IndexWriterConfig SetMaxBufferedDocs(int maxBufferedDocs) //{ // return (IndexWriterConfig)base.SetMaxBufferedDocs(maxBufferedDocs); //} //new public IndexWriterConfig SetMergedSegmentWarmer(IndexReaderWarmer mergeSegmentWarmer) //{ // return (IndexWriterConfig)base.SetMergedSegmentWarmer(mergeSegmentWarmer); //} //new public IndexWriterConfig SetRAMBufferSizeMB(double ramBufferSizeMB) //{ // return (IndexWriterConfig)base.SetRAMBufferSizeMB(ramBufferSizeMB); //} //new public IndexWriterConfig SetReaderTermsIndexDivisor(int divisor) //{ // return (IndexWriterConfig)base.SetReaderTermsIndexDivisor(divisor); //} //new public IndexWriterConfig SetTermIndexInterval(int interval) //{ // return (IndexWriterConfig)base.SetTermIndexInterval(interval); //} //new public IndexWriterConfig SetUseCompoundFile(bool useCompoundFile) //{ // return (IndexWriterConfig)base.SetUseCompoundFile(useCompoundFile); //} //new public IndexWriterConfig SetCheckIntegrityAtMerge(bool checkIntegrityAtMerge) //{ // return (IndexWriterConfig)base.SetCheckIntegrityAtMerge(checkIntegrityAtMerge); //} public override string ToString() { StringBuilder sb = new StringBuilder(base.ToString()); sb.Append("writer=").Append(writer).Append("\n"); return sb.ToString(); } } /// <summary> /// Specifies the open mode for <see cref="IndexWriter"/>. /// </summary> public enum OpenMode // LUCENENET specific: De-nested from IndexWriterConfig to prevent naming conflict { /// <summary> /// Creates a new index or overwrites an existing one. /// </summary> CREATE, /// <summary> /// Opens an existing index. /// </summary> APPEND, /// <summary> /// Creates a new index if one does not exist, /// otherwise it opens the index and documents will be appended. /// </summary> CREATE_OR_APPEND } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Xml; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { internal class PSClassHelpProvider : HelpProviderWithCache { /// <summary> /// Constructor for PSClassHelpProvider. /// </summary> internal PSClassHelpProvider(HelpSystem helpSystem) : base(helpSystem) { _context = helpSystem.ExecutionContext; } /// <summary> /// Execution context of the HelpSystem. /// </summary> private readonly ExecutionContext _context; /// <summary> /// This is a hashtable to track which help files are loaded already. /// /// This will avoid one help file getting loaded again and again. /// </summary> private readonly Hashtable _helpFiles = new Hashtable(); [TraceSource("PSClassHelpProvider", "PSClassHelpProvider")] private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("PSClassHelpProvider", "PSClassHelpProvider"); #region common properties /// <summary> /// Name of the Help Provider. /// </summary> internal override string Name { get { return "Powershell Class Help Provider"; } } /// <summary> /// Supported Help Categories. /// </summary> internal override HelpCategory HelpCategory { get { return Automation.HelpCategory.Class; } } #endregion /// <summary> /// Override SearchHelp to find a class module with help matching a pattern. /// </summary> /// <param name="helpRequest">Help request.</param> /// <param name="searchOnlyContent">Not used.</param> /// <returns></returns> internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { Debug.Assert(helpRequest != null, "helpRequest cannot be null."); string target = helpRequest.Target; Collection<string> patternList = new Collection<string>(); bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(helpRequest.Target); if (decoratedSearch) { patternList.Add("*" + target + "*"); } else patternList.Add(target); bool useWildCards = true; foreach (string pattern in patternList) { PSClassSearcher searcher = new PSClassSearcher(pattern, useWildCards, _context); foreach (var helpInfo in GetHelpInfo(searcher)) { if (helpInfo != null) yield return helpInfo; } } } /// <summary> /// Override ExactMatchHelp to find the matching class module matching help request. /// </summary> /// <param name="helpRequest">Help Request for the search.</param> /// <returns>Enumerable of HelpInfo objects.</returns> internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest) { Debug.Assert(helpRequest != null, "helpRequest cannot be null."); if ((helpRequest.HelpCategory & Automation.HelpCategory.Class) == 0) { yield return null; } string target = helpRequest.Target; bool useWildCards = false; PSClassSearcher searcher = new PSClassSearcher(target, useWildCards, _context); foreach (var helpInfo in GetHelpInfo(searcher)) { if (helpInfo != null) { yield return helpInfo; } } } /// <summary> /// Get the help in for the PS Class Info. /// /// </summary> /// <param name="searcher">Searcher for PS Classes.</param> /// <returns>Next HelpInfo object.</returns> private IEnumerable<HelpInfo> GetHelpInfo(PSClassSearcher searcher) { while (searcher.MoveNext()) { PSClassInfo current = ((IEnumerator<PSClassInfo>)searcher).Current; string moduleName = current.Module.Name; string moduleDir = current.Module.ModuleBase; if (!string.IsNullOrEmpty(moduleName) && !string.IsNullOrEmpty(moduleDir)) { string helpFileToFind = moduleName + "-Help.xml"; string helpFileName = null; Collection<string> searchPaths = new Collection<string>(); searchPaths.Add(moduleDir); string externalHelpFile = current.HelpFile; if (!string.IsNullOrEmpty(externalHelpFile)) { FileInfo helpFileInfo = new FileInfo(externalHelpFile); DirectoryInfo dirToSearch = helpFileInfo.Directory; if (dirToSearch.Exists) { searchPaths.Add(dirToSearch.FullName); helpFileToFind = helpFileInfo.Name; // If external help file is specified. Then use it. } } HelpInfo helpInfo = GetHelpInfoFromHelpFile(current, helpFileToFind, searchPaths, true, out helpFileName); if (helpInfo != null) { yield return helpInfo; } } } } /// <summary> /// Check whether a HelpItems node indicates that the help content is /// authored using maml schema. /// /// This covers two cases: /// a. If the help file has an extension .maml. /// b. If HelpItems node (which should be the top node of any command help file) /// has an attribute "schema" with value "maml", its content is in maml /// schema. /// </summary> /// <param name="helpFile">File name.</param> /// <param name="helpItemsNode">Nodes to check.</param> /// <returns></returns> internal static bool IsMamlHelp(string helpFile, XmlNode helpItemsNode) { Debug.Assert(!string.IsNullOrEmpty(helpFile), "helpFile cannot be null."); if (helpFile.EndsWith(".maml", StringComparison.OrdinalIgnoreCase)) return true; if (helpItemsNode.Attributes == null) return false; foreach (XmlNode attribute in helpItemsNode.Attributes) { if (attribute.Name.Equals("schema", StringComparison.OrdinalIgnoreCase) && attribute.Value.Equals("maml", StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } #region private methods private HelpInfo GetHelpInfoFromHelpFile(PSClassInfo classInfo, string helpFileToFind, Collection<string> searchPaths, bool reportErrors, out string helpFile) { Dbg.Assert(classInfo != null, "Caller should verify that classInfo != null"); Dbg.Assert(helpFileToFind != null, "Caller should verify that helpFileToFind != null"); helpFile = MUIFileSearcher.LocateFile(helpFileToFind, searchPaths); if (!File.Exists(helpFile)) return null; if (!string.IsNullOrEmpty(helpFile)) { // Load the help file only once. Then use it from the cache. if (!_helpFiles.Contains(helpFile)) { LoadHelpFile(helpFile, helpFile, classInfo.Name, reportErrors); } return GetFromPSClassHelpCache(helpFile, Automation.HelpCategory.Class); } return null; } /// <summary> /// Gets the HelpInfo object corresponding to the command. /// </summary> /// <param name="helpFileIdentifier">Help file identifier (either name of PSSnapIn or simply full path to help file).</param> /// <param name="helpCategory">Help Category for search.</param> /// <returns>HelpInfo object.</returns> private HelpInfo GetFromPSClassHelpCache(string helpFileIdentifier, HelpCategory helpCategory) { Debug.Assert(!string.IsNullOrEmpty(helpFileIdentifier), "helpFileIdentifier should not be null or empty."); HelpInfo result = GetCache(helpFileIdentifier); if (result != null) { MamlClassHelpInfo original = (MamlClassHelpInfo)result; result = original.Copy(helpCategory); } return result; } private void LoadHelpFile(string helpFile, string helpFileIdentifier, string commandName, bool reportErrors) { Exception e = null; try { LoadHelpFile(helpFile, helpFileIdentifier); } catch (IOException ioException) { e = ioException; } catch (System.Security.SecurityException securityException) { e = securityException; } catch (XmlException xmlException) { e = xmlException; } catch (NotSupportedException notSupportedException) { e = notSupportedException; } catch (UnauthorizedAccessException unauthorizedAccessException) { e = unauthorizedAccessException; } catch (InvalidOperationException invalidOperationException) { e = invalidOperationException; } if (e != null) s_tracer.WriteLine("Error occured in PSClassHelpProvider {0}", e.Message); if (reportErrors && (e != null)) { ReportHelpFileError(e, commandName, helpFile); } } /// <summary> /// Load help file for HelpInfo objects. The HelpInfo objects will be /// put into help cache. /// </summary> /// <remarks> /// 1. Needs to pay special attention about error handling in this function. /// Common errors include: file not found and invalid xml. None of these error /// should cause help search to stop. /// 2. a helpfile cache is used to avoid same file got loaded again and again. /// </remarks> private void LoadHelpFile(string helpFile, string helpFileIdentifier) { Dbg.Assert(!string.IsNullOrEmpty(helpFile), "HelpFile cannot be null or empty."); Dbg.Assert(!string.IsNullOrEmpty(helpFileIdentifier), "helpFileIdentifier cannot be null or empty."); XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( new FileInfo(helpFile), false, /* ignore whitespace, comments, etc. */ null); /* default maxCharactersInDocument */ // Add this file into _helpFiles hashtable to prevent it to be loaded again. _helpFiles[helpFile] = 0; XmlNode helpItemsNode = null; if (doc.HasChildNodes) { for (int i = 0; i < doc.ChildNodes.Count; i++) { XmlNode node = doc.ChildNodes[i]; if (node.NodeType == XmlNodeType.Element && string.Compare(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase) == 0) { helpItemsNode = node; break; } } } if (helpItemsNode == null) { s_tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile); return; } bool isMaml = IsMamlHelp(helpFile, helpItemsNode); using (this.HelpSystem.Trace(helpFile)) { if (helpItemsNode.HasChildNodes) { for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++) { XmlNode node = helpItemsNode.ChildNodes[i]; string nodeLocalName = node.LocalName; bool isClass = (string.Compare(nodeLocalName, "class", StringComparison.OrdinalIgnoreCase) == 0); if (node.NodeType == XmlNodeType.Element && isClass) { MamlClassHelpInfo helpInfo = null; if (isMaml) { if (isClass) helpInfo = MamlClassHelpInfo.Load(node, HelpCategory.Class); } if (helpInfo != null) { this.HelpSystem.TraceErrors(helpInfo.Errors); AddCache(helpFileIdentifier, helpInfo); } } } } } } #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 Xunit; namespace System.Tests { public partial class VersionTests { [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Ctor_String(string input, Version expected) { Assert.Equal(expected, new Version(input)); } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Ctor_String_Invalid(string input, Type exceptionType) { Assert.Throws(exceptionType, () => new Version(input)); // Input is invalid } [Theory] [InlineData(0, 0)] [InlineData(2, 3)] [InlineData(int.MaxValue, int.MaxValue)] public static void Ctor_Int_Int(int major, int minor) { VerifyVersion(new Version(major, minor), major, minor, -1, -1); } [Fact] public static void Ctor_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0)); // Major < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1)); // Minor < 0 } [Theory] [InlineData(0, 0, 0)] [InlineData(2, 3, 4)] [InlineData(int.MaxValue, int.MaxValue, int.MaxValue)] public static void Ctor_Int_Int_Int(int major, int minor, int build) { VerifyVersion(new Version(major, minor, build), major, minor, build, -1); } [Fact] public static void Ctor_Int_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0)); // Major < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0)); // Minor < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1)); // Build < 0 } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(2, 3, 4, 7)] [InlineData(2, 3, 4, 32767)] [InlineData(2, 3, 4, 32768)] [InlineData(2, 3, 4, 65535)] [InlineData(2, 3, 4, 65536)] [InlineData(2, 3, 4, 2147483647)] [InlineData(2, 3, 4, 2147450879)] [InlineData(2, 3, 4, 2147418112)] [InlineData(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue)] public static void Ctor_Int_Int_Int_Int(int major, int minor, int build, int revision) { VerifyVersion(new Version(major, minor, build, revision), major, minor, build, revision); } [Fact] public static void Ctor_Int_Int_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0, 0)); // Major < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0, 0)); // Minor < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1, 0)); // Build < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("revision", () => new Version(0, 0, 0, -1)); // Revision < 0 } public static IEnumerable<object[]> CompareTo_TestData() { yield return new object[] { new Version(1, 2), null, 1 }; yield return new object[] { new Version(1, 2), new Version(1, 2), 0 }; yield return new object[] { new Version(1, 2), new Version(1, 3), -1 }; yield return new object[] { new Version(1, 2), new Version(1, 1), 1 }; yield return new object[] { new Version(1, 2), new Version(2, 0), -1 }; yield return new object[] { new Version(1, 2), new Version(1, 2, 1), -1 }; yield return new object[] { new Version(1, 2), new Version(1, 2, 0, 1), -1 }; yield return new object[] { new Version(1, 2), new Version(1, 0), 1 }; yield return new object[] { new Version(1, 2), new Version(1, 0, 1), 1 }; yield return new object[] { new Version(1, 2), new Version(1, 0, 0, 1), 1 }; yield return new object[] { new Version(3, 2, 1), new Version(2, 2, 1), 1 }; yield return new object[] { new Version(3, 2, 1), new Version(3, 1, 1), 1 }; yield return new object[] { new Version(3, 2, 1), new Version(3, 2, 0), 1 }; yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 4), 0 }; yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 5), -1 }; yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 3), 1 }; } [Theory] [MemberData(nameof(CompareTo_TestData))] public static void CompareTo(Version version1, Version version2, int expectedSign) { Assert.Equal(expectedSign, Math.Sign(version1.CompareTo(version2))); if (version1 != null && version2 != null) { if (expectedSign >= 0) { Assert.True(version1 >= version2); Assert.False(version1 < version2); } if (expectedSign > 0) { Assert.True(version1 > version2); Assert.False(version1 <= version2); } if (expectedSign <= 0) { Assert.True(version1 <= version2); Assert.False(version1 > version2); } if (expectedSign < 0) { Assert.True(version1 < version2); Assert.False(version1 >= version2); } } IComparable comparable = version1; Assert.Equal(expectedSign, Math.Sign(comparable.CompareTo(version2))); } [Fact] public static void CompareTo_Invalid() { IComparable comparable = new Version(1, 1); Assert.Throws<ArgumentException>(null, () => comparable.CompareTo(1)); // Obj is not a version Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("1.1")); // Obj is not a version Version nullVersion = null; Version testVersion = new Version(1, 2); AssertExtensions.Throws<ArgumentNullException>("v1", () => testVersion >= nullVersion); // V2 is null AssertExtensions.Throws<ArgumentNullException>("v1", () => testVersion > nullVersion); // V2 is null AssertExtensions.Throws<ArgumentNullException>("v1", () => nullVersion < testVersion); // V1 is null AssertExtensions.Throws<ArgumentNullException>("v1", () => nullVersion <= testVersion); // V1 is null } private static IEnumerable<object[]> Equals_TestData() { yield return new object[] { new Version(2, 3), new Version(2, 3), true }; yield return new object[] { new Version(2, 3), new Version(2, 4), false }; yield return new object[] { new Version(2, 3), new Version(3, 3), false }; yield return new object[] { new Version(2, 3, 4), new Version(2, 3, 4), true }; yield return new object[] { new Version(2, 3, 4), new Version(2, 3, 5), false }; yield return new object[] { new Version(2, 3, 4), new Version(2, 3), false }; yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4, 5), true }; yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4, 6), false }; yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3), false }; yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4), false }; yield return new object[] { new Version(2, 3, 0), new Version(2, 3), false }; yield return new object[] { new Version(2, 3, 4, 0), new Version(2, 3, 4), false }; yield return new object[] { new Version(2, 3, 4, 5), new TimeSpan(), false }; yield return new object[] { new Version(2, 3, 4, 5), null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public static void Equals(Version version1, object obj, bool expected) { Version version2 = obj as Version; Assert.Equal(expected, version1.Equals(version2)); Assert.Equal(expected, version1.Equals(obj)); Assert.Equal(expected, version1 == version2); Assert.Equal(!expected, version1 != version2); if (version2 != null) { Assert.Equal(expected, version1.GetHashCode().Equals(version2.GetHashCode())); } } private static IEnumerable<object[]> Parse_Valid_TestData() { yield return new object[] { "1.2", new Version(1, 2) }; yield return new object[] { "1.2.3", new Version(1, 2, 3) }; yield return new object[] { "1.2.3.4", new Version(1, 2, 3, 4) }; yield return new object[] { "2 .3. 4. \t\r\n15 ", new Version(2, 3, 4, 15) }; yield return new object[] { " 2 .3. 4. \t\r\n15 ", new Version(2, 3, 4, 15) }; yield return new object[] { "+1.+2.+3.+4", new Version(1, 2, 3, 4) }; } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse(string input, Version expected) { Assert.Equal(expected, Version.Parse(input)); Version version; Assert.True(Version.TryParse(input, out version)); Assert.Equal(expected, version); } private static IEnumerable<object[]> Parse_Invalid_TestData() { yield return new object[] { null, typeof(ArgumentNullException) }; // Input is null yield return new object[] { "", typeof(ArgumentException) }; // Input is empty yield return new object[] { "1,2,3,4", typeof(ArgumentException) }; // Input has fewer than 4 version components yield return new object[] { "1", typeof(ArgumentException) }; // Input has fewer than 2 version components yield return new object[] { "1.2.3.4.5", typeof(ArgumentException) }; // Input has more than 4 version components yield return new object[] { "-1.2.3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value yield return new object[] { "1.-2.3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value yield return new object[] { "1.2.-3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value yield return new object[] { "1.2.3.-4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value yield return new object[] { "b.2.3.4", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "1.b.3.4", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "1.2.b.4", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "1.2.3.b", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "2147483648.2.3.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue yield return new object[] { "1.2147483648.3.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue yield return new object[] { "1.2.2147483648.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue yield return new object[] { "1.2.3.2147483648", typeof(OverflowException) }; // Input contains a value > int.MaxValue // Input contains a value < 0 yield return new object[] { "-1.2.3.4", typeof(ArgumentOutOfRangeException) }; yield return new object[] { "1.-2.3.4", typeof(ArgumentOutOfRangeException) }; yield return new object[] { "1.2.-3.4", typeof(ArgumentOutOfRangeException) }; yield return new object[] { "1.2.3.-4", typeof(ArgumentOutOfRangeException) }; } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Invalid(string input, Type exceptionType) { Assert.Throws(exceptionType, () => Version.Parse(input)); Version version; Assert.False(Version.TryParse(input, out version)); Assert.Null(version); } public static IEnumerable<object[]> ToString_TestData() { yield return new object[] { new Version(1, 2), new string[] { "", "1", "1.2" } }; yield return new object[] { new Version(1, 2, 3), new string[] { "", "1", "1.2", "1.2.3" } }; yield return new object[] { new Version(1, 2, 3, 4), new string[] { "", "1", "1.2", "1.2.3", "1.2.3.4" } }; } [Theory] [MemberData(nameof(ToString_TestData))] public static void ToString(Version version, string[] expected) { for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], version.ToString(i)); } int maxFieldCount = expected.Length - 1; Assert.Equal(expected[maxFieldCount], version.ToString()); AssertExtensions.Throws<ArgumentException>("fieldCount", () => version.ToString(-1)); // Index < 0 AssertExtensions.Throws<ArgumentException>("fieldCount", () => version.ToString(maxFieldCount + 1)); // Index > version.fieldCount } private static void VerifyVersion(Version version, int major, int minor, int build, int revision) { Assert.Equal(major, version.Major); Assert.Equal(minor, version.Minor); Assert.Equal(build, version.Build); Assert.Equal(revision, version.Revision); Assert.Equal((short)(revision >> 16), version.MajorRevision); Assert.Equal(unchecked((short)(revision & 0xFFFF)), version.MinorRevision); } } }
#if !NET45PLUS // 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Validation; namespace System.Collections.Immutable { /// <content> /// Contains the inner <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableDictionary<TKey, TValue> { /// <summary> /// A dictionary that mutates with little or no memory allocations, /// can produce and/or build on immutable dictionary instances very efficiently. /// </summary> /// <remarks> /// <para> /// While <see cref="ImmutableDictionary{TKey, TValue}.AddRange(IEnumerable{KeyValuePair{TKey, TValue}})"/> /// and other bulk change methods already provide fast bulk change operations on the collection, this class allows /// multiple combinations of changes to be made to a set with equal efficiency. /// </para> /// <para> /// Instance members of this class are <em>not</em> thread-safe. /// </para> /// </remarks> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableDictionaryBuilderDebuggerProxy<,>))] public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary { /// <summary> /// The root of the binary tree that stores the collection. Contents are typically not entirely frozen. /// </summary> private SortedInt32KeyNode<HashBucket> _root = SortedInt32KeyNode<HashBucket>.EmptyNode; /// <summary> /// The comparers. /// </summary> private Comparers _comparers; /// <summary> /// The number of elements in this collection. /// </summary> private int _count; /// <summary> /// Caches an immutable instance that represents the current state of the collection. /// </summary> /// <value>Null if no immutable view has been created for the current version.</value> private ImmutableDictionary<TKey, TValue> _immutable; /// <summary> /// A number that increments every time the builder changes its contents. /// </summary> private int _version; /// <summary> /// The object callers may use to synchronize access to this collection. /// </summary> private object _syncRoot; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class. /// </summary> /// <param name="map">The map that serves as the basis for this Builder.</param> internal Builder(ImmutableDictionary<TKey, TValue> map) { Requires.NotNull(map, "map"); _root = map._root; _count = map._count; _comparers = map._comparers; _immutable = map; } /// <summary> /// Gets or sets the key comparer. /// </summary> /// <value> /// The key comparer. /// </value> public IEqualityComparer<TKey> KeyComparer { get { return _comparers.KeyComparer; } set { Requires.NotNull(value, "value"); if (value != this.KeyComparer) { var comparers = Comparers.Get(value, this.ValueComparer); var input = new MutationInput(SortedInt32KeyNode<HashBucket>.EmptyNode, comparers, 0); var result = ImmutableDictionary<TKey, TValue>.AddRange(this, input); _immutable = null; _comparers = comparers; _count = result.CountAdjustment; // offset from 0 this.Root = result.Root; } } } /// <summary> /// Gets or sets the value comparer. /// </summary> /// <value> /// The value comparer. /// </value> public IEqualityComparer<TValue> ValueComparer { get { return _comparers.ValueComparer; } set { Requires.NotNull(value, "value"); if (value != this.ValueComparer) { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. _comparers = _comparers.WithValueComparer(value); _immutable = null; // invalidate cached immutable } } } #region IDictionary<TKey, TValue> Properties /// <summary> /// Gets the number of elements contained in the <see cref="ICollection{T}"/>. /// </summary> /// <returns>The number of elements contained in the <see cref="ICollection{T}"/>.</returns> public int Count { get { return _count; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.</returns> bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TKey> Keys { get { foreach (KeyValuePair<TKey, TValue> item in this) { yield return item.Key; } } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns>An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns> ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return this.Keys.ToArray(this.Count); } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TValue> Values { get { foreach (KeyValuePair<TKey, TValue> item in this) { yield return item.Value; } } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns>An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns> ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return this.Values.ToArray(this.Count); } } #endregion #region IDictionary Properties /// <summary> /// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size. /// </summary> /// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns> bool IDictionary.IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool IDictionary.IsReadOnly { get { return false; } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Keys { get { return this.Keys.ToArray(this.Count); } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Values { get { return this.Values.ToArray(this.Count); } } #endregion #region ICollection Properties /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return false; } } #endregion #region IDictionary Methods /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param> /// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param> void IDictionary.Add(object key, object value) { this.Add((TKey)key, (TValue)value); } /// <summary> /// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param> /// <returns> /// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false. /// </returns> bool IDictionary.Contains(object key) { return this.ContainsKey((TKey)key); } /// <summary> /// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </summary> /// <returns> /// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </returns> /// <exception cref="System.NotImplementedException"></exception> IDictionaryEnumerator IDictionary.GetEnumerator() { return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator()); } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The key of the element to remove.</param> void IDictionary.Remove(object key) { this.Remove((TKey)key); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> object IDictionary.this[object key] { get { return this[(TKey)key]; } set { this[(TKey)key] = (TValue)value; } } #endregion #region ICollection methods /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (var item in this) { array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++); } } #endregion /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return _version; } } /// <summary> /// Gets the initial data to pass to a query or mutation method. /// </summary> private MutationInput Origin { get { return new MutationInput(this.Root, _comparers, _count); } } /// <summary> /// Gets or sets the root of this data structure. /// </summary> private SortedInt32KeyNode<HashBucket> Root { get { return _root; } set { // We *always* increment the version number because some mutations // may not create a new value of root, although the existing root // instance may have mutated. _version++; if (_root != value) { _root = value; // Clear any cached value for the immutable view since it is now invalidated. _immutable = null; } } } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <returns>The element with the specified key.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// <exception cref="KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception> /// <exception cref="NotSupportedException">The property is set and the <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public TValue this[TKey key] { get { TValue value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(); } set { var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.SetValue, this.Origin); this.Apply(result); } } #region Public Methods /// <summary> /// Adds a sequence of values to this collection. /// </summary> /// <param name="items">The items.</param> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items) { var result = ImmutableDictionary<TKey, TValue>.AddRange(items, this.Origin); this.Apply(result); } /// <summary> /// Removes any entries from the dictionaries with keys that match those found in the specified sequence. /// </summary> /// <param name="keys">The keys for entries to remove from the dictionary.</param> public void RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, "keys"); foreach (var key in keys) { this.Remove(key); } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(_root, this); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <returns>The value for the key, or the default value of type <typeparamref name="TValue"/> if no matching key was found.</returns> [Pure] public TValue GetValueOrDefault(TKey key) { return this.GetValueOrDefault(key, default(TValue)); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param> /// <returns> /// The value for the key, or <paramref name="defaultValue"/> if no matching key was found. /// </returns> [Pure] public TValue GetValueOrDefault(TKey key, TValue defaultValue) { Requires.NotNullAllowStructs(key, "key"); TValue value; if (this.TryGetValue(key, out value)) { return value; } return defaultValue; } /// <summary> /// Creates an immutable dictionary based on the contents of this instance. /// </summary> /// <returns>An immutable map.</returns> /// <remarks> /// This method is an O(n) operation, and approaches O(1) time as the number of /// actual mutations to the set since the last call to this method approaches 0. /// </remarks> public ImmutableDictionary<TKey, TValue> ToImmutable() { // Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. if (_immutable == null) { _immutable = ImmutableDictionary<TKey, TValue>.Wrap(_root, _comparers, _count); } return _immutable; } #endregion #region IDictionary<TKey, TValue> Members /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The object to use as the key of the element to add.</param> /// <param name="value">The object to use as the value of the element to add.</param> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>.</exception> /// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public void Add(TKey key, TValue value) { var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, this.Origin); this.Apply(result); } /// <summary> /// Determines whether the <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary{TKey, TValue}"/>.</param> /// <returns> /// true if the <see cref="IDictionary{TKey, TValue}"/> contains an element with the key; otherwise, false. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> public bool ContainsKey(TKey key) { return ImmutableDictionary<TKey, TValue>.ContainsKey(key, this.Origin); } /// <summary> /// Determines whether the <see cref="ImmutableDictionary{TKey, TValue}"/> /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the <see cref="ImmutableDictionary{TKey, TValue}"/>. /// The value can be null for reference types. /// </param> /// <returns> /// true if the <see cref="ImmutableDictionary{TKey, TValue}"/> contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) { foreach (KeyValuePair<TKey, TValue> item in this) { if (this.ValueComparer.Equals(value, item.Value)) { return true; } } return false; } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// /// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public bool Remove(TKey key) { var result = ImmutableDictionary<TKey, TValue>.Remove(key, this.Origin); return this.Apply(result); } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key whose value to get.</param> /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value of the type <typeparamref name="TValue"/>. This parameter is passed uninitialized.</param> /// <returns> /// true if the object that implements <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key; otherwise, false. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> public bool TryGetValue(TKey key, out TValue value) { return ImmutableDictionary<TKey, TValue>.TryGetValue(key, this.Origin, out value); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { return ImmutableDictionary<TKey, TValue>.TryGetKey(equalKey, this.Origin, out actualKey); } /// <summary> /// Adds an item to the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception> public void Add(KeyValuePair<TKey, TValue> item) { this.Add(item.Key, item.Value); } /// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. /// </summary> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only. </exception> public void Clear() { this.Root = SortedInt32KeyNode<HashBucket>.EmptyNode; _count = 0; } /// <summary> /// Determines whether the <see cref="ICollection{T}"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false. /// </returns> public bool Contains(KeyValuePair<TKey, TValue> item) { return ImmutableDictionary<TKey, TValue>.Contains(item, this.Origin); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { Requires.NotNull(array, "array"); foreach (var item in this) { array[arrayIndex++] = item; } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members /// <summary> /// Removes the first occurrence of a specific object from the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="ICollection{T}"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="ICollection{T}"/>. /// </returns> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception> public bool Remove(KeyValuePair<TKey, TValue> item) { // Before removing based on the key, check that the key (if it exists) has the value given in the parameter as well. if (this.Contains(item)) { return this.Remove(item.Key); } return false; } #endregion #region IEnumerator<T> methods /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Applies the result of some mutation operation to this instance. /// </summary> /// <param name="result">The result.</param> private bool Apply(MutationResult result) { this.Root = result.Root; _count += result.CountAdjustment; return result.CountAdjustment != 0; } } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal class ImmutableDictionaryBuilderDebuggerProxy<TKey, TValue> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableDictionary<TKey, TValue>.Builder _map; /// <summary> /// The simple view of the collection. /// </summary> private KeyValuePair<TKey, TValue>[] _contents; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class. /// </summary> /// <param name="map">The collection to display in the debugger</param> public ImmutableDictionaryBuilderDebuggerProxy(ImmutableDictionary<TKey, TValue>.Builder map) { Requires.NotNull(map, "map"); _map = map; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair<TKey, TValue>[] Contents { get { if (_contents == null) { _contents = _map.ToArray(_map.Count); } return _contents; } } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Evaluation; using System.Linq; using Microsoft.Build.Execution; using Xunit; using Microsoft.Build.Tasks; namespace Microsoft.Build.UnitTests.GetInstalledSDKLocation_Tests { public class FakeSDKStructure : IDisposable { public string FakeSdkStructureRoot { get; } public string FakeSdkStructureRoot2 { get; } public FakeSDKStructure() { FakeSdkStructureRoot = FakeSDKStructure.MakeFakeSDKStructure(); FakeSdkStructureRoot2 = FakeSDKStructure.MakeFakeSDKStructure2(); } public void Dispose() { if (FileUtilities.DirectoryExistsNoThrow(FakeSdkStructureRoot)) { FileUtilities.DeleteDirectoryNoThrow(FakeSdkStructureRoot, true); } if (FileUtilities.DirectoryExistsNoThrow(FakeSdkStructureRoot2)) { FileUtilities.DeleteDirectoryNoThrow(FakeSdkStructureRoot2, true); } } /// <summary> /// Make a fake SDK structure on disk for testing. /// </summary> private static string MakeFakeSDKStructure() { string tempPath = Path.Combine(Path.GetTempPath(), "FakeSDKDirectory"); try { // Good Directory.CreateDirectory( Path.Combine(new[] { tempPath, "Windows", "v1.0", "ExtensionSDKs", "MyAssembly", "1.0" })); Directory.CreateDirectory( Path.Combine(new[] { tempPath, "Windows", "1.0", "ExtensionSDKs", "MyAssembly", "2.0" })); Directory.CreateDirectory( Path.Combine(new[] { tempPath, "Windows", "2.0", "ExtensionSDKs", "MyAssembly", "3.0" })); File.WriteAllText( Path.Combine( new[] { tempPath, "Windows", "v1.0", "ExtensionSDKs", "MyAssembly", "1.0", "SDKManifest.xml" }), "Hello"); File.WriteAllText( Path.Combine( new[] { tempPath, "Windows", "1.0", "ExtensionSDKs", "MyAssembly", "2.0", "SDKManifest.xml" }), "Hello"); File.WriteAllText( Path.Combine( new[] { tempPath, "Windows", "2.0", "ExtensionSDKs", "MyAssembly", "3.0", "SDKManifest.xml" }), "Hello"); //Bad because of v in the sdk version Directory.CreateDirectory( Path.Combine(new[] { tempPath, "Windows", "v1.0", "ExtensionSDKs", "MyAssembly", "v1.1" })); //Bad because no extensionSDKs directory under the platform version Directory.CreateDirectory(Path.Combine(tempPath, "Windows", "v3.0") + Path.DirectorySeparatorChar); // Bad because the directory under the identifier is not a version Directory.CreateDirectory( Path.Combine(tempPath, "Windows", "NotAVersion") + Path.DirectorySeparatorChar); // Bad because the directory under the identifier is not a version Directory.CreateDirectory( Path.Combine( new[] { tempPath, "Windows", "NotAVersion", "ExtensionSDKs", "Assembly", "1.0" })); // Good but are in a different target platform // Doors does not have an sdk manifest but does have extensionsdks under it so they should be found // when we are targeting doors Directory.CreateDirectory( Path.Combine(new[] { tempPath, "Doors", "2.0", "ExtensionSDKs", "MyAssembly", "3.0" })); File.WriteAllText( Path.Combine( new[] { tempPath, "Doors", "2.0", "ExtensionSDKs", "MyAssembly", "3.0", "SDKManifest.xml" }), "Hello"); // Walls has an SDK manifest so it should be found when looking for targetplatform sdks. // But it has no extensionSDKs so none should be found Directory.CreateDirectory(Path.Combine(tempPath, "Walls" + Path.DirectorySeparatorChar + "1.0" + Path.DirectorySeparatorChar)); File.WriteAllText(Path.Combine(tempPath, "Walls", "1.0", "SDKManifest.xml"), "Hello"); } catch (Exception) { FileUtilities.DeleteDirectoryNoThrow(tempPath, true); return null; } return tempPath; } /// <summary> /// Make a fake SDK structure on disk for testing. /// </summary> private static string MakeFakeSDKStructure2() { string tempPath = Path.Combine(Path.GetTempPath(), "FakeSDKDirectory2"); try { // Good Directory.CreateDirectory( Path.Combine(new[] { tempPath, "Windows", "v1.0", "ExtensionSDKs", "MyAssembly", "4.0" })); Directory.CreateDirectory( Path.Combine(new[] { tempPath, "Windows", "1.0", "ExtensionSDKs", "MyAssembly", "5.0" })); Directory.CreateDirectory( Path.Combine(new[] { tempPath, "Windows", "2.0", "ExtensionSDKs", "MyAssembly", "6.0" })); File.WriteAllText( Path.Combine( new[] { tempPath, "Windows", "v1.0", "ExtensionSDKs", "MyAssembly", "4.0", "SDKManifest.xml" }), "Hello"); File.WriteAllText( Path.Combine( new[] { tempPath, "Windows", "1.0", "ExtensionSDKs", "MyAssembly", "5.0", "SDKManifest.xml" }), "Hello"); File.WriteAllText( Path.Combine( new[] { tempPath, "Windows", "2.0", "ExtensionSDKs", "MyAssembly", "6.0", "SDKManifest.xml" }), "Hello"); } catch (Exception) { FileUtilities.DeleteDirectoryNoThrow(tempPath, true); return null; } return tempPath; } } /// <summary> /// Test the GetInstalledSDKLocations task /// </summary> public class GetInstalledSDKLocationsTestFixture : IClassFixture<FakeSDKStructure> { private readonly string _fakeSDKStructureRoot; private readonly string _fakeSDKStructureRoot2; public GetInstalledSDKLocationsTestFixture(FakeSDKStructure fakeSDKStructure) { _fakeSDKStructureRoot = fakeSDKStructure.FakeSdkStructureRoot; _fakeSDKStructureRoot2 = fakeSDKStructure.FakeSdkStructureRoot2; } #region TestMethods /// <summary> /// Make sure we get a ArgumentException if null is passed into the target platform version. /// </summary> [Fact] public void NullTargetPlatformVersion() { Assert.Throws<ArgumentNullException>(() => { GetInstalledSDKLocations t = new GetInstalledSDKLocations(); t.TargetPlatformIdentifier = "Hello"; t.TargetPlatformVersion = null; t.Execute(); } ); } /// <summary> /// Make sure we get a ArgumentException if null is passed into the target platform version. /// </summary> [Fact] public void NullTargetPlatformIdentifier() { Assert.Throws<ArgumentNullException>(() => { GetInstalledSDKLocations t = new GetInstalledSDKLocations(); t.TargetPlatformIdentifier = null; t.TargetPlatformVersion = "1.0"; t.Execute(); } ); } /// <summary> /// Make sure we get an error message if an empty platform identifier is passed in. /// </summary> [Fact] public void EmptyTargetPlatformIdentifier() { MockEngine engine = new MockEngine(); GetInstalledSDKLocations t = new GetInstalledSDKLocations(); t.TargetPlatformIdentifier = String.Empty; t.TargetPlatformVersion = "1.0"; t.BuildEngine = engine; bool success = t.Execute(); Assert.False(success); Assert.Equal(1, engine.Errors); engine.AssertLogContains("MSB3784"); } /// <summary> /// Make sure we get an error message if an empty platform Version is passed in. /// </summary> [Fact] public void EmptyTargetPlatformVersion() { MockEngine engine = new MockEngine(); GetInstalledSDKLocations t = new GetInstalledSDKLocations(); t.TargetPlatformIdentifier = "Hello"; t.TargetPlatformVersion = String.Empty; t.BuildEngine = engine; bool success = t.Execute(); Assert.False(success); Assert.Equal(1, engine.Errors); engine.AssertLogContains("MSB3784"); } /// <summary> /// Make sure we get an error message if an empty platform Version is passed in. /// </summary> [Fact] public void BadTargetPlatformVersion() { MockEngine engine = new MockEngine(); GetInstalledSDKLocations t = new GetInstalledSDKLocations(); t.TargetPlatformIdentifier = "Hello"; t.TargetPlatformVersion = "CAT"; t.BuildEngine = engine; bool success = t.Execute(); Assert.False(success); Assert.Equal(1, engine.Errors); engine.AssertLogContains("MSB3786"); } /// <summary> /// Make sure we get an Warning if no SDKs were found. /// </summary> [Fact] public void NoSDKsFound() { MockEngine engine = new MockEngine(); GetInstalledSDKLocations t = new GetInstalledSDKLocations(); t.TargetPlatformIdentifier = "Hello"; t.TargetPlatformVersion = "1.0"; t.BuildEngine = engine; bool success = t.Execute(); Assert.True(success); Assert.Equal(1, engine.Warnings); engine.AssertLogContains("MSB3785"); } /// <summary> /// Get a good set of SDKS installed on the machine from the fake SDK location. /// </summary> [Fact] public void GetSDKVersions() { try { Environment.SetEnvironmentVariable("MSBUILDSDKREFERENCEDIRECTORY", _fakeSDKStructureRoot + ";" + _fakeSDKStructureRoot2); Environment.SetEnvironmentVariable("MSBUILDDISABLEREGISTRYFORSDKLOOKUP", "true"); MockEngine engine = new MockEngine(); GetInstalledSDKLocations t = new GetInstalledSDKLocations(); t.TargetPlatformIdentifier = "Windows"; t.TargetPlatformVersion = new Version(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue).ToString(); t.SDKRegistryRoot = "Somewhere"; t.SDKRegistryRoot = "Hello;Jello"; t.BuildEngine = engine; bool success = t.Execute(); Assert.True(success); ITaskItem[] installedSDKs = t.InstalledSDKs; Assert.Equal(6, installedSDKs.Length); Dictionary<string, string> sdksAndVersions = new Dictionary<string, string>(); foreach (ITaskItem item in installedSDKs) { sdksAndVersions.Add(item.GetMetadata("SDKName"), item.GetMetadata("PlatformVersion")); } Assert.Equal("1.0", sdksAndVersions["MyAssembly, Version=1.0"]); Assert.Equal("1.0", sdksAndVersions["MyAssembly, Version=2.0"]); Assert.Equal("2.0", sdksAndVersions["MyAssembly, Version=3.0"]); Assert.Equal("1.0", sdksAndVersions["MyAssembly, Version=4.0"]); Assert.Equal("1.0", sdksAndVersions["MyAssembly, Version=5.0"]); Assert.Equal("2.0", sdksAndVersions["MyAssembly, Version=6.0"]); Assert.False(sdksAndVersions.ContainsValue("3.0")); Assert.False(sdksAndVersions.ContainsValue("4.0")); } finally { Environment.SetEnvironmentVariable("MSBUILDSDKREFERENCEDIRECTORY", null); Environment.SetEnvironmentVariable("MSBUILDDISABLEREGISTRYFORSDKLOOKUP", null); } } /// <summary> /// Get a good set of SDKS installed on the machine from the fake SDK location. /// </summary> [Fact] public void GetGoodSDKs() { try { Environment.SetEnvironmentVariable("MSBUILDSDKREFERENCEDIRECTORY", _fakeSDKStructureRoot + ";" + _fakeSDKStructureRoot2); Environment.SetEnvironmentVariable("MSBUILDDISABLEREGISTRYFORSDKLOOKUP", "true"); MockEngine engine = new MockEngine(); GetInstalledSDKLocations t = new GetInstalledSDKLocations(); t.TargetPlatformIdentifier = "Windows"; t.TargetPlatformVersion = new Version(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue).ToString(); t.SDKRegistryRoot = "Somewhere"; t.SDKRegistryRoot = "Hello;Jello"; t.BuildEngine = engine; bool success = t.Execute(); Assert.True(success); ITaskItem[] installedSDKs = t.InstalledSDKs; Assert.Equal(6, installedSDKs.Length); Dictionary<string, string> extensionSDKs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (ITaskItem item in installedSDKs) { extensionSDKs.Add(item.GetMetadata("SDKName"), item.ItemSpec); } Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=1.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot, "Windows", "v1.0", "ExtensionSDKs", "MyAssembly", "1.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=1.0"]); Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=2.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot, "Windows", "1.0", "ExtensionSDKs", "MyAssembly", "2.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=2.0"]); Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=3.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot, "Windows", "2.0", "ExtensionSDKs", "MyAssembly", "3.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=3.0"]); Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=4.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot2, "Windows", "v1.0", "ExtensionSDKs", "MyAssembly", "4.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=4.0"]); Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=5.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot2, "Windows", "1.0", "ExtensionSDKs", "MyAssembly", "5.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=5.0"]); Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=6.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot2, "Windows", "2.0", "ExtensionSDKs", "MyAssembly", "6.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=6.0"]); } finally { Environment.SetEnvironmentVariable("MSBUILDSDKREFERENCEDIRECTORY", null); Environment.SetEnvironmentVariable("MSBUILDDISABLEREGISTRYFORSDKLOOKUP", null); } } /// <summary> /// Get a good set of SDKS installed on the machine from the fake SDK location. /// </summary> [Fact] public void GetGoodSDKs2() { try { Environment.SetEnvironmentVariable("MSBUILDDISABLEREGISTRYFORSDKLOOKUP", "true"); MockEngine engine = new MockEngine(); GetInstalledSDKLocations t = new GetInstalledSDKLocations(); t.TargetPlatformIdentifier = "Windows"; t.TargetPlatformVersion = new Version(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue).ToString(); t.BuildEngine = engine; t.SDKRegistryRoot = String.Empty; t.SDKDirectoryRoots = new string[] { _fakeSDKStructureRoot, _fakeSDKStructureRoot2 }; bool success = t.Execute(); Assert.True(success); ITaskItem[] installedSDKs = t.InstalledSDKs; Assert.Equal(6, installedSDKs.Length); Dictionary<string, string> extensionSDKs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (ITaskItem item in installedSDKs) { extensionSDKs.Add(item.GetMetadata("SDKName"), item.ItemSpec); } Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=1.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot, "Windows", "v1.0", "ExtensionSDKs", "MyAssembly", "1.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=1.0"]); Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=2.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot, "Windows", "1.0", "ExtensionSDKs", "MyAssembly", "2.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=2.0"]); Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=3.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot, "Windows", "2.0", "ExtensionSDKs", "MyAssembly", "3.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=3.0"]); Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=4.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot2, "Windows", "v1.0", "ExtensionSDKs", "MyAssembly", "4.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=4.0"]); Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=5.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot2, "Windows", "1.0", "ExtensionSDKs", "MyAssembly", "5.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=5.0"]); Assert.True(extensionSDKs.ContainsKey("MyAssembly, Version=6.0")); Assert.Equal( Path.Combine( new[] { _fakeSDKStructureRoot2, "Windows", "2.0", "ExtensionSDKs", "MyAssembly", "6.0" }) + Path.DirectorySeparatorChar, extensionSDKs["MyAssembly, Version=6.0"]); } finally { Environment.SetEnvironmentVariable("MSBUILDDISABLEREGISTRYFORSDKLOOKUP", null); } } #endregion } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> //----------------------------------------------------------------------- #endregion using System; using System.Collections; using System.Collections.Generic; using System.Linq; using WootzJs.Testing; namespace WootzJs.Compiler.Tests { public class YieldTests : TestFixture { [Test] public void YieldBreak() { var strings = YieldClass.YieldBreak().ToArray(); AssertEquals(0, strings.Length); } [Test] public void YieldIsEnumerator() { var yieldBreak = YieldClass.YieldBreak(); AssertTrue(yieldBreak is IEnumerable<string>); } [Test] public void ReturnOne() { var strings = YieldClass.ReturnOne().ToArray(); AssertEquals(strings.Length, 1); AssertEquals(strings[0], "one"); } [Test] public void ReturnTwo() { var strings = YieldClass.ReturnTwo().ToArray(); AssertEquals(strings.Length, 2); AssertEquals(strings[0], "one"); AssertEquals(strings[1], "two"); } [Test] public void IfStatementTrue() { var strings = YieldClass.IfStatement(true).ToArray(); AssertEquals(strings.Length, 1); AssertEquals(strings[0], "true"); } [Test] public void IfStatementFalse() { var strings = YieldClass.IfStatement(false).ToArray(); AssertEquals(strings.Length, 1); AssertEquals(strings[0], "false"); } [Test] public void IfStatementTwoItemsTrue() { var strings = YieldClass.IfStatementTwoItems(true).ToArray(); AssertEquals(strings.Length, 2); AssertEquals(strings[0], "one"); AssertEquals(strings[1], "two"); } [Test] public void IfStatementTwoItemsFalse() { var strings = YieldClass.IfStatementTwoItems(false).ToArray(); AssertEquals(strings.Length, 2); AssertEquals(strings[0], "three"); AssertEquals(strings[1], "four"); } [Test] public void NestedIfTrueTrue() { var strings = YieldClass.NestedIf(true, true).ToArray(); AssertEquals(strings.Length, 1); AssertEquals(strings[0], "one"); } [Test] public void NestedIfTrueFalse() { var strings = YieldClass.NestedIf(true, false).ToArray(); AssertEquals(strings.Length, 1); AssertEquals(strings[0], "two"); } [Test] public void NestedIfFalseTrue() { var strings = YieldClass.NestedIf(false, true).ToArray(); AssertEquals(strings.Length, 1); AssertEquals(strings[0], "three"); } [Test] public void NestedIfFalseFalse() { var strings = YieldClass.NestedIf(false, false).ToArray(); AssertEquals(strings.Length, 1); AssertEquals(strings[0], "four"); } [Test] public void NestedIfTwoStatementsTrueTrue() { var strings = YieldClass.NestedIfTwoStatements(true, true).ToArray(); AssertEquals(strings.Length, 2); AssertEquals(strings[0], "one"); AssertEquals(strings[1], "two"); } [Test] public void NestedIfTwoStatementsTrueFalse() { var strings = YieldClass.NestedIfTwoStatements(true, false).ToArray(); AssertEquals(strings.Length, 2); AssertEquals(strings[0], "three"); AssertEquals(strings[1], "four"); } [Test] public void NestedIfTwoStatementsFalseTrue() { var strings = YieldClass.NestedIfTwoStatements(false, true).ToArray(); AssertEquals(strings.Length, 2); AssertEquals(strings[0], "five"); AssertEquals(strings[1], "six"); } [Test] public void ReturnAfterIfTrue() { var strings = YieldClass.ReturnAfterIf(true).ToArray(); AssertEquals(strings.Length, 5); AssertEquals(strings[0], "zero"); AssertEquals(strings[1], "one"); AssertEquals(strings[2], "two"); AssertEquals(strings[3], "five"); AssertEquals(strings[4], "six"); } [Test] public void ReturnAfterIfFalse() { var strings = YieldClass.ReturnAfterIf(false).ToArray(); AssertEquals(strings.Length, 5); AssertEquals(strings[0], "zero"); AssertEquals(strings[1], "three"); AssertEquals(strings[2], "four"); AssertEquals(strings[3], "five"); AssertEquals(strings[4], "six"); } [Test] public void IterateVariable() { var strings = YieldClass.InitializeVariable().ToArray(); AssertEquals(strings.Length, 1); AssertEquals(strings[0], "foo"); } [Test] public void WhileLoop() { var ints = YieldClass.WhileLoop().ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 0); AssertEquals(ints[1], 1); AssertEquals(ints[2], 2); } [Test] public void IfWithErrataAfterYield() { var ints = YieldClass.IfWithErrataAfterYield(true).ToArray(); AssertEquals(ints.Length, 2); AssertEquals(ints[0], 0); AssertEquals(ints[1], 1); } [Test] public void ForLoop() { var ints = YieldClass.ForLoop().ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 0); AssertEquals(ints[1], 1); AssertEquals(ints[2], 2); } [Test] public void ForLoopNoVariableWithInitializer() { var ints = YieldClass.ForLoopNoVariableWithInitializer().ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 0); AssertEquals(ints[1], 1); AssertEquals(ints[2], 2); } [Test] public void ForLoopNoVariableNoInitializer() { var ints = YieldClass.ForLoopNoVariableNoInitializer().ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 0); AssertEquals(ints[1], 1); AssertEquals(ints[2], 2); } [Test] public void ForLoopNoVariableNoInitializerNoIncrementor() { var ints = YieldClass.ForLoopNoVariableNoInitializerNoIncrementor().ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 0); AssertEquals(ints[1], 1); AssertEquals(ints[2], 2); } [Test] public void ForLoopTwoVariablesTwoIncrementors() { var ints = YieldClass.ForLoopTwoVariablesTwoIncrementors().ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 1); AssertEquals(ints[1], 3); AssertEquals(ints[2], 5); } [Test] public void NestedLoops() { var ints = YieldClass.NestedLoops().ToArray(); AssertEquals(ints.Length, 6); AssertEquals(ints[0], 0); AssertEquals(ints[1], 1); AssertEquals(ints[2], 0); AssertEquals(ints[3], 1); AssertEquals(ints[4], 2); AssertEquals(ints[5], 1); } [Test] public void TypeParameter() { var strings = YieldClass.TypeParameter<YieldClass>().ToArray(); AssertEquals(strings.Length, 1); AssertEquals(strings[0], "WootzJs.Compiler.Tests.YieldTests.YieldClass"); } [Test] public void Foreach() { var strings = YieldClass.Foreach().ToArray(); AssertEquals(strings.Length, 3); AssertEquals(strings[0], "one"); AssertEquals(strings[1], "two"); AssertEquals(strings[2], "three"); } [Test] public void DoWhileFalse() { var ints = YieldClass.DoWhileFalse().ToArray(); AssertEquals(ints.Length, 1); AssertEquals(ints[0], 1); } [Test] public void DoWhileLessThan3() { var ints = YieldClass.DoWhileLessThan3().ToArray(); AssertEquals(ints.Length, 2); AssertEquals(ints[0], 1); AssertEquals(ints[1], 2); } [Test] public void SwitchOne() { var ints = YieldClass.Switch("one").ToArray(); AssertEquals(ints.Length, 1); AssertEquals(ints[0], 1); } [Test] public void SwitchTwo() { var ints = YieldClass.Switch("two").ToArray(); AssertEquals(ints.Length, 2); AssertEquals(ints[0], 1); AssertEquals(ints[1], 2); } [Test] public void SwitchThree() { var ints = YieldClass.Switch("three").ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 1); AssertEquals(ints[1], 2); AssertEquals(ints[2], 3); } [Test] public void SwitchDefault() { var ints = YieldClass.Switch("foo").ToArray(); AssertEquals(ints.Length, 1); AssertEquals(ints[0], -1); } [Test] public void BreakWhile() { var ints = YieldClass.BreakWhile().ToArray(); AssertEquals(ints.Length, 1); AssertEquals(ints[0], 1); } [Test] public void ContinueWhile() { var ints = YieldClass.ContinueWhile().ToArray(); AssertEquals(ints.Length, 2); AssertEquals(ints[0], 2); AssertEquals(ints[1], 3); } [Test] public void BreakFor() { var ints = YieldClass.BreakFor().ToArray(); AssertEquals(ints.Length, 1); AssertEquals(ints[0], 1); } [Test] public void ContinueFor() { var ints = YieldClass.ContinueFor().ToArray(); AssertEquals(ints.Length, 2); AssertEquals(ints[0], 2); AssertEquals(ints[1], 3); } [Test] public void BreakForeach() { var ints = YieldClass.BreakForeach().ToArray(); AssertEquals(ints.Length, 1); AssertEquals(ints[0], 1); } [Test] public void ContinueForeach() { var ints = YieldClass.ContinueForeach().ToArray(); AssertEquals(ints.Length, 2); AssertEquals(ints[0], 2); AssertEquals(ints[1], 3); } [Test] public void BreakDoWhile() { var ints = YieldClass.BreakDoWhile().ToArray(); AssertEquals(ints.Length, 1); AssertEquals(ints[0], 1); } [Test] public void ContinueDoWhile() { var ints = YieldClass.ContinueDoWhile().ToArray(); AssertEquals(ints.Length, 2); AssertEquals(ints[0], 2); AssertEquals(ints[1], 3); } [Test] public void TryFinally() { var ints = YieldClass.TryFinally().ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 1); AssertEquals(ints[1], 2); AssertEquals(ints[2], 3); } [Test] public void NestedTryFinally() { var ints = YieldClass.NestedTryFinally().ToArray(); AssertEquals(ints.Length, 6); AssertEquals(ints[0], 1); AssertEquals(ints[1], 2); AssertEquals(ints[2], 3); AssertEquals(ints[3], 4); AssertEquals(ints[4], 11); AssertEquals(ints[5], 22); } [Test] public void TryFinallyThrowsException() { var enumerator = YieldClass.TryFinallyThrowsException(true).GetEnumerator(); AssertTrue(enumerator.MoveNext()); AssertEquals(enumerator.Current, 1); try { enumerator.MoveNext(); AssertTrue(false); } catch (Exception) { AssertTrue(true); } } [Test] public void LabeledStatementGotoFirst() { var ints = YieldClass.LabeledStatementGotoFirst(true).ToArray(); AssertEquals(ints.Length, 1); AssertEquals(ints[0], 1); ints = YieldClass.LabeledStatementGotoFirst(false).ToArray(); AssertEquals(ints.Length, 2); AssertEquals(ints[0], 1); AssertEquals(ints[1], 2); } [Test] public void LabeledStatementGotoSecond() { var ints = YieldClass.LabeledStatementGotoSecond().ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 1); AssertEquals(ints[1], 2); AssertEquals(ints[2], 3); } [Test] public void CollidingForeach() { var ints = YieldClass.CollidingForeach().ToArray(); AssertEquals(ints.Length, 4); AssertEquals(ints[0], 1); AssertEquals(ints[1], 2); AssertEquals(ints[2], 3); AssertEquals(ints[3], 4); } [Test] public void CollidingFor() { var ints = YieldClass.CollidingForeach().ToArray(); AssertEquals(ints.Length, 4); AssertEquals(ints[0], 1); AssertEquals(ints[1], 2); AssertEquals(ints[2], 3); AssertEquals(ints[3], 4); } [Test] public void ReuseEnumerable() { var enumerable = YieldClass.ReturnTwo(); var strings = enumerable.ToArray(); AssertEquals(strings.Length, 2); AssertEquals(strings[0], "one"); AssertEquals(strings[1], "two"); strings = enumerable.ToArray(); AssertEquals(strings.Length, 2); AssertEquals(strings[0], "one"); AssertEquals(strings[1], "two"); } public class YieldClass { public static IEnumerable<string> YieldBreak() { yield break; } public static IEnumerable<string> ReturnOne() { yield return "one"; } public static IEnumerable<string> ReturnTwo() { yield return "one"; yield return "two"; } public static IEnumerable<string> IfStatement(bool flag) { if (flag) { yield return "true"; } else { yield return "false"; } } public static IEnumerable<string> IfStatementTwoItems(bool flag) { if (flag) { yield return "one"; yield return "two"; } else { yield return "three"; yield return "four"; } } public static IEnumerable<string> NestedIf(bool flag1, bool flag2) { if (flag1) { if (flag2) { yield return "one"; } else { yield return "two"; } } else { if (flag2) { yield return "three"; } else { yield return "four"; } } } public static IEnumerable<string> NestedIfTwoStatements(bool flag1, bool flag2) { if (flag1) { if (flag2) { yield return "one"; yield return "two"; } else { yield return "three"; yield return "four"; } } else { if (flag2) { yield return "five"; yield return "six"; } else { yield return "seven"; yield return "eight"; } } } public static IEnumerable<string> ReturnAfterIf(bool flag) { yield return "zero"; if (flag) { yield return "one"; yield return "two"; } else { yield return "three"; yield return "four"; } yield return "five"; yield return "six"; } public static IEnumerable<string> InitializeVariable() { var s = "foo"; yield return s; } public static IEnumerable<int> WhileLoop() { var i = 0; while (i < 3) { yield return i; i++; } } public static IEnumerable<int> IfWithErrataAfterYield(bool flag) { var i = 0; if (flag) { yield return i; i++; } yield return i; } public static IEnumerable<int> ForLoop() { for (var i = 0; i < 3; i++) { yield return i; } } public static IEnumerable<int> ForLoopNoVariableWithInitializer() { int i; for (i = 0; i < 3; i++) { yield return i; } } public static IEnumerable<int> ForLoopNoVariableNoInitializer() { int i = 0; for (; i < 3; i++) { yield return i; } } public static IEnumerable<int> ForLoopNoVariableNoInitializerNoIncrementor() { int i = 0; for (; i < 3;) { yield return i; i++; } } public static IEnumerable<int> ForLoopTwoVariablesTwoIncrementors() { for (int i = 0, j = 1; i < 3; i++, j++) { yield return i + j; } } public static IEnumerable<int> NestedLoops() { for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { yield return i + j; } yield return i; } } public static IEnumerable<string> TypeParameter<T>() { yield return typeof(T).FullName; } public static IEnumerable<string> Foreach() { foreach (var s in new[] { "one", "two", "three" }) { yield return s; } } public static IEnumerable<int> DoWhileFalse() { var i = 1; do { yield return i; i++; } while (false); } public static IEnumerable<int> DoWhileLessThan3() { var i = 1; do { yield return i; i++; } while (i < 3); } public static IEnumerable<int> Switch(string s) { switch (s) { case "one": yield return 1; break; case "two": yield return 1; yield return 2; break; case "three": yield return 1; yield return 2; yield return 3; break; default: yield return -1; break; } } public static IEnumerable<int> BreakWhile() { var i = 0; while (true) { i++; yield return i; break; } } public static IEnumerable<int> ContinueWhile() { var i = 0; while (i < 3) { i++; if (i < 2) continue; yield return i; } } public static IEnumerable<int> BreakFor() { for (var i = 0;;) { i++; yield return i; break; } } public static IEnumerable<int> ContinueFor() { for (var i = 0; i < 3;) { i++; if (i < 2) continue; yield return i; } } public static IEnumerable<int> BreakForeach() { foreach (var i in new[] { 1, 2, 3 }) { yield return i; break; } } public static IEnumerable<int> ContinueForeach() { foreach (var i in new[] { 1, 2, 3 }) { if (i < 2) continue; yield return i; } } public static IEnumerable<int> BreakDoWhile() { var i = 0; do { i++; yield return i; break; } while (true); } public static IEnumerable<int> ContinueDoWhile() { var i = 0; do { i++; if (i < 2) continue; yield return i; } while (i < 3); } public static IEnumerable<int> TryFinally() { var i = 0; try { i++; yield return i; i++; yield return i; } finally { i++; } yield return i; } public static IEnumerable<int> NestedTryFinally() { var i = 0; try { yield return 1; yield return 2; try { yield return 3; yield return 4; } finally { i++; } yield return i + 10; } finally { i++; } yield return i + 20; } public static IEnumerable<int> TryFinallyThrowsException(bool flag) { var i = 0; try { i++; yield return i; if (flag) throw new Exception(); } finally { i++; } yield return i; } public static IEnumerable<int> LabeledStatementGotoFirst(bool flag) { var i = 1; if (flag) goto label; yield return i; i++; label: yield return i; } public static IEnumerable<int> LabeledStatementGotoSecond() { var i = 0; label: i++; yield return i; if (i < 3) goto label; } public static IEnumerable<int> CollidingForeach() { foreach (var item in new[] { 1, 2 }) { yield return item; } foreach (var item in new[] { 3, 4 }) { yield return item; } } public static IEnumerable<int> CollidingFor() { for (var i = 0; i < 3; i++) { yield return i; } for (var i = 2; i < 5; i++) { yield return i; } } } } }
using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Index; using Lucene.Net.Search; using Lucene.Net.Util; using System; using System.Collections.Generic; using System.IO; namespace Lucene.Net.Classification { /* * 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. */ /// <summary> /// A simplistic Lucene based NaiveBayes classifier, see <code>http://en.wikipedia.org/wiki/Naive_Bayes_classifier</code> /// /// @lucene.experimental /// </summary> public class SimpleNaiveBayesClassifier : IClassifier<BytesRef> { private AtomicReader _atomicReader; private string[] _textFieldNames; private string _classFieldName; private int _docsWithClassSize; private Analyzer _analyzer; private IndexSearcher _indexSearcher; private Query _query; /// <summary> /// Creates a new NaiveBayes classifier. /// Note that you must call <see cref="Train(AtomicReader, string, string, Analyzer)"/> before you can /// classify any documents. /// </summary> public SimpleNaiveBayesClassifier() { } /// <summary> /// Train the classifier using the underlying Lucene index /// </summary> /// <param name="analyzer"> the analyzer used to tokenize / filter the unseen text</param> /// <param name="atomicReader">the reader to use to access the Lucene index</param> /// <param name="classFieldName">the name of the field containing the class assigned to documents</param> /// <param name="textFieldName">the name of the field used to compare documents</param> public virtual void Train(AtomicReader atomicReader, string textFieldName, string classFieldName, Analyzer analyzer) { Train(atomicReader, textFieldName, classFieldName, analyzer, null); } /// <summary>Train the classifier using the underlying Lucene index</summary> /// <param name="analyzer">the analyzer used to tokenize / filter the unseen text</param> /// <param name="atomicReader">the reader to use to access the Lucene index</param> /// <param name="classFieldName">the name of the field containing the class assigned to documents</param> /// <param name="query">the query to filter which documents use for training</param> /// <param name="textFieldName">the name of the field used to compare documents</param> public virtual void Train(AtomicReader atomicReader, string textFieldName, string classFieldName, Analyzer analyzer, Query query) { Train(atomicReader, new string[]{textFieldName}, classFieldName, analyzer, query); } /// <summary>Train the classifier using the underlying Lucene index</summary> /// <param name="analyzer">the analyzer used to tokenize / filter the unseen text</param> /// <param name="atomicReader">the reader to use to access the Lucene index</param> /// <param name="classFieldName">the name of the field containing the class assigned to documents</param> /// <param name="query">the query to filter which documents use for training</param> /// <param name="textFieldNames">the names of the fields to be used to compare documents</param> public virtual void Train(AtomicReader atomicReader, string[] textFieldNames, string classFieldName, Analyzer analyzer, Query query) { _atomicReader = atomicReader; _indexSearcher = new IndexSearcher(_atomicReader); _textFieldNames = textFieldNames; _classFieldName = classFieldName; _analyzer = analyzer; _query = query; _docsWithClassSize = CountDocsWithClass(); } private int CountDocsWithClass() { int docCount = MultiFields.GetTerms(_atomicReader, _classFieldName).DocCount; if (docCount == -1) { // in case codec doesn't support getDocCount TotalHitCountCollector totalHitCountCollector = new TotalHitCountCollector(); BooleanQuery q = new BooleanQuery(); q.Add(new BooleanClause(new WildcardQuery(new Term(_classFieldName, WildcardQuery.WILDCARD_STRING.ToString())), Occur.MUST)); if (_query != null) { q.Add(_query, Occur.MUST); } _indexSearcher.Search(q, totalHitCountCollector); docCount = totalHitCountCollector.TotalHits; } return docCount; } private string[] TokenizeDoc(string doc) { ICollection<string> result = new LinkedList<string>(); foreach (string textFieldName in _textFieldNames) { TokenStream tokenStream = _analyzer.GetTokenStream(textFieldName, new StringReader(doc)); try { ICharTermAttribute charTermAttribute = tokenStream.AddAttribute<ICharTermAttribute>(); tokenStream.Reset(); while (tokenStream.IncrementToken()) { result.Add(charTermAttribute.ToString()); } tokenStream.End(); } finally { IOUtils.DisposeWhileHandlingException(tokenStream); } } var ret = new string[result.Count]; result.CopyTo(ret, 0); return ret; } /// <summary> /// Assign a class (with score) to the given text string /// </summary> /// <param name="inputDocument">a string containing text to be classified</param> /// <returns>a <see cref="ClassificationResult{BytesRef}"/> holding assigned class of type <see cref="BytesRef"/> and score</returns> public virtual ClassificationResult<BytesRef> AssignClass(string inputDocument) { if (_atomicReader == null) { throw new IOException("You must first call Classifier#train"); } double max = - double.MaxValue; BytesRef foundClass = new BytesRef(); Terms terms = MultiFields.GetTerms(_atomicReader, _classFieldName); TermsEnum termsEnum = terms.GetIterator(null); BytesRef next; string[] tokenizedDoc = TokenizeDoc(inputDocument); while ((next = termsEnum.Next()) != null) { double clVal = CalculateLogPrior(next) + CalculateLogLikelihood(tokenizedDoc, next); if (clVal > max) { max = clVal; foundClass = BytesRef.DeepCopyOf(next); } } double score = 10 / Math.Abs(max); return new ClassificationResult<BytesRef>(foundClass, score); } private double CalculateLogLikelihood(string[] tokenizedDoc, BytesRef c) { // for each word double result = 0d; foreach (string word in tokenizedDoc) { // search with text:word AND class:c int hits = GetWordFreqForClass(word, c); // num : count the no of times the word appears in documents of class c (+1) double num = hits + 1; // +1 is added because of add 1 smoothing // den : for the whole dictionary, count the no of times a word appears in documents of class c (+|V|) double den = GetTextTermFreqForClass(c) + _docsWithClassSize; // P(w|c) = num/den double wordProbability = num / den; result += Math.Log(wordProbability); } // log(P(d|c)) = log(P(w1|c))+...+log(P(wn|c)) return result; } private double GetTextTermFreqForClass(BytesRef c) { double avgNumberOfUniqueTerms = 0; foreach (string textFieldName in _textFieldNames) { Terms terms = MultiFields.GetTerms(_atomicReader, textFieldName); long numPostings = terms.SumDocFreq; // number of term/doc pairs avgNumberOfUniqueTerms += numPostings / (double) terms.DocCount; // avg # of unique terms per doc } int docsWithC = _atomicReader.DocFreq(new Term(_classFieldName, c)); return avgNumberOfUniqueTerms * docsWithC; // avg # of unique terms in text fields per doc * # docs with c } private int GetWordFreqForClass(string word, BytesRef c) { BooleanQuery booleanQuery = new BooleanQuery(); BooleanQuery subQuery = new BooleanQuery(); foreach (string textFieldName in _textFieldNames) { subQuery.Add(new BooleanClause(new TermQuery(new Term(textFieldName, word)), Occur.SHOULD)); } booleanQuery.Add(new BooleanClause(subQuery, Occur.MUST)); booleanQuery.Add(new BooleanClause(new TermQuery(new Term(_classFieldName, c)), Occur.MUST)); if (_query != null) { booleanQuery.Add(_query, Occur.MUST); } TotalHitCountCollector totalHitCountCollector = new TotalHitCountCollector(); _indexSearcher.Search(booleanQuery, totalHitCountCollector); return totalHitCountCollector.TotalHits; } private double CalculateLogPrior(BytesRef currentClass) { return Math.Log((double) DocCount(currentClass)) - Math.Log(_docsWithClassSize); } private int DocCount(BytesRef countedClass) { return _atomicReader.DocFreq(new Term(_classFieldName, countedClass)); } } }
// 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.Linq; using Xunit; namespace System.Net.Http.Tests { public class CurlResponseParseUtilsTest { private const string StatusCodeTemplate = "HTTP/1.1 {0} {1}"; private const string MissingSpaceFormat = "HTTP/1.1 {0}InvalidPhrase"; private const string StatusCodeVersionFormat = "HTTP/{0}.{1} 200 OK"; private const string StatusCodeMajorVersionOnlyFormat = "HTTP/{0} 200 OK"; private const string ValidHeader = "Content-Type: text/xml; charset=utf-8"; private const string HeaderNameWithInvalidChar = "Content{0}Type: text/xml; charset=utf-8"; private const string invalidChars = "()<>@,;\\\"/[]?={} \t"; public static readonly IEnumerable<object[]> ValidStatusCodeLines = GetStatusCodeLines(StatusCodeTemplate); public static readonly IEnumerable<object[]> InvalidStatusCodeLines = GetStatusCodeLines(MissingSpaceFormat); public static readonly IEnumerable<object[]> StatusCodeVersionLines = GetStatusCodeLinesForMajorVersions(1, 10).Concat(GetStatusCodeLinesForMajorMinorVersions(1, 10)); public static readonly IEnumerable<object[]> InvalidHeaderLines = GetInvalidHeaderLines(); private static IEnumerable<object[]> GetStatusCodeLines(string template) { const string reasonPhrase = "Test Phrase"; foreach(int code in Enum.GetValues(typeof(HttpStatusCode))) { yield return new object[] { string.Format(template, code, reasonPhrase), code, reasonPhrase}; } } private static IEnumerable<object[]> GetStatusCodeLinesForMajorVersions(int min, int max) { for(int major = min; major < max; major++) { yield return new object[] { string.Format(StatusCodeMajorVersionOnlyFormat, major), major, 0 }; } } private static IEnumerable<object[]> GetStatusCodeLinesForMajorMinorVersions(int min, int max) { for(int major = min; major < max; major++) { for(int minor = min; minor < max; minor++) { yield return new object[] {string.Format(StatusCodeVersionFormat, major, minor), major, minor}; } } } private static IEnumerable<object[]> GetInvalidHeaderLines() { foreach(char c in invalidChars) { yield return new object[] { string.Format(HeaderNameWithInvalidChar, c) }; } } #region StatusCode [Theory, MemberData(nameof(ValidStatusCodeLines))] public unsafe void ReadStatusLine_ValidStatusCode_ResponseMessageValueSet(string statusLine, HttpStatusCode expectedCode, string expectedPhrase) { byte[] buffer = statusLine.Select(c => checked((byte)c)).ToArray(); fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), checked((ulong)buffer.Length)); using (var response = new HttpResponseMessage()) { Assert.True(reader.ReadStatusLine(response)); Assert.Equal(expectedCode, response.StatusCode); Assert.Equal(expectedPhrase, response.ReasonPhrase); } } } [Theory, MemberData(nameof(InvalidStatusCodeLines))] public unsafe void ReadStatusLine_InvalidStatusCode_ThrowsHttpRequestException(string statusLine, HttpStatusCode expectedCode, string phrase) { byte[] buffer = statusLine.Select(c => checked((byte)c)).ToArray(); fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), checked((ulong)buffer.Length)); using (var response = new HttpResponseMessage()) { Assert.Throws<HttpRequestException>(() => reader.ReadStatusLine(response)); } } } [Theory, MemberData(nameof(StatusCodeVersionLines))] public unsafe void ReadStatusLine_ValidStatusCodeLine_ResponseMessageVersionSet(string statusLine, int major, int minor) { byte[] buffer = statusLine.Select(c => checked((byte)c)).ToArray(); fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), checked((ulong)buffer.Length)); using (var response = new HttpResponseMessage()) { Assert.True(reader.ReadStatusLine(response)); int expectedMajor = 0; int expectedMinor = 0; if (major == 1 && (minor == 0 || minor == 1)) { expectedMajor = 1; expectedMinor = minor; } else if (major == 2 && minor == 0) { expectedMajor = 2; expectedMinor = 0; } Assert.Equal(expectedMajor, response.Version.Major); Assert.Equal(expectedMinor, response.Version.Minor); } } } #endregion #region Headers public static IEnumerable<object[]> ReadHeader_ValidHeaderLine_HeaderReturned_MemberData() { var namesAndValues = new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("TestHeader", "Test header value"), new KeyValuePair<string, string>("TestHeader", ""), new KeyValuePair<string, string>("Server", "IIS"), new KeyValuePair<string, string>("Server", "I:I:S"), }; var whitespaces = new string[] { "", " ", " ", " \t" }; foreach (KeyValuePair<string, string> nameAndValue in namesAndValues) { foreach (string beforeColon in whitespaces) // only "" is valid according to the RFC, but we parse more leniently { foreach (string afterColon in whitespaces) { yield return new object[] { $"{nameAndValue.Key}{beforeColon}:{afterColon}{nameAndValue.Value}", nameAndValue.Key, nameAndValue.Value }; } } } } [Theory] [MemberData(nameof(ReadHeader_ValidHeaderLine_HeaderReturned_MemberData))] public unsafe void ReadHeader_ValidHeaderLine_HeaderReturned(string headerLine, string expectedHeaderName, string expectedHeaderValue) { byte[] buffer = headerLine.Select(c => checked((byte)c)).ToArray(); fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), checked((ulong)buffer.Length)); string headerName; string headerValue; Assert.True(reader.ReadHeader(out headerName, out headerValue)); Assert.Equal(expectedHeaderName, headerName); Assert.Equal(expectedHeaderValue, headerValue); } } [Fact] public unsafe void ReadHeader_EmptyBuffer_ReturnsFalse() { byte[] buffer = new byte[2]; // Non-empty array so we can get a valid pointer using fixed. ulong length = 0; // But a length of 0 for empty. fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), length); string headerName; string headerValue; Assert.False(reader.ReadHeader(out headerName, out headerValue)); Assert.Null(headerName); Assert.Null(headerValue); } } [Theory, MemberData(nameof(InvalidHeaderLines))] public unsafe void ReadHeaderName_InvalidHeaderLine_ThrowsHttpRequestException(string headerLine) { byte[] buffer = headerLine.Select(c => checked((byte)c)).ToArray(); fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), checked((ulong)buffer.Length)); string headerName; string headerValue; Assert.Throws<HttpRequestException>(() => reader.ReadHeader(out headerName, out headerValue)); } } #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: crm/guests/reservation_note_template.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 HOLMS.Types.CRM.Guests { /// <summary>Holder for reflection information generated from crm/guests/reservation_note_template.proto</summary> public static partial class ReservationNoteTemplateReflection { #region Descriptor /// <summary>File descriptor for crm/guests/reservation_note_template.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ReservationNoteTemplateReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cipjcm0vZ3Vlc3RzL3Jlc2VydmF0aW9uX25vdGVfdGVtcGxhdGUucHJvdG8S", "FmhvbG1zLnR5cGVzLmNybS5ndWVzdHMaNGNybS9ndWVzdHMvcmVzZXJ2YXRp", "b25fbm90ZV90ZW1wbGF0ZV9pbmRpY2F0b3IucHJvdG8aNW9wZXJhdGlvbnMv", "bm90ZV9yZXF1ZXN0cy9ub3RlX3JlcXVlc3RfaW5kaWNhdG9yLnByb3RvGixv", "cGVyYXRpb25zL25vdGVfcmVxdWVzdHMvbm90ZV9jYXRlZ29yeS5wcm90bxog", "Y3JtL2d1ZXN0cy9ndWVzdF9pbmRpY2F0b3IucHJvdG8iiwMKF1Jlc2VydmF0", "aW9uTm90ZVRlbXBsYXRlEksKCWVudGl0eV9pZBgBIAEoCzI4LmhvbG1zLnR5", "cGVzLmNybS5ndWVzdHMuUmVzZXJ2YXRpb25Ob3RlVGVtcGxhdGVJbmRpY2F0", "b3ISTwoLc291cmNlX25vdGUYAiABKAsyOi5ob2xtcy50eXBlcy5vcGVyYXRp", "b25zLm5vdGVfcmVxdWVzdHMuTm90ZVJlcXVlc3RJbmRpY2F0b3ISRAoIY2F0", "ZWdvcnkYAyABKA4yMi5ob2xtcy50eXBlcy5vcGVyYXRpb25zLm5vdGVfcmVx", "dWVzdHMuTm90ZUNhdGVnb3J5EhcKD2FkZGl0aW9uYWxfbm90ZRgEIAEoCRIf", "ChdpbmNsdWRlX29uX2NvbmZpcm1hdGlvbhgFIAEoCBIbChNzb3VyY2Vfbm90", "ZV9zdWJqZWN0GAcgASgJEjUKBWd1ZXN0GAggASgLMiYuaG9sbXMudHlwZXMu", "Y3JtLmd1ZXN0cy5HdWVzdEluZGljYXRvckIZqgIWSE9MTVMuVHlwZXMuQ1JN", "Lkd1ZXN0c2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.CRM.Guests.ReservationNoteTemplateIndicatorReflection.Descriptor, global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicatorReflection.Descriptor, global::HOLMS.Types.Operations.NoteRequests.NoteCategoryReflection.Descriptor, global::HOLMS.Types.CRM.Guests.GuestIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.CRM.Guests.ReservationNoteTemplate), global::HOLMS.Types.CRM.Guests.ReservationNoteTemplate.Parser, new[]{ "EntityId", "SourceNote", "Category", "AdditionalNote", "IncludeOnConfirmation", "SourceNoteSubject", "Guest" }, null, null, null) })); } #endregion } #region Messages public sealed partial class ReservationNoteTemplate : pb::IMessage<ReservationNoteTemplate> { private static readonly pb::MessageParser<ReservationNoteTemplate> _parser = new pb::MessageParser<ReservationNoteTemplate>(() => new ReservationNoteTemplate()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ReservationNoteTemplate> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.CRM.Guests.ReservationNoteTemplateReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationNoteTemplate() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationNoteTemplate(ReservationNoteTemplate other) : this() { EntityId = other.entityId_ != null ? other.EntityId.Clone() : null; SourceNote = other.sourceNote_ != null ? other.SourceNote.Clone() : null; category_ = other.category_; additionalNote_ = other.additionalNote_; includeOnConfirmation_ = other.includeOnConfirmation_; sourceNoteSubject_ = other.sourceNoteSubject_; Guest = other.guest_ != null ? other.Guest.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationNoteTemplate Clone() { return new ReservationNoteTemplate(this); } /// <summary>Field number for the "entity_id" field.</summary> public const int EntityIdFieldNumber = 1; private global::HOLMS.Types.CRM.Guests.ReservationNoteTemplateIndicator entityId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.CRM.Guests.ReservationNoteTemplateIndicator EntityId { get { return entityId_; } set { entityId_ = value; } } /// <summary>Field number for the "source_note" field.</summary> public const int SourceNoteFieldNumber = 2; private global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator sourceNote_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator SourceNote { get { return sourceNote_; } set { sourceNote_ = value; } } /// <summary>Field number for the "category" field.</summary> public const int CategoryFieldNumber = 3; private global::HOLMS.Types.Operations.NoteRequests.NoteCategory category_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.NoteRequests.NoteCategory Category { get { return category_; } set { category_ = value; } } /// <summary>Field number for the "additional_note" field.</summary> public const int AdditionalNoteFieldNumber = 4; private string additionalNote_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string AdditionalNote { get { return additionalNote_; } set { additionalNote_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "include_on_confirmation" field.</summary> public const int IncludeOnConfirmationFieldNumber = 5; private bool includeOnConfirmation_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool IncludeOnConfirmation { get { return includeOnConfirmation_; } set { includeOnConfirmation_ = value; } } /// <summary>Field number for the "source_note_subject" field.</summary> public const int SourceNoteSubjectFieldNumber = 7; private string sourceNoteSubject_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SourceNoteSubject { get { return sourceNoteSubject_; } set { sourceNoteSubject_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "guest" field.</summary> public const int GuestFieldNumber = 8; private global::HOLMS.Types.CRM.Guests.GuestIndicator guest_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.CRM.Guests.GuestIndicator Guest { get { return guest_; } set { guest_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ReservationNoteTemplate); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ReservationNoteTemplate other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(EntityId, other.EntityId)) return false; if (!object.Equals(SourceNote, other.SourceNote)) return false; if (Category != other.Category) return false; if (AdditionalNote != other.AdditionalNote) return false; if (IncludeOnConfirmation != other.IncludeOnConfirmation) return false; if (SourceNoteSubject != other.SourceNoteSubject) return false; if (!object.Equals(Guest, other.Guest)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (entityId_ != null) hash ^= EntityId.GetHashCode(); if (sourceNote_ != null) hash ^= SourceNote.GetHashCode(); if (Category != 0) hash ^= Category.GetHashCode(); if (AdditionalNote.Length != 0) hash ^= AdditionalNote.GetHashCode(); if (IncludeOnConfirmation != false) hash ^= IncludeOnConfirmation.GetHashCode(); if (SourceNoteSubject.Length != 0) hash ^= SourceNoteSubject.GetHashCode(); if (guest_ != null) hash ^= Guest.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (entityId_ != null) { output.WriteRawTag(10); output.WriteMessage(EntityId); } if (sourceNote_ != null) { output.WriteRawTag(18); output.WriteMessage(SourceNote); } if (Category != 0) { output.WriteRawTag(24); output.WriteEnum((int) Category); } if (AdditionalNote.Length != 0) { output.WriteRawTag(34); output.WriteString(AdditionalNote); } if (IncludeOnConfirmation != false) { output.WriteRawTag(40); output.WriteBool(IncludeOnConfirmation); } if (SourceNoteSubject.Length != 0) { output.WriteRawTag(58); output.WriteString(SourceNoteSubject); } if (guest_ != null) { output.WriteRawTag(66); output.WriteMessage(Guest); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (entityId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId); } if (sourceNote_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceNote); } if (Category != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Category); } if (AdditionalNote.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(AdditionalNote); } if (IncludeOnConfirmation != false) { size += 1 + 1; } if (SourceNoteSubject.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SourceNoteSubject); } if (guest_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Guest); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ReservationNoteTemplate other) { if (other == null) { return; } if (other.entityId_ != null) { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.CRM.Guests.ReservationNoteTemplateIndicator(); } EntityId.MergeFrom(other.EntityId); } if (other.sourceNote_ != null) { if (sourceNote_ == null) { sourceNote_ = new global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator(); } SourceNote.MergeFrom(other.SourceNote); } if (other.Category != 0) { Category = other.Category; } if (other.AdditionalNote.Length != 0) { AdditionalNote = other.AdditionalNote; } if (other.IncludeOnConfirmation != false) { IncludeOnConfirmation = other.IncludeOnConfirmation; } if (other.SourceNoteSubject.Length != 0) { SourceNoteSubject = other.SourceNoteSubject; } if (other.guest_ != null) { if (guest_ == null) { guest_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator(); } Guest.MergeFrom(other.Guest); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.CRM.Guests.ReservationNoteTemplateIndicator(); } input.ReadMessage(entityId_); break; } case 18: { if (sourceNote_ == null) { sourceNote_ = new global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator(); } input.ReadMessage(sourceNote_); break; } case 24: { category_ = (global::HOLMS.Types.Operations.NoteRequests.NoteCategory) input.ReadEnum(); break; } case 34: { AdditionalNote = input.ReadString(); break; } case 40: { IncludeOnConfirmation = input.ReadBool(); break; } case 58: { SourceNoteSubject = input.ReadString(); break; } case 66: { if (guest_ == null) { guest_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator(); } input.ReadMessage(guest_); break; } } } } } #endregion } #endregion Designer generated code
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Network.Models; namespace Microsoft.WindowsAzure.Management.Network.Models { /// <summary> /// The response structure for the Network Operations List operation. /// </summary> public partial class NetworkListResponse : AzureOperationResponse, IEnumerable<NetworkListResponse.VirtualNetworkSite> { private IList<NetworkListResponse.VirtualNetworkSite> _virtualNetworkSites; /// <summary> /// Optional. /// </summary> public IList<NetworkListResponse.VirtualNetworkSite> VirtualNetworkSites { get { return this._virtualNetworkSites; } set { this._virtualNetworkSites = value; } } /// <summary> /// Initializes a new instance of the NetworkListResponse class. /// </summary> public NetworkListResponse() { this.VirtualNetworkSites = new LazyList<NetworkListResponse.VirtualNetworkSite>(); } /// <summary> /// Gets the sequence of VirtualNetworkSites. /// </summary> public IEnumerator<NetworkListResponse.VirtualNetworkSite> GetEnumerator() { return this.VirtualNetworkSites.GetEnumerator(); } /// <summary> /// Gets the sequence of VirtualNetworkSites. /// </summary> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public partial class AddressSpace { private IList<string> _addressPrefixes; /// <summary> /// Optional. Address spaces, in CIDR format in the virtual network. /// </summary> public IList<string> AddressPrefixes { get { return this._addressPrefixes; } set { this._addressPrefixes = value; } } /// <summary> /// Initializes a new instance of the AddressSpace class. /// </summary> public AddressSpace() { this.AddressPrefixes = new LazyList<string>(); } } /// <summary> /// Specifies the type of connection of the local network site. The /// value of this element can be either IPsec or Dedicated. The /// default value is IPsec. /// </summary> public partial class Connection { private string _type; /// <summary> /// Optional. /// </summary> public string Type { get { return this._type; } set { this._type = value; } } /// <summary> /// Initializes a new instance of the Connection class. /// </summary> public Connection() { } } public partial class DnsServer { private string _address; /// <summary> /// Optional. The IPv4 address of the DNS server. /// </summary> public string Address { get { return this._address; } set { this._address = value; } } private string _name; /// <summary> /// Optional. The name of the DNS server. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } /// <summary> /// Initializes a new instance of the DnsServer class. /// </summary> public DnsServer() { } } /// <summary> /// Contains gateway references to the local network sites that the /// virtual network can connect to. /// </summary> public partial class Gateway { private string _profile; /// <summary> /// Optional. The gateway connection size. /// </summary> public string Profile { get { return this._profile; } set { this._profile = value; } } private IList<NetworkListResponse.LocalNetworkSite> _sites; /// <summary> /// Optional. The list of local network sites that the virtual /// network can connect to. /// </summary> public IList<NetworkListResponse.LocalNetworkSite> Sites { get { return this._sites; } set { this._sites = value; } } private NetworkListResponse.VPNClientAddressPool _vPNClientAddressPool; /// <summary> /// Optional. The VPN Client Address Pool reserves a pool of IP /// addresses for VPN clients. This object is used for /// point-to-site connectivity. /// </summary> public NetworkListResponse.VPNClientAddressPool VPNClientAddressPool { get { return this._vPNClientAddressPool; } set { this._vPNClientAddressPool = value; } } /// <summary> /// Initializes a new instance of the Gateway class. /// </summary> public Gateway() { this.Sites = new LazyList<NetworkListResponse.LocalNetworkSite>(); } } /// <summary> /// Contains the list of parameters defining the local network site. /// </summary> public partial class LocalNetworkSite { private NetworkListResponse.AddressSpace _addressSpace; /// <summary> /// Optional. The address space of the local network site. /// </summary> public NetworkListResponse.AddressSpace AddressSpace { get { return this._addressSpace; } set { this._addressSpace = value; } } private IList<NetworkListResponse.Connection> _connections; /// <summary> /// Optional. Specifies the types of connections to the local /// network site. /// </summary> public IList<NetworkListResponse.Connection> Connections { get { return this._connections; } set { this._connections = value; } } private string _name; /// <summary> /// Optional. The name of the local network site. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _vpnGatewayAddress; /// <summary> /// Optional. The IPv4 address of the local network site. /// </summary> public string VpnGatewayAddress { get { return this._vpnGatewayAddress; } set { this._vpnGatewayAddress = value; } } /// <summary> /// Initializes a new instance of the LocalNetworkSite class. /// </summary> public LocalNetworkSite() { this.Connections = new LazyList<NetworkListResponse.Connection>(); } } public partial class Subnet { private string _addressPrefix; /// <summary> /// Optional. Represents an address space, in CIDR format that /// defines the subnet. /// </summary> public string AddressPrefix { get { return this._addressPrefix; } set { this._addressPrefix = value; } } private string _name; /// <summary> /// Optional. Name of the subnet. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _networkSecurityGroup; /// <summary> /// Optional. Name of Network Security Group associated with this /// subnet. /// </summary> public string NetworkSecurityGroup { get { return this._networkSecurityGroup; } set { this._networkSecurityGroup = value; } } /// <summary> /// Initializes a new instance of the Subnet class. /// </summary> public Subnet() { } } /// <summary> /// Contains the collections of parameters used to configure a virtual /// network space that is dedicated to your subscription without /// overlapping with other networks /// </summary> public partial class VirtualNetworkSite { private NetworkListResponse.AddressSpace _addressSpace; /// <summary> /// Optional. The list of network address spaces for a virtual /// network site. This represents the overall network space /// contained within the virtual network site. /// </summary> public NetworkListResponse.AddressSpace AddressSpace { get { return this._addressSpace; } set { this._addressSpace = value; } } private string _affinityGroup; /// <summary> /// Optional. An affinity group, which indirectly refers to the /// location where the virtual network exists. /// </summary> public string AffinityGroup { get { return this._affinityGroup; } set { this._affinityGroup = value; } } private IList<NetworkListResponse.DnsServer> _dnsServers; /// <summary> /// Optional. The list of available DNS Servers associated with the /// virtual network site. /// </summary> public IList<NetworkListResponse.DnsServer> DnsServers { get { return this._dnsServers; } set { this._dnsServers = value; } } private NetworkListResponse.Gateway _gateway; /// <summary> /// Optional. The gateway that contains a list of Local Network /// Sites which enable the Virtual Network Site to communicate /// with a customer's on-premise networks. /// </summary> public NetworkListResponse.Gateway Gateway { get { return this._gateway; } set { this._gateway = value; } } private string _id; /// <summary> /// Optional. A unique string identifier that represents the /// virtual network site. /// </summary> public string Id { get { return this._id; } set { this._id = value; } } private string _label; /// <summary> /// Optional. The friendly identifier for the site. /// </summary> public string Label { get { return this._label; } set { this._label = value; } } private string _location; /// <summary> /// Optional. Gets or sets the virtual network location. /// </summary> public string Location { get { return this._location; } set { this._location = value; } } private string _migrationState; /// <summary> /// Optional. Specifies the IaaS Classic to ARM migration state of /// the Virtual Network Site. Possible values are: None, /// Preparing, Prepared, PrepareFailed, Committing, Committed, /// CommitFailed, Aborting, AbortFailed. None is treated as null /// value and it is not be visible. /// </summary> public string MigrationState { get { return this._migrationState; } set { this._migrationState = value; } } private string _name; /// <summary> /// Optional. Name of the virtual network site. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _state; /// <summary> /// Optional. Current status of the virtual network. (Created, /// Creating, Updating, Deleting, or Unavailable.) /// </summary> public string State { get { return this._state; } set { this._state = value; } } private IList<NetworkListResponse.Subnet> _subnets; /// <summary> /// Optional. The list of network subnets for a virtual network /// site. All network subnets must be contained within the overall /// virtual network address spaces. /// </summary> public IList<NetworkListResponse.Subnet> Subnets { get { return this._subnets; } set { this._subnets = value; } } /// <summary> /// Initializes a new instance of the VirtualNetworkSite class. /// </summary> public VirtualNetworkSite() { this.DnsServers = new LazyList<NetworkListResponse.DnsServer>(); this.Subnets = new LazyList<NetworkListResponse.Subnet>(); } } /// <summary> /// The VPN Client Address Pool reserves a pool of IP addresses for VPN /// clients. This object is used for point-to-site connectivity. /// </summary> public partial class VPNClientAddressPool { private IList<string> _addressPrefixes; /// <summary> /// Optional. The CIDR identifiers that identify addresses in the /// pool. /// </summary> public IList<string> AddressPrefixes { get { return this._addressPrefixes; } set { this._addressPrefixes = value; } } /// <summary> /// Initializes a new instance of the VPNClientAddressPool class. /// </summary> public VPNClientAddressPool() { this.AddressPrefixes = new LazyList<string>(); } } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Linq; using System.Text; #pragma warning disable 0618 namespace NLog.UnitTests.Contexts { using System; using System.Collections.Generic; using System.Threading; using Xunit; public class MappedDiagnosticsContextTests { /// <summary> /// Same as <see cref="MappedDiagnosticsContext" />, but there is one <see cref="MappedDiagnosticsContext"/> per each thread. /// </summary> [Fact] public void MDCTest1() { List<Exception> exceptions = new List<Exception>(); ManualResetEvent mre = new ManualResetEvent(false); int counter = 100; int remaining = counter; for (int i = 0; i < counter; ++i) { ThreadPool.QueueUserWorkItem( s => { try { MappedDiagnosticsContext.Clear(); Assert.False(MappedDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo")); Assert.False(MappedDiagnosticsContext.Contains("foo2")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo2")); Assert.Equal(0, MappedDiagnosticsContext.GetNames().Count); MappedDiagnosticsContext.Set("foo", "bar"); MappedDiagnosticsContext.Set("foo2", "bar2"); Assert.True(MappedDiagnosticsContext.Contains("foo")); Assert.Equal("bar", MappedDiagnosticsContext.Get("foo")); Assert.Equal(2, MappedDiagnosticsContext.GetNames().Count); MappedDiagnosticsContext.Remove("foo"); Assert.False(MappedDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo")); Assert.True(MappedDiagnosticsContext.Contains("foo2")); Assert.Equal("bar2", MappedDiagnosticsContext.Get("foo2")); Assert.Equal(1, MappedDiagnosticsContext.GetNames().Count); Assert.True(MappedDiagnosticsContext.GetNames().Contains("foo2")); Assert.Null(MappedDiagnosticsContext.GetObject("foo3")); MappedDiagnosticsContext.Set("foo3", new { One = 1 }); } catch (Exception exception) { lock (exceptions) { exceptions.Add(exception); } } finally { if (Interlocked.Decrement(ref remaining) == 0) { mre.Set(); } } }); } mre.WaitOne(); StringBuilder exceptionsMessage = new StringBuilder(); foreach (var ex in exceptions) { if (exceptionsMessage.Length > 0) { exceptionsMessage.Append("\r\n"); } exceptionsMessage.Append(ex.ToString()); } Assert.True(exceptions.Count == 0, exceptionsMessage.ToString()); } [Fact] public void MDCTest2() { List<Exception> exceptions = new List<Exception>(); ManualResetEvent mre = new ManualResetEvent(false); int counter = 100; int remaining = counter; for (int i = 0; i < counter; ++i) { ThreadPool.QueueUserWorkItem( s => { try { MDC.Clear(); Assert.False(MDC.Contains("foo")); Assert.Equal(string.Empty, MDC.Get("foo")); Assert.False(MDC.Contains("foo2")); Assert.Equal(string.Empty, MDC.Get("foo2")); MDC.Set("foo", "bar"); MDC.Set("foo2", "bar2"); Assert.True(MDC.Contains("foo")); Assert.Equal("bar", MDC.Get("foo")); MDC.Remove("foo"); Assert.False(MDC.Contains("foo")); Assert.Equal(string.Empty, MDC.Get("foo")); Assert.True(MDC.Contains("foo2")); Assert.Equal("bar2", MDC.Get("foo2")); Assert.Null(MDC.GetObject("foo3")); } catch (Exception ex) { lock (exceptions) { exceptions.Add(ex); } } finally { if (Interlocked.Decrement(ref remaining) == 0) { mre.Set(); } } }); } mre.WaitOne(); StringBuilder exceptionsMessage = new StringBuilder(); foreach (var ex in exceptions) { if (exceptionsMessage.Length > 0) { exceptionsMessage.Append("\r\n"); } exceptionsMessage.Append(ex.ToString()); } Assert.True(exceptions.Count == 0, exceptionsMessage.ToString()); } [Fact] public void timer_cannot_inherit_mappedcontext() { object getObject = null; string getValue = null; var mre = new ManualResetEvent(false); Timer thread = new Timer((s) => { try { getObject = MDC.GetObject("DoNotExist"); getValue = MDC.Get("DoNotExistEither"); } finally { mre.Set(); } }); thread.Change(0, Timeout.Infinite); mre.WaitOne(); Assert.Null(getObject); Assert.Empty(getValue); } [Fact] public void disposable_removes_item() { const string itemNotRemovedKey = "itemNotRemovedKey"; const string itemRemovedKey = "itemRemovedKey"; MappedDiagnosticsContext.Clear(); MappedDiagnosticsContext.Set(itemNotRemovedKey, "itemNotRemoved"); using (MappedDiagnosticsContext.SetScoped(itemRemovedKey, "itemRemoved")) { Assert.Equal(MappedDiagnosticsContext.GetNames(), new[] { itemNotRemovedKey, itemRemovedKey }); } Assert.Equal(MappedDiagnosticsContext.GetNames(), new[] { itemNotRemovedKey }); } [Fact] public void dispose_is_idempotent() { const string itemKey = "itemKey"; MappedDiagnosticsContext.Clear(); IDisposable disposable = MappedDiagnosticsContext.SetScoped(itemKey, "item1"); disposable.Dispose(); Assert.False(MappedDiagnosticsContext.Contains(itemKey)); //This item shouldn't be removed since it is not the disposable one MappedDiagnosticsContext.Set(itemKey, "item2"); disposable.Dispose(); Assert.True(MappedDiagnosticsContext.Contains(itemKey)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyNumber { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class NumberExtensions { /// <summary> /// Get null Number value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static double? GetNull(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null Number value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<double?> GetNullAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Get invalid float Number value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static double? GetInvalidFloat(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetInvalidFloatAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid float Number value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<double?> GetInvalidFloatAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetInvalidFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Get invalid double Number value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static double? GetInvalidDouble(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetInvalidDoubleAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid double Number value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<double?> GetInvalidDoubleAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetInvalidDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Get invalid decimal Number value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static decimal? GetInvalidDecimal(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetInvalidDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid decimal Number value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<decimal?> GetInvalidDecimalAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetInvalidDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put big float value 3.402823e+20 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> public static void PutBigFloat(this INumber operations, double? numberBody) { Task.Factory.StartNew(s => ((INumber)s).PutBigFloatAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put big float value 3.402823e+20 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutBigFloatAsync( this INumber operations, double? numberBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutBigFloatWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get big float value 3.402823e+20 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static double? GetBigFloat(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetBigFloatAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get big float value 3.402823e+20 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<double?> GetBigFloatAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetBigFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put big double value 2.5976931e+101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> public static void PutBigDouble(this INumber operations, double? numberBody) { Task.Factory.StartNew(s => ((INumber)s).PutBigDoubleAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put big double value 2.5976931e+101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutBigDoubleAsync( this INumber operations, double? numberBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutBigDoubleWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get big double value 2.5976931e+101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static double? GetBigDouble(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetBigDoubleAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get big double value 2.5976931e+101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<double?> GetBigDoubleAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetBigDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put big double value 99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> public static void PutBigDoublePositiveDecimal(this INumber operations, double? numberBody) { Task.Factory.StartNew(s => ((INumber)s).PutBigDoublePositiveDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put big double value 99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutBigDoublePositiveDecimalAsync( this INumber operations, double? numberBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutBigDoublePositiveDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get big double value 99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static double? GetBigDoublePositiveDecimal(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetBigDoublePositiveDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get big double value 99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<double?> GetBigDoublePositiveDecimalAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetBigDoublePositiveDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put big double value -99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> public static void PutBigDoubleNegativeDecimal(this INumber operations, double? numberBody) { Task.Factory.StartNew(s => ((INumber)s).PutBigDoubleNegativeDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put big double value -99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutBigDoubleNegativeDecimalAsync( this INumber operations, double? numberBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutBigDoubleNegativeDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get big double value -99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static double? GetBigDoubleNegativeDecimal(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetBigDoubleNegativeDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get big double value -99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<double?> GetBigDoubleNegativeDecimalAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetBigDoubleNegativeDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put big decimal value 2.5976931e+101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> public static void PutBigDecimal(this INumber operations, decimal? numberBody) { Task.Factory.StartNew(s => ((INumber)s).PutBigDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put big decimal value 2.5976931e+101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutBigDecimalAsync( this INumber operations, decimal? numberBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutBigDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get big decimal value 2.5976931e+101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static decimal? GetBigDecimal(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetBigDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get big decimal value 2.5976931e+101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<decimal?> GetBigDecimalAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetBigDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put big decimal value 99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> public static void PutBigDecimalPositiveDecimal(this INumber operations, decimal? numberBody) { Task.Factory.StartNew(s => ((INumber)s).PutBigDecimalPositiveDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put big decimal value 99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutBigDecimalPositiveDecimalAsync( this INumber operations, decimal? numberBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutBigDecimalPositiveDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get big decimal value 99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static decimal? GetBigDecimalPositiveDecimal(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetBigDecimalPositiveDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get big decimal value 99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<decimal?> GetBigDecimalPositiveDecimalAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetBigDecimalPositiveDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put big decimal value -99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> public static void PutBigDecimalNegativeDecimal(this INumber operations, decimal? numberBody) { Task.Factory.StartNew(s => ((INumber)s).PutBigDecimalNegativeDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put big decimal value -99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutBigDecimalNegativeDecimalAsync( this INumber operations, decimal? numberBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutBigDecimalNegativeDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get big decimal value -99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static decimal? GetBigDecimalNegativeDecimal(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetBigDecimalNegativeDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get big decimal value -99999999.99 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<decimal?> GetBigDecimalNegativeDecimalAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetBigDecimalNegativeDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put small float value 3.402823e-20 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> public static void PutSmallFloat(this INumber operations, double? numberBody) { Task.Factory.StartNew(s => ((INumber)s).PutSmallFloatAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put small float value 3.402823e-20 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutSmallFloatAsync( this INumber operations, double? numberBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutSmallFloatWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get big double value 3.402823e-20 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static double? GetSmallFloat(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetSmallFloatAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get big double value 3.402823e-20 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<double?> GetSmallFloatAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetSmallFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put small double value 2.5976931e-101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> public static void PutSmallDouble(this INumber operations, double? numberBody) { Task.Factory.StartNew(s => ((INumber)s).PutSmallDoubleAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put small double value 2.5976931e-101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutSmallDoubleAsync( this INumber operations, double? numberBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutSmallDoubleWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get big double value 2.5976931e-101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static double? GetSmallDouble(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetSmallDoubleAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get big double value 2.5976931e-101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<double?> GetSmallDoubleAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetSmallDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put small decimal value 2.5976931e-101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> public static void PutSmallDecimal(this INumber operations, decimal? numberBody) { Task.Factory.StartNew(s => ((INumber)s).PutSmallDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put small decimal value 2.5976931e-101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutSmallDecimalAsync( this INumber operations, decimal? numberBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutSmallDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get small decimal value 2.5976931e-101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static decimal? GetSmallDecimal(this INumber operations) { return Task.Factory.StartNew(s => ((INumber)s).GetSmallDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get small decimal value 2.5976931e-101 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<decimal?> GetSmallDecimalAsync( this INumber operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetSmallDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } } }
// 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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [ComVisible(true)] public class AutomationObject { private readonly IOptionService _optionService; internal AutomationObject(IOptionService optionService) { _optionService = optionService; } public int AutoComment { get { return GetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration); } set { SetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration, value); } } public int BringUpOnIdentifier { get { return GetBooleanOption(CompletionOptions.TriggerOnTypingLetters); } set { SetBooleanOption(CompletionOptions.TriggerOnTypingLetters, value); } } [Obsolete("This SettingStore option has now been deprecated in favor of CSharpClosedFileDiagnostics")] public int ClosedFileDiagnostics { get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); } set { // Even though this option has been deprecated, we want to respect the setting if the user has explicitly turned off closed file diagnostics (which is the non-default value for 'ClosedFileDiagnostics'). // So, we invoke the setter only for value = 0. if (value == 0) { SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value); } } } public int CSharpClosedFileDiagnostics { get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); } set { SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value); } } public int DisplayLineSeparators { get { return GetBooleanOption(FeatureOnOffOptions.LineSeparator); } set { SetBooleanOption(FeatureOnOffOptions.LineSeparator, value); } } public int EnableHighlightRelatedKeywords { get { return GetBooleanOption(FeatureOnOffOptions.KeywordHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.KeywordHighlighting, value); } } public int EnterOutliningModeOnOpen { get { return GetBooleanOption(FeatureOnOffOptions.Outlining); } set { SetBooleanOption(FeatureOnOffOptions.Outlining, value); } } public int ExtractMethod_AllowMovingDeclaration { get { return GetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration); } set { SetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration, value); } } public int ExtractMethod_DoNotPutOutOrRefOnStruct { get { return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct); } set { SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value); } } public int Formatting_TriggerOnBlockCompletion { get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace); } set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace, value); } } public int Formatting_TriggerOnPaste { get { return GetBooleanOption(FeatureOnOffOptions.FormatOnPaste); } set { SetBooleanOption(FeatureOnOffOptions.FormatOnPaste, value); } } public int Formatting_TriggerOnStatementCompletion { get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon); } set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon, value); } } public int HighlightReferences { get { return GetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting, value); } } public int Indent_BlockContents { get { return GetBooleanOption(CSharpFormattingOptions.IndentBlock); } set { SetBooleanOption(CSharpFormattingOptions.IndentBlock, value); } } public int Indent_Braces { get { return GetBooleanOption(CSharpFormattingOptions.IndentBraces); } set { SetBooleanOption(CSharpFormattingOptions.IndentBraces, value); } } public int Indent_CaseContents { get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection); } set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection, value); } } public int Indent_CaseLabels { get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchSection); } set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchSection, value); } } public int Indent_FlushLabelsLeft { get { var option = _optionService.GetOption(CSharpFormattingOptions.LabelPositioning); return option == LabelPositionOptions.LeftMost ? 1 : 0; } set { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent); _optionService.SetOptions(optionSet); } } public int Indent_UnindentLabels { get { var option = _optionService.GetOption(CSharpFormattingOptions.LabelPositioning); return (int)option; } set { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value); _optionService.SetOptions(optionSet); } } public int InsertNewlineOnEnterWithWholeWord { get { return GetBooleanOption(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord); } set { SetBooleanOption(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord, value); } } public int NewLines_AnonymousTypeInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, value); } } public int NewLines_Braces_AnonymousMethod { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, value); } } public int NewLines_Braces_AnonymousTypeInitializer { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, value); } } public int NewLines_Braces_ControlFlow { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, value); } } public int NewLines_Braces_LambdaExpressionBody { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, value); } } public int NewLines_Braces_Method { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods, value); } } public int NewLines_Braces_Property { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties, value); } } public int NewLines_Braces_Accessor { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors, value); } } public int NewLines_Braces_ObjectInitializer { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, value); } } public int NewLines_Braces_Type { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes, value); } } public int NewLines_Keywords_Catch { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForCatch); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForCatch, value); } } public int NewLines_Keywords_Else { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForElse); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForElse, value); } } public int NewLines_Keywords_Finally { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForFinally); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForFinally, value); } } public int NewLines_ObjectInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, value); } } public int NewLines_QueryExpression_EachClause { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery, value); } } public int Refactoring_Verification_Enabled { get { return GetBooleanOption(FeatureOnOffOptions.RefactoringVerification); } set { SetBooleanOption(FeatureOnOffOptions.RefactoringVerification, value); } } public int RenameSmartTagEnabled { get { return GetBooleanOption(FeatureOnOffOptions.RenameTracking); } set { SetBooleanOption(FeatureOnOffOptions.RenameTracking, value); } } public int RenameTrackingPreview { get { return GetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview); } set { SetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview, value); } } public int ShowKeywords { get { return GetBooleanOption(CompletionOptions.IncludeKeywords); } set { SetBooleanOption(CompletionOptions.IncludeKeywords, value); } } public int ShowSnippets { get { return GetBooleanOption(CSharpCompletionOptions.IncludeSnippets); } set { SetBooleanOption(CSharpCompletionOptions.IncludeSnippets, value); } } public int SortUsings_PlaceSystemFirst { get { return GetBooleanOption(OrganizerOptions.PlaceSystemNamespaceFirst); } set { SetBooleanOption(OrganizerOptions.PlaceSystemNamespaceFirst, value); } } public int Space_AfterBasesColon { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, value); } } public int Space_AfterCast { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterCast); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterCast, value); } } public int Space_AfterComma { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterComma); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterComma, value); } } public int Space_AfterDot { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterDot); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterDot, value); } } public int Space_AfterMethodCallName { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName, value); } } public int Space_AfterMethodDeclarationName { get { return GetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName); } set { SetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, value); } } public int Space_AfterSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, value); } } public int Space_AroundBinaryOperator { get { var option = _optionService.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); return option == BinaryOperatorSpacingOptions.Single ? 1 : 0; } set { var option = value == 1 ? BinaryOperatorSpacingOptions.Single : BinaryOperatorSpacingOptions.Ignore; var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, option); _optionService.SetOptions(optionSet); } } public int Space_BeforeBasesColon { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, value); } } public int Space_BeforeComma { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma, value); } } public int Space_BeforeDot { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot, value); } } public int Space_BeforeOpenSquare { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, value); } } public int Space_BeforeSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, value); } } public int Space_BetweenEmptyMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, value); } } public int Space_BetweenEmptyMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, value); } } public int Space_BetweenEmptySquares { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, value); } } public int Space_InControlFlowConstruct { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, value); } } public int Space_WithinCastParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses, value); } } public int Space_WithinExpressionParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses, value); } } public int Space_WithinMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, value); } } public int Space_WithinMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, value); } } public int Space_WithinOtherParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses, value); } } public int Space_WithinSquares { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets, value); } } public int Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration { get { return GetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration); } set { SetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value); } } public int Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess { get { return GetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); } set { SetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value); } } public int Style_QualifyMemberAccessWithThisOrMe { get { return GetBooleanOption(SimplificationOptions.QualifyMemberAccessWithThisOrMe); } set { SetBooleanOption(SimplificationOptions.QualifyMemberAccessWithThisOrMe, value); } } public int Style_UseVarWhenDeclaringLocals { get { return GetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals); } set { SetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals, value); } } public int WarnOnBuildErrors { get { return GetBooleanOption(OrganizerOptions.WarnOnBuildErrors); } set { SetBooleanOption(OrganizerOptions.WarnOnBuildErrors, value); } } public int Wrapping_IgnoreSpacesAroundBinaryOperators { get { var option = _optionService.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); return (int)option; } set { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, value); _optionService.SetOptions(optionSet); } } public int Wrapping_IgnoreSpacesAroundVariableDeclaration { get { return GetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, value); } } public int Wrapping_KeepStatementsOnSingleLine { get { return GetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine); } set { SetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, value); } } public int Wrapping_PreserveSingleLine { get { return GetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine); } set { SetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine, value); } } private int GetBooleanOption(Option<bool> key) { return _optionService.GetOption(key) ? 1 : 0; } private int GetBooleanOption(PerLanguageOption<bool> key) { return _optionService.GetOption(key, LanguageNames.CSharp) ? 1 : 0; } private void SetBooleanOption(Option<bool> key, int value) { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(key, value != 0); _optionService.SetOptions(optionSet); } private void SetBooleanOption(PerLanguageOption<bool> key, int value) { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(key, LanguageNames.CSharp, value != 0); _optionService.SetOptions(optionSet); } private int GetBooleanOption(PerLanguageOption<bool?> key) { var option = _optionService.GetOption(key, LanguageNames.CSharp); if (!option.HasValue) { return -1; } return option.Value ? 1 : 0; } private void SetBooleanOption(PerLanguageOption<bool?> key, int value) { bool? boolValue = (value < 0) ? (bool?)null : (value > 0); var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(key, LanguageNames.CSharp, boolValue); _optionService.SetOptions(optionSet); } } }
// TrackInfo.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Reflection; using System.Collections.Generic; using Mono.Unix; using Hyena; using Hyena.Data; using Banshee.Base; using Banshee.Streaming; namespace Banshee.Collection { // WARNING: Be extremely careful when changing property names flagged with [Exportable]! // There are third party applications depending on them! public class TrackInfo : CacheableItem, ITrackInfo { public const string ExportVersion = "1.0"; public static readonly double PlaybackSkippedThreshold = 0.5; public static readonly string UnknownTitle = Catalog.GetString ("Unknown Title"); public static readonly string UnknownTitleUntranslated = "Unknown Title"; public class ExportableAttribute : Attribute { private string export_name; public string ExportName { get { return export_name; } set { export_name = value; } } } public delegate bool IsPlayingHandler (TrackInfo track); public static IsPlayingHandler IsPlayingMethod; public delegate void PlaybackFinishedHandler (TrackInfo track, double percentCompleted); public static event PlaybackFinishedHandler PlaybackFinished; private string artist_name_sort; private string album_title_sort; private string album_artist; private string album_artist_sort; private string track_title_sort; private int track_count; private int disc_count; private StreamPlaybackError playback_error = StreamPlaybackError.None; public TrackInfo () { } public virtual void OnPlaybackFinished (double percentCompleted) { double total_plays = PlayCount + SkipCount; if (total_plays <= 0) { Score = (int) Math.Round (percentCompleted * 100); } else { Score = (int) Math.Round ((((double)Score * total_plays) + (percentCompleted * 100)) / (total_plays + 1)); } if (percentCompleted <= PlaybackSkippedThreshold) { LastSkipped = DateTime.Now; SkipCount++; } else { LastPlayed = DateTime.Now; PlayCount++; } PlaybackFinishedHandler handler = PlaybackFinished; if (handler != null) { handler (this, percentCompleted); } } public override string ToString () { return String.Format ("{0} - {1} (on {2}) <{3}> [{4}]", ArtistName, TrackTitle, AlbumTitle, Duration, Uri == null ? "<unknown>" : Uri.AbsoluteUri); } public virtual bool TrackEqual (TrackInfo track) { if (track == this) { return true; } if (track == null || track.Uri == null || Uri == null) { return false; } return track.Uri.AbsoluteUri == Uri.AbsoluteUri; } public bool ArtistAlbumEqual (TrackInfo track) { if (track == null) { return false; } return ArtworkId == track.ArtworkId; } public virtual void Save () { } public virtual void Update () { Save (); } public virtual void UpdateLastPlayed () { LastPlayed = DateTime.Now; } public virtual bool IsPlaying { get { return (IsPlayingMethod != null) ? IsPlayingMethod (this) : false; } } [Exportable (ExportName = "URI")] public virtual SafeUri Uri { get; set; } [Exportable] public string LocalPath { get { return Uri == null || !Uri.IsLocalPath ? null : Uri.LocalPath; } } [Exportable] public SafeUri MoreInfoUri { get; set; } [Exportable] public virtual string MimeType { get; set; } [Exportable] public virtual long FileSize { get; set; } public virtual long FileModifiedStamp { get; set; } public virtual DateTime LastSyncedStamp { get; set; } [Exportable (ExportName = "artist")] public virtual string ArtistName { get; set; } [Exportable (ExportName = "artistsort")] public virtual string ArtistNameSort { get { return artist_name_sort; } set { artist_name_sort = String.IsNullOrEmpty (value) ? null : value; } } [Exportable (ExportName = "album")] public virtual string AlbumTitle { get; set; } [Exportable (ExportName = "albumsort")] public virtual string AlbumTitleSort { get { return album_title_sort; } set { album_title_sort = String.IsNullOrEmpty (value) ? null : value; } } [Exportable] public virtual string AlbumArtist { get { return IsCompilation ? album_artist ?? Catalog.GetString ("Various Artists") : ArtistName; } set { album_artist = value; } } [Exportable] public virtual string AlbumArtistSort { get { return album_artist_sort; } set { album_artist_sort = String.IsNullOrEmpty (value) ? null : value; } } [Exportable] public virtual bool IsCompilation { get; set; } [Exportable (ExportName = "name")] public virtual string TrackTitle { get; set; } [Exportable (ExportName = "namesort")] public virtual string TrackTitleSort { get { return track_title_sort; } set { track_title_sort = String.IsNullOrEmpty (value) ? null : value; } } [Exportable] public virtual string MusicBrainzId { get; set; } [Exportable] public virtual string ArtistMusicBrainzId { get; set; } [Exportable] public virtual string AlbumMusicBrainzId { get; set; } public virtual DateTime ReleaseDate { get; set; } public virtual object ExternalObject { get { return null; } } public string DisplayArtistName { get { return StringUtil.MaybeFallback (ArtistName, ArtistInfo.UnknownArtistName); } } public string DisplayAlbumArtistName { get { return StringUtil.MaybeFallback (AlbumArtist, DisplayArtistName); } } public string DisplayAlbumTitle { get { return StringUtil.MaybeFallback (AlbumTitle, AlbumInfo.UnknownAlbumTitle); } } public string DisplayTrackTitle { get { return StringUtil.MaybeFallback (TrackTitle, UnknownTitle); } } public string DisplayGenre { get { string genre = Genre == null ? null : Genre.Trim (); return String.IsNullOrEmpty (genre) ? String.Empty : genre; } } [Exportable (ExportName = "artwork-id")] public virtual string ArtworkId { get { return CoverArtSpec.CreateArtistAlbumId (AlbumArtist, AlbumTitle); } } [Exportable] public virtual string Genre { get; set; } [Exportable] public virtual int TrackNumber { get; set; } [Exportable] public virtual int TrackCount { get { return (track_count != 0 && track_count < TrackNumber) ? TrackNumber : track_count; } set { track_count = value; } } [Exportable] public virtual int DiscNumber { get; set; } [Exportable] public virtual int DiscCount { get { return (disc_count != 0 && disc_count < DiscNumber) ? DiscNumber : disc_count; } set { disc_count = value; } } [Exportable] public virtual int Year { get; set; } [Exportable] public virtual string Composer { get; set; } [Exportable] public virtual string Conductor { get; set; } [Exportable] public virtual string Grouping { get; set; } [Exportable] public virtual string Copyright { get; set; } [Exportable] public virtual string LicenseUri { get; set; } [Exportable] public virtual string Comment { get; set; } [Exportable] public virtual int Rating { get; set; } [Exportable] public virtual int Score { get; set; } [Exportable] public virtual int Bpm { get; set; } [Exportable] public virtual int BitRate { get; set; } [Exportable] public virtual int SampleRate { get; set; } [Exportable] public virtual int BitsPerSample { get; set; } [Exportable] public virtual int PlayCount { get; set; } [Exportable] public virtual int SkipCount { get; set; } [Exportable (ExportName = "length")] public virtual TimeSpan Duration { get; set; } [Exportable] public virtual DateTime DateAdded { get; set; } [Exportable] public virtual DateTime LastPlayed { get; set; } [Exportable] public virtual DateTime LastSkipped { get; set; } public virtual StreamPlaybackError PlaybackError { get { return playback_error; } set { playback_error = value; } } public virtual string GetPlaybackErrorMessage () { switch (PlaybackError) { case StreamPlaybackError.None: return null; case StreamPlaybackError.ResourceNotFound: return IsLive ? Catalog.GetString ("Stream location not found") : Catalog.GetString ("File not found"); case StreamPlaybackError.CodecNotFound: return Catalog.GetString ("Codec for playing this media type not available"); case StreamPlaybackError.Drm: return Catalog.GetString ("File protected by Digital Rights Management (DRM)"); case StreamPlaybackError.Unknown: return Catalog.GetString ("Unknown error"); default: return null; } } public void SavePlaybackError (StreamPlaybackError value) { if (PlaybackError != value) { PlaybackError = value; Save (); } } private bool can_save_to_database = true; public bool CanSaveToDatabase { get { return can_save_to_database; } set { can_save_to_database = value; } } public bool IsLive { get; set; } private bool can_play = true; public bool CanPlay { get { return can_play; } set { can_play = value; } } private bool enabled = true; public bool Enabled { get { return enabled && can_play; } set { enabled = value; } } public virtual string MetadataHash { get { System.Text.StringBuilder sb = new System.Text.StringBuilder (); // Keep this field set/order in sync with UpdateMetadataHash in DatabaseTrackInfo.cs sb.Append (AlbumTitle); sb.Append (ArtistName); sb.Append (Genre); sb.Append (TrackTitle); sb.Append (TrackNumber); sb.Append (Year); return Hyena.CryptoUtil.Md5Encode (sb.ToString (), System.Text.Encoding.UTF8); } } private TrackMediaAttributes media_attributes = TrackMediaAttributes.Default; [Exportable] public virtual TrackMediaAttributes MediaAttributes { get { return media_attributes; } set { media_attributes = value; } } public bool HasAttribute (TrackMediaAttributes attr) { return (MediaAttributes & attr) != 0; } protected void SetAttributeIf (bool condition, TrackMediaAttributes attr) { if (condition) { MediaAttributes |= attr; } } // TODO turn this into a PrimarySource-owned delegate? private static readonly string restart_podcast = Catalog.GetString ("_Restart Podcast"); private static readonly string restart_audiobook = Catalog.GetString ("_Restart Audiobook"); private static readonly string restart_video = Catalog.GetString ("_Restart Video"); private static readonly string restart_song = Catalog.GetString ("_Restart Song"); private static readonly string restart_item = Catalog.GetString ("_Restart Item"); public string RestartLabel { get { if (HasAttribute (TrackMediaAttributes.Podcast)) return restart_podcast; if (HasAttribute (TrackMediaAttributes.AudioBook)) return restart_audiobook; if (HasAttribute (TrackMediaAttributes.VideoStream)) return restart_video; if (HasAttribute (TrackMediaAttributes.Music)) return restart_song; return restart_item; } } private static readonly string jump_to_podcast = Catalog.GetString ("_Jump to Playing Podcast"); private static readonly string jump_to_audiobook = Catalog.GetString ("_Jump to Playing Audiobook"); private static readonly string jump_to_video = Catalog.GetString ("_Jump to Playing Video"); private static readonly string jump_to_song = Catalog.GetString ("_Jump to Playing Song"); private static readonly string jump_to_item = Catalog.GetString ("_Jump to Playing Item"); public string JumpToLabel { get { if (HasAttribute (TrackMediaAttributes.Podcast)) return jump_to_podcast; if (HasAttribute (TrackMediaAttributes.AudioBook)) return jump_to_audiobook; if (HasAttribute (TrackMediaAttributes.VideoStream)) return jump_to_video; if (HasAttribute (TrackMediaAttributes.Music)) return jump_to_song; return jump_to_item; } } #region Exportable Properties public static void ExportableMerge (TrackInfo source, TrackInfo dest) { // Use the high level TrackInfo type if the source and dest types differ Type type = dest.GetType (); if (source.GetType () != type) { type = typeof (TrackInfo); } foreach (KeyValuePair<string, PropertyInfo> iter in GetExportableProperties (type)) { try { PropertyInfo property = iter.Value; if (property.CanWrite && property.CanRead) { property.SetValue (dest, property.GetValue (source, null), null); } } catch (Exception e) { Log.Exception (e); } } } public static IEnumerable<KeyValuePair<string, PropertyInfo>> GetExportableProperties (Type type) { FindExportableProperties (type); Dictionary<string, PropertyInfo> properties = null; if (exportable_properties.TryGetValue (type, out properties)) { foreach (KeyValuePair<string, PropertyInfo> property in properties) { yield return property; } } } public IDictionary<string, object> GenerateExportable () { return GenerateExportable (null); } public IDictionary<string, object> GenerateExportable (string [] fields) { Dictionary<string, object> dict = new Dictionary<string, object> (); foreach (KeyValuePair<string, PropertyInfo> property in GetExportableProperties (GetType ())) { if (fields != null) { bool found = false; foreach (string field in fields) { if (field == property.Key) { found = true; break; } } if (!found) { continue; } } object value = property.Value.GetValue (this, null); if (value == null) { continue; } if (value is TimeSpan) { value = ((TimeSpan)value).TotalSeconds; } else if (value is DateTime) { DateTime date = (DateTime)value; value = date == DateTime.MinValue ? 0L : DateTimeUtil.ToTimeT (date); } else if (value is SafeUri) { value = ((SafeUri)value).AbsoluteUri; } else if (value is TrackMediaAttributes) { value = value.ToString (); } else if (!(value.GetType ().IsPrimitive || value is string)) { Log.WarningFormat ("Invalid property in {0} marked as [Exportable]: ({1} is a {2})", property.Value.DeclaringType, property.Value.Name, value.GetType ()); continue; } // A bit lame if (!(value is string)) { string str_value = value.ToString (); if (str_value == "0" || str_value == "0.0") { continue; } } dict.Add (property.Key, value); } return dict; } private static Dictionary<Type, Dictionary<string, PropertyInfo>> exportable_properties; private static object exportable_properties_mutex = new object (); private static void FindExportableProperties (Type type) { lock (exportable_properties_mutex) { if (exportable_properties == null) { exportable_properties = new Dictionary<Type, Dictionary<string, PropertyInfo>> (); } else if (exportable_properties.ContainsKey (type)) { return; } // Build a stack of types to reflect Stack<Type> probe_types = new Stack<Type> (); Type probe_type = type; bool is_track_info = false; while (probe_type != null) { probe_types.Push (probe_type); if (probe_type == typeof (TrackInfo)) { is_track_info = true; break; } probe_type = probe_type.BaseType; } if (!is_track_info) { throw new ArgumentException ("Type must derive from Banshee.Collection.TrackInfo", "type"); } // Iterate through all types while (probe_types.Count > 0) { probe_type = probe_types.Pop (); if (exportable_properties.ContainsKey (probe_type)) { continue; } Dictionary<string, PropertyInfo> properties = null; // Reflect the type for exportable properties foreach (PropertyInfo property in probe_type.GetProperties (BindingFlags.Public | BindingFlags.Instance)) { if (property.DeclaringType != probe_type) { continue; } object [] exportable_attrs = property.GetCustomAttributes (typeof (ExportableAttribute), true); if (exportable_attrs == null || exportable_attrs.Length == 0) { continue; } string export_name = ((ExportableAttribute)exportable_attrs[0]).ExportName ?? StringUtil.CamelCaseToUnderCase (property.Name, '-'); if (String.IsNullOrEmpty (export_name) || (properties != null && properties.ContainsKey (export_name))) { continue; } if (properties == null) { properties = new Dictionary<string, PropertyInfo> (); exportable_properties.Add (probe_type, properties); } properties.Add (export_name, property); } // Merge properties in the type hierarchy through linking or aggregation Type parent_type = probe_type.BaseType; bool link = !exportable_properties.ContainsKey (probe_type); while (parent_type != null) { Dictionary<string, PropertyInfo> parent_properties = null; if (!exportable_properties.TryGetValue (parent_type, out parent_properties)) { parent_type = parent_type.BaseType; continue; } if (link) { // Link entire property set between types exportable_properties.Add (probe_type, parent_properties); return; } else { // Aggregate properties in parent sets foreach (KeyValuePair<string, PropertyInfo> parent_property in parent_properties) { properties.Add (parent_property.Key, parent_property.Value); } } parent_type = parent_type.BaseType; } } } } #endregion } }
using System; using System.Runtime.InteropServices; using System.Security; using ShellUtil; namespace SFML { namespace Graphics { //////////////////////////////////////////////////////////// /// <summary> /// This class defines a view (position, size, etc.) ; /// you can consider it as a 2D camera /// </summary> //////////////////////////////////////////////////////////// public class View : ObjectBase { //////////////////////////////////////////////////////////// private bool myExternal = false; #region Imports [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr sfView_create(); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr sfView_createFromRect(FloatRect Rect); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr sfView_copy(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern void sfView_destroy(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern void sfView_setCenter(IntPtr View, Vector2 center); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern void sfView_setSize(IntPtr View, Vector2 size); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern void sfView_setRotation(IntPtr View, float Angle); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern void sfView_setViewport(IntPtr View, FloatRect Viewport); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern void sfView_reset(IntPtr View, FloatRect Rectangle); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern Vector2 sfView_getCenter(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern Vector2 sfView_getSize(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern float sfView_getRotation(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern FloatRect sfView_getViewport(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern void sfView_move(IntPtr View, Vector2 offset); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern void sfView_rotate(IntPtr View, float Angle); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)] [SuppressUnmanagedCodeSecurity] private static extern void sfView_zoom(IntPtr View, float Factor); #endregion /// <summary> /// Create a default view (1000x1000) /// </summary> //////////////////////////////////////////////////////////// public View() : base(sfView_create()) {} //////////////////////////////////////////////////////////// /// <summary> /// Construct the view from a rectangle /// </summary> /// <param name="viewRect">Rectangle defining the position and size of the view</param> //////////////////////////////////////////////////////////// public View(FloatRect viewRect) : base(sfView_createFromRect(viewRect)) {} //////////////////////////////////////////////////////////// /// <summary> /// Construct the view from its center and size /// </summary> /// <param name="center">Center of the view</param> /// <param name="size">Size of the view</param> //////////////////////////////////////////////////////////// public View(Vector2 center, Vector2 size) : base(sfView_create()) { Center = center; Size = size; } //////////////////////////////////////////////////////////// /// <summary> /// Construct the view from another view /// </summary> /// <param name="copy">View to copy</param> //////////////////////////////////////////////////////////// public View(View copy) : base(sfView_copy(copy.CPointer)) {} /// <summary> /// Internal constructor for other classes which need to manipulate raw views /// </summary> /// <param name="cPointer">Direct pointer to the view object in the C library</param> //////////////////////////////////////////////////////////// internal View(IntPtr cPointer) : base(cPointer) { this.myExternal = true; } //////////////////////////////////////////////////////////// /// <summary> /// Center of the view /// </summary> //////////////////////////////////////////////////////////// public Vector2 Center { get { return sfView_getCenter(CPointer); } set { sfView_setCenter(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Half-size of the view /// </summary> //////////////////////////////////////////////////////////// public Vector2 Size { get { return sfView_getSize(CPointer); } set { sfView_setSize(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Rotation of the view, in degrees /// </summary> //////////////////////////////////////////////////////////// public float Rotation { get { return sfView_getRotation(CPointer); } set { sfView_setRotation(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Target viewport of the view, defined as a factor of the /// size of the target to which the view is applied /// </summary> //////////////////////////////////////////////////////////// public FloatRect Viewport { get { return sfView_getViewport(CPointer); } set { sfView_setViewport(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Rebuild the view from a rectangle /// </summary> /// <param name="rectangle">Rectangle defining the position and size of the view</param> //////////////////////////////////////////////////////////// public void Reset(FloatRect rectangle) { sfView_reset(CPointer, rectangle); } //////////////////////////////////////////////////////////// /// <summary> /// Move the view /// </summary> /// <param name="offset">Offset to move the view</param> //////////////////////////////////////////////////////////// public void Move(Vector2 offset) { sfView_move(CPointer, offset); } //////////////////////////////////////////////////////////// /// <summary> /// Rotate the view /// </summary> /// <param name="angle">Angle of rotation, in degrees</param> //////////////////////////////////////////////////////////// public void Rotate(float angle) { sfView_rotate(CPointer, angle); } //////////////////////////////////////////////////////////// /// <summary> /// Resize the view rectangle to simulate a zoom / unzoom effect /// </summary> /// <param name="factor">Zoom factor to apply, relative to the current zoom</param> //////////////////////////////////////////////////////////// public void Zoom(float factor) { sfView_zoom(CPointer, factor); } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[View]" + " Center(" + Center + ")" + " Size(" + Size + ")" + " Rotation(" + Rotation + ")" + " Viewport(" + Viewport + ")"; } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// <summary> /// Handle the destruction of the object /// </summary> /// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param> //////////////////////////////////////////////////////////// protected override void Destroy(bool disposing) { if (!this.myExternal) { sfView_destroy(CPointer); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { public partial class Process : IDisposable { private bool _haveMainWindow; private IntPtr _mainWindowHandle; private string _mainWindowTitle; private bool _haveResponding; private bool _responding; private bool StartCore(ProcessStartInfo startInfo) { return startInfo.UseShellExecute ? StartWithShellExecuteEx(startInfo) : StartWithCreateProcess(startInfo); } private unsafe bool StartWithShellExecuteEx(ProcessStartInfo startInfo) { if (!string.IsNullOrEmpty(startInfo.UserName) || startInfo.Password != null) throw new InvalidOperationException(SR.CantStartAsUser); if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) throw new InvalidOperationException(SR.CantRedirectStreams); if (startInfo.StandardInputEncoding != null) throw new InvalidOperationException(SR.StandardInputEncodingNotAllowed); if (startInfo.StandardErrorEncoding != null) throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed); if (startInfo.StandardOutputEncoding != null) throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed); if (startInfo._environmentVariables != null) throw new InvalidOperationException(SR.CantUseEnvVars); fixed (char* fileName = startInfo.FileName.Length > 0 ? startInfo.FileName : null) fixed (char* verb = startInfo.Verb.Length > 0 ? startInfo.Verb : null) fixed (char* parameters = startInfo.Arguments.Length > 0 ? startInfo.Arguments : null) fixed (char* directory = startInfo.WorkingDirectory.Length > 0 ? startInfo.WorkingDirectory : null) { Interop.Shell32.SHELLEXECUTEINFO shellExecuteInfo = new Interop.Shell32.SHELLEXECUTEINFO() { cbSize = (uint)sizeof(Interop.Shell32.SHELLEXECUTEINFO), lpFile = fileName, lpVerb = verb, lpParameters = parameters, lpDirectory = directory, fMask = Interop.Shell32.SEE_MASK_NOCLOSEPROCESS | Interop.Shell32.SEE_MASK_FLAG_DDEWAIT }; if (startInfo.ErrorDialog) shellExecuteInfo.hwnd = startInfo.ErrorDialogParentHandle; else shellExecuteInfo.fMask |= Interop.Shell32.SEE_MASK_FLAG_NO_UI; switch (startInfo.WindowStyle) { case ProcessWindowStyle.Hidden: shellExecuteInfo.nShow = Interop.Shell32.SW_HIDE; break; case ProcessWindowStyle.Minimized: shellExecuteInfo.nShow = Interop.Shell32.SW_SHOWMINIMIZED; break; case ProcessWindowStyle.Maximized: shellExecuteInfo.nShow = Interop.Shell32.SW_SHOWMAXIMIZED; break; default: shellExecuteInfo.nShow = Interop.Shell32.SW_SHOWNORMAL; break; } ShellExecuteHelper executeHelper = new ShellExecuteHelper(&shellExecuteInfo); if (!executeHelper.ShellExecuteOnSTAThread()) { int error = executeHelper.ErrorCode; if (error == 0) { error = GetShellError(shellExecuteInfo.hInstApp); } switch (error) { case Interop.Errors.ERROR_BAD_EXE_FORMAT: case Interop.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH: throw new Win32Exception(error, SR.InvalidApplication); case Interop.Errors.ERROR_CALL_NOT_IMPLEMENTED: // This happens on Windows Nano throw new PlatformNotSupportedException(SR.UseShellExecuteNotSupported); default: throw new Win32Exception(error); } } if (shellExecuteInfo.hProcess != IntPtr.Zero) { SetProcessHandle(new SafeProcessHandle(shellExecuteInfo.hProcess)); return true; } } return false; } private int GetShellError(IntPtr error) { switch ((long)error) { case Interop.Shell32.SE_ERR_FNF: return Interop.Errors.ERROR_FILE_NOT_FOUND; case Interop.Shell32.SE_ERR_PNF: return Interop.Errors.ERROR_PATH_NOT_FOUND; case Interop.Shell32.SE_ERR_ACCESSDENIED: return Interop.Errors.ERROR_ACCESS_DENIED; case Interop.Shell32.SE_ERR_OOM: return Interop.Errors.ERROR_NOT_ENOUGH_MEMORY; case Interop.Shell32.SE_ERR_DDEFAIL: case Interop.Shell32.SE_ERR_DDEBUSY: case Interop.Shell32.SE_ERR_DDETIMEOUT: return Interop.Errors.ERROR_DDE_FAIL; case Interop.Shell32.SE_ERR_SHARE: return Interop.Errors.ERROR_SHARING_VIOLATION; case Interop.Shell32.SE_ERR_NOASSOC: return Interop.Errors.ERROR_NO_ASSOCIATION; case Interop.Shell32.SE_ERR_DLLNOTFOUND: return Interop.Errors.ERROR_DLL_NOT_FOUND; default: return (int)(long)error; } } internal unsafe class ShellExecuteHelper { private Interop.Shell32.SHELLEXECUTEINFO* _executeInfo; private bool _succeeded; private bool _notpresent; public ShellExecuteHelper(Interop.Shell32.SHELLEXECUTEINFO* executeInfo) { _executeInfo = executeInfo; } private void ShellExecuteFunction() { try { if (!(_succeeded = Interop.Shell32.ShellExecuteExW(_executeInfo))) ErrorCode = Marshal.GetLastWin32Error(); } catch (EntryPointNotFoundException) { _notpresent = true; } } public bool ShellExecuteOnSTAThread() { // ShellExecute() requires STA in order to work correctly. if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { ThreadStart threadStart = new ThreadStart(ShellExecuteFunction); Thread executionThread = new Thread(threadStart); executionThread.SetApartmentState(ApartmentState.STA); executionThread.Start(); executionThread.Join(); } else { ShellExecuteFunction(); } if (_notpresent) throw new PlatformNotSupportedException(SR.UseShellExecuteNotSupported); return _succeeded; } public int ErrorCode { get; private set; } } private string GetMainWindowTitle() { IntPtr handle = MainWindowHandle; if (handle == IntPtr.Zero) return string.Empty; int length = Interop.User32.GetWindowTextLengthW(handle); if (length == 0) { #if DEBUG // We never used to throw here, want to surface possible mistakes on our part int error = Marshal.GetLastWin32Error(); Debug.Assert(error == 0, $"Failed GetWindowTextLengthW(): { new Win32Exception(error).Message }"); #endif return string.Empty; } StringBuilder builder = new StringBuilder(length); length = Interop.User32.GetWindowTextW(handle, builder, builder.Capacity + 1); #if DEBUG if (length == 0) { // We never used to throw here, want to surface possible mistakes on our part int error = Marshal.GetLastWin32Error(); Debug.Assert(error == 0, $"Failed GetWindowTextW(): { new Win32Exception(error).Message }"); } #endif builder.Length = length; return builder.ToString(); } public IntPtr MainWindowHandle { get { if (!_haveMainWindow) { EnsureState(State.IsLocal | State.HaveId); _mainWindowHandle = ProcessManager.GetMainWindowHandle(_processId); _haveMainWindow = true; } return _mainWindowHandle; } } private bool CloseMainWindowCore() { const int GWL_STYLE = -16; // Retrieves the window styles. const int WS_DISABLED = 0x08000000; // WindowStyle disabled. A disabled window cannot receive input from the user. const int WM_CLOSE = 0x0010; // WindowMessage close. IntPtr mainWindowHandle = MainWindowHandle; if (mainWindowHandle == (IntPtr)0) { return false; } int style = Interop.User32.GetWindowLong(mainWindowHandle, GWL_STYLE); if ((style & WS_DISABLED) != 0) { return false; } Interop.User32.PostMessage(mainWindowHandle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); return true; } public string MainWindowTitle { get { if (_mainWindowTitle == null) { _mainWindowTitle = GetMainWindowTitle(); } return _mainWindowTitle; } } private bool IsRespondingCore() { const int WM_NULL = 0x0000; const int SMTO_ABORTIFHUNG = 0x0002; IntPtr mainWindow = MainWindowHandle; if (mainWindow == (IntPtr)0) { return true; } IntPtr result; return Interop.User32.SendMessageTimeout(mainWindow, WM_NULL, IntPtr.Zero, IntPtr.Zero, SMTO_ABORTIFHUNG, 5000, out result) != (IntPtr)0; } public bool Responding { get { if (!_haveResponding) { _responding = IsRespondingCore(); _haveResponding = true; } return _responding; } } private bool WaitForInputIdleCore(int milliseconds) { const int WAIT_OBJECT_0 = 0x00000000; const int WAIT_FAILED = unchecked((int)0xFFFFFFFF); const int WAIT_TIMEOUT = 0x00000102; bool idle; using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.SYNCHRONIZE | Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { int ret = Interop.User32.WaitForInputIdle(handle, milliseconds); switch (ret) { case WAIT_OBJECT_0: idle = true; break; case WAIT_TIMEOUT: idle = false; break; case WAIT_FAILED: default: throw new InvalidOperationException(SR.InputIdleUnkownError); } } return idle; } } }
using System; using System.Collections.Generic; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Threading; using System.Globalization; using System.Collections; using Cuyahoga.Core; using Cuyahoga.Core.Domain; using Cuyahoga.Core.Service.SiteStructure; using Cuyahoga.Web.Util; using Cuyahoga.Web.Components; namespace Cuyahoga.Web.UI { /// <summary> /// Page engine. This class loads all content based on url parameters and merges /// the content with the template. /// </summary> public class PageEngine : CuyahogaPage { private Site _currentSite; private Node _rootNode; private Node _activeNode; private Section _activeSection; private BaseTemplate _templateControl; private bool _shouldLoadContent; private IDictionary<string, string> _stylesheets = new Dictionary<string, string>(); private IDictionary<string, string> _javaScripts = new Dictionary<string, string>(); private IDictionary<string, string> _metaTags = new Dictionary<string, string>(); private ModuleLoader _moduleLoader; private INodeService _nodeService; private ISiteService _siteService; private ISectionService _sectionService; #region properties /// <summary> /// Flag to indicate if the engine should load content (Templates, Nodes and Sections). /// </summary> protected bool ShouldLoadContent { set { this._shouldLoadContent = value; } } /// <summary> /// Property RootNode (Node) /// </summary> public Node RootNode { get { return this._rootNode; } } /// <summary> /// Property ActiveNode (Node) /// </summary> public Node ActiveNode { get { return this._activeNode; } } /// <summary> /// Property ActiveSection (Section) /// </summary> public Section ActiveSection { get { return this._activeSection; } } /// <summary> /// Property TemplateControl (BaseTemplate) /// </summary> public BaseTemplate TemplateControl { get { return this._templateControl; } set { this._templateControl = value; } } /// <summary> /// /// </summary> public User CuyahogaUser { get { return this.User.Identity as User; } } /// <summary> /// /// </summary> public Site CurrentSite { get { return this._currentSite; } } #endregion /// <summary> /// Default constructor. /// </summary> public PageEngine() { this._activeNode = null; this._activeSection = null; this._templateControl = null; this._shouldLoadContent = true; // Get services from the container. Ideally, it should be possible to register the aspx page in the container // to automatically resolve dependencies but there were memory issues with registering pages in the container. this._moduleLoader = Container.Resolve<ModuleLoader>(); this._nodeService = Container.Resolve<INodeService>(); this._siteService = Container.Resolve<ISiteService>(); this._sectionService = Container.Resolve<ISectionService>(); } /// <summary> /// Register stylesheets. /// </summary> /// <param name="key">The unique key for the stylesheet. Note that Cuyahoga already uses 'maincss' as key.</param> /// <param name="absoluteCssPath">The path to the css file from the application root (starting with /).</param> public void RegisterStylesheet(string key, string absoluteCssPath) { if (! this._stylesheets.ContainsKey(key)) { this._stylesheets.Add(key, absoluteCssPath); } } /// <summary> /// Register javascripts. /// </summary> /// <param name="key"></param> /// <param name="absoluteJavaScriptPath"></param> public void RegisterJavaScript(string key, string absoluteJavaScriptPath) { if (! this._javaScripts.ContainsKey(key)) { this._javaScripts.Add(key, absoluteJavaScriptPath); } } /// <summary> /// Register a meta tag. The values can be overriden. /// </summary> /// <param name="name"></param> /// <param name="content"></param> public void RegisterMetaTag(string name, string content) { if (!string.IsNullOrEmpty(content)) { this._metaTags[name] = content; } } /// <summary> /// Load the content and the template as early as possible, so everything is in place before /// modules handle their own ASP.NET lifecycle events. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param> protected override void OnInit(EventArgs e) { // Load the current site Node entryNode = null; string siteUrl = UrlHelper.GetSiteUrl(); SiteAlias currentSiteAlias = this._siteService.GetSiteAliasByUrl(siteUrl); if (currentSiteAlias != null) { this._currentSite = currentSiteAlias.Site; entryNode = currentSiteAlias.EntryNode; } else { this._currentSite = this._siteService.GetSiteBySiteUrl(siteUrl); } if (this._currentSite == null) { throw new SiteNullException("No site found at " + siteUrl); } // Load the active node // Query the cache by SectionId, ShortDescription and NodeId. if (Context.Request.QueryString["SectionId"] != null) { try { this._activeSection = this._sectionService.GetSectionById(Int32.Parse(Context.Request.QueryString["SectionId"])); this._activeNode = this._activeSection.Node; } catch { throw new SectionNullException("Section not found: " + Context.Request.QueryString["SectionId"]); } } else if (Context.Request.QueryString["ShortDescription"] != null) { this._activeNode = this._nodeService.GetNodeByShortDescriptionAndSite(Context.Request.QueryString["ShortDescription"], this._currentSite); } else if (Context.Request.QueryString["NodeId"] != null) { this._activeNode = this._nodeService.GetNodeById(Int32.Parse(Context.Request.QueryString["NodeId"])); } else if (entryNode != null) { this._activeNode = entryNode; } else { // Can't load a particular node, so the root node has to be the active node // Maybe we have culture information stored in a cookie, so we might need a different // root Node. string currentCulture = this._currentSite.DefaultCulture; if (Context.Request.Cookies["CuyahogaCulture"] != null) { currentCulture = Context.Request.Cookies["CuyahogaCulture"].Value; } this._activeNode = this._nodeService.GetRootNodeByCultureAndSite(currentCulture, this._currentSite); } // Raise an exception when there is no Node found. It will be handled by the global error handler // and translated into a proper 404. if (this._activeNode == null) { throw new NodeNullException(String.Format(@"No node found with the following parameters: NodeId: {0}, ShortDescription: {1}, SectionId: {2}" , Context.Request.QueryString["NodeId"] , Context.Request.QueryString["ShortDescription"] , Context.Request.QueryString["SectionId"])); } this._rootNode = this._activeNode.NodePath[0]; // Set culture // TODO: fix this because ASP.NET pages are not guaranteed to run in 1 thread (how?). Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(this._activeNode.Culture); Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(this._activeNode.Culture); // Check node-level security if (! this._activeNode.ViewAllowed(this.User.Identity)) { throw new AccessForbiddenException("You are not allowed to view this page."); } // Check if the active node is a link. If so, redirect to the link if (this._activeNode.IsExternalLink) { Response.Redirect(this._activeNode.LinkUrl); } else { if (this._shouldLoadContent) { LoadContent(); LoadMenus(); } } base.OnInit(e); } /// <summary> /// Use a custom HtmlTextWriter to render the page if the url is rewritten, to correct the form action. /// </summary> /// <param name="writer"></param> protected override void Render(System.Web.UI.HtmlTextWriter writer) { InsertStylesheets(); InsertJavaScripts(); InsertMetaTags(); if (Context.Items["VirtualUrl"] != null) { writer = new FormFixerHtmlTextWriter(writer.InnerWriter, "", Context.Items["VirtualUrl"].ToString()); } base.Render (writer); } private void LoadContent() { // PageEngine page = ( PageEngine ) Page; bool isAdmin = ( ( page.CuyahogaUser != null && page.CuyahogaUser.HasPermission( AccessLevel.Administrator ) ) ); // # added for v1.6.0 if ( ActiveNode.Site.OfflineTemplate != null) // check if an Offline template was selected { // check if any parent is offline if (_activeNode.Level >= 1 && !isAdmin) // from the 2nd level { if (IsAnyParentOffline(_activeNode, 1)) { _activeNode.Template = _currentSite.OfflineTemplate; ActiveNode.Status = (int) NodeStatus.Offline; // lo mettiamo off-line } } } // # added for v1.6.0 // ===== Load templates ===== string appRoot = UrlHelper.GetApplicationPath(); // We know the active node so the template can be loaded. if (this._activeNode.Template != null) { string templatePath = appRoot + this._activeNode.Template.Path; this._templateControl = (BaseTemplate)this.LoadControl(templatePath); // Explicitly set the id to 'p' to save some bytes (otherwise _ctl0 would be added). this._templateControl.ID = "p"; this._templateControl.Title = this._activeNode.Site.Name + " - " + this._activeNode.Title; // Register stylesheet that belongs to the template. RegisterStylesheet("maincss", appRoot + this._activeNode.Template.BasePath + "/Css/" + this._activeNode.Template.Css); //Register the metatags if (ActiveNode.MetaKeywords != null) { RegisterMetaTag("keywords", ActiveNode.MetaKeywords); } else { RegisterMetaTag("keywords", ActiveNode.Site.MetaKeywords); } if (ActiveNode.MetaDescription != null) { RegisterMetaTag("description", ActiveNode.MetaDescription); } else { RegisterMetaTag("description", ActiveNode.Site.MetaDescription); } // # added for v1.6.0 if( ActiveNode.Status == ( int ) NodeStatus.Online || (ActiveNode.Status == ( int ) NodeStatus.Offline && isAdmin) ) { // # added for v1.6.0 // Load sections that are related to the template foreach (DictionaryEntry sectionEntry in this.ActiveNode.Template.Sections) { string placeholder = sectionEntry.Key.ToString(); Section section = sectionEntry.Value as Section; if (section != null) { BaseModuleControl moduleControl = CreateModuleControlForSection(section); if (moduleControl != null) { ((PlaceHolder)this._templateControl.Containers[placeholder]).Controls.Add(moduleControl); } } } // # added for v1.6.0 } // # added for v1.6.0 } else { throw new Exception("No template associated with the current Node."); } // # added for v1.6.0 if( ActiveNode.Status == ( int ) NodeStatus.Online || ( ActiveNode.Status == ( int ) NodeStatus.Offline && isAdmin ) ) { // # added for v1.6.0 // ===== Load sections and modules ===== foreach (Section section in this._activeNode.Sections) { BaseModuleControl moduleControl = CreateModuleControlForSection(section); if (moduleControl != null) { ((PlaceHolder) this._templateControl.Containers[section.PlaceholderId]).Controls.Add( moduleControl); } } // # added for v1.6.0 } // # added for v1.6.0 this.Controls.AddAt(0, this._templateControl); // remove html that was in the original page (Default.aspx) for (int i = this.Controls.Count -1; i < 0; i --) this.Controls.RemoveAt(i); } /// <summary> /// Determines whether [is any parent offline] [the specified node]. /// </summary> /// <param name="node">The node.</param> /// <param name="minLevel">The min level.</param> /// <returns> /// <c>true</c> if [is any parent offline] [the specified node]; otherwise, <c>false</c>. /// </returns> private bool IsAnyParentOffline( Node node, int minLevel ) { if( node.ParentNode == null || node.ParentNode.Level < minLevel ) return (node.Status == (int)NodeStatus.Offline); //false; if( (node.ParentNode.Status == (int)NodeStatus.Offline) && node.ParentNode.Level >= minLevel ) { return true; } return IsAnyParentOffline( node.ParentNode, minLevel ); } private BaseModuleControl CreateModuleControlForSection(Section section) { // Check view permissions before adding the section to the page. if (section.ViewAllowed(this.User.Identity)) { // Create the module that is connected to the section. ModuleBase module = this._moduleLoader.GetModuleFromSection(section); //this._moduleLoader.NHibernateModuleAdded -= new EventHandler(ModuleLoader_ModuleAdded); if (module != null) { if (Context.Request.PathInfo.Length > 0 && section == this._activeSection) { // Parse the PathInfo of the request because they can be the parameters // for the module that is connected to the active section. module.ModulePathInfo = Context.Request.PathInfo; } return LoadModuleControl(module); } } return null; } private BaseModuleControl LoadModuleControl(ModuleBase module) { BaseModuleControl ctrl = (BaseModuleControl)this.LoadControl(UrlHelper.GetApplicationPath() + module.CurrentViewControlPath); ctrl.Module = module; return ctrl; } private void LoadMenus() { IList menus = this._nodeService.GetMenusByRootNode(this._rootNode); foreach (CustomMenu menu in menus) { PlaceHolder plc = this._templateControl.Containers[menu.Placeholder] as PlaceHolder; if (plc != null) { // rabol: [#CUY-57] fix. Control menuControlList = GetMenuControls(menu); if(menuControlList != null) { plc.Controls.Add(menuControlList); } } } } private Control GetMenuControls(CustomMenu menu) { if (menu.Nodes.Count > 0) { // The menu is just a simple <ul> list. HtmlGenericControl listControl = new HtmlGenericControl("ul"); foreach (Node node in menu.Nodes) { if (node.ViewAllowed(this.CuyahogaUser)) { HtmlGenericControl listItem = new HtmlGenericControl("li"); HyperLink hpl = new HyperLink(); hpl.NavigateUrl = UrlHelper.GetUrlFromNode(node); UrlHelper.SetHyperLinkTarget(hpl, node); hpl.Text = node.Title; listItem.Controls.Add(hpl); listControl.Controls.Add(listItem); if (node.Id == this.ActiveNode.Id) { hpl.CssClass = "selected"; } } } return listControl; } else { return null; } } private void InsertStylesheets() { List<string> stylesheetLinks = new List<string>(this._stylesheets.Values); this.TemplateControl.RenderCssLinks(stylesheetLinks.ToArray()); } private void InsertJavaScripts() { List<string> javaScriptLinks = new List<string>(this._javaScripts.Values); this.TemplateControl.RenderJavaScriptLinks(javaScriptLinks.ToArray()); } private void InsertMetaTags() { this.TemplateControl.RenderMetaTags((IDictionary) this._metaTags); } } }
// The MIT License (MIT) // Copyright 2015 Siney/Pangweiwei [email protected] // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace SLua { using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System; using System.Reflection; using UnityEditor; using LuaInterface; using System.Text; using System.Text.RegularExpressions; public class LuaCodeGen : MonoBehaviour { public const string Path = "Assets/Slua/LuaObject/"; public delegate void ExportGenericDelegate(Type t, string ns); static bool autoRefresh = true; static bool IsCompiling { get { if (EditorApplication.isCompiling) { Debug.Log("Unity Editor is compiling, please wait."); } return EditorApplication.isCompiling; } } [InitializeOnLoad] public class Startup { static Startup() { bool ok = System.IO.Directory.Exists(Path); if (!ok && EditorUtility.DisplayDialog("Slua", "Not found lua interface for Unity, generate it now?", "Generate", "No")) { GenerateAll(); } } } [MenuItem("SLua/All/Make")] static public void GenerateAll() { autoRefresh = false; Generate(); GenerateUI(); Custom(); Generate3rdDll(); autoRefresh = true; AssetDatabase.Refresh(); } [MenuItem("SLua/Unity/Make UnityEngine")] static public void Generate() { if (IsCompiling) { return; } Assembly assembly = Assembly.Load("UnityEngine"); Type[] types = assembly.GetExportedTypes(); List<string> uselist; List<string> noUseList; CustomExport.OnGetNoUseList(out noUseList); CustomExport.OnGetUseList(out uselist); List<Type> exports = new List<Type>(); string path = Path + "Unity/"; foreach (Type t in types) { bool export = true; // check type in uselist if (uselist != null && uselist.Count > 0) { export = false; foreach (string str in uselist) { if (t.FullName == str) { export = true; break; } } } else { // check type not in nouselist foreach (string str in noUseList) { if (t.FullName.Contains(str)) { export = false; break; } } } if (export) { if (Generate(t,path)) exports.Add(t); } } GenerateBind(exports, "BindUnity", 0,path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate engine interface finished"); } [MenuItem("SLua/Unity/Make UI (for Unity4.6+)")] static public void GenerateUI() { if (IsCompiling) { return; } List<string> noUseList = new List<string> { "CoroutineTween", "GraphicRebuildTracker", }; Assembly assembly = Assembly.Load("UnityEngine.UI"); Type[] types = assembly.GetExportedTypes(); List<Type> exports = new List<Type>(); string path = Path + "Unity/"; foreach (Type t in types) { bool export = true; foreach (string str in noUseList) { if (t.FullName.Contains(str)) export = false; } if (export) { if (Generate(t, path)) exports.Add(t); } } GenerateBind(exports, "BindUnityUI", 1,path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate UI interface finished"); } [MenuItem("SLua/Unity/Clear Uinty UI")] static public void ClearUnity() { clear(new string[] { Path + "Unity" }); Debug.Log("Clear Unity & UI complete."); } static public bool IsObsolete(MemberInfo t) { return t.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length > 0; } [MenuItem("SLua/Custom/Make")] static public void Custom() { if (IsCompiling) { return; } List<Type> exports = new List<Type>(); string path = Path + "Custom/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } ExportGenericDelegate fun = (Type t, string ns) => { if (Generate(t, ns, path)) exports.Add(t); }; // export self-dll Assembly assembly = Assembly.Load("Assembly-CSharp"); Type[] types = assembly.GetExportedTypes(); foreach (Type t in types) { if (t.GetCustomAttributes(typeof(CustomLuaClassAttribute), false).Length > 0) { fun(t, null); } } CustomExport.OnAddCustomClass(fun); GenerateBind(exports, "BindCustom", 3,path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate custom interface finished"); } [MenuItem("SLua/3rdDll/Make")] static public void Generate3rdDll() { if (IsCompiling) { return; } List<Type> cust = new List<Type>(); Assembly assembly = Assembly.Load("Assembly-CSharp"); Type[] types = assembly.GetExportedTypes(); List<string> assemblyList = new List<string>(); CustomExport.OnAddCustomAssembly(ref assemblyList); foreach (string assemblyItem in assemblyList) { assembly = Assembly.Load(assemblyItem); types = assembly.GetExportedTypes(); foreach (Type t in types) { cust.Add(t); } } if (cust.Count > 0) { List<Type> exports = new List<Type>(); string path = Path + "Dll/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } foreach (Type t in cust) { if (Generate(t,path)) exports.Add(t); } GenerateBind(exports, "BindDll", 2, path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate 3rdDll interface finished"); } } [MenuItem("SLua/3rdDll/Clear")] static public void Clear3rdDll() { clear(new string[] { Path + "Dll" }); Debug.Log("Clear AssemblyDll complete."); } [MenuItem("SLua/Custom/Clear")] static public void ClearCustom() { clear(new string[] { Path + "Custom" }); Debug.Log("Clear custom complete."); } [MenuItem("SLua/All/Clear")] static public void ClearALL() { clear(new string[] { Path.Substring(0, Path.Length - 1) }); Debug.Log("Clear all complete."); } static void clear(string[] paths) { try { foreach (string path in paths) { System.IO.Directory.Delete(path, true); } } catch { } AssetDatabase.Refresh(); } static bool Generate(Type t, string path) { return Generate(t, null, path); } static bool Generate(Type t, string ns, string path) { if (t.IsInterface) return false; CodeGenerator cg = new CodeGenerator(); cg.givenNamespace = ns; cg.path = path; return cg.Generate(t); } static void GenerateBind(List<Type> list, string name, int order,string path) { CodeGenerator cg = new CodeGenerator(); cg.path = path; cg.GenerateBind(list, name, order); } } class CodeGenerator { static List<string> memberFilter = new List<string> { "AnimationClip.averageDuration", "AnimationClip.averageAngularSpeed", "AnimationClip.averageSpeed", "AnimationClip.apparentSpeed", "AnimationClip.isLooping", "AnimationClip.isAnimatorMotion", "AnimationClip.isHumanMotion", "AnimatorOverrideController.PerformOverrideClipListCleanup", "Caching.SetNoBackupFlag", "Caching.ResetNoBackupFlag", "Light.areaSize", "Security.GetChainOfTrustValue", "Texture2D.alphaIsTransparency", "WWW.movie", "WebCamTexture.MarkNonReadable", "WebCamTexture.isReadable", // i don't why below 2 functions missed in iOS platform "Graphic.OnRebuildRequested", "Text.OnRebuildRequested", // il2cpp not exixts "Application.ExternalEval", "GameObject.networkView", "Component.networkView", // unity5 "AnimatorControllerParameter.name", "Input.IsJoystickPreconfigured", "Resources.LoadAssetAtPath", #if UNITY_4_6 "Motion.ValidateIfRetargetable", "Motion.averageDuration", "Motion.averageAngularSpeed", "Motion.averageSpeed", "Motion.apparentSpeed", "Motion.isLooping", "Motion.isAnimatorMotion", "Motion.isHumanMotion", #endif }; HashSet<string> funcname = new HashSet<string>(); Dictionary<string, bool> directfunc = new Dictionary<string, bool>(); public string givenNamespace; public string path; class PropPair { public string get = "null"; public string set = "null"; public bool isInstance = true; } Dictionary<string, PropPair> propname = new Dictionary<string, PropPair>(); int indent = 0; public void GenerateBind(List<Type> list, string name, int order) { HashSet<Type> exported = new HashSet<Type>(); string f = path + name + ".cs"; StreamWriter file = new StreamWriter(f, false, Encoding.UTF8); Write(file, "using System;"); Write(file, "namespace SLua {"); Write(file, "[LuaBinder({0})]", order); Write(file, "public class {0} {{", name); Write(file, "public static void Bind(IntPtr l) {"); foreach (Type t in list) { WriteBindType(file, t, list, exported); } Write(file, "}"); Write(file, "}"); Write(file, "}"); file.Close(); } void WriteBindType(StreamWriter file, Type t, List<Type> exported, HashSet<Type> binded) { if (t == null || binded.Contains(t) || !exported.Contains(t)) return; WriteBindType(file, t.BaseType, exported, binded); Write(file, "{0}.reg(l);", ExportName(t), binded); binded.Add(t); } public bool Generate(Type t) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!t.IsGenericTypeDefinition && (!IsObsolete(t) && t != typeof(YieldInstruction) && t != typeof(Coroutine)) || (t.BaseType != null && t.BaseType == typeof(System.MulticastDelegate))) { if (t.IsEnum) { StreamWriter file = Begin(t); WriteHead(t, file); RegEnumFunction(t, file); End(file); } else if (t.BaseType == typeof(System.MulticastDelegate)) { string f; if (t.IsGenericType) { if (t.ContainsGenericParameters) return false; f = path + string.Format("Lua{0}_{1}.cs", _Name(GenericBaseName(t)), _Name(GenericName(t))); } else { f = path + "LuaDelegate_" + _Name(t.FullName) + ".cs"; } StreamWriter file = new StreamWriter(f, false, Encoding.UTF8); WriteDelegate(t, file); file.Close(); return false; } else { funcname.Clear(); propname.Clear(); directfunc.Clear(); StreamWriter file = Begin(t); WriteHead(t, file); WriteConstructor(t, file); WriteFunction(t, file); WriteFunction(t, file, true); WriteField(t, file); RegFunction(t, file); End(file); if (t.BaseType != null && t.BaseType.Name == "UnityEvent`1") { string f = path + "LuaUnityEvent_" + _Name(GenericName(t.BaseType)) + ".cs"; file = new StreamWriter(f, false, Encoding.UTF8); WriteEvent(t, file); file.Close(); } } return true; } return false; } void WriteDelegate(Type t, StreamWriter file) { string temp = @" using System; using System.Collections.Generic; using LuaInterface; using UnityEngine; namespace SLua { public partial class LuaDelegation : LuaObject { static internal int checkDelegate(IntPtr l,int p,out $FN ua) { int op = extractFunction(l,p); if(LuaDLL.lua_isnil(l,p)) { ua=null; return op; } else if (LuaDLL.lua_isuserdata(l, p)==1) { ua = ($FN)checkObj(l, p); return op; } LuaDelegate ld; checkType(l, -1, out ld); if(ld.d!=null) { ua = ($FN)ld.d; return op; } LuaDLL.lua_pop(l,1); l = LuaState.get(l).L; ua = ($ARGS) => { int error = pushTry(l); "; temp = temp.Replace("$TN", t.Name); temp = temp.Replace("$FN", SimpleType(t)); MethodInfo mi = t.GetMethod("Invoke"); List<int> outindex = new List<int>(); List<int> refindex = new List<int>(); temp = temp.Replace("$ARGS", ArgsList(mi, ref outindex, ref refindex)); Write(file, temp); this.indent = 4; for (int n = 0; n < mi.GetParameters().Length; n++) { if (!outindex.Contains(n)) Write(file, "pushValue(l,a{0});", n + 1); } Write(file, "ld.call({0}, error);", mi.GetParameters().Length - outindex.Count); if (mi.ReturnType != typeof(void)) WriteValueCheck(file, mi.ReturnType, 1, "ret", "error+"); foreach (int i in outindex) { string a = string.Format("a{0}", i + 1); WriteCheckType(file, mi.GetParameters()[i].ParameterType, i + 1, a, "error+"); } foreach (int i in refindex) { string a = string.Format("a{0}", i + 1); WriteCheckType(file, mi.GetParameters()[i].ParameterType, i + 1, a, "error+"); } Write(file, "LuaDLL.lua_settop(l, error-1);"); if (mi.ReturnType != typeof(void)) Write(file, "return ret;"); Write(file, "};"); Write(file, "ld.d=ua;"); Write(file, "return op;"); Write(file, "}"); Write(file, "}"); Write(file, "}"); } string ArgsList(MethodInfo m, ref List<int> outindex, ref List<int> refindex) { string str = ""; ParameterInfo[] pars = m.GetParameters(); for (int n = 0; n < pars.Length; n++) { string t = SimpleType(pars[n].ParameterType); ParameterInfo p = pars[n]; if (p.ParameterType.IsByRef && p.IsOut) { str += string.Format("out {0} a{1}", t, n + 1); outindex.Add(n); } else if (p.ParameterType.IsByRef) { str += string.Format("ref {0} a{1}", t, n + 1); refindex.Add(n); } else str += string.Format("{0} a{1}", t, n + 1); if (n < pars.Length - 1) str += ","; } return str; } void tryMake(Type t) { if (t.BaseType == typeof(System.MulticastDelegate)) { CodeGenerator cg = new CodeGenerator(); cg.path = this.path; cg.Generate(t); } } void WriteEvent(Type t, StreamWriter file) { string temp = @" using System; using System.Collections.Generic; using LuaInterface; using UnityEngine; using UnityEngine.EventSystems; namespace SLua { public class LuaUnityEvent_$CLS : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int AddListener(IntPtr l) { try { UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l); UnityEngine.Events.UnityAction<$GN> a1; checkType(l, 2, out a1); self.AddListener(a1); return 0; } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int RemoveListener(IntPtr l) { try { UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l); UnityEngine.Events.UnityAction<$GN> a1; checkType(l, 2, out a1); self.RemoveListener(a1); return 0; } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Invoke(IntPtr l) { try { UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l); $GN o; checkType(l,2,out o); self.Invoke(o); return 0; } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } static public void reg(IntPtr l) { getTypeTable(l, typeof(LuaUnityEvent_$CLS).FullName); addMember(l, AddListener); addMember(l, RemoveListener); addMember(l, Invoke); createTypeMetatable(l, null, typeof(LuaUnityEvent_$CLS), typeof(UnityEngine.Events.UnityEventBase)); } static bool checkType(IntPtr l,int p,out UnityEngine.Events.UnityAction<$GN> ua) { LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TFUNCTION); LuaDelegate ld; checkType(l, p, out ld); if (ld.d != null) { ua = (UnityEngine.Events.UnityAction<$GN>)ld.d; return true; } l = LuaState.get(l).L; ua = ($GN v) => { int error = pushTry(l); pushValue(l, v); ld.call(1, error); LuaDLL.lua_settop(l,error - 1); }; ld.d = ua; return true; } } }"; temp = temp.Replace("$CLS", _Name(GenericName(t.BaseType))); temp = temp.Replace("$FNAME", FullName(t)); temp = temp.Replace("$GN", GenericName(t.BaseType)); Write(file, temp); } void RegEnumFunction(Type t, StreamWriter file) { // Write export function Write(file, "static public void reg(IntPtr l) {"); Write(file, "getEnumTable(l,\"{0}\");", FullName(t)); FieldInfo[] fields = t.GetFields(); foreach (FieldInfo f in fields) { if (f.Name == "value__") continue; Write(file, "addMember(l,{0},\"{1}\");", (int)f.GetValue(null), f.Name); } Write(file, "LuaDLL.lua_pop(l, 1);"); Write(file, "}"); } StreamWriter Begin(Type t) { string clsname = ExportName(t); string f = path + clsname + ".cs"; StreamWriter file = new StreamWriter(f, false, Encoding.UTF8); return file; } private void End(StreamWriter file) { Write(file, "}"); file.Flush(); file.Close(); } private void WriteHead(Type t, StreamWriter file) { Write(file, "using UnityEngine;"); Write(file, "using System;"); Write(file, "using LuaInterface;"); Write(file, "using SLua;"); Write(file, "using System.Collections.Generic;"); Write(file, "public class {0} : LuaObject {{", ExportName(t)); } private void WriteFunction(Type t, StreamWriter file, bool writeStatic = false) { BindingFlags bf = BindingFlags.Public | BindingFlags.DeclaredOnly; if (writeStatic) bf |= BindingFlags.Static; else bf |= BindingFlags.Instance; MethodInfo[] members = t.GetMethods(bf); foreach (MethodInfo mi in members) { bool instanceFunc; if (writeStatic && isPInvoke(mi, out instanceFunc)) { directfunc.Add(t.FullName + "." + mi.Name, instanceFunc); continue; } string fn = writeStatic ? staticName(mi.Name) : mi.Name; if (mi.MemberType == MemberTypes.Method && !IsObsolete(mi) && !DontExport(mi) && !funcname.Contains(fn) && isUsefullMethod(mi) && !MemberInFilter(t, mi)) { WriteFunctionDec(file, fn); WriteFunctionImpl(file, mi, t, bf); funcname.Add(fn); } } } bool isPInvoke(MethodInfo mi, out bool instanceFunc) { object[] attrs = mi.GetCustomAttributes(typeof(MonoPInvokeCallbackAttribute), false); if (attrs.Length > 0) { instanceFunc = mi.GetCustomAttributes(typeof(StaticExportAttribute), false).Length == 0; return true; } instanceFunc = true; return false; } string staticName(string name) { if (name.StartsWith("op_")) return name; return name + "_s"; } bool MemberInFilter(Type t, MemberInfo mi) { return memberFilter.Contains(t.Name + "." + mi.Name); } bool IsObsolete(MemberInfo mi) { return LuaCodeGen.IsObsolete(mi); } void RegFunction(Type t, StreamWriter file) { // Write export function Write(file, "static public void reg(IntPtr l) {"); if (t.BaseType != null && t.BaseType.Name.Contains("UnityEvent`")) { Write(file, "LuaUnityEvent_{1}.reg(l);", FullName(t), _Name((GenericName(t.BaseType)))); } Write(file, "getTypeTable(l,\"{0}\");", givenNamespace != null ? givenNamespace : FullName(t)); foreach (string f in funcname) { Write(file, "addMember(l,{0});", f); } foreach (string f in directfunc.Keys) { bool instance = directfunc[f]; Write(file, "addMember(l,{0},{1});", f, instance ? "true" : "false"); } foreach (string f in propname.Keys) { PropPair pp = propname[f]; Write(file, "addMember(l,\"{0}\",{1},{2},{3});", f, pp.get, pp.set, pp.isInstance ? "true" : "false"); } if (t.BaseType != null && !CutBase(t.BaseType)) { if (t.BaseType.Name.Contains("UnityEvent`1")) Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof(LuaUnityEvent_{1}));", TypeDecl(t), _Name(GenericName(t.BaseType)), constructorOrNot(t)); else Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof({1}));", TypeDecl(t), TypeDecl(t.BaseType), constructorOrNot(t)); } else Write(file, "createTypeMetatable(l,{1}, typeof({0}));", TypeDecl(t), constructorOrNot(t)); Write(file, "}"); } string constructorOrNot(Type t) { ConstructorInfo[] cons = GetValidConstructor(t); if (cons.Length > 0 || t.IsValueType) return "constructor"; return "null"; } bool CutBase(Type t) { if (t.FullName.StartsWith("System.Object")) return true; return false; } void WriteSet(StreamWriter file, Type t, string cls, string fn, bool isstatic = false) { if (t.BaseType == typeof(MulticastDelegate)) { if (isstatic) { Write(file, "if(op==0) {0}.{1}=v;", cls, fn); Write(file, "else if(op==1) {0}.{1}+=v;", cls, fn); Write(file, "else if(op==2) {0}.{1}-=v;", cls, fn); } else { Write(file, "if(op==0) self.{0}=v;", fn); Write(file, "else if(op==1) self.{0}+=v;", fn); Write(file, "else if(op==2) self.{0}-=v;", fn); } } else { if (isstatic) { Write(file, "{0}.{1}=v;", cls, fn); } else { Write(file, "self.{0}=v;", fn); } } } private void WriteField(Type t, StreamWriter file) { // Write field set/get FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (FieldInfo fi in fields) { if (DontExport(fi) || IsObsolete(fi)) continue; PropPair pp = new PropPair(); pp.isInstance = !fi.IsStatic; if (fi.FieldType.BaseType != typeof(MulticastDelegate)) { WriteFunctionAttr(file); Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.IsStatic) { WritePushValue(fi.FieldType, file, string.Format("{0}.{1}", TypeDecl(t), fi.Name)); } else { WriteCheckSelf(file, t); WritePushValue(fi.FieldType, file, string.Format("self.{0}", fi.Name)); } Write(file, "return 1;"); WriteCatchExecption(file); Write(file, "}"); pp.get = "get_" + fi.Name; } if (!fi.IsLiteral && !fi.IsInitOnly) { WriteFunctionAttr(file); Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.IsStatic) { Write(file, "{0} v;", TypeDecl(fi.FieldType)); WriteCheckType(file, fi.FieldType, 2); WriteSet(file, fi.FieldType, TypeDecl(t), fi.Name, true); } else { WriteCheckSelf(file, t); Write(file, "{0} v;", TypeDecl(fi.FieldType)); WriteCheckType(file, fi.FieldType, 2); WriteSet(file, fi.FieldType, t.FullName, fi.Name); } if (t.IsValueType && !fi.IsStatic) Write(file, "setBack(l,self);"); Write(file, "return 0;"); WriteCatchExecption(file); Write(file, "}"); pp.set = "set_" + fi.Name; } propname.Add(fi.Name, pp); tryMake(fi.FieldType); } //for this[] List<PropertyInfo> getter = new List<PropertyInfo>(); List<PropertyInfo> setter = new List<PropertyInfo>(); // Write property set/get PropertyInfo[] props = t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (PropertyInfo fi in props) { //if (fi.Name == "Item" || IsObsolete(fi) || MemberInFilter(t,fi) || DontExport(fi)) if (IsObsolete(fi) || MemberInFilter(t, fi) || DontExport(fi)) continue; if (fi.Name == "Item" || (t.Name == "String" && fi.Name == "Chars")) // for string[] { //for this[] if (!fi.GetGetMethod().IsStatic && fi.GetIndexParameters().Length == 1) { if (fi.CanRead && !IsNotSupport(fi.PropertyType)) getter.Add(fi); if (fi.CanWrite && fi.GetSetMethod() != null) setter.Add(fi); } continue; } PropPair pp = new PropPair(); bool isInstance = true; if (fi.CanRead && fi.GetGetMethod() != null) { if (!IsNotSupport(fi.PropertyType)) { WriteFunctionAttr(file); Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.GetGetMethod().IsStatic) { isInstance = false; WritePushValue(fi.PropertyType, file, string.Format("{0}.{1}", TypeDecl(t), fi.Name)); } else { WriteCheckSelf(file, t); WritePushValue(fi.PropertyType, file, string.Format("self.{0}", fi.Name)); } Write(file, "return 1;"); WriteCatchExecption(file); Write(file, "}"); pp.get = "get_" + fi.Name; } } if (fi.CanWrite && fi.GetSetMethod() != null) { WriteFunctionAttr(file); Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.GetSetMethod().IsStatic) { WriteValueCheck(file, fi.PropertyType, 2); WriteSet(file, fi.PropertyType, TypeDecl(t), fi.Name, true); isInstance = false; } else { WriteCheckSelf(file, t); WriteValueCheck(file, fi.PropertyType, 2); WriteSet(file, fi.PropertyType, TypeDecl(t), fi.Name); } if (t.IsValueType) Write(file, "setBack(l,self);"); Write(file, "return 0;"); WriteCatchExecption(file); Write(file, "}"); pp.set = "set_" + fi.Name; } pp.isInstance = isInstance; propname.Add(fi.Name, pp); tryMake(fi.PropertyType); } //for this[] WriteItemFunc(t, file, getter, setter); } void WriteItemFunc(Type t, StreamWriter file, List<PropertyInfo> getter, List<PropertyInfo> setter) { //Write property this[] set/get if (getter.Count > 0) { //get bool first_get = true; WriteFunctionAttr(file); Write(file, "static public int getItem(IntPtr l) {"); WriteTry(file); WriteCheckSelf(file, t); if (getter.Count == 1) { PropertyInfo _get = getter[0]; ParameterInfo[] infos = _get.GetIndexParameters(); WriteValueCheck(file, infos[0].ParameterType, 2, "v"); Write(file, "var ret = self[v];"); WritePushValue(_get.PropertyType, file, "ret"); Write(file, "return 1;"); } else { Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);"); for (int i = 0; i < getter.Count; i++) { PropertyInfo fii = getter[i]; ParameterInfo[] infos = fii.GetIndexParameters(); Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_get ? "if" : "else if", infos[0].ParameterType); WriteValueCheck(file, infos[0].ParameterType, 2, "v"); Write(file, "var ret = self[v];"); WritePushValue(fii.PropertyType, file, "ret"); Write(file, "return 1;"); Write(file, "}"); first_get = false; } Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");"); Write(file, "return 0;"); } WriteCatchExecption(file); Write(file, "}"); funcname.Add("getItem"); } if (setter.Count > 0) { bool first_set = true; WriteFunctionAttr(file); Write(file, "static public int setItem(IntPtr l) {"); WriteTry(file); WriteCheckSelf(file, t); if (setter.Count == 1) { PropertyInfo _set = setter[0]; ParameterInfo[] infos = _set.GetIndexParameters(); WriteValueCheck(file, infos[0].ParameterType, 2); WriteValueCheck(file, _set.PropertyType, 3, "c"); Write(file, "self[v]=c;"); } else { Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);"); for (int i = 0; i < setter.Count; i++) { PropertyInfo fii = setter[i]; if (t.BaseType != typeof(MulticastDelegate)) { ParameterInfo[] infos = fii.GetIndexParameters(); Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_set ? "if" : "else if", infos[0].ParameterType); WriteValueCheck(file, infos[0].ParameterType, 2, "v"); WriteValueCheck(file, fii.PropertyType, 3, "c"); Write(file, "self[v]=c;"); Write(file, "return 0;"); Write(file, "}"); first_set = false; } if (t.IsValueType) Write(file, "setBack(l,self);"); } Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");"); } Write(file, "return 0;"); WriteCatchExecption(file); Write(file, "}"); funcname.Add("setItem"); } } void WriteTry(StreamWriter file) { Write(file, "try {"); } void WriteCatchExecption(StreamWriter file) { Write(file, "}"); Write(file, "catch(Exception e) {"); Write(file, "LuaDLL.luaL_error(l, e.ToString());"); Write(file, "return 0;"); Write(file, "}"); } void WriteCheckType(StreamWriter file, Type t, int n, string v = "v", string nprefix = "") { if (t.IsEnum) Write(file, "checkEnum(l,{2}{0},out {1});", n, v, nprefix); else if (t.BaseType == typeof(System.MulticastDelegate)) Write(file, "int op=LuaDelegation.checkDelegate(l,{2}{0},out {1});", n, v, nprefix); else Write(file, "checkType(l,{2}{0},out {1});", n, v, nprefix); } void WriteValueCheck(StreamWriter file, Type t, int n, string v = "v", string nprefix = "") { Write(file, "{0} {1};", SimpleType(t), v); WriteCheckType(file, t, n, v, nprefix); } private void WriteFunctionAttr(StreamWriter file) { Write(file, "[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]"); } ConstructorInfo[] GetValidConstructor(Type t) { List<ConstructorInfo> ret = new List<ConstructorInfo>(); if (t.GetConstructor(Type.EmptyTypes) == null && t.IsAbstract && t.IsSealed) return ret.ToArray(); if (t.BaseType != null && t.BaseType.Name == "MonoBehaviour") return ret.ToArray(); ConstructorInfo[] cons = t.GetConstructors(BindingFlags.Instance | BindingFlags.Public); foreach (ConstructorInfo ci in cons) { if (!IsObsolete(ci) && !DontExport(ci) && !ContainUnsafe(ci)) ret.Add(ci); } return ret.ToArray(); } bool ContainUnsafe(MethodBase mi) { foreach (ParameterInfo p in mi.GetParameters()) { if (p.ParameterType.FullName.Contains("*")) return true; } return false; } bool DontExport(MemberInfo mi) { return mi.GetCustomAttributes(typeof(DoNotToLuaAttribute), false).Length > 0; } private void WriteConstructor(Type t, StreamWriter file) { ConstructorInfo[] cons = GetValidConstructor(t); if (cons.Length > 0) { WriteFunctionAttr(file); Write(file, "static public int constructor(IntPtr l) {"); WriteTry(file); if (cons.Length > 1) Write(file, "int argc = LuaDLL.lua_gettop(l);"); Write(file, "{0} o;", TypeDecl(t)); bool first = true; for (int n = 0; n < cons.Length; n++) { ConstructorInfo ci = cons[n]; ParameterInfo[] pars = ci.GetParameters(); if (cons.Length > 1) { if (isUniqueArgsCount(cons, ci)) Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", ci.GetParameters().Length + 1); else Write(file, "{0}(matchType(l,argc,2{1})){{", first ? "if" : "else if", TypeDecl(pars)); } for (int k = 0; k < pars.Length; k++) { ParameterInfo p = pars[k]; bool hasParams = p.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0; CheckArgument(file, p.ParameterType, k, 2, p.IsOut, hasParams); } Write(file, "o=new {0}({1});", TypeDecl(t), FuncCall(ci)); if (t.Name == "String") // if export system.string, push string as ud not lua string Write(file, "pushObject(l,o);"); else Write(file, "pushValue(l,o);"); Write(file, "return 1;"); if (cons.Length == 1) WriteCatchExecption(file); Write(file, "}"); first = false; } if (cons.Length > 1) { Write(file, "LuaDLL.luaL_error(l,\"New object failed.\");"); Write(file, "return 0;"); WriteCatchExecption(file); Write(file, "}"); } } else if (t.IsValueType) // default constructor { WriteFunctionAttr(file); Write(file, "static public int constructor(IntPtr l) {"); WriteTry(file); Write(file, "{0} o;", FullName(t)); Write(file, "o=new {0}();", FullName(t)); Write(file, "pushValue(l,o);"); Write(file, "return 1;"); WriteCatchExecption(file); Write(file, "}"); } } bool IsNotSupport(Type t) { if (t.IsSubclassOf(typeof(Delegate))) return true; return false; } string[] prefix = new string[] { "System.Collections.Generic" }; string RemoveRef(string s, bool removearray = true) { if (s.EndsWith("&")) s = s.Substring(0, s.Length - 1); if (s.EndsWith("[]") && removearray) s = s.Substring(0, s.Length - 2); if (s.StartsWith(prefix[0])) s = s.Substring(prefix[0].Length + 1, s.Length - prefix[0].Length - 1); s = s.Replace("+", "."); if (s.Contains("`")) { string regstr = @"`\d"; Regex r = new Regex(regstr, RegexOptions.None); s = r.Replace(s, ""); s = s.Replace("[", "<"); s = s.Replace("]", ">"); } return s; } string GenericBaseName(Type t) { string n = t.FullName; if (n.IndexOf('[') > 0) { n = n.Substring(0, n.IndexOf('[')); } return n.Replace("+", "."); } string GenericName(Type t) { try { Type[] tt = t.GetGenericArguments(); string ret = ""; for (int n = 0; n < tt.Length; n++) { string dt = SimpleType(tt[n]); ret += dt; if (n < tt.Length - 1) ret += "_"; } return ret; } catch (Exception e) { Debug.Log(e.ToString()); return ""; } } string _Name(string n) { string ret = ""; for (int i = 0; i < n.Length; i++) { if (char.IsLetterOrDigit(n[i])) ret += n[i]; else ret += "_"; } return ret; } string TypeDecl(ParameterInfo[] pars) { string ret = ""; for (int n = 0; n < pars.Length; n++) { ret += ",typeof("; if (pars[n].IsOut) ret += "LuaOut"; else ret += SimpleType(pars[n].ParameterType); ret += ")"; } return ret; } bool isUsefullMethod(MethodInfo method) { if (method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" && method.Name != "ToString" && method.Name != "Clone" && method.Name != "GetEnumerator" && method.Name != "CopyTo" && method.Name != "op_Implicit" && !method.Name.StartsWith("get_", StringComparison.Ordinal) && !method.Name.StartsWith("set_", StringComparison.Ordinal) && !method.Name.StartsWith("add_", StringComparison.Ordinal) && !IsObsolete(method) && !method.IsGenericMethod && //!method.Name.StartsWith("op_", StringComparison.Ordinal) && !method.Name.StartsWith("remove_", StringComparison.Ordinal)) { return true; } return false; } void WriteFunctionDec(StreamWriter file, string name) { WriteFunctionAttr(file); Write(file, "static public int {0}(IntPtr l) {{", name); } MethodBase[] GetMethods(Type t, string name, BindingFlags bf) { List<MethodBase> methods = new List<MethodBase>(); MemberInfo[] cons = t.GetMember(name, bf); foreach (MemberInfo m in cons) { if (m.MemberType == MemberTypes.Method && !IsObsolete(m) && !DontExport(m) && isUsefullMethod((MethodInfo)m)) methods.Add((MethodBase)m); } methods.Sort((a, b) => { return a.GetParameters().Length - b.GetParameters().Length; }); return methods.ToArray(); } void WriteFunctionImpl(StreamWriter file, MethodInfo m, Type t, BindingFlags bf) { WriteTry(file); MethodBase[] cons = GetMethods(t, m.Name, bf); if (cons.Length == 1) // no override function { if (isUsefullMethod(m) && !m.ReturnType.ContainsGenericParameters && !m.ContainsGenericParameters) // don't support generic method WriteFunctionCall(m, file, t); else { Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");"); Write(file, "return 0;"); } } else // 2 or more override function { Write(file, "int argc = LuaDLL.lua_gettop(l);"); bool first = true; for (int n = 0; n < cons.Length; n++) { if (cons[n].MemberType == MemberTypes.Method) { MethodInfo mi = cons[n] as MethodInfo; ParameterInfo[] pars = mi.GetParameters(); if (isUsefullMethod(mi) && !mi.ReturnType.ContainsGenericParameters /*&& !ContainGeneric(pars)*/) // don't support generic method { if (isUniqueArgsCount(cons, mi)) Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", mi.IsStatic ? mi.GetParameters().Length : mi.GetParameters().Length + 1); else Write(file, "{0}(matchType(l,argc,{1}{2})){{", first ? "if" : "else if", mi.IsStatic ? 1 : 2, TypeDecl(pars)); WriteFunctionCall(mi, file, t); Write(file, "}"); first = false; } } } Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");"); Write(file, "return 0;"); } WriteCatchExecption(file); Write(file, "}"); } bool isUniqueArgsCount(MethodBase[] cons, MethodBase mi) { foreach (MethodBase member in cons) { MethodBase m = (MethodBase)member; if (m != mi && mi.GetParameters().Length == m.GetParameters().Length) return false; } return true; } bool ContainGeneric(ParameterInfo[] pars) { foreach (ParameterInfo p in pars) { if (p.ParameterType.IsGenericType || p.ParameterType.IsGenericParameter || p.ParameterType.IsGenericTypeDefinition) return true; } return false; } void WriteCheckSelf(StreamWriter file, Type t) { if (t.IsValueType) { Write(file, "{0} self;", FullName(t)); Write(file, "checkType(l,1,out self);"); } else Write(file, "{0} self=({0})checkSelf(l);", TypeDecl(t)); } private void WriteFunctionCall(MethodInfo m, StreamWriter file, Type t) { bool hasref = false; ParameterInfo[] pars = m.GetParameters(); int argIndex = 1; if (!m.IsStatic) { WriteCheckSelf(file, t); argIndex++; } for (int n = 0; n < pars.Length; n++) { ParameterInfo p = pars[n]; string pn = p.ParameterType.Name; if (pn.EndsWith("&")) { hasref = true; } bool hasParams = p.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0; CheckArgument(file, p.ParameterType, n, argIndex, p.IsOut, hasParams); } string ret = ""; if (m.ReturnType != typeof(void)) { ret = "var ret="; } if (m.IsStatic) { if (m.Name == "op_Multiply") Write(file, "{0}a1*a2;", ret); else if (m.Name == "op_Subtraction") Write(file, "{0}a1-a2;", ret); else if (m.Name == "op_Addition") Write(file, "{0}a1+a2;", ret); else if (m.Name == "op_Division") Write(file, "{0}a1/a2;", ret); else if (m.Name == "op_UnaryNegation") Write(file, "{0}-a1;", ret); else if (m.Name == "op_Equality") Write(file, "{0}(a1==a2);", ret); else if (m.Name == "op_Inequality") Write(file, "{0}(a1!=a2);", ret); else if (m.Name == "op_LessThan") Write(file, "{0}(a1<a2);", ret); else if (m.Name == "op_GreaterThan") Write(file, "{0}(a2<a1);", ret); else if (m.Name == "op_LessThanOrEqual") Write(file, "{0}(a1<=a2);", ret); else if (m.Name == "op_GreaterThanOrEqual") Write(file, "{0}(a2<=a1);", ret); else Write(file, "{3}{2}.{0}({1});", m.Name, FuncCall(m), TypeDecl(t), ret); } else Write(file, "{2}self.{0}({1});", m.Name, FuncCall(m), ret); int retcount = 0; if (m.ReturnType != typeof(void)) { WritePushValue(m.ReturnType, file); retcount = 1; } // push out/ref value for return value if (hasref) { for (int n = 0; n < pars.Length; n++) { ParameterInfo p = pars[n]; if (p.ParameterType.IsByRef) { WritePushValue(p.ParameterType, file, string.Format("a{0}", n + 1)); retcount++; } } } if (t.IsValueType && m.ReturnType == typeof(void) && !m.IsStatic) Write(file, "setBack(l,self);"); Write(file, "return {0};", retcount); } string SimpleType_(Type t) { string tn = t.Name; switch (tn) { case "Single": return "float"; case "String": return "string"; case "Double": return "double"; case "Boolean": return "bool"; case "Int32": return "int"; case "Object": return FullName(t); default: tn = TypeDecl(t); tn = tn.Replace("System.Collections.Generic.", ""); tn = tn.Replace("System.Object", "object"); return tn; } } string SimpleType(Type t) { string ret = SimpleType_(t); return ret; } void WritePushValue(Type t, StreamWriter file) { if (t.IsEnum) Write(file, "pushEnum(l,(int)ret);"); else Write(file, "pushValue(l,ret);"); } void WritePushValue(Type t, StreamWriter file, string ret) { if (t.IsEnum) Write(file, "pushEnum(l,(int){0});", ret); else Write(file, "pushValue(l,{0});", ret); } void Write(StreamWriter file, string fmt, params object[] args) { if (fmt.StartsWith("}")) indent--; for (int n = 0; n < indent; n++) file.Write("\t"); if (args.Length == 0) file.WriteLine(fmt); else { string line = string.Format(fmt, args); file.WriteLine(line); } if (fmt.EndsWith("{")) indent++; } private void CheckArgument(StreamWriter file, Type t, int n, int argstart, bool isout, bool isparams) { Write(file, "{0} a{1};", TypeDecl(t), n + 1); if (!isout) { if (t.IsEnum) Write(file, "checkEnum(l,{0},out a{1});", n + argstart, n + 1); else if (t.BaseType == typeof(System.MulticastDelegate)) { tryMake(t); Write(file, "LuaDelegation.checkDelegate(l,{0},out a{1});", n + argstart, n + 1); } else if (isparams) Write(file, "checkParams(l,{0},out a{1});", n + argstart, n + 1); else Write(file, "checkType(l,{0},out a{1});", n + argstart, n + 1); } } string FullName(string str) { if (str == null) { throw new NullReferenceException(); } return RemoveRef(str.Replace("+", ".")); } string TypeDecl(Type t) { if (t.IsGenericType) { string ret = GenericBaseName(t); string gs = ""; gs += "<"; Type[] types = t.GetGenericArguments(); for (int n = 0; n < types.Length; n++) { gs += TypeDecl(types[n]); if (n < types.Length - 1) gs += ","; } gs += ">"; ret = Regex.Replace(ret, @"`\d", gs); return ret; } if (t.IsArray) { return TypeDecl(t.GetElementType()) + "[]"; } else return RemoveRef(t.ToString(), false); } string ExportName(Type t) { if (t.IsGenericType) { return string.Format("Lua_{0}_{1}", _Name(GenericBaseName(t)), _Name(GenericName(t))); } else { string name = RemoveRef(t.FullName, true); name = "Lua_" + name; return name.Replace(".", "_"); } } string FullName(Type t) { if (t.FullName == null) { Debug.Log(t.Name); return t.Name; } return FullName(t.FullName); } string FuncCall(MethodBase m) { string str = ""; ParameterInfo[] pars = m.GetParameters(); for (int n = 0; n < pars.Length; n++) { ParameterInfo p = pars[n]; if (p.ParameterType.IsByRef && p.IsOut) str += string.Format("out a{0}", n + 1); else if (p.ParameterType.IsByRef) str += string.Format("ref a{0}", n + 1); else str += string.Format("a{0}", n + 1); if (n < pars.Length - 1) str += ","; } return str; } } }
// // SmugMugExport.cs // // Author: // Stephane Delcroix <[email protected]> // // Copyright (C) 2006-2009 Novell, Inc. // Copyright (C) 2006-2009 Stephane Delcroix // // 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. // /* * SmugMugExport.cs * * Authors: * Thomas Van Machelen <[email protected]> * * Based on PicasaWebExport code from Stephane Delcroix. * * Copyright (C) 2006 Thomas Van Machelen */ using System; using System.Net; using System.IO; using System.Text; using System.Threading; using System.Collections; using System.Collections.Specialized; using System.Web; using Mono.Unix; using Gtk; using FSpot; using FSpot.Core; using FSpot.Filters; using FSpot.Widgets; using Hyena; using FSpot.UI.Dialog; using Gnome.Keyring; using SmugMugNet; namespace FSpot.Exporters.SmugMug { public class SmugMugExport : FSpot.Extensions.IExporter { public SmugMugExport () {} public void Run (IBrowsableCollection selection) { builder = new GtkBeans.Builder (null, "smugmug_export_dialog.ui", null); builder.Autoconnect (this); gallery_optionmenu = Gtk.ComboBox.NewText(); album_optionmenu = Gtk.ComboBox.NewText(); (edit_button.Parent as Gtk.HBox).PackStart (gallery_optionmenu); (album_button.Parent as Gtk.HBox).PackStart (album_optionmenu); (edit_button.Parent as Gtk.HBox).ReorderChild (gallery_optionmenu, 1); (album_button.Parent as Gtk.HBox).ReorderChild (album_optionmenu, 1); gallery_optionmenu.Show (); album_optionmenu.Show (); this.items = selection.Items; album_button.Sensitive = false; var view = new TrayView (selection); view.DisplayDates = false; view.DisplayTags = false; Dialog.Modal = false; Dialog.TransientFor = null; Dialog.Close += HandleCloseEvent; thumb_scrolledwindow.Add (view); view.Show (); Dialog.Show (); SmugMugAccountManager manager = SmugMugAccountManager.GetInstance (); manager.AccountListChanged += PopulateSmugMugOptionMenu; PopulateSmugMugOptionMenu (manager, null); if (edit_button != null) edit_button.Clicked += HandleEditGallery; Dialog.Response += HandleResponse; connect = true; HandleSizeActive (null, null); Connect (); LoadPreference (SCALE_KEY); LoadPreference (SIZE_KEY); LoadPreference (BROWSER_KEY); } private bool scale; private int size; private bool browser; private bool connect = false; private long approx_size = 0; private long sent_bytes = 0; IPhoto [] items; int photo_index; ThreadProgressDialog progress_dialog; ArrayList accounts; private SmugMugAccount account; private Album album; private string dialog_name = "smugmug_export_dialog"; private GtkBeans.Builder builder; // Widgets [GtkBeans.Builder.Object] Gtk.Dialog dialog; Gtk.ComboBox gallery_optionmenu; Gtk.ComboBox album_optionmenu; [GtkBeans.Builder.Object] Gtk.CheckButton browser_check; [GtkBeans.Builder.Object] Gtk.CheckButton scale_check; [GtkBeans.Builder.Object] Gtk.SpinButton size_spin; [GtkBeans.Builder.Object] Gtk.Button album_button; [GtkBeans.Builder.Object] Gtk.Button edit_button; [GtkBeans.Builder.Object] Gtk.Button export_button; [GtkBeans.Builder.Object] Gtk.ScrolledWindow thumb_scrolledwindow; System.Threading.Thread command_thread; public const string EXPORT_SERVICE = "smugmug/"; public const string SCALE_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "scale"; public const string SIZE_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "size"; public const string BROWSER_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "browser"; private void HandleResponse (object sender, Gtk.ResponseArgs args) { if (args.ResponseId != Gtk.ResponseType.Ok) { Dialog.Destroy (); return; } if (scale_check != null) { scale = scale_check.Active; size = size_spin.ValueAsInt; } else scale = false; browser = browser_check.Active; if (account != null) { album = (Album) account.SmugMug.GetAlbums() [Math.Max (0, album_optionmenu.Active)]; photo_index = 0; Dialog.Destroy (); command_thread = new System.Threading.Thread (new System.Threading.ThreadStart (this.Upload)); command_thread.Name = Mono.Unix.Catalog.GetString ("Uploading Pictures"); progress_dialog = new ThreadProgressDialog (command_thread, items.Length); progress_dialog.Start (); // Save these settings for next time Preferences.Set (SCALE_KEY, scale); Preferences.Set (SIZE_KEY, size); Preferences.Set (BROWSER_KEY, browser); } } public void HandleSizeActive (object sender, EventArgs args) { size_spin.Sensitive = scale_check.Active; } private void Upload () { sent_bytes = 0; approx_size = 0; System.Uri album_uri = null; Log.Debug ("Starting Upload to Smugmug, album " + album.Title + " - " + album.AlbumID); FilterSet filters = new FilterSet (); filters.Add (new JpegFilter ()); if (scale) filters.Add (new ResizeFilter ((uint)size)); while (photo_index < items.Length) { try { IPhoto item = items[photo_index]; FileInfo file_info; Log.Debug ("uploading " + photo_index); progress_dialog.Message = String.Format (Catalog.GetString ("Uploading picture \"{0}\" ({1} of {2})"), item.Name, photo_index+1, items.Length); progress_dialog.ProgressText = string.Empty; progress_dialog.Fraction = ((photo_index) / (double) items.Length); photo_index++; FilterRequest request = new FilterRequest (item.DefaultVersion.Uri); filters.Convert (request); file_info = new FileInfo (request.Current.LocalPath); if (approx_size == 0) //first image approx_size = file_info.Length * items.Length; else approx_size = sent_bytes * items.Length / (photo_index - 1); int image_id = account.SmugMug.Upload (request.Current.LocalPath, album.AlbumID); if (App.Instance.Database != null && item is Photo && image_id >= 0) App.Instance.Database.Exports.Create ((item as Photo).Id, (item as Photo).DefaultVersionId, ExportStore.SmugMugExportType, account.SmugMug.GetAlbumUrl (image_id).ToString ()); sent_bytes += file_info.Length; if (album_uri == null) album_uri = account.SmugMug.GetAlbumUrl (image_id); } catch (System.Exception e) { progress_dialog.Message = String.Format (Mono.Unix.Catalog.GetString ("Error Uploading To Gallery: {0}"), e.Message); progress_dialog.ProgressText = Mono.Unix.Catalog.GetString ("Error"); Log.DebugException (e); if (progress_dialog.PerformRetrySkip ()) { photo_index--; if (photo_index == 0) approx_size = 0; } } } progress_dialog.Message = Catalog.GetString ("Done Sending Photos"); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Mono.Unix.Catalog.GetString ("Upload Complete"); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (browser && album_uri != null) { GtkBeans.Global.ShowUri (Dialog.Screen, album_uri.ToString ()); } } private void PopulateSmugMugOptionMenu (SmugMugAccountManager manager, SmugMugAccount changed_account) { this.account = changed_account; int pos = 0; accounts = manager.GetAccounts (); if (accounts == null || accounts.Count == 0) { gallery_optionmenu.AppendText (Mono.Unix.Catalog.GetString ("(No Gallery)")); gallery_optionmenu.Sensitive = false; edit_button.Sensitive = false; } else { int i = 0; foreach (SmugMugAccount account in accounts) { if (account == changed_account) pos = i; gallery_optionmenu.AppendText(account.Username); i++; } gallery_optionmenu.Sensitive = true; edit_button.Sensitive = true; } gallery_optionmenu.Active = pos; } private void Connect () { Connect (null); } private void Connect (SmugMugAccount selected) { Connect (selected, null); } private void Connect (SmugMugAccount selected, string text) { try { if (accounts.Count != 0 && connect) { if (selected == null) account = (SmugMugAccount) accounts [gallery_optionmenu.Active]; else account = selected; if (!account.Connected) account.Connect (); PopulateAlbumOptionMenu (account.SmugMug); } } catch (System.Exception) { Log.Warning ("Can not connect to SmugMug. Bad username? Password? Network connection?"); if (selected != null) account = selected; PopulateAlbumOptionMenu (account.SmugMug); album_button.Sensitive = false; new SmugMugAccountDialog (this.Dialog, account); } } private void HandleAccountSelected (object sender, System.EventArgs args) { Connect (); } public void HandleAlbumAdded (string title) { SmugMugAccount account = (SmugMugAccount) accounts [gallery_optionmenu.Active]; PopulateAlbumOptionMenu (account.SmugMug); // make the newly created album selected Album[] albums = account.SmugMug.GetAlbums(); for (int i=0; i < albums.Length; i++) { if (((Album)albums[i]).Title == title) { album_optionmenu.Active = 1; } } } private void PopulateAlbumOptionMenu (SmugMugApi smugmug) { Album[] albums = null; if (smugmug != null) { try { albums = smugmug.GetAlbums(); } catch (Exception) { Log.Debug ("Can't get the albums"); smugmug = null; } } bool disconnected = smugmug == null || !account.Connected || albums == null; if (disconnected || albums.Length == 0) { string msg = disconnected ? Mono.Unix.Catalog.GetString ("(Not Connected)") : Mono.Unix.Catalog.GetString ("(No Albums)"); album_optionmenu.AppendText(msg); export_button.Sensitive = false; album_optionmenu.Sensitive = false; album_button.Sensitive = false; } else { foreach (Album album in albums) { System.Text.StringBuilder label_builder = new System.Text.StringBuilder (); label_builder.Append (album.Title); album_optionmenu.AppendText (label_builder.ToString()); } export_button.Sensitive = items.Length > 0; album_optionmenu.Sensitive = true; album_button.Sensitive = true; } album_optionmenu.Active = 0; } public void HandleAddGallery (object sender, System.EventArgs args) { new SmugMugAccountDialog (this.Dialog); } public void HandleEditGallery (object sender, System.EventArgs args) { new SmugMugAccountDialog (this.Dialog, account); } public void HandleAddAlbum (object sender, System.EventArgs args) { if (account == null) throw new Exception (Catalog.GetString ("No account selected")); new SmugMugAddAlbum (this, account.SmugMug); } void LoadPreference (string key) { switch (key) { case SCALE_KEY: if (scale_check.Active != Preferences.Get<bool> (key)) { scale_check.Active = Preferences.Get<bool> (key); } break; case SIZE_KEY: size_spin.Value = (double) Preferences.Get<int> (key); break; case BROWSER_KEY: if (browser_check.Active != Preferences.Get<bool> (key)) browser_check.Active = Preferences.Get<bool> (key); break; } } protected void HandleCloseEvent (object sender, System.EventArgs args) { account.SmugMug.Logout (); } private Gtk.Dialog Dialog { get { if (dialog == null) dialog = new Gtk.Dialog (builder.GetRawObject (dialog_name)); return dialog; } } } }
namespace PokerTell.LiveTracker.Tests.Overlay { using System; using System.Text.RegularExpressions; using System.Windows; using Machine.Specifications; using Moq; using PokerRooms; using PokerTell.LiveTracker.Interfaces; using PokerTell.LiveTracker.Overlay; using Tools.Interfaces; using Tools.WPF.Interfaces; using It = Machine.Specifications.It; // Resharper disable InconsistentNaming public abstract class OverlayToTableAttacherSpecs { protected static Mock<IWindowManipulator> _windowManipulator_Mock; protected static Mock<IWindowFinder> _windowFinder_Mock; protected static Mock<IWindowManager> _overlayWindow_Mock; protected static Mock<IDispatcherTimer> _watchTableTimer_Stub; protected static Mock<IDispatcherTimer> _findTableAgainTimer_Mock; protected static Mock<IPokerRoomInfo> _pokerRoomInfo_Stub; protected static string _processName; protected const string _tableName = "Parsed Table Name"; protected const string _adjustedTableName = "Adjusted Table Name"; protected static OverlayToTableAttacherSut _sut; Establish specContext = () => { _windowManipulator_Mock = new Mock<IWindowManipulator>(); _windowFinder_Mock = new Mock<IWindowFinder>(); _overlayWindow_Mock = new Mock<IWindowManager>(); _watchTableTimer_Stub = new Mock<IDispatcherTimer>(); _findTableAgainTimer_Mock = new Mock<IDispatcherTimer>(); _processName = "SomeProcessName"; _pokerRoomInfo_Stub = new Mock<IPokerRoomInfo>(); _pokerRoomInfo_Stub .SetupGet(i => i.ProcessName) .Returns(_processName); _pokerRoomInfo_Stub .Setup(i => i.TableNameFoundInPokerTableTitleFrom(_tableName)) .Returns(_adjustedTableName); _sut = new OverlayToTableAttacherSut(_windowManipulator_Mock.Object, _windowFinder_Mock.Object); _sut.InitializeWith(_overlayWindow_Mock.Object, _watchTableTimer_Stub.Object, _findTableAgainTimer_Mock.Object, _pokerRoomInfo_Stub.Object, _tableName); }; [Subject(typeof(OverlayToTableAttacher), "Activate")] public class when_it_is_activated : OverlayToTableAttacherSpecs { Because of = () => _sut.Activate(); It should_try_to_find_the_poker_table = () => _windowFinder_Mock.Verify( wf => wf.FindWindowMatching(Moq.It.IsAny<Regex>(), Moq.It.IsAny<Regex>(), Moq.It.IsAny<Func<IntPtr, bool>>())); } [Subject(typeof(OverlayToTableAttacher), "Activate")] public class when_it_is_activated_and_the_window_finder_finds_the_poker_table : OverlayToTableAttacherSpecs { protected static IntPtr foundHandle; protected static bool tableClosedWasRaised; Establish context = () => { foundHandle = (IntPtr)1; _windowFinder_Mock .Setup(wf => wf.FindWindowMatching(Moq.It.IsAny<Regex>(), Moq.It.IsAny<Regex>(), Moq.It.IsAny<Func<IntPtr, bool>>())) .Callback((Regex r1, Regex r2, Func<IntPtr, bool> cb) => cb(foundHandle)); _sut.TableClosed += () => tableClosedWasRaised = true; }; Because of = () => _sut.Activate(); It should_assign_the_returned_WindowHandle_to_the_window_manipulator = () => _windowManipulator_Mock.VerifySet(wm => wm.WindowHandle = foundHandle); It should_start_to_watch_the_table = () => _watchTableTimer_Stub.Verify(wt => wt.Start()); It should_not_tell_me_that_the_table_is_closed = () => tableClosedWasRaised.ShouldBeFalse(); } [Subject(typeof(OverlayToTableAttacher), "Activate")] public class when_it_is_activated_and_the_window_finder_does_not_find_the_poker_table : OverlayToTableAttacherSpecs { protected static bool tableClosedWasRaised; Establish context = () => { _windowFinder_Mock .Setup(wf => wf.FindWindowMatching(Moq.It.IsAny<Regex>(), Moq.It.IsAny<Regex>(), Moq.It.IsAny<Func<IntPtr, bool>>())) .Callback((Regex r1, Regex r2, Func<IntPtr, bool> cb) => { /* doesn't find anything */ }); _sut.TableClosed += () => tableClosedWasRaised = true; }; Because of = () => _sut.Activate(); It should_not_start_to_watch_the_table = () => _watchTableTimer_Stub.Verify(wt => wt.Start(), Times.Never()); It should_tell_me_that_the_table_is_closed = () => tableClosedWasRaised.ShouldBeTrue(); } [Subject(typeof(OverlayToTableAttacher), "Watching Table")] public class when_watch_timer_fires_when_not_waiting_for_new_table_name : OverlayToTableAttacherSpecs { protected static string fullText; Establish context = () => fullText = _sut.FullText; Because of = () => _watchTableTimer_Stub.Raise(t => t.Tick += null, null, null); It should_check_for_any_size_or_position_changes_of_the_poker_table = () => _windowManipulator_Mock.Verify(wm => wm.CheckWindowLocationAndSize(Moq.It.IsAny<Action<Point, Size>>())); It shoud_ensure_that_the_overlay_is_still_directly_on_top_of_the_poker_table = () => _windowManipulator_Mock.Verify(wm => wm.PlaceThisWindowDirectlyOnTopOfYours(_overlayWindow_Mock.Object, Moq.It.IsAny<Action>())); It should_set_the_window_text_to_the_adjusted_TableName = () => _windowManipulator_Mock.Verify(wm => wm.SetTextTo(_adjustedTableName, Moq.It.IsAny<Action<string>>())); } [Subject(typeof(OverlayToTableAttacher), "Watching Table")] public class when_watch_timer_fires_while_waiting_for_new_table_name : OverlayToTableAttacherSpecs { protected static string fullText; Establish context = () => { fullText = _sut.FullText; _sut.SetWaitingForNewTableName(true); }; Because of = () => _watchTableTimer_Stub.Raise(t => t.Tick += null, null, null); It should_check_for_any_size_or_position_changes_of_the_poker_table = () => _windowManipulator_Mock.Verify(wm => wm.CheckWindowLocationAndSize(Moq.It.IsAny<Action<Point, Size>>())); It shoud_ensure_that_the_overlay_is_still_directly_on_top_of_the_poker_table = () => _windowManipulator_Mock.Verify(wm => wm.PlaceThisWindowDirectlyOnTopOfYours(_overlayWindow_Mock.Object, Moq.It.IsAny<Action>())); It should_not_set_the_window_text_to_the_adjusted_TableName = () => _windowManipulator_Mock.Verify(wm => wm.SetTextTo(_adjustedTableName, Moq.It.IsAny<Action<string>>()), Times.Never()); } [Subject(typeof(OverlayToTableAttacher), "Watching Table")] public class when_watch_timer_fires_and_the_window_Manipulator_detects_a_change_in_location_and_size_of_the_poker_table : OverlayToTableAttacherSpecs { protected static Point newLocation; protected static Size newSize; Establish context = () => { newLocation = new Point(1.0, 2.0); newSize = new Size(1.0, 2.0); _windowManipulator_Mock .Setup(wm => wm.CheckWindowLocationAndSize(Moq.It.IsAny<Action<Point, Size>>())) .Callback((Action<Point, Size> cb) => cb(newLocation, newSize)); }; Because of = () => _watchTableTimer_Stub.Raise(wt => wt.Tick += null, null, null); It should_adjust_the_location_of_the_overlay_window_to_the_new_location = () => { _overlayWindow_Mock.VerifySet(ow => ow.Left = newLocation.X); _overlayWindow_Mock.VerifySet(ow => ow.Top = newLocation.Y); }; It should_adjust_the_size_of_the_overlay_window_to_the_new_size = () => { _overlayWindow_Mock.VerifySet(ow => ow.Width = newSize.Width); _overlayWindow_Mock.VerifySet(ow => ow.Height = newSize.Height); }; } [Subject(typeof(OverlayToTableAttacher), "Watching Table")] public class when_the_watcher_timer_fires_and_the_window_manipulator_detects_that_the_table_name_is_not_contained_in_the_poker_table_title : OverlayToTableAttacherSpecs { protected static bool tableChangedWasRaised; protected static string newFullText; protected static string raisedWithFullText; Establish context = () => { newFullText = "new Text"; _windowManipulator_Mock .Setup(wm => wm.SetTextTo(Moq.It.IsAny<string>(), Moq.It.IsAny<Action<string>>())) .Callback((string s1, Action<string> cb) => cb(newFullText)); _sut.TableChanged += ft => { raisedWithFullText = ft; tableChangedWasRaised = true; }; }; Because of = () => _watchTableTimer_Stub.Raise(wt => wt.Tick += null, null, null); It should_start_waiting_for_a_new_table_name = () => _sut.WaitingForNewTableName.ShouldBeTrue(); It should_tell_me_that_the_table_changed = () => tableChangedWasRaised.ShouldBeTrue(); It should_tell_me_the_new_title_of_the_table = () => raisedWithFullText.ShouldEqual(newFullText); } [Subject(typeof(OverlayToTableAttacher), "SetTableName")] public class when_table_name_is_set_while_waiting_for_new_table_name { Establish context = () => _sut.SetWaitingForNewTableName(true); Because of = () => _sut.TableName = _tableName; It should_stop_waiting_for_a_new_table_name = () => _sut.WaitingForNewTableName.ShouldBeFalse(); It should_set_the_tablename_to_the_adapted_name_returned_by_the_pokerroom_info = () => _sut.TableName.ShouldEqual(_adjustedTableName); } [Subject(typeof(OverlayToTableAttacher), "Table is lost")] public class when_the_window_manipulator_says_it_lost_the_table_while_trying_to_place_the_overlay_on_top_of_it : OverlayToTableAttacherSpecs { Establish context = () => _windowManipulator_Mock .Setup(wm => wm.PlaceThisWindowDirectlyOnTopOfYours(Moq.It.IsAny<IWindowManager>(), Moq.It.IsAny<Action>())) .Callback((IWindowManager _, Action tableLostCallback) => tableLostCallback()); Because of = () => _watchTableTimer_Stub.Raise(wt => wt.Tick += null, null, null); It should_stop_to_watch_the_table = () => _watchTableTimer_Stub.Verify(wt => wt.Stop()); It should_try_to_find_the_table_again = () => _findTableAgainTimer_Mock.Verify(ft => ft.Start()); } [Subject(typeof(OverlayToTableAttacher), "Finding table again")] public class when_the_find_table_again_timer_fires : OverlayToTableAttacherSpecs { Because of = () => _findTableAgainTimer_Mock.Raise(ft => ft.Tick += null, null, null); It should_try_to_find_the_poker_table = () => _windowFinder_Mock.Verify( wf => wf.FindWindowMatching(Moq.It.IsAny<Regex>(), Moq.It.IsAny<Regex>(), Moq.It.IsAny<Func<IntPtr, bool>>())); } [Subject(typeof(OverlayToTableAttacher), "Dispose")] public class when_it_is_disposed : OverlayToTableAttacherSpecs { Because of = () => _sut.Dispose(); It should_stop_the_watcher_timer = () => _watchTableTimer_Stub.Verify(wt => wt.Stop()); It should_stop_the_find_table_again_timer = () => _findTableAgainTimer_Mock.Verify(ft => ft.Stop()); It should_dispose_the_overlay_window = () => _overlayWindow_Mock.Verify(ow => ow.Dispose()); } } public class OverlayToTableAttacherSut : OverlayToTableAttacher { public OverlayToTableAttacherSut(IWindowManipulator windowManipulator, IWindowFinder windowFinder) : base(windowManipulator, windowFinder) { } public OverlayToTableAttacherSut SetWaitingForNewTableName(bool waiting) { _waitingForNewTableName = true; return this; } public bool WaitingForNewTableName { get { return _waitingForNewTableName; } } } }
// 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.Globalization; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Diagnostics; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.Threading; using Microsoft.Xml; using SessionIdleManager = System.ServiceModel.Channels.ServiceChannel.SessionIdleManager; namespace System.ServiceModel.Dispatcher { internal class ChannelHandler { public static readonly TimeSpan CloseAfterFaultTimeout = TimeSpan.FromSeconds(10); public const string MessageBufferPropertyName = "_RequestMessageBuffer_"; private readonly IChannelBinder _binder; private readonly DuplexChannelBinder _duplexBinder; private readonly bool _incrementedActivityCountInConstructor; private readonly bool _isCallback; private readonly ListenerHandler _listener; private readonly SessionIdleManager _idleManager; private readonly bool _sendAsynchronously; private static AsyncCallback s_onAsyncReplyComplete = Fx.ThunkCallback(new AsyncCallback(ChannelHandler.OnAsyncReplyComplete)); private static AsyncCallback s_onAsyncReceiveComplete = Fx.ThunkCallback(new AsyncCallback(ChannelHandler.OnAsyncReceiveComplete)); private static Action<object> s_onContinueAsyncReceive = new Action<object>(ChannelHandler.OnContinueAsyncReceive); private static Action<object> s_onStartSyncMessagePump = new Action<object>(ChannelHandler.OnStartSyncMessagePump); private static Action<object> s_onStartAsyncMessagePump = new Action<object>(ChannelHandler.OnStartAsyncMessagePump); private static Action<object> s_openAndEnsurePump = new Action<object>(ChannelHandler.OpenAndEnsurePump); private RequestInfo _requestInfo; private ServiceChannel _channel; private bool _doneReceiving; private bool _hasRegisterBeenCalled; private bool _hasSession; private int _isPumpAcquired; private bool _isConcurrent; private bool _isManualAddressing; private MessageVersion _messageVersion; private ErrorHandlingReceiver _receiver; private bool _receiveSynchronously; private RequestContext _replied; private EventTraceActivity _eventTraceActivity; private bool _shouldRejectMessageWithOnOpenActionHeader; private object _acquirePumpLock = new object(); internal ChannelHandler(MessageVersion messageVersion, IChannelBinder binder, ServiceChannel channel) { ClientRuntime clientRuntime = channel.ClientRuntime; _messageVersion = messageVersion; _isManualAddressing = clientRuntime.ManualAddressing; _binder = binder; _channel = channel; _isConcurrent = true; _duplexBinder = binder as DuplexChannelBinder; _hasSession = binder.HasSession; _isCallback = true; DispatchRuntime dispatchRuntime = clientRuntime.DispatchRuntime; if (dispatchRuntime == null) { _receiver = new ErrorHandlingReceiver(binder, null); } else { _receiver = new ErrorHandlingReceiver(binder, dispatchRuntime.ChannelDispatcher); } _requestInfo = new RequestInfo(this); } internal ChannelHandler(MessageVersion messageVersion, IChannelBinder binder, ListenerHandler listener, SessionIdleManager idleManager) { ChannelDispatcher channelDispatcher = listener.ChannelDispatcher; _messageVersion = messageVersion; _isManualAddressing = channelDispatcher.ManualAddressing; _binder = binder; _listener = listener; _receiveSynchronously = channelDispatcher.ReceiveSynchronously; _sendAsynchronously = channelDispatcher.SendAsynchronously; _duplexBinder = binder as DuplexChannelBinder; _hasSession = binder.HasSession; _isConcurrent = ConcurrencyBehavior.IsConcurrent(channelDispatcher, _hasSession); if (channelDispatcher.MaxPendingReceives > 1) { throw NotImplemented.ByDesign; } if (channelDispatcher.BufferedReceiveEnabled) { _binder = new BufferedReceiveBinder(_binder); } _receiver = new ErrorHandlingReceiver(_binder, channelDispatcher); _idleManager = idleManager; Fx.Assert((_idleManager != null) == (_binder.HasSession && _listener.ChannelDispatcher.DefaultCommunicationTimeouts.ReceiveTimeout != TimeSpan.MaxValue), "idle manager is present only when there is a session with a finite receive timeout"); _requestInfo = new RequestInfo(this); if (_listener.State == CommunicationState.Opened) { _listener.ChannelDispatcher.Channels.IncrementActivityCount(); _incrementedActivityCountInConstructor = true; } } internal IChannelBinder Binder { get { return _binder; } } internal ServiceChannel Channel { get { return _channel; } } internal bool HasRegisterBeenCalled { get { return _hasRegisterBeenCalled; } } private bool IsOpen { get { return _binder.Channel.State == CommunicationState.Opened; } } private object ThisLock { get { return this; } } private EventTraceActivity EventTraceActivity { get { if (_eventTraceActivity == null) { _eventTraceActivity = new EventTraceActivity(); } return _eventTraceActivity; } } internal static void Register(ChannelHandler handler) { handler.Register(); } internal static void Register(ChannelHandler handler, RequestContext request) { BufferedReceiveBinder bufferedBinder = handler.Binder as BufferedReceiveBinder; Fx.Assert(bufferedBinder != null, "ChannelHandler.Binder is not a BufferedReceiveBinder"); bufferedBinder.InjectRequest(request); handler.Register(); } private void Register() { _hasRegisterBeenCalled = true; if (_binder.Channel.State == CommunicationState.Created) { ActionItem.Schedule(s_openAndEnsurePump, this); } else { this.EnsurePump(); } } private void AsyncMessagePump() { IAsyncResult result = this.BeginTryReceive(); if ((result != null) && result.CompletedSynchronously) { this.AsyncMessagePump(result); } } private void AsyncMessagePump(IAsyncResult result) { if (WcfEventSource.Instance.ChannelReceiveStopIsEnabled()) { WcfEventSource.Instance.ChannelReceiveStop(this.EventTraceActivity, this.GetHashCode()); } for (; ; ) { RequestContext request; while (!this.EndTryReceive(result, out request)) { result = this.BeginTryReceive(); if ((result == null) || !result.CompletedSynchronously) { return; } } if (!HandleRequest(request, null)) { break; } if (!TryAcquirePump()) { break; } result = this.BeginTryReceive(); if (result == null || !result.CompletedSynchronously) { break; } } } private IAsyncResult BeginTryReceive() { _requestInfo.Cleanup(); if (WcfEventSource.Instance.ChannelReceiveStartIsEnabled()) { WcfEventSource.Instance.ChannelReceiveStart(this.EventTraceActivity, this.GetHashCode()); } return _receiver.BeginTryReceive(TimeSpan.MaxValue, ChannelHandler.s_onAsyncReceiveComplete, this); } private bool DispatchAndReleasePump(RequestContext request, bool cleanThread, OperationContext currentOperationContext) { ServiceChannel channel = _requestInfo.Channel; EndpointDispatcher endpoint = _requestInfo.Endpoint; bool releasedPump = false; try { DispatchRuntime dispatchBehavior = _requestInfo.DispatchRuntime; if (channel == null || dispatchBehavior == null) { Fx.Assert("System.ServiceModel.Dispatcher.ChannelHandler.Dispatch(): (channel == null || dispatchBehavior == null)"); return true; } EventTraceActivity eventTraceActivity = TraceDispatchMessageStart(request.RequestMessage); Message message = request.RequestMessage; DispatchOperationRuntime operation = dispatchBehavior.GetOperation(ref message); if (operation == null) { Fx.Assert("ChannelHandler.Dispatch (operation == null)"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "No DispatchOperationRuntime found to process message."))); } if (_shouldRejectMessageWithOnOpenActionHeader && message.Headers.Action == OperationDescription.SessionOpenedAction) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxNoEndpointMatchingAddressForConnectionOpeningMessage, message.Headers.Action, "Open"))); } if (MessageLogger.LoggingEnabled) { MessageLogger.LogMessage(ref message, (operation.IsOneWay ? MessageLoggingSource.ServiceLevelReceiveDatagram : MessageLoggingSource.ServiceLevelReceiveRequest) | MessageLoggingSource.LastChance); } bool hasOperationContextBeenSet; if (currentOperationContext != null) { hasOperationContextBeenSet = true; currentOperationContext.ReInit(request, message, channel); } else { hasOperationContextBeenSet = false; currentOperationContext = new OperationContext(request, message, channel); } MessageRpc rpc = new MessageRpc(request, message, operation, channel, this, cleanThread, currentOperationContext, _requestInfo.ExistingInstanceContext, eventTraceActivity); TraceUtility.MessageFlowAtMessageReceived(message, currentOperationContext, eventTraceActivity, true); // These need to happen before Dispatch but after accessing any ChannelHandler // state, because we go multi-threaded after this until we reacquire pump mutex. ReleasePump(); releasedPump = true; return operation.Parent.Dispatch(ref rpc, hasOperationContextBeenSet); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } return this.HandleError(e, request, channel); } finally { if (!releasedPump) { this.ReleasePump(); } } } internal void DispatchDone() { } private bool EndTryReceive(IAsyncResult result, out RequestContext requestContext) { bool valid; { valid = _receiver.EndTryReceive(result, out requestContext); } if (valid) { this.HandleReceiveComplete(requestContext); } return valid; } private void EnsureChannelAndEndpoint(RequestContext request) { _requestInfo.Channel = _channel; if (_requestInfo.Channel == null) { bool addressMatched; if (_hasSession) { _requestInfo.Channel = this.GetSessionChannel(request.RequestMessage, out _requestInfo.Endpoint, out addressMatched); } else { _requestInfo.Channel = this.GetDatagramChannel(request.RequestMessage, out _requestInfo.Endpoint, out addressMatched); } if (_requestInfo.Channel == null) { if (addressMatched) { this.ReplyContractFilterDidNotMatch(request); } else { this.ReplyAddressFilterDidNotMatch(request); } } } else { _requestInfo.Endpoint = _requestInfo.Channel.EndpointDispatcher; } _requestInfo.EndpointLookupDone = true; if (_requestInfo.Channel == null) { // SFx drops a message here TraceUtility.TraceDroppedMessage(request.RequestMessage, _requestInfo.Endpoint); request.Close(); return; } if (_requestInfo.Channel.HasSession || _isCallback) { _requestInfo.DispatchRuntime = _requestInfo.Channel.DispatchRuntime; } else { _requestInfo.DispatchRuntime = _requestInfo.Endpoint.DispatchRuntime; } } private void EnsurePump() { if (TryAcquirePump()) { if (_receiveSynchronously) { ActionItem.Schedule(ChannelHandler.s_onStartSyncMessagePump, this); } else { IAsyncResult result = this.BeginTryReceive(); if ((result != null) && result.CompletedSynchronously) { ActionItem.Schedule(ChannelHandler.s_onContinueAsyncReceive, result); } } } } private ServiceChannel GetDatagramChannel(Message message, out EndpointDispatcher endpoint, out bool addressMatched) { addressMatched = false; endpoint = this.GetEndpointDispatcher(message, out addressMatched); if (endpoint == null) { return null; } if (endpoint.DatagramChannel == null) { lock (_listener.ThisLock) { if (endpoint.DatagramChannel == null) { endpoint.DatagramChannel = new ServiceChannel(_binder, endpoint, _listener.ChannelDispatcher, _idleManager); this.InitializeServiceChannel(endpoint.DatagramChannel); } } } return endpoint.DatagramChannel; } private EndpointDispatcher GetEndpointDispatcher(Message message, out bool addressMatched) { return _listener.Endpoints.Lookup(message, out addressMatched); } private ServiceChannel GetSessionChannel(Message message, out EndpointDispatcher endpoint, out bool addressMatched) { addressMatched = false; if (_channel == null) { lock (this.ThisLock) { if (_channel == null) { endpoint = this.GetEndpointDispatcher(message, out addressMatched); if (endpoint != null) { _channel = new ServiceChannel(_binder, endpoint, _listener.ChannelDispatcher, _idleManager); this.InitializeServiceChannel(_channel); } } } } if (_channel == null) { endpoint = null; } else { endpoint = _channel.EndpointDispatcher; } return _channel; } private void InitializeServiceChannel(ServiceChannel channel) { ClientRuntime clientRuntime = channel.ClientRuntime; if (clientRuntime != null) { Type contractType = clientRuntime.ContractClientType; Type callbackType = clientRuntime.CallbackClientType; if (contractType != null) { channel.Proxy = ServiceChannelFactory.CreateProxy(contractType, callbackType, MessageDirection.Output, channel); } } if (_listener != null) { _listener.ChannelDispatcher.InitializeChannel((IClientChannel)channel.Proxy); } ((IChannel)channel).Open(); } private void ProvideFault(Exception e, ref ErrorHandlerFaultInfo faultInfo) { if (_listener != null) { _listener.ChannelDispatcher.ProvideFault(e, _requestInfo.Channel == null ? _binder.Channel.GetProperty<FaultConverter>() : _requestInfo.Channel.GetProperty<FaultConverter>(), ref faultInfo); } else if (_channel != null) { DispatchRuntime dispatchBehavior = _channel.ClientRuntime.CallbackDispatchRuntime; dispatchBehavior.ChannelDispatcher.ProvideFault(e, _channel.GetProperty<FaultConverter>(), ref faultInfo); } } internal bool HandleError(Exception e) { ErrorHandlerFaultInfo dummy = new ErrorHandlerFaultInfo(); return this.HandleError(e, ref dummy); } private bool HandleError(Exception e, ref ErrorHandlerFaultInfo faultInfo) { if (!(e != null)) { Fx.Assert(SRServiceModel.SFxNonExceptionThrown); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.SFxNonExceptionThrown)); } if (_listener != null) { return _listener.ChannelDispatcher.HandleError(e, ref faultInfo); } else if (_channel != null) { return _channel.ClientRuntime.CallbackDispatchRuntime.ChannelDispatcher.HandleError(e, ref faultInfo); } else { return false; } } private bool HandleError(Exception e, RequestContext request, ServiceChannel channel) { ErrorHandlerFaultInfo faultInfo = new ErrorHandlerFaultInfo(_messageVersion.Addressing.DefaultFaultAction); bool replied, replySentAsync; ProvideFaultAndReplyFailure(request, e, ref faultInfo, out replied, out replySentAsync); if (!replySentAsync) { return this.HandleErrorContinuation(e, request, channel, ref faultInfo, replied); } else { return false; } } private bool HandleErrorContinuation(Exception e, RequestContext request, ServiceChannel channel, ref ErrorHandlerFaultInfo faultInfo, bool replied) { if (replied) { try { request.Close(); } catch (Exception e1) { if (Fx.IsFatal(e1)) { throw; } this.HandleError(e1); } } else { request.Abort(); } if (!this.HandleError(e, ref faultInfo) && _hasSession) { if (channel != null) { if (replied) { TimeoutHelper timeoutHelper = new TimeoutHelper(CloseAfterFaultTimeout); try { channel.Close(timeoutHelper.RemainingTime()); } catch (Exception e2) { if (Fx.IsFatal(e2)) { throw; } this.HandleError(e2); } try { _binder.CloseAfterFault(timeoutHelper.RemainingTime()); } catch (Exception e3) { if (Fx.IsFatal(e3)) { throw; } this.HandleError(e3); } } else { channel.Abort(); _binder.Abort(); } } else { if (replied) { try { _binder.CloseAfterFault(CloseAfterFaultTimeout); } catch (Exception e4) { if (Fx.IsFatal(e4)) { throw; } this.HandleError(e4); } } else { _binder.Abort(); } } } return true; } private void HandleReceiveComplete(RequestContext context) { try { if (_channel != null) { _channel.HandleReceiveComplete(context); } else { if (context == null && _hasSession) { bool close; lock (this.ThisLock) { close = !_doneReceiving; _doneReceiving = true; } if (close) { _receiver.Close(); if (_idleManager != null) { _idleManager.CancelTimer(); } } } } } finally { if ((context == null) && _incrementedActivityCountInConstructor) { _listener.ChannelDispatcher.Channels.DecrementActivityCount(); } } } private bool HandleRequest(RequestContext request, OperationContext currentOperationContext) { if (request == null) { // channel EOF, stop receiving return false; } ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? TraceUtility.ExtractActivity(request.RequestMessage) : null; using (ServiceModelActivity.BoundOperation(activity)) { if (this.HandleRequestAsReply(request)) { this.ReleasePump(); return true; } if (_requestInfo.RequestContext != null) { Fx.Assert("ChannelHandler.HandleRequest: this.requestInfo.RequestContext != null"); } _requestInfo.RequestContext = request; if (!this.TryRetrievingInstanceContext(request)) { //Would have replied and close the request. return true; } _requestInfo.Channel.CompletedIOOperation(); if (!this.DispatchAndReleasePump(request, true, currentOperationContext)) { // this.DispatchDone will be called to continue return false; } } return true; } private bool HandleRequestAsReply(RequestContext request) { if (_duplexBinder != null) { if (_duplexBinder.HandleRequestAsReply(request.RequestMessage)) { return true; } } return false; } private static void OnStartAsyncMessagePump(object state) { ((ChannelHandler)state).AsyncMessagePump(); } private static void OnStartSyncMessagePump(object state) { ChannelHandler handler = state as ChannelHandler; if (WcfEventSource.Instance.ChannelReceiveStopIsEnabled()) { WcfEventSource.Instance.ChannelReceiveStop(handler.EventTraceActivity, state.GetHashCode()); } handler.SyncMessagePump(); } private static void OnAsyncReceiveComplete(IAsyncResult result) { if (!result.CompletedSynchronously) { ((ChannelHandler)result.AsyncState).AsyncMessagePump(result); } } private static void OnContinueAsyncReceive(object state) { IAsyncResult result = (IAsyncResult)state; ((ChannelHandler)result.AsyncState).AsyncMessagePump(result); } private static void OpenAndEnsurePump(object state) { ((ChannelHandler)state).OpenAndEnsurePump(); } private void OpenAndEnsurePump() { Exception exception = null; try { _binder.Channel.Open(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } if (exception != null) { SessionIdleManager idleManager = _idleManager; if (idleManager != null) { idleManager.CancelTimer(); } bool errorHandled = this.HandleError(exception); if (_incrementedActivityCountInConstructor) { _listener.ChannelDispatcher.Channels.DecrementActivityCount(); } if (!errorHandled) { _binder.Channel.Abort(); } } else { this.EnsurePump(); } } private bool TryReceive(TimeSpan timeout, out RequestContext requestContext) { _shouldRejectMessageWithOnOpenActionHeader = false; bool valid = _receiver.TryReceive(timeout, out requestContext); if (valid) { this.HandleReceiveComplete(requestContext); } return valid; } private void ReplyAddressFilterDidNotMatch(RequestContext request) { FaultCode code = FaultCode.CreateSenderFaultCode(AddressingStrings.DestinationUnreachable, _messageVersion.Addressing.Namespace); string reason = string.Format(SRServiceModel.SFxNoEndpointMatchingAddress, request.RequestMessage.Headers.To); ReplyFailure(request, code, reason); } private void ReplyContractFilterDidNotMatch(RequestContext request) { // By default, the contract filter is just a filter over the set of initiating actions in // the contract, so we do error messages accordingly AddressingVersion addressingVersion = _messageVersion.Addressing; if (addressingVersion != AddressingVersion.None && request.RequestMessage.Headers.Action == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new MessageHeaderException( string.Format(SRServiceModel.SFxMissingActionHeader, addressingVersion.Namespace), AddressingStrings.Action, addressingVersion.Namespace)); } else { // some of this code is duplicated in DispatchRuntime.UnhandledActionInvoker // ideally both places would use FaultConverter and ActionNotSupportedException FaultCode code = FaultCode.CreateSenderFaultCode(AddressingStrings.ActionNotSupported, _messageVersion.Addressing.Namespace); string reason = string.Format(SRServiceModel.SFxNoEndpointMatchingContract, request.RequestMessage.Headers.Action); ReplyFailure(request, code, reason, _messageVersion.Addressing.FaultAction); } } private void ReplyFailure(RequestContext request, FaultCode code, string reason) { string action = _messageVersion.Addressing.DefaultFaultAction; ReplyFailure(request, code, reason, action); } private void ReplyFailure(RequestContext request, FaultCode code, string reason, string action) { Message fault = Message.CreateMessage(_messageVersion, code, reason, action); ReplyFailure(request, fault, action, reason, code); } private void ReplyFailure(RequestContext request, Message fault, string action, string reason, FaultCode code) { FaultException exception = new FaultException(reason, code); ErrorBehavior.ThrowAndCatch(exception); ErrorHandlerFaultInfo faultInfo = new ErrorHandlerFaultInfo(action); faultInfo.Fault = fault; bool replied, replySentAsync; ProvideFaultAndReplyFailure(request, exception, ref faultInfo, out replied, out replySentAsync); this.HandleError(exception, ref faultInfo); } private void ProvideFaultAndReplyFailure(RequestContext request, Exception exception, ref ErrorHandlerFaultInfo faultInfo, out bool replied, out bool replySentAsync) { replied = false; replySentAsync = false; bool requestMessageIsFault = false; try { requestMessageIsFault = request.RequestMessage.IsFault; } #pragma warning disable 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } // do not propagate non-fatal exceptions } bool enableFaults = false; if (_listener != null) { enableFaults = _listener.ChannelDispatcher.EnableFaults; } else if (_channel != null && _channel.IsClient) { enableFaults = _channel.ClientRuntime.EnableFaults; } if ((!requestMessageIsFault) && enableFaults) { this.ProvideFault(exception, ref faultInfo); if (faultInfo.Fault != null) { Message reply = faultInfo.Fault; try { try { if (this.PrepareReply(request, reply)) { if (_sendAsynchronously) { var state = new ContinuationState { ChannelHandler = this, Channel = _channel, Exception = exception, FaultInfo = faultInfo, Request = request, Reply = reply }; var result = request.BeginReply(reply, ChannelHandler.s_onAsyncReplyComplete, state); if (result.CompletedSynchronously) { ChannelHandler.AsyncReplyComplete(result, state); replied = true; } else { replySentAsync = true; } } else { request.Reply(reply); replied = true; } } } finally { if (!replySentAsync) { reply.Close(); } } } #pragma warning disable 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.HandleError(e); } } } } /// <summary> /// Prepares a reply that can either be sent asynchronously or synchronously depending on the value of /// sendAsynchronously /// </summary> /// <param name="request">The request context to prepare</param> /// <param name="reply">The reply to prepare</param> /// <returns>True if channel is open and prepared reply should be sent; otherwise false.</returns> private bool PrepareReply(RequestContext request, Message reply) { // Ensure we only reply once (we may hit the same error multiple times) if (_replied == request) { return false; } _replied = request; bool canSendReply = true; Message requestMessage = null; try { requestMessage = request.RequestMessage; } #pragma warning disable 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } // do not propagate non-fatal exceptions } if (!object.ReferenceEquals(requestMessage, null)) { UniqueId requestID = null; try { requestID = requestMessage.Headers.MessageId; } catch (MessageHeaderException) { // Do not propagate this exception - we don't need to correlate the reply if the MessageId header is bad } if (!object.ReferenceEquals(requestID, null) && !_isManualAddressing) { System.ServiceModel.Channels.RequestReplyCorrelator.PrepareReply(reply, requestID); } if (!_hasSession && !_isManualAddressing) { try { canSendReply = System.ServiceModel.Channels.RequestReplyCorrelator.AddressReply(reply, requestMessage); } catch (MessageHeaderException) { // Do not propagate this exception - we don't need to address the reply if the FaultTo header is bad } } } // ObjectDisposeException can happen // if the channel is closed in a different // thread. 99% this check will avoid false // exceptions. return this.IsOpen && canSendReply; } private static void AsyncReplyComplete(IAsyncResult result, ContinuationState state) { try { state.Request.EndReply(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } state.ChannelHandler.HandleError(e); } try { state.Reply.Close(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } state.ChannelHandler.HandleError(e); } try { state.ChannelHandler.HandleErrorContinuation(state.Exception, state.Request, state.Channel, ref state.FaultInfo, true); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } state.ChannelHandler.HandleError(e); } state.ChannelHandler.EnsurePump(); } private static void OnAsyncReplyComplete(IAsyncResult result) { if (result.CompletedSynchronously) { return; } try { var state = (ContinuationState)result.AsyncState; ChannelHandler.AsyncReplyComplete(result, state); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } } } private void ReleasePump() { if (_isConcurrent) { lock (_acquirePumpLock) { _isPumpAcquired = 0; } } } private void SyncMessagePump() { OperationContext existingOperationContext = OperationContext.Current; try { OperationContext currentOperationContext = new OperationContext(); OperationContext.Current = currentOperationContext; for (; ; ) { RequestContext request; _requestInfo.Cleanup(); while (!TryReceive(TimeSpan.MaxValue, out request)) { } if (!HandleRequest(request, currentOperationContext)) { break; } if (!TryAcquirePump()) { break; } currentOperationContext.Recycle(); } } finally { OperationContext.Current = existingOperationContext; } } //Return: False denotes failure, Caller should discard the request. // : True denotes operation is successful. private bool TryRetrievingInstanceContext(RequestContext request) { bool releasePump = true; try { if (!_requestInfo.EndpointLookupDone) { this.EnsureChannelAndEndpoint(request); } if (_requestInfo.Channel == null) { return false; } if (_requestInfo.DispatchRuntime != null) { IContextChannel transparentProxy = _requestInfo.Channel.Proxy as IContextChannel; try { _requestInfo.ExistingInstanceContext = _requestInfo.DispatchRuntime.InstanceContextProvider.GetExistingInstanceContext(request.RequestMessage, transparentProxy); releasePump = false; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } _requestInfo.Channel = null; this.HandleError(e, request, _channel); return false; } } else { // This can happen if we are pumping for an async client, // and we receive a bogus reply. In that case, there is no // DispatchRuntime, because we are only expecting replies. // // One possible fix for this would be in DuplexChannelBinder // to drop all messages with a RelatesTo that do not match a // pending request. // // However, that would not fix: // (a) we could get a valid request message with a // RelatesTo that we should try to process. // (b) we could get a reply message that does not have // a RelatesTo. // // So we do the null check here. // // SFx drops a message here TraceUtility.TraceDroppedMessage(request.RequestMessage, _requestInfo.Endpoint); request.Close(); return false; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.HandleError(e, request, _channel); return false; } finally { if (releasePump) { this.ReleasePump(); } } return true; } private bool TryAcquirePump() { if (_isConcurrent) { lock (_acquirePumpLock) { if (_isPumpAcquired != 0) { return false; } _isPumpAcquired = 1; return true; } } return true; } private struct RequestInfo { public EndpointDispatcher Endpoint; public InstanceContext ExistingInstanceContext; public ServiceChannel Channel; public bool EndpointLookupDone; public DispatchRuntime DispatchRuntime; public RequestContext RequestContext; public ChannelHandler ChannelHandler; public RequestInfo(ChannelHandler channelHandler) { this.Endpoint = null; this.ExistingInstanceContext = null; this.Channel = null; this.EndpointLookupDone = false; this.DispatchRuntime = null; this.RequestContext = null; this.ChannelHandler = channelHandler; } public void Cleanup() { this.Endpoint = null; this.ExistingInstanceContext = null; this.Channel = null; this.EndpointLookupDone = false; this.RequestContext = null; } } private EventTraceActivity TraceDispatchMessageStart(Message message) { if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && message != null) { EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); if (WcfEventSource.Instance.DispatchMessageStartIsEnabled()) { WcfEventSource.Instance.DispatchMessageStart(eventTraceActivity); } return eventTraceActivity; } return null; } /// <summary> /// Data structure used to carry state for asynchronous replies /// </summary> private struct ContinuationState { public ChannelHandler ChannelHandler; public Exception Exception; public RequestContext Request; public Message Reply; public ServiceChannel Channel; public ErrorHandlerFaultInfo FaultInfo; } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Wgl { /// <summary> /// [WGL] Value of WGL_GENLOCK_SOURCE_MULTIVIEW_I3D symbol. /// </summary> [RequiredByFeature("WGL_I3D_genlock")] public const int GENLOCK_SOURCE_MULTIVIEW_I3D = 0x2044; /// <summary> /// [WGL] Value of WGL_GENLOCK_SOURCE_EXTERNAL_SYNC_I3D symbol. /// </summary> [RequiredByFeature("WGL_I3D_genlock")] public const int GENLOCK_SOURCE_EXTERNAL_SYNC_I3D = 0x2045; /// <summary> /// [WGL] Value of WGL_GENLOCK_SOURCE_EXTERNAL_FIELD_I3D symbol. /// </summary> [RequiredByFeature("WGL_I3D_genlock")] public const int GENLOCK_SOURCE_EXTERNAL_FIELD_I3D = 0x2046; /// <summary> /// [WGL] Value of WGL_GENLOCK_SOURCE_EXTERNAL_TTL_I3D symbol. /// </summary> [RequiredByFeature("WGL_I3D_genlock")] public const int GENLOCK_SOURCE_EXTERNAL_TTL_I3D = 0x2047; /// <summary> /// [WGL] Value of WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D symbol. /// </summary> [RequiredByFeature("WGL_I3D_genlock")] public const int GENLOCK_SOURCE_DIGITAL_SYNC_I3D = 0x2048; /// <summary> /// [WGL] Value of WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D symbol. /// </summary> [RequiredByFeature("WGL_I3D_genlock")] public const int GENLOCK_SOURCE_DIGITAL_FIELD_I3D = 0x2049; /// <summary> /// [WGL] Value of WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D symbol. /// </summary> [RequiredByFeature("WGL_I3D_genlock")] public const int GENLOCK_SOURCE_EDGE_FALLING_I3D = 0x204A; /// <summary> /// [WGL] Value of WGL_GENLOCK_SOURCE_EDGE_RISING_I3D symbol. /// </summary> [RequiredByFeature("WGL_I3D_genlock")] public const int GENLOCK_SOURCE_EDGE_RISING_I3D = 0x204B; /// <summary> /// [WGL] Value of WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D symbol. /// </summary> [RequiredByFeature("WGL_I3D_genlock")] public const int GENLOCK_SOURCE_EDGE_BOTH_I3D = 0x204C; /// <summary> /// [WGL] wglEnableGenlockI3D: Binding for wglEnableGenlockI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool EnableGenlockI3D(IntPtr hDC) { bool retValue; Debug.Assert(Delegates.pwglEnableGenlockI3D != null, "pwglEnableGenlockI3D not implemented"); retValue = Delegates.pwglEnableGenlockI3D(hDC); LogCommand("wglEnableGenlockI3D", retValue, hDC ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglDisableGenlockI3D: Binding for wglDisableGenlockI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool DisableGenlockI3D(IntPtr hDC) { bool retValue; Debug.Assert(Delegates.pwglDisableGenlockI3D != null, "pwglDisableGenlockI3D not implemented"); retValue = Delegates.pwglDisableGenlockI3D(hDC); LogCommand("wglDisableGenlockI3D", retValue, hDC ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglIsEnabledGenlockI3D: Binding for wglIsEnabledGenlockI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="pFlag"> /// A <see cref="T:bool[]"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool IsEnabledGenlockI3D(IntPtr hDC, [Out] bool[] pFlag) { bool retValue; unsafe { fixed (bool* p_pFlag = pFlag) { Debug.Assert(Delegates.pwglIsEnabledGenlockI3D != null, "pwglIsEnabledGenlockI3D not implemented"); retValue = Delegates.pwglIsEnabledGenlockI3D(hDC, p_pFlag); LogCommand("wglIsEnabledGenlockI3D", retValue, hDC, pFlag ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglGenlockSourceI3D: Binding for wglGenlockSourceI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="uSource"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool GenlockSourceI3D(IntPtr hDC, uint uSource) { bool retValue; Debug.Assert(Delegates.pwglGenlockSourceI3D != null, "pwglGenlockSourceI3D not implemented"); retValue = Delegates.pwglGenlockSourceI3D(hDC, uSource); LogCommand("wglGenlockSourceI3D", retValue, hDC, uSource ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglGetGenlockSourceI3D: Binding for wglGetGenlockSourceI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="uSource"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool GetGenlockSourceI3D(IntPtr hDC, [Out] uint[] uSource) { bool retValue; unsafe { fixed (uint* p_uSource = uSource) { Debug.Assert(Delegates.pwglGetGenlockSourceI3D != null, "pwglGetGenlockSourceI3D not implemented"); retValue = Delegates.pwglGetGenlockSourceI3D(hDC, p_uSource); LogCommand("wglGetGenlockSourceI3D", retValue, hDC, uSource ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglGenlockSourceEdgeI3D: Binding for wglGenlockSourceEdgeI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="uEdge"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool GenlockSourceEdgeI3D(IntPtr hDC, uint uEdge) { bool retValue; Debug.Assert(Delegates.pwglGenlockSourceEdgeI3D != null, "pwglGenlockSourceEdgeI3D not implemented"); retValue = Delegates.pwglGenlockSourceEdgeI3D(hDC, uEdge); LogCommand("wglGenlockSourceEdgeI3D", retValue, hDC, uEdge ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglGetGenlockSourceEdgeI3D: Binding for wglGetGenlockSourceEdgeI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="uEdge"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool GetGenlockSourceEdgeI3D(IntPtr hDC, [Out] uint[] uEdge) { bool retValue; unsafe { fixed (uint* p_uEdge = uEdge) { Debug.Assert(Delegates.pwglGetGenlockSourceEdgeI3D != null, "pwglGetGenlockSourceEdgeI3D not implemented"); retValue = Delegates.pwglGetGenlockSourceEdgeI3D(hDC, p_uEdge); LogCommand("wglGetGenlockSourceEdgeI3D", retValue, hDC, uEdge ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglGenlockSampleRateI3D: Binding for wglGenlockSampleRateI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="uRate"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool GenlockSampleRateI3D(IntPtr hDC, uint uRate) { bool retValue; Debug.Assert(Delegates.pwglGenlockSampleRateI3D != null, "pwglGenlockSampleRateI3D not implemented"); retValue = Delegates.pwglGenlockSampleRateI3D(hDC, uRate); LogCommand("wglGenlockSampleRateI3D", retValue, hDC, uRate ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglGetGenlockSampleRateI3D: Binding for wglGetGenlockSampleRateI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="uRate"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool GetGenlockSampleRateI3D(IntPtr hDC, [Out] uint[] uRate) { bool retValue; unsafe { fixed (uint* p_uRate = uRate) { Debug.Assert(Delegates.pwglGetGenlockSampleRateI3D != null, "pwglGetGenlockSampleRateI3D not implemented"); retValue = Delegates.pwglGetGenlockSampleRateI3D(hDC, p_uRate); LogCommand("wglGetGenlockSampleRateI3D", retValue, hDC, uRate ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglGenlockSourceDelayI3D: Binding for wglGenlockSourceDelayI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="uDelay"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool GenlockSourceDelayI3D(IntPtr hDC, uint uDelay) { bool retValue; Debug.Assert(Delegates.pwglGenlockSourceDelayI3D != null, "pwglGenlockSourceDelayI3D not implemented"); retValue = Delegates.pwglGenlockSourceDelayI3D(hDC, uDelay); LogCommand("wglGenlockSourceDelayI3D", retValue, hDC, uDelay ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglGetGenlockSourceDelayI3D: Binding for wglGetGenlockSourceDelayI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="uDelay"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool GetGenlockSourceDelayI3D(IntPtr hDC, [Out] uint[] uDelay) { bool retValue; unsafe { fixed (uint* p_uDelay = uDelay) { Debug.Assert(Delegates.pwglGetGenlockSourceDelayI3D != null, "pwglGetGenlockSourceDelayI3D not implemented"); retValue = Delegates.pwglGetGenlockSourceDelayI3D(hDC, p_uDelay); LogCommand("wglGetGenlockSourceDelayI3D", retValue, hDC, uDelay ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglQueryGenlockMaxSourceDelayI3D: Binding for wglQueryGenlockMaxSourceDelayI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="uMaxLineDelay"> /// A <see cref="T:uint[]"/>. /// </param> /// <param name="uMaxPixelDelay"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("WGL_I3D_genlock")] public static bool QueryGenlockMaxSourceDelayI3D(IntPtr hDC, uint[] uMaxLineDelay, uint[] uMaxPixelDelay) { bool retValue; unsafe { fixed (uint* p_uMaxLineDelay = uMaxLineDelay) fixed (uint* p_uMaxPixelDelay = uMaxPixelDelay) { Debug.Assert(Delegates.pwglQueryGenlockMaxSourceDelayI3D != null, "pwglQueryGenlockMaxSourceDelayI3D not implemented"); retValue = Delegates.pwglQueryGenlockMaxSourceDelayI3D(hDC, p_uMaxLineDelay, p_uMaxPixelDelay); LogCommand("wglQueryGenlockMaxSourceDelayI3D", retValue, hDC, uMaxLineDelay, uMaxPixelDelay ); } } DebugCheckErrors(retValue); return (retValue); } internal static unsafe partial class Delegates { [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglEnableGenlockI3D(IntPtr hDC); [RequiredByFeature("WGL_I3D_genlock")] internal static wglEnableGenlockI3D pwglEnableGenlockI3D; [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglDisableGenlockI3D(IntPtr hDC); [RequiredByFeature("WGL_I3D_genlock")] internal static wglDisableGenlockI3D pwglDisableGenlockI3D; [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglIsEnabledGenlockI3D(IntPtr hDC, bool* pFlag); [RequiredByFeature("WGL_I3D_genlock")] internal static wglIsEnabledGenlockI3D pwglIsEnabledGenlockI3D; [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglGenlockSourceI3D(IntPtr hDC, uint uSource); [RequiredByFeature("WGL_I3D_genlock")] internal static wglGenlockSourceI3D pwglGenlockSourceI3D; [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglGetGenlockSourceI3D(IntPtr hDC, uint* uSource); [RequiredByFeature("WGL_I3D_genlock")] internal static wglGetGenlockSourceI3D pwglGetGenlockSourceI3D; [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglGenlockSourceEdgeI3D(IntPtr hDC, uint uEdge); [RequiredByFeature("WGL_I3D_genlock")] internal static wglGenlockSourceEdgeI3D pwglGenlockSourceEdgeI3D; [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglGetGenlockSourceEdgeI3D(IntPtr hDC, uint* uEdge); [RequiredByFeature("WGL_I3D_genlock")] internal static wglGetGenlockSourceEdgeI3D pwglGetGenlockSourceEdgeI3D; [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglGenlockSampleRateI3D(IntPtr hDC, uint uRate); [RequiredByFeature("WGL_I3D_genlock")] internal static wglGenlockSampleRateI3D pwglGenlockSampleRateI3D; [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglGetGenlockSampleRateI3D(IntPtr hDC, uint* uRate); [RequiredByFeature("WGL_I3D_genlock")] internal static wglGetGenlockSampleRateI3D pwglGetGenlockSampleRateI3D; [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglGenlockSourceDelayI3D(IntPtr hDC, uint uDelay); [RequiredByFeature("WGL_I3D_genlock")] internal static wglGenlockSourceDelayI3D pwglGenlockSourceDelayI3D; [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglGetGenlockSourceDelayI3D(IntPtr hDC, uint* uDelay); [RequiredByFeature("WGL_I3D_genlock")] internal static wglGetGenlockSourceDelayI3D pwglGetGenlockSourceDelayI3D; [RequiredByFeature("WGL_I3D_genlock")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglQueryGenlockMaxSourceDelayI3D(IntPtr hDC, uint* uMaxLineDelay, uint* uMaxPixelDelay); [RequiredByFeature("WGL_I3D_genlock")] internal static wglQueryGenlockMaxSourceDelayI3D pwglQueryGenlockMaxSourceDelayI3D; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.ComponentModel; using Microsoft.AspNetCore.Razor.TagHelpers; namespace Microsoft.CodeAnalysis.Razor.Workspaces.Test { public enum CustomEnum { FirstValue, SecondValue } public class EnumTagHelper : TagHelper { public int NonEnumProperty { get; set; } public CustomEnum EnumProperty { get; set; } } [HtmlTargetElement("p")] [HtmlTargetElement("input")] public class MultiEnumTagHelper : EnumTagHelper { } public class NestedEnumTagHelper : EnumTagHelper { public NestedEnum NestedEnumProperty { get; set; } public enum NestedEnum { NestedOne, NestedTwo } } [HtmlTargetElement("input", ParentTag = "div")] public class RequiredParentTagHelper : TagHelper { } [HtmlTargetElement("p", ParentTag = "div")] [HtmlTargetElement("input", ParentTag = "section")] public class MultiSpecifiedRequiredParentTagHelper : TagHelper { } [HtmlTargetElement("p")] [HtmlTargetElement("input", ParentTag = "div")] public class MultiWithUnspecifiedRequiredParentTagHelper : TagHelper { } [RestrictChildren("p")] public class RestrictChildrenTagHelper { } [RestrictChildren("p", "strong")] public class DoubleRestrictChildrenTagHelper { } [HtmlTargetElement("p")] [HtmlTargetElement("div")] [RestrictChildren("p", "strong")] public class MultiTargetRestrictChildrenTagHelper { } [HtmlTargetElement("input", TagStructure = TagStructure.WithoutEndTag)] public class TagStructureTagHelper : TagHelper { } [HtmlTargetElement("p", TagStructure = TagStructure.NormalOrSelfClosing)] [HtmlTargetElement("input", TagStructure = TagStructure.WithoutEndTag)] public class MultiSpecifiedTagStructureTagHelper : TagHelper { } [HtmlTargetElement("p")] [HtmlTargetElement("input", TagStructure = TagStructure.WithoutEndTag)] public class MultiWithUnspecifiedTagStructureTagHelper : TagHelper { } [EditorBrowsable(EditorBrowsableState.Always)] public class DefaultEditorBrowsableTagHelper : TagHelper { [EditorBrowsable(EditorBrowsableState.Always)] public int Property { get; set; } } public class HiddenPropertyEditorBrowsableTagHelper : TagHelper { [EditorBrowsable(EditorBrowsableState.Never)] public int Property { get; set; } } public class MultiPropertyEditorBrowsableTagHelper : TagHelper { [EditorBrowsable(EditorBrowsableState.Never)] public int Property { get; set; } public virtual int Property2 { get; set; } } public class OverriddenPropertyEditorBrowsableTagHelper : MultiPropertyEditorBrowsableTagHelper { [EditorBrowsable(EditorBrowsableState.Never)] public override int Property2 { get; set; } } [EditorBrowsable(EditorBrowsableState.Never)] public class EditorBrowsableTagHelper : TagHelper { [EditorBrowsable(EditorBrowsableState.Never)] public virtual int Property { get; set; } } public class InheritedEditorBrowsableTagHelper : EditorBrowsableTagHelper { public override int Property { get; set; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public class OverriddenEditorBrowsableTagHelper : EditorBrowsableTagHelper { [EditorBrowsable(EditorBrowsableState.Advanced)] public override int Property { get; set; } } [HtmlTargetElement("p")] [HtmlTargetElement("div")] [EditorBrowsable(EditorBrowsableState.Never)] public class MultiEditorBrowsableTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "class*")] public class AttributeWildcardTargetingTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "class*,style*")] public class MultiAttributeWildcardTargetingTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "class")] public class AttributeTargetingTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "class,style")] public class MultiAttributeTargetingTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "custom")] [HtmlTargetElement(Attributes = "class,style")] public class MultiAttributeAttributeTargetingTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "style")] public class InheritedAttributeTargetingTagHelper : AttributeTargetingTagHelper { } [HtmlTargetElement("input", Attributes = "class")] public class RequiredAttributeTagHelper : TagHelper { } [HtmlTargetElement("div", Attributes = "class")] public class InheritedRequiredAttributeTagHelper : RequiredAttributeTagHelper { } [HtmlTargetElement("div", Attributes = "class")] [HtmlTargetElement("input", Attributes = "class")] public class MultiAttributeRequiredAttributeTagHelper : TagHelper { } [HtmlTargetElement("input", Attributes = "style")] [HtmlTargetElement("input", Attributes = "class")] public class MultiAttributeSameTagRequiredAttributeTagHelper : TagHelper { } [HtmlTargetElement("input", Attributes = "class,style")] public class MultiRequiredAttributeTagHelper : TagHelper { } [HtmlTargetElement("div", Attributes = "style")] public class InheritedMultiRequiredAttributeTagHelper : MultiRequiredAttributeTagHelper { } [HtmlTargetElement("div", Attributes = "class,style")] [HtmlTargetElement("input", Attributes = "class,style")] public class MultiTagMultiRequiredAttributeTagHelper : TagHelper { } [HtmlTargetElement("p")] [HtmlTargetElement("div")] public class MultiTagTagHelper { public string ValidAttribute { get; set; } } public class InheritedMultiTagTagHelper : MultiTagTagHelper { } [HtmlTargetElement("p")] [HtmlTargetElement("p")] [HtmlTargetElement("div")] [HtmlTargetElement("div")] public class DuplicateTagNameTagHelper { } [HtmlTargetElement("data-condition")] public class OverrideNameTagHelper { } public class InheritedSingleAttributeTagHelper : SingleAttributeTagHelper { } public class DuplicateAttributeNameTagHelper { public string MyNameIsLegion { get; set; } [HtmlAttributeName("my-name-is-legion")] public string Fred { get; set; } } public class NotBoundAttributeTagHelper { public object BoundProperty { get; set; } [HtmlAttributeNotBound] public string NotBoundProperty { get; set; } [HtmlAttributeName("unused")] [HtmlAttributeNotBound] public string NamedNotBoundProperty { get; set; } } public class OverriddenAttributeTagHelper { [HtmlAttributeName("SomethingElse")] public virtual string ValidAttribute1 { get; set; } [HtmlAttributeName("Something-Else")] public string ValidAttribute2 { get; set; } } public class InheritedOverriddenAttributeTagHelper : OverriddenAttributeTagHelper { public override string ValidAttribute1 { get; set; } } public class InheritedNotOverriddenAttributeTagHelper : OverriddenAttributeTagHelper { } public class ALLCAPSTAGHELPER : TagHelper { public int ALLCAPSATTRIBUTE { get; set; } } public class CAPSOnOUTSIDETagHelper : TagHelper { public int CAPSOnOUTSIDEATTRIBUTE { get; set; } } public class capsONInsideTagHelper : TagHelper { public int capsONInsideattribute { get; set; } } public class One1Two2Three3TagHelper : TagHelper { public int One1Two2Three3Attribute { get; set; } } public class ONE1TWO2THREE3TagHelper : TagHelper { public int ONE1TWO2THREE3Attribute { get; set; } } public class First_Second_ThirdHiTagHelper : TagHelper { public int First_Second_ThirdAttribute { get; set; } } public class UNSuffixedCLASS : TagHelper { public int UNSuffixedATTRIBUTE { get; set; } } public class InvalidBoundAttribute : TagHelper { public string DataSomething { get; set; } } public class InvalidBoundAttributeWithValid : SingleAttributeTagHelper { public string DataSomething { get; set; } } public class OverriddenInvalidBoundAttributeWithValid : TagHelper { [HtmlAttributeName("valid-something")] public string DataSomething { get; set; } } public class OverriddenValidBoundAttributeWithInvalid : TagHelper { [HtmlAttributeName("data-something")] public string ValidSomething { get; set; } } public class OverriddenValidBoundAttributeWithInvalidUpperCase : TagHelper { [HtmlAttributeName("DATA-SOMETHING")] public string ValidSomething { get; set; } } public class DefaultValidHtmlAttributePrefix : TagHelper { public IDictionary<string, string> DictionaryProperty { get; set; } } public class SingleValidHtmlAttributePrefix : TagHelper { [HtmlAttributeName("valid-name")] public IDictionary<string, string> DictionaryProperty { get; set; } } public class MultipleValidHtmlAttributePrefix : TagHelper { [HtmlAttributeName("valid-name1", DictionaryAttributePrefix = "valid-prefix1-")] public Dictionary<string, object> DictionaryProperty { get; set; } [HtmlAttributeName("valid-name2", DictionaryAttributePrefix = "valid-prefix2-")] public DictionarySubclass DictionarySubclassProperty { get; set; } [HtmlAttributeName("valid-name3", DictionaryAttributePrefix = "valid-prefix3-")] public DictionaryWithoutParameterlessConstructor DictionaryWithoutParameterlessConstructorProperty { get; set; } [HtmlAttributeName("valid-name4", DictionaryAttributePrefix = "valid-prefix4-")] public GenericDictionarySubclass<object> GenericDictionarySubclassProperty { get; set; } [HtmlAttributeName("valid-name5", DictionaryAttributePrefix = "valid-prefix5-")] public SortedDictionary<string, int> SortedDictionaryProperty { get; set; } [HtmlAttributeName("valid-name6")] public string StringProperty { get; set; } public IDictionary<string, int> GetOnlyDictionaryProperty { get; } [HtmlAttributeName(DictionaryAttributePrefix = "valid-prefix6")] public IDictionary<string, string> GetOnlyDictionaryPropertyWithAttributePrefix { get; } } public class SingleInvalidHtmlAttributePrefix : TagHelper { [HtmlAttributeName("valid-name", DictionaryAttributePrefix = "valid-prefix")] public string StringProperty { get; set; } } public class MultipleInvalidHtmlAttributePrefix : TagHelper { [HtmlAttributeName("valid-name1")] public long LongProperty { get; set; } [HtmlAttributeName("valid-name2", DictionaryAttributePrefix = "valid-prefix2-")] public Dictionary<int, string> DictionaryOfIntProperty { get; set; } [HtmlAttributeName("valid-name3", DictionaryAttributePrefix = "valid-prefix3-")] public IReadOnlyDictionary<string, object> ReadOnlyDictionaryProperty { get; set; } [HtmlAttributeName("valid-name4", DictionaryAttributePrefix = "valid-prefix4-")] public int IntProperty { get; set; } [HtmlAttributeName("valid-name5", DictionaryAttributePrefix = "valid-prefix5-")] public DictionaryOfIntSubclass DictionaryOfIntSubclassProperty { get; set; } [HtmlAttributeName(DictionaryAttributePrefix = "valid-prefix6")] public IDictionary<int, string> GetOnlyDictionaryAttributePrefix { get; } [HtmlAttributeName("invalid-name7")] public IDictionary<string, object> GetOnlyDictionaryPropertyWithAttributeName { get; } } public class DictionarySubclass : Dictionary<string, string> { } public class DictionaryWithoutParameterlessConstructor : Dictionary<string, string> { public DictionaryWithoutParameterlessConstructor(int count) : base() { } } public class DictionaryOfIntSubclass : Dictionary<int, string> { } public class GenericDictionarySubclass<TValue> : Dictionary<string, TValue> { } [OutputElementHint("strong")] public class OutputElementHintTagHelper : TagHelper { } [HtmlTargetElement("a")] [HtmlTargetElement("p")] [OutputElementHint("div")] public class MultipleDescriptorTagHelperWithOutputElementHint : TagHelper { } public class NonPublicAccessorTagHelper : TagHelper { public string ValidAttribute { get; set; } public string InvalidPrivateSetAttribute { get; private set; } public string InvalidPrivateGetAttribute { private get; set; } protected string InvalidProtectedAttribute { get; set; } internal string InvalidInternalAttribute { get; set; } protected internal string InvalidProtectedInternalAttribute { get; set; } } public class SingleAttributeTagHelper : TagHelper { public int IntAttribute { get; set; } } public class MissingAccessorTagHelper : TagHelper { public string ValidAttribute { get; set; } public string InvalidNoGetAttribute { set { } } public string InvalidNoSetAttribute { get { return string.Empty; } } } }
using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Data.Spatial; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Web.DynamicData.ModelProviders; using System.Web.DynamicData.Util; namespace System.Web.DynamicData { /// <summary> /// Object that represents a database column used by dynamic data /// </summary> public class MetaColumn : IFieldFormattingOptions, IMetaColumn { private TypeCode _typeCode = TypeCode.Empty; private Type _type; private object _metadataCacheLock = new object(); // text, ntext, varchar(max), nvarchar(max) all have different maximum lengths so this is a minimum value // that ensures that all of the abovementioned columns get treated as long strings. private static readonly int s_longStringLengthCutoff = ((Int32.MaxValue >> 1) - 4); // Metadata related members private IMetaColumnMetadata _metadata; private bool? _scaffoldValueManual; private bool? _scaffoldValueDefault; public MetaColumn(MetaTable table, ColumnProvider columnProvider) { Table = table; Provider = columnProvider; } /// <summary> /// The collection of metadata attributes that apply to this column /// </summary> public AttributeCollection Attributes { get { return Metadata.Attributes; } } /// <summary> /// The CLR type of the property/column /// </summary> public Type ColumnType { get { if (_type == null) { // If it's an Nullable<T>, work with T instead _type = Misc.RemoveNullableFromType(Provider.ColumnType); } return _type; } } /// <summary> /// The DataTypeAttribute used for the column /// </summary> public DataTypeAttribute DataTypeAttribute { get { return Metadata.DataTypeAttribute; } } /// <summary> /// This column's defalut value. It is typically used to populate the field when creating a new entry. /// </summary> public object DefaultValue { get { return Metadata.DefaultValue; } } /// <summary> /// A description for this column /// </summary> public virtual string Description { get { // return Metadata.Description; } } /// <summary> /// A friendly display name for this column /// </summary> public virtual string DisplayName { get { // Default to the Name if there is no DisplayName return Metadata.DisplayName ?? Name; } } /// <summary> /// The PropertyInfo of the property that represents this column on the entity type /// </summary> public PropertyInfo EntityTypeProperty { get { return Provider.EntityTypeProperty; } } /// <summary> /// The FilterUIHint used for the column /// </summary> public string FilterUIHint { get { return Metadata.FilterUIHint; } } /// <summary> /// Does this column contain binary data /// </summary> public bool IsBinaryData { get { return ColumnType == typeof(byte[]); } } /// <summary> /// meant to indicate that a member is an extra property that was declared in a partial class /// </summary> public bool IsCustomProperty { get { return Provider.IsCustomProperty; } } /// <summary> /// Is this column a floating point type (float, double, decimal) /// </summary> public bool IsFloatingPoint { get { return ColumnType == typeof(float) || ColumnType == typeof(double) || ColumnType == typeof(decimal); } } /// <summary> /// This is set for columns that are part of a foreign key. Note that it is NOT set for /// the strongly typed entity ref columns (though those columns 'use' one or more columns /// where IsForeignKeyComponent is set). /// </summary> public bool IsForeignKeyComponent { get { return Provider.IsForeignKeyComponent; } } /// <summary> /// Is this column's value auto-generated in the database /// </summary> public bool IsGenerated { get { return Provider.IsGenerated; } } /// <summary> /// Is this column a integer /// </summary> public bool IsInteger { get { return ColumnType == typeof(byte) || ColumnType == typeof(short) || ColumnType == typeof(int) || ColumnType == typeof(long); } } /// <summary> /// Is this column a 'long' string. This is used to determine whether a textbox or textarea should be used. /// </summary> public bool IsLongString { get { return IsString && Provider.MaxLength >= s_longStringLengthCutoff; } } /// <summary> /// Is this column part if the table's primary key /// </summary> public bool IsPrimaryKey { get { return Provider.IsPrimaryKey; } } /// <summary> /// Is this a readonly column /// </summary> [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces", Justification = "Interface denotes existence of property, not used for security.")] public virtual bool IsReadOnly { get { return Provider.IsReadOnly || Metadata.IsReadOnly || (Metadata.EditableAttribute != null && !Metadata.EditableAttribute.AllowEdit); } } /// <summary> /// Specifies if a read-only column (see IsReadOnly) allows for a value to be set on insert. /// The default value is false when the column is read-only; true when the column is not read-only. /// The default value can be override by using EditableAttribute (note that this will indicate that /// the column is meant to be read only). /// </summary> public bool AllowInitialValue { get { if (IsGenerated) { // always return false for generated columns, since that is a stronger statement. return false; } return Metadata.EditableAttribute.GetPropertyValue(a => a.AllowInitialValue, !IsReadOnly); } } /// <summary> /// Does this column require a value /// </summary> public bool IsRequired { get { return Metadata.RequiredAttribute != null; } } /// <summary> /// Is this column a string /// </summary> public bool IsString { get { return ColumnType == typeof(string); } } /// <summary> /// The maximun length allowed for this column (applies to string columns) /// </summary> public int MaxLength { get { var stringLengthAttribute = Metadata.StringLengthAttribute; return stringLengthAttribute != null ? stringLengthAttribute.MaximumLength : Provider.MaxLength; } } /// <summary> /// The MetaModel that this column belongs to /// </summary> public MetaModel Model { get { return Table.Model; } } /// <summary> /// The column's name /// </summary> public string Name { get { return Provider.Name; } } /// <summary> /// A value that can be used as a watermark in UI bound to value represented by this column. /// </summary> public virtual string Prompt { get { return Metadata.Prompt; } } /// <summary> /// the abstraction provider object that was used to construct this metacolumn. /// </summary> public ColumnProvider Provider { get; private set; } /// <summary> /// The error message used if this column is required and it is set to empty /// </summary> public string RequiredErrorMessage { get { var requiredAttribute = Metadata.RequiredAttribute; return requiredAttribute != null ? requiredAttribute.FormatErrorMessage(DisplayName) : String.Empty; } } /// <summary> /// Is it a column that should be displayed (e.g. in a GridView's auto generate mode) /// </summary> [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces", Justification = "Interface denotes existence of property, not used for security.")] public virtual bool Scaffold { get { // If the value was explicitely set, that always takes precedence if (_scaffoldValueManual != null) { return _scaffoldValueManual.Value; } // If there is a DisplayAttribute with an explicit value, always honor it var displayAttribute = Metadata.DisplayAttribute; if (displayAttribute != null && displayAttribute.GetAutoGenerateField().HasValue) { return displayAttribute.GetAutoGenerateField().Value; } // If there is an explicit Scaffold attribute, always honor it var scaffoldAttribute = Metadata.ScaffoldColumnAttribute; if (scaffoldAttribute != null) { return scaffoldAttribute.Scaffold; } if (_scaffoldValueDefault == null) { _scaffoldValueDefault = ScaffoldNoCache; } return _scaffoldValueDefault.Value; } set { _scaffoldValueManual = value; } } /// <summary> /// Look at various pieces of data on the column to determine whether it's /// Scaffold mode should be on. This only gets called once per column and the result /// is cached /// </summary> internal virtual bool ScaffoldNoCache { get { // Any field with a UIHint should be included if (!String.IsNullOrEmpty(UIHint)) return true; // Skip columns that are part of a foreign key, since they are already 'covered' in the // strongly typed foreign key column if (IsForeignKeyComponent) return false; // Skip generated columns, which are not typically interesting if (IsGenerated) return false; // Always include non-generated primary keys if (IsPrimaryKey) return true; // Skip custom properties if (IsCustomProperty) return false; // Include strings and characters if (IsString) return true; if (ColumnType == typeof(char)) return true; // Include numbers if (IsInteger) return true; if (IsFloatingPoint) return true; // Include date related columns if (ColumnType == typeof(DateTime)) return true; if (ColumnType == typeof(TimeSpan)) return true; if (ColumnType == typeof(DateTimeOffset)) return true; // Include bools if (ColumnType == typeof(bool)) return true; // Include enums Type enumType; if (this.IsEnumType(out enumType)) return true; //Include spatial types if (ColumnType == typeof(DbGeography)) return true; if (ColumnType == typeof(DbGeometry)) return true; return false; } } /// <summary> /// A friendly short display name for this column. Meant to be used in GridView and similar controls where there might be /// limited column header space /// </summary> public virtual string ShortDisplayName { get { // Default to the DisplayName if there is no ShortDisplayName return Metadata.ShortDisplayName ?? DisplayName; } } /// <summary> /// The expression used to determine the sort order for this column /// </summary> public string SortExpression { get { return SortExpressionInternal; } } internal virtual string SortExpressionInternal { get { return Provider.IsSortable ? Name : string.Empty; } } /// <summary> /// The MetaTable that this column belongs to /// </summary> public MetaTable Table { get; private set; } /// <summary> /// The TypeCode of this column. It is derived from the ColumnType /// </summary> public TypeCode TypeCode { get { if (_typeCode == TypeCode.Empty) { _typeCode = DataSourceUtil.TypeCodeFromType(ColumnType); } return _typeCode; } } /// <summary> /// The UIHint used for the column /// </summary> [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces", Justification = "Interface denotes existence of property, not used for security.")] public virtual string UIHint { get { return Metadata.UIHint; } } #region IFieldFormattingOptions Members /// <summary> /// Same semantic as the same property on System.Web.UI.WebControls.BoundField /// </summary> public bool ApplyFormatInEditMode { get { return Metadata.ApplyFormatInEditMode; } } /// <summary> /// Same semantic as the same property on System.Web.UI.WebControls.BoundField /// </summary> public bool ConvertEmptyStringToNull { get { return Metadata.ConvertEmptyStringToNull; } } /// <summary> /// Same semantic as the same property on System.Web.UI.WebControls.BoundField /// </summary> public string DataFormatString { get { return Metadata.DataFormatString; } } /// <summary> /// Same semantic as the same property on System.Web.UI.WebControls.BoundField /// </summary> public bool HtmlEncode { get { return Metadata.HtmlEncode; } } /// <summary> /// Same semantic as the same property on System.Web.UI.WebControls.BoundField /// </summary> public string NullDisplayText { get { return Metadata.NullDisplayText; } } #endregion /// <summary> /// Build the attribute collection, later made available through the Attributes property /// </summary> protected virtual AttributeCollection BuildAttributeCollection() { return Provider.Attributes; } /// <summary> /// Perform initialization logic for this column /// </summary> internal protected virtual void Initialize() { } /// <summary> /// Resets cached column metadata (i.e. information coming from attributes). The metadata cache will be rebuilt /// the next time any metadata-derived information gets requested. /// </summary> public void ResetMetadata() { _metadata = null; } /// <summary> /// Shows the column name. Mostly for debugging purpose. /// </summary> [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] public override string ToString() { return GetType().Name + " " + Name; } internal IMetaColumnMetadata Metadata { get { // Use a local to avoid returning null if ResetMetadata is called IMetaColumnMetadata metadata = _metadata; if (metadata == null) { metadata = new MetaColumnMetadata(this); _metadata = metadata; } return metadata; } set { // settable for unit testing _metadata = value; } } #region Metadata abstraction internal interface IMetaColumnMetadata { AttributeCollection Attributes { get; } DisplayAttribute DisplayAttribute { get; } bool ApplyFormatInEditMode { get; } bool ConvertEmptyStringToNull { get; } bool HtmlEncode { get; } string DataFormatString { get; } DataTypeAttribute DataTypeAttribute { get; } object DefaultValue { get; } string Description { get; } string DisplayName { get; } string FilterUIHint { get; } string ShortDisplayName { get; } string NullDisplayText { get; } string Prompt { get; } RequiredAttribute RequiredAttribute { get; } ScaffoldColumnAttribute ScaffoldColumnAttribute { get; } StringLengthAttribute StringLengthAttribute { get; } string UIHint { get; } bool IsReadOnly { get; } EditableAttribute EditableAttribute { get; } } internal class MetaColumnMetadata : IMetaColumnMetadata { private MetaColumn Column { get; set; } public AttributeCollection Attributes { get; private set; } public MetaColumnMetadata(MetaColumn column) { Debug.Assert(column != null); Column = column; Attributes = Column.BuildAttributeCollection(); DisplayAttribute = Attributes.FirstOrDefault<DisplayAttribute>(); DataTypeAttribute = Attributes.FirstOrDefault<DataTypeAttribute>() ?? GetDefaultDataTypeAttribute(); DescriptionAttribute = Attributes.FirstOrDefault<DescriptionAttribute>(); DefaultValueAttribute = Attributes.FirstOrDefault<DefaultValueAttribute>(); DisplayNameAttribute = Attributes.FirstOrDefault<DisplayNameAttribute>(); RequiredAttribute = Attributes.FirstOrDefault<RequiredAttribute>(); ScaffoldColumnAttribute = Attributes.FirstOrDefault<ScaffoldColumnAttribute>(); StringLengthAttribute = Attributes.FirstOrDefault<StringLengthAttribute>(); UIHint = GetHint<UIHintAttribute>(a => a.PresentationLayer, a => a.UIHint); FilterUIHint = GetHint<FilterUIHintAttribute>(a => a.PresentationLayer, a => a.FilterUIHint); EditableAttribute = Attributes.FirstOrDefault<EditableAttribute>(); IsReadOnly = Attributes.GetAttributePropertyValue<ReadOnlyAttribute, bool>(a => a.IsReadOnly, false); var displayFormatAttribute = Attributes.FirstOrDefault<DisplayFormatAttribute>() ?? (DataTypeAttribute != null ? DataTypeAttribute.DisplayFormat : null); ApplyFormatInEditMode = displayFormatAttribute.GetPropertyValue(a => a.ApplyFormatInEditMode, false); ConvertEmptyStringToNull = displayFormatAttribute.GetPropertyValue(a => a.ConvertEmptyStringToNull, true); DataFormatString = displayFormatAttribute.GetPropertyValue(a => a.DataFormatString, String.Empty); NullDisplayText = displayFormatAttribute.GetPropertyValue(a => a.NullDisplayText, String.Empty); HtmlEncode = displayFormatAttribute.GetPropertyValue(a => a.HtmlEncode, true); } public DisplayAttribute DisplayAttribute { get; private set; } public bool ApplyFormatInEditMode { get; private set; } public bool ConvertEmptyStringToNull { get; private set; } public string DataFormatString { get; private set; } public DataTypeAttribute DataTypeAttribute { get; private set; } public object DefaultValue { get { return DefaultValueAttribute.GetPropertyValue(a => a.Value, null); } } private DefaultValueAttribute DefaultValueAttribute { get; set; } public string Description { get { return DisplayAttribute.GetPropertyValue(a => a.GetDescription(), null) ?? DescriptionAttribute.GetPropertyValue(a => a.Description, null); } } private DescriptionAttribute DescriptionAttribute { get; set; } public string DisplayName { get { return DisplayAttribute.GetPropertyValue(a => a.GetName(), null) ?? DisplayNameAttribute.GetPropertyValue(a => a.DisplayName, null); } } public string ShortDisplayName { get { return DisplayAttribute.GetPropertyValue(a => a.GetShortName(), null); } } private DisplayNameAttribute DisplayNameAttribute { get; set; } public string FilterUIHint { get; private set; } public EditableAttribute EditableAttribute { get; private set; } public bool IsReadOnly { get; private set; } public string NullDisplayText { get; private set; } public string Prompt { get { return DisplayAttribute.GetPropertyValue(a => a.GetPrompt(), null); } } public RequiredAttribute RequiredAttribute { get; private set; } public ScaffoldColumnAttribute ScaffoldColumnAttribute { get; private set; } public StringLengthAttribute StringLengthAttribute { get; private set; } public string UIHint { get; private set; } private DataTypeAttribute GetDefaultDataTypeAttribute() { if (Column.IsString) { if (Column.IsLongString) { return new DataTypeAttribute(DataType.MultilineText); } else { return new DataTypeAttribute(DataType.Text); } } return null; } private string GetHint<T>(Func<T, string> presentationLayerPropertyAccessor, Func<T, string> hintPropertyAccessor) where T : Attribute { var uiHints = Attributes.OfType<T>(); var presentationLayerNotSpecified = uiHints.Where(a => String.IsNullOrEmpty(presentationLayerPropertyAccessor(a))); var presentationLayerSpecified = uiHints.Where(a => !String.IsNullOrEmpty(presentationLayerPropertyAccessor(a))); T uiHintAttribute = presentationLayerSpecified.FirstOrDefault(a => presentationLayerPropertyAccessor(a).ToLower(CultureInfo.InvariantCulture) == "webforms" || presentationLayerPropertyAccessor(a).ToLower(CultureInfo.InvariantCulture) == "mvc") ?? presentationLayerNotSpecified.FirstOrDefault(); return uiHintAttribute.GetPropertyValue(hintPropertyAccessor); } public bool HtmlEncode { get; set; } } #endregion string IMetaColumn.Description { get { return Description; } } string IMetaColumn.DisplayName { get { return DisplayName; } } string IMetaColumn.Prompt { get { return Prompt; } } string IMetaColumn.ShortDisplayName { get { return ShortDisplayName; } } IMetaTable IMetaColumn.Table { get { return Table; } } IMetaModel IMetaColumn.Model { get { return Model; } } } }
/** * 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. * * Contains some contributions under the Thrift Software License. * Please see doc/old-thrift-license.txt in the Thrift distribution for * details. */ using System; using System.Net.Sockets; namespace Thrift.Transport { public class TSocket : TStreamTransport { private TcpClient client = null; private string host = null; private int port = 0; private int timeout = 0; public TSocket(TcpClient client) { this.client = client; if (IsOpen) { inputStream = client.GetStream(); outputStream = client.GetStream(); } } public TSocket(string host, int port) : this(host, port, 0) { } public TSocket(string host, int port, int timeout) { this.host = host; this.port = port; this.timeout = timeout; InitSocket(); } private void InitSocket() { client = new TcpClient(); client.ReceiveTimeout = client.SendTimeout = timeout; client.Client.NoDelay = true; } public int Timeout { set { client.ReceiveTimeout = client.SendTimeout = timeout = value; } } public TcpClient TcpClient { get { return client; } } public string Host { get { return host; } } public int Port { get { return port; } } public override bool IsOpen { get { if (client == null) { return false; } return client.Connected; } } public override void Open() { if (IsOpen) { throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected"); } if (String.IsNullOrEmpty(host)) { throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host"); } if (port <= 0) { throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port"); } if (client == null) { InitSocket(); } if( timeout == 0) // no timeout -> infinite { client.Connect(host, port); } else // we have a timeout -> use it { ConnectHelper hlp = new ConnectHelper(client); IAsyncResult asyncres = client.BeginConnect(host, port, new AsyncCallback(ConnectCallback), hlp); bool bConnected = asyncres.AsyncWaitHandle.WaitOne(timeout) && client.Connected; if (!bConnected) { lock (hlp.Mutex) { if( hlp.CallbackDone) { asyncres.AsyncWaitHandle.Close(); client.Close(); } else { hlp.DoCleanup = true; client = null; } } throw new TTransportException(TTransportException.ExceptionType.TimedOut, "Connect timed out"); } } inputStream = client.GetStream(); outputStream = client.GetStream(); } static void ConnectCallback(IAsyncResult asyncres) { ConnectHelper hlp = asyncres.AsyncState as ConnectHelper; lock (hlp.Mutex) { hlp.CallbackDone = true; try { if( hlp.Client.Client != null) hlp.Client.EndConnect(asyncres); } catch (SocketException) { // catch that away } if (hlp.DoCleanup) { asyncres.AsyncWaitHandle.Close(); if (hlp.Client is IDisposable) ((IDisposable)hlp.Client).Dispose(); hlp.Client = null; } } } private class ConnectHelper { public object Mutex = new object(); public bool DoCleanup = false; public bool CallbackDone = false; public TcpClient Client; public ConnectHelper(TcpClient client) { Client = client; } } public override void Close() { base.Close(); if (client != null) { client.Close(); client = null; } } #region " IDisposable Support " private bool _IsDisposed; // IDisposable protected override void Dispose(bool disposing) { if (!_IsDisposed) { if (disposing) { if (client != null) ((IDisposable)client).Dispose(); base.Dispose(disposing); } } _IsDisposed = true; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.IdentityModel.Policy; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Runtime; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Security.Tokens; using System.Xml; using SignatureResourcePool = System.IdentityModel.SignatureResourcePool; namespace System.ServiceModel.Security { internal abstract class ReceiveSecurityHeader : SecurityHeader { // client->server symmetric binding case: only primaryTokenAuthenticator is set // server->client symmetric binding case: only primary token is set // asymmetric binding case: primaryTokenAuthenticator and wrapping token is set private SecurityTokenAuthenticator _primaryTokenAuthenticator; private bool _allowFirstTokenMismatch; private SecurityToken _outOfBandPrimaryToken; private IList<SecurityToken> _outOfBandPrimaryTokenCollection; private SecurityTokenParameters _primaryTokenParameters; private TokenTracker _primaryTokenTracker; private SecurityToken _wrappingToken; private SecurityTokenParameters _wrappingTokenParameters; private SecurityTokenAuthenticator _derivedTokenAuthenticator; // assumes that the caller has done the check for uniqueness of types private IList<SupportingTokenAuthenticatorSpecification> _supportingTokenAuthenticators; private ChannelBinding _channelBinding; private ExtendedProtectionPolicy _extendedProtectionPolicy; private bool _expectBasicTokens; private bool _expectSignedTokens; private bool _expectEndorsingTokens; private bool _expectSignatureConfirmation; // maps from token to wire form (for basic and signed), and also tracks operations done // maps from supporting token parameter to the operations done for that token type private List<TokenTracker> _supportingTokenTrackers; private List<SecurityTokenAuthenticator> _allowedAuthenticators; private SecurityTokenAuthenticator _pendingSupportingTokenAuthenticator; private Collection<SecurityToken> _signedEndorsingTokens; private Dictionary<SecurityToken, ReadOnlyCollection<IAuthorizationPolicy>> _tokenPoliciesMapping; private SecurityTimestamp _timestamp; private SecurityHeaderTokenResolver _universalTokenResolver; private SecurityHeaderTokenResolver _primaryTokenResolver; private ReadOnlyCollection<SecurityTokenResolver> _outOfBandTokenResolver; private SecurityTokenResolver _combinedPrimaryTokenResolver; private XmlAttributeHolder[] _securityElementAttributes; private OrderTracker _orderTracker = new OrderTracker(); private OperationTracker _signatureTracker = new OperationTracker(); private OperationTracker _encryptionTracker = new OperationTracker(); private int _maxDerivedKeys; private int _numDerivedKeys; private bool _enforceDerivedKeyRequirement = true; private NonceCache _nonceCache; private TimeSpan _replayWindow; private TimeSpan _clockSkew; private TimeoutHelper _timeoutHelper; private long _maxReceivedMessageSize = TransportDefaults.MaxReceivedMessageSize; private XmlDictionaryReaderQuotas _readerQuotas; private MessageProtectionOrder _protectionOrder; private bool _hasEndorsingOrSignedEndorsingSupportingTokens; private SignatureResourcePool _resourcePool; private bool _replayDetectionEnabled = false; private const int AppendPosition = -1; protected ReceiveSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay, SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithmSuite, int headerIndex, MessageDirection direction) : base(message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, direction) { HeaderIndex = headerIndex; ElementManager = new ReceiveSecurityHeaderElementManager(this); } public Collection<SecurityToken> BasicSupportingTokens { get; } public Collection<SecurityToken> SignedSupportingTokens { get; } public Collection<SecurityToken> EndorsingSupportingTokens { get; } public Collection<SecurityToken> SignedEndorsingSupportingTokens { get { return _signedEndorsingTokens; } } public bool EnforceDerivedKeyRequirement { get { return _enforceDerivedKeyRequirement; } set { ThrowIfProcessingStarted(); _enforceDerivedKeyRequirement = value; } } public byte[] PrimarySignatureValue { get; } public SecurityToken EncryptionToken { get { return _encryptionTracker.Token; } } public bool ExpectBasicTokens { get { return _expectBasicTokens; } set { ThrowIfProcessingStarted(); _expectBasicTokens = value; } } public ReceiveSecurityHeaderElementManager ElementManager { get; } public SecurityTokenAuthenticator DerivedTokenAuthenticator { get { return _derivedTokenAuthenticator; } set { ThrowIfProcessingStarted(); _derivedTokenAuthenticator = value; } } public bool ReplayDetectionEnabled { get { return _replayDetectionEnabled; } set { ThrowIfProcessingStarted(); _replayDetectionEnabled = value; } } public bool ExpectSignatureConfirmation { get { return _expectSignatureConfirmation; } set { ThrowIfProcessingStarted(); _expectSignatureConfirmation = value; } } public bool ExpectSignedTokens { get { return _expectSignedTokens; } set { ThrowIfProcessingStarted(); _expectSignedTokens = value; } } public bool ExpectEndorsingTokens { get { return _expectEndorsingTokens; } set { ThrowIfProcessingStarted(); _expectEndorsingTokens = value; } } public SecurityTokenResolver CombinedUniversalTokenResolver { get; private set; } internal int HeaderIndex { get; } internal long MaxReceivedMessageSize { get { return _maxReceivedMessageSize; } set { ThrowIfProcessingStarted(); _maxReceivedMessageSize = value; } } internal XmlDictionaryReaderQuotas ReaderQuotas { get { return _readerQuotas; } set { ThrowIfProcessingStarted(); _readerQuotas = value ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); } } public override string Name { get { return StandardsManager.SecurityVersion.HeaderName.Value; } } public override string Namespace { get { return StandardsManager.SecurityVersion.HeaderNamespace.Value; } } public Message ProcessedMessage { get { return Message; } } protected SignatureResourcePool ResourcePool { get { if (_resourcePool == null) { _resourcePool = new SignatureResourcePool(); } return _resourcePool; } } internal SecurityVerifiedMessage SecurityVerifiedMessage { get; private set; } public SecurityToken SignatureToken { get { return _signatureTracker.Token; } } public Dictionary<SecurityToken, ReadOnlyCollection<IAuthorizationPolicy>> SecurityTokenAuthorizationPoliciesMapping { get { if (_tokenPoliciesMapping == null) { _tokenPoliciesMapping = new Dictionary<SecurityToken, ReadOnlyCollection<IAuthorizationPolicy>>(); } return _tokenPoliciesMapping; } } public int MaxDerivedKeyLength { get; private set; } internal XmlDictionaryReader CreateSecurityHeaderReader() { return SecurityVerifiedMessage.GetReaderAtSecurityHeader(); } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { XmlDictionaryReader securityHeaderReader = GetReaderAtSecurityHeader(); securityHeaderReader.ReadStartElement(); for (int i = 0; i < ElementManager.Count; ++i) { ReceiveSecurityHeaderEntry entry; ElementManager.GetElementEntry(i, out entry); XmlDictionaryReader reader = null; if (entry._encrypted) { reader = ElementManager.GetReader(i, false); writer.WriteNode(reader, false); reader.Close(); securityHeaderReader.Skip(); } else { writer.WriteNode(securityHeaderReader, false); } } securityHeaderReader.Close(); } private XmlDictionaryReader GetReaderAtSecurityHeader() { XmlDictionaryReader reader = SecurityVerifiedMessage.GetReaderAtFirstHeader(); for (int i = 0; i < HeaderIndex; ++i) { reader.Skip(); } return reader; } // replay detection done if enableReplayDetection is set to true. public void SetTimeParameters(NonceCache nonceCache, TimeSpan replayWindow, TimeSpan clockSkew) { _nonceCache = nonceCache; _replayWindow = replayWindow; _clockSkew = clockSkew; } public void Process(TimeSpan timeout, ChannelBinding channelBinding, ExtendedProtectionPolicy extendedProtectionPolicy) { Fx.Assert(ReaderQuotas != null, "Reader quotas must be set before processing"); MessageProtectionOrder actualProtectionOrder = _protectionOrder; bool wasProtectionOrderDowngraded = false; if (_protectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature) { throw ExceptionHelper.PlatformNotSupported(); // No support for message encryption } _channelBinding = channelBinding; _extendedProtectionPolicy = extendedProtectionPolicy; _orderTracker.SetRequiredProtectionOrder(actualProtectionOrder); SetProcessingStarted(); _timeoutHelper = new TimeoutHelper(timeout); Message = SecurityVerifiedMessage = new SecurityVerifiedMessage(Message, this); XmlDictionaryReader reader = CreateSecurityHeaderReader(); reader.MoveToStartElement(); if (reader.IsEmptyElement) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.SecurityHeaderIsEmpty), Message); } if (RequireMessageProtection) { _securityElementAttributes = XmlAttributeHolder.ReadAttributes(reader); } else { _securityElementAttributes = XmlAttributeHolder.emptyArray; } reader.ReadStartElement(); if (_primaryTokenParameters != null) { _primaryTokenTracker = new TokenTracker(null, _outOfBandPrimaryToken, _allowFirstTokenMismatch); } // universalTokenResolver is used for resolving tokens _universalTokenResolver = new SecurityHeaderTokenResolver(this); // primary token resolver is used for resolving primary signature and decryption _primaryTokenResolver = new SecurityHeaderTokenResolver(this); if (_outOfBandPrimaryToken != null) { _universalTokenResolver.Add(_outOfBandPrimaryToken, SecurityTokenReferenceStyle.External, _primaryTokenParameters); _primaryTokenResolver.Add(_outOfBandPrimaryToken, SecurityTokenReferenceStyle.External, _primaryTokenParameters); } else if (_outOfBandPrimaryTokenCollection != null) { for (int i = 0; i < _outOfBandPrimaryTokenCollection.Count; ++i) { _universalTokenResolver.Add(_outOfBandPrimaryTokenCollection[i], SecurityTokenReferenceStyle.External, _primaryTokenParameters); _primaryTokenResolver.Add(_outOfBandPrimaryTokenCollection[i], SecurityTokenReferenceStyle.External, _primaryTokenParameters); } } if (_wrappingToken != null) { _universalTokenResolver.ExpectedWrapper = _wrappingToken; _universalTokenResolver.ExpectedWrapperTokenParameters = _wrappingTokenParameters; _primaryTokenResolver.ExpectedWrapper = _wrappingToken; _primaryTokenResolver.ExpectedWrapperTokenParameters = _wrappingTokenParameters; } if (_outOfBandTokenResolver == null) { CombinedUniversalTokenResolver = _universalTokenResolver; _combinedPrimaryTokenResolver = _primaryTokenResolver; } else { CombinedUniversalTokenResolver = new AggregateSecurityHeaderTokenResolver(_universalTokenResolver, _outOfBandTokenResolver); _combinedPrimaryTokenResolver = new AggregateSecurityHeaderTokenResolver(_primaryTokenResolver, _outOfBandTokenResolver); } _allowedAuthenticators = new List<SecurityTokenAuthenticator>(); if (_primaryTokenAuthenticator != null) { _allowedAuthenticators.Add(_primaryTokenAuthenticator); } if (DerivedTokenAuthenticator != null) { _allowedAuthenticators.Add(DerivedTokenAuthenticator); } _pendingSupportingTokenAuthenticator = null; int numSupportingTokensRequiringDerivation = 0; if (_supportingTokenAuthenticators != null && _supportingTokenAuthenticators.Count > 0) { _supportingTokenTrackers = new List<TokenTracker>(_supportingTokenAuthenticators.Count); for (int i = 0; i < _supportingTokenAuthenticators.Count; ++i) { SupportingTokenAuthenticatorSpecification spec = _supportingTokenAuthenticators[i]; switch (spec.SecurityTokenAttachmentMode) { case SecurityTokenAttachmentMode.Endorsing: _hasEndorsingOrSignedEndorsingSupportingTokens = true; break; case SecurityTokenAttachmentMode.Signed: break; case SecurityTokenAttachmentMode.SignedEndorsing: _hasEndorsingOrSignedEndorsingSupportingTokens = true; break; case SecurityTokenAttachmentMode.SignedEncrypted: break; } if ((_primaryTokenAuthenticator != null) && (_primaryTokenAuthenticator.GetType().Equals(spec.TokenAuthenticator.GetType()))) { _pendingSupportingTokenAuthenticator = spec.TokenAuthenticator; } else { _allowedAuthenticators.Add(spec.TokenAuthenticator); } if (spec.TokenParameters.RequireDerivedKeys && !spec.TokenParameters.HasAsymmetricKey && (spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing)) { ++numSupportingTokensRequiringDerivation; } _supportingTokenTrackers.Add(new TokenTracker(spec)); } } if (DerivedTokenAuthenticator != null) { // we expect key derivation. Compute quotas for derived keys int maxKeyDerivationLengthInBits = AlgorithmSuite.DefaultEncryptionKeyDerivationLength >= AlgorithmSuite.DefaultSignatureKeyDerivationLength ? AlgorithmSuite.DefaultEncryptionKeyDerivationLength : AlgorithmSuite.DefaultSignatureKeyDerivationLength; MaxDerivedKeyLength = maxKeyDerivationLengthInBits / 8; // the upper bound of derived keys is (1 for primary signature + 1 for encryption + supporting token signatures requiring derivation)*2 // the multiplication by 2 is to take care of interop scenarios that may arise that require more derived keys than the lower bound. _maxDerivedKeys = (1 + 1 + numSupportingTokensRequiringDerivation) * 2; } SecurityHeaderElementInferenceEngine engine = SecurityHeaderElementInferenceEngine.GetInferenceEngine(Layout); engine.ExecuteProcessingPasses(this, reader); if (RequireMessageProtection) { throw ExceptionHelper.PlatformNotSupported(); } EnsureDecryptionComplete(); _signatureTracker.SetDerivationSourceIfRequired(); _encryptionTracker.SetDerivationSourceIfRequired(); if (EncryptionToken != null) { throw ExceptionHelper.PlatformNotSupported(); } // ensure that the primary signature was signed with derived keys if required if (EnforceDerivedKeyRequirement) { if (SignatureToken != null) { if (_primaryTokenParameters != null) { if (_primaryTokenParameters.RequireDerivedKeys && !_primaryTokenParameters.HasAsymmetricKey && !_primaryTokenTracker.IsDerivedFrom) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(SR.PrimarySignatureWasNotSignedByDerivedKey, _primaryTokenParameters))); } } else if (_wrappingTokenParameters != null && _wrappingTokenParameters.RequireDerivedKeys) { if (!_signatureTracker.IsDerivedToken) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(SR.PrimarySignatureWasNotSignedByDerivedWrappedKey, _wrappingTokenParameters))); } } } // verify that the encryption is using key derivation if (EncryptionToken != null) { throw ExceptionHelper.PlatformNotSupported(); } } if (wasProtectionOrderDowngraded && (BasicSupportingTokens != null) && (BasicSupportingTokens.Count > 0)) { throw ExceptionHelper.PlatformNotSupported(); } // verify all supporting token parameters have their requirements met if (_supportingTokenTrackers != null && _supportingTokenTrackers.Count > 0) { throw ExceptionHelper.PlatformNotSupported(); } if (_replayDetectionEnabled) { throw ExceptionHelper.PlatformNotSupported(); } if (ExpectSignatureConfirmation) { throw ExceptionHelper.PlatformNotSupported(); } MarkHeaderAsUnderstood(); } protected abstract void EnsureDecryptionComplete(); internal void ExecuteFullPass(XmlDictionaryReader reader) { bool primarySignatureFound = !RequireMessageProtection; int position = 0; while (reader.IsStartElement()) { if (IsReaderAtSignature(reader)) { throw ExceptionHelper.PlatformNotSupported(); } else if (IsReaderAtReferenceList(reader)) { throw ExceptionHelper.PlatformNotSupported(); } else if (StandardsManager.WSUtilitySpecificationVersion.IsReaderAtTimestamp(reader)) { ReadTimestamp(reader); } else if (IsReaderAtEncryptedKey(reader)) { throw ExceptionHelper.PlatformNotSupported(); } else if (IsReaderAtEncryptedData(reader)) { throw ExceptionHelper.PlatformNotSupported(); } else if (StandardsManager.SecurityVersion.IsReaderAtSignatureConfirmation(reader)) { throw ExceptionHelper.PlatformNotSupported(); } else if (IsReaderAtSecurityTokenReference(reader)) { throw ExceptionHelper.PlatformNotSupported(); } else { ReadToken(reader, AppendPosition, null, null, null, _timeoutHelper.RemainingTime()); } position++; } reader.ReadEndElement(); // wsse:Security reader.Close(); } internal void EnsureDerivedKeyLimitNotReached() { ++_numDerivedKeys; if (_numDerivedKeys > _maxDerivedKeys) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(SR.DerivedKeyLimitExceeded, _maxDerivedKeys))); } } protected TokenTracker GetSupportingTokenTracker(SecurityTokenAuthenticator tokenAuthenticator, out SupportingTokenAuthenticatorSpecification spec) { spec = null; if (_supportingTokenAuthenticators == null) { return null; } for (int i = 0; i < _supportingTokenAuthenticators.Count; ++i) { if (_supportingTokenAuthenticators[i].TokenAuthenticator == tokenAuthenticator) { spec = _supportingTokenAuthenticators[i]; return _supportingTokenTrackers[i]; } } return null; } private void ReadTimestamp(XmlDictionaryReader reader) { if (_timestamp != null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.DuplicateTimestampInSecurityHeader), Message); } bool expectTimestampToBeSigned = RequireMessageProtection || _hasEndorsingOrSignedEndorsingSupportingTokens; string expectedDigestAlgorithm = expectTimestampToBeSigned ? AlgorithmSuite.DefaultDigestAlgorithm : null; SignatureResourcePool resourcePool = expectTimestampToBeSigned ? ResourcePool : null; _timestamp = StandardsManager.WSUtilitySpecificationVersion.ReadTimestamp(reader, expectedDigestAlgorithm, resourcePool); _timestamp.ValidateRangeAndFreshness(_replayWindow, _clockSkew); ElementManager.AppendTimestamp(_timestamp); } private bool IsPrimaryToken(SecurityToken token) { bool result = (token == _outOfBandPrimaryToken || (_primaryTokenTracker != null && token == _primaryTokenTracker.Token)); if (!result && _outOfBandPrimaryTokenCollection != null) { for (int i = 0; i < _outOfBandPrimaryTokenCollection.Count; ++i) { if (_outOfBandPrimaryTokenCollection[i] == token) { result = true; break; } } } return result; } private void ReadToken(XmlDictionaryReader reader, int position, byte[] decryptedBuffer, SecurityToken encryptionToken, string idInEncryptedForm, TimeSpan timeout) { Fx.Assert((position == AppendPosition) == (decryptedBuffer == null), "inconsistent position, decryptedBuffer parameters"); Fx.Assert((position == AppendPosition) == (encryptionToken == null), "inconsistent position, encryptionToken parameters"); string localName = reader.LocalName; string namespaceUri = reader.NamespaceURI; string valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); SecurityTokenAuthenticator usedTokenAuthenticator; SecurityToken token = ReadToken(reader, CombinedUniversalTokenResolver, _allowedAuthenticators, out usedTokenAuthenticator); if (token == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.Format(SR.TokenManagerCouldNotReadToken, localName, namespaceUri, valueType)), Message); } DerivedKeySecurityToken derivedKeyToken = token as DerivedKeySecurityToken; if (derivedKeyToken != null) { EnsureDerivedKeyLimitNotReached(); derivedKeyToken.InitializeDerivedKey(MaxDerivedKeyLength); } if (usedTokenAuthenticator == _primaryTokenAuthenticator) { _allowedAuthenticators.Remove(usedTokenAuthenticator); } ReceiveSecurityHeaderBindingModes mode; TokenTracker supportingTokenTracker = null; if (usedTokenAuthenticator == _primaryTokenAuthenticator) { // this is the primary token. Add to resolver as such _universalTokenResolver.Add(token, SecurityTokenReferenceStyle.Internal, _primaryTokenParameters); _primaryTokenResolver.Add(token, SecurityTokenReferenceStyle.Internal, _primaryTokenParameters); if (_pendingSupportingTokenAuthenticator != null) { _allowedAuthenticators.Add(_pendingSupportingTokenAuthenticator); _pendingSupportingTokenAuthenticator = null; } _primaryTokenTracker.RecordToken(token); mode = ReceiveSecurityHeaderBindingModes.Primary; } else if (usedTokenAuthenticator == DerivedTokenAuthenticator) { if (token is DerivedKeySecurityTokenStub) { if (Layout == SecurityHeaderLayout.Strict) { DerivedKeySecurityTokenStub tmpToken = (DerivedKeySecurityTokenStub)token; throw TraceUtility.ThrowHelperError(new MessageSecurityException( SR.Format(SR.UnableToResolveKeyInfoClauseInDerivedKeyToken, tmpToken.TokenToDeriveIdentifier)), Message); } } else { AddDerivedKeyTokenToResolvers(token); } mode = ReceiveSecurityHeaderBindingModes.Unknown; } else { SupportingTokenAuthenticatorSpecification supportingTokenSpec; supportingTokenTracker = GetSupportingTokenTracker(usedTokenAuthenticator, out supportingTokenSpec); if (supportingTokenTracker == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(SR.UnknownTokenAuthenticatorUsedInTokenProcessing, usedTokenAuthenticator))); } if (supportingTokenTracker.Token != null) { supportingTokenTracker = new TokenTracker(supportingTokenSpec); _supportingTokenTrackers.Add(supportingTokenTracker); } supportingTokenTracker.RecordToken(token); if (encryptionToken != null) { supportingTokenTracker.IsEncrypted = true; } bool isBasic; bool isSignedButNotBasic; SecurityTokenAttachmentModeHelper.Categorize(supportingTokenSpec.SecurityTokenAttachmentMode, out isBasic, out isSignedButNotBasic, out mode); if (isBasic) { if (!ExpectBasicTokens) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.BasicTokenNotExpected)); } // only basic tokens have to be part of the reference list. Encrypted Saml tokens dont for example if (RequireMessageProtection && encryptionToken != null) { throw ExceptionHelper.PlatformNotSupported(); } } if (isSignedButNotBasic && !ExpectSignedTokens) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.SignedSupportingTokenNotExpected)); } _universalTokenResolver.Add(token, SecurityTokenReferenceStyle.Internal, supportingTokenSpec.TokenParameters); } if (position == AppendPosition) { ElementManager.AppendToken(token, mode, supportingTokenTracker); } else { ElementManager.SetTokenAfterDecryption(position, token, mode, decryptedBuffer, supportingTokenTracker); } } private SecurityToken GetRootToken(SecurityToken token) { if (token is DerivedKeySecurityToken) { return ((DerivedKeySecurityToken)token).TokenToDerive; } else { return token; } } private SecurityToken ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver, IList<SecurityTokenAuthenticator> allowedTokenAuthenticators, out SecurityTokenAuthenticator usedTokenAuthenticator) { SecurityToken token = StandardsManager.SecurityTokenSerializer.ReadToken(reader, tokenResolver); if (token is DerivedKeySecurityTokenStub) { if (DerivedTokenAuthenticator == null) { // No Authenticator registered for DerivedKeySecurityToken throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.Format(SR.UnableToFindTokenAuthenticator, typeof(DerivedKeySecurityToken)))); } // This is just the stub. Nothing to Validate. Set the usedTokenAuthenticator to // DerivedKeySecurityTokenAuthenticator. usedTokenAuthenticator = DerivedTokenAuthenticator; return token; } for (int i = 0; i < allowedTokenAuthenticators.Count; ++i) { SecurityTokenAuthenticator tokenAuthenticator = allowedTokenAuthenticators[i]; if (tokenAuthenticator.CanValidateToken(token)) { ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies; authorizationPolicies = tokenAuthenticator.ValidateToken(token); SecurityTokenAuthorizationPoliciesMapping.Add(token, authorizationPolicies); usedTokenAuthenticator = tokenAuthenticator; return token; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.Format(SR.UnableToFindTokenAuthenticator, token.GetType()))); } private void AddDerivedKeyTokenToResolvers(SecurityToken token) { _universalTokenResolver.Add(token); // add it to the primary token resolver only if its root is primary SecurityToken rootToken = GetRootToken(token); if (IsPrimaryToken(rootToken)) { _primaryTokenResolver.Add(token); } } protected abstract bool IsReaderAtEncryptedKey(XmlDictionaryReader reader); protected abstract bool IsReaderAtEncryptedData(XmlDictionaryReader reader); protected abstract bool IsReaderAtReferenceList(XmlDictionaryReader reader); protected abstract bool IsReaderAtSignature(XmlDictionaryReader reader); protected abstract bool IsReaderAtSecurityTokenReference(XmlDictionaryReader reader); private void MarkHeaderAsUnderstood() { // header decryption does not reorder or delete headers MessageHeaderInfo header = Message.Headers[HeaderIndex]; Fx.Assert(header.Name == Name && header.Namespace == Namespace && header.Actor == Actor, "security header index mismatch"); Message.Headers.UnderstoodHeaders.Add(header); } private struct OrderTracker { private static readonly ReceiverProcessingOrder[] s_stateTransitionTableOnDecrypt = new ReceiverProcessingOrder[] { ReceiverProcessingOrder.Decrypt, ReceiverProcessingOrder.VerifyDecrypt, ReceiverProcessingOrder.Decrypt, ReceiverProcessingOrder.Mixed, ReceiverProcessingOrder.VerifyDecrypt, ReceiverProcessingOrder.Mixed }; private static readonly ReceiverProcessingOrder[] s_stateTransitionTableOnVerify = new ReceiverProcessingOrder[] { ReceiverProcessingOrder.Verify, ReceiverProcessingOrder.Verify, ReceiverProcessingOrder.DecryptVerify, ReceiverProcessingOrder.DecryptVerify, ReceiverProcessingOrder.Mixed, ReceiverProcessingOrder.Mixed }; private const int MaxAllowedWrappedKeys = 1; private int _referenceListCount; private ReceiverProcessingOrder _state; private int _signatureCount; private int _unencryptedSignatureCount; private MessageProtectionOrder _protectionOrder; private bool _enforce; public bool AllSignaturesEncrypted { get { return _unencryptedSignatureCount == 0; } } public bool EncryptBeforeSignMode { get { return _enforce && _protectionOrder == MessageProtectionOrder.EncryptBeforeSign; } } public bool EncryptBeforeSignOrderRequirementMet { get { return _state != ReceiverProcessingOrder.DecryptVerify && _state != ReceiverProcessingOrder.Mixed; } } public bool PrimarySignatureDone { get { return _signatureCount > 0; } } public bool SignBeforeEncryptOrderRequirementMet { get { return _state != ReceiverProcessingOrder.VerifyDecrypt && _state != ReceiverProcessingOrder.Mixed; } } private void EnforceProtectionOrder() { switch (_protectionOrder) { case MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature: throw ExceptionHelper.PlatformNotSupported(); case MessageProtectionOrder.SignBeforeEncrypt: if (!SignBeforeEncryptOrderRequirementMet) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.Format(SR.MessageProtectionOrderMismatch, _protectionOrder))); } break; case MessageProtectionOrder.EncryptBeforeSign: throw ExceptionHelper.PlatformNotSupported(); default: Fx.Assert(""); break; } } public void OnProcessReferenceList() { Fx.Assert(_enforce, "OrderTracker should have 'enforce' set to true."); if (_referenceListCount > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.AtMostOneReferenceListIsSupportedWithDefaultPolicyCheck)); } _referenceListCount++; _state = s_stateTransitionTableOnDecrypt[(int)_state]; if (_enforce) { EnforceProtectionOrder(); } } public void SetRequiredProtectionOrder(MessageProtectionOrder protectionOrder) { _protectionOrder = protectionOrder; _enforce = true; } private enum ReceiverProcessingOrder : int { None = 0, Verify = 1, Decrypt = 2, DecryptVerify = 3, VerifyDecrypt = 4, Mixed = 5 } } private struct OperationTracker { private bool _isDerivedToken; public MessagePartSpecification Parts { get; set; } public SecurityToken Token { get; private set; } public bool IsDerivedToken { get { return _isDerivedToken; } } public void RecordToken(SecurityToken token) { if (Token == null) { Token = token; } else if (!ReferenceEquals(Token, token)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.MismatchInSecurityOperationToken)); } } public void SetDerivationSourceIfRequired() { DerivedKeySecurityToken derivedKeyToken = Token as DerivedKeySecurityToken; if (derivedKeyToken != null) { Token = derivedKeyToken.TokenToDerive; _isDerivedToken = true; } } } } internal class TokenTracker { private bool _allowFirstTokenMismatch; public SupportingTokenAuthenticatorSpecification spec; public SecurityToken Token { get; set; } public bool IsDerivedFrom { get; set; } public bool IsSigned { get; set; } public bool IsEncrypted { get; set; } public bool IsEndorsing { get; set; } public bool AlreadyReadEndorsingSignature { get; set; } public TokenTracker(SupportingTokenAuthenticatorSpecification spec) : this(spec, null, false) { } public TokenTracker(SupportingTokenAuthenticatorSpecification spec, SecurityToken token, bool allowFirstTokenMismatch) { this.spec = spec; Token = token; _allowFirstTokenMismatch = allowFirstTokenMismatch; } public void RecordToken(SecurityToken token) { if (Token == null) { Token = token; } else if (_allowFirstTokenMismatch) { if (!AreTokensEqual(Token, token)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.MismatchInSecurityOperationToken)); } Token = token; _allowFirstTokenMismatch = false; } else if (!object.ReferenceEquals(Token, token)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.MismatchInSecurityOperationToken)); } } private static bool AreTokensEqual(SecurityToken outOfBandToken, SecurityToken replyToken) { // we support the serialized reply token legacy feature only for X509 certificates. // in this case the thumbprint of the reply certificate must match the outofband certificate's thumbprint if ((outOfBandToken is X509SecurityToken) && (replyToken is X509SecurityToken)) { byte[] outOfBandCertificateThumbprint = ((X509SecurityToken)outOfBandToken).Certificate.GetCertHash(); byte[] replyCertificateThumbprint = ((X509SecurityToken)replyToken).Certificate.GetCertHash(); return (SecurityUtils.IsEqual(outOfBandCertificateThumbprint, replyCertificateThumbprint)); } else { return false; } } } internal class AggregateSecurityHeaderTokenResolver : AggregateTokenResolver { private SecurityHeaderTokenResolver _tokenResolver; public AggregateSecurityHeaderTokenResolver(SecurityHeaderTokenResolver tokenResolver, ReadOnlyCollection<SecurityTokenResolver> outOfBandTokenResolvers) : base(outOfBandTokenResolvers) { _tokenResolver = tokenResolver ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(tokenResolver)); } protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key) { bool resolved = false; key = null; resolved = _tokenResolver.TryResolveSecurityKey(keyIdentifierClause, false, out key); if (!resolved) { resolved = base.TryResolveSecurityKeyCore(keyIdentifierClause, out key); } if (!resolved) { resolved = SecurityUtils.TryCreateKeyFromIntrinsicKeyClause(keyIdentifierClause, this, out key); } return resolved; } protected override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token) { bool resolved = false; token = null; resolved = _tokenResolver.TryResolveToken(keyIdentifier, false, false, out token); if (!resolved) { resolved = base.TryResolveTokenCore(keyIdentifier, out token); } if (!resolved) { for (int i = 0; i < keyIdentifier.Count; ++i) { if (TryResolveTokenFromIntrinsicKeyClause(keyIdentifier[i], out token)) { resolved = true; break; } } } return resolved; } private bool TryResolveTokenFromIntrinsicKeyClause(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token) { token = null; if (keyIdentifierClause is X509RawDataKeyIdentifierClause) { token = new X509SecurityToken(new X509Certificate2(((X509RawDataKeyIdentifierClause)keyIdentifierClause).GetX509RawData()), false); return true; } else if (keyIdentifierClause is EncryptedKeyIdentifierClause) { throw ExceptionHelper.PlatformNotSupported(); } return false; } protected override bool TryResolveTokenCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token) { bool resolved = false; token = null; resolved = _tokenResolver.TryResolveToken(keyIdentifierClause, false, false, out token); if (!resolved) { resolved = base.TryResolveTokenCore(keyIdentifierClause, out token); } if (!resolved) { resolved = TryResolveTokenFromIntrinsicKeyClause(keyIdentifierClause, out token); } return resolved; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Linq; using Avalonia.Logging; using Avalonia.VisualTree; namespace Avalonia.Layout { /// <summary> /// Defines how a control aligns itself horizontally in its parent control. /// </summary> public enum HorizontalAlignment { /// <summary> /// The control stretches to fill the width of the parent control. /// </summary> Stretch, /// <summary> /// The control aligns itself to the left of the parent control. /// </summary> Left, /// <summary> /// The control centers itself in the parent control. /// </summary> Center, /// <summary> /// The control aligns itself to the right of the parent control. /// </summary> Right, } /// <summary> /// Defines how a control aligns itself vertically in its parent control. /// </summary> public enum VerticalAlignment { /// <summary> /// The control stretches to fill the height of the parent control. /// </summary> Stretch, /// <summary> /// The control aligns itself to the top of the parent control. /// </summary> Top, /// <summary> /// The control centers itself within the parent control. /// </summary> Center, /// <summary> /// The control aligns itself to the bottom of the parent control. /// </summary> Bottom, } /// <summary> /// Implements layout-related functionality for a control. /// </summary> public class Layoutable : Visual, ILayoutable { /// <summary> /// Defines the <see cref="DesiredSize"/> property. /// </summary> public static readonly DirectProperty<Layoutable, Size> DesiredSizeProperty = AvaloniaProperty.RegisterDirect<Layoutable, Size>(nameof(DesiredSize), o => o.DesiredSize); /// <summary> /// Defines the <see cref="Width"/> property. /// </summary> public static readonly StyledProperty<double> WidthProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(Width), double.NaN); /// <summary> /// Defines the <see cref="Height"/> property. /// </summary> public static readonly StyledProperty<double> HeightProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(Height), double.NaN); /// <summary> /// Defines the <see cref="MinWidth"/> property. /// </summary> public static readonly StyledProperty<double> MinWidthProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(MinWidth)); /// <summary> /// Defines the <see cref="MaxWidth"/> property. /// </summary> public static readonly StyledProperty<double> MaxWidthProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(MaxWidth), double.PositiveInfinity); /// <summary> /// Defines the <see cref="MinHeight"/> property. /// </summary> public static readonly StyledProperty<double> MinHeightProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(MinHeight)); /// <summary> /// Defines the <see cref="MaxHeight"/> property. /// </summary> public static readonly StyledProperty<double> MaxHeightProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(MaxHeight), double.PositiveInfinity); /// <summary> /// Defines the <see cref="Margin"/> property. /// </summary> public static readonly StyledProperty<Thickness> MarginProperty = AvaloniaProperty.Register<Layoutable, Thickness>(nameof(Margin)); /// <summary> /// Defines the <see cref="HorizontalAlignment"/> property. /// </summary> public static readonly StyledProperty<HorizontalAlignment> HorizontalAlignmentProperty = AvaloniaProperty.Register<Layoutable, HorizontalAlignment>(nameof(HorizontalAlignment)); /// <summary> /// Defines the <see cref="VerticalAlignment"/> property. /// </summary> public static readonly StyledProperty<VerticalAlignment> VerticalAlignmentProperty = AvaloniaProperty.Register<Layoutable, VerticalAlignment>(nameof(VerticalAlignment)); /// <summary> /// Defines the <see cref="UseLayoutRoundingProperty"/> property. /// </summary> public static readonly StyledProperty<bool> UseLayoutRoundingProperty = AvaloniaProperty.Register<Layoutable, bool>(nameof(UseLayoutRounding), defaultValue: true, inherits: true); private bool _measuring; private Size? _previousMeasure; private Rect? _previousArrange; /// <summary> /// Initializes static members of the <see cref="Layoutable"/> class. /// </summary> static Layoutable() { AffectsMeasure<Layoutable>( IsVisibleProperty, WidthProperty, HeightProperty, MinWidthProperty, MaxWidthProperty, MinHeightProperty, MaxHeightProperty, MarginProperty, HorizontalAlignmentProperty, VerticalAlignmentProperty); } /// <summary> /// Occurs when a layout pass completes for the control. /// </summary> public event EventHandler LayoutUpdated; /// <summary> /// Gets or sets the width of the element. /// </summary> public double Width { get { return GetValue(WidthProperty); } set { SetValue(WidthProperty, value); } } /// <summary> /// Gets or sets the height of the element. /// </summary> public double Height { get { return GetValue(HeightProperty); } set { SetValue(HeightProperty, value); } } /// <summary> /// Gets or sets the minimum width of the element. /// </summary> public double MinWidth { get { return GetValue(MinWidthProperty); } set { SetValue(MinWidthProperty, value); } } /// <summary> /// Gets or sets the maximum width of the element. /// </summary> public double MaxWidth { get { return GetValue(MaxWidthProperty); } set { SetValue(MaxWidthProperty, value); } } /// <summary> /// Gets or sets the minimum height of the element. /// </summary> public double MinHeight { get { return GetValue(MinHeightProperty); } set { SetValue(MinHeightProperty, value); } } /// <summary> /// Gets or sets the maximum height of the element. /// </summary> public double MaxHeight { get { return GetValue(MaxHeightProperty); } set { SetValue(MaxHeightProperty, value); } } /// <summary> /// Gets or sets the margin around the element. /// </summary> public Thickness Margin { get { return GetValue(MarginProperty); } set { SetValue(MarginProperty, value); } } /// <summary> /// Gets or sets the element's preferred horizontal alignment in its parent. /// </summary> public HorizontalAlignment HorizontalAlignment { get { return GetValue(HorizontalAlignmentProperty); } set { SetValue(HorizontalAlignmentProperty, value); } } /// <summary> /// Gets or sets the element's preferred vertical alignment in its parent. /// </summary> public VerticalAlignment VerticalAlignment { get { return GetValue(VerticalAlignmentProperty); } set { SetValue(VerticalAlignmentProperty, value); } } /// <summary> /// Gets the size that this element computed during the measure pass of the layout process. /// </summary> public Size DesiredSize { get; private set; } /// <summary> /// Gets a value indicating whether the control's layout measure is valid. /// </summary> public bool IsMeasureValid { get; private set; } /// <summary> /// Gets a value indicating whether the control's layouts arrange is valid. /// </summary> public bool IsArrangeValid { get; private set; } /// <summary> /// Gets or sets a value that determines whether the element should be snapped to pixel /// boundaries at layout time. /// </summary> public bool UseLayoutRounding { get { return GetValue(UseLayoutRoundingProperty); } set { SetValue(UseLayoutRoundingProperty, value); } } /// <summary> /// Gets the available size passed in the previous layout pass, if any. /// </summary> Size? ILayoutable.PreviousMeasure => _previousMeasure; /// <summary> /// Gets the layout rect passed in the previous layout pass, if any. /// </summary> Rect? ILayoutable.PreviousArrange => _previousArrange; /// <summary> /// Creates the visual children of the control, if necessary /// </summary> public virtual void ApplyTemplate() { } /// <summary> /// Carries out a measure of the control. /// </summary> /// <param name="availableSize">The available size for the control.</param> public void Measure(Size availableSize) { if (double.IsNaN(availableSize.Width) || double.IsNaN(availableSize.Height)) { throw new InvalidOperationException("Cannot call Measure using a size with NaN values."); } if (!IsMeasureValid || _previousMeasure != availableSize) { var previousDesiredSize = DesiredSize; var desiredSize = default(Size); IsMeasureValid = true; try { _measuring = true; desiredSize = MeasureCore(availableSize).Constrain(availableSize); } finally { _measuring = false; } if (IsInvalidSize(desiredSize)) { throw new InvalidOperationException("Invalid size returned for Measure."); } DesiredSize = desiredSize; _previousMeasure = availableSize; Logger.Verbose(LogArea.Layout, this, "Measure requested {DesiredSize}", DesiredSize); if (DesiredSize != previousDesiredSize) { this.GetVisualParent<ILayoutable>()?.ChildDesiredSizeChanged(this); } } } /// <summary> /// Arranges the control and its children. /// </summary> /// <param name="rect">The control's new bounds.</param> public void Arrange(Rect rect) { if (IsInvalidRect(rect)) { throw new InvalidOperationException("Invalid Arrange rectangle."); } if (!IsMeasureValid) { Measure(_previousMeasure ?? rect.Size); } if (!IsArrangeValid || _previousArrange != rect) { Logger.Verbose(LogArea.Layout, this, "Arrange to {Rect} ", rect); IsArrangeValid = true; ArrangeCore(rect); _previousArrange = rect; LayoutUpdated?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Called by InvalidateMeasure /// </summary> protected virtual void OnMeasureInvalidated() { } /// <summary> /// Invalidates the measurement of the control and queues a new layout pass. /// </summary> public void InvalidateMeasure() { if (IsMeasureValid) { Logger.Verbose(LogArea.Layout, this, "Invalidated measure"); IsMeasureValid = false; IsArrangeValid = false; if (((ILayoutable)this).IsAttachedToVisualTree) { (VisualRoot as ILayoutRoot)?.LayoutManager.InvalidateMeasure(this); InvalidateVisual(); } OnMeasureInvalidated(); } } /// <summary> /// Invalidates the arrangement of the control and queues a new layout pass. /// </summary> public void InvalidateArrange() { if (IsArrangeValid) { Logger.Verbose(LogArea.Layout, this, "Invalidated arrange"); IsArrangeValid = false; (VisualRoot as ILayoutRoot)?.LayoutManager?.InvalidateArrange(this); InvalidateVisual(); } } /// <inheritdoc/> void ILayoutable.ChildDesiredSizeChanged(ILayoutable control) { if (!_measuring) { InvalidateMeasure(); } } /// <summary> /// Marks a property as affecting the control's measurement. /// </summary> /// <param name="properties">The properties.</param> /// <remarks> /// After a call to this method in a control's static constructor, any change to the /// property will cause <see cref="InvalidateMeasure"/> to be called on the element. /// </remarks> [Obsolete("Use AffectsMeasure<T> and specify the control type.")] protected static void AffectsMeasure(params AvaloniaProperty[] properties) { AffectsMeasure<Layoutable>(properties); } /// <summary> /// Marks a property as affecting the control's measurement. /// </summary> /// <typeparam name="T">The control which the property affects.</typeparam> /// <param name="properties">The properties.</param> /// <remarks> /// After a call to this method in a control's static constructor, any change to the /// property will cause <see cref="InvalidateMeasure"/> to be called on the element. /// </remarks> protected static void AffectsMeasure<T>(params AvaloniaProperty[] properties) where T : class, ILayoutable { void Invalidate(AvaloniaPropertyChangedEventArgs e) { (e.Sender as T)?.InvalidateMeasure(); } foreach (var property in properties) { property.Changed.Subscribe(Invalidate); } } /// <summary> /// Marks a property as affecting the control's arrangement. /// </summary> /// <param name="properties">The properties.</param> /// <remarks> /// After a call to this method in a control's static constructor, any change to the /// property will cause <see cref="InvalidateArrange"/> to be called on the element. /// </remarks> [Obsolete("Use AffectsArrange<T> and specify the control type.")] protected static void AffectsArrange(params AvaloniaProperty[] properties) { AffectsArrange<Layoutable>(properties); } /// <summary> /// Marks a property as affecting the control's arrangement. /// </summary> /// <typeparam name="T">The control which the property affects.</typeparam> /// <param name="properties">The properties.</param> /// <remarks> /// After a call to this method in a control's static constructor, any change to the /// property will cause <see cref="InvalidateArrange"/> to be called on the element. /// </remarks> protected static void AffectsArrange<T>(params AvaloniaProperty[] properties) where T : class, ILayoutable { void Invalidate(AvaloniaPropertyChangedEventArgs e) { (e.Sender as T)?.InvalidateArrange(); } foreach (var property in properties) { property.Changed.Subscribe(Invalidate); } } /// <summary> /// The default implementation of the control's measure pass. /// </summary> /// <param name="availableSize">The size available to the control.</param> /// <returns>The desired size for the control.</returns> /// <remarks> /// This method calls <see cref="MeasureOverride(Size)"/> which is probably the method you /// want to override in order to modify a control's arrangement. /// </remarks> protected virtual Size MeasureCore(Size availableSize) { if (IsVisible) { var margin = Margin; ApplyTemplate(); var constrained = LayoutHelper.ApplyLayoutConstraints( this, availableSize.Deflate(margin)); var measured = MeasureOverride(constrained); var width = measured.Width; var height = measured.Height; if (!double.IsNaN(Width)) { width = Width; } width = Math.Min(width, MaxWidth); width = Math.Max(width, MinWidth); if (!double.IsNaN(Height)) { height = Height; } height = Math.Min(height, MaxHeight); height = Math.Max(height, MinHeight); if (UseLayoutRounding) { var scale = GetLayoutScale(); width = Math.Ceiling(width * scale) / scale; height = Math.Ceiling(height * scale) / scale; } return NonNegative(new Size(width, height).Inflate(margin)); } else { return new Size(); } } /// <summary> /// Measures the control and its child elements as part of a layout pass. /// </summary> /// <param name="availableSize">The size available to the control.</param> /// <returns>The desired size for the control.</returns> protected virtual Size MeasureOverride(Size availableSize) { double width = 0; double height = 0; foreach (ILayoutable child in this.GetVisualChildren()) { child.Measure(availableSize); width = Math.Max(width, child.DesiredSize.Width); height = Math.Max(height, child.DesiredSize.Height); } return new Size(width, height); } /// <summary> /// The default implementation of the control's arrange pass. /// </summary> /// <param name="finalRect">The control's new bounds.</param> /// <remarks> /// This method calls <see cref="ArrangeOverride(Size)"/> which is probably the method you /// want to override in order to modify a control's arrangement. /// </remarks> protected virtual void ArrangeCore(Rect finalRect) { if (IsVisible) { var margin = Margin; var originX = finalRect.X + margin.Left; var originY = finalRect.Y + margin.Top; var availableSizeMinusMargins = new Size( Math.Max(0, finalRect.Width - margin.Left - margin.Right), Math.Max(0, finalRect.Height - margin.Top - margin.Bottom)); var horizontalAlignment = HorizontalAlignment; var verticalAlignment = VerticalAlignment; var size = availableSizeMinusMargins; var scale = GetLayoutScale(); if (horizontalAlignment != HorizontalAlignment.Stretch) { size = size.WithWidth(Math.Min(size.Width, DesiredSize.Width - margin.Left - margin.Right)); } if (verticalAlignment != VerticalAlignment.Stretch) { size = size.WithHeight(Math.Min(size.Height, DesiredSize.Height - margin.Top - margin.Bottom)); } size = LayoutHelper.ApplyLayoutConstraints(this, size); if (UseLayoutRounding) { size = new Size( Math.Ceiling(size.Width * scale) / scale, Math.Ceiling(size.Height * scale) / scale); availableSizeMinusMargins = new Size( Math.Ceiling(availableSizeMinusMargins.Width * scale) / scale, Math.Ceiling(availableSizeMinusMargins.Height * scale) / scale); } size = ArrangeOverride(size).Constrain(size); switch (horizontalAlignment) { case HorizontalAlignment.Center: case HorizontalAlignment.Stretch: originX += (availableSizeMinusMargins.Width - size.Width) / 2; break; case HorizontalAlignment.Right: originX += availableSizeMinusMargins.Width - size.Width; break; } switch (verticalAlignment) { case VerticalAlignment.Center: case VerticalAlignment.Stretch: originY += (availableSizeMinusMargins.Height - size.Height) / 2; break; case VerticalAlignment.Bottom: originY += availableSizeMinusMargins.Height - size.Height; break; } if (UseLayoutRounding) { originX = Math.Floor(originX * scale) / scale; originY = Math.Floor(originY * scale) / scale; } Bounds = new Rect(originX, originY, size.Width, size.Height); } } /// <summary> /// Positions child elements as part of a layout pass. /// </summary> /// <param name="finalSize">The size available to the control.</param> /// <returns>The actual size used.</returns> protected virtual Size ArrangeOverride(Size finalSize) { foreach (ILayoutable child in this.GetVisualChildren().OfType<ILayoutable>()) { child.Arrange(new Rect(finalSize)); } return finalSize; } /// <inheritdoc/> protected override sealed void OnVisualParentChanged(IVisual oldParent, IVisual newParent) { foreach (ILayoutable i in this.GetSelfAndVisualDescendants()) { i.InvalidateMeasure(); } base.OnVisualParentChanged(oldParent, newParent); } /// <summary> /// Tests whether any of a <see cref="Rect"/>'s properties include negative values, /// a NaN or Infinity. /// </summary> /// <param name="rect">The rect.</param> /// <returns>True if the rect is invalid; otherwise false.</returns> private static bool IsInvalidRect(Rect rect) { return rect.Width < 0 || rect.Height < 0 || double.IsInfinity(rect.X) || double.IsInfinity(rect.Y) || double.IsInfinity(rect.Width) || double.IsInfinity(rect.Height) || double.IsNaN(rect.X) || double.IsNaN(rect.Y) || double.IsNaN(rect.Width) || double.IsNaN(rect.Height); } /// <summary> /// Tests whether any of a <see cref="Size"/>'s properties include negative values, /// a NaN or Infinity. /// </summary> /// <param name="size">The size.</param> /// <returns>True if the size is invalid; otherwise false.</returns> private static bool IsInvalidSize(Size size) { return size.Width < 0 || size.Height < 0 || double.IsInfinity(size.Width) || double.IsInfinity(size.Height) || double.IsNaN(size.Width) || double.IsNaN(size.Height); } /// <summary> /// Ensures neither component of a <see cref="Size"/> is negative. /// </summary> /// <param name="size">The size.</param> /// <returns>The non-negative size.</returns> private static Size NonNegative(Size size) { return new Size(Math.Max(size.Width, 0), Math.Max(size.Height, 0)); } private double GetLayoutScale() { var result = (VisualRoot as ILayoutRoot)?.LayoutScaling ?? 1.0; if (result == 0 || double.IsNaN(result) || double.IsInfinity(result)) { throw new Exception($"Invalid LayoutScaling returned from {VisualRoot.GetType()}"); } return result; } } }
// Copyright 2016 Esri. // // 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 Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks; using Esri.ArcGISRuntime.Tasks.Geoprocessing; using Esri.ArcGISRuntime.UI; using System; using System.Collections.Generic; using System.Threading.Tasks; using Xamarin.Forms; namespace ArcGISRuntime.Samples.AnalyzeViewshed { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Analyze viewshed (geoprocessing)", category: "Geoprocessing", description: "Calculate a viewshed using a geoprocessing service, in this case showing what parts of a landscape are visible from points on mountainous terrain.", instructions: "Tap the map to see all areas visible from that point within a 15km radius. Clicking on an elevated area will highlight a larger part of the surrounding landscape. It may take a few seconds for the task to run and send back the results.", tags: new[] { "geoprocessing", "heat map", "heatmap", "viewshed" })] public partial class AnalyzeViewshed : ContentPage { // Url for the geoprocessing service private const string _viewshedUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Elevation/ESRI_Elevation_World/GPServer/Viewshed"; // The graphics overlay to show where the user clicked in the map private GraphicsOverlay _inputOverlay; // The graphics overlay to display the result of the viewshed analysis private GraphicsOverlay _resultOverlay; public AnalyzeViewshed() { InitializeComponent(); // Create the UI, setup the control references and execute initialization Initialize(); } private void Initialize() { // Create a map with topographic basemap and an initial location Map myMap = new Map(BasemapType.Topographic, 45.3790902612337, 6.84905317262762, 13); // Hook into the MapView tapped event MyMapView.GeoViewTapped += MyMapView_GeoViewTapped; // Create empty overlays for the user clicked location and the results of the viewshed analysis CreateOverlays(); // Assign the map to the MapView MyMapView.Map = myMap; } private async void MyMapView_GeoViewTapped(object sender, Esri.ArcGISRuntime.Xamarin.Forms.GeoViewInputEventArgs e) { // Indicate that the geoprocessing is running SetBusy(); // Clear previous user click location and the viewshed geoprocessing task results _inputOverlay.Graphics.Clear(); _resultOverlay.Graphics.Clear(); // Get the tapped point MapPoint geometry = e.Location; // Create a marker graphic where the user clicked on the map and add it to the existing graphics overlay Graphic myInputGraphic = new Graphic(geometry); _inputOverlay.Graphics.Add(myInputGraphic); // Normalize the geometry if wrap-around is enabled // This is necessary because of how wrapped-around map coordinates are handled by Runtime // Without this step, the task may fail because wrapped-around coordinates are out of bounds. if (MyMapView.IsWrapAroundEnabled) { geometry = (MapPoint)GeometryEngine.NormalizeCentralMeridian(geometry); } try { // Execute the geoprocessing task using the user click location await CalculateViewshed(geometry); } catch (Exception ex) { await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK"); } } private async Task CalculateViewshed(MapPoint location) { // This function will define a new geoprocessing task that performs a custom viewshed analysis based upon a // user click on the map and then display the results back as a polygon fill graphics overlay. If there // is a problem with the execution of the geoprocessing task an error message will be displayed // Create new geoprocessing task using the url defined in the member variables section GeoprocessingTask myViewshedTask = await GeoprocessingTask.CreateAsync(new Uri(_viewshedUrl)); // Create a new feature collection table based upon point geometries using the current map view spatial reference FeatureCollectionTable myInputFeatures = new FeatureCollectionTable(new List<Field>(), GeometryType.Point, MyMapView.SpatialReference); // Create a new feature from the feature collection table. It will not have a coordinate location (x,y) yet Feature myInputFeature = myInputFeatures.CreateFeature(); // Assign a physical location to the new point feature based upon where the user clicked in the map view myInputFeature.Geometry = location; // Add the new feature with (x,y) location to the feature collection table await myInputFeatures.AddFeatureAsync(myInputFeature); // Create the parameters that are passed to the used geoprocessing task GeoprocessingParameters myViewshedParameters = new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute) { // Request the output features to use the same SpatialReference as the map view OutputSpatialReference = MyMapView.SpatialReference }; // Add an input location to the geoprocessing parameters myViewshedParameters.Inputs.Add("Input_Observation_Point", new GeoprocessingFeatures(myInputFeatures)); // Create the job that handles the communication between the application and the geoprocessing task GeoprocessingJob myViewshedJob = myViewshedTask.CreateJob(myViewshedParameters); try { // Execute analysis and wait for the results GeoprocessingResult myAnalysisResult = await myViewshedJob.GetResultAsync(); // Get the results from the outputs GeoprocessingFeatures myViewshedResultFeatures = (GeoprocessingFeatures)myAnalysisResult.Outputs["Viewshed_Result"]; // Add all the results as a graphics to the map IFeatureSet myViewshedAreas = myViewshedResultFeatures.Features; foreach (Feature myFeature in myViewshedAreas) { _resultOverlay.Graphics.Add(new Graphic(myFeature.Geometry)); } } catch (Exception ex) { // Display an error message if there is a problem if (myViewshedJob.Status == JobStatus.Failed && myViewshedJob.Error != null) { await Application.Current.MainPage.DisplayAlert("Geoprocessing error", "Executing geoprocessing failed. " + myViewshedJob.Error.Message, "OK"); } else { await Application.Current.MainPage.DisplayAlert("Sample error", "An error occurred. " + ex.ToString(), "OK"); } } finally { // Indicate that the geoprocessing is not running SetBusy(false); } } private void CreateOverlays() { // This function will create the overlays that show the user clicked location and the results of the // viewshed analysis. Note: the overlays will not be populated with any graphics at this point // Create renderer for input graphic. Set the size and color properties for the simple renderer SimpleRenderer myInputRenderer = new SimpleRenderer() { Symbol = new SimpleMarkerSymbol() { Size = 15, Color = System.Drawing.Color.Red } }; // Create overlay to where input graphic is shown _inputOverlay = new GraphicsOverlay() { Renderer = myInputRenderer }; // Create fill renderer for output of the viewshed analysis. Set the color property of the simple renderer SimpleRenderer myResultRenderer = new SimpleRenderer() { Symbol = new SimpleFillSymbol() { Color = System.Drawing.Color.FromArgb(100, 226, 119, 40) } }; // Create overlay to where viewshed analysis graphic is shown _resultOverlay = new GraphicsOverlay() { Renderer = myResultRenderer }; // Add the created overlays to the MapView MyMapView.GraphicsOverlays.Add(_inputOverlay); MyMapView.GraphicsOverlays.Add(_resultOverlay); } private void SetBusy(bool isBusy = true) { // This function toggles running of the 'progress' control feedback status to denote if // the viewshed analysis is executing as a result of the user click on the map if (isBusy) { // Show busy activity indication MyActivityIndicator.IsVisible = true; MyActivityIndicator.IsRunning = true; } else { // Remove the busy activity indication MyActivityIndicator.IsRunning = false; MyActivityIndicator.IsVisible = false; } } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using NuGet.Commands; using NuGet.Common; namespace NuGet { public class Program { private const string NuGetExtensionsKey = "NUGET_EXTENSIONS_PATH"; private static readonly string ExtensionsDirectoryRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Commands"); [Import] public HelpCommand HelpCommand { get; set; } [ImportMany] public IEnumerable<ICommand> Commands { get; set; } [Import] public ICommandManager Manager { get; set; } /// <summary> /// Flag meant for unit tests that prevents command line extensions from being loaded. /// </summary> public static bool IgnoreExtensions { get; set; } public static int Main(string[] args) { DebugHelper.WaitForAttach(ref args); // This is to avoid applying weak event pattern usage, which breaks under Mono or restricted environments, e.g. Windows Azure Web Sites. EnvironmentUtility.SetRunningFromCommandLine(); // set output encoding to UTF8 if -utf8 is specified var oldOutputEncoding = System.Console.OutputEncoding; if (args.Any(arg => String.Equals(arg, "-utf8", StringComparison.OrdinalIgnoreCase))) { args = args.Where(arg => !String.Equals(arg, "-utf8", StringComparison.OrdinalIgnoreCase)).ToArray(); SetConsoleOutputEncoding(System.Text.Encoding.UTF8); } var console = new Common.Console(); var fileSystem = new PhysicalFileSystem(Directory.GetCurrentDirectory()); Func<Exception, string> getErrorMessage = e => e.Message; try { // Remove NuGet.exe.old RemoveOldFile(fileSystem); // Import Dependencies var p = new Program(); p.Initialize(fileSystem, console); // Add commands to the manager foreach (ICommand cmd in p.Commands) { p.Manager.RegisterCommand(cmd); } CommandLineParser parser = new CommandLineParser(p.Manager); // Parse the command ICommand command = parser.ParseCommandLine(args) ?? p.HelpCommand; // Fallback on the help command if we failed to parse a valid command if (!ArgumentCountValid(command)) { // Get the command name and add it to the argument list of the help command string commandName = command.CommandAttribute.CommandName; // Print invalid command then show help console.WriteLine(LocalizedResourceManager.GetString("InvalidArguments"), commandName); p.HelpCommand.ViewHelpForCommand(commandName); } else { SetConsoleInteractivity(console, command as Command); // When we're detailed, get the whole exception including the stack // This is useful for debugging errors. if (console.Verbosity == Verbosity.Detailed) { getErrorMessage = e => e.ToString(); } command.Execute(); } } catch (AggregateException exception) { string message; Exception unwrappedEx = ExceptionUtility.Unwrap(exception); if (unwrappedEx == exception) { // If the AggregateException contains more than one InnerException, it cannot be unwrapped. In which case, simply print out individual error messages message = String.Join(Environment.NewLine, exception.InnerExceptions.Select(getErrorMessage).Distinct(StringComparer.CurrentCulture)); } else { message = getErrorMessage(ExceptionUtility.Unwrap(exception)); } console.WriteError(message); return 1; } catch (Exception e) { console.WriteError(getErrorMessage(ExceptionUtility.Unwrap(e))); return 1; } finally { OptimizedZipPackage.PurgeCache(); SetConsoleOutputEncoding(oldOutputEncoding); } return 0; } private static void SetConsoleOutputEncoding(System.Text.Encoding encoding) { try { System.Console.OutputEncoding = encoding; } catch (IOException) { } } private void Initialize(IFileSystem fileSystem, IConsole console) { using (var catalog = new AggregateCatalog(new AssemblyCatalog(GetType().Assembly))) { if (!IgnoreExtensions) { AddExtensionsToCatalog(catalog, console); } using (var container = new CompositionContainer(catalog)) { container.ComposeExportedValue<IConsole>(console); container.ComposeExportedValue<IPackageRepositoryFactory>(new NuGet.Common.CommandLineRepositoryFactory(console)); container.ComposeExportedValue<IFileSystem>(fileSystem); container.ComposeExportedValue<IShimControllerProvider>(new NuGet.ShimV3.ShimControllerProvider()); container.ComposeParts(this); } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want to block the exe from usage if anything failed")] internal static void RemoveOldFile(IFileSystem fileSystem) { string oldFile = typeof(Program).Assembly.Location + ".old"; try { if (fileSystem.FileExists(oldFile)) { fileSystem.DeleteFile(oldFile); } } catch { // We don't want to block the exe from usage if anything failed } } public static bool ArgumentCountValid(ICommand command) { CommandAttribute attribute = command.CommandAttribute; return command.Arguments.Count >= attribute.MinArgs && command.Arguments.Count <= attribute.MaxArgs; } private static void AddExtensionsToCatalog(AggregateCatalog catalog, IConsole console) { IEnumerable<string> directories = new[] { ExtensionsDirectoryRoot }; var customExtensions = Environment.GetEnvironmentVariable(NuGetExtensionsKey); if (!String.IsNullOrEmpty(customExtensions)) { // Add all directories from the environment variable if available. directories = directories.Concat(customExtensions.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)); } IEnumerable<string> files; foreach (var directory in directories) { if (Directory.Exists(directory)) { files = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories); RegisterExtensions(catalog, files, console); } } // Ideally we want to look for all files. However, using MEF to identify imports results in assemblies being loaded and locked by our App Domain // which could be slow, might affect people's build systems and among other things breaks our build. // Consequently, we'll use a convention - only binaries ending in the name Extensions would be loaded. var nugetDirectory = Path.GetDirectoryName(typeof(Program).Assembly.Location); files = Directory.EnumerateFiles(nugetDirectory, "*Extensions.dll"); RegisterExtensions(catalog, files, console); } private static void RegisterExtensions(AggregateCatalog catalog, IEnumerable<string> enumerateFiles, IConsole console) { foreach (var item in enumerateFiles) { try { catalog.Catalogs.Add(new AssemblyCatalog(item)); } catch (BadImageFormatException ex) { // Ignore if the dll wasn't a valid assembly console.WriteWarning(ex.Message); } catch (FileLoadException ex) { // Ignore if we couldn't load the assembly. console.WriteWarning(ex.Message); } } } private static void SetConsoleInteractivity(IConsole console, Command command) { // Global environment variable to prevent the exe for prompting for credentials string globalSwitch = Environment.GetEnvironmentVariable("NUGET_EXE_NO_PROMPT"); // When running from inside VS, no input is available to our executable locking up VS. // VS sets up a couple of environment variables one of which is named VisualStudioVersion. // Every time this is setup, we will just fail. // TODO: Remove this in next iteration. This is meant for short-term backwards compat. string vsSwitch = Environment.GetEnvironmentVariable("VisualStudioVersion"); console.IsNonInteractive = !String.IsNullOrEmpty(globalSwitch) || !String.IsNullOrEmpty(vsSwitch) || (command != null && command.NonInteractive); string forceInteractive = Environment.GetEnvironmentVariable("FORCE_NUGET_EXE_INTERACTIVE"); if (!String.IsNullOrEmpty(forceInteractive)) { console.IsNonInteractive = false; } if (command != null) { console.Verbosity = command.Verbosity; } } } }
// 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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MetadataMemberTests : CSharpTestBase { private const string VTableGapClassIL = @" .class public auto ansi beforefieldinit Class extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void _VtblGap1_1() cil managed { ret } .method public hidebysig specialname instance int32 _VtblGap2_1() cil managed { ret } .method public hidebysig specialname instance void set_GetterIsGap(int32 'value') cil managed { ret } .method public hidebysig specialname instance int32 get_SetterIsGap() cil managed { ret } .method public hidebysig specialname instance void _VtblGap3_1(int32 'value') cil managed { ret } .method public hidebysig specialname instance int32 _VtblGap4_1() cil managed { ret } .method public hidebysig specialname instance void _VtblGap5_1(int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .property instance int32 GetterIsGap() { .get instance int32 Class::_VtblGap2_1() .set instance void Class::set_GetterIsGap(int32) } // end of property Class::GetterIsGap .property instance int32 SetterIsGap() { .get instance int32 Class::get_SetterIsGap() .set instance void Class::_VtblGap3_1(int32) } // end of property Class::SetterIsGap .property instance int32 BothAccessorsAreGaps() { .get instance int32 Class::_VtblGap4_1() .set instance void Class::_VtblGap5_1(int32) } // end of property Class::BothAccessorsAreGaps } // end of class Class "; private const string VTableGapInterfaceIL = @" .class interface public abstract auto ansi Interface { .method public hidebysig newslot specialname rtspecialname abstract virtual instance void _VtblGap1_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 _VtblGap2_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_GetterIsGap(int32 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 get_SetterIsGap() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void _VtblGap3_1(int32 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 _VtblGap4_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void _VtblGap5_1(int32 'value') cil managed { } .property instance int32 GetterIsGap() { .get instance int32 Interface::_VtblGap2_1() .set instance void Interface::set_GetterIsGap(int32) } // end of property Interface::GetterIsGap .property instance int32 SetterIsGap() { .get instance int32 Interface::get_SetterIsGap() .set instance void Interface::_VtblGap3_1(int32) } // end of property Interface::SetterIsGap .property instance int32 BothAccessorsAreGaps() { .get instance int32 Interface::_VtblGap4_1() .set instance void Interface::_VtblGap5_1(int32) } // end of property Interface::BothAccessorsAreGaps } // end of class Interface "; [WorkItem(537346, "DevDiv")] [Fact] public void MetadataMethodSymbolCtor01() { var text = "public class A {}"; var compilation = CreateCompilationWithMscorlib(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var type1 = ns1.GetTypeMembers("StringComparer").Single() as NamedTypeSymbol; var ctor = type1.InstanceConstructors.Single(); Assert.Equal(type1, ctor.ContainingSymbol); Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name); Assert.Equal(SymbolKind.Method, ctor.Kind); Assert.Equal(MethodKind.Constructor, ctor.MethodKind); Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility); Assert.True(ctor.IsDefinition); Assert.False(ctor.IsStatic); Assert.False(ctor.IsSealed); Assert.False(ctor.IsOverride); Assert.False(ctor.IsExtensionMethod); Assert.True(ctor.ReturnsVoid); Assert.False(ctor.IsVararg); // Bug - 2067 Assert.Equal("System.StringComparer." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString()); Assert.Equal(0, ctor.TypeParameters.Length); Assert.Equal("Void", ctor.ReturnType.Name); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(537345, "DevDiv")] [Fact] public void MetadataMethodSymbol01() { var text = "public class A {}"; var compilation = CreateCompilationWithMscorlib(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns3.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; var members = class1.GetMembers("StrongNameSignatureGeneration"); // 4 overloads Assert.Equal(4, members.Length); var member1 = members.Last() as MethodSymbol; Assert.Equal(mscorNS, member1.ContainingAssembly); Assert.Equal(class1, member1.ContainingSymbol); Assert.Equal(SymbolKind.Method, member1.Kind); Assert.Equal(MethodKind.Ordinary, member1.MethodKind); Assert.Equal(Accessibility.Public, member1.DeclaredAccessibility); Assert.True(member1.IsDefinition); Assert.True(member1.IsStatic); Assert.False(member1.IsAbstract); Assert.False(member1.IsSealed); Assert.False(member1.IsVirtual); Assert.False(member1.IsOverride); // Bug - // Assert.True(member1.IsOverloads); Assert.False(member1.IsGenericMethod); // Not Impl // Assert.False(member1.IsExtensionMethod); Assert.False(member1.ReturnsVoid); Assert.False(member1.IsVararg); var fullName = "System.Boolean Microsoft.Runtime.Hosting.StrongNameHelpers.StrongNameSignatureGeneration(System.String pwzFilePath, System.String pwzKeyContainer, System.Byte[] bKeyBlob, System.Int32 cbKeyBlob, ref System.IntPtr ppbSignatureBlob, out System.Int32 pcbSignatureBlob)"; Assert.Equal(fullName, member1.ToTestDisplayString()); Assert.Equal(0, member1.TypeArguments.Length); Assert.Equal(0, member1.TypeParameters.Length); Assert.Equal(6, member1.Parameters.Length); Assert.Equal("Boolean", member1.ReturnType.Name); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(527150, "DevDiv")] [WorkItem(527151, "DevDiv")] [Fact] public void MetadataParameterSymbol01() { var text = "public class A {}"; var compilation = CreateCompilationWithMscorlib(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = (ns1.GetMembers("Runtime").Single() as NamespaceSymbol).GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns2.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; var members = class1.GetMembers("StrongNameSignatureGeneration"); var member1 = members.Last() as MethodSymbol; Assert.Equal(6, member1.Parameters.Length); var p1 = member1.Parameters[0] as ParameterSymbol; var p2 = member1.Parameters[1] as ParameterSymbol; var p3 = member1.Parameters[2] as ParameterSymbol; var p4 = member1.Parameters[3] as ParameterSymbol; var p5 = member1.Parameters[4] as ParameterSymbol; var p6 = member1.Parameters[5] as ParameterSymbol; Assert.Equal(mscorNS, p1.ContainingAssembly); Assert.Equal(class1, p1.ContainingType); Assert.Equal(member1, p1.ContainingSymbol); Assert.Equal(SymbolKind.Parameter, p1.Kind); Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility); Assert.Equal("pwzFilePath", p1.Name); Assert.Equal("System.String pwzKeyContainer", p2.ToTestDisplayString()); Assert.Equal("String", p2.Type.Name); Assert.True(p2.IsDefinition); Assert.Equal("System.Byte[] bKeyBlob", p3.ToTestDisplayString()); Assert.Equal("System.Byte[]", p3.Type.ToTestDisplayString()); //array types do not have names - use ToTestDisplayString Assert.False(p1.IsStatic); Assert.False(p1.IsAbstract); Assert.False(p2.IsSealed); Assert.False(p2.IsVirtual); Assert.False(p3.IsOverride); Assert.False(p3.IsParams); Assert.False(p4.IsOptional); Assert.False(p4.HasExplicitDefaultValue); // Not Impl - out of scope // Assert.Null(p4.DefaultValue); Assert.Equal("ppbSignatureBlob", p5.Name); Assert.Equal("IntPtr", p5.Type.Name); Assert.Equal(RefKind.Ref, p5.RefKind); Assert.Equal("out System.Int32 pcbSignatureBlob", p6.ToTestDisplayString()); Assert.Equal(RefKind.Out, p6.RefKind); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataMethodSymbolGen02() { var text = "public class A {}"; var compilation = CreateCompilationWithMscorlib(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IDictionary").First() as NamedTypeSymbol; var member1 = type1.GetMembers("Add").Single() as MethodSymbol; var member2 = type1.GetMembers("TryGetValue").Single() as MethodSymbol; Assert.Equal(mscorNS, member1.ContainingAssembly); Assert.Equal(type1, member1.ContainingSymbol); Assert.Equal(SymbolKind.Method, member1.Kind); // Not Impl //Assert.Equal(MethodKind.Ordinary, member2.MethodKind); Assert.Equal(Accessibility.Public, member2.DeclaredAccessibility); Assert.True(member2.IsDefinition); Assert.False(member1.IsStatic); Assert.True(member1.IsAbstract); Assert.False(member2.IsSealed); Assert.False(member2.IsVirtual); Assert.False(member2.IsOverride); //Assert.True(member1.IsOverloads); //Assert.True(member2.IsOverloads); Assert.False(member1.IsGenericMethod); // Not Impl //Assert.False(member1.IsExtensionMethod); Assert.True(member1.ReturnsVoid); Assert.False(member2.IsVararg); Assert.Equal(0, member1.TypeArguments.Length); Assert.Equal(0, member2.TypeParameters.Length); Assert.Equal(2, member1.Parameters.Length); Assert.Equal("Boolean", member2.ReturnType.Name); Assert.Equal("System.Boolean System.Collections.Generic.IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)", member2.ToTestDisplayString()); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataParameterSymbolGen02() { var text = "public class A {}"; var compilation = CreateCompilationWithMscorlib(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IDictionary").First() as NamedTypeSymbol; var member1 = type1.GetMembers("TryGetValue").Single() as MethodSymbol; Assert.Equal(2, member1.Parameters.Length); var p1 = member1.Parameters[0] as ParameterSymbol; var p2 = member1.Parameters[1] as ParameterSymbol; Assert.Equal(mscorNS, p1.ContainingAssembly); Assert.Equal(type1, p2.ContainingType); Assert.Equal(member1, p1.ContainingSymbol); Assert.Equal(SymbolKind.Parameter, p2.Kind); Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility); Assert.Equal("value", p2.Name); Assert.Equal("TKey key", p1.ToTestDisplayString()); // Empty // Assert.Equal("TValue", p2.Type.Name); Assert.True(p2.IsDefinition); Assert.False(p1.IsStatic); Assert.False(p1.IsAbstract); Assert.False(p2.IsSealed); Assert.False(p2.IsVirtual); Assert.False(p1.IsOverride); Assert.False(p1.IsExtern); Assert.False(p1.IsParams); Assert.False(p2.IsOptional); Assert.False(p2.HasExplicitDefaultValue); // Not Impl - Not in M2 scope // Assert.Null(p2.DefaultValue); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(537424, "DevDiv")] [Fact] public void MetadataMethodStaticAndInstanceCtor() { var text = @" class C { C() { } static C() { } }"; var compilation = CreateCompilationWithMscorlib(text); Assert.False(compilation.GetDiagnostics().Any()); var classC = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single(); // NamedTypeSymbol.Constructors only contains instance constructors Assert.Equal(1, classC.InstanceConstructors.Length); Assert.Equal(1, classC.GetMembers(WellKnownMemberNames.StaticConstructorName).Length); } [ClrOnlyFact] public void ImportDecimalConstantAttribute() { const string ilSource = @" .class public C extends [mscorlib]System.Object { .field public static initonly valuetype [mscorlib]System.Decimal MyDecimalTen .custom instance void [mscorlib]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 00 00 ) } // end of class C"; const string cSharpSource = @" class B { static void Main() { var x = C.MyDecimalTen; System.Console.Write(x); } } "; CompileWithCustomILSource(cSharpSource, ilSource, emitOptions: TestEmitters.RefEmitBug, expectedOutput: "10"); } [Fact] public void TypeAndNamespaceWithSameNameButDifferentArities() { var il = @" .class interface public abstract auto ansi A.B.C { } .class interface public abstract auto ansi A.B`1<T> { } "; var csharp = @""; var compilation = CreateCompilationWithCustomILSource(csharp, il); var namespaceA = compilation.GlobalNamespace.GetMember<NamespaceSymbol>("A"); var members = namespaceA.GetMembers("B"); Assert.Equal(2, members.Length); Assert.NotNull(members[0]); Assert.NotNull(members[1]); } [Fact] public void TypeAndNamespaceWithSameNameAndArity() { var il = @" .class interface public abstract auto ansi A.B.C { } .class interface public abstract auto ansi A.B { } "; var csharp = @""; var compilation = CreateCompilationWithCustomILSource(csharp, il); var namespaceA = compilation.GlobalNamespace.GetMember<NamespaceSymbol>("A"); var members = namespaceA.GetMembers("B"); Assert.Equal(2, members.Length); Assert.NotNull(members[0]); Assert.NotNull(members[1]); } // TODO: Update this test if we decide to include gaps in the symbol table for NoPIA (DevDiv #17472). [WorkItem(546951, "DevDiv")] [Fact] public void VTableGapsNotInSymbolTable() { var csharp = @""; var comp = CreateCompilationWithCustomILSource(csharp, VTableGapClassIL); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Class"); AssertEx.None(type.GetMembersUnordered(), symbol => symbol.Name.StartsWith("_VtblGap", StringComparison.Ordinal)); // Dropped entirely. Assert.Equal(0, type.GetMembers("_VtblGap1_1").Length); // Dropped entirely, since both accessors are dropped. Assert.Equal(0, type.GetMembers("BothAccessorsAreGaps").Length); // Getter is silently dropped, property appears valid and write-only. var propWithoutGetter = type.GetMember<PropertySymbol>("GetterIsGap"); Assert.Null(propWithoutGetter.GetMethod); Assert.NotNull(propWithoutGetter.SetMethod); Assert.False(propWithoutGetter.MustCallMethodsDirectly); // Setter is silently dropped, property appears valid and read-only. var propWithoutSetter = type.GetMember<PropertySymbol>("SetterIsGap"); Assert.NotNull(propWithoutSetter.GetMethod); Assert.Null(propWithoutSetter.SetMethod); Assert.False(propWithoutSetter.MustCallMethodsDirectly); } [WorkItem(546951, "DevDiv")] [Fact] public void CallVTableGap() { var csharp = @" class Test { static void Main() { Class c = new Class(); c._VtblGap1_1(); // CS1061 int x; x = c.BothAccessorsAreGaps; // CS1061 c.BothAccessorsAreGaps = x; // CS1061 x = c.GetterIsGap; // CS0154 c.GetterIsGap = x; x = c.SetterIsGap; c.SetterIsGap = x; // CS0200 } } "; var comp = CreateCompilationWithCustomILSource(csharp, VTableGapClassIL); comp.VerifyDiagnostics( // (8,11): error CS1061: 'Class' does not contain a definition for '_VtblGap1_1' and no extension method '_VtblGap1_1' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c._VtblGap1_1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "_VtblGap1_1").WithArguments("Class", "_VtblGap1_1"), // (12,15): error CS1061: 'Class' does not contain a definition for 'BothAccessorsAreGaps' and no extension method 'BothAccessorsAreGaps' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // x = c.BothAccessorsAreGaps; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BothAccessorsAreGaps").WithArguments("Class", "BothAccessorsAreGaps"), // (13,11): error CS1061: 'Class' does not contain a definition for 'BothAccessorsAreGaps' and no extension method 'BothAccessorsAreGaps' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.BothAccessorsAreGaps = x; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BothAccessorsAreGaps").WithArguments("Class", "BothAccessorsAreGaps"), // (15,13): error CS0154: The property or indexer 'Class.GetterIsGap' cannot be used in this context because it lacks the get accessor // x = c.GetterIsGap; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c.GetterIsGap").WithArguments("Class.GetterIsGap"), // (19,9): error CS0200: Property or indexer 'Class.SetterIsGap' cannot be assigned to -- it is read only // c.SetterIsGap = x; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.SetterIsGap").WithArguments("Class.SetterIsGap")); } [WorkItem(546951, "DevDiv")] [Fact] public void ImplementVTableGap() { var csharp = @" class Empty : Interface { } class Implicit : Interface { public void _VtblGap1_1() { } public int GetterIsGap { get; set; } public int SetterIsGap { get; set; } public int BothAccessorsAreGaps { get; set; } } class Explicit : Interface { void Interface._VtblGap1_1() { } int Interface.GetterIsGap { get; set; } int Interface.SetterIsGap { get; set; } int Interface.BothAccessorsAreGaps { get; set; } } "; var comp = CreateCompilationWithCustomILSource(csharp, VTableGapInterfaceIL); comp.VerifyDiagnostics( // (2,7): error CS0535: 'Empty' does not implement interface member 'Interface.SetterIsGap' // class Empty : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Empty", "Interface.SetterIsGap"), // (2,7): error CS0535: 'Empty' does not implement interface member 'Interface.GetterIsGap' // class Empty : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Empty", "Interface.GetterIsGap"), // (17,33): error CS0550: 'Explicit.Interface.GetterIsGap.get' adds an accessor not found in interface member 'Interface.GetterIsGap' // int Interface.GetterIsGap { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Explicit.Interface.GetterIsGap.get", "Interface.GetterIsGap"), // (18,38): error CS0550: 'Explicit.Interface.SetterIsGap.set' adds an accessor not found in interface member 'Interface.SetterIsGap' // int Interface.SetterIsGap { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Explicit.Interface.SetterIsGap.set", "Interface.SetterIsGap"), // (19,19): error CS0539: 'Explicit.BothAccessorsAreGaps' in explicit interface declaration is not a member of interface // int Interface.BothAccessorsAreGaps { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "BothAccessorsAreGaps").WithArguments("Explicit.BothAccessorsAreGaps"), // (16,20): error CS0539: 'Explicit._VtblGap1_1()' in explicit interface declaration is not a member of interface // void Interface._VtblGap1_1() { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "_VtblGap1_1").WithArguments("Explicit._VtblGap1_1()")); } [Fact, WorkItem(1094411, "DevDiv")] public void Bug1094411_01() { var source1 = @" class Test { public int F; public int P {get; set;} public event System.Action E { add { } remove { } } public void M() {} } "; var members = new[] { "F", "P", "E", "M" }; var comp1 = CreateCompilationWithMscorlib(source1, options: TestOptions.ReleaseDll); var test1 = comp1.GetTypeByMetadataName("Test"); var memberNames1 = new HashSet<string>(test1.MemberNames); foreach (var m in members) { Assert.True(memberNames1.Contains(m), m); } var comp2 = CreateCompilationWithMscorlib("", new[] { comp1.EmitToImageReference() }); var test2 = comp2.GetTypeByMetadataName("Test"); var memberNames2 = new HashSet<string>(test2.MemberNames); foreach (var m in members) { Assert.True(memberNames2.Contains(m), m); } } [Fact, WorkItem(1094411, "DevDiv")] public void Bug1094411_02() { var source1 = @" class Test { public int F; public int P {get; set;} public event System.Action E { add { } remove { } } public void M() {} } "; var members = new[] { "F", "P", "E", "M" }; var comp1 = CreateCompilationWithMscorlib(source1, options: TestOptions.ReleaseDll); var test1 = comp1.GetTypeByMetadataName("Test"); test1.GetMembers(); var memberNames1 = new HashSet<string>(test1.MemberNames); foreach (var m in members) { Assert.True(memberNames1.Contains(m), m); } var comp2 = CreateCompilationWithMscorlib("", new[] { comp1.EmitToImageReference() }); var test2 = comp2.GetTypeByMetadataName("Test"); test2.GetMembers(); var memberNames2 = new HashSet<string>(test2.MemberNames); foreach (var m in members) { Assert.True(memberNames2.Contains(m), m); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Windows.Media; using Caliburn.Micro; using Cocoa.Document.SpellCheck; using Cocoa.DocumentSources.MetaWeblog; using Cocoa.Events; using Cocoa.Framework; using Cocoa.Plugins; using Cocoa.Settings.Models; namespace Cocoa.Settings.UI { public class SettingsViewModel : Screen { public const string FontSizeSettingsKey = "Font"; public const string FontFamilySettingsKey = "FontFamily"; private readonly ISettingsProvider settingsProvider; private readonly IEventAggregator eventAggregator; private readonly Func<IPlugin, PluginViewModel> pluginViewModelCreator; private readonly ISpellingService spellingService; private readonly IList<IPlugin> plugins; private readonly IBlogService blogService; private readonly ICocoaRegistryEditor CocoaRegistryEditor; private BlogSetting currentBlog; public IEnumerable<ExtensionViewModel> Extensions { get; set; } public IEnumerable<FontSizes> FontSizes { get; set; } public IEnumerable<FontFamily> FontFamilies { get; set; } public ObservableCollection<BlogSetting> Blogs { get; set; } public IEnumerable<SpellingLanguages> Languages { get; set; } public SpellingLanguages SelectedLanguage { get; set; } public FontSizes SelectedFontSize { get; set; } public FontFamily SelectedFontFamily { get; set; } public bool EnableFloatingToolBar { get; set; } public PluginViewModel SelectedPlugin { get; set; } public IEnumerable<PluginViewModel> Plugins { get; private set; } public IndentType IndentType { get; set; } public bool EnableMarkdownExtra { get; set; } public bool CanEditBlog { get { return currentBlog != null; } } public bool CanRemoveBlog { get { return currentBlog != null; } } public bool IsColorsInverted { get; set; } public BlogSetting CurrentBlog { get { return currentBlog; } set { currentBlog = value; NotifyOfPropertyChange(() => CanEditBlog); NotifyOfPropertyChange(() => CanRemoveBlog); } } public int SelectedActualFontSize { get { return Constants.FONT_SIZE_ENUM_ADJUSTMENT + (int)SelectedFontSize; } } public string EditorFontPreviewLabel { get { return string.Format( "Editor font ({0}, {1} pt)", SelectedFontFamily.Source, SelectedActualFontSize); } } public ObservableCollection<IndentType> IndentTypes { get { return new ObservableCollection<IndentType> { IndentType.Tabs, IndentType.Spaces }; } } public SettingsViewModel( ISettingsProvider settingsProvider, IEventAggregator eventAggregator, Func<IPlugin, PluginViewModel> pluginViewModelCreator, ISpellingService spellingService, IEnumerable<IPlugin> plugins, IBlogService blogService, ICocoaRegistryEditor CocoaRegistryEditor) { this.DisplayName = "Settings"; this.settingsProvider = settingsProvider; this.eventAggregator = eventAggregator; this.pluginViewModelCreator = pluginViewModelCreator; this.spellingService = spellingService; this.blogService = blogService; this.plugins = plugins.ToList(); this.CocoaRegistryEditor = CocoaRegistryEditor; } public void Initialize() { Extensions = CocoaRegistryEditor.GetExtensionsFromRegistry(); var settings = settingsProvider.GetSettings<CocoaSettings>(); var blogs = blogService.GetBlogs(); Blogs = new ObservableCollection<BlogSetting>(blogs); Languages = Enum.GetValues(typeof(SpellingLanguages)).OfType<SpellingLanguages>().ToArray(); FontSizes = Enum.GetValues(typeof(FontSizes)).OfType<FontSizes>().ToArray(); FontFamilies = Fonts.SystemFontFamilies.OrderBy(f => f.Source); SelectedLanguage = settings.Language; var fontFamily = settings.FontFamily; SelectedFontFamily = Fonts.SystemFontFamilies.FirstOrDefault(f => f.Source == fontFamily); SelectedFontSize = settings.FontSize; if (SelectedFontFamily == null) { SelectedFontFamily = FontHelpers.TryGetFontFamilyFromStack(Constants.DEFAULT_EDITOR_FONT_FAMILY); SelectedFontSize = Constants.DEFAULT_EDITOR_FONT_SIZE; } EnableFloatingToolBar = settings.FloatingToolBarEnabled; IsColorsInverted = settings.IsEditorColorsInverted; Plugins = plugins .Where(plugin => !plugin.IsHidden) .Select(plugin => pluginViewModelCreator(plugin)); EnableMarkdownExtra = settings.MarkdownExtraEnabled; } public bool AddBlog() { var blog = blogService.AddBlog(); if (blog != null) { Blogs.Add(blog); return true; } return false; } public void EditBlog() { if (CurrentBlog == null) return; blogService.EditBlog(CurrentBlog); } public void RemoveBlog() { if (CurrentBlog != null) { blogService.Remove(CurrentBlog); Blogs.Remove(CurrentBlog); } } public void ResetFont() { SelectedFontFamily = FontHelpers.TryGetFontFamilyFromStack(Constants.DEFAULT_EDITOR_FONT_FAMILY); SelectedFontSize = Constants.DEFAULT_EDITOR_FONT_SIZE; IsColorsInverted = false; } public void Accept() { CocoaRegistryEditor.UpdateExtensionRegistryKeys(Extensions); spellingService.SetLanguage(SelectedLanguage); UpdateCocoaSettings(); eventAggregator.Publish(new SettingsChangedEvent()); } public void HideSettings() { eventAggregator.Publish(new SettingsCloseEvent()); Accept(); } private void UpdateCocoaSettings() { var settings = settingsProvider.GetSettings<CocoaSettings>(); settings.FontSize = SelectedFontSize; settings.FontFamily = SelectedFontFamily.Source; settings.FloatingToolBarEnabled = EnableFloatingToolBar; settings.IsEditorColorsInverted = IsColorsInverted; settings.IndentType = IndentType; settings.Language = SelectedLanguage; settings.MarkdownExtraEnabled = EnableMarkdownExtra; settingsProvider.SaveSettings(settings); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Microsoft.Build.BackEnd.SdkResolution; using Microsoft.Build.Construction; using Microsoft.Build.Definition; using Microsoft.Build.Evaluation; using Microsoft.Build.Evaluation.Context; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Unittest; using Shouldly; using Xunit; using SdkResult = Microsoft.Build.BackEnd.SdkResolution.SdkResult; namespace Microsoft.Build.UnitTests.Definition { /// <summary> /// Tests some manipulations of Project and ProjectCollection that require dealing with internal data. /// </summary> public class ProjectEvaluationContext_Tests : IDisposable { public ProjectEvaluationContext_Tests() { _env = TestEnvironment.Create(); _resolver = new SdkUtilities.ConfigurableMockSdkResolver( new Dictionary<string, SdkResult> { {"foo", new SdkResult(new SdkReference("foo", "1.0.0", null), "path", "1.0.0", null)}, {"bar", new SdkResult(new SdkReference("bar", "1.0.0", null), "path", "1.0.0", null)} }); } public void Dispose() { _env.Dispose(); } private readonly SdkUtilities.ConfigurableMockSdkResolver _resolver; private readonly TestEnvironment _env; private static void SetResolverForContext(EvaluationContext context, SdkResolver resolver) { var sdkService = (SdkResolverService) context.SdkResolverService; sdkService.InitializeForTests(null, new List<SdkResolver> {resolver}); } [Theory] [InlineData(EvaluationContext.SharingPolicy.Shared)] [InlineData(EvaluationContext.SharingPolicy.Isolated)] public void SharedContextShouldGetReusedWhereasIsolatedContextShouldNot(EvaluationContext.SharingPolicy policy) { var previousContext = EvaluationContext.Create(policy); for (var i = 0; i < 10; i++) { var currentContext = previousContext.ContextForNewProject(); if (i == 0) { currentContext.ShouldBeSameAs(previousContext, "first usage context was not the same as the initial context"); } else { switch (policy) { case EvaluationContext.SharingPolicy.Shared: currentContext.ShouldBeSameAs(previousContext, $"Shared policy: usage {i} was not the same as usage {i - 1}"); break; case EvaluationContext.SharingPolicy.Isolated: currentContext.ShouldNotBeSameAs(previousContext, $"Isolated policy: usage {i} was the same as usage {i - 1}"); break; default: throw new ArgumentOutOfRangeException(nameof(policy), policy, null); } } previousContext = currentContext; } } [Fact] public void PassedInFileSystemShouldBeReusedInSharedContext() { var projectFiles = new[] { _env.CreateFile("1.proj", @"<Project> <PropertyGroup Condition=`Exists('1.file')`></PropertyGroup> </Project>".Cleanup()).Path, _env.CreateFile("2.proj", @"<Project> <PropertyGroup Condition=`Exists('2.file')`></PropertyGroup> </Project>".Cleanup()).Path }; var projectCollection = _env.CreateProjectCollection().Collection; var fileSystem = new Helpers.LoggingFileSystem(); var evaluationContext = EvaluationContext.Create(EvaluationContext.SharingPolicy.Shared, fileSystem); foreach (var projectFile in projectFiles) { Project.FromFile( projectFile, new ProjectOptions { ProjectCollection = projectCollection, EvaluationContext = evaluationContext } ); } fileSystem.ExistenceChecks.OrderBy(kvp => kvp.Key) .ShouldBe( new Dictionary<string, int> { {Path.Combine(_env.DefaultTestDirectory.Path, "1.file"), 1}, {Path.Combine(_env.DefaultTestDirectory.Path, "2.file"), 1} }.OrderBy(kvp => kvp.Key)); fileSystem.FileOrDirectoryExistsCalls.ShouldBe(2); } [Fact] public void IsolatedContextShouldNotSupportBeingPassedAFileSystem() { var fileSystem = new Helpers.LoggingFileSystem(); Should.Throw<ArgumentException>(() => EvaluationContext.Create(EvaluationContext.SharingPolicy.Isolated, fileSystem)); } [Theory] [InlineData(EvaluationContext.SharingPolicy.Shared)] [InlineData(EvaluationContext.SharingPolicy.Isolated)] public void ReevaluationShouldNotReuseInitialContext(EvaluationContext.SharingPolicy policy) { try { EvaluationContext.TestOnlyHookOnCreate = c => SetResolverForContext(c, _resolver); var collection = _env.CreateProjectCollection().Collection; var context = EvaluationContext.Create(policy); var project = Project.FromXmlReader( XmlReader.Create(new StringReader("<Project Sdk=\"foo\"></Project>")), new ProjectOptions { ProjectCollection = collection, EvaluationContext = context, LoadSettings = ProjectLoadSettings.IgnoreMissingImports }); _resolver.ResolvedCalls["foo"].ShouldBe(1); project.AddItem("a", "b"); project.ReevaluateIfNecessary(); _resolver.ResolvedCalls["foo"].ShouldBe(2); } finally { EvaluationContext.TestOnlyHookOnCreate = null; } } [Theory] [InlineData(EvaluationContext.SharingPolicy.Shared)] [InlineData(EvaluationContext.SharingPolicy.Isolated)] public void ProjectInstanceShouldRespectSharingPolicy(EvaluationContext.SharingPolicy policy) { try { var seenContexts = new HashSet<EvaluationContext>(); EvaluationContext.TestOnlyHookOnCreate = c => seenContexts.Add(c); var collection = _env.CreateProjectCollection().Collection; var context = EvaluationContext.Create(policy); const int numIterations = 10; for (int i = 0; i < numIterations; i++) { ProjectInstance.FromProjectRootElement( ProjectRootElement.Create(), new ProjectOptions { ProjectCollection = collection, EvaluationContext = context, LoadSettings = ProjectLoadSettings.IgnoreMissingImports }); } int expectedNumContexts = policy == EvaluationContext.SharingPolicy.Shared ? 1 : numIterations; seenContexts.Count.ShouldBe(expectedNumContexts); seenContexts.ShouldAllBe(c => c.Policy == policy); } finally { EvaluationContext.TestOnlyHookOnCreate = null; } } private static string[] _sdkResolutionProjects = { "<Project Sdk=\"foo\"></Project>", "<Project Sdk=\"bar\"></Project>", "<Project Sdk=\"foo\"></Project>", "<Project Sdk=\"bar\"></Project>" }; [Theory] [InlineData(EvaluationContext.SharingPolicy.Shared, 1, 1)] [InlineData(EvaluationContext.SharingPolicy.Isolated, 4, 4)] public void ContextPinsSdkResolverCache(EvaluationContext.SharingPolicy policy, int sdkLookupsForFoo, int sdkLookupsForBar) { try { EvaluationContext.TestOnlyHookOnCreate = c => SetResolverForContext(c, _resolver); var context = EvaluationContext.Create(policy); EvaluateProjects(_sdkResolutionProjects, context, null); _resolver.ResolvedCalls.Count.ShouldBe(2); _resolver.ResolvedCalls["foo"].ShouldBe(sdkLookupsForFoo); _resolver.ResolvedCalls["bar"].ShouldBe(sdkLookupsForBar); } finally { EvaluationContext.TestOnlyHookOnCreate = null; } } [Fact] public void DefaultContextIsIsolatedContext() { try { var seenContexts = new HashSet<EvaluationContext>(); EvaluationContext.TestOnlyHookOnCreate = c => seenContexts.Add(c); EvaluateProjects(_sdkResolutionProjects, null, null); seenContexts.Count.ShouldBe(8); // 4 evaluations and 4 reevaluations seenContexts.ShouldAllBe(c => c.Policy == EvaluationContext.SharingPolicy.Isolated); } finally { EvaluationContext.TestOnlyHookOnCreate = null; } } public static IEnumerable<object[]> ContextPinsGlobExpansionCacheData { get { yield return new object[] { EvaluationContext.SharingPolicy.Shared, new[] { new[] {"0.cs"}, new[] {"0.cs"}, new[] {"0.cs"}, new[] {"0.cs"} } }; yield return new object[] { EvaluationContext.SharingPolicy.Isolated, new[] { new[] {"0.cs"}, new[] {"0.cs", "1.cs"}, new[] {"0.cs", "1.cs", "2.cs"}, new[] {"0.cs", "1.cs", "2.cs", "3.cs"}, } }; } } private static string[] _projectsWithGlobs = { @"<Project> <ItemGroup> <i Include=`**/*.cs` /> </ItemGroup> </Project>", @"<Project> <ItemGroup> <i Include=`**/*.cs` /> </ItemGroup> </Project>", }; [Theory] [MemberData(nameof(ContextPinsGlobExpansionCacheData))] public void ContextCachesItemElementGlobExpansions(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions) { var projectDirectory = _env.DefaultTestDirectory.Path; var context = EvaluationContext.Create(policy); var evaluationCount = 0; File.WriteAllText(Path.Combine(projectDirectory, $"{evaluationCount}.cs"), ""); EvaluateProjects( _projectsWithGlobs, context, project => { var expectedGlobExpansion = expectedGlobExpansions[evaluationCount]; evaluationCount++; File.WriteAllText(Path.Combine(projectDirectory, $"{evaluationCount}.cs"), ""); ObjectModelHelpers.AssertItems(expectedGlobExpansion, project.GetItems("i")); } ); } public static IEnumerable<object[]> ContextDisambiguatesRelativeGlobsData { get { yield return new object[] { EvaluationContext.SharingPolicy.Shared, new[] { new[] {"0.cs"}, // first project new[] {"0.cs", "1.cs"}, // second project new[] {"0.cs"}, // first project reevaluation new[] {"0.cs", "1.cs"}, // second project reevaluation } }; yield return new object[] { EvaluationContext.SharingPolicy.Isolated, new[] { new[] {"0.cs"}, new[] {"0.cs", "1.cs"}, new[] {"0.cs", "1.cs", "2.cs"}, new[] {"0.cs", "1.cs", "2.cs", "3.cs"}, } }; } } [Theory] [MemberData(nameof(ContextDisambiguatesRelativeGlobsData))] public void ContextDisambiguatesSameRelativeGlobsPointingInsideDifferentProjectCones(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions) { var projectDirectory1 = _env.DefaultTestDirectory.CreateDirectory("1").Path; var projectDirectory2 = _env.DefaultTestDirectory.CreateDirectory("2").Path; var context = EvaluationContext.Create(policy); var evaluationCount = 0; File.WriteAllText(Path.Combine(projectDirectory1, $"1.{evaluationCount}.cs"), ""); File.WriteAllText(Path.Combine(projectDirectory2, $"2.{evaluationCount}.cs"), ""); EvaluateProjects( new [] { new ProjectSpecification( Path.Combine(projectDirectory1, "1"), $@"<Project> <ItemGroup> <i Include=`{Path.Combine("**", "*.cs")}` /> </ItemGroup> </Project>"), new ProjectSpecification( Path.Combine(projectDirectory2, "2"), $@"<Project> <ItemGroup> <i Include=`{Path.Combine("**", "*.cs")}` /> </ItemGroup> </Project>"), }, context, project => { var projectName = Path.GetFileNameWithoutExtension(project.FullPath); var expectedGlobExpansion = expectedGlobExpansions[evaluationCount] .Select(i => $"{projectName}.{i}") .ToArray(); ObjectModelHelpers.AssertItems(expectedGlobExpansion, project.GetItems("i")); evaluationCount++; File.WriteAllText(Path.Combine(projectDirectory1, $"1.{evaluationCount}.cs"), ""); File.WriteAllText(Path.Combine(projectDirectory2, $"2.{evaluationCount}.cs"), ""); } ); } [Theory] [MemberData(nameof(ContextDisambiguatesRelativeGlobsData))] public void ContextDisambiguatesSameRelativeGlobsPointingOutsideDifferentProjectCones(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions) { var project1Root = _env.DefaultTestDirectory.CreateDirectory("Project1"); var project1Directory = project1Root.CreateDirectory("1").Path; var project1GlobDirectory = project1Root.CreateDirectory("Glob").CreateDirectory("1").Path; var project2Root = _env.DefaultTestDirectory.CreateDirectory("Project2"); var project2Directory = project2Root.CreateDirectory("2").Path; var project2GlobDirectory = project2Root.CreateDirectory("Glob").CreateDirectory("2").Path; var context = EvaluationContext.Create(policy); var evaluationCount = 0; File.WriteAllText(Path.Combine(project1GlobDirectory, $"1.{evaluationCount}.cs"), ""); File.WriteAllText(Path.Combine(project2GlobDirectory, $"2.{evaluationCount}.cs"), ""); EvaluateProjects( new [] { new ProjectSpecification( Path.Combine(project1Directory, "1"), $@"<Project> <ItemGroup> <i Include=`{Path.Combine("..", "Glob", "**", "*.cs")}`/> </ItemGroup> </Project>"), new ProjectSpecification( Path.Combine(project2Directory, "2"), $@"<Project> <ItemGroup> <i Include=`{Path.Combine("..", "Glob", "**", "*.cs")}`/> </ItemGroup> </Project>") }, context, project => { var projectName = Path.GetFileNameWithoutExtension(project.FullPath); // globs have the fixed directory part prepended, so add it to the expected results var expectedGlobExpansion = expectedGlobExpansions[evaluationCount] .Select(i => Path.Combine("..", "Glob", projectName, $"{projectName}.{i}")) .ToArray(); var actualGlobExpansion = project.GetItems("i"); ObjectModelHelpers.AssertItems(expectedGlobExpansion, actualGlobExpansion); evaluationCount++; File.WriteAllText(Path.Combine(project1GlobDirectory, $"1.{evaluationCount}.cs"), ""); File.WriteAllText(Path.Combine(project2GlobDirectory, $"2.{evaluationCount}.cs"), ""); } ); } [Theory] [MemberData(nameof(ContextDisambiguatesRelativeGlobsData))] public void ContextDisambiguatesAFullyQualifiedGlobPointingInAnotherRelativeGlobsCone(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions) { if (policy == EvaluationContext.SharingPolicy.Shared) { // This test case has a dependency on our glob expansion caching policy. If the evaluation context is reused // between evaluations and files are added to the filesystem between evaluations, the cache may be returning // stale results. Run only the Isolated variant. return; } var project1Directory = _env.DefaultTestDirectory.CreateDirectory("Project1"); var project1GlobDirectory = project1Directory.CreateDirectory("Glob").CreateDirectory("1").Path; var project2Directory = _env.DefaultTestDirectory.CreateDirectory("Project2"); var context = EvaluationContext.Create(policy); var evaluationCount = 0; File.WriteAllText(Path.Combine(project1GlobDirectory, $"{evaluationCount}.cs"), ""); EvaluateProjects( new [] { // first project uses a relative path new ProjectSpecification( Path.Combine(project1Directory.Path, "1"), $@"<Project> <ItemGroup> <i Include=`{Path.Combine("Glob", "**", "*.cs")}` /> </ItemGroup> </Project>"), // second project reaches out into first project's cone via a fully qualified path new ProjectSpecification( Path.Combine(project2Directory.Path, "2"), $@"<Project> <ItemGroup> <i Include=`{Path.Combine(project1Directory.Path, "Glob", "**", "*.cs")}` /> </ItemGroup> </Project>") }, context, project => { var projectName = Path.GetFileNameWithoutExtension(project.FullPath); // globs have the fixed directory part prepended, so add it to the expected results var expectedGlobExpansion = expectedGlobExpansions[evaluationCount] .Select(i => Path.Combine("Glob", "1", i)) .ToArray(); // project 2 has fully qualified directory parts, so make the results for 2 fully qualified if (projectName.Equals("2")) { expectedGlobExpansion = expectedGlobExpansion .Select(i => Path.Combine(project1Directory.Path, i)) .ToArray(); } var actualGlobExpansion = project.GetItems("i"); ObjectModelHelpers.AssertItems(expectedGlobExpansion, actualGlobExpansion); evaluationCount++; File.WriteAllText(Path.Combine(project1GlobDirectory, $"{evaluationCount}.cs"), ""); } ); } [Theory] [MemberData(nameof(ContextDisambiguatesRelativeGlobsData))] public void ContextDisambiguatesDistinctRelativeGlobsPointingOutsideOfSameProjectCone(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions) { var globDirectory = _env.DefaultTestDirectory.CreateDirectory("glob"); var projectRoot = _env.DefaultTestDirectory.CreateDirectory("proj"); var project1Directory = projectRoot.CreateDirectory("Project1"); var project2SubDir = projectRoot.CreateDirectory("subdirectory"); var project2Directory = project2SubDir.CreateDirectory("Project2"); var context = EvaluationContext.Create(policy); var evaluationCount = 0; File.WriteAllText(Path.Combine(globDirectory.Path, $"{evaluationCount}.cs"), ""); EvaluateProjects( new [] { new ProjectSpecification( Path.Combine(project1Directory.Path, "1"), @"<Project> <ItemGroup> <i Include=`../../glob/*.cs` /> </ItemGroup> </Project>"), new ProjectSpecification( Path.Combine(project2Directory.Path, "2"), @"<Project> <ItemGroup> <i Include=`../../../glob/*.cs` /> </ItemGroup> </Project>") }, context, project => { var projectName = Path.GetFileNameWithoutExtension(project.FullPath); var globFixedDirectoryPart = projectName.EndsWith("1") ? Path.Combine("..", "..", "glob") : Path.Combine("..", "..", "..", "glob"); // globs have the fixed directory part prepended, so add it to the expected results var expectedGlobExpansion = expectedGlobExpansions[evaluationCount] .Select(i => Path.Combine(globFixedDirectoryPart, i)) .ToArray(); var actualGlobExpansion = project.GetItems("i"); ObjectModelHelpers.AssertItems(expectedGlobExpansion, actualGlobExpansion); evaluationCount++; File.WriteAllText(Path.Combine(globDirectory.Path, $"{evaluationCount}.cs"), ""); } ); } [Theory] [MemberData(nameof(ContextPinsGlobExpansionCacheData))] // projects should cache glob expansions when the __fully qualified__ glob is shared between projects and points outside of project cone public void ContextCachesCommonOutOfProjectConeFullyQualifiedGlob(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions) { ContextCachesCommonOutOfProjectCone(itemSpecPathIsRelative: false, policy: policy, expectedGlobExpansions: expectedGlobExpansions); } [Theory (Skip="https://github.com/Microsoft/msbuild/issues/3889")] [MemberData(nameof(ContextPinsGlobExpansionCacheData))] // projects should cache glob expansions when the __relative__ glob is shared between projects and points outside of project cone public void ContextCachesCommonOutOfProjectConeRelativeGlob(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions) { ContextCachesCommonOutOfProjectCone(itemSpecPathIsRelative: true, policy: policy, expectedGlobExpansions: expectedGlobExpansions); } private void ContextCachesCommonOutOfProjectCone(bool itemSpecPathIsRelative, EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions) { var testDirectory = _env.DefaultTestDirectory; var globDirectory = testDirectory.CreateDirectory("GlobDirectory"); var itemSpecDirectoryPart = itemSpecPathIsRelative ? Path.Combine("..", "GlobDirectory") : globDirectory.Path; Directory.CreateDirectory(globDirectory.Path); // Globs with a directory part will produce items prepended with that directory part foreach (var globExpansion in expectedGlobExpansions) { for (var i = 0; i < globExpansion.Length; i++) { globExpansion[i] = Path.Combine(itemSpecDirectoryPart, globExpansion[i]); } } var projectSpecs = new[] { $@"<Project> <ItemGroup> <i Include=`{Path.Combine("{0}", "**", "*.cs")}`/> </ItemGroup> </Project>", $@"<Project> <ItemGroup> <i Include=`{Path.Combine("{0}", "**", "*.cs")}`/> </ItemGroup> </Project>" } .Select(p => string.Format(p, itemSpecDirectoryPart)) .Select((p, i) => new ProjectSpecification(Path.Combine(testDirectory.Path, $"ProjectDirectory{i}", $"Project{i}.proj"), p)); var context = EvaluationContext.Create(policy); var evaluationCount = 0; File.WriteAllText(Path.Combine(globDirectory.Path, $"{evaluationCount}.cs"), ""); EvaluateProjects( projectSpecs, context, project => { var expectedGlobExpansion = expectedGlobExpansions[evaluationCount]; evaluationCount++; File.WriteAllText(Path.Combine(globDirectory.Path, $"{evaluationCount}.cs"), ""); ObjectModelHelpers.AssertItems(expectedGlobExpansion, project.GetItems("i")); } ); } private static string[] _projectsWithGlobImports = { @"<Project> <Import Project=`*.props` /> </Project>", @"<Project> <Import Project=`*.props` /> </Project>", }; [Theory] [MemberData(nameof(ContextPinsGlobExpansionCacheData))] public void ContextCachesImportGlobExpansions(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions) { var projectDirectory = _env.DefaultTestDirectory.Path; var context = EvaluationContext.Create(policy); var evaluationCount = 0; File.WriteAllText(Path.Combine(projectDirectory, $"{evaluationCount}.props"), $"<Project><ItemGroup><i Include=`{evaluationCount}.cs`/></ItemGroup></Project>".Cleanup()); EvaluateProjects( _projectsWithGlobImports, context, project => { var expectedGlobExpansion = expectedGlobExpansions[evaluationCount]; evaluationCount++; File.WriteAllText(Path.Combine(projectDirectory, $"{evaluationCount}.props"), $"<Project><ItemGroup><i Include=`{evaluationCount}.cs`/></ItemGroup></Project>".Cleanup()); ObjectModelHelpers.AssertItems(expectedGlobExpansion, project.GetItems("i")); } ); } private static string[] _projectsWithConditions = { @"<Project> <PropertyGroup Condition=`Exists('0.cs')`> <p>val</p> </PropertyGroup> </Project>", @"<Project> <PropertyGroup Condition=`Exists('0.cs')`> <p>val</p> </PropertyGroup> </Project>", }; [Theory] [InlineData(EvaluationContext.SharingPolicy.Isolated)] [InlineData(EvaluationContext.SharingPolicy.Shared)] public void ContextCachesExistenceChecksInConditions(EvaluationContext.SharingPolicy policy) { var projectDirectory = _env.DefaultTestDirectory.Path; var context = EvaluationContext.Create(policy); var theFile = Path.Combine(projectDirectory, "0.cs"); File.WriteAllText(theFile, ""); var evaluationCount = 0; EvaluateProjects( _projectsWithConditions, context, project => { evaluationCount++; if (File.Exists(theFile)) { File.Delete(theFile); } if (evaluationCount == 1) { project.GetPropertyValue("p").ShouldBe("val"); } else switch (policy) { case EvaluationContext.SharingPolicy.Shared: project.GetPropertyValue("p").ShouldBe("val"); break; case EvaluationContext.SharingPolicy.Isolated: project.GetPropertyValue("p").ShouldBeEmpty(); break; default: throw new ArgumentOutOfRangeException(nameof(policy), policy, null); } } ); } [Theory] [InlineData(EvaluationContext.SharingPolicy.Isolated)] [InlineData(EvaluationContext.SharingPolicy.Shared)] public void ContextCachesExistenceChecksInGetDirectoryNameOfFileAbove(EvaluationContext.SharingPolicy policy) { var context = EvaluationContext.Create(policy); var subdirectory = _env.DefaultTestDirectory.CreateDirectory("subDirectory"); var subdirectoryFile = subdirectory.CreateFile("a"); _env.DefaultTestDirectory.CreateFile("a"); int evaluationCount = 0; EvaluateProjects( new [] { $@"<Project> <PropertyGroup> <SearchedPath>$([MSBuild]::GetDirectoryNameOfFileAbove('{subdirectory.Path}', 'a'))</SearchedPath> </PropertyGroup> </Project>" }, context, project => { evaluationCount++; var searchedPath = project.GetProperty("SearchedPath"); switch (policy) { case EvaluationContext.SharingPolicy.Shared: searchedPath.EvaluatedValue.ShouldBe(subdirectory.Path); break; case EvaluationContext.SharingPolicy.Isolated: searchedPath.EvaluatedValue.ShouldBe( evaluationCount == 1 ? subdirectory.Path : _env.DefaultTestDirectory.Path); break; default: throw new ArgumentOutOfRangeException(nameof(policy), policy, null); } if (evaluationCount == 1) { // this will cause the upper file to get picked up in the Isolated policy subdirectoryFile.Delete(); } }); evaluationCount.ShouldBe(2); } [Theory] [InlineData(EvaluationContext.SharingPolicy.Isolated)] [InlineData(EvaluationContext.SharingPolicy.Shared)] public void ContextCachesExistenceChecksInGetPathOfFileAbove(EvaluationContext.SharingPolicy policy) { var context = EvaluationContext.Create(policy); var subdirectory = _env.DefaultTestDirectory.CreateDirectory("subDirectory"); var subdirectoryFile = subdirectory.CreateFile("a"); var rootFile = _env.DefaultTestDirectory.CreateFile("a"); int evaluationCount = 0; EvaluateProjects( new [] { $@"<Project> <PropertyGroup> <SearchedPath>$([MSBuild]::GetPathOfFileAbove('a', '{subdirectory.Path}'))</SearchedPath> </PropertyGroup> </Project>" }, context, project => { evaluationCount++; var searchedPath = project.GetProperty("SearchedPath"); switch (policy) { case EvaluationContext.SharingPolicy.Shared: searchedPath.EvaluatedValue.ShouldBe(subdirectoryFile.Path); break; case EvaluationContext.SharingPolicy.Isolated: searchedPath.EvaluatedValue.ShouldBe( evaluationCount == 1 ? subdirectoryFile.Path : rootFile.Path); break; default: throw new ArgumentOutOfRangeException(nameof(policy), policy, null); } if (evaluationCount == 1) { // this will cause the upper file to get picked up in the Isolated policy subdirectoryFile.Delete(); } }); evaluationCount.ShouldBe(2); } private void EvaluateProjects(IEnumerable<string> projectContents, EvaluationContext context, Action<Project> afterEvaluationAction) { EvaluateProjects( projectContents.Select((p, i) => new ProjectSpecification(Path.Combine(_env.DefaultTestDirectory.Path, $"Project{i}.proj"), p)), context, afterEvaluationAction); } private struct ProjectSpecification { public string ProjectFilePath { get; } public string ProjectContents { get; } public ProjectSpecification(string projectFilePath, string projectContents) { ProjectFilePath = projectFilePath; ProjectContents = projectContents; } public void Deconstruct(out string projectPath, out string projectContents) { projectPath = this.ProjectFilePath; projectContents = this.ProjectContents; } } /// <summary> /// Should be at least two test projects to test cache visibility between projects /// </summary> private void EvaluateProjects(IEnumerable<ProjectSpecification> projectSpecs, EvaluationContext context, Action<Project> afterEvaluationAction) { var collection = _env.CreateProjectCollection().Collection; var projects = new List<Project>(); foreach (var (projectFilePath, projectContents) in projectSpecs) { Directory.CreateDirectory(Path.GetDirectoryName(projectFilePath)); File.WriteAllText(projectFilePath, projectContents.Cleanup()); var project = Project.FromFile( projectFilePath, new ProjectOptions { ProjectCollection = collection, EvaluationContext = context, LoadSettings = ProjectLoadSettings.IgnoreMissingImports }); afterEvaluationAction?.Invoke(project); projects.Add(project); } foreach (var project in projects) { project.AddItem("a", "b"); project.ReevaluateIfNecessary(context); afterEvaluationAction?.Invoke(project); } } } }
using System; using Gtk; using System.IO; using System.Timers; using Moscrif.IDE.Controls; using Moscrif.IDE.Tool; using Moscrif.IDE.Task; using Moscrif.IDE.Execution; using GLib; using Moscrif.IDE.Option; using Moscrif.IDE.Iface; using Moscrif.IDE.Iface.Entities; using MessageDialogs = Moscrif.IDE.Controls.MessageDialog; using Mono.Unix; using System.Threading; using System.Text; namespace Moscrif.IDE { class MainClass { public static void Main(string[] args) { //foreach(string str in args) // Logger.Log("arg ->{0}",str); Application.Init(); Logger.Log(Languages.Translate("start_app")); ExceptionManager.UnhandledException += delegate(UnhandledExceptionArgs argsum) { StringBuilder sb = new StringBuilder(); Exception ex = (Exception)argsum.ExceptionObject; sb.AppendLine(ex.Message); sb.AppendLine(ex.StackTrace); Logger.Error(ex.Message); Logger.Error(ex.StackTrace); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); if (ex.InnerException != null) { Logger.Error(ex.InnerException.Message); Logger.Error(ex.InnerException.StackTrace); Logger.Error(ex.InnerException.Source); Console.WriteLine(ex.InnerException.Message); Console.WriteLine(ex.InnerException.StackTrace); Console.WriteLine(ex.InnerException.Source); sb.AppendLine(ex.InnerException.Message); sb.AppendLine(ex.InnerException.StackTrace); sb.AppendLine(ex.InnerException.Source); } ErrorDialog ed= new ErrorDialog(); ed.ErrorMessage = sb.ToString(); ed.Run(); ed.Destroy(); argsum.ExitApplication = true; }; Gdk.Global.InitCheck(ref args); if (Platform.IsWindows){ string themePath = Paths.DefaultTheme; if (System.IO.File.Exists (themePath)){ Gtk.Rc.AddDefaultFile(themePath); Gtk.Rc.Parse (themePath); } } mainWindow = new MainWindow(args); MainWindow.Show(); if((MainClass.Settings.Account == null) || (String.IsNullOrEmpty(MainClass.Settings.Account.Token))){ LoginRegisterDialog ld = new LoginRegisterDialog(null); ld.Run(); ld.Destroy(); } else { LoggingInfo log = new LoggingInfo(); log.LoggWebThread(LoggingInfo.ActionId.IDEStart); } if (!String.IsNullOrEmpty(Paths.TempDir)) { Application.Run(); } } static ProcessService processService = null; static internal ProcessService ProcessService { get { if (processService != null) return processService; processService = new ProcessService(); return processService; } } static TaskServices taskServices = null; static internal TaskServices TaskServices { get { if (taskServices != null) return taskServices; taskServices = new TaskServices(); return taskServices; } } //static MainWindow mainWindow = null; static MainWindow mainWindow = null; static internal MainWindow MainWindow { get { /*if (mainWindow != null) return mainWindow; mainWindow = new MainWindow();*/ return mainWindow; } } static Tools tools = null; static internal Tools Tools { get { if (tools != null) return tools; tools = new Tools(); return tools; } } static Paths paths = null; static internal Paths Paths { get { if (paths != null) return paths; paths = new Paths(); return paths; } } static Platform platform = null; static internal Platform Platform { get { if (platform != null) return platform; platform = new Platform(); return platform; } } static Languages languages = null; static internal Languages Languages { get { if (languages != null) return languages; string file = System.IO.Path.Combine(Paths.LanguageDir, "en.lng"); languages = new Languages(file); return languages; } } static Moscrif.IDE.Option.Settings settings = null; static internal Moscrif.IDE.Option.Settings Settings { get { if (settings != null) return settings; string file = System.IO.Path.Combine(Paths.SettingDir, "moscrif.mss"); if (File.Exists(file)) { try{ settings = Moscrif.IDE.Option.Settings.OpenSettings(file); }catch{//(Exception ex){ MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "Error", Languages.Translate("setting_file_corrupted"), Gtk.MessageType.Error,null); ms.ShowDialog(); settings = new Moscrif.IDE.Option.Settings(file); } settings.FilePath = file; } if (settings == null) settings = new Moscrif.IDE.Option.Settings(file); return settings; } } static Workspace.Workspace workspace = null; static internal Workspace.Workspace Workspace { get { if (workspace != null) return workspace; Logger.Log("Workspace.Workspace ->"+Settings.CurrentWorkspace); workspace = new Workspace.Workspace(); if (String.IsNullOrEmpty(Settings.CurrentWorkspace)) return workspace; string file = Settings.CurrentWorkspace; if (File.Exists(file)) { workspace = Moscrif.IDE.Workspace.Workspace.OpenWorkspace(file); if (workspace == null){ workspace = new Workspace.Workspace(); return workspace; } workspace.FilePath = file; } return workspace; } set { workspace = value; if (workspace != null) Settings.CurrentWorkspace = workspace.FilePath; else Settings.CurrentWorkspace = String.Empty; } } //static KeyBindings keyBinding = null; static internal KeyBindings KeyBinding{ get{ KeyBindings keyBinding = null; if(keyBinding == null){ string file = System.IO.Path.Combine(MainClass.Paths.SettingDir, "keybinding"); try{ if(!File.Exists(file)){ KeyBindings.CreateKeyBindingsWin(file); } keyBinding = KeyBindings.OpenKeyBindings(file); } catch(Exception ex){ Logger.Error(ex.Message); return new KeyBindings(file); } } return keyBinding; } } static CompletedCache completedCache = null; static internal CompletedCache CompletedCache{ get{ if(completedCache == null){ string file = System.IO.Path.Combine(MainClass.Paths.ConfingDir, ".completedcache"); try{ completedCache = CompletedCache.OpenCompletedCache(file); completedCache.GetCompletedData(); } catch(Exception ex){ Logger.Error(ex.Message); return new CompletedCache(); } } return completedCache; } } static Account account = null; static internal Account User{ get{ return account; } set{ account = value; if ((account == null) || (account.Remember)){ MainClass.Settings.Account = account; } } } static LicensesSystem licencesSystem = null; static internal LicensesSystem LicencesSystem{ get{ if(licencesSystem==null){ licencesSystem = new LicensesSystem(); } return licencesSystem; } set{ licencesSystem = value; } } static BannersSystem bannersSystem = null; static internal BannersSystem BannersSystem{ get{ if(bannersSystem==null){ bannersSystem = new BannersSystem(); } return bannersSystem; } set{ bannersSystem = value; } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; using System.IO; using System.Globalization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { internal enum ReadType { Read, ReadAsInt32, ReadAsBytes, ReadAsString, ReadAsDecimal, ReadAsDateTime, #if !NET20 ReadAsDateTimeOffset #endif } /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to JSON text data. /// </summary> public class JsonTextReader : JsonReader, IJsonLineInfo { private const char UnicodeReplacementChar = '\uFFFD'; private const int MaximumJavascriptIntegerCharacterLength = 380; private readonly TextReader _reader; private char[] _chars; private int _charsUsed; private int _charPos; private int _lineStartPos; private int _lineNumber; private bool _isEndOfFile; private StringBuffer _buffer; private StringReference _stringReference; internal PropertyNameTable NameTable; /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> /// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param> public JsonTextReader(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); _reader = reader; _lineNumber = 1; _chars = new char[1025]; } #if DEBUG internal void SetCharBuffer(char[] chars) { _chars = chars; } #endif private StringBuffer GetBuffer() { if (_buffer == null) { _buffer = new StringBuffer(1025); } else { _buffer.Position = 0; } return _buffer; } private void OnNewLine(int pos) { _lineNumber++; _lineStartPos = pos - 1; } private void ParseString(char quote) { _charPos++; ShiftBufferIfNeeded(); ReadStringIntoBuffer(quote); SetPostValueState(true); if (_readType == ReadType.ReadAsBytes) { Guid g; byte[] data; if (_stringReference.Length == 0) { data = new byte[0]; } else if (_stringReference.Length == 36 && ConvertUtils.TryConvertGuid(_stringReference.ToString(), out g)) { data = g.ToByteArray(); } else { data = Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length); } SetToken(JsonToken.Bytes, data, false); } else if (_readType == ReadType.ReadAsString) { string text = _stringReference.ToString(); SetToken(JsonToken.String, text, false); _quoteChar = quote; } else { string text = _stringReference.ToString(); if (_dateParseHandling != DateParseHandling.None) { DateParseHandling dateParseHandling; if (_readType == ReadType.ReadAsDateTime) dateParseHandling = DateParseHandling.DateTime; #if !NET20 else if (_readType == ReadType.ReadAsDateTimeOffset) dateParseHandling = DateParseHandling.DateTimeOffset; #endif else dateParseHandling = _dateParseHandling; object dt; if (DateTimeUtils.TryParseDateTime(text, dateParseHandling, DateTimeZoneHandling, DateFormatString, Culture, out dt)) { SetToken(JsonToken.Date, dt, false); return; } } SetToken(JsonToken.String, text, false); _quoteChar = quote; } } private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count) { const int charByteCount = 2; Buffer.BlockCopy(src, srcOffset * charByteCount, dst, dstOffset * charByteCount, count * charByteCount); } private void ShiftBufferIfNeeded() { // once in the last 10% of the buffer shift the remaining content to the start to avoid // unnessesarly increasing the buffer size when reading numbers/strings int length = _chars.Length; if (length - _charPos <= length * 0.1) { int count = _charsUsed - _charPos; if (count > 0) BlockCopyChars(_chars, _charPos, _chars, 0, count); _lineStartPos -= _charPos; _charPos = 0; _charsUsed = count; _chars[_charsUsed] = '\0'; } } private int ReadData(bool append) { return ReadData(append, 0); } private int ReadData(bool append, int charsRequired) { if (_isEndOfFile) return 0; // char buffer is full if (_charsUsed + charsRequired >= _chars.Length - 1) { if (append) { // copy to new array either double the size of the current or big enough to fit required content int newArrayLength = Math.Max(_chars.Length * 2, _charsUsed + charsRequired + 1); // increase the size of the buffer char[] dst = new char[newArrayLength]; BlockCopyChars(_chars, 0, dst, 0, _chars.Length); _chars = dst; } else { int remainingCharCount = _charsUsed - _charPos; if (remainingCharCount + charsRequired + 1 >= _chars.Length) { // the remaining count plus the required is bigger than the current buffer size char[] dst = new char[remainingCharCount + charsRequired + 1]; if (remainingCharCount > 0) BlockCopyChars(_chars, _charPos, dst, 0, remainingCharCount); _chars = dst; } else { // copy any remaining data to the beginning of the buffer if needed and reset positions if (remainingCharCount > 0) BlockCopyChars(_chars, _charPos, _chars, 0, remainingCharCount); } _lineStartPos -= _charPos; _charPos = 0; _charsUsed = remainingCharCount; } } int attemptCharReadCount = _chars.Length - _charsUsed - 1; int charsRead = _reader.Read(_chars, _charsUsed, attemptCharReadCount); _charsUsed += charsRead; if (charsRead == 0) _isEndOfFile = true; _chars[_charsUsed] = '\0'; return charsRead; } private bool EnsureChars(int relativePosition, bool append) { if (_charPos + relativePosition >= _charsUsed) return ReadChars(relativePosition, append); return true; } private bool ReadChars(int relativePosition, bool append) { if (_isEndOfFile) return false; int charsRequired = _charPos + relativePosition - _charsUsed + 1; int totalCharsRead = 0; // it is possible that the TextReader doesn't return all data at once // repeat read until the required text is returned or the reader is out of content do { int charsRead = ReadData(append, charsRequired - totalCharsRead); // no more content if (charsRead == 0) break; totalCharsRead += charsRead; } while (totalCharsRead < charsRequired); if (totalCharsRead < charsRequired) return false; return true; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns> /// true if the next token was read successfully; false if there are no more tokens to read. /// </returns> [DebuggerStepThrough] public override bool Read() { _readType = ReadType.Read; if (!ReadInternal()) { SetToken(JsonToken.None); return false; } return true; } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Byte"/>[]. /// </summary> /// <returns> /// A <see cref="Byte"/>[] or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array. /// </returns> public override byte[] ReadAsBytes() { return ReadAsBytesInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public override decimal? ReadAsDecimal() { return ReadAsDecimalInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>. /// </summary> /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns> public override int? ReadAsInt32() { return ReadAsInt32Internal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public override string ReadAsString() { return ReadAsStringInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public override DateTime? ReadAsDateTime() { return ReadAsDateTimeInternal(); } #if !NET20 /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="DateTimeOffset"/>. This method will return <c>null</c> at the end of an array.</returns> public override DateTimeOffset? ReadAsDateTimeOffset() { return ReadAsDateTimeOffsetInternal(); } #endif internal override bool ReadInternal() { while (true) { switch (_currentState) { case State.Start: case State.Property: case State.Array: case State.ArrayStart: case State.Constructor: case State.ConstructorStart: return ParseValue(); case State.Object: case State.ObjectStart: return ParseObject(); case State.PostValue: // returns true if it hits // end of object or array if (ParsePostValue()) return true; break; case State.Finished: if (EnsureChars(0, false)) { EatWhitespace(false); if (_isEndOfFile) { return false; } if (_chars[_charPos] == '/') { ParseComment(); return true; } throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } return false; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); } } } private void ReadStringIntoBuffer(char quote) { int charPos = _charPos; int initialPosition = _charPos; int lastWritePosition = _charPos; StringBuffer buffer = null; while (true) { switch (_chars[charPos++]) { case '\0': if (_charsUsed == charPos - 1) { charPos--; if (ReadData(true) == 0) { _charPos = charPos; throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } } break; case '\\': _charPos = charPos; if (!EnsureChars(0, true)) { _charPos = charPos; throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } // start of escape sequence int escapeStartPos = charPos - 1; char currentChar = _chars[charPos]; char writeChar; switch (currentChar) { case 'b': charPos++; writeChar = '\b'; break; case 't': charPos++; writeChar = '\t'; break; case 'n': charPos++; writeChar = '\n'; break; case 'f': charPos++; writeChar = '\f'; break; case 'r': charPos++; writeChar = '\r'; break; case '\\': charPos++; writeChar = '\\'; break; case '"': case '\'': case '/': writeChar = currentChar; charPos++; break; case 'u': charPos++; _charPos = charPos; writeChar = ParseUnicode(); if (StringUtils.IsLowSurrogate(writeChar)) { // low surrogate with no preceding high surrogate; this char is replaced writeChar = UnicodeReplacementChar; } else if (StringUtils.IsHighSurrogate(writeChar)) { bool anotherHighSurrogate; // loop for handling situations where there are multiple consecutive high surrogates do { anotherHighSurrogate = false; // potential start of a surrogate pair if (EnsureChars(2, true) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u') { char highSurrogate = writeChar; _charPos += 2; writeChar = ParseUnicode(); if (StringUtils.IsLowSurrogate(writeChar)) { // a valid surrogate pair! } else if (StringUtils.IsHighSurrogate(writeChar)) { // another high surrogate; replace current and start check over highSurrogate = UnicodeReplacementChar; anotherHighSurrogate = true; } else { // high surrogate not followed by low surrogate; original char is replaced highSurrogate = UnicodeReplacementChar; } if (buffer == null) buffer = GetBuffer(); WriteCharToBuffer(buffer, highSurrogate, lastWritePosition, escapeStartPos); lastWritePosition = _charPos; } else { // there are not enough remaining chars for the low surrogate or is not follow by unicode sequence // replace high surrogate and continue on as usual writeChar = UnicodeReplacementChar; } } while (anotherHighSurrogate); } charPos = _charPos; break; default: charPos++; _charPos = charPos; throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar)); } if (buffer == null) buffer = GetBuffer(); WriteCharToBuffer(buffer, writeChar, lastWritePosition, escapeStartPos); lastWritePosition = charPos; break; case StringUtils.CarriageReturn: _charPos = charPos - 1; ProcessCarriageReturn(true); charPos = _charPos; break; case StringUtils.LineFeed: _charPos = charPos - 1; ProcessLineFeed(); charPos = _charPos; break; case '"': case '\'': if (_chars[charPos - 1] == quote) { charPos--; if (initialPosition == lastWritePosition) { _stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition); } else { if (buffer == null) buffer = GetBuffer(); if (charPos > lastWritePosition) buffer.Append(_chars, lastWritePosition, charPos - lastWritePosition); _stringReference = new StringReference(buffer.GetInternalBuffer(), 0, buffer.Position); } charPos++; _charPos = charPos; return; } break; } } } private void WriteCharToBuffer(StringBuffer buffer, char writeChar, int lastWritePosition, int writeToPosition) { if (writeToPosition > lastWritePosition) { buffer.Append(_chars, lastWritePosition, writeToPosition - lastWritePosition); } buffer.Append(writeChar); } private char ParseUnicode() { char writeChar; if (EnsureChars(4, true)) { string hexValues = new string(_chars, _charPos, 4); char hexChar = Convert.ToChar(int.Parse(hexValues, NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo)); writeChar = hexChar; _charPos += 4; } else { throw JsonReaderException.Create(this, "Unexpected end while parsing unicode character."); } return writeChar; } private void ReadNumberIntoBuffer() { int charPos = _charPos; while (true) { switch (_chars[charPos]) { case '\0': _charPos = charPos; if (_charsUsed == charPos) { if (ReadData(true) == 0) return; } else { return; } break; case '-': case '+': case 'a': case 'A': case 'b': case 'B': case 'c': case 'C': case 'd': case 'D': case 'e': case 'E': case 'f': case 'F': case 'x': case 'X': case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': charPos++; break; default: _charPos = charPos; char currentChar = _chars[_charPos]; if (char.IsWhiteSpace(currentChar) || currentChar == ',' || currentChar == '}' || currentChar == ']' || currentChar == ')' || currentChar == '/') { return; } throw JsonReaderException.Create(this, "Unexpected character encountered while parsing number: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } } private void ClearRecentString() { if (_buffer != null) _buffer.Position = 0; _stringReference = new StringReference(); } private bool ParsePostValue() { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) { _currentState = State.Finished; return false; } } else { _charPos++; } break; case '}': _charPos++; SetToken(JsonToken.EndObject); return true; case ']': _charPos++; SetToken(JsonToken.EndArray); return true; case ')': _charPos++; SetToken(JsonToken.EndConstructor); return true; case '/': ParseComment(); return true; case ',': _charPos++; // finished parsing SetStateBasedOnCurrent(); return false; case ' ': case StringUtils.Tab: // eat _charPos++; break; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; } else { throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } break; } } } private bool ParseObject() { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) return false; } else { _charPos++; } break; case '}': SetToken(JsonToken.EndObject); _charPos++; return true; case '/': ParseComment(); return true; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; } else { return ParseProperty(); } break; } } } private bool ParseProperty() { char firstChar = _chars[_charPos]; char quoteChar; if (firstChar == '"' || firstChar == '\'') { _charPos++; quoteChar = firstChar; ShiftBufferIfNeeded(); ReadStringIntoBuffer(quoteChar); } else if (ValidIdentifierChar(firstChar)) { quoteChar = '\0'; ShiftBufferIfNeeded(); ParseUnquotedProperty(); } else { throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } string propertyName; if (NameTable != null) { propertyName = NameTable.Get(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length); // no match in name table if (propertyName == null) propertyName = _stringReference.ToString(); } else { propertyName = _stringReference.ToString(); } EatWhitespace(false); if (_chars[_charPos] != ':') throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); _charPos++; SetToken(JsonToken.PropertyName, propertyName); _quoteChar = quoteChar; ClearRecentString(); return true; } private bool ValidIdentifierChar(char value) { return (char.IsLetterOrDigit(value) || value == '_' || value == '$'); } private void ParseUnquotedProperty() { int initialPosition = _charPos; // parse unquoted property name until whitespace or colon while (true) { switch (_chars[_charPos]) { case '\0': if (_charsUsed == _charPos) { if (ReadData(true) == 0) throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name."); break; } _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); return; default: char currentChar = _chars[_charPos]; if (ValidIdentifierChar(currentChar)) { _charPos++; break; } else if (char.IsWhiteSpace(currentChar) || currentChar == ':') { _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); return; } throw JsonReaderException.Create(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } } private bool ParseValue() { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) return false; } else { _charPos++; } break; case '"': case '\'': ParseString(currentChar); return true; case 't': ParseTrue(); return true; case 'f': ParseFalse(); return true; case 'n': if (EnsureChars(1, true)) { char next = _chars[_charPos + 1]; if (next == 'u') ParseNull(); else if (next == 'e') ParseConstructor(); else throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } else { throw JsonReaderException.Create(this, "Unexpected end."); } return true; case 'N': ParseNumberNaN(); return true; case 'I': ParseNumberPositiveInfinity(); return true; case '-': if (EnsureChars(1, true) && _chars[_charPos + 1] == 'I') ParseNumberNegativeInfinity(); else ParseNumber(); return true; case '/': ParseComment(); return true; case 'u': ParseUndefined(); return true; case '{': _charPos++; SetToken(JsonToken.StartObject); return true; case '[': _charPos++; SetToken(JsonToken.StartArray); return true; case ']': _charPos++; SetToken(JsonToken.EndArray); return true; case ',': // don't increment position, the next call to read will handle comma // this is done to handle multiple empty comma values SetToken(JsonToken.Undefined); return true; case ')': _charPos++; SetToken(JsonToken.EndConstructor); return true; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; break; } if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.') { ParseNumber(); return true; } throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } } private void ProcessLineFeed() { _charPos++; OnNewLine(_charPos); } private void ProcessCarriageReturn(bool append) { _charPos++; if (EnsureChars(1, append) && _chars[_charPos] == StringUtils.LineFeed) _charPos++; OnNewLine(_charPos); } private bool EatWhitespace(bool oneOrMore) { bool finished = false; bool ateWhitespace = false; while (!finished) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) finished = true; } else { _charPos++; } break; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; default: if (currentChar == ' ' || char.IsWhiteSpace(currentChar)) { ateWhitespace = true; _charPos++; } else { finished = true; } break; } } return (!oneOrMore || ateWhitespace); } private void ParseConstructor() { if (MatchValueWithTrailingSeparator("new")) { EatWhitespace(false); int initialPosition = _charPos; int endPosition; while (true) { char currentChar = _chars[_charPos]; if (currentChar == '\0') { if (_charsUsed == _charPos) { if (ReadData(true) == 0) throw JsonReaderException.Create(this, "Unexpected end while parsing constructor."); } else { endPosition = _charPos; _charPos++; break; } } else if (char.IsLetterOrDigit(currentChar)) { _charPos++; } else if (currentChar == StringUtils.CarriageReturn) { endPosition = _charPos; ProcessCarriageReturn(true); break; } else if (currentChar == StringUtils.LineFeed) { endPosition = _charPos; ProcessLineFeed(); break; } else if (char.IsWhiteSpace(currentChar)) { endPosition = _charPos; _charPos++; break; } else if (currentChar == '(') { endPosition = _charPos; break; } else { throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } _stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition); string constructorName = _stringReference.ToString(); EatWhitespace(false); if (_chars[_charPos] != '(') throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); _charPos++; ClearRecentString(); SetToken(JsonToken.StartConstructor, constructorName); } else { throw JsonReaderException.Create(this, "Unexpected content while parsing JSON."); } } private void ParseNumber() { ShiftBufferIfNeeded(); char firstChar = _chars[_charPos]; int initialPosition = _charPos; ReadNumberIntoBuffer(); // set state to PostValue now so that if there is an error parsing the number then the reader can continue SetPostValueState(true); _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); object numberValue; JsonToken numberType; bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1); bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1 && _stringReference.Chars[_stringReference.StartIndex + 1] != '.' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'e' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'E'); if (_readType == ReadType.ReadAsInt32) { if (singleDigit) { // digit char values start at 48 numberValue = firstChar - 48; } else if (nonBase10) { string number = _stringReference.ToString(); try { int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt32(number, 16) : Convert.ToInt32(number, 8); numberValue = integer; } catch (Exception ex) { throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, number), ex); } } else { int value; ParseResult parseResult = ConvertUtils.Int32TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value); if (parseResult == ParseResult.Success) numberValue = value; else if (parseResult == ParseResult.Overflow) throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int32.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); else throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); } numberType = JsonToken.Integer; } else if (_readType == ReadType.ReadAsDecimal) { if (singleDigit) { // digit char values start at 48 numberValue = (decimal)firstChar - 48; } else if (nonBase10) { string number = _stringReference.ToString(); try { // decimal.Parse doesn't support parsing hexadecimal values long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); numberValue = Convert.ToDecimal(integer); } catch (Exception ex) { throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number), ex); } } else { string number = _stringReference.ToString(); decimal value; if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out value)) numberValue = value; else throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); } numberType = JsonToken.Float; } else { if (singleDigit) { // digit char values start at 48 numberValue = (long)firstChar - 48; numberType = JsonToken.Integer; } else if (nonBase10) { string number = _stringReference.ToString(); try { numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); } catch (Exception ex) { throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex); } numberType = JsonToken.Integer; } else { long value; ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value); if (parseResult == ParseResult.Success) { numberValue = value; numberType = JsonToken.Integer; } else if (parseResult == ParseResult.Overflow) { #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) string number = _stringReference.ToString(); if (number.Length > MaximumJavascriptIntegerCharacterLength) throw JsonReaderException.Create(this, "JSON integer {0} is too large to parse.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); numberValue = System.Numerics.BigInteger.Parse(number); // Mono 2.10.8.1 fix. numberType = JsonToken.Integer; #else throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); #endif } else { string number = _stringReference.ToString(); if (_floatParseHandling == FloatParseHandling.Decimal) { decimal d; if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out d)) numberValue = d; else throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number)); } else { double d; if (double.TryParse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d)) numberValue = d; else throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number)); } numberType = JsonToken.Float; } } } ClearRecentString(); // index has already been updated SetToken(numberType, numberValue, false); } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) // By using the BigInteger type in a separate method, // the runtime can execute the ParseNumber even if // the System.Numerics.BigInteger.Parse method is // missing, which happens in some versions of Mono /*[MethodImpl(MethodImplOptions.NoInlining)] // Mono 2.10.8.1 fix. private static object BigIntegerParse(string number, CultureInfo culture) { return System.Numerics.BigInteger.Parse(number, culture); }*/ #endif private void ParseComment() { // should have already parsed / character before reaching this method _charPos++; if (!EnsureChars(1, false)) throw JsonReaderException.Create(this, "Unexpected end while parsing comment."); bool singlelineComment; if (_chars[_charPos] == '*') singlelineComment = false; else if (_chars[_charPos] == '/') singlelineComment = true; else throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); _charPos++; int initialPosition = _charPos; bool commentFinished = false; while (!commentFinished) { switch (_chars[_charPos]) { case '\0': if (_charsUsed == _charPos) { if (ReadData(true) == 0) { if (!singlelineComment) throw JsonReaderException.Create(this, "Unexpected end while parsing comment."); _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); commentFinished = true; } } else { _charPos++; } break; case '*': _charPos++; if (!singlelineComment) { if (EnsureChars(0, true)) { if (_chars[_charPos] == '/') { _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition - 1); _charPos++; commentFinished = true; } } } break; case StringUtils.CarriageReturn: if (singlelineComment) { _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); commentFinished = true; } ProcessCarriageReturn(true); break; case StringUtils.LineFeed: if (singlelineComment) { _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); commentFinished = true; } ProcessLineFeed(); break; default: _charPos++; break; } } SetToken(JsonToken.Comment, _stringReference.ToString()); ClearRecentString(); } private bool MatchValue(string value) { if (!EnsureChars(value.Length - 1, true)) return false; for (int i = 0; i < value.Length; i++) { if (_chars[_charPos + i] != value[i]) { return false; } } _charPos += value.Length; return true; } private bool MatchValueWithTrailingSeparator(string value) { // will match value and then move to the next character, checking that it is a separator character bool match = MatchValue(value); if (!match) return false; if (!EnsureChars(0, false)) return true; return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0'; } private bool IsSeparator(char c) { switch (c) { case '}': case ']': case ',': return true; case '/': // check next character to see if start of a comment if (!EnsureChars(1, false)) return false; var nextChart = _chars[_charPos + 1]; return (nextChart == '*' || nextChart == '/'); case ')': if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart) return true; break; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: return true; default: if (char.IsWhiteSpace(c)) return true; break; } return false; } private void ParseTrue() { // check characters equal 'true' // and that it is followed by either a separator character // or the text ends if (MatchValueWithTrailingSeparator(JsonConvert.True)) { SetToken(JsonToken.Boolean, true); } else { throw JsonReaderException.Create(this, "Error parsing boolean value."); } } private void ParseNull() { if (MatchValueWithTrailingSeparator(JsonConvert.Null)) { SetToken(JsonToken.Null); } else { throw JsonReaderException.Create(this, "Error parsing null value."); } } private void ParseUndefined() { if (MatchValueWithTrailingSeparator(JsonConvert.Undefined)) { SetToken(JsonToken.Undefined); } else { throw JsonReaderException.Create(this, "Error parsing undefined value."); } } private void ParseFalse() { if (MatchValueWithTrailingSeparator(JsonConvert.False)) { SetToken(JsonToken.Boolean, false); } else { throw JsonReaderException.Create(this, "Error parsing boolean value."); } } private void ParseNumberNegativeInfinity() { if (MatchValueWithTrailingSeparator(JsonConvert.NegativeInfinity)) { if (_floatParseHandling == FloatParseHandling.Decimal) throw new JsonReaderException("Cannot read -Infinity as a decimal."); SetToken(JsonToken.Float, double.NegativeInfinity); } else { throw JsonReaderException.Create(this, "Error parsing negative infinity value."); } } private void ParseNumberPositiveInfinity() { if (MatchValueWithTrailingSeparator(JsonConvert.PositiveInfinity)) { if (_floatParseHandling == FloatParseHandling.Decimal) throw new JsonReaderException("Cannot read Infinity as a decimal."); SetToken(JsonToken.Float, double.PositiveInfinity); } else { throw JsonReaderException.Create(this, "Error parsing positive infinity value."); } } private void ParseNumberNaN() { if (MatchValueWithTrailingSeparator(JsonConvert.NaN)) { if (_floatParseHandling == FloatParseHandling.Decimal) throw new JsonReaderException("Cannot read NaN as a decimal."); SetToken(JsonToken.Float, double.NaN); } else { throw JsonReaderException.Create(this, "Error parsing NaN value."); } } /// <summary> /// Changes the state to closed. /// </summary> public override void Close() { base.Close(); if (CloseInput && _reader != null) { #if !(DOTNET || PORTABLE40 || PORTABLE) _reader.Close(); #else _reader.Dispose(); #endif } if (_buffer != null) _buffer.Clear(); } /// <summary> /// Gets a value indicating whether the class can return line information. /// </summary> /// <returns> /// <c>true</c> if LineNumber and LinePosition can be provided; otherwise, <c>false</c>. /// </returns> public bool HasLineInfo() { return true; } /// <summary> /// Gets the current line number. /// </summary> /// <value> /// The current line number or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LineNumber { get { if (CurrentState == State.Start && LinePosition == 0) return 0; return _lineNumber; } } /// <summary> /// Gets the current line position. /// </summary> /// <value> /// The current line position or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LinePosition { get { return _charPos - _lineStartPos; } } } }
/* * Project: Membership Log (application using WhaTBI?) * Filename: Member.cs * Description: Class describing a member in the app */ using System; using System.Collections; using System.ComponentModel; using Pdbartlett.Whatbi; using Pdbartlett.Whatbi.Custom; namespace Pdbartlett.MembershipLog { public class Member : DynamicObjectHelper, ICloneable, IGetKey { // value types private bool m_doneGymInduction = false; private DateTime m_dateOfBirth; // scalar ref types private string m_id = ""; private string m_lastName = ""; private string m_firstName = ""; private string m_homeAddress = ""; private string m_department = ""; // collections private DetailCollection m_details = new DetailCollection(); private MembershipCollection m_memberships = new MembershipCollection(); private PaymentCollection m_payments = new PaymentCollection(); public string Id { get { return m_id; } set { m_id = value; } } public string LastName { get { return m_lastName; } set { m_lastName = value; } } public string FirstName { get { return m_firstName; } set { m_firstName = value; } } public DateTime DateOfBirth { get { return m_dateOfBirth; } set { m_dateOfBirth = value; } } public int Age { get { // !!! approximation !!! TimeSpan ts = DateTime.Today - m_dateOfBirth; return (int)(Math.Floor(ts.Days / 365.25)); } } public string HomeAddress { get { return m_homeAddress; } set { m_homeAddress = value; } } public string Department { get { return m_department; } set { m_department = value; } } public bool DoneGymInduction { get { return m_doneGymInduction; } set { m_doneGymInduction = value; } } public DetailCollection Details { get { return m_details; } } public MembershipCollection Memberships { get { return m_memberships; } } public PaymentCollection Payments { get { return m_payments; } } public double OwedCalc { get { Decimal owed = 0; foreach (object o in Memberships) { Membership m = (Membership)o; owed += m.Cost; } foreach (object o in Payments) { Payment p = (Payment)o; owed -= p.Amount; } return (double)owed; } } public string Owed { get { return String.Format("{0:0.00}", OwedCalc); } } public DateTime CurrentEndDate { get { DateTime max = DateTime.MinValue; foreach (object o in Memberships) { Membership m = (Membership)o; if (m.EndDate > max) max = m.EndDate; } return max; } } protected override PropertyDescriptorCollection InternalGetPropDescColl() { PropertyDescriptorCollection pdc = base.InternalGetPropDescColl(); DetailTypeCollection dtc = Settings.Current.Details; PropertyDescriptor[] pda = new PropertyDescriptor[pdc.Count + dtc.Count]; pdc.CopyTo(pda, 0); int i = pdc.Count; foreach (object o in Settings.Current.Details) { DetailType d = (DetailType)o; // for all detail values are strings pda[i++] = new PropInfoToPropDescAdapter( GetType(), new DynamicPropertyInfo(d.Name, new TypeToTypeInfoAdapter(typeof(string)), new ObjectValueGetter(DetailGetter))); } return new PropertyDescriptorCollection(pda); } private static object DetailGetter(IPropertyInfo sender, object o) { Member member = (Member)o; Detail detail = member.Details.Get(sender.Name) as Detail; return detail == null ? "" : detail.Value; } public object Clone() { Member m = (Member)MemberwiseClone(); // must use member variables as the corresponding properties are read-only m.m_details = new DetailCollection(Details.GetAll()); m.m_memberships = new MembershipCollection(Memberships.GetAll()); m.m_payments = new PaymentCollection(Payments.GetAll()); return m; } public override bool Equals(object otherObject) { Member otherMember = otherObject as Member; return otherMember != null && otherMember.Id == Id && otherMember.LastName == LastName && otherMember.FirstName == FirstName && otherMember.DateOfBirth == DateOfBirth && otherMember.HomeAddress == HomeAddress && otherMember.Department == Department ; } public override int GetHashCode() { return Id.GetHashCode(); } public object GetKey() { return Id; } internal static Member GenerateRandom(string id) { Member random = new Member(); random.Id = id; random.LastName = (string)RandomListElement(lastNames); random.FirstName = (string)RandomListElement(firstNames); random.Department = (string)RandomListElement(deptNames); int yearsOld = 16 + Random0toN(20) + Random0toN(20) + Random0toN(20); int daysOld = 365 * yearsOld + Random0toN(365); random.DateOfBirth = DateTime.Today - new TimeSpan(daysOld, 0, 0, 0); string addressLine1 = String.Format("{0} {1} {2}", Random1toN(99), RandomListElement(roadNames), RandomListElement(roadTypes)); if (Random1toN(10) > 6) { random.HomeAddress = String.Format("{0}\n{1}\nBristol\nBS{2} {3}{4}{5}", addressLine1, RandomListElement(bristolAreas), Random1toN(99), Random0toN(9), RandomLetter(), RandomLetter()); } else { random.HomeAddress = String.Format("{0}\n{1}\nBath\nBA1 {2}{3}{4}", addressLine1, RandomListElement(bathAreas), Random0toN(9), RandomLetter(), RandomLetter()); } foreach (object o in Settings.Current.Details.GetAll()) { if (Random0toN(10) < 8) { Detail detail = new Detail(); detail.Name = ((DetailType)o).Name; detail.Value = "Test"; random.Details.Add(detail); } } int cMaxYears = Math.Min(10, random.Age - 15); int cYears = Random1toN(cMaxYears); int thisYear = DateTime.Today.Year; for (int i = 0; i < cYears; ++i) { Membership ms = new Membership(); ms.StartDate = new DateTime(thisYear - i, 1, 1); ms.EndDate = new DateTime(thisYear - i, 12, 31); ms.Cost = (Decimal)(20 - i + 0.50); ms.MembershipType = "Standard"; random.Memberships.Add(ms); int r = Random1toN(20); if (i ==0 && r == 1) continue; Payment p = new Payment(); p.PaymentDate = ms.StartDate + new TimeSpan(Random0toN(90), 0, 0, 0); Decimal proportion = (Decimal)((i == 0 && r == 2) ? Random1toN(12) / 12.0 : 1); p.Amount = Decimal.Round(proportion * ms.Cost, 2); p.Description = "Cash"; random.Payments.Add(p); } return random; } private static object RandomListElement(IList list) { return list[Random0toN(list.Count - 1)]; } private static int Random0toN(int n) { if (n < 0) throw new ArgumentException(); int val = -1; while (val < 0 || val > n) val = rand.Next(n + 1); return val; } private static int Random1toN(int n) { return 1 + Random0toN(n - 1); } private static char RandomLetter() { return (char)((int)'A' + Random0toN(25)); } private static Random rand = new Random(); private static readonly string[] lastNames = { "Allen", "Aston", "Bartlett", "Brown", "Cole", "Cutler", "Davidson", "Dunn", "Ellis", "East", "Fenchurch", "Foster", "Gardner", "Goldman", "Hall", "Horne", "Innis", "Irwin", "Jackson", "Jones", "Keller", "Keighley", "Lawson", "Lester", "Maddison", "Morton", "Newton", "North", "Old", "Oakley", "Peterson", "Pullman", "Quinlan", "Quincy", "Rawlins", "Rowley", "Smith", "Sells", "Tomkins", "Taylor", "Unwin", "Upson", "Vardey", "Vickers", "Watson", "Weston", "Yardley", "Zimmerman" }; private static readonly string[] firstNames = { "Anne", "Andrew", "Brenda", "Barney", "Cathy", "Charles", "Dawn", "David", "Ellie", "Edward", "Fern", "Frank", "Geraldine", "George", "Helen", "Hector", "Isobel", "Ian", "Jill", "Jack", "Kelly", "Keith", "Lucy", "Lee", "Maggie", "Michael", "Nancy", "Nigel", "Orla", "Oswald", "Penny", "Peter", "Rosie", "Rachel", "Robert", "Richard", "Sophie", "Sally", "Simon", "Steven", "Tara", "Tina", "Thomas", "Timothy", "Ulrika", "Vincent", "Wesley", "Zoe" }; private static readonly string[] roadNames = { "Alder", "Bank", "Castle", "Down", "East", "Forest", "Grange", "Hills", "Inver", "Juniper", "Kings", "Laurel", "Mansion", "North", "Oak", "Parsonage", "Queens", "Railway", "South", "Thames", "Underwood", "Vine", "West", "Yew Tree", "Zoo" }; private static readonly string[] roadTypes = { "Avenue", "Road", "Street", "Cottages", "Lane", "Close", "Way" }; private static readonly string[] bristolAreas = { "Clifton", "Fishponds", "Bitton", "St Pauls" }; private static readonly string[] bathAreas = { "Weston", "Bear Flat", "Oldfield Park", "Combe Down", "Landsdown", "Odd Down" }; private static readonly string[] deptNames = { "General Surgery", "Radiology", "PAW", "ENT", "Gynae/Obs", "Clerical", "Porterage", "Ancillary", "Paediatrics", "Maxillo-Facial", "Dermatology", "Medical Imaging", "Cardiology", "Physiotherapy", "A&E", "Other", "N/A" }; } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License Is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HWPF.Model.Types { using System; using NPOI.Util; using NPOI.HWPF.UserModel; using System.Text; /** * Base part of the File information Block (FibBase). Holds the core part of the FIB, from the first 32 bytes. * NOTE: This source Is automatically generated please do not modify this file. Either subclass or * remove the record in src/records/definitions. * @author Andrew C. Oliver */ public abstract class FIBAbstractType : BaseObject { protected int field_1_wIdent; protected int field_2_nFib; protected int field_3_nProduct; protected int field_4_lid; protected int field_5_pnNext; protected short field_6_options; private static BitField fDot = BitFieldFactory.GetInstance(0x0001); private static BitField fGlsy = BitFieldFactory.GetInstance(0x0002); private static BitField fComplex = BitFieldFactory.GetInstance(0x0004); private static BitField fHasPic = BitFieldFactory.GetInstance(0x0008); private static BitField cQuickSaves = BitFieldFactory.GetInstance(0x00F0); private static BitField fEncrypted = BitFieldFactory.GetInstance(0x0100); private static BitField fWhichTblStm = BitFieldFactory.GetInstance(0x0200); private static BitField fReadOnlyRecommended = BitFieldFactory.GetInstance(0x0400); private static BitField fWriteReservation = BitFieldFactory.GetInstance(0x0800); private static BitField fExtChar = BitFieldFactory.GetInstance(0x1000); private static BitField fLoadOverride = BitFieldFactory.GetInstance(0x2000); private static BitField fFarEast = BitFieldFactory.GetInstance(0x4000); private static BitField fCrypto = BitFieldFactory.GetInstance(0x8000); protected int field_7_nFibBack; protected int field_8_lKey; protected int field_9_envr; protected short field_10_history; private static BitField fMac = BitFieldFactory.GetInstance(0x0001); private static BitField fEmptySpecial = BitFieldFactory.GetInstance(0x0002); private static BitField fLoadOverridePage = BitFieldFactory.GetInstance(0x0004); private static BitField fFutureSavedUndo = BitFieldFactory.GetInstance(0x0008); private static BitField fWord97Saved = BitFieldFactory.GetInstance(0x0010); private static BitField fSpare0 = BitFieldFactory.GetInstance(0x00FE); protected int field_11_chs; /** Latest docs say this Is Reserved3! */ protected int field_12_chsTables; /** Latest docs say this Is Reserved4! */ protected int field_13_fcMin; /** Latest docs say this Is Reserved5! */ protected int field_14_fcMac; /** Latest docs say this Is Reserved6! */ public FIBAbstractType() { } protected void FillFields(byte[] data, int offset) { field_1_wIdent = LittleEndian.GetShort(data, 0x0 + offset); field_2_nFib = LittleEndian.GetShort(data, 0x2 + offset); field_3_nProduct = LittleEndian.GetShort(data, 0x4 + offset); field_4_lid = LittleEndian.GetShort(data, 0x6 + offset); field_5_pnNext = LittleEndian.GetShort(data, 0x8 + offset); field_6_options = LittleEndian.GetShort(data, 0xa + offset); field_7_nFibBack = LittleEndian.GetShort(data, 0xc + offset); field_8_lKey = LittleEndian.GetShort(data, 0xe + offset); field_9_envr = LittleEndian.GetShort(data, 0x10 + offset); field_10_history = LittleEndian.GetShort(data, 0x12 + offset); field_11_chs = LittleEndian.GetShort(data, 0x14 + offset); field_12_chsTables = LittleEndian.GetShort(data, 0x16 + offset); field_13_fcMin = LittleEndian.GetInt(data, 0x18 + offset); field_14_fcMac = LittleEndian.GetInt(data, 0x1c + offset); } public void Serialize(byte[] data, int offset) { LittleEndian.PutShort(data, 0x0 + offset, (short)field_1_wIdent); ; LittleEndian.PutShort(data, 0x2 + offset, (short)field_2_nFib); ; LittleEndian.PutShort(data, 0x4 + offset, (short)field_3_nProduct); ; LittleEndian.PutShort(data, 0x6 + offset, (short)field_4_lid); ; LittleEndian.PutShort(data, 0x8 + offset, (short)field_5_pnNext); ; LittleEndian.PutShort(data, 0xa + offset, (short)field_6_options); ; LittleEndian.PutShort(data, 0xc + offset, (short)field_7_nFibBack); ; LittleEndian.PutShort(data, 0xe + offset, (short)field_8_lKey); ; LittleEndian.PutShort(data, 0x10 + offset, (short)field_9_envr); ; LittleEndian.PutShort(data, 0x12 + offset, (short)field_10_history); ; LittleEndian.PutShort(data, 0x14 + offset, (short)field_11_chs); ; LittleEndian.PutShort(data, 0x16 + offset, (short)field_12_chsTables); ; LittleEndian.PutInt(data, 0x18 + offset, field_13_fcMin); ; LittleEndian.PutInt(data, 0x1c + offset, field_14_fcMac); ; } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[FIB]\n"); buffer.Append(" .wIdent = "); buffer.Append(" (").Append(GetWIdent()).Append(" )\n"); buffer.Append(" .nFib = "); buffer.Append(" (").Append(GetNFib()).Append(" )\n"); buffer.Append(" .nProduct = "); buffer.Append(" (").Append(GetNProduct()).Append(" )\n"); buffer.Append(" .lid = "); buffer.Append(" (").Append(GetLid()).Append(" )\n"); buffer.Append(" .pnNext = "); buffer.Append(" (").Append(GetPnNext()).Append(" )\n"); buffer.Append(" .options = "); buffer.Append(" (").Append(GetOptions()).Append(" )\n"); buffer.Append(" .fDot = ").Append(IsFDot()).Append('\n'); buffer.Append(" .fGlsy = ").Append(IsFGlsy()).Append('\n'); buffer.Append(" .fComplex = ").Append(IsFComplex()).Append('\n'); buffer.Append(" .fHasPic = ").Append(IsFHasPic()).Append('\n'); buffer.Append(" .cQuickSaves = ").Append(GetCQuickSaves()).Append('\n'); buffer.Append(" .fEncrypted = ").Append(IsFEncrypted()).Append('\n'); buffer.Append(" .fWhichTblStm = ").Append(IsFWhichTblStm()).Append('\n'); buffer.Append(" .fReadOnlyRecommended = ").Append(IsFReadOnlyRecommended()).Append('\n'); buffer.Append(" .fWriteReservation = ").Append(IsFWriteReservation()).Append('\n'); buffer.Append(" .fExtChar = ").Append(IsFExtChar()).Append('\n'); buffer.Append(" .fLoadOverride = ").Append(IsFLoadOverride()).Append('\n'); buffer.Append(" .fFarEast = ").Append(IsFFarEast()).Append('\n'); buffer.Append(" .fCrypto = ").Append(IsFCrypto()).Append('\n'); buffer.Append(" .nFibBack = "); buffer.Append(" (").Append(GetNFibBack()).Append(" )\n"); buffer.Append(" .lKey = "); buffer.Append(" (").Append(GetLKey()).Append(" )\n"); buffer.Append(" .envr = "); buffer.Append(" (").Append(GetEnvr()).Append(" )\n"); buffer.Append(" .history = "); buffer.Append(" (").Append(GetHistory()).Append(" )\n"); buffer.Append(" .fMac = ").Append(IsFMac()).Append('\n'); buffer.Append(" .fEmptySpecial = ").Append(IsFEmptySpecial()).Append('\n'); buffer.Append(" .fLoadOverridePage = ").Append(IsFLoadOverridePage()).Append('\n'); buffer.Append(" .fFutureSavedUndo = ").Append(IsFFutureSavedUndo()).Append('\n'); buffer.Append(" .fWord97Saved = ").Append(IsFWord97Saved()).Append('\n'); buffer.Append(" .fSpare0 = ").Append(GetFSpare0()).Append('\n'); buffer.Append(" .chs = "); buffer.Append(" (").Append(GetChs()).Append(" )\n"); buffer.Append(" .chsTables = "); buffer.Append(" (").Append(GetChsTables()).Append(" )\n"); buffer.Append(" .fcMin = "); buffer.Append(" (").Append(GetFcMin()).Append(" )\n"); buffer.Append(" .fcMac = "); buffer.Append(" (").Append(GetFcMac()).Append(" )\n"); buffer.Append("[/FIB]\n"); return buffer.ToString(); } /** * Size of record (exluding 4 byte header) */ public virtual int GetSize() { return 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 4 + 4; } /** * Get the wIdent field for the FIB record. */ public int GetWIdent() { return field_1_wIdent; } /** * Set the wIdent field for the FIB record. */ public void SetWIdent(int field_1_wIdent) { this.field_1_wIdent = field_1_wIdent; } /** * Get the nFib field for the FIB record. */ public int GetNFib() { return field_2_nFib; } /** * Set the nFib field for the FIB record. */ public void SetNFib(int field_2_nFib) { this.field_2_nFib = field_2_nFib; } /** * Get the nProduct field for the FIB record. */ public int GetNProduct() { return field_3_nProduct; } /** * Set the nProduct field for the FIB record. */ public void SetNProduct(int field_3_nProduct) { this.field_3_nProduct = field_3_nProduct; } /** * Get the lid field for the FIB record. */ public int GetLid() { return field_4_lid; } /** * Set the lid field for the FIB record. */ public void SetLid(int field_4_lid) { this.field_4_lid = field_4_lid; } /** * Get the pnNext field for the FIB record. */ public int GetPnNext() { return field_5_pnNext; } /** * Set the pnNext field for the FIB record. */ public void SetPnNext(int field_5_pnNext) { this.field_5_pnNext = field_5_pnNext; } /** * Get the options field for the FIB record. */ public short GetOptions() { return field_6_options; } /** * Set the options field for the FIB record. */ public void SetOptions(short field_6_options) { this.field_6_options = field_6_options; } /** * Get the nFibBack field for the FIB record. */ public int GetNFibBack() { return field_7_nFibBack; } /** * Set the nFibBack field for the FIB record. */ public void SetNFibBack(int field_7_nFibBack) { this.field_7_nFibBack = field_7_nFibBack; } /** * Get the lKey field for the FIB record. */ public int GetLKey() { return field_8_lKey; } /** * Set the lKey field for the FIB record. */ public void SetLKey(int field_8_lKey) { this.field_8_lKey = field_8_lKey; } /** * Get the envr field for the FIB record. */ public int GetEnvr() { return field_9_envr; } /** * Set the envr field for the FIB record. */ public void SetEnvr(int field_9_envr) { this.field_9_envr = field_9_envr; } /** * Get the history field for the FIB record. */ public short GetHistory() { return field_10_history; } /** * Set the history field for the FIB record. */ public void SetHistory(short field_10_history) { this.field_10_history = field_10_history; } /** * Get the chs field for the FIB record. */ public int GetChs() { return field_11_chs; } /** * Set the chs field for the FIB record. */ public void SetChs(int field_11_chs) { this.field_11_chs = field_11_chs; } /** * Get the chsTables field for the FIB record. */ public int GetChsTables() { return field_12_chsTables; } /** * Set the chsTables field for the FIB record. */ public void SetChsTables(int field_12_chsTables) { this.field_12_chsTables = field_12_chsTables; } /** * Get the fcMin field for the FIB record. */ public int GetFcMin() { return field_13_fcMin; } /** * Set the fcMin field for the FIB record. */ public void SetFcMin(int field_13_fcMin) { this.field_13_fcMin = field_13_fcMin; } /** * Get the fcMac field for the FIB record. */ public int GetFcMac() { return field_14_fcMac; } /** * Set the fcMac field for the FIB record. */ public void SetFcMac(int field_14_fcMac) { this.field_14_fcMac = field_14_fcMac; } /** * Sets the fDot field value. * */ public void SetFDot(bool value) { field_6_options = (short)fDot.SetBoolean(field_6_options, value); } /** * * @return the fDot field value. */ public bool IsFDot() { return fDot.IsSet(field_6_options); } /** * Sets the fGlsy field value. * */ public void SetFGlsy(bool value) { field_6_options = (short)fGlsy.SetBoolean(field_6_options, value); } /** * * @return the fGlsy field value. */ public bool IsFGlsy() { return fGlsy.IsSet(field_6_options); } /** * Sets the fComplex field value. * */ public void SetFComplex(bool value) { field_6_options = (short)fComplex.SetBoolean(field_6_options, value); } /** * * @return the fComplex field value. */ public bool IsFComplex() { return fComplex.IsSet(field_6_options); } /** * Sets the fHasPic field value. * */ public void SetFHasPic(bool value) { field_6_options = (short)fHasPic.SetBoolean(field_6_options, value); } /** * * @return the fHasPic field value. */ public bool IsFHasPic() { return fHasPic.IsSet(field_6_options); } /** * Sets the cQuickSaves field value. * */ public void SetCQuickSaves(byte value) { field_6_options = (short)cQuickSaves.SetValue(field_6_options, value); } /** * * @return the cQuickSaves field value. */ public byte GetCQuickSaves() { return (byte)cQuickSaves.GetValue(field_6_options); } /** * Sets the fEncrypted field value. * */ public void SetFEncrypted(bool value) { field_6_options = (short)fEncrypted.SetBoolean(field_6_options, value); } /** * * @return the fEncrypted field value. */ public bool IsFEncrypted() { return fEncrypted.IsSet(field_6_options); } /** * Sets the fWhichTblStm field value. * */ public void SetFWhichTblStm(bool value) { field_6_options = (short)fWhichTblStm.SetBoolean(field_6_options, value); } /** * * @return the fWhichTblStm field value. */ public bool IsFWhichTblStm() { return fWhichTblStm.IsSet(field_6_options); } /** * Sets the fReadOnlyRecommended field value. * */ public void SetFReadOnlyRecommended(bool value) { field_6_options = (short)fReadOnlyRecommended.SetBoolean(field_6_options, value); } /** * * @return the fReadOnlyRecommended field value. */ public bool IsFReadOnlyRecommended() { return fReadOnlyRecommended.IsSet(field_6_options); } /** * Sets the fWriteReservation field value. * */ public void SetFWriteReservation(bool value) { field_6_options = (short)fWriteReservation.SetBoolean(field_6_options, value); } /** * * @return the fWriteReservation field value. */ public bool IsFWriteReservation() { return fWriteReservation.IsSet(field_6_options); } /** * Sets the fExtChar field value. * */ public void SetFExtChar(bool value) { field_6_options = (short)fExtChar.SetBoolean(field_6_options, value); } /** * * @return the fExtChar field value. */ public bool IsFExtChar() { return fExtChar.IsSet(field_6_options); } /** * Sets the fLoadOverride field value. * */ public void SetFLoadOverride(bool value) { field_6_options = (short)fLoadOverride.SetBoolean(field_6_options, value); } /** * * @return the fLoadOverride field value. */ public bool IsFLoadOverride() { return fLoadOverride.IsSet(field_6_options); } /** * Sets the fFarEast field value. * */ public void SetFFarEast(bool value) { field_6_options = (short)fFarEast.SetBoolean(field_6_options, value); } /** * * @return the fFarEast field value. */ public bool IsFFarEast() { return fFarEast.IsSet(field_6_options); } /** * Sets the fCrypto field value. * */ public void SetFCrypto(bool value) { field_6_options = (short)fCrypto.SetBoolean(field_6_options, value); } /** * * @return the fCrypto field value. */ public bool IsFCrypto() { return fCrypto.IsSet(field_6_options); } /** * Sets the fMac field value. * */ public void SetFMac(bool value) { field_10_history = (short)fMac.SetBoolean(field_10_history, value); } /** * * @return the fMac field value. */ public bool IsFMac() { return fMac.IsSet(field_10_history); } /** * Sets the fEmptySpecial field value. * */ public void SetFEmptySpecial(bool value) { field_10_history = (short)fEmptySpecial.SetBoolean(field_10_history, value); } /** * * @return the fEmptySpecial field value. */ public bool IsFEmptySpecial() { return fEmptySpecial.IsSet(field_10_history); } /** * Sets the fLoadOverridePage field value. * */ public void SetFLoadOverridePage(bool value) { field_10_history = (short)fLoadOverridePage.SetBoolean(field_10_history, value); } /** * * @return the fLoadOverridePage field value. */ public bool IsFLoadOverridePage() { return fLoadOverridePage.IsSet(field_10_history); } /** * Sets the fFutureSavedUndo field value. * */ public void SetFFutureSavedUndo(bool value) { field_10_history = (short)fFutureSavedUndo.SetBoolean(field_10_history, value); } /** * * @return the fFutureSavedUndo field value. */ public bool IsFFutureSavedUndo() { return fFutureSavedUndo.IsSet(field_10_history); } /** * Sets the fWord97Saved field value. * */ public void SetFWord97Saved(bool value) { field_10_history = (short)fWord97Saved.SetBoolean(field_10_history, value); } /** * * @return the fWord97Saved field value. */ public bool IsFWord97Saved() { return fWord97Saved.IsSet(field_10_history); } /** * Sets the fSpare0 field value. * */ public void SetFSpare0(byte value) { field_10_history = (short)fSpare0.SetValue(field_10_history, value); } /** * * @return the fSpare0 field value. */ public byte GetFSpare0() { return (byte)fSpare0.GetValue(field_10_history); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using Internal.Runtime.CompilerServices; namespace System { /// <summary> /// Memory represents a contiguous region of arbitrary memory similar to <see cref="Span{T}"/>. /// Unlike <see cref="Span{T}"/>, it is not a byref-like type. /// </summary> [DebuggerTypeProxy(typeof(MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct Memory<T> { // NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout, // as code uses Unsafe.As to cast between them. // The highest order bit of _index is used to discern whether _object is a pre-pinned array. // (_index < 0) => _object is a pre-pinned array, so Pin() will not allocate a new GCHandle // (else) => Pin() needs to allocate a new GCHandle to pin the object. private readonly object _object; private readonly int _index; private readonly int _length; /// <summary> /// Creates a new memory over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array) { if (array == null) { this = default; return; // returns default } if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(T[] array, int start) { if (array == null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); _object = array; _index = start; _length = array.Length - start; } /// <summary> /// Creates a new memory over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); #if BIT64 // See comment in Span<T>.Slice for how this works. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); #else if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); #endif _object = array; _index = start; _length = length; } /// <summary> /// Creates a new memory from a memory manager that provides specific method implementations beginning /// at 0 index and ending at 'end' index (exclusive). /// </summary> /// <param name="manager">The memory manager.</param> /// <param name="length">The number of items in the memory.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> /// <remarks>For internal infrastructure only</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int length) { Debug.Assert(manager != null); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _object = manager; _index = 0; _length = length; } /// <summary> /// Creates a new memory from a memory manager that provides specific method implementations beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="manager">The memory manager.</param> /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or <paramref name="length"/> is negative. /// </exception> /// <remarks>For internal infrastructure only</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int start, int length) { Debug.Assert(manager != null); if (length < 0 || start < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _object = manager; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(object obj, int start, int length) { // No validation performed in release builds; caller must provide any necessary validation. // 'obj is T[]' below also handles things like int[] <-> uint[] being convertible Debug.Assert((obj == null) || (typeof(T) == typeof(char) && obj is string) #if FEATURE_UTF8STRING || ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && obj is Utf8String) #endif // FEATURE_UTF8STRING || (obj is T[]) || (obj is MemoryManager<T>)); _object = obj; _index = start; _length = length; } /// <summary> /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(T[] array) => new Memory<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(ArraySegment<T> segment) => new Memory<T>(segment.Array, segment.Offset, segment.Count); /// <summary> /// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/> /// </summary> public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) => Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory); /// <summary> /// Returns an empty <see cref="Memory{T}"/> /// </summary> public static Memory<T> Empty => default; /// <summary> /// The number of items in the memory. /// </summary> public int Length => _length; /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty => _length == 0; /// <summary> /// For <see cref="Memory{Char}"/>, returns a new instance of string that represents the characters pointed to by the memory. /// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements. /// </summary> public override string ToString() { if (typeof(T) == typeof(char)) { return (_object is string str) ? str.Substring(_index, _length) : Span.ToString(); } #if FEATURE_UTF8STRING else if (typeof(T) == typeof(Char8)) { // TODO_UTF8STRING: Call into optimized transcoding routine when it's available. Span<T> span = Span; return Encoding.UTF8.GetString(new ReadOnlySpan<byte>(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length)); } #endif // FEATURE_UTF8STRING return string.Format("System.Memory<{0}>[{1}]", typeof(T).Name, _length); } /// <summary> /// Forms a slice out of the given memory, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start) { if ((uint)start > (uint)_length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } // It is expected for _index + start to be negative if the memory is already pre-pinned. return new Memory<T>(_object, _index + start, _length - start); } /// <summary> /// Forms a slice out of the given memory, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start, int length) { #if BIT64 // See comment in Span<T>.Slice for how this works. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); #else if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); #endif // It is expected for _index + start to be negative if the memory is already pre-pinned. return new Memory<T>(_object, _index + start, length); } /// <summary> /// Forms a slice out of the given memory, beginning at 'startIndex' /// </summary> /// <param name="startIndex">The index at which to begin this slice.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(Index startIndex) { int actualIndex = startIndex.GetOffset(_length); return Slice(actualIndex); } /// <summary> /// Forms a slice out of the given memory using the range start and end indexes. /// </summary> /// <param name="range">The range used to slice the memory using its start and end indexes.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(Range range) { (int start, int length) = range.GetOffsetAndLength(_length); // It is expected for _index + start to be negative if the memory is already pre-pinned. return new Memory<T>(_object, _index + start, length); } /// <summary> /// Forms a slice out of the given memory using the range start and end indexes. /// </summary> /// <param name="range">The range used to slice the memory using its start and end indexes.</param> public Memory<T> this[Range range] => Slice(range); /// <summary> /// Returns a span from the memory. /// </summary> public unsafe Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { // This property getter has special support for returning a mutable Span<char> that wraps // an immutable String instance. This is obviously a dangerous feature and breaks type safety. // However, we need to handle the case where a ReadOnlyMemory<char> was created from a string // and then cast to a Memory<T>. Such a cast can only be done with unsafe or marshaling code, // in which case that's the dangerous operation performed by the dev, and we're just following // suit here to make it work as best as possible. ref T refToReturn = ref Unsafe.AsRef<T>(null); int lengthOfUnderlyingSpan = 0; // Copy this field into a local so that it can't change out from under us mid-operation. object tmpObject = _object; if (tmpObject != null) { if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string)) { // Special-case string since it's the most common for ROM<char>. refToReturn = ref Unsafe.As<char, T>(ref Unsafe.As<string>(tmpObject).GetRawStringData()); lengthOfUnderlyingSpan = Unsafe.As<string>(tmpObject).Length; } #if FEATURE_UTF8STRING else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject.GetType() == typeof(Utf8String)) { refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<Utf8String>(tmpObject).DangerousGetMutableReference()); lengthOfUnderlyingSpan = Unsafe.As<Utf8String>(tmpObject).Length; } #endif // FEATURE_UTF8STRING else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject)) { // We know the object is not null, it's not a string, and it is variable-length. The only // remaining option is for it to be a T[] (or a U[] which is blittable to T[], like int[] // and uint[]). Otherwise somebody used private reflection to set this field, and we're not // too worried about type safety violations at this point. // 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible Debug.Assert(tmpObject is T[]); refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()); lengthOfUnderlyingSpan = Unsafe.As<T[]>(tmpObject).Length; } else { // We know the object is not null, and it's not variable-length, so it must be a MemoryManager<T>. // Otherwise somebody used private reflection to set this field, and we're not too worried about // type safety violations at that point. Note that it can't be a MemoryManager<U>, even if U and // T are blittable (e.g., MemoryManager<int> to MemoryManager<uint>), since there exists no // constructor or other public API which would allow such a conversion. Debug.Assert(tmpObject is MemoryManager<T>); Span<T> memoryManagerSpan = Unsafe.As<MemoryManager<T>>(tmpObject).GetSpan(); refToReturn = ref MemoryMarshal.GetReference(memoryManagerSpan); lengthOfUnderlyingSpan = memoryManagerSpan.Length; } // If the Memory<T> or ReadOnlyMemory<T> instance is torn, this property getter has undefined behavior. // We try to detect this condition and throw an exception, but it's possible that a torn struct might // appear to us to be valid, and we'll return an undesired span. Such a span is always guaranteed at // least to be in-bounds when compared with the original Memory<T> instance, so using the span won't // AV the process. int desiredStartIndex = _index & ReadOnlyMemory<T>.RemoveFlagsBitMask; int desiredLength = _length; #if BIT64 // See comment in Span<T>.Slice for how this works. if ((ulong)(uint)desiredStartIndex + (ulong)(uint)desiredLength > (ulong)(uint)lengthOfUnderlyingSpan) { ThrowHelper.ThrowArgumentOutOfRangeException(); } #else if ((uint)desiredStartIndex > (uint)lengthOfUnderlyingSpan || (uint)desiredLength > (uint)(lengthOfUnderlyingSpan - desiredStartIndex)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } #endif refToReturn = ref Unsafe.Add(ref refToReturn, desiredStartIndex); lengthOfUnderlyingSpan = desiredLength; } return new Span<T>(ref refToReturn, lengthOfUnderlyingSpan); } } /// <summary> /// Copies the contents of the memory into the destination. If the source /// and destination overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. /// /// <param name="destination">The Memory to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination is shorter than the source. /// </exception> /// </summary> public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span); /// <summary> /// Copies the contents of the memory into the destination. If the source /// and destination overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. /// /// <returns>If the destination is shorter than the source, this method /// return false and no data is written to the destination.</returns> /// </summary> /// <param name="destination">The span to copy items into.</param> public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span); /// <summary> /// Creates a handle for the memory. /// The GC will not move the memory until the returned <see cref="MemoryHandle"/> /// is disposed, enabling taking and using the memory's address. /// <exception cref="System.ArgumentException"> /// An instance with nonprimitive (non-blittable) members cannot be pinned. /// </exception> /// </summary> public unsafe MemoryHandle Pin() { // Just like the Span property getter, we have special support for a mutable Memory<char> // that wraps an immutable String instance. This might happen if a caller creates an // immutable ROM<char> wrapping a String, then uses Unsafe.As to create a mutable M<char>. // This needs to work, however, so that code that uses a single Memory<char> field to store either // a readable ReadOnlyMemory<char> or a writable Memory<char> can still be pinned and // used for interop purposes. // It's possible that the below logic could result in an AV if the struct // is torn. This is ok since the caller is expecting to use raw pointers, // and we're not required to keep this as safe as the other Span-based APIs. object tmpObject = _object; if (tmpObject != null) { if (typeof(T) == typeof(char) && tmpObject is string s) { GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned); ref char stringData = ref Unsafe.Add(ref s.GetRawStringData(), _index); return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle); } #if FEATURE_UTF8STRING else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject is Utf8String utf8String) { GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned); ref byte stringData = ref utf8String.DangerousGetMutableReference(_index); return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle); } #endif // FEATURE_UTF8STRING else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject)) { // 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible Debug.Assert(tmpObject is T[]); // Array is already pre-pinned if (_index < 0) { void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index & ReadOnlyMemory<T>.RemoveFlagsBitMask); return new MemoryHandle(pointer); } else { GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index); return new MemoryHandle(pointer, handle); } } else { Debug.Assert(tmpObject is MemoryManager<T>); return Unsafe.As<MemoryManager<T>>(tmpObject).Pin(_index); } } return default; } /// <summary> /// Copies the contents from the memory into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] ToArray() => Span.ToArray(); /// <summary> /// Determines whether the specified object is equal to the current object. /// Returns true if the object is Memory or ReadOnlyMemory and if both objects point to the same array and have the same length. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T>) { return ((ReadOnlyMemory<T>)obj).Equals(this); } else if (obj is Memory<T> memory) { return Equals(memory); } else { return false; } } /// <summary> /// Returns true if the memory points to the same array and has the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public bool Equals(Memory<T> other) { return _object == other._object && _index == other._index && _length == other._length; } /// <summary> /// Serves as the default hash function. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { // We use RuntimeHelpers.GetHashCode instead of Object.GetHashCode because the hash // code is based on object identity and referential equality, not deep equality (as common with string). return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0; } } }
namespace Factotum { partial class InspectionPeriodEdit { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InspectionPeriodEdit)); this.btnOK = new System.Windows.Forms.Button(); this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components); this.btnCancel = new System.Windows.Forms.Button(); this.dtpCalIn = new System.Windows.Forms.DateTimePicker(); this.label4 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.dtpCalOut = new System.Windows.Forms.DateTimePicker(); this.label2 = new System.Windows.Forms.Label(); this.dtpCalCheck1 = new System.Windows.Forms.DateTimePicker(); this.label3 = new System.Windows.Forms.Label(); this.dtpCalCheck2 = new System.Windows.Forms.DateTimePicker(); this.ckCheck1 = new System.Windows.Forms.CheckBox(); this.ckCheck2 = new System.Windows.Forms.CheckBox(); this.lblSiteName = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit(); this.SuspendLayout(); // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOK.Location = new System.Drawing.Point(228, 168); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(64, 22); this.btnOK.TabIndex = 8; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // errorProvider1 // this.errorProvider1.ContainerControl = this; // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.Location = new System.Drawing.Point(298, 168); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(64, 22); this.btnCancel.TabIndex = 9; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // dtpCalIn // this.dtpCalIn.CustomFormat = "MM-dd-yyyy H:mm"; this.dtpCalIn.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.dtpCalIn.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.dtpCalIn.Location = new System.Drawing.Point(118, 44); this.dtpCalIn.Name = "dtpCalIn"; this.dtpCalIn.Size = new System.Drawing.Size(134, 22); this.dtpCalIn.TabIndex = 7; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(44, 48); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(68, 13); this.label4.TabIndex = 6; this.label4.Text = "Calibration In"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(36, 130); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(76, 13); this.label1.TabIndex = 10; this.label1.Text = "Calibration Out"; // // dtpCalOut // this.dtpCalOut.CustomFormat = "MM-dd-yyyy H:mm"; this.dtpCalOut.DropDownAlign = System.Windows.Forms.LeftRightAlignment.Right; this.dtpCalOut.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.dtpCalOut.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.dtpCalOut.Location = new System.Drawing.Point(118, 126); this.dtpCalOut.Name = "dtpCalOut"; this.dtpCalOut.Size = new System.Drawing.Size(134, 22); this.dtpCalOut.TabIndex = 11; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(13, 76); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(99, 13); this.label2.TabIndex = 12; this.label2.Text = "Calibration Check 1"; // // dtpCalCheck1 // this.dtpCalCheck1.CustomFormat = "MM-dd-yyyy H:mm"; this.dtpCalCheck1.DropDownAlign = System.Windows.Forms.LeftRightAlignment.Right; this.dtpCalCheck1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.dtpCalCheck1.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.dtpCalCheck1.Location = new System.Drawing.Point(118, 72); this.dtpCalCheck1.Name = "dtpCalCheck1"; this.dtpCalCheck1.Size = new System.Drawing.Size(134, 22); this.dtpCalCheck1.TabIndex = 13; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(13, 102); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(99, 13); this.label3.TabIndex = 14; this.label3.Text = "Calibration Check 2"; // // dtpCalCheck2 // this.dtpCalCheck2.CustomFormat = "MM-dd-yyyy H:mm"; this.dtpCalCheck2.DropDownAlign = System.Windows.Forms.LeftRightAlignment.Right; this.dtpCalCheck2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.dtpCalCheck2.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.dtpCalCheck2.Location = new System.Drawing.Point(118, 98); this.dtpCalCheck2.Name = "dtpCalCheck2"; this.dtpCalCheck2.Size = new System.Drawing.Size(134, 22); this.dtpCalCheck2.TabIndex = 15; // // ckCheck1 // this.ckCheck1.AutoSize = true; this.ckCheck1.Location = new System.Drawing.Point(307, 77); this.ckCheck1.Name = "ckCheck1"; this.ckCheck1.Size = new System.Drawing.Size(57, 17); this.ckCheck1.TabIndex = 16; this.ckCheck1.Text = "Check"; this.ckCheck1.UseVisualStyleBackColor = true; this.ckCheck1.CheckedChanged += new System.EventHandler(this.ckCheck1_CheckedChanged); // // ckCheck2 // this.ckCheck2.AutoSize = true; this.ckCheck2.Location = new System.Drawing.Point(307, 103); this.ckCheck2.Name = "ckCheck2"; this.ckCheck2.Size = new System.Drawing.Size(57, 17); this.ckCheck2.TabIndex = 17; this.ckCheck2.Text = "Check"; this.ckCheck2.UseVisualStyleBackColor = true; this.ckCheck2.CheckedChanged += new System.EventHandler(this.ckCheck2_CheckedChanged); // // lblSiteName // this.lblSiteName.AutoSize = true; this.lblSiteName.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblSiteName.ForeColor = System.Drawing.Color.DimGray; this.lblSiteName.Location = new System.Drawing.Point(115, 9); this.lblSiteName.Name = "lblSiteName"; this.lblSiteName.Size = new System.Drawing.Size(80, 16); this.lblSiteName.TabIndex = 18; this.lblSiteName.Text = "Component:"; // // InspectionPeriodEdit // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(374, 202); this.Controls.Add(this.lblSiteName); this.Controls.Add(this.ckCheck2); this.Controls.Add(this.ckCheck1); this.Controls.Add(this.label3); this.Controls.Add(this.dtpCalCheck2); this.Controls.Add(this.label2); this.Controls.Add(this.dtpCalCheck1); this.Controls.Add(this.label1); this.Controls.Add(this.dtpCalOut); this.Controls.Add(this.label4); this.Controls.Add(this.dtpCalIn); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(382, 236); this.Name = "InspectionPeriodEdit"; this.Text = "Edit Inspection Period"; ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnOK; private System.Windows.Forms.ErrorProvider errorProvider1; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Label label4; private System.Windows.Forms.DateTimePicker dtpCalIn; private System.Windows.Forms.Label label3; private System.Windows.Forms.DateTimePicker dtpCalCheck2; private System.Windows.Forms.Label label2; private System.Windows.Forms.DateTimePicker dtpCalCheck1; private System.Windows.Forms.Label label1; private System.Windows.Forms.DateTimePicker dtpCalOut; private System.Windows.Forms.CheckBox ckCheck1; private System.Windows.Forms.CheckBox ckCheck2; private System.Windows.Forms.Label lblSiteName; } }
// ClientLineItemEditorViewModel.cs // using Client.QuoteLineItemEditor.Model; using jQueryApi; using KnockoutApi; using SparkleXrm; using SparkleXrm.GridEditor; using System; using System.Collections.Generic; using System.Html; using Xrm; using Xrm.Sdk; using Slick; namespace Client.QuoteLineItemEditor.ViewModels { public class QuoteLineItemEditorViewModel : ViewModelBase { #region Fields public EntityDataViewModel Lines; public Observable<ObservableQuoteDetail> SelectedQuoteDetail = Knockout.Observable<ObservableQuoteDetail>(); private string _transactionCurrencyId; #endregion #region Constructors public QuoteLineItemEditorViewModel() { Lines = new EntityDataViewModel(10, typeof(QuoteDetail), false); Lines.OnSelectedRowsChanged += OnSelectedRowsChanged; Lines.FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' returntotalrecordcount='true' no-lock='true' distinct='false' count='{0}' paging-cookie='{1}' page='{2}'> <entity name='quotedetail'> <attribute name='productid' /> <attribute name='productdescription' /> <attribute name='priceperunit' /> <attribute name='quantity' /> <attribute name='extendedamount' /> <attribute name='quotedetailid' /> <attribute name='isproductoverridden' /> <attribute name='ispriceoverridden' /> <attribute name='manualdiscountamount' /> <attribute name='lineitemnumber' /> <attribute name='description' /> <attribute name='transactioncurrencyid' /> <attribute name='baseamount' /> <attribute name='requestdeliveryby' /> <attribute name='salesrepid' /> <attribute name='uomid' /> {3} <link-entity name='quote' from='quoteid' to='quoteid' alias='ac'> <filter type='and'> <condition attribute='quoteid' operator='eq' uiname='tes' uitype='quote' value='" + GetQuoteId() + @"' /> </filter> </link-entity> </entity> </fetch>"; Lines.SortBy(new SortCol("lineitemnumber", true)); Lines.NewItemFactory = NewLineFactory; QuoteDetailValidation.Register(Lines.ValidationBinder); SelectedQuoteDetail.SetValue(new ObservableQuoteDetail()); } #endregion #region Methods public bool IsEditForm() { if (ParentPage.Ui != null) return (ParentPage.Ui.GetFormType() == FormTypes.Update); else return true; // Debug } public string GetQuoteId() { string quoteId = "DB040ECD-5ED4-E211-9BE0-000C299FFE7D"; // Debug if (ParentPage.Ui != null) { string guid = ParentPage.Data.Entity.GetId(); if (guid != null) quoteId = guid.Replace("{", "").Replace("}", ""); this._transactionCurrencyId = ((Lookup[])ParentPage.GetAttribute("transactioncurrencyid").GetValue())[0].Id; } return quoteId; } public Entity NewLineFactory(object item) { QuoteDetail newLine = new QuoteDetail(); jQuery.Extend(newLine, item); newLine.LineItemNumber = Lines.GetPagingInfo().TotalRows + 1; newLine.QuoteId = new EntityReference(new Guid(GetQuoteId()), "quote", null); if (_transactionCurrencyId != null) newLine.TransactionCurrencyId = new EntityReference(new Guid(_transactionCurrencyId), "transactioncurrency", ""); return newLine; } private void OnSelectedRowsChanged() { SelectedRange[] selectedContacts = Lines.GetSelectedRows(); if (selectedContacts.Length > 0) { ObservableQuoteDetail observableQuoteDetail = SelectedQuoteDetail.GetValue(); if (observableQuoteDetail.InnerQuoteDetail != null) observableQuoteDetail.InnerQuoteDetail.PropertyChanged -= quote_PropertyChanged; QuoteDetail selectedQuoteDetail = (QuoteDetail)Lines.GetItem(selectedContacts[0].FromRow.Value); if (selectedQuoteDetail != null) selectedQuoteDetail.PropertyChanged += quote_PropertyChanged; SelectedQuoteDetail.GetValue().SetValue(selectedQuoteDetail); } else SelectedQuoteDetail.GetValue().SetValue(null); } void quote_PropertyChanged(object sender, Xrm.ComponentModel.PropertyChangedEventArgs e) { Window.SetTimeout(delegate() { Lines.Refresh(); }, 0); } public void ProductSearchCommand(string term, Action<EntityCollection> callback) { // Get products from the search term string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='product'> <attribute name='productid' /> <attribute name='name' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='name' operator='like' value='%{0}%' /> </filter> </entity> </fetch>"; fetchXml = string.Format(fetchXml, XmlHelper.Encode(term)); OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result) { EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity)); callback(fetchResult); }); } public void UoMSearchCommand(string term, Action<EntityCollection> callback) { string fetchXml = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='uom'> <attribute name='uomid' /> <attribute name='name' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='name' operator='like' value='%{0}%' /> </filter> </entity> </fetch>"; fetchXml = string.Format(fetchXml, XmlHelper.Encode(term)); OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result) { EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity)); callback(fetchResult); }); } public void SalesRepSearchCommand(string term, Action<EntityCollection> callback) { string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='systemuser'> <attribute name='fullname' /> <attribute name='businessunitid' /> <attribute name='title' /> <attribute name='address1_telephone1' /> <attribute name='systemuserid' /> <order attribute='fullname' descending='false' /> <filter type='and'> <condition attribute='fullname' operator='like' value='%{0}%' /> </filter> </entity> </fetch>"; fetchXml = string.Format(fetchXml, XmlHelper.Encode(term)); OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result) { EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity)); callback(fetchResult); }); } private void SaveNextRecord(List<QuoteDetail> dirtyCollection, List<string> errorMessages, Action callBack) { QuoteDetail itemToSave = dirtyCollection[0]; if (itemToSave.EntityState == EntityStates.Deleted) { OrganizationServiceProxy.BeginDelete("quotedetail",itemToSave.QuoteDetailId, delegate(object r) { try { OrganizationServiceProxy.EndDelete(r); itemToSave.EntityState = EntityStates.Unchanged; } catch (Exception ex) { // Something when wrong with delete errorMessages.Add(ex.Message); } FinishSaveRecord(dirtyCollection, errorMessages, callBack, itemToSave); }); } else if (itemToSave.QuoteDetailId == null) { OrganizationServiceProxy.BeginCreate(itemToSave, delegate(object r) { try { Guid newID = OrganizationServiceProxy.EndCreate(r); itemToSave.QuoteDetailId = newID; itemToSave.EntityState = EntityStates.Unchanged; } catch (Exception ex) { // Something when wrong with create errorMessages.Add(ex.Message); } FinishSaveRecord(dirtyCollection, errorMessages, callBack, itemToSave); }); } else { OrganizationServiceProxy.BeginUpdate(itemToSave, delegate(object r) { try { OrganizationServiceProxy.EndUpdate(r); itemToSave.EntityState = EntityStates.Unchanged; } catch (Exception ex) { // Something when wrong with update errorMessages.Add(ex.Message); } FinishSaveRecord(dirtyCollection, errorMessages, callBack, itemToSave); }); } } private void FinishSaveRecord(List<QuoteDetail> dirtyCollection, List<string> errorMessages, Action callBack, QuoteDetail itemToSave) { dirtyCollection.Remove(itemToSave); if (dirtyCollection.Count == 0) callBack(); else SaveNextRecord(dirtyCollection, errorMessages, callBack); } #endregion #region Commands private Action _saveCommand; public Action SaveCommand() { if (_saveCommand == null) { _saveCommand = delegate() { if (!CommitEdit()) return; List<QuoteDetail> dirtyCollection = new List<QuoteDetail>(); // Add new/changed items foreach (Entity item in this.Lines.Data) { if (item != null && item.EntityState != EntityStates.Unchanged) dirtyCollection.Add((QuoteDetail)item); } // Add deleted items if (this.Lines.DeleteData != null) { foreach (Entity item in this.Lines.DeleteData) { if (item.EntityState == EntityStates.Deleted) dirtyCollection.Add((QuoteDetail)item); } } int itemCount = dirtyCollection.Count; if (itemCount == 0) return; bool confirmed = Script.Confirm(String.Format("Are you sure that you want to save the {0} quote lines in the Grid?", itemCount)); if (!confirmed) return; IsBusy.SetValue(true); List<string> errorMessages = new List<string>(); SaveNextRecord(dirtyCollection, errorMessages, delegate() { if (errorMessages.Count > 0) { Script.Alert("One or more records failed to save.\nPlease contact your System Administrator.\n\n" + errorMessages.Join(",")); } if (Lines.DeleteData != null) Lines.DeleteData.Clear(); Lines.Refresh(); IsBusy.SetValue(false); }); }; } return _saveCommand; } private Action _deleteCommand; public Action DeleteCommand() { if (_deleteCommand == null) { _deleteCommand = delegate() { List<int> selectedRows = DataViewBase.RangesToRows(Lines.GetSelectedRows()); if (selectedRows.Count == 0) return; bool confirmed = Script.Confirm(String.Format("Are you sure that you want to delete the {0} quote lines in the Grid?", selectedRows.Count)); if (!confirmed) return; List<Entity> itemsToRemove = new List<Entity>(); foreach (int row in selectedRows) { itemsToRemove.Add((Entity)Lines.GetItem(row)); } foreach (Entity item in itemsToRemove) { item.EntityState = EntityStates.Deleted; Lines.RemoveItem(item); } Lines.Refresh(); }; } return _deleteCommand; } private Action _moveUpCommand; public Action MoveUpCommand() { if (_moveUpCommand == null) { _moveUpCommand = delegate() { // reindex all the items by moving the selected index up SelectedRange[] range = Lines.GetSelectedRows(); int fromRow = (int)range[0].FromRow; if (fromRow == 0) return; QuoteDetail line = (QuoteDetail)Lines.GetItem(fromRow); QuoteDetail lineBefore = (QuoteDetail)Lines.GetItem(fromRow - 1); // swap the indexes from the item before int? lineItemNumber = line.LineItemNumber; line.LineItemNumber = lineBefore.LineItemNumber; lineBefore.LineItemNumber = lineItemNumber; line.RaisePropertyChanged("LineItemNumber"); lineBefore.RaisePropertyChanged("LineItemNumber"); range[0].FromRow--; Lines.RaiseOnSelectedRowsChanged(range); Lines.SortBy(new SortCol("lineitemnumber", true)); Lines.Refresh(); }; } return _moveUpCommand; } private Action _moveDownCommand; public Action MoveDownCommand() { if (_moveDownCommand == null) { _moveDownCommand = delegate() { // reindex all the items by moving the selected index up SelectedRange[] range = Lines.GetSelectedRows(); int fromRow = (int)range[0].FromRow; if (fromRow == Lines.GetLength() - 1) return; QuoteDetail line = (QuoteDetail)Lines.GetItem(fromRow); QuoteDetail lineAfter = (QuoteDetail)Lines.GetItem(fromRow + 1); // swap the indexes from the item before int? lineItemNumber = line.LineItemNumber; line.RaisePropertyChanged("LineItemNumber"); lineAfter.RaisePropertyChanged("LineItemNumber"); line.LineItemNumber = lineAfter.LineItemNumber; lineAfter.LineItemNumber = lineItemNumber; range[0].FromRow++; Lines.RaiseOnSelectedRowsChanged(range); Lines.SortBy(new SortCol("lineitemnumber", true)); Lines.Refresh(); }; } return _moveDownCommand; } #endregion } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Reactive.Linq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.Input; using Avalonia.Media; using Avalonia.Platform; using Avalonia.UnitTests; using Moq; using Xunit; namespace Avalonia.Controls.UnitTests { public class TextBoxTests { [Fact] public void DefaultBindingMode_Should_Be_TwoWay() { Assert.Equal( BindingMode.TwoWay, TextBox.TextProperty.GetMetadata(typeof(TextBox)).DefaultBindingMode); } [Fact] public void CaretIndex_Can_Moved_To_Position_After_The_End_Of_Text_With_Arrow_Key() { using (UnitTestApplication.Start(Services)) { var target = new TextBox { Template = CreateTemplate(), Text = "1234" }; target.CaretIndex = 3; RaiseKeyEvent(target, Key.Right, 0); Assert.Equal(4, target.CaretIndex); } } [Fact] public void Press_Ctrl_A_Select_All_Text() { using (UnitTestApplication.Start(Services)) { var target = new TextBox { Template = CreateTemplate(), Text = "1234" }; RaiseKeyEvent(target, Key.A, InputModifiers.Control); Assert.Equal(0, target.SelectionStart); Assert.Equal(4, target.SelectionEnd); } } [Fact] public void Press_Ctrl_A_Select_All_Null_Text() { using (UnitTestApplication.Start(Services)) { var target = new TextBox { Template = CreateTemplate() }; RaiseKeyEvent(target, Key.A, InputModifiers.Control); Assert.Equal(0, target.SelectionStart); Assert.Equal(0, target.SelectionEnd); } } [Fact] public void Press_Ctrl_Z_Will_Not_Modify_Text() { using (UnitTestApplication.Start(Services)) { var target = new TextBox { Template = CreateTemplate(), Text = "1234" }; RaiseKeyEvent(target, Key.Z, InputModifiers.Control); Assert.Equal("1234", target.Text); } } [Fact] public void Typing_Beginning_With_0_Should_Not_Modify_Text_When_Bound_To_Int() { using (UnitTestApplication.Start(Services)) { var source = new Class1(); var target = new TextBox { DataContext = source, Template = CreateTemplate(), }; target.ApplyTemplate(); target.Bind(TextBox.TextProperty, new Binding(nameof(Class1.Foo), BindingMode.TwoWay)); Assert.Equal("0", target.Text); target.CaretIndex = 1; target.RaiseEvent(new TextInputEventArgs { RoutedEvent = InputElement.TextInputEvent, Text = "2", }); Assert.Equal("02", target.Text); } } [Fact] public void Control_Backspace_Should_Remove_The_Word_Before_The_Caret_If_There_Is_No_Selection() { using (UnitTestApplication.Start(Services)) { TextBox textBox = new TextBox { Text = "First Second Third Fourth", CaretIndex = 5 }; // (First| Second Third Fourth) RaiseKeyEvent(textBox, Key.Back, InputModifiers.Control); Assert.Equal(" Second Third Fourth", textBox.Text); // ( Second |Third Fourth) textBox.CaretIndex = 8; RaiseKeyEvent(textBox, Key.Back, InputModifiers.Control); Assert.Equal(" Third Fourth", textBox.Text); // ( Thi|rd Fourth) textBox.CaretIndex = 4; RaiseKeyEvent(textBox, Key.Back, InputModifiers.Control); Assert.Equal(" rd Fourth", textBox.Text); // ( rd F[ou]rth) textBox.SelectionStart = 5; textBox.SelectionEnd = 7; RaiseKeyEvent(textBox, Key.Back, InputModifiers.Control); Assert.Equal(" rd Frth", textBox.Text); // ( |rd Frth) textBox.CaretIndex = 1; RaiseKeyEvent(textBox, Key.Back, InputModifiers.Control); Assert.Equal("rd Frth", textBox.Text); } } [Fact] public void Control_Delete_Should_Remove_The_Word_After_The_Caret_If_There_Is_No_Selection() { using (UnitTestApplication.Start(Services)) { TextBox textBox = new TextBox { Text = "First Second Third Fourth", CaretIndex = 19 }; // (First Second Third |Fourth) RaiseKeyEvent(textBox, Key.Delete, InputModifiers.Control); Assert.Equal("First Second Third ", textBox.Text); // (First Second |Third ) textBox.CaretIndex = 13; RaiseKeyEvent(textBox, Key.Delete, InputModifiers.Control); Assert.Equal("First Second ", textBox.Text); // (First Sec|ond ) textBox.CaretIndex = 9; RaiseKeyEvent(textBox, Key.Delete, InputModifiers.Control); Assert.Equal("First Sec", textBox.Text); // (Fi[rs]t Sec ) textBox.SelectionStart = 2; textBox.SelectionEnd = 4; RaiseKeyEvent(textBox, Key.Delete, InputModifiers.Control); Assert.Equal("Fit Sec", textBox.Text); // (Fit Sec| ) textBox.Text += " "; textBox.CaretIndex = 7; RaiseKeyEvent(textBox, Key.Delete, InputModifiers.Control); Assert.Equal("Fit Sec", textBox.Text); } } [Fact] public void Setting_SelectionStart_To_SelectionEnd_Sets_CaretPosition_To_SelectionStart() { using (UnitTestApplication.Start(Services)) { var textBox = new TextBox { Text = "0123456789" }; textBox.SelectionStart = 2; textBox.SelectionEnd = 2; Assert.Equal(2, textBox.CaretIndex); } } [Fact] public void Setting_Text_Updates_CaretPosition() { using (UnitTestApplication.Start(Services)) { var target = new TextBox { Text = "Initial Text", CaretIndex = 11 }; var invoked = false; target.GetObservable(TextBox.TextProperty).Skip(1).Subscribe(_ => { // Caret index should be set before Text changed notification, as we don't want // to notify with an invalid CaretIndex. Assert.Equal(7, target.CaretIndex); invoked = true; }); target.Text = "Changed"; Assert.True(invoked); } } [Fact] public void Press_Enter_Does_Not_Accept_Return() { using (UnitTestApplication.Start(Services)) { var target = new TextBox { Template = CreateTemplate(), AcceptsReturn = false, Text = "1234" }; RaiseKeyEvent(target, Key.Enter, 0); Assert.Equal("1234", target.Text); } } [Fact] public void Press_Enter_Add_Default_Newline() { using (UnitTestApplication.Start(Services)) { var target = new TextBox { Template = CreateTemplate(), AcceptsReturn = true }; RaiseKeyEvent(target, Key.Enter, 0); Assert.Equal(Environment.NewLine, target.Text); } } [Fact] public void Press_Enter_Add_Custom_Newline() { using (UnitTestApplication.Start(Services)) { var target = new TextBox { Template = CreateTemplate(), AcceptsReturn = true, NewLine = "Test" }; RaiseKeyEvent(target, Key.Enter, 0); Assert.Equal("Test", target.Text); } } [Theory] [InlineData(new object[] { false, TextWrapping.NoWrap, ScrollBarVisibility.Hidden })] [InlineData(new object[] { false, TextWrapping.Wrap, ScrollBarVisibility.Hidden })] [InlineData(new object[] { true, TextWrapping.NoWrap, ScrollBarVisibility.Auto })] [InlineData(new object[] { true, TextWrapping.Wrap, ScrollBarVisibility.Disabled })] public void Has_Correct_Horizontal_ScrollBar_Visibility( bool acceptsReturn, TextWrapping wrapping, ScrollBarVisibility expected) { using (UnitTestApplication.Start(Services)) { var target = new TextBox { AcceptsReturn = acceptsReturn, TextWrapping = wrapping, }; Assert.Equal(expected, ScrollViewer.GetHorizontalScrollBarVisibility(target)); } } [Fact] public void SelectionEnd_Doesnt_Cause_Exception() { using (UnitTestApplication.Start(Services)) { var target = new TextBox { Template = CreateTemplate(), Text = "0123456789" }; target.SelectionStart = 0; target.SelectionEnd = 9; target.Text = "123"; RaiseTextEvent(target, "456"); Assert.True(true); } } [Fact] public void SelectionStart_Doesnt_Cause_Exception() { using (UnitTestApplication.Start(Services)) { var target = new TextBox { Template = CreateTemplate(), Text = "0123456789" }; target.SelectionStart = 8; target.SelectionEnd = 9; target.Text = "123"; RaiseTextEvent(target, "456"); Assert.True(true); } } [Fact] public void SelectionStartEnd_Are_Valid_AterTextChange() { using (UnitTestApplication.Start(Services)) { var target = new TextBox { Template = CreateTemplate(), Text = "0123456789" }; target.SelectionStart = 8; target.SelectionEnd = 9; target.Text = "123"; Assert.True(target.SelectionStart <= "123".Length); Assert.True(target.SelectionEnd <= "123".Length); } } private static TestServices Services => TestServices.MockThreadingInterface.With( standardCursorFactory: Mock.Of<IStandardCursorFactory>()); private IControlTemplate CreateTemplate() { return new FuncControlTemplate<TextBox>(control => new TextPresenter { Name = "PART_TextPresenter", [!!TextPresenter.TextProperty] = new Binding { Path = "Text", Mode = BindingMode.TwoWay, Priority = BindingPriority.TemplatedParent, RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent), }, }); } private void RaiseKeyEvent(TextBox textBox, Key key, InputModifiers inputModifiers) { textBox.RaiseEvent(new KeyEventArgs { RoutedEvent = InputElement.KeyDownEvent, Modifiers = inputModifiers, Key = key }); } private void RaiseTextEvent(TextBox textBox, string text) { textBox.RaiseEvent(new TextInputEventArgs { RoutedEvent = InputElement.TextInputEvent, Text = text }); } private class Class1 : NotifyingBase { private int _foo; public int Foo { get { return _foo; } set { _foo = value; RaisePropertyChanged(); } } } } }
using System; using System.IO; using System.Collections.Generic; using Antlr.Runtime; using Antlr.Runtime.Tree; using Antlr.StringTemplate; using Antlr.StringTemplate.Language; namespace Thor.DataForge { public enum eCompilerMessageSeverity { Error, Warning } public class CompileException : Exception { public CompileException(string message) : base(message) { } } public class Compiler { private ProjectOptions m_Options; private Package m_RootPackage; private Package m_CurrentPackage; private Stack<string> m_ParsedFilesStack; private List<string> m_ParsedFiles; private static Compiler m_Instance = new Compiler(); private bool m_StageFailed; private StringTemplateGroup m_StringTemplateGroup; private Dictionary<string, List<Tuple<string, bool>>> m_ImportMap = new Dictionary<string, List<Tuple<string, bool>>>(); private Dictionary<string, GeneratedFileDesc> m_GeneratedFiles = new Dictionary<string, GeneratedFileDesc>(); private Compiler() { m_Options = new ProjectOptions(); m_RootPackage = new Package(); m_CurrentPackage = m_RootPackage; m_ParsedFilesStack = new Stack<string>(); m_ParsedFiles = new List<string>(); m_StageFailed = false; } public List<Tuple<string, bool>> GetImportedFiles(string target) { List<Tuple<string, bool>> result = null; if (m_ImportMap.TryGetValue(target, out result)) return result; else return null; } public GeneratedFileDesc GetGeneratedFileDesc(string name) { GeneratedFileDesc desc = null; if (!m_GeneratedFiles.TryGetValue(name, out desc)) { desc = new GeneratedFileDesc(); m_GeneratedFiles.Add(name, desc); } return desc; } public bool IsFileInImports(string target, string file) { if (target == file) return true; List<Tuple<string, bool>> flist = null; if (m_ImportMap.TryGetValue(target, out flist)) { if (flist.Find(it => it.Item1 == GetFilePath(file)) != null) return true; } return false; } public void AddImportedFile(string target, string path, bool inFileScope = true) { path = Path.GetFullPath(path); AddImportedFileImpl(target, path, inFileScope); List<Tuple<string, bool>> files= null; if (m_ImportMap.TryGetValue(path, out files)) { foreach (var f in files) { AddImportedFile(target, f.Item1, false); } } } private void AddImportedFileImpl(string target, string path, bool inFileScope) { List<Tuple<string, bool>> files = null; if (m_ImportMap.TryGetValue(target, out files)) { if (files.Find(it => it.Item1 == path) == null) files.Add(new Tuple<string, bool>(path, inFileScope)); } else { files = new List<Tuple<string, bool>>(); files.Add(new Tuple<string, bool>(path, inFileScope)); m_ImportMap.Add(target, files); } } public static Compiler Instance { get { return m_Instance; } } public void LoadTemplateGroup(string path) { string template = File.ReadAllText(path); m_StringTemplateGroup = new StringTemplateGroup(new StringReader(template)); } //Compiler errors and checkers public void WriteErrorFileLine(eCompilerMessageSeverity sev, IToken token) { if (sev == eCompilerMessageSeverity.Error) { Console.BackgroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.White; } else { Console.BackgroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.White; } m_StageFailed = true; if (token != null) Utilities.Log.WriteLine(sev + " -> file: " + CurrentFile + " line: " + token.Line); Console.ResetColor(); } public void WriteErrorFileLine(eCompilerMessageSeverity sev, Symbol sym) { if (sev == eCompilerMessageSeverity.Error) { Console.BackgroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.White; } else { Console.BackgroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.White; } m_StageFailed = true; if (sym != null) Utilities.Log.WriteLine(sev + " -> file: " + sym.FileName + " line: " + sym.Line); Console.ResetColor(); } public void InvalidConstantType(DataField val) { WriteErrorFileLine(eCompilerMessageSeverity.Error, val.Token); Utilities.Log.WriteLine("\tConstant can only be of a built in type. Invalid type " + val.Name + "."); } public void InvalidEnumValuesOrder(IToken token) { WriteErrorFileLine(eCompilerMessageSeverity.Error, token); Utilities.Log.WriteLine("\tEnumerations must declare their values in ascending order, token: " + token.Text + "."); } public void InvalidUnaryOp(eUnaryOp op, IToken token) { WriteErrorFileLine(eCompilerMessageSeverity.Error, token); Utilities.Log.WriteLine("\tUnary operation " + op + " cannot be applied to this type."); } public void InvalidProfileExpression(IToken token) { WriteErrorFileLine(eCompilerMessageSeverity.Error, token); Utilities.Log.WriteLine("\tProfile option expressions can only use symbolic values as its operands (something like SYM)."); } public void CheckProfileExpression(Expression expr, IToken token) { if(expr==null) { InvalidProfileExpression(token); } } public void DuplicateEnumField(EnumDeclaration e, string fieldName) { WriteErrorFileLine(eCompilerMessageSeverity.Error, e.Token); Utilities.Log.WriteLine("\tEnum " + e.Name + " contains duplicate fields named " + fieldName + "."); } public void DuplicateDataField<T>(CompoundTypeDeclaration<T> decl, DataField field) { WriteErrorFileLine(eCompilerMessageSeverity.Error, field.Token); Utilities.Log.WriteLine("\tData type " + decl.Name + " contains duplicate fields named " + field.Name + "."); } public void DuplicateConstant(DataField field) { WriteErrorFileLine(eCompilerMessageSeverity.Error, field.Token); Utilities.Log.WriteLine("\tConstant " + field.Name + " is already declared."); } public void DuplicateEnumeration(EnumDeclaration decl) { WriteErrorFileLine(eCompilerMessageSeverity.Error, decl.Token); Utilities.Log.WriteLine("\tEnumeration " + decl.Name + " is already declared."); } public void DuplicateStructure(StructDeclaration decl) { WriteErrorFileLine(eCompilerMessageSeverity.Error, decl.Token); Utilities.Log.WriteLine("\tStructure " + decl.Name + " is already declared."); } public void DuplicateEntity(EntityDeclaration decl) { WriteErrorFileLine(eCompilerMessageSeverity.Error, decl.Token); Utilities.Log.WriteLine("\tEntity " + decl.Name + " is already declared."); } /// public void TypeNotFound(BaseType type) { WriteErrorFileLine(eCompilerMessageSeverity.Error, type); Utilities.Log.WriteLine("\tType " + type.FullName + " is not found in current scope."); } public void TypeNotInProfile(BaseType type) { WriteErrorFileLine(eCompilerMessageSeverity.Error, type); Utilities.Log.WriteLine("\tType " + type.FullName + " is not found in current scope, it is defined but not in the current compilation profile."); } public void EntityFieldDeclared(BaseType type, BaseType field) { WriteErrorFileLine(eCompilerMessageSeverity.Error, type); Utilities.Log.WriteLine("\tType " + type.FullName + " has an entity field of type " + field.Name + ", only references to entities are allowed."); } public void TypeNotImported(BaseType type, string file) { WriteErrorFileLine(eCompilerMessageSeverity.Error, type); Utilities.Log.WriteLine("\tType " + type.FullName + " is defined in " + type.FileName + " but not imported in " + file + "."); } public void EntityNotFound(EntityDeclaration type) { WriteErrorFileLine(eCompilerMessageSeverity.Error, type); Utilities.Log.WriteLine("\tEntity " + type.Parent.FullName + " does not exist."); } public void StructureNotFound(StructDeclaration type) { WriteErrorFileLine(eCompilerMessageSeverity.Error, type); Utilities.Log.WriteLine("\tStructure " + type.Parent.FullName + " does not exist."); } public void CheckConstantType(DataField val) { if (!val.Type.IsBuiltIn) { InvalidConstantType(val); } } public void InvalidFieldInitializer(DataField field, int numRequiredConstants) { WriteErrorFileLine(eCompilerMessageSeverity.Error, field.Type); Utilities.Log.WriteLine("\tField " + field.Name + " has invalid number of constants in it`s initializer, expecting " + numRequiredConstants + "."); } public void InitializerNotSupported(DataField field) { WriteErrorFileLine(eCompilerMessageSeverity.Error, field.Type); Utilities.Log.WriteLine("\tField " + field.Name + " cannot have initializers."); } public void EnumHasNoSuchValue(DataField field, EnumDeclaration ed, string val) { WriteErrorFileLine(eCompilerMessageSeverity.Error, field.Type); Utilities.Log.WriteLine("\tField " + field.Name + " references value " + val + " which enum " + ed.FullName + " does not have."); } public void InvalidEnumInitializer(DataField field) { WriteErrorFileLine(eCompilerMessageSeverity.Error, field.Type); Utilities.Log.WriteLine("\tField " + field.Name + " has invalid enum initializer."); } public void ConstantNotFound(SymbolConstant cnt) { WriteErrorFileLine(eCompilerMessageSeverity.Error, cnt); Utilities.Log.WriteLine("\tConstant " + cnt.Name + " is not found in current scope."); } public void FileNotFound(string fileName) { WriteErrorFileLine(eCompilerMessageSeverity.Error, (IToken)null); Utilities.Log.WriteLine("\tFile " + fileName + " does not exist."); } public void CheckSupportedMapKeyType(MapType map) { if (map.KeyType.Type > eType.BASICTYPESEND) { WriteErrorFileLine(eCompilerMessageSeverity.Error, map.Token); Utilities.Log.WriteLine("\tMap field " + map.Name + " has unsupported key value, only basic types can be map keys."); } } public Package CurrentPackage { get { return m_CurrentPackage; } set { m_CurrentPackage = value; } } public Package RootPackage { get { return m_RootPackage; } } public string CurrentFile { get { return m_ParsedFilesStack.Peek(); } } public ProjectOptions Options { get { return m_Options; } } public void ParseFile(string fileName) { try { fileName = GetFilePath(fileName); if (m_ParsedFiles.Contains(fileName)) return; m_ParsedFiles.Add(fileName); //init state Package prevPackage = m_CurrentPackage; m_ParsedFilesStack.Push(fileName); //parse file ICharStream input = new ANTLRFileStream(fileName); DataForgeLexer lex = new DataForgeLexer(input); CommonTokenStream tokens = new CommonTokenStream(lex); DataForgeParser parser = new DataForgeParser(tokens); Utilities.Log.WriteLine("Parsing file " + fileName); parser.compiler = this; parser.translation_unit(); if (parser.Failed()) m_StageFailed = true; Utilities.Log.WriteLine("Done " + fileName); //restore state m_ParsedFilesStack.Pop();//remove file name from the stack used to report filename in error messages m_CurrentPackage = prevPackage; } catch (RecognitionException re) { WriteErrorFileLine(eCompilerMessageSeverity.Error, re.Token); Utilities.Log.WriteLine("Parsing error, last token " + re.Token); Utilities.Log.PrintExceptionInfo(re); } catch (Exception e) { m_StageFailed = true; Utilities.Log.PrintExceptionInfo(e); } } private void SetupRealTypeTables() { if (m_Options.RealType == eRealType.Float) { var valueTypeMap = m_StringTemplateGroup.GetMap("valueTypeMap"); var typeMapDualBuffer = m_StringTemplateGroup.GetMap("typeMapDualBuffer"); var typeMapSimple = m_StringTemplateGroup.GetMap("typeMapSimple"); var typeMapSimpleThreadSafe = m_StringTemplateGroup.GetMap("typeMapSimpleThreadSafe"); var defaultValues = m_StringTemplateGroup.GetMap("defaultValues"); valueTypeMap["real"] = "ThF32"; typeMapDualBuffer["real"] = "ThF32Field"; typeMapSimple["real"] = "ThF32SimpleField"; typeMapSimpleThreadSafe["real"] = "ThF32SimpleFieldThreadSafe"; defaultValues["real"] = "0.0f"; valueTypeMap["vec2"] = "ThVec2"; typeMapDualBuffer["vec2"] = "ThVec2Field"; typeMapSimple["vec2"] = "ThVec2SimpleField"; typeMapSimpleThreadSafe["vec2"] = "ThVec2SimpleFieldThreadSafe"; valueTypeMap["vec3"] = "ThVec3"; typeMapDualBuffer["vec3"] = "ThVec3Field"; typeMapSimple["vec3"] = "ThVec3SimpleField"; typeMapSimpleThreadSafe["vec3"] = "ThVec3SimpleFieldThreadSafe"; valueTypeMap["vec4"] = "ThVec4"; typeMapDualBuffer["vec4"] = "ThVec4Field"; typeMapSimple["vec4"] = "ThVec4SimpleField"; typeMapSimpleThreadSafe["vec4"] = "ThVec4SimpleFieldThreadSafe"; valueTypeMap["mat2x2"] = "ThMat2x2"; typeMapDualBuffer["mat2x2"] = "ThMat2x2Field"; typeMapSimple["mat2x2"] = "ThMat2x2SimpleField"; typeMapSimpleThreadSafe["mat2x2"] = "ThMat2x2SimpleFieldThreadSafe"; valueTypeMap["mat3x3"] = "ThMat3x3"; typeMapDualBuffer["mat3x3"] = "ThMat3x3Field"; typeMapSimple["mat3x3"] = "ThMat3x3SimpleField"; typeMapSimpleThreadSafe["mat3x3"] = "ThMat3x3SimpleFieldThreadSafe"; valueTypeMap["mat4x4"] = "ThMat4x4"; typeMapDualBuffer["mat4x4"] = "ThMat4x4Field"; typeMapSimple["mat4x4"] = "ThMat4x4SimpleField"; typeMapSimpleThreadSafe["mat4x4"] = "ThMat4x4SimpleFieldThreadSafe"; valueTypeMap["quat"] = "ThQuat"; typeMapDualBuffer["quat"] = "ThQuatField"; typeMapSimple["quat"] = "ThQuatSimpleField"; typeMapSimpleThreadSafe["quat"] = "ThQuatSimpleFieldThreadSafe"; } else if (m_Options.RealType == eRealType.Double) { var valueTypeMap = m_StringTemplateGroup.GetMap("valueTypeMap"); var typeMapDualBuffer = m_StringTemplateGroup.GetMap("typeMapDualBuffer"); var typeMapSimple = m_StringTemplateGroup.GetMap("typeMapSimple"); var typeMapSimpleThreadSafe = m_StringTemplateGroup.GetMap("typeMapSimpleThreadSafe"); var defaultValues = m_StringTemplateGroup.GetMap("defaultValues"); valueTypeMap["real"] = "ThF64"; typeMapDualBuffer["real"] = "ThF64Field"; typeMapSimple["real"] = "ThF64SimpleField"; typeMapSimpleThreadSafe["real"] = "ThF64SimpleFieldThreadSafe"; defaultValues["real"] = "0.0"; valueTypeMap["vec2"] = "ThVec2d"; typeMapDualBuffer["vec2"] = "ThVec2dField"; typeMapSimple["vec2"] = "ThVec2dSimpleField"; typeMapSimpleThreadSafe["vec2"] = "ThVec2dSimpleFieldThreadSafe"; valueTypeMap["vec3"] = "ThVec3d"; typeMapDualBuffer["vec3"] = "ThVec3dField"; typeMapSimple["vec3"] = "ThVec3dSimpleField"; typeMapSimpleThreadSafe["vec3"] = "ThVec3dSimpleFieldThreadSafe"; valueTypeMap["vec4"] = "ThVec4d"; typeMapDualBuffer["vec4"] = "ThVec4dField"; typeMapSimple["vec4"] = "ThVec4dSimpleField"; typeMapSimpleThreadSafe["vec4"] = "ThVec4dSimpleFieldThreadSafe"; valueTypeMap["mat2x2"] = "ThMat2x2d"; typeMapDualBuffer["mat2x2"] = "ThMat2x2dField"; typeMapSimple["mat2x2"] = "ThMat2x2dSimpleField"; typeMapSimpleThreadSafe["mat2x2"] = "ThMat2x2dSimpleFieldThreadSafe"; valueTypeMap["mat3x3"] = "ThMat3x3d"; typeMapDualBuffer["mat3x3"] = "ThMat3x3dField"; typeMapSimple["mat3x3"] = "ThMat3x3dSimpleField"; typeMapSimpleThreadSafe["mat3x3"] = "ThMat3x3dSimpleFieldThreadSafe"; valueTypeMap["mat4x4"] = "ThMat4x4d"; typeMapDualBuffer["mat4x4"] = "ThMat4x4dField"; typeMapSimple["mat4x4"] = "ThMat4x4dSimpleField"; typeMapSimpleThreadSafe["mat4x4"] = "ThMat4x4dSimpleFieldThreadSafe"; valueTypeMap["quat"] = "ThQuatd"; typeMapDualBuffer["quat"] = "ThQuatdField"; typeMapSimple["quat"] = "ThQuatdSimpleField"; typeMapSimpleThreadSafe["quat"] = "ThQuatdSimpleFieldThreadSafe"; } } public void BuildProject(string projectName) { m_Options.Parse(projectName); SetupRealTypeTables(); foreach(var f in m_Options.Files) { try { ParseFile(f); } catch(Exception e) { Utilities.Log.PrintExceptionInfo(e); } } if(!m_StageFailed) { RootPackage.Preprocess(); RootPackage.GenerateTemplates(m_StringTemplateGroup); } else { Utilities.Log.WriteLine("Parsing stage failed, compilation can not continue"); return; } if (!m_StageFailed) { RootPackage.GenerateCode(m_StringTemplateGroup); foreach (var gen in m_GeneratedFiles) { gen.Value.WriteFiles(); } } else { Utilities.Log.WriteLine("Template generation stage failed, compilation can not continue."); return; } if (!m_StageFailed) { Utilities.Log.WriteLine("Compilation succedeed."); } } public string GetFilePath(string filePath) { string fullPath = Path.GetFullPath(filePath); if (File.Exists(fullPath)) return fullPath; foreach (var inc in m_Options.Includes) { fullPath = Path.Combine(inc, filePath); if (File.Exists(fullPath)) return fullPath; } FileNotFound(filePath); return null; } } }
//--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // // <copyright file=TextParentUndoUnit.cs company=Microsoft> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // // See spec at http://avalon/uis/Stock%20Services/Undo%20spec.htm // // History: // 03/23/2004 : eveselov - created // //--------------------------------------------------------------------------- using System; using MS.Internal; using System.Windows.Input; using System.Windows.Controls; using System.Windows.Documents.Internal; using System.Windows.Threading; using System.ComponentModel; using System.Windows.Media; using System.Windows.Markup; using System.Text; using MS.Utility; using MS.Internal.Documents; namespace System.Windows.Documents { /// <summary> /// TextParentUndoUnit /// </summary> internal class TextParentUndoUnit : ParentUndoUnit { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="selection"> /// TextSelection before executing the operation. /// </param> internal TextParentUndoUnit(ITextSelection selection) : this(selection, selection.AnchorPosition, selection.MovingPosition) { } internal TextParentUndoUnit(ITextSelection selection, ITextPointer anchorPosition, ITextPointer movingPosition) : base(String.Empty) { _selection = selection; _undoAnchorPositionOffset = anchorPosition.Offset; _undoAnchorPositionDirection = anchorPosition.LogicalDirection; _undoMovingPositionOffset = movingPosition.Offset; _undoMovingPositionDirection = movingPosition.LogicalDirection; // Bug 1706768: we are seeing unitialized values when the undo // undo is pulled off the undo stack. _redoAnchorPositionOffset // and _redoMovingPositionOffset are supposed to be initialized // with calls to RecordRedoSelectionState before that happens. // // This code path is being left enabled in DEBUG to help track down // the underlying bug post V1. #if DEBUG _redoAnchorPositionOffset = -1; _redoMovingPositionOffset = -1; #else _redoAnchorPositionOffset = 0; _redoMovingPositionOffset = 0; #endif } /// <summary> /// Creates a redo unit from an undo unit. /// </summary> protected TextParentUndoUnit(TextParentUndoUnit undoUnit) : base(String.Empty) { _selection = undoUnit._selection; _undoAnchorPositionOffset = undoUnit._redoAnchorPositionOffset; _undoAnchorPositionDirection = undoUnit._redoAnchorPositionDirection; _undoMovingPositionOffset = undoUnit._redoMovingPositionOffset; _undoMovingPositionDirection = undoUnit._redoMovingPositionDirection; // Bug 1706768: we are seeing unitialized values when the undo // undo is pulled off the undo stack. _redoAnchorPositionOffset // and _redoMovingPositionOffset are supposed to be initialized // with calls to RecordRedoSelectionState before that happens. // // This code path is being left enabled in DEBUG to help track down // the underlying bug post V1. #if DEBUG _redoAnchorPositionOffset = -1; _redoMovingPositionOffset = -1; #else _redoAnchorPositionOffset = 0; _redoMovingPositionOffset = 0; #endif } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Implements IUndoUnit::Do(). For IParentUndoUnit, this means iterating through /// all contained units and calling their Do(). /// </summary> public override void Do() { base.Do(); // Note: TextParentUndoUnit will be created here by our callback CreateParentUndoUnitForSelf. ITextContainer textContainer = _selection.Start.TextContainer; ITextPointer anchorPosition = textContainer.CreatePointerAtOffset(_undoAnchorPositionOffset, _undoAnchorPositionDirection); ITextPointer movingPosition = textContainer.CreatePointerAtOffset(_undoMovingPositionOffset, _undoMovingPositionDirection); _selection.Select(anchorPosition, movingPosition); _redoUnit.RecordRedoSelectionState(); } #endregion Public Methods //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implements a callback called from base.Do method for /// creating appropriate ParentUndoUnit for redo. /// </summary> /// <returns></returns> protected override IParentUndoUnit CreateParentUndoUnitForSelf() { _redoUnit = CreateRedoUnit(); return _redoUnit; } protected virtual TextParentUndoUnit CreateRedoUnit() { return new TextParentUndoUnit(this); } protected void MergeRedoSelectionState(TextParentUndoUnit undoUnit) { _redoAnchorPositionOffset = undoUnit._redoAnchorPositionOffset; _redoAnchorPositionDirection = undoUnit._redoAnchorPositionDirection; _redoMovingPositionOffset = undoUnit._redoMovingPositionOffset; _redoMovingPositionDirection = undoUnit._redoMovingPositionDirection; } #endregion Protected Methods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// This method should be called just before the undo unit is closed. It will capture /// the current selectionStart and selectionEnd offsets for use later when this undo unit /// gets Redone. /// </summary> internal void RecordRedoSelectionState() { RecordRedoSelectionState(_selection.AnchorPosition, _selection.MovingPosition); } /// <summary> /// This method should be called just before the undo unit is closed. It will capture /// the current selectionStart and selectionEnd offsets for use later when this undo unit /// gets Redone. /// </summary> internal void RecordRedoSelectionState(ITextPointer anchorPosition, ITextPointer movingPosition) { _redoAnchorPositionOffset = anchorPosition.Offset; _redoAnchorPositionDirection = anchorPosition.LogicalDirection; _redoMovingPositionOffset = movingPosition.Offset; _redoMovingPositionDirection = movingPosition.LogicalDirection; } #endregion Internal Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private readonly ITextSelection _selection; private readonly int _undoAnchorPositionOffset; private readonly LogicalDirection _undoAnchorPositionDirection; private readonly int _undoMovingPositionOffset; private readonly LogicalDirection _undoMovingPositionDirection; private int _redoAnchorPositionOffset; private LogicalDirection _redoAnchorPositionDirection; private int _redoMovingPositionOffset; private LogicalDirection _redoMovingPositionDirection; private TextParentUndoUnit _redoUnit; #if DEBUG // Debug-only unique identifier for this instance. private readonly int _debugId = _debugIdCounter++; // Debug-only id counter. private static int _debugIdCounter; #endif #endregion Private Fields } }
// 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; /// <summary> /// System.Collections.Generic.List.GetRange(Int32,Int32) /// </summary> public class ListGetRange { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int"); try { int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); int startIdx = this.GetInt32(0, 9); //The starting index of the section to make a shallow copy int endIdx = this.GetInt32(startIdx, 10);//The end index of the section to make a shallow copy int count = endIdx - startIdx + 1; List<int> listResult = listObject.GetRange(startIdx, count); for (int i = 0; i < count; i++) { if (listResult[i] != iArray[i + startIdx]) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,result is: " + listResult[i] + " expected value is: " + iArray[i + startIdx]); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string"); try { string[] strArray = { "apple", "banana", "chocolate", "dog", "food" }; List<string> listObject = new List<string>(strArray); int startIdx = this.GetInt32(0, 4); //The starting index of the section to make a shallow copy int endIdx = this.GetInt32(startIdx, 5);//The end index of the section to make a shallow copy int count = endIdx - startIdx + 1; List<string> listResult = listObject.GetRange(startIdx, count); for (int i = 0; i < count; i++) { if (listResult[i] != strArray[i + startIdx]) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,result is: " + listResult[i] + " expected value is: " + strArray[i + startIdx]); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is a custom type"); try { MyClass myclass1 = new MyClass(); MyClass myclass2 = new MyClass(); MyClass myclass3 = new MyClass(); MyClass[] mc = new MyClass[3] { myclass1, myclass2, myclass3 }; List<MyClass> listObject = new List<MyClass>(mc); int startIdx = this.GetInt32(0, 2); //The starting index of the section to make a shallow copy int endIdx = this.GetInt32(startIdx, 3);//The end index of the section to make a shallow copy int count = endIdx - startIdx + 1; List<MyClass> listResult = listObject.GetRange(startIdx, count); for (int i = 0; i < count; i++) { if (listResult[i] != mc[i + startIdx]) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,result is: " + listResult[i] + " expected value is: " + mc[i + startIdx]); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Copy no elements to the new list"); try { int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); List<int> listResult = listObject.GetRange(5, 0); if (listResult == null) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } if (listResult.Count != 0) { TestLibrary.TestFramework.LogError("008", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The index is a negative number"); try { int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); List<int> listResult = listObject.GetRange(-1, 4); TestLibrary.TestFramework.LogError("101", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The count is a negative number"); try { int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); List<int> listResult = listObject.GetRange(6, -4); TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: index and count do not denote a valid range of elements in the List"); try { char[] iArray = { '#', ' ', '&', 'c', '1', '_', 'A' }; List<char> listObject = new List<char>(iArray); List<char> listResult = listObject.GetRange(4, 4); TestLibrary.TestFramework.LogError("103", "The ArgumentException was not thrown as expected"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ListGetRange test = new ListGetRange(); TestLibrary.TestFramework.BeginTestCase("ListGetRange"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } } public class MyClass { }
//TODO: it's a bit of a misnomer to call this a 'core' //that's libretro nomenclature for a particular core (nes, genesis, doom, etc.) //we should call this LibretroEmulator (yeah, it was originally called that) //Since it's an IEmulator.. but... I dont know. Yeah, that's probably best using System; using System.Linq; using System.Xml; using System.Xml.Linq; using System.IO; using System.Collections.Generic; using System.Runtime.InteropServices; using BizHawk.Common; using BizHawk.Common.BufferExtensions; using BizHawk.Emulation.Common; namespace BizHawk.Emulation.Cores.Libretro { [Core("Libretro", "zeromus")] [ServiceNotApplicable(typeof(IDriveLight))] public unsafe partial class LibretroCore : IEmulator, ISettable<LibretroCore.Settings, LibretroCore.SyncSettings>, ISaveRam, IStatable, IVideoProvider, IInputPollable { private LibretroApi api; public LibretroCore(CoreComm nextComm, string corePath) { //TODO: codepath just for introspection (lighter weight; no speex, no controls, etc.) ServiceProvider = new BasicServiceProvider(this); _SyncSettings = new SyncSettings(); CoreComm = nextComm; string dllPath = Path.Combine(CoreComm.CoreFileProvider.DllPath(), "LibretroBridge.dll"); api = new LibretroApi(dllPath, corePath); if (api.comm->env.retro_api_version != 1) throw new InvalidOperationException("Unsupported Libretro API version (or major error in interop)"); //SO: I think I need these paths set before I call retro_set_environment //and I need retro_set_environment set so I can find out if the core supports no-game //therefore, I need a complete environment (including pathing) before I can complete my introspection of the core. //Sucky, but that's life. //I dont even know for sure what paths I should use until... (what?) //not sure about each of these.. but we may be doing things different than retroarch. //I wish I could initialize these with placeholders during a separate introspection codepath.. string SystemDirectory = CoreComm.CoreFileProvider.GetRetroSystemPath(); string SaveDirectory = CoreComm.CoreFileProvider.GetRetroSaveRAMDirectory(); string CoreDirectory = Path.GetDirectoryName(corePath); string CoreAssetsDirectory = Path.GetDirectoryName(corePath); api.CopyAscii(LibretroApi.BufId.SystemDirectory, SystemDirectory); api.CopyAscii(LibretroApi.BufId.SaveDirectory, SaveDirectory); api.CopyAscii(LibretroApi.BufId.CoreDirectory, CoreDirectory); api.CopyAscii(LibretroApi.BufId.CoreAssetsDirectory, CoreAssetsDirectory); api.CMD_SetEnvironment(); //TODO: IT'S A BOWL OF SPAGHETTI! I KNOW, IM GOING TO FIX IT api.core = this; Description = api.CalculateDescription(); ControllerDefinition = CreateControllerDefinition(_SyncSettings); } bool disposed = false; public void Dispose() { if (disposed) return; disposed = true; //TODO //api.CMD_unload_cartridge(); //api.CMD_term(); if(resampler != null) resampler.Dispose(); api.Dispose(); if(vidBufferHandle.IsAllocated) vidBufferHandle.Free(); } public CoreComm CoreComm { get; private set; } public RetroDescription Description { get; private set; } public bool LoadData(byte[] data, string id) { bool ret = api.CMD_LoadData(data, id); LoadHandler(); return ret; } public bool LoadPath(string path) { bool ret = api.CMD_LoadPath(path); LoadHandler(); return ret; } public bool LoadNoGame() { bool ret = api.CMD_LoadNoGame(); LoadHandler(); return ret; } void LoadHandler() { //this stuff can only happen after the game is loaded //allocate a video buffer which will definitely be large enough SetVideoBuffer((int)api.comm->env.retro_system_av_info.geometry.base_width, (int)api.comm->env.retro_system_av_info.geometry.base_height); vidBuffer = new int[api.comm->env.retro_system_av_info.geometry.max_width * api.comm->env.retro_system_av_info.geometry.max_height]; vidBufferHandle = GCHandle.Alloc(vidBuffer, GCHandleType.Pinned); api.comm->env.fb_bufptr = (int*)vidBufferHandle.AddrOfPinnedObject().ToPointer(); //TODO: latch DAR? we may want to change it synchronously, or something // TODO: more precise VsyncNumerator = (int)(10000000 * api.comm->env.retro_system_av_info.timing.fps); VsyncDenominator = 10000000; SetupResampler(api.comm->env.retro_system_av_info.timing.fps, api.comm->env.retro_system_av_info.timing.sample_rate); (ServiceProvider as BasicServiceProvider).Register<ISoundProvider>(resampler); } public IEmulatorServiceProvider ServiceProvider { get; private set; } public IDictionary<string, RegisterValue> GetCpuFlagsAndRegisters() { return new Dictionary<string, RegisterValue>(); } public IInputCallbackSystem InputCallbacks { get { return _inputCallbacks; } } private readonly InputCallbackSystem _inputCallbacks = new InputCallbackSystem(); public ITraceable Tracer { get; private set; } public IMemoryCallbackSystem MemoryCallbacks { get; private set; } public bool CanStep(StepType type) { return false; } [FeatureNotImplemented] public void Step(StepType type) { throw new NotImplementedException(); } [FeatureNotImplemented] public void SetCpuRegister(string register, int value) { throw new NotImplementedException(); } [FeatureNotImplemented] public long TotalExecutedCycles { get { throw new NotImplementedException(); } } private IController _controller; public bool FrameAdvance(IController controller, bool render, bool rendersound) { _controller = controller; api.CMD_Run(); timeFrameCounter++; return true; } GCHandle vidBufferHandle; int[] vidBuffer; int vidWidth = -1, vidHeight = -1; private void SetVideoBuffer(int width, int height) { //actually, we've already allocated a buffer with the given maximum size if (vidWidth == width && vidHeight == height) return; vidWidth = width; vidHeight = height; } //video provider int IVideoProvider.BackgroundColor { get { return 0; } } int[] IVideoProvider.GetVideoBuffer() { return vidBuffer; } public int VirtualWidth { get { var dar = api.AVInfo.geometry.aspect_ratio; if(dar<=0) return vidWidth; else if (dar > 1.0f) return (int)(vidHeight * dar); else return vidWidth; } } public int VirtualHeight { get { var dar = api.AVInfo.geometry.aspect_ratio; if(dar<=0) return vidHeight; if (dar < 1.0f) return (int)(vidWidth / dar); else return vidHeight; } } public void SIG_VideoUpdate() { SetVideoBuffer(api.comm->env.fb_width, api.comm->env.fb_height); } int IVideoProvider.BufferWidth { get { return vidWidth; } } int IVideoProvider.BufferHeight { get { return vidHeight; } } public int VsyncNumerator { get; private set; } public int VsyncDenominator { get; private set; } #region ISoundProvider SpeexResampler resampler; short[] sampbuff = new short[0]; // debug int nsamprecv = 0; void SetupResampler(double fps, double sps) { Console.WriteLine("FPS {0} SPS {1}", fps, sps); // todo: more precise? uint spsnum = (uint)sps * 1000; uint spsden = (uint)1000; resampler = new SpeexResampler(SpeexResampler.Quality.QUALITY_DESKTOP, 44100 * spsden, spsnum, (uint)sps, 44100, null, null); } //TODO: handle these in c++ (queue there and blast after frameadvance to c#) public void retro_audio_sample(short left, short right) { resampler.EnqueueSample(left, right); nsamprecv++; } public void retro_audio_sample_batch(void* data, int frames) { if (sampbuff.Length < frames * 2) sampbuff = new short[frames * 2]; Marshal.Copy(new IntPtr(data), sampbuff, 0, (int)(frames * 2)); resampler.EnqueueSamples(sampbuff, (int)frames); nsamprecv += (int)frames; } #endregion public static ControllerDefinition CreateControllerDefinition(SyncSettings syncSettings) { ControllerDefinition definition = new ControllerDefinition(); definition.Name = "LibRetro Controls"; // <-- for compatibility foreach(var item in new[] { "P1 {0} Up", "P1 {0} Down", "P1 {0} Left", "P1 {0} Right", "P1 {0} Select", "P1 {0} Start", "P1 {0} Y", "P1 {0} B", "P1 {0} X", "P1 {0} A", "P1 {0} L", "P1 {0} R", "P2 {0} Up", "P2 {0} Down", "P2 {0} Left", "P2 {0} Right", "P2 {0} Select", "P2 {0} Start", "P2 {0} Y", "P2 {0} B", "P2 {0} X", "P2 {0} A", "P2 {0} L", "P2 {0} R", }) definition.BoolButtons.Add(string.Format(item,"RetroPad")); definition.BoolButtons.Add("Pointer Pressed"); //TODO: this isnt showing up in the binding panel. I dont want to find out why. definition.FloatControls.Add("Pointer X"); definition.FloatControls.Add("Pointer Y"); definition.FloatRanges.Add(new ControllerDefinition.FloatRange(-32767, 0, 32767)); definition.FloatRanges.Add(new ControllerDefinition.FloatRange(-32767, 0, 32767)); foreach (var key in new[]{ "Key Backspace", "Key Tab", "Key Clear", "Key Return", "Key Pause", "Key Escape", "Key Space", "Key Exclaim", "Key QuoteDbl", "Key Hash", "Key Dollar", "Key Ampersand", "Key Quote", "Key LeftParen", "Key RightParen", "Key Asterisk", "Key Plus", "Key Comma", "Key Minus", "Key Period", "Key Slash", "Key 0", "Key 1", "Key 2", "Key 3", "Key 4", "Key 5", "Key 6", "Key 7", "Key 8", "Key 9", "Key Colon", "Key Semicolon", "Key Less", "Key Equals", "Key Greater", "Key Question", "Key At", "Key LeftBracket", "Key Backslash", "Key RightBracket", "Key Caret", "Key Underscore", "Key Backquote", "Key A", "Key B", "Key C", "Key D", "Key E", "Key F", "Key G", "Key H", "Key I", "Key J", "Key K", "Key L", "Key M", "Key N", "Key O", "Key P", "Key Q", "Key R", "Key S", "Key T", "Key U", "Key V", "Key W", "Key X", "Key Y", "Key Z", "Key Delete", "Key KP0", "Key KP1", "Key KP2", "Key KP3", "Key KP4", "Key KP5", "Key KP6", "Key KP7", "Key KP8", "Key KP9", "Key KP_Period", "Key KP_Divide", "Key KP_Multiply", "Key KP_Minus", "Key KP_Plus", "Key KP_Enter", "Key KP_Equals", "Key Up", "Key Down", "Key Right", "Key Left", "Key Insert", "Key Home", "Key End", "Key PageUp", "Key PageDown", "Key F1", "Key F2", "Key F3", "Key F4", "Key F5", "Key F6", "Key F7", "Key F8", "Key F9", "Key F10", "Key F11", "Key F12", "Key F13", "Key F14", "Key F15", "Key NumLock", "Key CapsLock", "Key ScrollLock", "Key RShift", "Key LShift", "Key RCtrl", "Key LCtrl", "Key RAlt", "Key LAlt", "Key RMeta", "Key LMeta", "Key LSuper", "Key RSuper", "Key Mode", "Key Compose", "Key Help", "Key Print", "Key SysReq", "Key Break", "Key Menu", "Key Power", "Key Euro", "Key Undo" }) { definition.BoolButtons.Add(key); definition.CategoryLabels[key] = "RetroKeyboard"; } return definition; } public ControllerDefinition ControllerDefinition { get; private set; } int timeFrameCounter; public int Frame { get { return timeFrameCounter; } set { timeFrameCounter = value; } } public int LagCount { get; set; } public bool IsLagFrame { get; set; } public string SystemId { get { return "Libretro"; } } public bool DeterministicEmulation { get { return false; } } #region ISaveRam //TODO - terrible things will happen if this changes at runtime byte[] saverambuff = new byte[0]; public byte[] CloneSaveRam() { var mem = api.QUERY_GetMemory(LibretroApi.RETRO_MEMORY.SAVE_RAM); var buf = new byte[mem.Item2]; Marshal.Copy(mem.Item1, buf, 0, (int)mem.Item2); return buf; } public void StoreSaveRam(byte[] data) { var mem = api.QUERY_GetMemory(LibretroApi.RETRO_MEMORY.SAVE_RAM); //bail if the size is 0 if (mem.Item2 == 0) return; Marshal.Copy(data, 0, mem.Item1, (int)mem.Item2); } public bool SaveRamModified { [FeatureNotImplemented] get { //if we dont have saveram, it isnt modified. otherwise, assume it is var mem = api.QUERY_GetMemory(LibretroApi.RETRO_MEMORY.SAVE_RAM); //bail if the size is 0 if (mem.Item2 == 0) return false; return true; } [FeatureNotImplemented] set { throw new NotImplementedException(); } } #endregion public void ResetCounters() { timeFrameCounter = 0; LagCount = 0; IsLagFrame = false; } #region savestates private byte[] savebuff, savebuff2; public void SaveStateText(System.IO.TextWriter writer) { var temp = SaveStateBinary(); temp.SaveAsHex(writer); } public void LoadStateText(System.IO.TextReader reader) { string hex = reader.ReadLine(); byte[] state = new byte[hex.Length / 2]; state.ReadFromHex(hex); LoadStateBinary(new BinaryReader(new MemoryStream(state))); } public void SaveStateBinary(System.IO.BinaryWriter writer) { api.CMD_UpdateSerializeSize(); if (savebuff == null || savebuff.Length != (int)api.comm->env.retro_serialize_size) { savebuff = new byte[api.comm->env.retro_serialize_size]; savebuff2 = new byte[savebuff.Length + 13]; } api.CMD_Serialize(savebuff); writer.Write(savebuff.Length); writer.Write(savebuff); // other variables writer.Write(Frame); writer.Write(LagCount); writer.Write(IsLagFrame); } public void LoadStateBinary(System.IO.BinaryReader reader) { int newlen = reader.ReadInt32(); if (newlen > savebuff.Length) throw new Exception("Unexpected buffer size"); reader.Read(savebuff, 0, newlen); api.CMD_Unserialize(savebuff); // other variables Frame = reader.ReadInt32(); LagCount = reader.ReadInt32(); IsLagFrame = reader.ReadBoolean(); } public byte[] SaveStateBinary() { api.CMD_UpdateSerializeSize(); if (savebuff == null || savebuff.Length != (int)api.comm->env.retro_serialize_size) { savebuff = new byte[api.comm->env.retro_serialize_size]; savebuff2 = new byte[savebuff.Length + 13]; } var ms = new System.IO.MemoryStream(savebuff2, true); var bw = new System.IO.BinaryWriter(ms); SaveStateBinary(bw); bw.Flush(); ms.Close(); return savebuff2; } public bool BinarySaveStatesPreferred { get { return true; } } #endregion } //class } //namespace
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: contract.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf.Examples.AddressBook { /// <summary>Holder for reflection information generated from contract.proto</summary> public static partial class ContractReflection { #region Descriptor /// <summary>File descriptor for contract.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ContractReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cg5jb250cmFjdC5wcm90bxIIdHV0b3JpYWwi1QEKBlBlcnNvbhIMCgRuYW1l", "GAEgASgJEgoKAmlkGAIgASgFEg0KBWVtYWlsGAMgASgJEiwKBnBob25lcxgE", "IAMoCzIcLnR1dG9yaWFsLlBlcnNvbi5QaG9uZU51bWJlchpHCgtQaG9uZU51", "bWJlchIOCgZudW1iZXIYASABKAkSKAoEdHlwZRgCIAEoDjIaLnR1dG9yaWFs", "LlBlcnNvbi5QaG9uZVR5cGUiKwoJUGhvbmVUeXBlEgoKBk1PQklMRRAAEggK", "BEhPTUUQARIICgRXT1JLEAJCJ6oCJEdvb2dsZS5Qcm90b2J1Zi5FeGFtcGxl", "cy5BZGRyZXNzQm9va2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.Person), global::Google.Protobuf.Examples.AddressBook.Person.Parser, new[]{ "Name", "Id", "Email", "Phones" }, null, new[]{ typeof(global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber), global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber.Parser, new[]{ "Number", "Type" }, null, null, null)}) })); } #endregion } #region Messages public sealed partial class Person : pb::IMessage<Person> { private static readonly pb::MessageParser<Person> _parser = new pb::MessageParser<Person>(() => new Person()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Person> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.Examples.AddressBook.ContractReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Person() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Person(Person other) : this() { name_ = other.name_; id_ = other.id_; email_ = other.email_; phones_ = other.phones_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Person Clone() { return new Person(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 2; private int id_; /// <summary> /// Unique ID number for this person. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Id { get { return id_; } set { id_ = value; } } /// <summary>Field number for the "email" field.</summary> public const int EmailFieldNumber = 3; private string email_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Email { get { return email_; } set { email_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "phones" field.</summary> public const int PhonesFieldNumber = 4; private static readonly pb::FieldCodec<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber> _repeated_phones_codec = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber> phones_ = new pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber> Phones { get { return phones_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Person); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Person other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Id != other.Id) return false; if (Email != other.Email) return false; if(!phones_.Equals(other.phones_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Id != 0) hash ^= Id.GetHashCode(); if (Email.Length != 0) hash ^= Email.GetHashCode(); hash ^= phones_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Id != 0) { output.WriteRawTag(16); output.WriteInt32(Id); } if (Email.Length != 0) { output.WriteRawTag(26); output.WriteString(Email); } phones_.WriteTo(output, _repeated_phones_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Id != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Id); } if (Email.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Email); } size += phones_.CalculateSize(_repeated_phones_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Person other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Id != 0) { Id = other.Id; } if (other.Email.Length != 0) { Email = other.Email; } phones_.Add(other.phones_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 16: { Id = input.ReadInt32(); break; } case 26: { Email = input.ReadString(); break; } case 34: { phones_.AddEntriesFrom(input, _repeated_phones_codec); break; } } } } #region Nested types /// <summary>Container for nested types declared in the Person message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum PhoneType { [pbr::OriginalName("MOBILE")] Mobile = 0, [pbr::OriginalName("HOME")] Home = 1, [pbr::OriginalName("WORK")] Work = 2, } public sealed partial class PhoneNumber : pb::IMessage<PhoneNumber> { private static readonly pb::MessageParser<PhoneNumber> _parser = new pb::MessageParser<PhoneNumber>(() => new PhoneNumber()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PhoneNumber> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.Examples.AddressBook.Person.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PhoneNumber() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PhoneNumber(PhoneNumber other) : this() { number_ = other.number_; type_ = other.type_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PhoneNumber Clone() { return new PhoneNumber(this); } /// <summary>Field number for the "number" field.</summary> public const int NumberFieldNumber = 1; private string number_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Number { get { return number_; } set { number_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 2; private global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType type_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType Type { get { return type_; } set { type_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PhoneNumber); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PhoneNumber other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Number != other.Number) return false; if (Type != other.Type) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Number.Length != 0) hash ^= Number.GetHashCode(); if (Type != 0) hash ^= Type.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Number.Length != 0) { output.WriteRawTag(10); output.WriteString(Number); } if (Type != 0) { output.WriteRawTag(16); output.WriteEnum((int) Type); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Number.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Number); } if (Type != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PhoneNumber other) { if (other == null) { return; } if (other.Number.Length != 0) { Number = other.Number; } if (other.Type != 0) { Type = other.Type; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Number = input.ReadString(); break; } case 16: { type_ = (global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType) input.ReadEnum(); break; } } } } } } #endregion } #endregion } #endregion Designer generated code
using ClosedXML.Excel.CalcEngine.Exceptions; using ClosedXML.Excel.CalcEngine.Functions; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace ClosedXML.Excel.CalcEngine { /// <summary> /// CalcEngine parses strings and returns Expression objects that can /// be evaluated. /// </summary> /// <remarks> /// <para>This class has three extensibility points:</para> /// <para>Use the <b>DataContext</b> property to add an object's properties to the engine scope.</para> /// <para>Use the <b>RegisterFunction</b> method to define custom functions.</para> /// <para>Override the <b>GetExternalObject</b> method to add arbitrary variables to the engine scope.</para> /// </remarks> internal class CalcEngine { private const string defaultFunctionNameSpace = "_xlfn"; //--------------------------------------------------------------------------- #region ** fields // members private string _expr; // expression being parsed private int _len; // length of the expression being parsed private int _ptr; // current pointer into expression private char[] _idChars; // valid characters in identifiers (besides alpha and digits) private Token _currentToken; // current token being parsed private Token _nextToken; // next token being parsed. to be used by Peek private Dictionary<object, Token> _tkTbl; // table with tokens (+, -, etc) private Dictionary<string, FunctionDefinition> _fnTbl; // table with constants and functions (pi, sin, etc) private Dictionary<string, object> _vars; // table with variables private object _dataContext; // object with properties private bool _optimize; // optimize expressions when parsing protected ExpressionCache _cache; // cache with parsed expressions private CultureInfo _ci; // culture info used to parse numbers/dates private char _decimal, _listSep, _percent; // localized decimal separator, list separator, percent sign #endregion ** fields //--------------------------------------------------------------------------- #region ** ctor public CalcEngine() { CultureInfo = CultureInfo.InvariantCulture; _tkTbl = GetSymbolTable(); _fnTbl = GetFunctionTable(); _vars = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); _cache = new ExpressionCache(this); _optimize = true; #if DEBUG //this.Test(); #endif } #endregion ** ctor //--------------------------------------------------------------------------- #region ** object model /// <summary> /// Parses a string into an <see cref="Expression"/>. /// </summary> /// <param name="expression">String to parse.</param> /// <returns>An <see cref="Expression"/> object that can be evaluated.</returns> public Expression Parse(string expression) { // initialize _expr = expression; _len = _expr.Length; _ptr = 0; _currentToken = null; _nextToken = null; // skip leading equals sign if (_len > 0 && _expr[0] == '=') _ptr++; // skip leading +'s while (_len > _ptr && _expr[_ptr] == '+') _ptr++; // parse the expression var expr = ParseExpression(); // check for errors if (_currentToken.ID == TKID.OPEN) Throw("Unknown function: " + expr.LastParseItem); else if (_currentToken.ID != TKID.END) Throw("Expected end of expression"); // optimize expression if (_optimize) { expr = expr.Optimize(); } // done return expr; } /// <summary> /// Evaluates a string. /// </summary> /// <param name="expression">Expression to evaluate.</param> /// <returns>The value of the expression.</returns> /// <remarks> /// If you are going to evaluate the same expression several times, /// it is more efficient to parse it only once using the <see cref="Parse"/> /// method and then using the Expression.Evaluate method to evaluate /// the parsed expression. /// </remarks> public object Evaluate(string expression) { var x = _cache != null ? _cache[expression] : Parse(expression); return x.Evaluate(); } /// <summary> /// Gets or sets whether the calc engine should keep a cache with parsed /// expressions. /// </summary> public bool CacheExpressions { get { return _cache != null; } set { if (value != CacheExpressions) { _cache = value ? new ExpressionCache(this) : null; } } } /// <summary> /// Gets or sets whether the calc engine should optimize expressions when /// they are parsed. /// </summary> public bool OptimizeExpressions { get { return _optimize; } set { _optimize = value; } } /// <summary> /// Gets or sets a string that specifies special characters that are valid for identifiers. /// </summary> /// <remarks> /// Identifiers must start with a letter or an underscore, which may be followed by /// additional letters, underscores, or digits. This string allows you to specify /// additional valid characters such as ':' or '!' (used in Excel range references /// for example). /// </remarks> public char[] IdentifierChars { get { return _idChars; } set { _idChars = value; } } /// <summary> /// Registers a function that can be evaluated by this <see cref="CalcEngine"/>. /// </summary> /// <param name="functionName">Function name.</param> /// <param name="parmMin">Minimum parameter count.</param> /// <param name="parmMax">Maximum parameter count.</param> /// <param name="fn">Delegate that evaluates the function.</param> public void RegisterFunction(string functionName, int parmMin, int parmMax, CalcEngineFunction fn) { _fnTbl.Add(functionName, new FunctionDefinition(parmMin, parmMax, fn)); } /// <summary> /// Registers a function that can be evaluated by this <see cref="CalcEngine"/>. /// </summary> /// <param name="functionName">Function name.</param> /// <param name="parmCount">Parameter count.</param> /// <param name="fn">Delegate that evaluates the function.</param> public void RegisterFunction(string functionName, int parmCount, CalcEngineFunction fn) { RegisterFunction(functionName, parmCount, parmCount, fn); } /// <summary> /// Gets an external object based on an identifier. /// </summary> /// <remarks> /// This method is useful when the engine needs to create objects dynamically. /// For example, a spreadsheet calc engine would use this method to dynamically create cell /// range objects based on identifiers that cannot be enumerated at design time /// (such as "AB12", "A1:AB12", etc.) /// </remarks> public virtual object GetExternalObject(string identifier) { return null; } /// <summary> /// Gets or sets the DataContext for this <see cref="CalcEngine"/>. /// </summary> /// <remarks> /// Once a DataContext is set, all public properties of the object become available /// to the CalcEngine, including sub-properties such as "Address.Street". These may /// be used with expressions just like any other constant. /// </remarks> public virtual object DataContext { get { return _dataContext; } set { _dataContext = value; } } /// <summary> /// Gets the dictionary that contains function definitions. /// </summary> public Dictionary<string, FunctionDefinition> Functions { get { return _fnTbl; } } /// <summary> /// Gets the dictionary that contains simple variables (not in the DataContext). /// </summary> public Dictionary<string, object> Variables { get { return _vars; } } /// <summary> /// Gets or sets the <see cref="CultureInfo"/> to use when parsing numbers and dates. /// </summary> public CultureInfo CultureInfo { get { return _ci; } set { _ci = value; var nf = _ci.NumberFormat; _decimal = nf.NumberDecimalSeparator[0]; _percent = nf.PercentSymbol[0]; _listSep = _ci.TextInfo.ListSeparator[0]; } } #endregion ** object model //--------------------------------------------------------------------------- #region ** token/keyword tables private static readonly IDictionary<string, ErrorExpression.ExpressionErrorType> ErrorMap = new Dictionary<string, ErrorExpression.ExpressionErrorType>() { ["#REF!"] = ErrorExpression.ExpressionErrorType.CellReference, ["#VALUE!"] = ErrorExpression.ExpressionErrorType.CellValue, ["#DIV/0!"] = ErrorExpression.ExpressionErrorType.DivisionByZero, ["#NAME?"] = ErrorExpression.ExpressionErrorType.NameNotRecognized, ["#N/A"] = ErrorExpression.ExpressionErrorType.NoValueAvailable, ["#NULL!"] = ErrorExpression.ExpressionErrorType.NullValue, ["#NUM!"] = ErrorExpression.ExpressionErrorType.NumberInvalid }; // build/get static token table private Dictionary<object, Token> GetSymbolTable() { if (_tkTbl == null) { _tkTbl = new Dictionary<object, Token>(); AddToken('&', TKID.CONCAT, TKTYPE.ADDSUB); AddToken('+', TKID.ADD, TKTYPE.ADDSUB); AddToken('-', TKID.SUB, TKTYPE.ADDSUB); AddToken('(', TKID.OPEN, TKTYPE.GROUP); AddToken(')', TKID.CLOSE, TKTYPE.GROUP); AddToken('*', TKID.MUL, TKTYPE.MULDIV); AddToken('.', TKID.PERIOD, TKTYPE.GROUP); AddToken('/', TKID.DIV, TKTYPE.MULDIV); AddToken('\\', TKID.DIVINT, TKTYPE.MULDIV); AddToken('%', TKID.DIV100, TKTYPE.MULDIV_UNARY); AddToken('=', TKID.EQ, TKTYPE.COMPARE); AddToken('>', TKID.GT, TKTYPE.COMPARE); AddToken('<', TKID.LT, TKTYPE.COMPARE); AddToken('^', TKID.POWER, TKTYPE.POWER); AddToken("<>", TKID.NE, TKTYPE.COMPARE); AddToken(">=", TKID.GE, TKTYPE.COMPARE); AddToken("<=", TKID.LE, TKTYPE.COMPARE); // list separator is localized, not necessarily a comma // so it can't be on the static table //AddToken(',', TKID.COMMA, TKTYPE.GROUP); } return _tkTbl; } private void AddToken(object symbol, TKID id, TKTYPE type) { var token = new Token(symbol, id, type); _tkTbl.Add(symbol, token); } // build/get static keyword table private Dictionary<string, FunctionDefinition> GetFunctionTable() { if (_fnTbl == null) { // create table _fnTbl = new Dictionary<string, FunctionDefinition>(StringComparer.InvariantCultureIgnoreCase); // register built-in functions (and constants) Engineering.Register(this); Information.Register(this); Logical.Register(this); Lookup.Register(this); MathTrig.Register(this); Text.Register(this); Statistical.Register(this); DateAndTime.Register(this); Financial.Register(this); } return _fnTbl; } #endregion ** token/keyword tables //--------------------------------------------------------------------------- #region ** private stuff private Expression ParseExpression() { GetToken(); return ParseCompare(); } private Expression ParseCompare() { var x = ParseAddSub(); while (_currentToken.Type == TKTYPE.COMPARE) { var t = _currentToken; GetToken(); var exprArg = ParseAddSub(); x = new BinaryExpression(t, x, exprArg); } return x; } private Expression ParseAddSub() { var x = ParseMulDiv(); while (_currentToken.Type == TKTYPE.ADDSUB) { var t = _currentToken; GetToken(); var exprArg = ParseMulDiv(); x = new BinaryExpression(t, x, exprArg); } return x; } private Expression ParseMulDiv() { var x = ParsePower(); while (_currentToken.Type == TKTYPE.MULDIV) { var t = _currentToken; GetToken(); var a = ParsePower(); x = new BinaryExpression(t, x, a); } return x; } private Expression ParsePower() { var x = ParseMulDivUnary(); while (_currentToken.Type == TKTYPE.POWER) { var t = _currentToken; GetToken(); var a = ParseMulDivUnary(); x = new BinaryExpression(t, x, a); } return x; } private Expression ParseMulDivUnary() { var x = ParseUnary(); while (_currentToken.Type == TKTYPE.MULDIV_UNARY) { var t = _tkTbl['/']; var a = new Expression(100); x = new BinaryExpression(t, x, a); GetToken(); } return x; } private Expression ParseUnary() { // unary plus and minus if (_currentToken.Type == TKTYPE.ADDSUB) { var sign = 1; do { if (_currentToken.ID == TKID.SUB) sign = -sign; GetToken(); } while (_currentToken.Type == TKTYPE.ADDSUB); var a = ParseAtom(); var t = (sign == 1) ? _tkTbl['+'] : _tkTbl['-']; return new UnaryExpression(t, a); } // not unary, return atom return ParseAtom(); } private Expression ParseAtom() { string id; Expression x = null; switch (_currentToken.Type) { // literals case TKTYPE.LITERAL: x = new Expression(_currentToken); break; // identifiers case TKTYPE.IDENTIFIER: // get identifier id = (string)_currentToken.Value; // Peek ahead to see whether we have a function name (which will be followed by parenthesis // Or another identifier, like a named range or cell reference if (PeekToken().ID == TKID.OPEN) { // look for functions var foundFunction = _fnTbl.TryGetValue(id, out FunctionDefinition functionDefinition); if (!foundFunction && id.StartsWith($"{defaultFunctionNameSpace}.")) foundFunction = _fnTbl.TryGetValue(id.Substring(defaultFunctionNameSpace.Length + 1), out functionDefinition); if (!foundFunction) throw new NameNotRecognizedException($"The identifier `{id}` was not recognised."); var p = GetParameters(); var pCnt = p == null ? 0 : p.Count; if (functionDefinition.ParmMin != -1 && pCnt < functionDefinition.ParmMin) { Throw(string.Format("Too few parameters for function '{0}'. Expected a minimum of {1} and a maximum of {2}.", id, functionDefinition.ParmMin, functionDefinition.ParmMax)); } if (functionDefinition.ParmMax != -1 && pCnt > functionDefinition.ParmMax) { Throw(string.Format("Too many parameters for function '{0}'.Expected a minimum of {1} and a maximum of {2}.", id, functionDefinition.ParmMin, functionDefinition.ParmMax)); } x = new FunctionExpression(functionDefinition, p); break; } // look for simple variables (much faster than binding!) if (_vars.ContainsKey(id)) { x = new VariableExpression(_vars, id); break; } // look for external objects var xObj = GetExternalObject(id); if (xObj == null) throw new NameNotRecognizedException($"The identifier `{id}` was not recognised."); x = new XObjectExpression(xObj); break; // sub-expressions case TKTYPE.GROUP: // Normally anything other than opening parenthesis is illegal here // but Excel allows omitted parameters so return empty value expression. if (_currentToken.ID != TKID.OPEN) { return new EmptyValueExpression(); } // get expression GetToken(); x = ParseCompare(); // check that the parenthesis was closed if (_currentToken.ID != TKID.CLOSE) { Throw("Unbalanced parenthesis."); } break; case TKTYPE.ERROR: x = new ErrorExpression((ErrorExpression.ExpressionErrorType)_currentToken.Value); break; } // make sure we got something... if (x == null) { Throw(); } // done GetToken(); return x; } #endregion ** private stuff //--------------------------------------------------------------------------- #region ** parser private static IDictionary<char, char> matchingClosingSymbols = new Dictionary<char, char>() { { '\'', '\'' }, { '[', ']' } }; private Token ParseToken() { // eat white space while (_ptr < _len && _expr[_ptr] <= ' ') { _ptr++; } // are we done? if (_ptr >= _len) { return new Token(null, TKID.END, TKTYPE.GROUP); } // prepare to parse int i; var c = _expr[_ptr]; // operators // this gets called a lot, so it's pretty optimized. // note that operators must start with non-letter/digit characters. var isLetter = char.IsLetter(c); var isDigit = char.IsDigit(c); var isEnclosed = matchingClosingSymbols.TryGetValue(c, out char matchingClosingSymbol); if (!isLetter && !isDigit && !isEnclosed) { // if this is a number starting with a decimal, don't parse as operator var nxt = _ptr + 1 < _len ? _expr[_ptr + 1] : '0'; bool isNumber = c == _decimal && char.IsDigit(nxt); if (!isNumber) { // look up localized list separator if (c == _listSep) { _ptr++; return new Token(c, TKID.COMMA, TKTYPE.GROUP); } // look up single-char tokens on table if (_tkTbl.TryGetValue(c, out Token t)) { // save token we found var token = t; _ptr++; // look for double-char tokens (special case) if (_ptr < _len && (c == '>' || c == '<') && _tkTbl.TryGetValue(_expr.Substring(_ptr - 1, 2), out t)) { token = t; _ptr++; } // found token on the table return token; } } } // parse numbers if (isDigit || c == _decimal) { var sci = false; var div = -1.0; // use double, not int (this may get really big) var val = 0.0; for (i = 0; i + _ptr < _len; i++) { c = _expr[_ptr + i]; // digits always OK if (char.IsDigit(c)) { val = val * 10 + (c - '0'); if (div > -1) { div *= 10; } continue; } // one decimal is OK if (c == _decimal && div < 0) { div = 1; continue; } // scientific notation? if ((c == 'E' || c == 'e') && !sci) { sci = true; c = _expr[_ptr + i + 1]; if (c == '+' || c == '-') i++; continue; } // end of literal break; } // end of number, get value if (!sci) { // much faster than ParseDouble if (div > 1) { val /= div; } } else { var lit = _expr.Substring(_ptr, i); val = ParseDouble(lit, _ci); } if (c != ':') { // advance pointer and return _ptr += i; // build token return new Token(val, TKID.ATOM, TKTYPE.LITERAL); } } // parse strings if (c == '\"') { // look for end quote, skip double quotes for (i = 1; i + _ptr < _len; i++) { c = _expr[_ptr + i]; if (c != '\"') continue; char cNext = i + _ptr < _len - 1 ? _expr[_ptr + i + 1] : ' '; if (cNext != '\"') break; i++; } // check that we got the end of the string if (c != '\"') { Throw("Can't find final quote."); } // end of string var lit = _expr.Substring(_ptr + 1, i - 1); _ptr += i + 1; return new Token(lit.Replace("\"\"", "\""), TKID.ATOM, TKTYPE.LITERAL); } // parse #REF! (and other errors) in formula if (c == '#' && ErrorMap.Any(pair => _len > _ptr + pair.Key.Length && _expr.Substring(_ptr, pair.Key.Length).Equals(pair.Key, StringComparison.OrdinalIgnoreCase))) { var errorPair = ErrorMap.Single(pair => _len > _ptr + pair.Key.Length && _expr.Substring(_ptr, pair.Key.Length).Equals(pair.Key, StringComparison.OrdinalIgnoreCase)); _ptr += errorPair.Key.Length; return new Token(errorPair.Value, TKID.ATOM, TKTYPE.ERROR); } // identifiers (functions, objects) must start with alpha or underscore if (!isEnclosed && !isLetter && c != '_' && (_idChars == null || !_idChars.Contains(c))) { Throw("Identifier expected."); } // and must contain only letters/digits/_idChars for (i = 1; i + _ptr < _len; i++) { c = _expr[_ptr + i]; isLetter = char.IsLetter(c); isDigit = char.IsDigit(c); if (isEnclosed && c == matchingClosingSymbol) { isEnclosed = false; matchingClosingSymbol = '\0'; i++; c = _expr[_ptr + i]; isLetter = char.IsLetter(c); isDigit = char.IsDigit(c); } var disallowedSymbols = new List<char>() { '\\', '/', '*', '[', ':', '?' }; if (isEnclosed && disallowedSymbols.Contains(c)) break; var allowedSymbols = new List<char>() { '_', '.' }; if (!isLetter && !isDigit && !(isEnclosed || allowedSymbols.Contains(c)) && (_idChars == null || !_idChars.Contains(c))) break; } // got identifier var id = _expr.Substring(_ptr, i); _ptr += i; // If we have a true/false, return a literal if (bool.TryParse(id, out var b)) return new Token(b, TKID.ATOM, TKTYPE.LITERAL); return new Token(id, TKID.ATOM, TKTYPE.IDENTIFIER); } private void GetToken() { if (_nextToken == null) { _currentToken = ParseToken(); } else { _currentToken = _nextToken; _nextToken = null; } } private Token PeekToken() => _nextToken ??= ParseToken(); private static double ParseDouble(string str, CultureInfo ci) { if (str.Length > 0 && str[str.Length - 1] == ci.NumberFormat.PercentSymbol[0]) { str = str.Substring(0, str.Length - 1); return double.Parse(str, NumberStyles.Any, ci) / 100.0; } return double.Parse(str, NumberStyles.Any, ci); } private List<Expression> GetParameters() // e.g. myfun(a, b, c+2) { // check whether next token is a (, // restore state and bail if it's not var pos = _ptr; var tk = _currentToken; GetToken(); if (_currentToken.ID != TKID.OPEN) { _ptr = pos; _currentToken = tk; return null; } // check for empty Parameter list pos = _ptr; GetToken(); if (_currentToken.ID == TKID.CLOSE) { return null; } _ptr = pos; // get Parameters until we reach the end of the list var parms = new List<Expression>(); var expr = ParseExpression(); parms.Add(expr); while (_currentToken.ID == TKID.COMMA) { expr = ParseExpression(); parms.Add(expr); } // make sure the list was closed correctly if (_currentToken.ID == TKID.OPEN) Throw("Unknown function: " + expr.LastParseItem); else if (_currentToken.ID != TKID.CLOSE) Throw("Syntax error: expected ')'"); // done return parms; } private Token GetMember() { // check whether next token is a MEMBER token ('.'), // restore state and bail if it's not var pos = _ptr; var tk = _currentToken; GetToken(); if (_currentToken.ID != TKID.PERIOD) { _ptr = pos; _currentToken = tk; return null; } // skip member token GetToken(); if (_currentToken.Type != TKTYPE.IDENTIFIER) { Throw("Identifier expected"); } return _currentToken; } #endregion ** parser //--------------------------------------------------------------------------- #region ** static helpers private static void Throw() { Throw("Syntax error."); } private static void Throw(string msg) { throw new ExpressionParseException(msg); } #endregion ** static helpers } /// <summary> /// Delegate that represents CalcEngine functions. /// </summary> /// <param name="parms">List of <see cref="Expression"/> objects that represent the /// parameters to be used in the function call.</param> /// <returns>The function result.</returns> internal delegate object CalcEngineFunction(List<Expression> parms); }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Runtime; using Umbraco.Cms.Core.Serialization; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Sync; namespace Umbraco.Cms.Infrastructure.Sync { /// <summary> /// An <see cref="IServerMessenger"/> that works by storing messages in the database. /// </summary> public abstract class DatabaseServerMessenger : ServerMessengerBase, IDisposable { /* * this messenger writes ALL instructions to the database, * but only processes instructions coming from remote servers, * thus ensuring that instructions run only once */ private readonly IMainDom _mainDom; private readonly CacheRefresherCollection _cacheRefreshers; private readonly IServerRoleAccessor _serverRoleAccessor; private readonly ISyncBootStateAccessor _syncBootStateAccessor; private readonly ManualResetEvent _syncIdle; private readonly object _locko = new object(); private readonly IHostingEnvironment _hostingEnvironment; private readonly LastSyncedFileManager _lastSyncedFileManager; private DateTime _lastSync; private DateTime _lastPruned; private readonly Lazy<SyncBootState?> _initialized; private bool _syncing; private bool _disposedValue; private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private readonly CancellationToken _cancellationToken; /// <summary> /// Initializes a new instance of the <see cref="DatabaseServerMessenger"/> class. /// </summary> protected DatabaseServerMessenger( IMainDom mainDom, CacheRefresherCollection cacheRefreshers, IServerRoleAccessor serverRoleAccessor, ILogger<DatabaseServerMessenger> logger, bool distributedEnabled, ISyncBootStateAccessor syncBootStateAccessor, IHostingEnvironment hostingEnvironment, ICacheInstructionService cacheInstructionService, IJsonSerializer jsonSerializer, LastSyncedFileManager lastSyncedFileManager, IOptions<GlobalSettings> globalSettings) : base(distributedEnabled) { _cancellationToken = _cancellationTokenSource.Token; _mainDom = mainDom; _cacheRefreshers = cacheRefreshers; _serverRoleAccessor = serverRoleAccessor; _hostingEnvironment = hostingEnvironment; Logger = logger; _syncBootStateAccessor = syncBootStateAccessor; CacheInstructionService = cacheInstructionService; JsonSerializer = jsonSerializer; _lastSyncedFileManager = lastSyncedFileManager; GlobalSettings = globalSettings.Value; _lastPruned = _lastSync = DateTime.UtcNow; _syncIdle = new ManualResetEvent(true); using (var process = Process.GetCurrentProcess()) { // See notes on _localIdentity LocalIdentity = Environment.MachineName // eg DOMAIN\SERVER + "/" + hostingEnvironment.ApplicationId // eg /LM/S3SVC/11/ROOT + " [P" + process.Id // eg 1234 + "/D" + AppDomain.CurrentDomain.Id // eg 22 + "] " + Guid.NewGuid().ToString("N").ToUpper(); // make it truly unique } _initialized = new Lazy<SyncBootState?>(InitializeWithMainDom); } public GlobalSettings GlobalSettings { get; } protected ILogger<DatabaseServerMessenger> Logger { get; } protected ICacheInstructionService CacheInstructionService { get; } protected IJsonSerializer JsonSerializer { get; } /// <summary> /// Gets the unique local identity of the executing AppDomain. /// </summary> /// <remarks> /// <para>It is not only about the "server" (machine name and appDomainappId), but also about /// an AppDomain, within a Process, on that server - because two AppDomains running at the same /// time on the same server (eg during a restart) are, practically, a LB setup.</para> /// <para>Practically, all we really need is the guid, the other infos are here for information /// and debugging purposes.</para> /// </remarks> protected string LocalIdentity { get; } /// <summary> /// Returns true if initialization was successfull (i.e. Is MainDom) /// </summary> protected bool EnsureInitialized() => _initialized.Value.HasValue; #region Messenger // we don't care if there are servers listed or not, // if distributed call is enabled we will make the call protected override bool RequiresDistributed(ICacheRefresher refresher, MessageType dispatchType) => EnsureInitialized() && DistributedEnabled; protected override void DeliverRemote( ICacheRefresher refresher, MessageType messageType, IEnumerable<object> ids = null, string json = null) { var idsA = ids?.ToArray(); if (GetArrayType(idsA, out Type idType) == false) { throw new ArgumentException("All items must be of the same type, either int or Guid.", nameof(ids)); } IEnumerable<RefreshInstruction> instructions = RefreshInstruction.GetInstructions(refresher, JsonSerializer, messageType, idsA, idType, json); CacheInstructionService.DeliverInstructions(instructions, LocalIdentity); } #endregion #region Sync /// <summary> /// Boots the messenger. /// </summary> private SyncBootState? InitializeWithMainDom() { // weight:10, must release *before* the published snapshot service, because once released // the service will *not* be able to properly handle our notifications anymore. const int weight = 10; var registered = _mainDom.Register( release: () => { lock (_locko) { _cancellationTokenSource.Cancel(); // no more syncs } // Wait a max of 3 seconds and then return, so that we don't block // the entire MainDom callbacks chain and prevent the AppDomain from // properly releasing MainDom - a timeout here means that one refresher // is taking too much time processing, however when it's done we will // not update lastId and stop everything. var idle = _syncIdle.WaitOne(3000); if (idle == false) { Logger.LogWarning("The wait lock timed out, application is shutting down. The current instruction batch will be re-processed."); } }, weight: weight); if (registered == false) { // return null if we cannot initialize return null; } return InitializeColdBootState(); } // <summary> /// Initializes a server that has never synchronized before. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// Callers MUST ensure thread-safety. /// </remarks> private SyncBootState InitializeColdBootState() { lock (_locko) { if (_cancellationToken.IsCancellationRequested) { return SyncBootState.Unknown; } SyncBootState syncState = _syncBootStateAccessor.GetSyncBootState(); if (syncState == SyncBootState.ColdBoot) { // Get the last id in the db and store it. // Note: Do it BEFORE initializing otherwise some instructions might get lost // when doing it before. Some instructions might run twice but this is not an issue. var maxId = CacheInstructionService.GetMaxInstructionId(); // if there is a max currently, or if we've never synced if (maxId > 0 || _lastSyncedFileManager.LastSyncedId < 0) { _lastSyncedFileManager.SaveLastSyncedId(maxId); } } return syncState; } } /// <summary> /// Synchronize the server (throttled). /// </summary> public override void Sync() { if (!EnsureInitialized()) { return; } lock (_locko) { if (_syncing) { return; } // Don't continue if we are released if (_cancellationToken.IsCancellationRequested) { return; } if ((DateTime.UtcNow - _lastSync) <= GlobalSettings.DatabaseServerMessenger.TimeBetweenSyncOperations) { return; } // Set our flag and the lock to be in it's original state (i.e. it can be awaited) _syncing = true; _syncIdle.Reset(); _lastSync = DateTime.UtcNow; } try { ProcessInstructionsResult result = CacheInstructionService.ProcessInstructions( _cacheRefreshers, _serverRoleAccessor.CurrentServerRole, _cancellationToken, LocalIdentity, _lastPruned, _lastSyncedFileManager.LastSyncedId); if (result.InstructionsWerePruned) { _lastPruned = _lastSync; } if (result.LastId > 0) { _lastSyncedFileManager.SaveLastSyncedId(result.LastId); } } finally { lock (_locko) { // We must reset our flag and signal any waiting locks _syncing = false; } _syncIdle.Set(); } } protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { _syncIdle?.Dispose(); } _disposedValue = true; } } /// <summary> /// Dispose /// </summary> public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Azure.Management.SiteRecovery.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.RecoveryServices { /// <summary> /// Definition of vault extended info operations for the Site Recovery /// extension. /// </summary> internal partial class VaultExtendedInfoOperations : IServiceOperations<RecoveryServicesManagementClient>, IVaultExtendedInfoOperations { /// <summary> /// Initializes a new instance of the VaultExtendedInfoOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VaultExtendedInfoOperations(RecoveryServicesManagementClient client) { this._client = client; } private RecoveryServicesManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.RecoveryServices.RecoveryServicesManagementClient. /// </summary> public RecoveryServicesManagementClient Client { get { return this._client; } } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Required. Create resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateExtendedInfoAsync(string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (extendedInfoArgs == null) { throw new ArgumentNullException("extendedInfoArgs"); } if (extendedInfoArgs.ContractVersion == null) { throw new ArgumentNullException("extendedInfoArgs.ContractVersion"); } if (extendedInfoArgs.ExtendedInfo == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfo"); } if (extendedInfoArgs.ExtendedInfoETag == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfoETag"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("extendedInfoArgs", extendedInfoArgs); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "CreateExtendedInfoAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-08-15"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject resourceExtendedInformationArgsValue = new JObject(); requestDoc = resourceExtendedInformationArgsValue; resourceExtendedInformationArgsValue["ContractVersion"] = extendedInfoArgs.ContractVersion; resourceExtendedInformationArgsValue["ExtendedInfo"] = extendedInfoArgs.ExtendedInfo; resourceExtendedInformationArgsValue["ExtendedInfoETag"] = extendedInfoArgs.ExtendedInfoETag; requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode >= HttpStatusCode.BadRequest) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public async Task<ResourceExtendedInformationResponse> GetExtendedInfoAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "GetExtendedInfoAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-08-15"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceExtendedInformationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceExtendedInformationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceExtendedInformation extendedInformationInstance = new ResourceExtendedInformation(); result.ResourceExtendedInformation = extendedInformationInstance; JToken resourceGroupNameValue = responseDoc["resourceGroupName"]; if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null) { string resourceGroupNameInstance = ((string)resourceGroupNameValue); extendedInformationInstance.ResourceGroupName = resourceGroupNameInstance; } JToken extendedInfoValue = responseDoc["extendedInfo"]; if (extendedInfoValue != null && extendedInfoValue.Type != JTokenType.Null) { string extendedInfoInstance = ((string)extendedInfoValue); extendedInformationInstance.ExtendedInfo = extendedInfoInstance; } JToken extendedInfoETagValue = responseDoc["extendedInfoETag"]; if (extendedInfoETagValue != null && extendedInfoETagValue.Type != JTokenType.Null) { string extendedInfoETagInstance = ((string)extendedInfoETagValue); extendedInformationInstance.ExtendedInfoETag = extendedInfoETagInstance; } JToken resourceIdValue = responseDoc["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); extendedInformationInstance.ResourceId = resourceIdInstance; } JToken resourceNameValue = responseDoc["resourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); extendedInformationInstance.ResourceName = resourceNameInstance; } JToken resourceTypeValue = responseDoc["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); extendedInformationInstance.ResourceType = resourceTypeInstance; } JToken subscriptionIdValue = responseDoc["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { Guid subscriptionIdInstance = Guid.Parse(((string)subscriptionIdValue)); extendedInformationInstance.SubscriptionId = subscriptionIdInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Optional. Update resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public async Task<ResourceExtendedInformationResponse> UpdateExtendedInfoAsync(string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (extendedInfoArgs != null) { if (extendedInfoArgs.ContractVersion == null) { throw new ArgumentNullException("extendedInfoArgs.ContractVersion"); } if (extendedInfoArgs.ExtendedInfo == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfo"); } if (extendedInfoArgs.ExtendedInfoETag == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfoETag"); } } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("extendedInfoArgs", extendedInfoArgs); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UpdateExtendedInfoAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-08-15"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceExtendedInformationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceExtendedInformationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceExtendedInformation extendedInformationInstance = new ResourceExtendedInformation(); result.ResourceExtendedInformation = extendedInformationInstance; JToken resourceGroupNameValue = responseDoc["resourceGroupName"]; if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null) { string resourceGroupNameInstance = ((string)resourceGroupNameValue); extendedInformationInstance.ResourceGroupName = resourceGroupNameInstance; } JToken extendedInfoValue = responseDoc["extendedInfo"]; if (extendedInfoValue != null && extendedInfoValue.Type != JTokenType.Null) { string extendedInfoInstance = ((string)extendedInfoValue); extendedInformationInstance.ExtendedInfo = extendedInfoInstance; } JToken extendedInfoETagValue = responseDoc["extendedInfoETag"]; if (extendedInfoETagValue != null && extendedInfoETagValue.Type != JTokenType.Null) { string extendedInfoETagInstance = ((string)extendedInfoETagValue); extendedInformationInstance.ExtendedInfoETag = extendedInfoETagInstance; } JToken resourceIdValue = responseDoc["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); extendedInformationInstance.ResourceId = resourceIdInstance; } JToken resourceNameValue = responseDoc["resourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); extendedInformationInstance.ResourceName = resourceNameInstance; } JToken resourceTypeValue = responseDoc["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); extendedInformationInstance.ResourceType = resourceTypeInstance; } JToken subscriptionIdValue = responseDoc["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { Guid subscriptionIdInstance = Guid.Parse(((string)subscriptionIdValue)); extendedInformationInstance.SubscriptionId = subscriptionIdInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='parameters'> /// Required. Upload Vault Certificate input parameters. /// </param> /// <param name='certFriendlyName'> /// Required. Certificate friendly name /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the upload certificate response /// </returns> public async Task<UploadCertificateResponse> UploadCertificateAsync(string resourceGroupName, string resourceName, CertificateArgs parameters, string certFriendlyName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (certFriendlyName == null) { throw new ArgumentNullException("certFriendlyName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("certFriendlyName", certFriendlyName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UploadCertificateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(certFriendlyName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-08-15"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject parametersValue = new JObject(); requestDoc = parametersValue; if (parameters.Properties != null) { if (parameters.Properties is ILazyCollection == false || ((ILazyCollection)parameters.Properties).IsInitialized) { JObject propertiesDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Properties) { string propertiesKey = pair.Key; string propertiesValue = pair.Value; propertiesDictionary[propertiesKey] = propertiesValue; } parametersValue["properties"] = propertiesDictionary; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result UploadCertificateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new UploadCertificateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { CertificateProperties propertiesInstance = new CertificateProperties(); result.Properties = propertiesInstance; JToken friendlyNameValue = propertiesValue2["friendlyName"]; if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null) { string friendlyNameInstance = ((string)friendlyNameValue); propertiesInstance.FriendlyName = friendlyNameInstance; } JToken globalAcsHostNameValue = propertiesValue2["globalAcsHostName"]; if (globalAcsHostNameValue != null && globalAcsHostNameValue.Type != JTokenType.Null) { string globalAcsHostNameInstance = ((string)globalAcsHostNameValue); propertiesInstance.GlobalAcsHostName = globalAcsHostNameInstance; } JToken globalAcsNamespaceValue = propertiesValue2["globalAcsNamespace"]; if (globalAcsNamespaceValue != null && globalAcsNamespaceValue.Type != JTokenType.Null) { string globalAcsNamespaceInstance = ((string)globalAcsNamespaceValue); propertiesInstance.GlobalAcsNamespace = globalAcsNamespaceInstance; } JToken globalAcsRPRealmValue = propertiesValue2["globalAcsRPRealm"]; if (globalAcsRPRealmValue != null && globalAcsRPRealmValue.Type != JTokenType.Null) { string globalAcsRPRealmInstance = ((string)globalAcsRPRealmValue); propertiesInstance.GlobalAcsRPRealm = globalAcsRPRealmInstance; } JToken resourceIdValue = propertiesValue2["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); propertiesInstance.ResourceId = resourceIdInstance; } } JToken clientRequestIdValue = responseDoc["ClientRequestId"]; if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null) { string clientRequestIdInstance = ((string)clientRequestIdValue); result.ClientRequestId = clientRequestIdInstance; } JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"]; if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null) { string correlationRequestIdInstance = ((string)correlationRequestIdValue); result.CorrelationRequestId = correlationRequestIdInstance; } JToken dateValue = responseDoc["Date"]; if (dateValue != null && dateValue.Type != JTokenType.Null) { string dateInstance = ((string)dateValue); result.Date = dateInstance; } JToken contentTypeValue = responseDoc["ContentType"]; if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null) { string contentTypeInstance = ((string)contentTypeValue); result.ContentType = contentTypeInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections; namespace EvoXP_Server { /// <summary> /// Summary description for TradeDepot. /// </summary> [Serializable] public class TradeDepot : Property { public SortedList _Inventory = new SortedList(); public string _desc; public double _factTechnology = 0.0; public double _factEconomic = 0.0; public double _factMilitant = 0.0; public double _factProductivity = 0.0; public double _factResearch = 0.0; public double _factLaw = 0.0; public double _factEnvironment = 0.0; public double _factFaith = 0.0; public GalaxyNode _belong = null; public bool _hasShipYard = false; public BankAccount _BA = null; public double _lastTaxes = 0.0; public TradeDepot(string name) : base(name, 100000) { _BA = new BankAccount("_(TD)_" + name); _BA.Deposit(10000000); } public override double Value() { double val = 0.0; for(int i = 0 ; i < _Inventory.Count ; i++ ) { InventoryDetail ID = _Inventory.GetByIndex(i) as InventoryDetail; val += CalculateWorthAt(ID) * ID._volume; } return val; } public void heartbeat(InventoryDetail ID, double dt) { // val += CalculateWorthAt(ID) * ID._volume; double prod = ID._factProduction * CalculateProduction(ID); double cons = ID._factDesire * CalculateConsumption(ID); if(ID._volume < ID._maxVolume) { ID._volume += prod * dt; } if(ID._volume > 0) { ID._volume -= cons * dt; } if(ID._volume < 0 ) ID._volume = 0; if(ID._volume > ID._maxVolume ) ID._volume = ID._maxVolume; } public double CalculateProduction(InventoryDetail ID) { if(ID._commodity._prodFunc==null) return 0.0; ExprEval EE = new ExprEval(); EE.SetFunc(ID._commodity._prodFunc); EE.Replace("TEK",_factTechnology); EE.Replace("ECO",_factEconomic); EE.Replace("MIL",_factMilitant); EE.Replace("PRO",_factProductivity); EE.Replace("RES",_factResearch); EE.Replace("LAW",_factLaw); EE.Replace("ENV",_factEnvironment); EE.Replace("FAI",_factFaith); EE.Replace("P", ID._factProduction); EE.Replace("D", ID._factDesire); return EE.Eval();; } public double CalculateConsumption(InventoryDetail ID) { if(ID._commodity._consFunc==null) return 0.0; ExprEval EE = new ExprEval(); EE.SetFunc(ID._commodity._consFunc); EE.Replace("TEK",_factTechnology); EE.Replace("ECO",_factEconomic); EE.Replace("MIL",_factMilitant); EE.Replace("PRO",_factProductivity); EE.Replace("RES",_factResearch); EE.Replace("LAW",_factLaw); EE.Replace("ENV",_factEnvironment); EE.Replace("FAI",_factFaith); EE.Replace("P", ID._factProduction); EE.Replace("D", ID._factDesire); return EE.Eval();; } public double CalculateWorthAt(InventoryDetail ID) { if(ID._commodity._calcFunc==null) return 0.0; ExprEval EE = new ExprEval(); EE.SetFunc(ID._commodity._calcFunc); EE.Replace("TEK",_factTechnology); EE.Replace("ECO",_factEconomic); EE.Replace("MIL",_factMilitant); EE.Replace("PRO",_factProductivity); EE.Replace("RES",_factResearch); EE.Replace("LAW",_factLaw); EE.Replace("ENV",_factEnvironment); EE.Replace("FAI",_factFaith); EE.Replace("P", ID._factProduction); EE.Replace("D", ID._factDesire); return EE.Eval();; } /* * Public Function zprice(ByVal b As Double, ByVal v As Double, ByVal des As Double, ByVal prod As Double) As Double sl = ln(b) / (des * 0.5 + 0.1) sh = -ln(b) / (-prod - 0.1) fl = Exp(sl * ((des * 0.5 + 0.1) - v)) fh = -Exp(sh * (v - (1 - prod - 0.1))) zprice = b + fl + fh End Function Public Function zprice2(b As Double, v1 As Double, v0 As Double, des As Double, prod As Double) As Double sl = ln(b) / (des * 0.5 + 0.1) sh = -ln(b) / (-prod - 0.1) fl1 = Exp(sl * ((des * 0.5 + 0.1) - v1)) / -sl fl0 = Exp(sl * ((des * 0.5 + 0.1) - v0)) / -sl fh1 = -Exp(sh * (v1 - (1 - prod - 0.1))) / sh fh0 = -Exp(sh * (v0 - (1 - prod - 0.1))) / sh zprice2 = b * (v1 - v0) + (fh1 - fh0) + (fl1 - fl0) End Function * */ private double ln(double v) { return Math.Log(v, Math.Exp(1)); } public double GetTaxes(double m) { //=EXP(-0.001 * C5+10) return Math.Exp(-0.001 * m + 10); } public double GetValue(InventoryDetail ID) { double v = ID._volume / ID._maxVolume; double b = CalculateWorthAt(ID); double sl = ln(b) / (ID._factDesire * 0.5 + 0.1); double sh = -ln(b) / (-ID._factProduction - 0.1); double fl = Math.Exp(sl * ((ID._factDesire * 0.5 + 0.1) - v)); double fh = -Math.Exp(sh * (v-(.9 - ID._factProduction))); return b + (fl * ID._factDesire) + (fh * ID._factProduction); } public double GetAvgValue(InventoryDetail ID, double v1i, double v0i) { double v0 = v0i / ID._maxVolume; double v1 = v1i / ID._maxVolume; if((v1-v0)==0) return 0.0; double b = CalculateWorthAt(ID); double sl = ln(b) / (ID._factDesire * 0.5 + 0.1); double sh = -ln(b) / (-ID._factProduction - 0.1); double fl0 = Math.Exp(sl * ((ID._factDesire * 0.5 + 0.1) - v0)) / (-sl); double fl1 = Math.Exp(sl * ((ID._factDesire * 0.5 + 0.1) - v1)) / (-sl); double fh0 = -Math.Exp(sh * (v0-(.9 - ID._factProduction))) / sh; double fh1 = -Math.Exp(sh * (v1-(.9 - ID._factProduction))) / sh; return (b * (v1 - v0) + ((fl1 - fl0) * ID._factDesire) + ((fh1 - fh0) * ID._factProduction))/(v1-v0);; } public InventoryDetail GetDetail(Commodity com) { int kAt = _Inventory.IndexOfKey(com._name); if(kAt>=0) { return (InventoryDetail) _Inventory.GetByIndex(kAt); } else { InventoryDetail ID = new InventoryDetail(com); _Inventory.Add(com._name, ID); return ID; } } public double GetFactor(string codename) { if(codename=="TEK") return _factTechnology; else if(codename=="ECO") return _factEconomic; else if(codename=="MIL") return _factMilitant; else if(codename=="PRO") return _factProductivity; else if(codename=="RES") return _factResearch; else if(codename=="LAW") return _factLaw; else if(codename=="ENV") return _factEnvironment; else if(codename=="FAI") return _factFaith; return 0.0; } public void SetFactor(string codename, double val) { if(codename=="TEK") _factTechnology = val; else if(codename=="ECO") _factEconomic = val; else if(codename=="MIL") _factMilitant = val; else if(codename=="PRO") _factProductivity = val; else if(codename=="RES") _factResearch = val; else if(codename=="LAW") _factLaw = val; else if(codename=="ENV") _factEnvironment = val; else if(codename=="FAI") _factFaith = val; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding; using System.Diagnostics; [AddComponentMenu ("Pathfinding/Seeker")] /** Handles path calls for a single unit. * \ingroup relevant * This is a component which is meant to be attached to a single unit (AI, Robot, Player, whatever) to handle it's pathfinding calls. * It also handles post-processing of paths using modifiers. * \see \ref calling-pathfinding */ public class Seeker : MonoBehaviour { //====== SETTINGS ====== /* Recalculate last queried path when a graph changes. \see AstarPath.OnGraphsUpdated */ //public bool recalcOnGraphChange = true; public bool drawGizmos = true; public bool detailedGizmos = false; /** Saves nearest nodes for previous path to enable faster Get Nearest Node calls. * This variable basically does not a affect anything at the moment. So it is hidden in the inspector */ [HideInInspector] public bool saveGetNearestHints = true; public StartEndModifier startEndModifier = new StartEndModifier (); [HideInInspector] public TagMask traversableTags = new TagMask (-1,-1); [HideInInspector] /** Penalties for each tag. * Tag 0 which is the default tag, will have added a penalty of tagPenalties[0]. * These should only be positive values since the A* algorithm cannot handle negative penalties. * \note This array should always have a length of 32. * \see Pathfinding.Path.tagPenalties */ public int[] tagPenalties = new int[32]; //====== SETTINGS ====== //public delegate Path PathReturn (Path p); /** Callback for when a path is completed. Movement scripts should register to this delegate.\n * A temporary callback can also be set when calling StartPath, but that delegate will only be called for that path */ public OnPathDelegate pathCallback; /** Called before pathfinding is started */ public OnPathDelegate preProcessPath; /** For anything which requires the original nodes (Node[]) (before modifiers) to work */ public OnPathDelegate postProcessOriginalPath; /** Anything which only modifies the positions (Vector3[]) */ public OnPathDelegate postProcessPath; //public GetNextTargetDelegate getNextTarget; //DEBUG //public Path lastCompletedPath; [System.NonSerialized] public List<Vector3> lastCompletedVectorPath; [System.NonSerialized] public List<Node> lastCompletedNodePath; //END DEBUG /** The current path */ [System.NonSerialized] protected Path path; /** Previous path. Used to draw gizmos */ private Path prevPath; /** Returns #path */ public Path GetCurrentPath () { return path; } private Node startHint; private Node endHint; private OnPathDelegate onPathDelegate; private OnPathDelegate onPartialPathDelegate; /** Temporary callback only called for the current path. This value is set by the StartPath functions */ private OnPathDelegate tmpPathCallback; /** The path ID of the last path queried */ protected uint lastPathID = 0; #if PhotonImplementation public Seeker () { Awake (); } #endif /** Initializes a few variables */ public void Awake () { onPathDelegate = OnPathComplete; onPartialPathDelegate = OnPartialPathComplete; startEndModifier.Awake (this); } /** Cleans up some variables. * Releases any eventually claimed paths. * Calls OnDestroy on the #startEndModifier. * * \see ReleaseClaimedPath * \see startEndModifier */ public void OnDestroy () { ReleaseClaimedPath (); startEndModifier.OnDestroy (this); } /** Releases an eventual claimed path. * The seeker keeps the latest path claimed so it can draw gizmos. * In some cases this might not be desireable and you want it released. * In that case, you can call this method to release it (not that path gizmos will then not be drawn). * * If you didn't understand anything from the description above, you probably don't need to use this method. */ public void ReleaseClaimedPath () { if (prevPath != null) { prevPath.ReleaseSilent (this); prevPath = null; } } private List<IPathModifier> modifiers = new List<IPathModifier> (); public void RegisterModifier (IPathModifier mod) { if (modifiers == null) { modifiers = new List<IPathModifier> (1); } modifiers.Add (mod); } public void DeregisterModifier (IPathModifier mod) { if (modifiers == null) { return; } modifiers.Remove (mod); } public enum ModifierPass { PreProcess, PostProcessOriginal, PostProcess } /** Post Processes the path. * This will run any modifiers attached to this GameObject on the path. * This is identical to calling RunModifiers(ModifierPass.PostProcess, path) * \see RunModifiers * \since Added in 3.2 */ public void PostProcess (Path p) { RunModifiers (ModifierPass.PostProcess,p); } /** Runs modifiers on path \a p */ public void RunModifiers (ModifierPass pass, Path p) { //Sort the modifiers based on priority (bubble sort (slow but since it's a small list, it works good)) bool changed = true; while (changed) { changed = false; for (int i=0;i<modifiers.Count-1;i++) { if (modifiers[i].Priority < modifiers[i+1].Priority) { IPathModifier tmp = modifiers[i]; modifiers[i] = modifiers[i+1]; modifiers[i+1] = tmp; changed = true; } } } //Call eventual delegates switch (pass) { case ModifierPass.PreProcess: if (preProcessPath != null) preProcessPath (p); break; case ModifierPass.PostProcessOriginal: if (postProcessOriginalPath != null) postProcessOriginalPath (p); break; case ModifierPass.PostProcess: if (postProcessPath != null) postProcessPath (p); break; } //No modifiers, then exit here if (modifiers.Count == 0) return; ModifierData prevOutput = ModifierData.All; IPathModifier prevMod = modifiers[0]; //Loop through all modifiers and apply post processing for (int i=0;i<modifiers.Count;i++) { //Cast to MonoModifier, i.e modifiers attached as scripts to the game object MonoModifier mMod = modifiers[i] as MonoModifier; //Ignore modifiers which are not enabled if (mMod != null && !mMod.enabled) continue; switch (pass) { case ModifierPass.PreProcess: modifiers[i].PreProcess (p); break; case ModifierPass.PostProcessOriginal: modifiers[i].ApplyOriginal (p); break; case ModifierPass.PostProcess: //Convert the path if necessary to match the required input for the modifier ModifierData newInput = ModifierConverter.Convert (p,prevOutput,modifiers[i].input); if (newInput != ModifierData.None) { modifiers[i].Apply (p,newInput); prevOutput = modifiers[i].output; } else { UnityEngine.Debug.Log ("Error converting "+(i > 0 ? prevMod.GetType ().Name : "original")+"'s output to "+(modifiers[i].GetType ().Name)+"'s input.\nTry rearranging the modifier priorities on the Seeker."); prevOutput = ModifierData.None; } prevMod = modifiers[i]; break; } if (prevOutput == ModifierData.None) { break; } } } /** Is the current path done calculating. * Returns true if the current #path has been returned or if the #path is null. * * \note Do not confuse this with Pathfinding.Path.IsDone. They do mostly return the same value, but not always. * * \since Added in 3.0.8 * \version Behaviour changed in 3.2 * */ public bool IsDone () { return path == null || path.GetState() >= PathState.Returned; } /** Called when a path has completed. * This should have been implemented as optional parameter values, but that didn't seem to work very well with delegates (the values weren't the default ones) * \see OnPathComplete(Path,bool,bool) */ public void OnPathComplete (Path p) { OnPathComplete (p,true,true); } /** Called when a path has completed. * Will post process it and return it by calling #tmpPathCallback and #pathCallback */ public void OnPathComplete (Path p, bool runModifiers, bool sendCallbacks) { AstarProfiler.StartProfile ("Seeker OnPathComplete"); if (p != null && p != path && sendCallbacks) { return; } if (this == null || p == null || p != path) return; if (!path.error && runModifiers) { AstarProfiler.StartProfile ("Seeker Modifiers"); //This will send the path for post processing to modifiers attached to this Seeker RunModifiers (ModifierPass.PostProcessOriginal, path); //This will send the path for post processing to modifiers attached to this Seeker RunModifiers (ModifierPass.PostProcess, path); AstarProfiler.EndProfile (); } if (sendCallbacks) { p.Claim (this); AstarProfiler.StartProfile ("Seeker Callbacks"); lastCompletedNodePath = p.path; lastCompletedVectorPath = p.vectorPath; //This will send the path to the callback (if any) specified when calling StartPath if (tmpPathCallback != null) { tmpPathCallback (p); } //This will send the path to any script which has registered to the callback if (pathCallback != null) { pathCallback (p); } //Recycle the previous path if (prevPath != null) { prevPath.ReleaseSilent (this); } prevPath = p; //If not drawing gizmos, then storing prevPath is quite unecessary //So clear it and set prevPath to null if (!drawGizmos) ReleaseClaimedPath (); AstarProfiler.EndProfile(); } AstarProfiler.EndProfile (); } /** Called for each path in a MultiTargetPath. Only post processes the path, does not return it. * \astarpro */ public void OnPartialPathComplete (Path p) { OnPathComplete (p,true,false); } /** Called once for a MultiTargetPath. Only returns the path, does not post process. * \astarpro */ public void OnMultiPathComplete (Path p) { OnPathComplete (p,false,true); } /*public void OnEnable () { //AstarPath.OnGraphsUpdated += CheckPathValidity; } public void OnDisable () { //AstarPath.OnGraphsUpdated -= CheckPathValidity; }*/ /*public void CheckPathValidity (AstarPath active) { /*if (!recalcOnGraphChange) { return; } //Debug.Log ("Checking Path Validity"); //Debug.Break (); if (lastCompletedPath != null && !lastCompletedPath.error) { //Debug.Log ("Checking Path Validity"); StartPath (transform.position,lastCompletedPath.endPoint); /*if (!lastCompletedPath.path[0].IsWalkable (lastCompletedPath)) { StartPath (transform.position,lastCompletedPath.endPoint); return; } for (int i=0;i<lastCompletedPath.path.Length-1;i++) { if (!lastCompletedPath.path[i].ContainsConnection (lastCompletedPath.path[i+1],lastCompletedPath)) { StartPath (transform.position,lastCompletedPath.endPoint); return; } Debug.DrawLine (lastCompletedPath.path[i].position,lastCompletedPath.path[i+1].position,Color.cyan); }* }* }*/ //The frame the last call was made from this Seeker //private int lastPathCall = -1000; /** Returns a new path instance. The path will be taken from the path pool if path recycling is turned on.\n * This path can be sent to #StartPath(Path,OnPathDelegate,int) with no change, but if no change is required #StartPath(Vector3,Vector3,OnPathDelegate) does just that. * \code Seeker seeker = GetComponent (typeof(Seeker)) as Seeker; * Path p = seeker.GetNewPath (transform.position, transform.position+transform.forward*100); * p.nnConstraint = NNConstraint.Default; \endcode */ public Path GetNewPath (Vector3 start, Vector3 end) { //Construct a path with start and end points Path p = ABPath.Construct (start, end, null); return p; } /** Call this function to start calculating a path. * \param start The start point of the path * \param end The end point of the path */ public Path StartPath (Vector3 start, Vector3 end) { return StartPath (start,end,null,-1); } /** Call this function to start calculating a path. * \param start The start point of the path * \param end The end point of the path * \param callback The function to call when the path has been calculated * * \a callback will be called when the path has completed. * \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */ public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback) { return StartPath (start,end,callback,-1); } /** Call this function to start calculating a path. * \param start The start point of the path * \param end The end point of the path * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. * * \a callback will be called when the path has completed. * \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */ public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback, int graphMask) { Path p = GetNewPath (start,end); return StartPath (p, callback, graphMask); } /** Call this function to start calculating a path. * \param p The path to start calculating * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. \astarproParam * * \a callback will be called when the path has completed. * \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */ public Path StartPath (Path p, OnPathDelegate callback = null, int graphMask = -1) { p.enabledTags = traversableTags.tagsChange; p.tagPenalties = tagPenalties; //In case a multi target path has been specified, call special logic if (p.GetType () == typeof (MultiTargetPath)) { return StartMultiTargetPath (p as MultiTargetPath,callback); } //Cancel a previously requested path is it has not been processed yet and also make sure that it has not been recycled and used somewhere else if (path != null && path.GetState() <= PathState.Processing && lastPathID == path.pathID) { path.LogError ("Canceled path because a new one was requested\nGameObject: "+gameObject.name); //No callback should be sent for the canceled path } path = p; path.callback += onPathDelegate; path.nnConstraint.graphMask = graphMask; tmpPathCallback = callback; //Set the Get Nearest Node hints if they have not already been set /*if (path.startHint == null) path.startHint = startHint; if (path.endHint == null) path.endHint = endHint; */ //Save the path id so we can make sure that if we cancel a path (see above) it should not have been recycled yet. lastPathID = path.pathID; //Delay the path call by one frame if it was sent the same frame as the previous call /*if (lastPathCall == Time.frameCount) { StartCoroutine (DelayPathStart (path)); return path; }*/ //lastPathCall = Time.frameCount; //Pre process the path RunModifiers (ModifierPass.PreProcess, path); //Send the request to the pathfinder AstarPath.StartPath (path); return path; } /** Starts a Multi Target Path from one start point to multiple end points. A Multi Target Path will search for all the end points in one search and will return all paths if \a pathsForAll is true, or only the shortest one if \a pathsForAll is false.\n * \param start The start point of the path * \param endPoints The end points of the path * \param pathsForAll Indicates whether or not a path to all end points should be searched for or only to the closest one * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. \astarproParam * * \a callback and #pathCallback will be called when the path has completed. \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) * \astarpro * \see Pathfinding.MultiTargetPath * \see \ref MultiTargetPathExample.cs "Example of how to use multi-target-paths" */ public MultiTargetPath StartMultiTargetPath (Vector3 start, Vector3[] endPoints, bool pathsForAll, OnPathDelegate callback = null, int graphMask = -1) { MultiTargetPath p = MultiTargetPath.Construct (start, endPoints, null, null); p.pathsForAll = pathsForAll; return StartMultiTargetPath (p, callback, graphMask); } /** Starts a Multi Target Path from multiple start points to a single target point. A Multi Target Path will search from all start points to the target point in one search and will return all paths if \a pathsForAll is true, or only the shortest one if \a pathsForAll is false.\n * \param startPoints The start points of the path * \param end The end point of the path * \param pathsForAll Indicates whether or not a path from all start points should be searched for or only to the closest one * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. \astarproParam * * \a callback and #pathCallback will be called when the path has completed. \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) * \astarpro * \see Pathfinding.MultiTargetPath * \see \ref MultiTargetPathExample.cs "Example of how to use multi-target-paths" */ public MultiTargetPath StartMultiTargetPath (Vector3[] startPoints, Vector3 end, bool pathsForAll, OnPathDelegate callback = null, int graphMask = -1) { MultiTargetPath p = MultiTargetPath.Construct (startPoints, end, null, null); p.pathsForAll = pathsForAll; return StartMultiTargetPath (p, callback, graphMask); } /** Starts a Multi Target Path. Takes a MultiTargetPath and wires everything up for it to send callbacks to the seeker for post-processing.\n * \param p The path to start calculating * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. \astarproParam * * \a callback and #pathCallback will be called when the path has completed. \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) * \astarpro * \see Pathfinding.MultiTargetPath * \see \ref MultiTargetPathExample.cs "Example of how to use multi-target-paths" */ public MultiTargetPath StartMultiTargetPath (MultiTargetPath p, OnPathDelegate callback = null, int graphMask = -1) { //Cancel a previously requested path is it has not been processed yet and also make sure that it has not been recycled and used somewhere else if (path != null && path.GetState () <= PathState.Processing && lastPathID == path.pathID) { path.LogError ("Canceled path because a new one was requested"); //No callback should be sent for the canceled path } OnPathDelegate[] callbacks = new OnPathDelegate[p.targetPoints.Length]; for (int i=0;i<callbacks.Length;i++) { callbacks[i] = onPartialPathDelegate; } p.callbacks = callbacks; p.callback += OnMultiPathComplete; p.nnConstraint.graphMask = graphMask; path = p; tmpPathCallback = callback; //Save the path id so we can make sure that if we cancel a path (see above) it should not have been recycled yet. lastPathID = path.pathID; //Delay the path call by one frame if it was sent the same frame as the previous call /*if (lastPathCall == Time.frameCount) { StartCoroutine (DelayPathStart (path)); return p; } lastPathCall = Time.frameCount;*/ //Pre process the path RunModifiers (ModifierPass.PreProcess, path); //Send the request to the pathfinder AstarPath.StartPath (path); return p; } public IEnumerator DelayPathStart (Path p) { yield return 0; //lastPathCall = Time.frameCount; RunModifiers (ModifierPass.PreProcess, p); AstarPath.StartPath (p); } #if !PhotonImplementation public void OnDrawGizmos () { if (lastCompletedNodePath == null || !drawGizmos) { return; } if (detailedGizmos) { Gizmos.color = new Color (0.7F,0.5F,0.1F,0.5F); if (lastCompletedNodePath != null) { for (int i=0;i<lastCompletedNodePath.Count-1;i++) { Gizmos.DrawLine ((Vector3)lastCompletedNodePath[i].position,(Vector3)lastCompletedNodePath[i+1].position); } } } Gizmos.color = new Color (0,1F,0,1F); if (lastCompletedVectorPath != null) { for (int i=0;i<lastCompletedVectorPath.Count-1;i++) { Gizmos.DrawLine (lastCompletedVectorPath[i],lastCompletedVectorPath[i+1]); } } } #endif }
/* * Copyright 2015 Dominick Baier, Brock Allen * * 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.Linq; using System.Security.Claims; using System.Threading.Tasks; using IdentityModel; using IdentityServer3.Core; using IdentityServer3.Core.Extensions; using IdentityServer3.Core.Models; using IdentityServer3.Core.Services.Default; namespace FulcrumSeed.WebAuth.App_Packages.IdentityServer3.AspNetIdentity { public class AspNetIdentityUserService<TUser, TKey> : UserServiceBase where TUser : class, Microsoft.AspNet.Identity.IUser<TKey>, new() where TKey : IEquatable<TKey> { public string DisplayNameClaimType { get; set; } public bool EnableSecurityStamp { get; set; } protected readonly Microsoft.AspNet.Identity.UserManager<TUser, TKey> userManager; protected readonly Func<string, TKey> ConvertSubjectToKey; public AspNetIdentityUserService(Microsoft.AspNet.Identity.UserManager<TUser, TKey> userManager, Func<string, TKey> parseSubject = null) { if (userManager == null) throw new ArgumentNullException("userManager"); this.userManager = userManager; if (parseSubject != null) { ConvertSubjectToKey = parseSubject; } else { var keyType = typeof (TKey); if (keyType == typeof (string)) ConvertSubjectToKey = subject => (TKey) ParseString(subject); else if (keyType == typeof (int)) ConvertSubjectToKey = subject => (TKey) ParseInt(subject); else if (keyType == typeof (uint)) ConvertSubjectToKey = subject => (TKey) ParseUInt32(subject); else if (keyType == typeof (long)) ConvertSubjectToKey = subject => (TKey) ParseLong(subject); else if (keyType == typeof (Guid)) ConvertSubjectToKey = subject => (TKey) ParseGuid(subject); else { throw new InvalidOperationException("Key type not supported"); } } EnableSecurityStamp = true; } object ParseString(string sub) { return sub; } object ParseInt(string sub) { int key; if (!Int32.TryParse(sub, out key)) return 0; return key; } object ParseUInt32(string sub) { uint key; if (!UInt32.TryParse(sub, out key)) return 0; return key; } object ParseLong(string sub) { long key; if (!Int64.TryParse(sub, out key)) return 0; return key; } object ParseGuid(string sub) { Guid key; if (!Guid.TryParse(sub, out key)) return Guid.Empty; return key; } public override async Task GetProfileDataAsync(ProfileDataRequestContext ctx) { var subject = ctx.Subject; var requestedClaimTypes = ctx.RequestedClaimTypes; if (subject == null) throw new ArgumentNullException("subject"); TKey key = ConvertSubjectToKey(subject.GetSubjectId()); var acct = await userManager.FindByIdAsync(key); if (acct == null) { throw new ArgumentException("Invalid subject identifier"); } var claims = await GetClaimsFromAccount(acct); if (requestedClaimTypes != null && requestedClaimTypes.Any()) { claims = claims.Where(x => requestedClaimTypes.Contains(x.Type)); } ctx.IssuedClaims = claims; } protected virtual async Task<IEnumerable<Claim>> GetClaimsFromAccount(TUser user) { var claims = new List<Claim>{ new Claim(Constants.ClaimTypes.Subject, user.Id.ToString()), new Claim(Constants.ClaimTypes.PreferredUserName, user.UserName), }; if (userManager.SupportsUserEmail) { var email = await userManager.GetEmailAsync(user.Id); if (!String.IsNullOrWhiteSpace(email)) { claims.Add(new Claim(Constants.ClaimTypes.Email, email)); var verified = await userManager.IsEmailConfirmedAsync(user.Id); claims.Add(new Claim(Constants.ClaimTypes.EmailVerified, verified ? "true" : "false")); } } if (userManager.SupportsUserPhoneNumber) { var phone = await userManager.GetPhoneNumberAsync(user.Id); if (!String.IsNullOrWhiteSpace(phone)) { claims.Add(new Claim(Constants.ClaimTypes.PhoneNumber, phone)); var verified = await userManager.IsPhoneNumberConfirmedAsync(user.Id); claims.Add(new Claim(Constants.ClaimTypes.PhoneNumberVerified, verified ? "true" : "false")); } } if (userManager.SupportsUserClaim) { claims.AddRange(await userManager.GetClaimsAsync(user.Id)); } if (userManager.SupportsUserRole) { var roleClaims = from role in await userManager.GetRolesAsync(user.Id) select new Claim(Constants.ClaimTypes.Role, role); claims.AddRange(roleClaims); } return claims; } protected virtual async Task<string> GetDisplayNameForAccountAsync(TKey userID) { var user = await userManager.FindByIdAsync(userID); var claims = await GetClaimsFromAccount(user); Claim nameClaim = null; if (DisplayNameClaimType != null) { nameClaim = claims.FirstOrDefault(x => x.Type == DisplayNameClaimType); } if (nameClaim == null) nameClaim = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.Name); if (nameClaim == null) nameClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.Name); if (nameClaim != null) return nameClaim.Value; return user.UserName; } protected async virtual Task<TUser> FindUserAsync(string username) { return await userManager.FindByNameAsync(username); } protected virtual Task<AuthenticateResult> PostAuthenticateLocalAsync(TUser user, SignInMessage message) { return Task.FromResult<AuthenticateResult>(null); } public override async Task AuthenticateLocalAsync(LocalAuthenticationContext ctx) { var username = ctx.UserName; var password = ctx.Password; var message = ctx.SignInMessage; ctx.AuthenticateResult = null; if (userManager.SupportsUserPassword) { var user = await FindUserAsync(username); if (user != null) { if (userManager.SupportsUserLockout && await userManager.IsLockedOutAsync(user.Id)) { return; } if (await userManager.CheckPasswordAsync(user, password)) { if (userManager.SupportsUserLockout) { await userManager.ResetAccessFailedCountAsync(user.Id); } var result = await PostAuthenticateLocalAsync(user, message); if (result == null) { var claims = await GetClaimsForAuthenticateResult(user); result = new AuthenticateResult(user.Id.ToString(), await GetDisplayNameForAccountAsync(user.Id), claims); } ctx.AuthenticateResult = result; } else if (userManager.SupportsUserLockout) { await userManager.AccessFailedAsync(user.Id); } } } } protected virtual async Task<IEnumerable<Claim>> GetClaimsForAuthenticateResult(TUser user) { List<Claim> claims = new List<Claim>(); if (EnableSecurityStamp && userManager.SupportsUserSecurityStamp) { var stamp = await userManager.GetSecurityStampAsync(user.Id); if (!String.IsNullOrWhiteSpace(stamp)) { claims.Add(new Claim("security_stamp", stamp)); } } return claims; } public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext ctx) { var externalUser = ctx.ExternalIdentity; var message = ctx.SignInMessage; if (externalUser == null) { throw new ArgumentNullException("externalUser"); } var user = await userManager.FindAsync(new Microsoft.AspNet.Identity.UserLoginInfo(externalUser.Provider, externalUser.ProviderId)); if (user == null) { ctx.AuthenticateResult = await ProcessNewExternalAccountAsync(externalUser.Provider, externalUser.ProviderId, externalUser.Claims); } else { ctx.AuthenticateResult = await ProcessExistingExternalAccountAsync(user.Id, externalUser.Provider, externalUser.ProviderId, externalUser.Claims); } } protected virtual async Task<AuthenticateResult> ProcessNewExternalAccountAsync(string provider, string providerId, IEnumerable<Claim> claims) { var user = await TryGetExistingUserFromExternalProviderClaimsAsync(provider, claims); if (user == null) { user = await InstantiateNewUserFromExternalProviderAsync(provider, providerId, claims); if (user == null) throw new InvalidOperationException("CreateNewAccountFromExternalProvider returned null"); var createResult = await userManager.CreateAsync(user); if (!createResult.Succeeded) { return new AuthenticateResult(createResult.Errors.First()); } } var externalLogin = new Microsoft.AspNet.Identity.UserLoginInfo(provider, providerId); var addExternalResult = await userManager.AddLoginAsync(user.Id, externalLogin); if (!addExternalResult.Succeeded) { return new AuthenticateResult(addExternalResult.Errors.First()); } var result = await AccountCreatedFromExternalProviderAsync(user.Id, provider, providerId, claims); if (result != null) return result; return await SignInFromExternalProviderAsync(user.Id, provider); } protected virtual Task<TUser> InstantiateNewUserFromExternalProviderAsync(string provider, string providerId, IEnumerable<Claim> claims) { var user = new TUser() { UserName = Guid.NewGuid().ToString("N") }; return Task.FromResult(user); } protected virtual Task<TUser> TryGetExistingUserFromExternalProviderClaimsAsync(string provider, IEnumerable<Claim> claims) { return Task.FromResult<TUser>(null); } protected virtual async Task<AuthenticateResult> AccountCreatedFromExternalProviderAsync(TKey userID, string provider, string providerId, IEnumerable<Claim> claims) { claims = await SetAccountEmailAsync(userID, claims); claims = await SetAccountPhoneAsync(userID, claims); return await UpdateAccountFromExternalClaimsAsync(userID, provider, providerId, claims); } protected virtual async Task<AuthenticateResult> SignInFromExternalProviderAsync(TKey userID, string provider) { var user = await userManager.FindByIdAsync(userID); var claims = await GetClaimsForAuthenticateResult(user); return new AuthenticateResult( userID.ToString(), await GetDisplayNameForAccountAsync(userID), claims, authenticationMethod: Constants.AuthenticationMethods.External, identityProvider: provider); } protected virtual async Task<AuthenticateResult> UpdateAccountFromExternalClaimsAsync(TKey userID, string provider, string providerId, IEnumerable<Claim> claims) { var existingClaims = await userManager.GetClaimsAsync(userID); var intersection = existingClaims.Intersect(claims, new ClaimComparer()); var newClaims = claims.Except(intersection, new ClaimComparer()); foreach (var claim in newClaims) { var result = await userManager.AddClaimAsync(userID, claim); if (!result.Succeeded) { return new AuthenticateResult(result.Errors.First()); } } return null; } protected virtual async Task<AuthenticateResult> ProcessExistingExternalAccountAsync(TKey userID, string provider, string providerId, IEnumerable<Claim> claims) { return await SignInFromExternalProviderAsync(userID, provider); } protected virtual async Task<IEnumerable<Claim>> SetAccountEmailAsync(TKey userID, IEnumerable<Claim> claims) { var email = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.Email); if (email != null) { var userEmail = await userManager.GetEmailAsync(userID); if (userEmail == null) { // if this fails, then presumably the email is already associated with another account // so ignore the error and let the claim pass thru var result = await userManager.SetEmailAsync(userID, email.Value); if (result.Succeeded) { var email_verified = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.EmailVerified); if (email_verified != null && email_verified.Value == "true") { var token = await userManager.GenerateEmailConfirmationTokenAsync(userID); await userManager.ConfirmEmailAsync(userID, token); } var emailClaims = new string[] { Constants.ClaimTypes.Email, Constants.ClaimTypes.EmailVerified }; return claims.Where(x => !emailClaims.Contains(x.Type)); } } } return claims; } protected virtual async Task<IEnumerable<Claim>> SetAccountPhoneAsync(TKey userID, IEnumerable<Claim> claims) { var phone = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.PhoneNumber); if (phone != null) { var userPhone = await userManager.GetPhoneNumberAsync(userID); if (userPhone == null) { // if this fails, then presumably the phone is already associated with another account // so ignore the error and let the claim pass thru var result = await userManager.SetPhoneNumberAsync(userID, phone.Value); if (result.Succeeded) { var phone_verified = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.PhoneNumberVerified); if (phone_verified != null && phone_verified.Value == "true") { var token = await userManager.GenerateChangePhoneNumberTokenAsync(userID, phone.Value); await userManager.ChangePhoneNumberAsync(userID, phone.Value, token); } var phoneClaims = new string[] { Constants.ClaimTypes.PhoneNumber, Constants.ClaimTypes.PhoneNumberVerified }; return claims.Where(x => !phoneClaims.Contains(x.Type)); } } } return claims; } public override async Task IsActiveAsync(IsActiveContext ctx) { var subject = ctx.Subject; if (subject == null) throw new ArgumentNullException("subject"); var id = subject.GetSubjectId(); TKey key = ConvertSubjectToKey(id); var acct = await userManager.FindByIdAsync(key); ctx.IsActive = false; if (acct != null) { if (EnableSecurityStamp && userManager.SupportsUserSecurityStamp) { var security_stamp = subject.Claims.Where(x => x.Type == "security_stamp").Select(x => x.Value).SingleOrDefault(); if (security_stamp != null) { var db_security_stamp = await userManager.GetSecurityStampAsync(key); if (db_security_stamp != security_stamp) { return; } } } ctx.IsActive = true; } } } }
/* Originally started back last year, and completely rewritten from the ground up to handle the * Profiles for InWorldz, LLC. * Modified again on 1/22/2011 by Beth Reischl to: * Pull a couple of DB queries from the Classifieds section that were not needed * Pulled a DB query from Profiles and modified another one. * Pulled out the queryParcelUUID from PickInfoUpdate method, this was resulting in null parcel IDs * being passed all the time. * Fixed the PickInfoUpdate and PickInfoRequest to show Username, Parcel Information, Region Name, (xyz) * coords for proper teleportation */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Xml; using OpenMetaverse; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Communications.Cache; using OpenSim.Data.SimpleDB; namespace OpenSimProfile.Modules.OpenProfile { public class OpenProfileModule : IRegionModule { // // Log module // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // // Module vars // private bool m_Enabled = true; private ConnectionFactory _connFactory; private ConnectionFactory _regionConnFactory; private string _currencyString = "I'z$"; public void Initialize(Scene scene, IConfigSource config) { if (!m_Enabled) return; //TODO: At some point, strip this out of the ini file, in Search Module, // we're going to recycle the Profile connection string however to make // life a bit easier. IConfig profileConfig = config.Configs["Startup"]; string connstr = profileConfig.GetString("core_connection_string", String.Empty); m_log.Info("[PROFILE] Profile module is activated"); //TODO: Bad assumption on my part that we're enabling it and the connstr is actually // valid, but I'm sick of dinking with this thing :) m_Enabled = true; _connFactory = new ConnectionFactory("MySQL", connstr); string storageConnStr = profileConfig.GetString("storage_connection_string", String.Empty); _regionConnFactory = new ConnectionFactory("MySQL", storageConnStr); IMoneyModule mm = scene.RequestModuleInterface<IMoneyModule>(); if (mm != null) { _currencyString = mm.GetCurrencySymbol(); } // Hook up events scene.EventManager.OnNewClient += OnNewClient; } public void PostInitialize() { if (!m_Enabled) return; } public void Close() { } public string Name { get { return "ProfileModule"; } } public bool IsSharedModule { get { return true; } } /// New Client Event Handler private void OnNewClient(IClientAPI client) { // Classifieds client.AddGenericPacketHandler("avatarclassifiedsrequest", HandleAvatarClassifiedsRequest); client.OnClassifiedInfoUpdate += ClassifiedInfoUpdate; client.OnClassifiedDelete += ClassifiedDelete; // Picks //TODO: there is an error generated here in the Grid as we've removed the // need for this and wrapped it down below. This needs to be fixed. // This applies to any reqeusts made for general info. //client.AddGenericPacketHandler("avatarpicksrequest", HandlePickInfoRequest); client.AddGenericPacketHandler("pickinforequest", HandlePickInfoRequest); client.OnPickInfoUpdate += PickInfoUpdate; client.OnPickDelete += PickDelete; // Notes client.AddGenericPacketHandler("avatarnotesrequest", HandleAvatarNotesRequest); client.OnAvatarNotesUpdate += AvatarNotesUpdate; // Interests client.OnRequestAvatarProperties += new RequestAvatarProperties(client_OnRequestAvatarProperties); client.OnAvatarInterestsUpdate += AvatarInterestsUpdate; } void client_OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID) { List<String> alist = new List<String>(); alist.Add(avatarID.ToString()); HandleAvatarInterestsRequest(remoteClient, alist); HandleAvatarPicksRequest(remoteClient, alist); } // Interests Handler public void HandleAvatarInterestsRequest(Object sender, List<String> args) { IClientAPI remoteClient = (IClientAPI)sender; UUID avatarID = new UUID(args[0]); using (ISimpleDB db = _connFactory.GetConnection()) { uint skillsMask = new uint(); string skillsText = String.Empty; uint wantToMask = new uint(); string wantToText = String.Empty; string languagesText = String.Empty; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); string query = "SELECT skillsMask, skillsText, wantToMask, wantToText, languagesText FROM users " + "WHERE UUID=?avatarID"; List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); foreach (Dictionary<string, string> row in results) { skillsMask = Convert.ToUInt16(row["skillsMask"]); skillsText = row["skillsText"]; wantToMask = Convert.ToUInt16(row["wantToMask"]); wantToText = row["wantToText"]; languagesText = row["languagesText"]; } remoteClient.SendAvatarInterestsReply(avatarID, skillsMask, skillsText, wantToMask, wantToText, languagesText); } } // Interests Update public void AvatarInterestsUpdate(IClientAPI remoteClient, uint querySkillsMask, string querySkillsText, uint queryWantToMask, string queryWantToText, string queryLanguagesText) { UUID avatarID = remoteClient.AgentId; using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?skillsMask", querySkillsMask); parms.Add("?skillsText", querySkillsText); parms.Add("?wantToMask", queryWantToMask); parms.Add("?wantToText", queryWantToText); parms.Add("?languagesText", queryLanguagesText); string query = "UPDATE users set skillsMask=?wantToMask, skillsText=?wantToText, wantToMask=?skillsMask, " + "wantToText=?skillsText, languagesText=?languagesText where UUID=?avatarID"; db.QueryNoResults(query, parms); } } // Classifieds Handler public void HandleAvatarClassifiedsRequest(Object sender, string method, List<String> args) { if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; UUID avatarID = new UUID(args[0]); using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>(); Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); string query = "SELECT classifieduuid, name from classifieds " + "WHERE creatoruuid=?avatarID"; List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); foreach (Dictionary<string, string> row in results) { classifieds[new UUID(row["classifieduuid"].ToString())] = row["name"].ToString(); } remoteClient.SendAvatarClassifiedReply(avatarID, classifieds); } } // Classifieds Update public const int MIN_CLASSIFIED_PRICE = 50; public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID, uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags, int queryclassifiedPrice, IClientAPI remoteClient) { // getting information lined up for the query UUID avatarID = remoteClient.AgentId; UUID regionUUID = remoteClient.Scene.RegionInfo.RegionID; UUID ParcelID = UUID.Zero; uint regionX = remoteClient.Scene.RegionInfo.RegionLocX; uint regionY = remoteClient.Scene.RegionInfo.RegionLocY; // m_log.DebugFormat("[CLASSIFIED]: Got the RegionX Location as: {0}, and RegionY as: {1}", regionX.ToString(), regionY.ToString()); string regionName = remoteClient.Scene.RegionInfo.RegionName; int creationDate = Util.UnixTimeSinceEpoch(); int expirationDate = creationDate + 604800; if (queryclassifiedPrice < MIN_CLASSIFIED_PRICE) { m_log.ErrorFormat("[CLASSIFIED]: Got a request for invalid price I'z${0} on a classified from {1}.", queryclassifiedPrice.ToString(), remoteClient.AgentId.ToString()); remoteClient.SendAgentAlertMessage("Error: The minimum price for a classified advertisement is I'z$" + MIN_CLASSIFIED_PRICE.ToString()+".", true); return; } // Check for hacked names that start with special characters if (!Char.IsLetterOrDigit(queryName, 0)) { m_log.ErrorFormat("[CLASSIFIED]: Got a hacked request from {0} for invalid name classified name: {1}", remoteClient.AgentId.ToString(), queryName); remoteClient.SendAgentAlertMessage("Error: The name of your classified must start with a letter or a number. No punctuation is allowed.", true); return; } // In case of insert, original values are the new values (by default) int origPrice = 0; using (ISimpleDB db = _connFactory.GetConnection()) { //if this is an existing classified make sure the client is the owner or don't touch it string existingCheck = "SELECT creatoruuid FROM classifieds WHERE classifieduuid = ?classifiedID"; Dictionary<string, object> checkParms = new Dictionary<string, object>(); checkParms.Add("?classifiedID", queryclassifiedID); List<Dictionary<string, string>> existingResults = db.QueryWithResults(existingCheck, checkParms); if (existingResults.Count > 0) { string existingAuthor = existingResults[0]["creatoruuid"]; if (existingAuthor != avatarID.ToString()) { m_log.ErrorFormat("[CLASSIFIED]: Got a request for from {0} to modify a classified from {1}: {2}", remoteClient.AgentId.ToString(), existingAuthor, queryclassifiedID.ToString()); remoteClient.SendAgentAlertMessage("Error: You do not have permission to modify that classified ad.", true); return; } } Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?classifiedID", queryclassifiedID); parms.Add("?category", queryCategory); parms.Add("?name", queryName); parms.Add("?description", queryDescription); //parms.Add("?parcelID", queryParcelID); parms.Add("?parentEstate", queryParentEstate); parms.Add("?snapshotID", querySnapshotID); parms.Add("?globalPos", queryGlobalPos); parms.Add("?classifiedFlags", queryclassifiedFlags); parms.Add("?classifiedPrice", queryclassifiedPrice); parms.Add("?creationDate", creationDate); parms.Add("?expirationDate", expirationDate); parms.Add("?regionUUID", regionUUID); parms.Add("?regionName", regionName); // We need parcelUUID from land to place in the query properly // However, there can be multiple Parcel UUIDS per region, // so we need to do some math from the classified entry // to the positioning of the avatar // The point we have is a global position value, which means // we need to to get the location with: (GlobalX / 256) - RegionX and // (GlobalY / 256) - RegionY for the values of the avatar standign position // then compare that to the parcels for the closest match // explode the GlobalPos value off the bat string origGlobPos = queryGlobalPos.ToString(); string tempAGlobPos = origGlobPos.Replace("<", String.Empty); string tempBGlobPos = tempAGlobPos.Replace(">", String.Empty); char[] delimiterChars = { ',', ' ' }; string[] globalPosBits = tempBGlobPos.Split(delimiterChars); uint tempAvaXLoc = Convert.ToUInt32(Convert.ToDouble(globalPosBits[0])); uint tempAvaYLoc = Convert.ToUInt32(Convert.ToDouble(globalPosBits[2])); uint avaXLoc = tempAvaXLoc - (256 * regionX); uint avaYLoc = tempAvaYLoc - (256 * regionY); //uint avatarPosX = (posGlobalX / 256) - regionX; parms.Add("?avaXLoc", avaXLoc.ToString()); parms.Add("?avaYLoc", avaYLoc.ToString()); string parcelLocate = "select uuid, MIN(ABS(UserLocationX - ?avaXLoc)) as minXValue, MIN(ABS(UserLocationY - ?avaYLoc)) as minYValue from land where RegionUUID=?regionUUID GROUP BY UserLocationX ORDER BY minXValue, minYValue LIMIT 1;"; using (ISimpleDB landDb = _regionConnFactory.GetConnection()) { List<Dictionary<string, string>> parcelLocated = landDb.QueryWithResults(parcelLocate, parms); foreach (Dictionary<string, string> row in parcelLocated) { ParcelID = new UUID(row["uuid"].ToString()); } } parms.Add("?parcelID", ParcelID); string queryClassifieds = "select * from classifieds where classifieduuid=?classifiedID AND creatoruuid=?avatarID"; List<Dictionary <string, string>> results = db.QueryWithResults(queryClassifieds, parms); bool isUpdate = false; int costToApply; string transactionDesc; if (results.Count != 0) { if (results.Count != 1) { remoteClient.SendAgentAlertMessage("Classified record is not consistent. Contact Support for assistance.", false); m_log.ErrorFormat("[CLASSIFIED]: Error, query for user {0} classified ad {1} returned {2} results.", avatarID.ToString(), queryclassifiedID.ToString(), results.Count.ToString()); return; } // This is an upgrade of a classified ad. Dictionary<string, string> row = results[0]; isUpdate = true; transactionDesc = "Classified price change"; origPrice = Convert.ToInt32(row["priceforlisting"]); // Also preserve original creation date and expiry. creationDate = Convert.ToInt32(row["creationdate"]); expirationDate = Convert.ToInt32(row["expirationdate"]); costToApply = queryclassifiedPrice - origPrice; if (costToApply < 0) costToApply = 0; } else { // This is the initial placement of the classified. transactionDesc = "Classified charge"; creationDate = Util.UnixTimeSinceEpoch(); expirationDate = creationDate + 604800; costToApply = queryclassifiedPrice; } EventManager.ClassifiedPaymentArgs paymentArgs = new EventManager.ClassifiedPaymentArgs(remoteClient.AgentId, queryclassifiedID, origPrice, queryclassifiedPrice, transactionDesc, true); if (costToApply > 0) { // Now check whether the payment is authorized by the currency system. ((Scene)remoteClient.Scene).EventManager.TriggerClassifiedPayment(remoteClient, paymentArgs); if (!paymentArgs.mIsAuthorized) return; // already reported to user by the check above. } string query; if (isUpdate) { query = "UPDATE classifieds set creationdate=?creationDate, " + "category=?category, name=?name, description=?description, parceluuid=?parcelID, " + "parentestate=?parentEstate, snapshotuuid=?snapshotID, simname=?regionName, posglobal=?globalPos, parcelname=?name, " + " classifiedflags=?classifiedFlags, priceforlisting=?classifiedPrice where classifieduuid=?classifiedID"; } else { query = "INSERT into classifieds (classifieduuid, creatoruuid, creationdate, expirationdate, category, name, " + "description, parceluuid, parentestate, snapshotuuid, simname, posglobal, parcelname, classifiedflags, priceforlisting) " + "VALUES (?classifiedID, ?avatarID, ?creationDate, ?expirationDate, ?category, ?name, ?description, ?parcelID, " + "?parentEstate, ?snapshotID, ?regionName, ?globalPos, ?name, ?classifiedFlags, ?classifiedPrice)"; } db.QueryNoResults(query, parms); if (costToApply > 0) // no refunds for lower prices { // Handle the actual money transaction here. paymentArgs.mIsPreCheck = false; // now call it again but for real this time ((Scene)remoteClient.Scene).EventManager.TriggerClassifiedPayment(remoteClient, paymentArgs); // Errors reported by the payment request above. } } } // Classifieds Delete public void ClassifiedDelete(UUID queryClassifiedID, IClientAPI remoteClient) { UUID avatarID = remoteClient.AgentId; UUID classifiedID = queryClassifiedID; using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?classifiedID", classifiedID); parms.Add("?avatarID", avatarID); string query = "delete from classifieds where classifieduuid=?classifiedID AND creatorUUID=?avatarID"; db.QueryNoResults(query, parms); } } // Picks Handler public void HandleAvatarPicksRequest(Object sender, List<String> args) { if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; UUID avatarID = new UUID(args[0]); using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<UUID, string> picksRequest = new Dictionary<UUID, string>(); Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); string query = "SELECT pickuuid, name from userpicks " + "WHERE creatoruuid=?avatarID"; List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); foreach (Dictionary<string, string> row in results) { picksRequest[new UUID(row["pickuuid"].ToString())] = row["name"].ToString(); } remoteClient.SendAvatarPicksReply(avatarID, picksRequest); } } // Picks Request public void HandlePickInfoRequest(Object sender, string method, List<String> args) { if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; UUID avatarID = new UUID(args[0]); UUID pickID = new UUID(args[1]); using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?pickID", pickID); string query = "SELECT * from userpicks WHERE creatoruuid=?avatarID AND pickuuid=?pickID"; List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); bool topPick = new bool(); UUID parcelUUID = new UUID(); string name = String.Empty; string description = String.Empty; UUID snapshotID = new UUID(); string userName = String.Empty; string originalName = String.Empty; string simName = String.Empty; Vector3 globalPos = new Vector3(); int sortOrder = new int(); bool enabled = new bool(); foreach (Dictionary<string, string> row in results) { topPick = Boolean.Parse(row["toppick"]); parcelUUID = UUID.Parse(row["parceluuid"]); name = row["name"]; description = row["description"]; snapshotID = UUID.Parse(row["snapshotuuid"]); userName = row["user"]; //userName = row["simname"]; originalName = row["originalname"]; simName = row["simname"]; globalPos = Vector3.Parse(row["posglobal"]); sortOrder = Convert.ToInt32(row["sortorder"]); enabled = Boolean.Parse(row["enabled"]); } remoteClient.SendPickInfoReply( pickID, avatarID, topPick, parcelUUID, name, description, snapshotID, userName, originalName, simName, globalPos, sortOrder, enabled); } } // Picks Update // pulled the original method due to UUID queryParcelID always being returned as null. If this is ever fixed to where // the viewer does in fact return the parcelID, then we can put this back in. //public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, // UUID queryParcelID, Vector3 queryGlobalPos, UUID snapshotID, int sortOrder, bool enabled) public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, Vector3 queryGlobalPos, UUID snapshotID, int sortOrder, bool enabled) { string userRegion = remoteClient.Scene.RegionInfo.RegionName; UUID userRegionID = remoteClient.Scene.RegionInfo.RegionID; string userFName = remoteClient.FirstName; string userLName = remoteClient.LastName; string avatarName = userFName + " " + userLName; UUID tempParcelUUID = UUID.Zero; UUID avatarID = remoteClient.AgentId; using (ISimpleDB db = _connFactory.GetConnection()) { //if this is an existing pick make sure the client is the owner or don't touch it string existingCheck = "SELECT creatoruuid FROM userpicks WHERE pickuuid = ?pickID"; Dictionary<string, object> checkParms = new Dictionary<string, object>(); checkParms.Add("?pickID", pickID); List<Dictionary<string, string>> existingResults = db.QueryWithResults(existingCheck, checkParms); if (existingResults.Count > 0) { if (existingResults[0]["creatoruuid"] != avatarID.ToString()) { return; } } //reassign creator id, it has to be this avatar creatorID = avatarID; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?pickID", pickID); parms.Add("?creatorID", creatorID); parms.Add("?topPick", topPick); parms.Add("?name", name); parms.Add("?desc", desc); parms.Add("?globalPos", queryGlobalPos); parms.Add("?snapshotID", snapshotID); parms.Add("?sortOrder", sortOrder); parms.Add("?enabled", enabled); parms.Add("?regionID", userRegionID); parms.Add("?regionName", userRegion); // we need to know if we're on a parcel or not, and if so, put it's UUID in there // viewer isn't giving it to us from what I can determine // TODO: David will need to clean this up cause more arrays are not my thing :) string queryParcelUUID = "select UUID from land where regionUUID=?regionID AND name=?name limit 1"; using (ISimpleDB landDb = _regionConnFactory.GetConnection()) { List<Dictionary<string, string>> simID = landDb.QueryWithResults(queryParcelUUID, parms); foreach (Dictionary<string, string> row in simID) { tempParcelUUID = UUID.Parse(row["UUID"]); } } UUID parcelUUID = tempParcelUUID; parms.Add("?parcelID", parcelUUID); m_log.Debug("Got parcel of: " + parcelUUID.ToString()); parms.Add("?parcelName", name); string queryPicksCount = "select COUNT(pickuuid) from userpicks where pickuuid=?pickID AND " + "creatoruuid=?creatorID"; List<Dictionary <string, string>> countList = db.QueryWithResults(queryPicksCount, parms); string query; string picksCount = String.Empty; foreach (Dictionary<string, string> row in countList) { picksCount = row["COUNT(pickuuid)"]; } parms.Add("?avatarName", avatarName); //TODO: We're defaulting topPick to false for the moment along with enabled default to True // We'll need to look over the conversion vs MySQL cause data truncating should not happen if(picksCount == "0") { query = "INSERT into userpicks (pickuuid, creatoruuid, toppick, parceluuid, name, description, snapshotuuid, user, " + "originalname, simname, posglobal, sortorder, enabled) " + "VALUES (?pickID, ?creatorID, 'false', ?parcelID, ?name, ?desc, ?snapshotID, " + "?avatarName, ?parcelName, ?regionName, ?globalPos, ?sortOrder, 'true')"; } else { query = "UPDATE userpicks set toppick='false', " + " parceluuid=?parcelID, name=?name, description=?desc, snapshotuuid=?snapshotID, " + "user=?avatarName, originalname=?parcelName, simname=?regionName, posglobal=?globalPos, sortorder=?sortOrder, " + " enabled='true' where pickuuid=?pickID"; } db.QueryNoResults(query, parms); } } // Picks Delete public void PickDelete(IClientAPI remoteClient, UUID queryPickID) { UUID avatarID = remoteClient.AgentId; using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?pickID", queryPickID); parms.Add("?avatarID", avatarID); string query = "delete from userpicks where pickuuid=?pickID AND creatoruuid=?avatarID"; db.QueryNoResults(query, parms); } } private const string LEGACY_EMPTY = "No notes currently for this avatar!"; public void HandleAvatarNotesRequest(Object sender, string method, List<String> args) { if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; UUID avatarID = remoteClient.AgentId; UUID targetAvatarID = new UUID(args[0]); using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?targetID", targetAvatarID); string query = "SELECT notes from usernotes where useruuid=?avatarID AND targetuuid=?targetID"; List<Dictionary<string, string>> notesResult = db.QueryWithResults(query, parms); string notes = String.Empty; if (notesResult.Count > 0) notes = notesResult[0]["notes"]; if (notes == LEGACY_EMPTY) // filter out the old text that said there was no text. ;) notes = String.Empty; remoteClient.SendAvatarNotesReply(targetAvatarID, notes); } } public void AvatarNotesUpdate(IClientAPI remoteClient, UUID queryTargetID, string queryNotes) { UUID avatarID = remoteClient.AgentId; // allow leading spaces for formatting, but TrimEnd will help us detect an empty field other than spaces string notes = queryNotes.TrimEnd(); // filter out the old text that said there was no text. ;) if (notes == LEGACY_EMPTY) notes = String.Empty; using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?targetID", queryTargetID); parms.Add("?notes", notes); string query; if (String.IsNullOrEmpty(notes)) query = "DELETE FROM usernotes WHERE useruuid=?avatarID AND targetuuid=?targetID"; else query = "INSERT INTO usernotes(useruuid, targetuuid, notes) VALUES(?avatarID,?targetID,?notes) ON DUPLICATE KEY UPDATE notes=?notes"; db.QueryNoResults(query, parms); } } } }
// // System.Net.HttpListenerResponse // // Author: // Gonzalo Paniagua Javier ([email protected]) // // Copyright (c) 2005 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; using System.IO; using System.Net; using System.Text; namespace Reactor.Net { public sealed class HttpListenerResponse : IDisposable { private bool disposed; private Encoding content_encoding; private long content_length; private bool cl_set; private string content_type; private CookieCollection cookies; private WebHeaderCollection headers = new WebHeaderCollection(); private bool keep_alive = true; private ResponseStream output_stream; private Version version = HttpVersion.Version11; private string location; private int status_code = 200; private string status_description = "OK"; private bool chunked; private HttpListenerContext context; internal bool HeadersSent; internal object headers_lock = new object(); bool force_close_chunked; internal HttpListenerResponse(HttpListenerContext context) { this.context = context; } internal bool ForceCloseChunked { get { return force_close_chunked; } } public Encoding ContentEncoding { get { if (content_encoding == null) { content_encoding = Encoding.Default; } return content_encoding; } set { if (disposed) { throw new ObjectDisposedException(GetType().ToString()); } //TODO: is null ok? if (HeadersSent) { throw new InvalidOperationException("Cannot be changed after headers are sent."); } content_encoding = value; } } public long ContentLength64 { get { return content_length; } set { if (disposed) { throw new ObjectDisposedException(GetType().ToString()); } if (HeadersSent) { throw new InvalidOperationException("Cannot be changed after headers are sent."); } if (value < 0) { throw new ArgumentOutOfRangeException("Must be >= 0", "value"); } cl_set = true; content_length = value; } } public string ContentType { get { return content_type; } set { // TODO: is null ok? if (disposed) { throw new ObjectDisposedException(GetType().ToString()); } if (HeadersSent) { throw new InvalidOperationException("Cannot be changed after headers are sent."); } content_type = value; } } // RFC 2109, 2965 + the netscape specification at http://wp.netscape.com/newsref/std/cookie_spec.html public CookieCollection Cookies { get { if (cookies == null) { cookies = new CookieCollection(); } return cookies; } set { cookies = value; } // null allowed? } public WebHeaderCollection Headers { get { return headers; } set { /** * "If you attempt to set a Content-Length, Keep-Alive, Transfer-Encoding, or * WWW-Authenticate header using the Headers property, an exception will be * thrown. Use the KeepAlive or ContentLength64 properties to set these headers. * You cannot set the Transfer-Encoding or WWW-Authenticate headers manually." */ // TODO: check if this is marked readonly after headers are sent. headers = value; } } public bool KeepAlive { get { return keep_alive; } set { if (disposed) { throw new ObjectDisposedException(GetType().ToString()); } if (HeadersSent) { throw new InvalidOperationException("Cannot be changed after headers are sent."); } keep_alive = value; } } public Stream OutputStream { get { if (output_stream == null) { output_stream = context.Connection.GetResponseStream(); } return output_stream; } } public Version ProtocolVersion { get { return version; } set { if (disposed) { throw new ObjectDisposedException(GetType().ToString()); } if (HeadersSent) { throw new InvalidOperationException("Cannot be changed after headers are sent."); } if (value == null) { throw new ArgumentNullException("value"); } if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1)) { throw new ArgumentException("Must be 1.0 or 1.1", "value"); } if (disposed) { throw new ObjectDisposedException(GetType().ToString()); } version = value; } } public string RedirectLocation { get { return location; } set { if (disposed) { throw new ObjectDisposedException(GetType().ToString()); } if (HeadersSent) { throw new InvalidOperationException("Cannot be changed after headers are sent."); } location = value; } } public bool SendChunked { get { return chunked; } set { if (disposed) { throw new ObjectDisposedException(GetType().ToString()); } if (HeadersSent) { throw new InvalidOperationException("Cannot be changed after headers are sent."); } chunked = value; } } public int StatusCode { get { return status_code; } set { if (disposed) { throw new ObjectDisposedException(GetType().ToString()); } if (HeadersSent) { throw new InvalidOperationException("Cannot be changed after headers are sent."); } if (value < 100 || value > 999) { throw new ProtocolViolationException("StatusCode must be between 100 and 999."); } status_code = value; status_description = GetStatusDescription(value); } } internal static string GetStatusDescription(int code) { switch (code) { case 100: return "Continue"; case 101: return "Switching Protocols"; case 102: return "Processing"; case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 206: return "Partial Content"; case 207: return "Multi-Status"; case 300: return "Multiple Choices"; case 301: return "Moved Permanently"; case 302: return "Found"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 307: return "Temporary Redirect"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Request Entity Too Large"; case 414: return "Request-Uri Too Long"; case 415: return "Unsupported Media Type"; case 416: return "Requested Range Not Satisfiable"; case 417: return "Expectation Failed"; case 422: return "Unprocessable Entity"; case 423: return "Locked"; case 424: return "Failed Dependency"; case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Timeout"; case 505: return "Http Version Not Supported"; case 507: return "Insufficient Storage"; } return ""; } public string StatusDescription { get { return status_description; } set { status_description = value; } } void IDisposable.Dispose() { Close(true); //TODO: Abort or Close? } public void Abort() { if (disposed) { return; } Close(true); } public void AddHeader(string name, string value) { if (name == null) { throw new ArgumentNullException("name"); } if (name == "") { throw new ArgumentException("'name' cannot be empty", "name"); } //TODO: check for forbidden headers and invalid characters if (value.Length > 65535) { throw new ArgumentOutOfRangeException("value"); } headers.Set(name, value); } public void AppendCookie(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException("cookie"); } Cookies.Add(cookie); } public void AppendHeader(string name, string value) { if (name == null) { throw new ArgumentNullException("name"); } if (name == "") { throw new ArgumentException("'name' cannot be empty", "name"); } if (value.Length > 65535) { throw new ArgumentOutOfRangeException("value"); } headers.Add(name, value); } void Close(bool force) { disposed = true; context.Connection.Close(force); } public void Close() { if (disposed) { return; } Close(false); } public void Close(byte[] responseEntity, bool willBlock) { if (disposed) { return; } if (responseEntity == null) { throw new ArgumentNullException("responseEntity"); } //TODO: if willBlock -> BeginWrite + Close ? ContentLength64 = responseEntity.Length; OutputStream.Write(responseEntity, 0, (int)content_length); Close(false); } public void CopyFrom(HttpListenerResponse templateResponse) { headers.Clear(); headers.Add(templateResponse.headers); content_length = templateResponse.content_length; status_code = templateResponse.status_code; status_description = templateResponse.status_description; keep_alive = templateResponse.keep_alive; version = templateResponse.version; } public void Redirect(string url) { StatusCode = 302; // Found location = url; } bool FindCookie(Cookie cookie) { string name = cookie.Name; string domain = cookie.Domain; string path = cookie.Path; foreach (Cookie c in cookies) { if (name != c.Name) { continue; } if (domain != c.Domain) { continue; } if (path == c.Path) { return true; } } return false; } internal void SendHeaders(bool closing, MemoryStream ms) { Encoding encoding = content_encoding; if (encoding == null) { encoding = Encoding.Default; } if (content_type != null) { if (content_encoding != null && content_type.IndexOf("charset=", StringComparison.Ordinal) == -1) { string enc_name = content_encoding.WebName; headers.SetInternal("Content-Type", content_type + "; charset=" + enc_name); } else { headers.SetInternal("Content-Type", content_type); } } if (headers["Server"] == null) { headers.SetInternal("Server", "Reactor-HTTPAPI/1.0"); } CultureInfo inv = CultureInfo.InvariantCulture; if (headers["Date"] == null) { headers.SetInternal("Date", DateTime.UtcNow.ToString("r", inv)); } if (!chunked) { if (!cl_set && closing) { cl_set = true; content_length = 0; } if (cl_set) { headers.SetInternal("Content-Length", content_length.ToString(inv)); } } Version v = context.Request.ProtocolVersion; if (!cl_set && !chunked && v >= HttpVersion.Version11) { chunked = true; } /* Apache forces closing the connection for these status codes: * HttpStatusCode.BadRequest 400 * HttpStatusCode.RequestTimeout 408 * HttpStatusCode.LengthRequired 411 * HttpStatusCode.RequestEntityTooLarge 413 * HttpStatusCode.RequestUriTooLong 414 * HttpStatusCode.InternalServerError 500 * HttpStatusCode.ServiceUnavailable 503 */ bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 || status_code == 413 || status_code == 414 || status_code == 500 || status_code == 503); if (conn_close == false) { conn_close = !context.Request.KeepAlive; } // They sent both KeepAlive: true and Connection: close!? if (!keep_alive || conn_close) { headers.SetInternal("Connection", "close"); conn_close = true; } if (chunked) { headers.SetInternal("Transfer-Encoding", "chunked"); } int reuses = context.Connection.Reuses; if (reuses >= 100) { force_close_chunked = true; if (!conn_close) { headers.SetInternal("Connection", "close"); conn_close = true; } } if (!conn_close) { headers.SetInternal("Keep-Alive", String.Format("timeout=15,max={0}", 100 - reuses)); if (context.Request.ProtocolVersion <= HttpVersion.Version10) { headers.SetInternal("Connection", "keep-alive"); } } if (location != null) { headers.SetInternal("Location", location); } if (cookies != null) { foreach (Cookie cookie in cookies) { headers.SetInternal("Set-Cookie", cookie.ToClientString()); } } StreamWriter writer = new StreamWriter(ms, encoding, 256); writer.Write("HTTP/{0} {1} {2}\r\n", version, status_code, status_description); string headers_str = headers.ToStringMultiValue(); writer.Write(headers_str); writer.Flush(); int preamble = (encoding.CodePage == 65001) ? 3 : encoding.GetPreamble().Length; if (output_stream == null) { output_stream = context.Connection.GetResponseStream(); } /* Assumes that the ms was at position 0 */ ms.Position = preamble; HeadersSent = true; } public void SetCookie(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException("cookie"); } if (cookies != null) { if (FindCookie(cookie)) { throw new ArgumentException("The cookie already exists."); } } else { cookies = new CookieCollection(); } cookies.Add(cookie); } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // 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; namespace NUnit.Framework.Internal { /// <summary> /// PlatformHelper class is used by the PlatformAttribute class to /// determine whether a platform is supported. /// </summary> public class PlatformHelper { private OSPlatform os; private RuntimeFramework rt; // Set whenever we fail to support a list of platforms private string reason = string.Empty; /// <summary> /// Comma-delimited list of all supported OS platform constants /// </summary> public static readonly string OSPlatforms = "Win,Win32,Win32S,Win32NT,Win32Windows,WinCE,Win95,Win98,WinMe,NT3,NT4,NT5,NT6,Win2K,WinXP,Win2003Server,Vista,Win2008Server,Win2008ServerR2,Win2012Server,Windows7,Windows8,Unix,Linux"; /// <summary> /// Comma-delimited list of all supported Runtime platform constants /// </summary> public static readonly string RuntimePlatforms = "Net,NetCF,SSCLI,Rotor,Mono"; /// <summary> /// Default constructor uses the operating system and /// common language runtime of the system. /// </summary> public PlatformHelper() { this.os = OSPlatform.CurrentPlatform; this.rt = RuntimeFramework.CurrentFramework; } /// <summary> /// Contruct a PlatformHelper for a particular operating /// system and common language runtime. Used in testing. /// </summary> /// <param name="os">OperatingSystem to be used</param> /// <param name="rt">RuntimeFramework to be used</param> public PlatformHelper( OSPlatform os, RuntimeFramework rt ) { this.os = os; this.rt = rt; } /// <summary> /// Test to determine if one of a collection of platforms /// is being used currently. /// </summary> /// <param name="platforms"></param> /// <returns></returns> public bool IsPlatformSupported( string[] platforms ) { foreach( string platform in platforms ) if ( IsPlatformSupported( platform ) ) return true; return false; } /// <summary> /// Tests to determine if the current platform is supported /// based on a platform attribute. /// </summary> /// <param name="platformAttribute">The attribute to examine</param> /// <returns></returns> public bool IsPlatformSupported( PlatformAttribute platformAttribute ) { string include = platformAttribute.Include; string exclude = platformAttribute.Exclude; try { if (include != null && !IsPlatformSupported(include)) { reason = string.Format("Only supported on {0}", include); return false; } if (exclude != null && IsPlatformSupported(exclude)) { reason = string.Format("Not supported on {0}", exclude); return false; } } catch (Exception ex) { reason = ex.Message; return false; } return true; } /// <summary> /// Test to determine if the a particular platform or comma- /// delimited set of platforms is in use. /// </summary> /// <param name="platform">Name of the platform or comma-separated list of platform names</param> /// <returns>True if the platform is in use on the system</returns> public bool IsPlatformSupported( string platform ) { if ( platform.IndexOf( ',' ) >= 0 ) return IsPlatformSupported( platform.Split( new char[] { ',' } ) ); string platformName = platform.Trim(); bool isSupported = false; // string versionSpecification = null; // // string[] parts = platformName.Split( new char[] { '-' } ); // if ( parts.Length == 2 ) // { // platformName = parts[0]; // versionSpecification = parts[1]; // } switch( platformName.ToUpper() ) { case "WIN": case "WIN32": isSupported = os.IsWindows; break; case "WIN32S": isSupported = os.IsWin32S; break; case "WIN32WINDOWS": isSupported = os.IsWin32Windows; break; case "WIN32NT": isSupported = os.IsWin32NT; break; case "WINCE": isSupported = os.IsWinCE; break; case "WIN95": isSupported = os.IsWin95; break; case "WIN98": isSupported = os.IsWin98; break; case "WINME": isSupported = os.IsWinME; break; case "NT3": isSupported = os.IsNT3; break; case "NT4": isSupported = os.IsNT4; break; case "NT5": isSupported = os.IsNT5; break; case "WIN2K": isSupported = os.IsWin2K; break; case "WINXP": isSupported = os.IsWinXP; break; case "WIN2003SERVER": isSupported = os.IsWin2003Server; break; case "NT6": isSupported = os.IsNT6; break; case "VISTA": isSupported = os.IsVista; break; case "WIN2008SERVER": isSupported = os.IsWin2008Server; break; case "WIN2008SERVERR2": isSupported = os.IsWin2008ServerR2; break; case "WIN2012SERVER": isSupported = os.IsWin2012Server; break; case "WINDOWS7": isSupported = os.IsWindows7; break; case "WINDOWS8": isSupported = os.IsWindows8; break; case "UNIX": case "LINUX": isSupported = os.IsUnix; break; default: isSupported = IsRuntimeSupported(platformName); break; } if (!isSupported) this.reason = "Only supported on " + platform; return isSupported; } /// <summary> /// Return the last failure reason. Results are not /// defined if called before IsSupported( Attribute ) /// is called. /// </summary> public string Reason { get { return reason; } } private bool IsRuntimeSupported(string platformName) { string versionSpecification = null; string[] parts = platformName.Split(new char[] { '-' }); if (parts.Length == 2) { platformName = parts[0]; versionSpecification = parts[1]; } switch (platformName.ToUpper()) { case "NET": return IsRuntimeSupported(RuntimeType.Net, versionSpecification); case "NETCF": return IsRuntimeSupported(RuntimeType.NetCF, versionSpecification); case "SSCLI": case "ROTOR": return IsRuntimeSupported(RuntimeType.SSCLI, versionSpecification); case "MONO": return IsRuntimeSupported(RuntimeType.Mono, versionSpecification); default: throw new ArgumentException("Invalid platform name", platformName); } } private bool IsRuntimeSupported(RuntimeType runtime, string versionSpecification) { Version version = versionSpecification == null ? RuntimeFramework.DefaultVersion : new Version(versionSpecification); RuntimeFramework target = new RuntimeFramework(runtime, version); return rt.Supports(target); } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class ClusterMembersExtendedResponseEncoder { public const ushort BLOCK_LENGTH = 24; public const ushort TEMPLATE_ID = 43; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private ClusterMembersExtendedResponseEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public ClusterMembersExtendedResponseEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ClusterMembersExtendedResponseEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public ClusterMembersExtendedResponseEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int CorrelationIdEncodingOffset() { return 0; } public static int CorrelationIdEncodingLength() { return 8; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public ClusterMembersExtendedResponseEncoder CorrelationId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int CurrentTimeNsEncodingOffset() { return 8; } public static int CurrentTimeNsEncodingLength() { return 8; } public static long CurrentTimeNsNullValue() { return -9223372036854775808L; } public static long CurrentTimeNsMinValue() { return -9223372036854775807L; } public static long CurrentTimeNsMaxValue() { return 9223372036854775807L; } public ClusterMembersExtendedResponseEncoder CurrentTimeNs(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int LeaderMemberIdEncodingOffset() { return 16; } public static int LeaderMemberIdEncodingLength() { return 4; } public static int LeaderMemberIdNullValue() { return -2147483648; } public static int LeaderMemberIdMinValue() { return -2147483647; } public static int LeaderMemberIdMaxValue() { return 2147483647; } public ClusterMembersExtendedResponseEncoder LeaderMemberId(int value) { _buffer.PutInt(_offset + 16, value, ByteOrder.LittleEndian); return this; } public static int MemberIdEncodingOffset() { return 20; } public static int MemberIdEncodingLength() { return 4; } public static int MemberIdNullValue() { return -2147483648; } public static int MemberIdMinValue() { return -2147483647; } public static int MemberIdMaxValue() { return 2147483647; } public ClusterMembersExtendedResponseEncoder MemberId(int value) { _buffer.PutInt(_offset + 20, value, ByteOrder.LittleEndian); return this; } private ActiveMembersEncoder _ActiveMembers = new ActiveMembersEncoder(); public static long ActiveMembersId() { return 5; } public ActiveMembersEncoder ActiveMembersCount(int count) { _ActiveMembers.Wrap(_parentMessage, _buffer, count); return _ActiveMembers; } public class ActiveMembersEncoder { private static int HEADER_SIZE = 4; private GroupSizeEncodingEncoder _dimensions = new GroupSizeEncodingEncoder(); private ClusterMembersExtendedResponseEncoder _parentMessage; private IMutableDirectBuffer _buffer; private int _count; private int _index; private int _offset; public void Wrap( ClusterMembersExtendedResponseEncoder parentMessage, IMutableDirectBuffer buffer, int count) { if (count < 0 || count > 65534) { throw new ArgumentException("count outside allowed range: count=" + count); } this._parentMessage = parentMessage; this._buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit()); _dimensions.BlockLength((ushort)28); _dimensions.NumInGroup((ushort)count); _index = -1; this._count = count; parentMessage.Limit(parentMessage.Limit() + HEADER_SIZE); } public static int SbeHeaderSize() { return HEADER_SIZE; } public static int SbeBlockLength() { return 28; } public ActiveMembersEncoder Next() { if (_index + 1 >= _count) { throw new IndexOutOfRangeException(); } _offset = _parentMessage.Limit(); _parentMessage.Limit(_offset + SbeBlockLength()); ++_index; return this; } public static int LeadershipTermIdEncodingOffset() { return 0; } public static int LeadershipTermIdEncodingLength() { return 8; } public static long LeadershipTermIdNullValue() { return -9223372036854775808L; } public static long LeadershipTermIdMinValue() { return -9223372036854775807L; } public static long LeadershipTermIdMaxValue() { return 9223372036854775807L; } public ActiveMembersEncoder LeadershipTermId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int LogPositionEncodingOffset() { return 8; } public static int LogPositionEncodingLength() { return 8; } public static long LogPositionNullValue() { return -9223372036854775808L; } public static long LogPositionMinValue() { return -9223372036854775807L; } public static long LogPositionMaxValue() { return 9223372036854775807L; } public ActiveMembersEncoder LogPosition(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int TimeOfLastAppendNsEncodingOffset() { return 16; } public static int TimeOfLastAppendNsEncodingLength() { return 8; } public static long TimeOfLastAppendNsNullValue() { return -9223372036854775808L; } public static long TimeOfLastAppendNsMinValue() { return -9223372036854775807L; } public static long TimeOfLastAppendNsMaxValue() { return 9223372036854775807L; } public ActiveMembersEncoder TimeOfLastAppendNs(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public static int MemberIdEncodingOffset() { return 24; } public static int MemberIdEncodingLength() { return 4; } public static int MemberIdNullValue() { return -2147483648; } public static int MemberIdMinValue() { return -2147483647; } public static int MemberIdMaxValue() { return 2147483647; } public ActiveMembersEncoder MemberId(int value) { _buffer.PutInt(_offset + 24, value, ByteOrder.LittleEndian); return this; } public static int IngressEndpointId() { return 10; } public static string IngressEndpointCharacterEncoding() { return "US-ASCII"; } public static string IngressEndpointMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int IngressEndpointHeaderLength() { return 4; } public ActiveMembersEncoder PutIngressEndpoint(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ActiveMembersEncoder PutIngressEndpoint(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ActiveMembersEncoder IngressEndpoint(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public static int ConsensusEndpointId() { return 11; } public static string ConsensusEndpointCharacterEncoding() { return "US-ASCII"; } public static string ConsensusEndpointMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ConsensusEndpointHeaderLength() { return 4; } public ActiveMembersEncoder PutConsensusEndpoint(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ActiveMembersEncoder PutConsensusEndpoint(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ActiveMembersEncoder ConsensusEndpoint(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public static int LogEndpointId() { return 12; } public static string LogEndpointCharacterEncoding() { return "US-ASCII"; } public static string LogEndpointMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int LogEndpointHeaderLength() { return 4; } public ActiveMembersEncoder PutLogEndpoint(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ActiveMembersEncoder PutLogEndpoint(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ActiveMembersEncoder LogEndpoint(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public static int CatchupEndpointId() { return 13; } public static string CatchupEndpointCharacterEncoding() { return "US-ASCII"; } public static string CatchupEndpointMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int CatchupEndpointHeaderLength() { return 4; } public ActiveMembersEncoder PutCatchupEndpoint(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ActiveMembersEncoder PutCatchupEndpoint(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ActiveMembersEncoder CatchupEndpoint(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public static int ArchiveEndpointId() { return 14; } public static string ArchiveEndpointCharacterEncoding() { return "US-ASCII"; } public static string ArchiveEndpointMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ArchiveEndpointHeaderLength() { return 4; } public ActiveMembersEncoder PutArchiveEndpoint(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ActiveMembersEncoder PutArchiveEndpoint(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ActiveMembersEncoder ArchiveEndpoint(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } } private PassiveMembersEncoder _PassiveMembers = new PassiveMembersEncoder(); public static long PassiveMembersId() { return 15; } public PassiveMembersEncoder PassiveMembersCount(int count) { _PassiveMembers.Wrap(_parentMessage, _buffer, count); return _PassiveMembers; } public class PassiveMembersEncoder { private static int HEADER_SIZE = 4; private GroupSizeEncodingEncoder _dimensions = new GroupSizeEncodingEncoder(); private ClusterMembersExtendedResponseEncoder _parentMessage; private IMutableDirectBuffer _buffer; private int _count; private int _index; private int _offset; public void Wrap( ClusterMembersExtendedResponseEncoder parentMessage, IMutableDirectBuffer buffer, int count) { if (count < 0 || count > 65534) { throw new ArgumentException("count outside allowed range: count=" + count); } this._parentMessage = parentMessage; this._buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit()); _dimensions.BlockLength((ushort)28); _dimensions.NumInGroup((ushort)count); _index = -1; this._count = count; parentMessage.Limit(parentMessage.Limit() + HEADER_SIZE); } public static int SbeHeaderSize() { return HEADER_SIZE; } public static int SbeBlockLength() { return 28; } public PassiveMembersEncoder Next() { if (_index + 1 >= _count) { throw new IndexOutOfRangeException(); } _offset = _parentMessage.Limit(); _parentMessage.Limit(_offset + SbeBlockLength()); ++_index; return this; } public static int LeadershipTermIdEncodingOffset() { return 0; } public static int LeadershipTermIdEncodingLength() { return 8; } public static long LeadershipTermIdNullValue() { return -9223372036854775808L; } public static long LeadershipTermIdMinValue() { return -9223372036854775807L; } public static long LeadershipTermIdMaxValue() { return 9223372036854775807L; } public PassiveMembersEncoder LeadershipTermId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int LogPositionEncodingOffset() { return 8; } public static int LogPositionEncodingLength() { return 8; } public static long LogPositionNullValue() { return -9223372036854775808L; } public static long LogPositionMinValue() { return -9223372036854775807L; } public static long LogPositionMaxValue() { return 9223372036854775807L; } public PassiveMembersEncoder LogPosition(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int TimeOfLastAppendNsEncodingOffset() { return 16; } public static int TimeOfLastAppendNsEncodingLength() { return 8; } public static long TimeOfLastAppendNsNullValue() { return -9223372036854775808L; } public static long TimeOfLastAppendNsMinValue() { return -9223372036854775807L; } public static long TimeOfLastAppendNsMaxValue() { return 9223372036854775807L; } public PassiveMembersEncoder TimeOfLastAppendNs(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public static int MemberIdEncodingOffset() { return 24; } public static int MemberIdEncodingLength() { return 4; } public static int MemberIdNullValue() { return -2147483648; } public static int MemberIdMinValue() { return -2147483647; } public static int MemberIdMaxValue() { return 2147483647; } public PassiveMembersEncoder MemberId(int value) { _buffer.PutInt(_offset + 24, value, ByteOrder.LittleEndian); return this; } public static int IngressEndpointId() { return 20; } public static string IngressEndpointCharacterEncoding() { return "US-ASCII"; } public static string IngressEndpointMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int IngressEndpointHeaderLength() { return 4; } public PassiveMembersEncoder PutIngressEndpoint(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public PassiveMembersEncoder PutIngressEndpoint(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public PassiveMembersEncoder IngressEndpoint(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public static int ConsensusEndpointId() { return 21; } public static string ConsensusEndpointCharacterEncoding() { return "US-ASCII"; } public static string ConsensusEndpointMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ConsensusEndpointHeaderLength() { return 4; } public PassiveMembersEncoder PutConsensusEndpoint(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public PassiveMembersEncoder PutConsensusEndpoint(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public PassiveMembersEncoder ConsensusEndpoint(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public static int LogEndpointId() { return 22; } public static string LogEndpointCharacterEncoding() { return "US-ASCII"; } public static string LogEndpointMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int LogEndpointHeaderLength() { return 4; } public PassiveMembersEncoder PutLogEndpoint(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public PassiveMembersEncoder PutLogEndpoint(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public PassiveMembersEncoder LogEndpoint(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public static int CatchupEndpointId() { return 23; } public static string CatchupEndpointCharacterEncoding() { return "US-ASCII"; } public static string CatchupEndpointMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int CatchupEndpointHeaderLength() { return 4; } public PassiveMembersEncoder PutCatchupEndpoint(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public PassiveMembersEncoder PutCatchupEndpoint(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public PassiveMembersEncoder CatchupEndpoint(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public static int ArchiveEndpointId() { return 24; } public static string ArchiveEndpointCharacterEncoding() { return "US-ASCII"; } public static string ArchiveEndpointMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ArchiveEndpointHeaderLength() { return 4; } public PassiveMembersEncoder PutArchiveEndpoint(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public PassiveMembersEncoder PutArchiveEndpoint(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public PassiveMembersEncoder ArchiveEndpoint(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { ClusterMembersExtendedResponseDecoder writer = new ClusterMembersExtendedResponseDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { // NOTE: Microsoft.VisualStudio.LanguageServices.TypeScript.TypeScriptProject derives from AbstractProject. internal abstract partial class AbstractProject : ForegroundThreadAffinitizedObject, IVisualStudioHostProject { internal static object RuleSetErrorId = new object(); private readonly object _gate = new object(); #region Mutable fields accessed from foreground or background threads - need locking for access. private readonly List<ProjectReference> _projectReferences = new List<ProjectReference>(); private readonly List<VisualStudioMetadataReference> _metadataReferences = new List<VisualStudioMetadataReference>(); private readonly Dictionary<DocumentId, IVisualStudioHostDocument> _documents = new Dictionary<DocumentId, IVisualStudioHostDocument>(); private readonly Dictionary<string, IVisualStudioHostDocument> _documentMonikers = new Dictionary<string, IVisualStudioHostDocument>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, VisualStudioAnalyzer> _analyzers = new Dictionary<string, VisualStudioAnalyzer>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<DocumentId, IVisualStudioHostDocument> _additionalDocuments = new Dictionary<DocumentId, IVisualStudioHostDocument>(); /// <summary> /// The list of files which have been added to the project but we aren't tracking since they /// aren't real source files. Sometimes we're asked to add silly things like HTML files or XAML /// files, and if those are open in a strange editor we just bail. /// </summary> private readonly ISet<string> _untrackedDocuments = new HashSet<string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// The path to a metadata reference that was converted to project references. /// </summary> private readonly Dictionary<string, ProjectReference> _metadataFileNameToConvertedProjectReference = new Dictionary<string, ProjectReference>(StringComparer.OrdinalIgnoreCase); private bool _pushingChangesToWorkspaceHosts; #endregion #region Mutable fields accessed only from the foreground thread - does not need locking for access. /// <summary> /// When a reference changes on disk we start a delayed task to update the <see cref="Workspace"/>. /// It is delayed for two reasons: first, there are often a bunch of change notifications in quick succession /// as the file is written. Second, we often get the first notification while something is still writing the /// file, so we're unable to actually load it. To avoid both of these issues, we wait five seconds before /// reloading the metadata. This <see cref="Dictionary{TKey, TValue}"/> holds on to /// <see cref="CancellationTokenSource"/>s that allow us to cancel the existing reload task if another file /// change comes in before we process it. /// </summary> private readonly Dictionary<VisualStudioMetadataReference, CancellationTokenSource> _donotAccessDirectlyChangedReferencesPendingUpdate = new Dictionary<VisualStudioMetadataReference, CancellationTokenSource>(); private Dictionary<VisualStudioMetadataReference, CancellationTokenSource> ChangedReferencesPendingUpdate { get { AssertIsForeground(); return _donotAccessDirectlyChangedReferencesPendingUpdate; } } #endregion // PERF: Create these event handlers once to be shared amongst all documents (the sender arg identifies which document and project) private static readonly EventHandler<bool> s_documentOpenedEventHandler = OnDocumentOpened; private static readonly EventHandler<bool> s_documentClosingEventHandler = OnDocumentClosing; private static readonly EventHandler s_documentUpdatedOnDiskEventHandler = OnDocumentUpdatedOnDisk; private static readonly EventHandler<bool> s_additionalDocumentOpenedEventHandler = OnAdditionalDocumentOpened; private static readonly EventHandler<bool> s_additionalDocumentClosingEventHandler = OnAdditionalDocumentClosing; private static readonly EventHandler s_additionalDocumentUpdatedOnDiskEventHandler = OnAdditionalDocumentUpdatedOnDisk; private readonly DiagnosticDescriptor _errorReadingRulesetRule = new DiagnosticDescriptor( id: IDEDiagnosticIds.ErrorReadingRulesetId, title: ServicesVSResources.ErrorReadingRuleset, messageFormat: ServicesVSResources.Error_reading_ruleset_file_0_1, category: FeaturesResources.Roslyn_HostError, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); public AbstractProject( VisualStudioProjectTracker projectTracker, Func<ProjectId, IVsReportExternalErrors> reportExternalErrorCreatorOpt, string projectSystemName, string projectFilePath, IVsHierarchy hierarchy, string language, Guid projectGuid, IServiceProvider serviceProvider, VisualStudioWorkspaceImpl visualStudioWorkspaceOpt, HostDiagnosticUpdateSource hostDiagnosticUpdateSourceOpt, ICommandLineParserService commandLineParserServiceOpt = null) { Contract.ThrowIfNull(projectSystemName); ServiceProvider = serviceProvider; Language = language; Hierarchy = hierarchy; Guid = projectGuid; var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); ContentTypeRegistryService = componentModel.GetService<IContentTypeRegistryService>(); this.RunningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable)); this.DisplayName = projectSystemName; this.ProjectTracker = projectTracker; ProjectSystemName = projectSystemName; Workspace = visualStudioWorkspaceOpt; CommandLineParserService = commandLineParserServiceOpt; HostDiagnosticUpdateSource = hostDiagnosticUpdateSourceOpt; // Set the default value for last design time build result to be true, until the project system lets us know that it failed. LastDesignTimeBuildSucceeded = true; UpdateProjectDisplayNameAndFilePath(projectSystemName, projectFilePath); if (ProjectFilePath != null) { Version = VersionStamp.Create(File.GetLastWriteTimeUtc(ProjectFilePath)); } else { Version = VersionStamp.Create(); } Id = this.ProjectTracker.GetOrCreateProjectIdForPath(ProjectFilePath ?? ProjectSystemName, ProjectSystemName); if (reportExternalErrorCreatorOpt != null) { ExternalErrorReporter = reportExternalErrorCreatorOpt(Id); } if (visualStudioWorkspaceOpt != null) { if (Language == LanguageNames.CSharp || Language == LanguageNames.VisualBasic) { this.EditAndContinueImplOpt = new VsENCRebuildableProjectImpl(this); } this.MetadataService = visualStudioWorkspaceOpt.Services.GetService<IMetadataService>(); } UpdateAssemblyName(); } internal IServiceProvider ServiceProvider { get; } /// <summary> /// Indicates whether this project is a website type. /// </summary> public bool IsWebSite { get; protected set; } /// <summary> /// A full path to the project obj output binary, or null if the project doesn't have an obj output binary. /// </summary> internal string ObjOutputPath { get; private set; } /// <summary> /// A full path to the project bin output binary, or null if the project doesn't have an bin output binary. /// </summary> internal string BinOutputPath { get; private set; } public IRuleSetFile RuleSetFile { get; private set; } protected VisualStudioProjectTracker ProjectTracker { get; } protected IVsRunningDocumentTable4 RunningDocumentTable { get; } protected IVsReportExternalErrors ExternalErrorReporter { get; } internal HostDiagnosticUpdateSource HostDiagnosticUpdateSource { get; } public ProjectId Id { get; } public string Language { get; } private ICommandLineParserService CommandLineParserService { get; } /// <summary> /// The <see cref="IVsHierarchy"/> for this project. NOTE: May be null in Deferred Project Load cases. /// </summary> public IVsHierarchy Hierarchy { get; } /// <summary> /// Guid of the project /// /// it is not readonly since it can be changed while loading project /// </summary> public Guid Guid { get; protected set; } public Workspace Workspace { get; } public VersionStamp Version { get; } public IMetadataService MetadataService { get; } /// <summary> /// The containing directory of the project. Null if none exists (consider Venus.) /// </summary> protected string ContainingDirectoryPathOpt { get { var projectFilePath = this.ProjectFilePath; if (projectFilePath != null) { return Path.GetDirectoryName(projectFilePath); } else { return null; } } } /// <summary> /// The full path of the project file. Null if none exists (consider Venus.) /// Note that the project file path might change with project file rename. /// If you need the folder of the project, just use <see cref="ContainingDirectoryPathOpt" /> which doesn't change for a project. /// </summary> public string ProjectFilePath { get; private set; } /// <summary> /// The public display name of the project. This name is not unique and may be shared /// between multiple projects, especially in cases like Venus where the intellisense /// projects will match the name of their logical parent project. /// </summary> public string DisplayName { get; private set; } internal string AssemblyName { get; private set; } /// <summary> /// The name of the project according to the project system. In "regular" projects this is /// equivalent to <see cref="DisplayName"/>, but in Venus cases these will differ. The /// ProjectSystemName is the 2_Default.aspx project name, whereas the regular display name /// matches the display name of the project the user actually sees in the solution explorer. /// These can be assumed to be unique within the Visual Studio workspace. /// </summary> public string ProjectSystemName { get; } protected DocumentProvider DocumentProvider => this.ProjectTracker.DocumentProvider; protected VisualStudioMetadataReferenceManager MetadataReferenceProvider => this.ProjectTracker.MetadataReferenceProvider; protected IContentTypeRegistryService ContentTypeRegistryService { get; } /// <summary> /// Flag indicating if the latest design time build has succeeded for current project state. /// </summary> /// <remarks>Default value is true.</remarks> protected bool LastDesignTimeBuildSucceeded { get; private set; } internal VsENCRebuildableProjectImpl EditAndContinueImplOpt { get; private set; } /// <summary> /// Override this method to validate references when creating <see cref="ProjectInfo"/> for current state. /// By default, this method does nothing. /// </summary> protected virtual void ValidateReferences() { } public ProjectInfo CreateProjectInfoForCurrentState() { ValidateReferences(); lock (_gate) { var info = ProjectInfo.Create( this.Id, this.Version, this.DisplayName, this.AssemblyName ?? this.ProjectSystemName, this.Language, filePath: this.ProjectFilePath, outputFilePath: this.ObjOutputPath, compilationOptions: this.CurrentCompilationOptions, parseOptions: this.CurrentParseOptions, documents: _documents.Values.Select(d => d.GetInitialState()), metadataReferences: _metadataReferences.Select(r => r.CurrentSnapshot), projectReferences: _projectReferences, analyzerReferences: _analyzers.Values.Select(a => a.GetReference()), additionalDocuments: _additionalDocuments.Values.Select(d => d.GetInitialState())); return info.WithHasAllInformation(hasAllInformation: LastDesignTimeBuildSucceeded); } } protected void SetIntellisenseBuildResultAndNotifyWorkspaceHosts(bool succeeded) { // set intellisense related info LastDesignTimeBuildSucceeded = succeeded; if (PushingChangesToWorkspaceHosts) { // set workspace reference info ProjectTracker.NotifyWorkspaceHosts(host => (host as IVisualStudioWorkspaceHost2)?.OnHasAllInformation(Id, succeeded)); } } protected ImmutableArray<string> GetStrongNameKeyPaths() { var outputPath = this.ObjOutputPath; if (this.ContainingDirectoryPathOpt == null && outputPath == null) { return ImmutableArray<string>.Empty; } var builder = ArrayBuilder<string>.GetInstance(); if (this.ContainingDirectoryPathOpt != null) { builder.Add(this.ContainingDirectoryPathOpt); } if (outputPath != null) { builder.Add(Path.GetDirectoryName(outputPath)); } return builder.ToImmutableAndFree(); } public ImmutableArray<ProjectReference> GetCurrentProjectReferences() { lock (_gate) { return ImmutableArray.CreateRange(_projectReferences); } } public ImmutableArray<VisualStudioMetadataReference> GetCurrentMetadataReferences() { lock (_gate) { return ImmutableArray.CreateRange(_metadataReferences); } } public ImmutableArray<VisualStudioAnalyzer> GetCurrentAnalyzers() { lock (_gate) { return ImmutableArray.CreateRange(_analyzers.Values); } } public IVisualStudioHostDocument GetDocumentOrAdditionalDocument(DocumentId id) { lock (_gate) { _documents.TryGetValue(id, out var doc); if (doc == null) { _additionalDocuments.TryGetValue(id, out doc); } return doc; } } public ImmutableArray<IVisualStudioHostDocument> GetCurrentDocuments() { lock (_gate) { return _documents.Values.ToImmutableArrayOrEmpty(); } } public ImmutableArray<IVisualStudioHostDocument> GetCurrentAdditionalDocuments() { lock (_gate) { return _additionalDocuments.Values.ToImmutableArrayOrEmpty(); } } public bool ContainsFile(string moniker) { lock (_gate) { return _documentMonikers.ContainsKey(moniker); } } public IVisualStudioHostDocument GetCurrentDocumentFromPath(string filePath) { lock (_gate) { _documentMonikers.TryGetValue(filePath, out var document); return document; } } public bool HasMetadataReference(string filename) { lock (_gate) { return _metadataReferences.Any(r => StringComparer.OrdinalIgnoreCase.Equals(r.FilePath, filename)); } } public VisualStudioMetadataReference TryGetCurrentMetadataReference(string filename) { // We must normalize the file path, since the paths we're comparing to are always normalized filename = FileUtilities.NormalizeAbsolutePath(filename); lock (_gate) { return _metadataReferences.SingleOrDefault(r => StringComparer.OrdinalIgnoreCase.Equals(r.FilePath, filename)); } } private void AddMetadataFileNameToConvertedProjectReference(string filePath, ProjectReference projectReference) { lock (_gate) { _metadataFileNameToConvertedProjectReference.Add(filePath, projectReference); } } private void UpdateMetadataFileNameToConvertedProjectReference(string filePath, ProjectReference projectReference) { lock (_gate) { _metadataFileNameToConvertedProjectReference[filePath] = projectReference; } } private bool RemoveMetadataFileNameToConvertedProjectReference(string filePath) { lock (_gate) { return _metadataFileNameToConvertedProjectReference.Remove(filePath); } } private bool TryGetMetadataFileNameToConvertedProjectReference(string filePath, out ProjectReference projectReference) { lock (_gate) { return _metadataFileNameToConvertedProjectReference.TryGetValue(filePath, out projectReference); } } private bool HasMetadataFileNameToConvertedProjectReference(string filePath) { lock (_gate) { return _metadataFileNameToConvertedProjectReference.ContainsKey(filePath); } } public bool CurrentProjectReferencesContains(ProjectId projectId) { lock (_gate) { return _projectReferences.Any(r => r.ProjectId == projectId); } } private bool TryGetAnalyzer(string analyzerAssemblyFullPath, out VisualStudioAnalyzer analyzer) { lock (_gate) { return _analyzers.TryGetValue(analyzerAssemblyFullPath, out analyzer); } } private void AddOrUpdateAnalyzer(string analyzerAssemblyFullPath, VisualStudioAnalyzer analyzer) { lock (_gate) { _analyzers[analyzerAssemblyFullPath] = analyzer; } } private void RemoveAnalyzer(string analyzerAssemblyFullPath) { lock (_gate) { _analyzers.Remove(analyzerAssemblyFullPath); } } public bool CurrentProjectAnalyzersContains(string fullPath) { lock (_gate) { return _analyzers.ContainsKey(fullPath); } } /// <summary> /// Returns a map from full path to <see cref="VisualStudioAnalyzer"/>. /// </summary> public ImmutableDictionary<string, VisualStudioAnalyzer> GetProjectAnalyzersMap() { lock (_gate) { return _analyzers.ToImmutableDictionary(); } } private static string GetAssemblyNameFromPath(string outputPath) { Contract.Requires(outputPath != null); // dev11 sometimes gives us output path w/o extension, so removing extension becomes problematic if (outputPath.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) || outputPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || outputPath.EndsWith(".netmodule", StringComparison.OrdinalIgnoreCase) || outputPath.EndsWith(".winmdobj", StringComparison.OrdinalIgnoreCase)) { return Path.GetFileNameWithoutExtension(outputPath); } else { return Path.GetFileName(outputPath); } } protected bool CanConvertToProjectReferences { get { if (this.Workspace != null) { return this.Workspace.Options.GetOption(InternalFeatureOnOffOptions.ProjectReferenceConversion); } else { return InternalFeatureOnOffOptions.ProjectReferenceConversion.DefaultValue; } } } protected int AddMetadataReferenceAndTryConvertingToProjectReferenceIfPossible(string filePath, MetadataReferenceProperties properties) { // If this file is coming from a project, then we should convert it to a project reference instead if (this.CanConvertToProjectReferences && ProjectTracker.TryGetProjectByBinPath(filePath, out var project)) { var projectReference = new ProjectReference(project.Id, properties.Aliases, properties.EmbedInteropTypes); if (CanAddProjectReference(projectReference)) { AddProjectReference(projectReference); AddMetadataFileNameToConvertedProjectReference(filePath, projectReference); return VSConstants.S_OK; } } // regardless whether the file exists or not, we still record it. one of reason // we do that is some cross language p2p references might be resolved // after they are already reported as metadata references. since we use bin path // as a way to discover them, if we don't previously record the reference ourselves, // cross p2p references won't be resolved as p2p references when we finally have // all required information. // // it looks like // 1. project system sometimes won't guarantee build dependency for intellisense build // if it is cross language dependency // 2. output path of referenced cross language project might be changed to right one // once it is already added as a metadata reference. // // but this has one consequence. even if a user adds a project in the solution as // a metadata reference explicitly, that dll will be automatically converted back to p2p // reference. // // unfortunately there is no way to prevent this using information we have since, // at this point, we don't know whether it is a metadata reference added because // we don't have enough information yet for p2p reference or user explicitly added it // as a metadata reference. AddMetadataReferenceCore(this.MetadataReferenceProvider.CreateMetadataReference(this, filePath, properties)); // here, we change behavior compared to old C# language service. regardless of file being exist or not, // we will always return S_OK. this is to support cross language p2p reference better. // // this should make project system to cache all cross language p2p references regardless // whether it actually exist in disk or not. // (see Roslyn bug 7315 for history - http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems?_a=edit&id=7315) // // after this point, Roslyn will take care of non-exist metadata reference. // // But, this doesn't sovle the issue where actual metadata reference // (not cross language p2p reference) is missing at the time project is opened. // // in that case, msbuild filter those actual metadata references out, so project system doesn't know // path to the reference. since it doesn't know where dll is, it can't (or currently doesn't) // setup file change notification either to find out when dll becomes available. // // at this point, user has 2 ways to recover missing metadata reference once it becomes available. // // one way is explicitly clicking that missing reference from solution explorer reference node. // the other is building the project. at that point, project system will refresh references // which will discover new dll and connect to us. once it is connected, we will take care of it. return VSConstants.S_OK; } protected void RemoveMetadataReference(string filePath) { // Is this a reference we converted to a project reference? if (TryGetMetadataFileNameToConvertedProjectReference(filePath, out var projectReference)) { // We converted this, so remove the project reference instead RemoveProjectReference(projectReference); Contract.ThrowIfFalse(RemoveMetadataFileNameToConvertedProjectReference(filePath)); } // Just a metadata reference, so remove all of those var referenceToRemove = TryGetCurrentMetadataReference(filePath); if (referenceToRemove != null) { RemoveMetadataReferenceCore(referenceToRemove, disposeReference: true); } } private void AddMetadataReferenceCore(VisualStudioMetadataReference reference) { lock (_gate) { _metadataReferences.Add(reference); } if (_pushingChangesToWorkspaceHosts) { var snapshot = reference.CurrentSnapshot; this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnMetadataReferenceAdded(this.Id, snapshot)); } reference.UpdatedOnDisk += OnImportChanged; } private void RemoveMetadataReferenceCore(VisualStudioMetadataReference reference, bool disposeReference) { lock (_gate) { _metadataReferences.Remove(reference); } if (_pushingChangesToWorkspaceHosts) { var snapshot = reference.CurrentSnapshot; this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnMetadataReferenceRemoved(this.Id, snapshot)); } reference.UpdatedOnDisk -= OnImportChanged; if (disposeReference) { reference.Dispose(); } } /// <summary> /// Called when a referenced metadata file changes on disk. /// </summary> private void OnImportChanged(object sender, EventArgs e) { AssertIsForeground(); VisualStudioMetadataReference reference = (VisualStudioMetadataReference)sender; if (ChangedReferencesPendingUpdate.TryGetValue(reference, out var delayTaskCancellationTokenSource)) { delayTaskCancellationTokenSource.Cancel(); } delayTaskCancellationTokenSource = new CancellationTokenSource(); ChangedReferencesPendingUpdate[reference] = delayTaskCancellationTokenSource; var task = Task.Delay(TimeSpan.FromSeconds(5), delayTaskCancellationTokenSource.Token) .ContinueWith( OnImportChangedAfterDelay, reference, delayTaskCancellationTokenSource.Token, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); } private void OnImportChangedAfterDelay(Task previous, object state) { AssertIsForeground(); var reference = (VisualStudioMetadataReference)state; ChangedReferencesPendingUpdate.Remove(reference); lock (_gate) { // Ensure that we are still referencing this binary if (_metadataReferences.Contains(reference)) { // remove the old metadata reference this.RemoveMetadataReferenceCore(reference, disposeReference: false); // Signal to update the underlying reference snapshot reference.UpdateSnapshot(); // add it back (it will now be based on the new file contents) this.AddMetadataReferenceCore(reference); } } } private void OnAnalyzerChanged(object sender, EventArgs e) { // Postpone handler's actions to prevent deadlock. This AnalyzeChanged event can // be invoked while the FileChangeService lock is held, and VisualStudioAnalyzer's // efforts to listen to file changes can lead to a deadlock situation. // Postponing the VisualStudioAnalyzer operations gives this thread the opportunity // to release the lock. Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => { VisualStudioAnalyzer analyzer = (VisualStudioAnalyzer)sender; RemoveAnalyzerReference(analyzer.FullPath); AddAnalyzerReference(analyzer.FullPath); })); } // Internal for unit testing internal void AddProjectReference(ProjectReference projectReference) { // dev11 is sometimes calling us multiple times for the same data if (!CanAddProjectReference(projectReference)) { return; } lock (_gate) { // always manipulate current state after workspace is told so it will correctly observe the initial state _projectReferences.Add(projectReference); } if (_pushingChangesToWorkspaceHosts) { // This project is already pushed to listening workspace hosts, but it's possible that our target // project hasn't been yet. Get the dependent project into the workspace as well. var targetProject = this.ProjectTracker.GetProject(projectReference.ProjectId); this.ProjectTracker.StartPushingToWorkspaceAndNotifyOfOpenDocuments(SpecializedCollections.SingletonEnumerable(targetProject)); this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnProjectReferenceAdded(this.Id, projectReference)); } } protected bool CanAddProjectReference(ProjectReference projectReference) { if (projectReference.ProjectId == this.Id) { // cannot self reference return false; } lock (_gate) { if (_projectReferences.Contains(projectReference)) { // already have this reference return false; } } var project = this.ProjectTracker.GetProject(projectReference.ProjectId); if (project != null) { // cannot add a reference to a project that references us (it would make a cycle) return !project.TransitivelyReferences(this.Id); } return true; } private bool TransitivelyReferences(ProjectId projectId) { return TransitivelyReferencesWorker(projectId, new HashSet<ProjectId>()); } private bool TransitivelyReferencesWorker(ProjectId projectId, HashSet<ProjectId> visited) { visited.Add(this.Id); foreach (var pr in GetCurrentProjectReferences()) { if (projectId == pr.ProjectId) { return true; } if (!visited.Contains(pr.ProjectId)) { var project = this.ProjectTracker.GetProject(pr.ProjectId); if (project != null) { if (project.TransitivelyReferencesWorker(projectId, visited)) { return true; } } } } return false; } protected void RemoveProjectReference(ProjectReference projectReference) { lock (_gate) { Contract.ThrowIfFalse(_projectReferences.Remove(projectReference)); } if (_pushingChangesToWorkspaceHosts) { this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnProjectReferenceRemoved(this.Id, projectReference)); } } private static void OnDocumentOpened(object sender, bool isCurrentContext) { IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender; AbstractProject project = (AbstractProject)document.Project; if (project._pushingChangesToWorkspaceHosts) { project.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentOpened(document.Id, document.GetOpenTextBuffer(), isCurrentContext)); } else { StartPushingToWorkspaceAndNotifyOfOpenDocuments(project); } } private static void OnDocumentClosing(object sender, bool updateActiveContext) { IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender; AbstractProject project = (AbstractProject)document.Project; var projectTracker = project.ProjectTracker; if (project._pushingChangesToWorkspaceHosts) { projectTracker.NotifyWorkspaceHosts(host => host.OnDocumentClosed(document.Id, document.GetOpenTextBuffer(), document.Loader, updateActiveContext)); } } private static void OnDocumentUpdatedOnDisk(object sender, EventArgs e) { IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender; AbstractProject project = (AbstractProject)document.Project; if (project._pushingChangesToWorkspaceHosts) { project.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentTextUpdatedOnDisk(document.Id)); } } private static void OnAdditionalDocumentOpened(object sender, bool isCurrentContext) { IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender; AbstractProject project = (AbstractProject)document.Project; if (project._pushingChangesToWorkspaceHosts) { project.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentOpened(document.Id, document.GetOpenTextBuffer(), isCurrentContext)); } else { StartPushingToWorkspaceAndNotifyOfOpenDocuments(project); } } private static void OnAdditionalDocumentClosing(object sender, bool notUsed) { IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender; AbstractProject project = (AbstractProject)document.Project; var projectTracker = project.ProjectTracker; if (project._pushingChangesToWorkspaceHosts) { projectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentClosed(document.Id, document.GetOpenTextBuffer(), document.Loader)); } } private static void OnAdditionalDocumentUpdatedOnDisk(object sender, EventArgs e) { IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender; AbstractProject project = (AbstractProject)document.Project; if (project._pushingChangesToWorkspaceHosts) { project.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentTextUpdatedOnDisk(document.Id)); } } protected void AddFile( string filename, SourceCodeKind sourceCodeKind, Func<IVisualStudioHostDocument, bool> getIsCurrentContext, Func<uint, IReadOnlyList<string>> getFolderNames) { // We can currently be on a background thread. // So, hookup the handlers when creating the standard text document, as we might receive these handler notifications on the UI thread. var document = this.DocumentProvider.TryGetDocumentForFile( this, filePath: filename, sourceCodeKind: sourceCodeKind, getFolderNames: getFolderNames, canUseTextBuffer: CanUseTextBuffer, updatedOnDiskHandler: s_documentUpdatedOnDiskEventHandler, openedHandler: s_documentOpenedEventHandler, closingHandler: s_documentClosingEventHandler); if (document == null) { // It's possible this file is open in some very strange editor. In that case, we'll just ignore it. // This might happen if somebody decides to mark a non-source-file as something to compile. // TODO: Venus does this for .aspx/.cshtml files which is completely unnecessary for Roslyn. We should remove that code. AddUntrackedFile(filename); return; } AddDocument(document, getIsCurrentContext(document), hookupHandlers: false); } protected virtual bool CanUseTextBuffer(ITextBuffer textBuffer) { return true; } protected void AddUntrackedFile(string filename) { lock (_gate) { _untrackedDocuments.Add(filename); } } protected void RemoveFile(string filename) { lock (_gate) { // Remove this as an untracked file, if it is if (_untrackedDocuments.Remove(filename)) { return; } } IVisualStudioHostDocument document = this.GetCurrentDocumentFromPath(filename); if (document == null) { throw new InvalidOperationException("The document is not a part of the finalProject."); } RemoveDocument(document); } internal void AddDocument(IVisualStudioHostDocument document, bool isCurrentContext, bool hookupHandlers) { // We do not want to allow message pumping/reentrancy when processing project system changes. using (Dispatcher.CurrentDispatcher.DisableProcessing()) { lock (_gate) { _documents.Add(document.Id, document); _documentMonikers.Add(document.Key.Moniker, document); } if (_pushingChangesToWorkspaceHosts) { this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentAdded(document.GetInitialState())); if (document.IsOpen) { this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentOpened(document.Id, document.GetOpenTextBuffer(), isCurrentContext)); } } if (hookupHandlers) { document.Opened += s_documentOpenedEventHandler; document.Closing += s_documentClosingEventHandler; document.UpdatedOnDisk += s_documentUpdatedOnDiskEventHandler; } DocumentProvider.NotifyDocumentRegisteredToProjectAndStartToRaiseEvents(document); if (!_pushingChangesToWorkspaceHosts && document.IsOpen) { StartPushingToWorkspaceAndNotifyOfOpenDocuments(); } } } internal void RemoveDocument(IVisualStudioHostDocument document) { // We do not want to allow message pumping/reentrancy when processing project system changes. using (Dispatcher.CurrentDispatcher.DisableProcessing()) { lock (_gate) { _documents.Remove(document.Id); _documentMonikers.Remove(document.Key.Moniker); } UninitializeDocument(document); OnDocumentRemoved(document.Key.Moniker); } } internal void AddAdditionalDocument(IVisualStudioHostDocument document, bool isCurrentContext) { lock (_gate) { _additionalDocuments.Add(document.Id, document); _documentMonikers.Add(document.Key.Moniker, document); } if (_pushingChangesToWorkspaceHosts) { this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentAdded(document.GetInitialState())); if (document.IsOpen) { this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentOpened(document.Id, document.GetOpenTextBuffer(), isCurrentContext)); } } DocumentProvider.NotifyDocumentRegisteredToProjectAndStartToRaiseEvents(document); if (!_pushingChangesToWorkspaceHosts && document.IsOpen) { StartPushingToWorkspaceAndNotifyOfOpenDocuments(); } } internal void RemoveAdditionalDocument(IVisualStudioHostDocument document) { lock (_gate) { _additionalDocuments.Remove(document.Id); _documentMonikers.Remove(document.Key.Moniker); } UninitializeAdditionalDocument(document); } public virtual void Disconnect() { AssertIsForeground(); using (Workspace?.Services.GetService<IGlobalOperationNotificationService>()?.Start("Disconnect Project")) { lock (_gate) { // No sense in reloading any metadata references anymore. foreach (var cancellationTokenSource in ChangedReferencesPendingUpdate.Values) { cancellationTokenSource.Cancel(); } ChangedReferencesPendingUpdate.Clear(); var wasPushing = _pushingChangesToWorkspaceHosts; // disable pushing down to workspaces, so we don't get redundant workspace document removed events _pushingChangesToWorkspaceHosts = false; // The project is going away, so let's remove ourselves from the host. First, we // close and dispose of any remaining documents foreach (var document in _documents.Values) { UninitializeDocument(document); } foreach (var document in _additionalDocuments.Values) { UninitializeAdditionalDocument(document); } // Dispose metadata references. foreach (var reference in _metadataReferences) { reference.Dispose(); } foreach (var analyzer in _analyzers.Values) { analyzer.Dispose(); } // Make sure we clear out any external errors left when closing the project. ExternalErrorReporter?.ClearAllErrors(); // Make sure we clear out any host errors left when closing the project. HostDiagnosticUpdateSource?.ClearAllDiagnosticsForProject(this.Id); ClearAnalyzerRuleSet(); // reinstate pushing down to workspace, so the workspace project remove event fires _pushingChangesToWorkspaceHosts = wasPushing; this.ProjectTracker.RemoveProject(this); _pushingChangesToWorkspaceHosts = false; this.EditAndContinueImplOpt = null; } } } internal void TryProjectConversionForIntroducedOutputPath(string binPath, AbstractProject projectToReference) { if (this.CanConvertToProjectReferences) { // We should not already have references for this, since we're only introducing the path for the first time Contract.ThrowIfTrue(HasMetadataFileNameToConvertedProjectReference(binPath)); var metadataReference = TryGetCurrentMetadataReference(binPath); if (metadataReference != null) { var projectReference = new ProjectReference( projectToReference.Id, metadataReference.Properties.Aliases, metadataReference.Properties.EmbedInteropTypes); if (CanAddProjectReference(projectReference)) { RemoveMetadataReferenceCore(metadataReference, disposeReference: true); AddProjectReference(projectReference); AddMetadataFileNameToConvertedProjectReference(binPath, projectReference); } } } } internal void UndoProjectReferenceConversionForDisappearingOutputPath(string binPath) { if (TryGetMetadataFileNameToConvertedProjectReference(binPath, out var projectReference)) { // We converted this, so convert it back to a metadata reference RemoveProjectReference(projectReference); var metadataReferenceProperties = new MetadataReferenceProperties( MetadataImageKind.Assembly, projectReference.Aliases, projectReference.EmbedInteropTypes); AddMetadataReferenceCore(MetadataReferenceProvider.CreateMetadataReference(this, binPath, metadataReferenceProperties)); Contract.ThrowIfFalse(RemoveMetadataFileNameToConvertedProjectReference(binPath)); } } protected void UpdateMetadataReferenceAliases(string file, ImmutableArray<string> aliases) { file = FileUtilities.NormalizeAbsolutePath(file); // Have we converted these to project references? if (TryGetMetadataFileNameToConvertedProjectReference(file, out var convertedProjectReference)) { var project = ProjectTracker.GetProject(convertedProjectReference.ProjectId); UpdateProjectReferenceAliases(project, aliases); } else { var existingReference = TryGetCurrentMetadataReference(file); Contract.ThrowIfNull(existingReference); var newProperties = existingReference.Properties.WithAliases(aliases); RemoveMetadataReferenceCore(existingReference, disposeReference: true); AddMetadataReferenceCore(this.MetadataReferenceProvider.CreateMetadataReference(this, file, newProperties)); } } protected void UpdateProjectReferenceAliases(AbstractProject referencedProject, ImmutableArray<string> aliases) { var projectReference = GetCurrentProjectReferences().Single(r => r.ProjectId == referencedProject.Id); var newProjectReference = new ProjectReference(referencedProject.Id, aliases, projectReference.EmbedInteropTypes); // Is this a project with converted references? If so, make sure we track it string referenceBinPath = referencedProject.BinOutputPath; if (referenceBinPath != null && HasMetadataFileNameToConvertedProjectReference(referenceBinPath)) { UpdateMetadataFileNameToConvertedProjectReference(referenceBinPath, newProjectReference); } // Remove the existing reference first RemoveProjectReference(projectReference); AddProjectReference(newProjectReference); } private void UninitializeDocument(IVisualStudioHostDocument document) { if (_pushingChangesToWorkspaceHosts) { if (document.IsOpen) { this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentClosed(document.Id, document.GetOpenTextBuffer(), document.Loader, updateActiveContext: true)); } this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentRemoved(document.Id)); } document.Opened -= s_documentOpenedEventHandler; document.Closing -= s_documentClosingEventHandler; document.UpdatedOnDisk -= s_documentUpdatedOnDiskEventHandler; document.Dispose(); } private void UninitializeAdditionalDocument(IVisualStudioHostDocument document) { if (_pushingChangesToWorkspaceHosts) { if (document.IsOpen) { this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentClosed(document.Id, document.GetOpenTextBuffer(), document.Loader)); } this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentRemoved(document.Id)); } document.Opened -= s_additionalDocumentOpenedEventHandler; document.Closing -= s_additionalDocumentClosingEventHandler; document.UpdatedOnDisk -= s_additionalDocumentUpdatedOnDiskEventHandler; document.Dispose(); } protected virtual void OnDocumentRemoved(string filePath) { } internal void StartPushingToWorkspaceHosts() { _pushingChangesToWorkspaceHosts = true; } internal void StopPushingToWorkspaceHosts() { _pushingChangesToWorkspaceHosts = false; } internal void StartPushingToWorkspaceAndNotifyOfOpenDocuments() { StartPushingToWorkspaceAndNotifyOfOpenDocuments(this); } internal bool PushingChangesToWorkspaceHosts { get { return _pushingChangesToWorkspaceHosts; } } protected void UpdateRuleSetError(IRuleSetFile ruleSetFile) { if (this.HostDiagnosticUpdateSource == null) { return; } if (ruleSetFile == null || ruleSetFile.GetException() == null) { this.HostDiagnosticUpdateSource.ClearDiagnosticsForProject(this.Id, RuleSetErrorId); } else { var messageArguments = new string[] { ruleSetFile.FilePath, ruleSetFile.GetException().Message }; if (DiagnosticData.TryCreate(_errorReadingRulesetRule, messageArguments, this.Id, this.Workspace, out var diagnostic)) { this.HostDiagnosticUpdateSource.UpdateDiagnosticsForProject(this.Id, RuleSetErrorId, SpecializedCollections.SingletonEnumerable(diagnostic)); } } } protected void SetObjOutputPathAndRelatedData(string objOutputPath) { var currentObjOutputPath = this.ObjOutputPath; if (PathUtilities.IsAbsolute(objOutputPath) && !string.Equals(currentObjOutputPath, objOutputPath, StringComparison.OrdinalIgnoreCase)) { // set obj output path this.ObjOutputPath = objOutputPath; // Workspace/services can be null for tests. if (this.MetadataService != null) { var newCompilationOptions = CurrentCompilationOptions.WithMetadataReferenceResolver(CreateMetadataReferenceResolver( metadataService: this.MetadataService, projectDirectory: this.ContainingDirectoryPathOpt, outputDirectory: Path.GetDirectoryName(objOutputPath))); SetOptionsCore(newCompilationOptions); } if (_pushingChangesToWorkspaceHosts) { this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnOptionsChanged(this.Id, CurrentCompilationOptions, CurrentParseOptions)); this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnOutputFilePathChanged(this.Id, objOutputPath)); } UpdateAssemblyName(); } } private void UpdateAssemblyName() { // set assembly name if changed // we use designTimeOutputPath to get assembly name since it is more reliable way to get the assembly name. // otherwise, friend assembly all get messed up. var newAssemblyName = GetAssemblyNameFromPath(this.ObjOutputPath ?? this.ProjectSystemName); if (!string.Equals(AssemblyName, newAssemblyName, StringComparison.Ordinal)) { AssemblyName = newAssemblyName; if (_pushingChangesToWorkspaceHosts) { this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAssemblyNameChanged(this.Id, newAssemblyName)); } } } protected void SetBinOutputPathAndRelatedData(string binOutputPath) { // refresh final output path var currentBinOutputPath = this.BinOutputPath; if (binOutputPath != null && !string.Equals(currentBinOutputPath, binOutputPath, StringComparison.OrdinalIgnoreCase)) { this.BinOutputPath = binOutputPath; // If the project has been hooked up with the project tracker, then update the bin path with the tracker. if (this.ProjectTracker.GetProject(Id) != null) { this.ProjectTracker.UpdateProjectBinPath(this, currentBinOutputPath, binOutputPath); } } } protected void UpdateProjectDisplayName(string newDisplayName) { UpdateProjectDisplayNameAndFilePath(newDisplayName, newFilePath: null); } protected void UpdateProjectFilePath(string newFilePath) { UpdateProjectDisplayNameAndFilePath(newDisplayName: null, newFilePath: newFilePath); } protected void UpdateProjectDisplayNameAndFilePath(string newDisplayName, string newFilePath) { bool updateMade = false; if (newDisplayName != null && this.DisplayName != newDisplayName) { this.DisplayName = newDisplayName; updateMade = true; } if (newFilePath != null && File.Exists(newFilePath) && this.ProjectFilePath != newFilePath) { Debug.Assert(PathUtilities.IsAbsolute(newFilePath)); this.ProjectFilePath = newFilePath; updateMade = true; } if (updateMade && _pushingChangesToWorkspaceHosts) { this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnProjectNameChanged(Id, this.DisplayName, this.ProjectFilePath)); } } private static void StartPushingToWorkspaceAndNotifyOfOpenDocuments(AbstractProject project) { // If a document is opened in a project but we haven't started pushing yet, we want to stop doing lazy // loading for this project and get it up to date so the user gets a fast experience there. If the file // was presented as open to us right away, then we'll never do this in OnDocumentOpened, so we should do // it here. It's important to do this after everything else happens in this method, so we don't get // strange ordering issues. It's still possible that this won't actually push changes if the workspace // host isn't ready to receive events yet. project.ProjectTracker.StartPushingToWorkspaceAndNotifyOfOpenDocuments(SpecializedCollections.SingletonEnumerable(project)); } private static MetadataReferenceResolver CreateMetadataReferenceResolver(IMetadataService metadataService, string projectDirectory, string outputDirectory) { ImmutableArray<string> assemblySearchPaths; if (projectDirectory != null && outputDirectory != null) { assemblySearchPaths = ImmutableArray.Create(projectDirectory, outputDirectory); } else if (projectDirectory != null) { assemblySearchPaths = ImmutableArray.Create(projectDirectory); } else if (outputDirectory != null) { assemblySearchPaths = ImmutableArray.Create(outputDirectory); } else { assemblySearchPaths = ImmutableArray<string>.Empty; } return new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(assemblySearchPaths, baseDirectory: projectDirectory)); } #if DEBUG public virtual bool Debug_VBEmbeddedCoreOptionOn { get { return false; } } #endif /// <summary> /// Used for unit testing: don't crash the process if something bad happens. /// </summary> internal static bool CrashOnException = true; protected static bool FilterException(Exception e) { if (CrashOnException) { FatalError.Report(e); } // Nothing fancy, so don't catch return false; } #region FolderNames private readonly List<string> _tmpFolders = new List<string>(); private readonly Dictionary<uint, IReadOnlyList<string>> _folderNameMap = new Dictionary<uint, IReadOnlyList<string>>(); public IReadOnlyList<string> GetFolderNamesFromHierarchy(uint documentItemID) { if (documentItemID != (uint)VSConstants.VSITEMID.Nil && Hierarchy.GetProperty(documentItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK) { var parentID = UnboxVSItemId(parentObj); if (parentID != (uint)VSConstants.VSITEMID.Nil && parentID != (uint)VSConstants.VSITEMID.Root) { return GetFolderNamesForFolder(parentID); } } return SpecializedCollections.EmptyReadOnlyList<string>(); } private IReadOnlyList<string> GetFolderNamesForFolder(uint folderItemID) { // note: use of tmpFolders is assuming this API is called on UI thread only. _tmpFolders.Clear(); if (!_folderNameMap.TryGetValue(folderItemID, out var names)) { ComputeFolderNames(folderItemID, _tmpFolders, Hierarchy); names = _tmpFolders.ToImmutableArray(); _folderNameMap.Add(folderItemID, names); } else { // verify names, and change map if we get a different set. // this is necessary because we only get document adds/removes from the project system // when a document name or folder name changes. ComputeFolderNames(folderItemID, _tmpFolders, Hierarchy); if (!Enumerable.SequenceEqual(names, _tmpFolders)) { names = _tmpFolders.ToImmutableArray(); _folderNameMap[folderItemID] = names; } } return names; } // Different hierarchies are inconsistent on whether they return ints or uints for VSItemIds. // Technically it should be a uint. However, there's no enforcement of this, and marshalling // from native to managed can end up resulting in boxed ints instead. Handle both here so // we're resilient to however the IVsHierarchy was actually implemented. private static uint UnboxVSItemId(object id) { return id is uint ? (uint)id : unchecked((uint)(int)id); } private static void ComputeFolderNames(uint folderItemID, List<string> names, IVsHierarchy hierarchy) { if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Name, out var nameObj) == VSConstants.S_OK) { // For 'Shared' projects, IVSHierarchy returns a hierarchy item with < character in its name (i.e. <SharedProjectName>) // as a child of the root item. There is no such item in the 'visual' hierarchy in solution explorer and no such folder // is present on disk either. Since this is not a real 'folder', we exclude it from the contents of Document.Folders. // Note: The parent of the hierarchy item that contains < character in its name is VSITEMID.Root. So we don't need to // worry about accidental propagation out of the Shared project to any containing 'Solution' folders - the check for // VSITEMID.Root below already takes care of that. var name = (string)nameObj; if (!name.StartsWith("<", StringComparison.OrdinalIgnoreCase)) { names.Insert(0, name); } } if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK) { var parentID = UnboxVSItemId(parentObj); if (parentID != (uint)VSConstants.VSITEMID.Nil && parentID != (uint)VSConstants.VSITEMID.Root) { ComputeFolderNames(parentID, names, hierarchy); } } } #endregion } }
using ShopifySharp.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Xunit; using EmptyAssert = ShopifySharp.Tests.Extensions.EmptyExtensions; namespace ShopifySharp.Tests { [Trait("Category", "Customer")] public class Customer_Tests : IClassFixture<Customer_Tests_Fixture> { private Customer_Tests_Fixture Fixture { get; } public Customer_Tests(Customer_Tests_Fixture fixture) { this.Fixture = fixture; } [Fact] public async Task Counts_Customers() { var count = await Fixture.Service.CountAsync(); Assert.True(count > 0); } [Fact] public async Task Lists_Customers() { var list = await Fixture.Service.ListAsync(); Assert.True(list.Items.Count() > 0); } [Fact] public async Task Deletes_Customers() { var created = await Fixture.Create(); bool threw = false; try { await Fixture.Service.DeleteAsync(created.Id.Value); } catch (ShopifyException ex) { Console.WriteLine($"{nameof(Deletes_Customers)} failed. {ex.Message}"); threw = true; } Assert.False(threw); } [Fact] public async Task Gets_Customers() { var customer = await Fixture.Service.GetAsync(Fixture.Created.First().Id.Value); Assert.NotNull(customer); Assert.Equal(Fixture.FirstName, customer.FirstName); Assert.Equal(Fixture.LastName, customer.LastName); Assert.Equal(Fixture.Note, customer.Note); Assert.NotNull(customer.Addresses); Assert.NotNull(customer.DefaultAddress); } [Fact] public async Task Gets_Customers_With_Options() { var customer = await Fixture.Service.GetAsync(Fixture.Created.First().Id.Value, "first_name,last_name"); Assert.NotNull(customer); Assert.Equal(Fixture.FirstName, customer.FirstName); Assert.Equal(Fixture.LastName, customer.LastName); EmptyAssert.NullOrEmpty(customer.Note); EmptyAssert.NullOrEmpty(customer.Addresses); Assert.Null(customer.DefaultAddress); } [Fact] public async Task Creates_Customers() { var customer = await Fixture.Create(); Assert.NotNull(customer); Assert.Equal(Fixture.FirstName, customer.FirstName); Assert.Equal(Fixture.LastName, customer.LastName); Assert.Equal(Fixture.Note, customer.Note); Assert.NotNull(customer.Addresses); } [Fact] public async Task Creates_Customers_With_Options() { var customer = await Fixture.Create(options: new CustomerCreateOptions() { Password = "loktarogar", PasswordConfirmation = "loktarogar", SendEmailInvite = false, SendWelcomeEmail = false, }); Assert.NotNull(customer); Assert.Equal(Fixture.FirstName, customer.FirstName); Assert.Equal(Fixture.LastName, customer.LastName); Assert.Equal(Fixture.Note, customer.Note); Assert.NotNull(customer.Addresses); } [Fact] public async Task Updates_Customers() { string firstName = "Jane"; var created = await Fixture.Create(); long id = created.Id.Value; created.FirstName = firstName; created.Id = null; var updated = await Fixture.Service.UpdateAsync(id, created); // Reset the id so the Fixture can properly delete this object. created.Id = id; Assert.Equal(firstName, updated.FirstName); } [Fact] public async Task Updates_Customers_With_Options() { string firstName = "Jane"; var created = await Fixture.Create(); long id = created.Id.Value; created.FirstName = firstName; created.Id = null; var updated = await Fixture.Service.UpdateAsync(id, created, new CustomerUpdateOptions() { Password = "loktarogar", PasswordConfirmation = "loktarogar" }); // Reset the id so the Fixture can properly delete this object. created.Id = id; Assert.Equal(firstName, updated.FirstName); } [Fact] public async Task Searches_For_Customers() { // It takes anywhere between 3 seconds to 30 seconds for Shopify to index new customers for searches. // Rather than putting a 20 second Thread.Sleep in the test, we'll just assume it's successful if the // test doesn't throw an exception. bool threw = false; try { var search = await Fixture.Service.SearchAsync(new CustomerSearchListFilter { Query = "John" }); } catch (ShopifyException ex) { Console.WriteLine($"{nameof(Searches_For_Customers)} failed. {ex.Message}"); threw = true; } Assert.False(threw); } [Fact] public async Task Can_Be_Partially_Updated() { string newFirstName = "Sheev"; string newLastName = "Palpatine"; var created = await Fixture.Create(); var updated = await Fixture.Service.UpdateAsync(created.Id.Value, new Customer() { FirstName = newFirstName, LastName = newLastName }); Assert.Equal(created.Id, updated.Id); Assert.Equal(newFirstName, updated.FirstName); Assert.Equal(newLastName, updated.LastName); // In previous versions of ShopifySharp, the updated JSON would have sent 'email=null' or 'note=null', clearing out the email address. Assert.Equal(created.Email, updated.Email); Assert.Equal(created.Note, updated.Note); } [Fact] public async Task SendInvite_Customers_Default() { var created = await Fixture.Create(); long id = created.Id.Value; var invite = await Fixture.Service.SendInviteAsync(created.Id.Value); Assert.NotNull(invite); } [Fact] public async Task SendInvite_Customers_Custom() { var created = await Fixture.Create(); long id = created.Id.Value; var options = new CustomerInvite() { Subject = "Custom Subject courtesy of ShopifySharp", CustomMessage = "Custom Message courtesy of ShopifySharp" }; var invite = await Fixture.Service.SendInviteAsync(created.Id.Value, options); Assert.NotNull(invite); Assert.Equal(options.Subject, invite.Subject); Assert.Equal(options.CustomMessage, invite.CustomMessage); } [Fact] public async Task GetAccountActivationUrl_Customers() { var created = await Fixture.Create(); long id = created.Id.Value; var url = await Fixture.Service.GetAccountActivationUrl(created.Id.Value); Assert.NotEmpty(url); Assert.Contains("account/activate", url); } } public class Customer_Tests_Fixture : IAsyncLifetime { public CustomerService Service { get; } = new CustomerService(Utils.MyShopifyUrl, Utils.AccessToken); public List<Customer> Created { get; } = new List<Customer>(); public string FirstName => "John"; public string LastName => "Doe"; public string Note => "Test note about this customer."; public async Task InitializeAsync() { Service.SetExecutionPolicy(new LeakyBucketExecutionPolicy()); // Create one customer for use with count, list, get, etc. tests. await Create(); } public async Task DisposeAsync() { foreach (var obj in Created) { try { await Service.DeleteAsync(obj.Id.Value); } catch (ShopifyException ex) { if (ex.HttpStatusCode != HttpStatusCode.NotFound) { Console.WriteLine($"Failed to delete created Customer with id {obj.Id.Value}. {ex.Message}"); } } } } public async Task<Customer> Create(bool skipAddToCreatedList = false, CustomerCreateOptions options = null) { var obj = await Service.CreateAsync(new Customer() { FirstName = FirstName, LastName = LastName, Email = Guid.NewGuid().ToString() + "@example.com", Addresses = new List<Address>() { new Address() { Address1 = "123 4th Street", City = "Minneapolis", Province = "Minnesota", ProvinceCode = "MN", Zip = "55401", Phone = "555-555-5555", FirstName = "John", LastName = "Doe", Company = "Tomorrow Corporation", Country = "United States", CountryCode = "US", Default = true, } }, VerifiedEmail = true, Note = Note, State = "enabled" }, options); if (!skipAddToCreatedList) { Created.Add(obj); } return obj; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using System; using System.Collections.Generic; using Markdig.Helpers; using Markdig.Parsers; using Markdig.Syntax; using Markdig.Syntax.Inlines; namespace Markdig.Extensions.Abbreviations { /// <summary> /// A block parser for abbreviations. /// </summary> /// <seealso cref="BlockParser" /> public class AbbreviationParser : BlockParser { /// <summary> /// Initializes a new instance of the <see cref="AbbreviationParser"/> class. /// </summary> public AbbreviationParser() { OpeningCharacters = new[] { '*' }; } public override BlockState TryOpen(BlockProcessor processor) { if (processor.IsCodeIndent) { return BlockState.None; } // A link must be of the form *[Some Text]: An abbreviation var slice = processor.Line; var startPosition = slice.Start; var c = slice.NextChar(); if (c != '[') { return BlockState.None; } if (!LinkHelper.TryParseLabel(ref slice, out string label, out SourceSpan labelSpan)) { return BlockState.None; } c = slice.CurrentChar; if (c != ':') { return BlockState.None; } slice.NextChar(); slice.Trim(); var abbr = new Abbreviation(this) { Label = label, Text = slice, Span = new SourceSpan(startPosition, slice.End), Line = processor.LineIndex, Column = processor.Column, LabelSpan = labelSpan, }; if (!processor.Document.HasAbbreviations()) { processor.Document.ProcessInlinesBegin += DocumentOnProcessInlinesBegin; } processor.Document.AddAbbreviation(abbr.Label, abbr); return BlockState.BreakDiscard; } private void DocumentOnProcessInlinesBegin(InlineProcessor inlineProcessor, Inline inline) { inlineProcessor.Document.ProcessInlinesBegin -= DocumentOnProcessInlinesBegin; var abbreviations = inlineProcessor.Document.GetAbbreviations(); // Should not happen, but another extension could decide to remove them, so... if (abbreviations == null) { return; } // Build a text matcher from the abbreviations labels var prefixTree = new CompactPrefixTree<Abbreviation>(abbreviations); inlineProcessor.LiteralInlineParser.PostMatch += (InlineProcessor processor, ref StringSlice slice) => { var literal = (LiteralInline)processor.Inline; var originalLiteral = literal; ContainerInline container = null; // This is slow, but we don't have much the choice var content = literal.Content; var text = content.Text; for (int i = content.Start; i <= content.End; i++) { // Abbreviation must be a whole word == start at the start of a line or after a whitespace if (i != 0) { for (i = i - 1; i <= content.End; i++) { if (text[i].IsWhitespace()) { i++; goto ValidAbbreviationStart; } } break; } ValidAbbreviationStart:; if (prefixTree.TryMatchLongest(text.AsSpan(i, content.End - i + 1), out KeyValuePair<string, Abbreviation> abbreviationMatch)) { var match = abbreviationMatch.Key; if (!IsValidAbbreviationEnding(match, content, i)) { continue; } var indexAfterMatch = i + match.Length; // If we don't have a container, create a new one if (container == null) { container = literal.Parent ?? new ContainerInline { Span = originalLiteral.Span, Line = originalLiteral.Line, Column = originalLiteral.Column, }; } var abbrInline = new AbbreviationInline(abbreviationMatch.Value) { Span = { Start = processor.GetSourcePosition(i, out int line, out int column), }, Line = line, Column = column }; abbrInline.Span.End = abbrInline.Span.Start + match.Length - 1; // Append the previous literal if (i > content.Start && literal.Parent == null) { container.AppendChild(literal); } literal.Span.End = abbrInline.Span.Start - 1; // Truncate it before the abbreviation literal.Content.End = i - 1; // Append the abbreviation container.AppendChild(abbrInline); // If this is the end of the string, clear the literal and exit if (content.End == indexAfterMatch - 1) { literal = null; break; } // Process the remaining literal literal = new LiteralInline() { Span = new SourceSpan(abbrInline.Span.End + 1, literal.Span.End), Line = line, Column = column + match.Length, }; content.Start = indexAfterMatch; literal.Content = content; i = indexAfterMatch - 1; } } if (container != null) { if (literal != null) { container.AppendChild(literal); } processor.Inline = container; } }; } private static bool IsValidAbbreviationEnding(string match, StringSlice content, int matchIndex) { // This will check if the next char at the end of the StringSlice is whitespace, punctuation or \0. var contentNew = content; contentNew.End = content.End + 1; int index = matchIndex + match.Length; while (index <= contentNew.End) { var c = contentNew.PeekCharAbsolute(index); if (!(c == '\0' || c.IsWhitespace() || c.IsAsciiPunctuation())) { return false; } if (c.IsAlphaNumeric()) { return false; } if (c.IsWhitespace()) { break; } index++; } return true; } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Windows.Forms; namespace MapTableCreator { class Parser { public static SortedDictionary<ushort, ushort> table = new SortedDictionary<ushort, ushort>(); private static ushort AddToDictinary(ushort key, ushort value) { ushort valued; lock (table) { if (!table.TryGetValue(key, out valued)) table.Add(key, value); else { if (value != valued) return valued; } } return 0; } private BinaryReader br; private TextWriter err,output; private bool writeonlyfiles, tilecheck, staticcheck, delimitercheck; private const ushort BLOCK_WIDTH = 64; private const ushort BLOCK_HEIGHT = 64; private const ushort YBLOCKS = 64; private MapPoint mp; private ushort fileid; private void WriteFileErr(String towrite) { lock(err) { err.WriteLine(towrite); } } private void WriteFileOut(String towrite) { lock (output) { output.Write(towrite); } } public Parser(string filename,TextWriter err,TextWriter output, bool writeonlyfiles, bool delimitercheck,bool staticcheck,bool tilecheck) { br = new BinaryReader(File.OpenRead(filename)); this.err =err; this.output=output; this.writeonlyfiles = writeonlyfiles; this.delimitercheck = delimitercheck; this.tilecheck = tilecheck; this.staticcheck = staticcheck; } private ushort AdjustX(ushort x) { ushort XBlock = (ushort)(fileid / YBLOCKS); return (ushort)(XBlock * YBLOCKS + x); } private ushort AdjustY(ushort y) { ushort YBlock = (ushort)(fileid / YBLOCKS); YBlock = (ushort)(fileid - YBlock * YBLOCKS); return (ushort)(YBlock * YBLOCKS + y); } private Landtile ReadLandtile() { Landtile l = new Landtile(); l.z = br.ReadSByte(); l.KRGraphic = br.ReadUInt16(); l.Type3 = br.ReadByte(); l.MLGraphic = br.ReadUInt16(); ushort value = AddToDictinary(l.MLGraphic, l.KRGraphic); if (value!=0) WriteFileErr("FileID=" + fileid + ", Error X=" + mp.x + " (offset " + mp.offsetx + "), Y=" + mp.y + " (offset " + mp.offsety + "), KR Graphic: " + value + ", for ML: " + l.MLGraphic + " inserted another: " + l.KRGraphic); if(l.Type3!=0 && mp.x<6144) WriteFileErr("FileID="+fileid + ", Error X=" + mp.x + " (offset " + mp.offsetx + "), Y=" + mp.y + " (offset " + mp.offsety + "), Type3 is: " +l.Type3+", KR Graphic: "+l.KRGraphic+" ML:"+l.MLGraphic); return l; } private Static ReadStatic() { Static s = new Static(); s.graphic = br.ReadUInt16(); ushort zero=br.ReadUInt16(); if (zero != 0) WriteFileErr("FileID=" + fileid + ", X=" + mp.x + " (offset " + mp.offsetx + "), Y=" + mp.y + " (offset " + mp.offsety + "), error static two zero byte is not zero: " + zero); s.z = br.ReadSByte(); s.color = br.ReadUInt16(); return s; } private Delimiter ReadDelimiter() { Delimiter d = new Delimiter(); d.direction = (DelimiterDirection)br.ReadByte(); d.z = br.ReadSByte(); d.graphic = br.ReadUInt16(); d.unk=br.ReadByte(); if (mp.offsetx != 63 && mp.offsetx != 0 && mp.offsety != 63 && mp.offsety != 0) { WriteFileErr("FileID=" + fileid + ", X=" + mp.x + " (offset " + mp.offsetx + "), Y=" + mp.y + " (offset " + mp.offsety + "), error delimiter!"); } return d; } public BlockFile Parse() { BlockFile result = new BlockFile(); result.header.facet=br.ReadByte(); result.header.FileID = br.ReadUInt16(); fileid = result.header.FileID; if (output != null) WriteFileOut(result.header.Dump()); mp = new MapPoint(); mp.offsetx = 0; mp.x = AdjustX(0); mp.offsety = 0; mp.y = AdjustY(0); mp.lt = ReadLandtile(); ushort currentx=0; ushort currenty=0; byte type1,type2; while (br.BaseStream.Position < br.BaseStream.Length - 3) { type1 = br.ReadByte(); type2 = br.ReadByte(); if (type1 == 0 && type2 == 0) //Landtile { currenty++; if (currenty == BLOCK_HEIGHT) { currentx++; currenty = 0; if (currentx >= BLOCK_WIDTH) WriteFileErr("FileID=" + fileid + ", ERROR X is too huge: " + currentx); } if ((mp.delimiter_list.Count > 0 && delimitercheck) || (mp.static_list.Count > 0 && staticcheck) || (mp.delimiter_list.Count == 0 && mp.static_list.Count == 0 && tilecheck)) { if(!writeonlyfiles) result.blocks.Add(mp); if(output!=null) WriteFileOut(mp.Dump()); } mp = new MapPoint(); mp.offsetx = currentx; mp.x = AdjustX(currentx); mp.offsety = currenty; mp.y = AdjustY(currenty); mp.lt=ReadLandtile(); } else if (type1 == 0 && type2 != 0) //Static { for (int i = 0; i < type2; i++) { if (i > 0) { ushort zero = br.ReadUInt16(); if (zero != 0) WriteFileErr("FileID=" + fileid + ", X=" + AdjustX(currentx) + " (offset " + currentx + "), Y=" + AdjustY(currenty) + " (offset " + currenty + "), error static header placeholder zero byte is not zero: " + zero); } mp.static_list.Add(ReadStatic()); } } else if (type1 > 0) { br.BaseStream.Position--; for (int i = 0; i < type1; i++) { if (i > 0) { byte zero = br.ReadByte(); if (zero != 0) WriteFileErr("FileID=" + fileid + ", X=" + AdjustX(currentx) + " (offset " + currentx + "), Y=" + AdjustY(currenty) + " (offset " + currenty + "), error delimiter type1 placeholder zero byte is not zero: " + zero); } mp.delimiter_list.Add(ReadDelimiter()); } } else WriteFileErr("FileID=" + fileid + ", ERROR Type undefined, type1:" + type1 + ", type2:" + type2); } if ((mp.delimiter_list.Count > 0 && delimitercheck) || (mp.static_list.Count > 0 && staticcheck) || (mp.delimiter_list.Count == 0 && mp.static_list.Count == 0 && tilecheck)) { if (!writeonlyfiles) result.blocks.Add(mp); if (output != null) WriteFileOut(mp.Dump()); } br.Close(); return result; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; // using log4net; // using System.Reflection; /***************************************************** * * WorldCommModule * * * Holding place for world comms - basically llListen * function implementation. * * lLListen(integer channel, string name, key id, string msg) * The name, id, and msg arguments specify the filtering * criteria. You can pass the empty string * (or NULL_KEY for id) for these to set a completely * open filter; this causes the listen() event handler to be * invoked for all chat on the channel. To listen only * for chat spoken by a specific object or avatar, * specify the name and/or id arguments. To listen * only for a specific command, specify the * (case-sensitive) msg argument. If msg is not empty, * listener will only hear strings which are exactly equal * to msg. You can also use all the arguments to establish * the most restrictive filtering criteria. * * It might be useful for each listener to maintain a message * digest, with a list of recent messages by UUID. This can * be used to prevent in-world repeater loops. However, the * linden functions do not have this capability, so for now * thats the way it works. * Instead it blocks messages originating from the same prim. * (not Object!) * * For LSL compliance, note the following: * (Tested again 1.21.1 on May 2, 2008) * 1. 'id' has to be parsed into a UUID. None-UUID keys are * to be replaced by the ZeroID key. (Well, TryParse does * that for us. * 2. Setting up an listen event from the same script, with the * same filter settings (including step 1), returns the same * handle as the original filter. * 3. (TODO) handles should be script-local. Starting from 1. * Might be actually easier to map the global handle into * script-local handle in the ScriptEngine. Not sure if its * worth the effort tho. * * **************************************************/ namespace OpenSim.Region.CoreModules.Scripting.WorldComm { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WorldCommModule")] public class WorldCommModule : IWorldComm, INonSharedRegionModule { // private static readonly ILog m_log = // LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int DEBUG_CHANNEL = 2147483647; private ListenerManager m_listenerManager; private Queue m_pending; private Queue m_pendingQ; private Scene m_scene; private int m_whisperdistance = 10; private int m_saydistance = 20; private int m_shoutdistance = 100; #region INonSharedRegionModule Members public void Initialise(IConfigSource config) { // wrap this in a try block so that defaults will work if // the config file doesn't specify otherwise. int maxlisteners = 1000; int maxhandles = 64; try { m_whisperdistance = config.Configs["Chat"].GetInt( "whisper_distance", m_whisperdistance); m_saydistance = config.Configs["Chat"].GetInt( "say_distance", m_saydistance); m_shoutdistance = config.Configs["Chat"].GetInt( "shout_distance", m_shoutdistance); maxlisteners = config.Configs["LL-Functions"].GetInt( "max_listens_per_region", maxlisteners); maxhandles = config.Configs["LL-Functions"].GetInt( "max_listens_per_script", maxhandles); } catch (Exception) { } if (maxlisteners < 1) maxlisteners = int.MaxValue; if (maxhandles < 1) maxhandles = int.MaxValue; m_listenerManager = new ListenerManager(maxlisteners, maxhandles); m_pendingQ = new Queue(); m_pending = Queue.Synchronized(m_pendingQ); } public void PostInitialise() { } public void AddRegion(Scene scene) { m_scene = scene; m_scene.RegisterModuleInterface<IWorldComm>(this); m_scene.EventManager.OnChatFromClient += DeliverClientMessage; m_scene.EventManager.OnChatBroadcast += DeliverClientMessage; } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { if (scene != m_scene) return; m_scene.UnregisterModuleInterface<IWorldComm>(this); m_scene.EventManager.OnChatBroadcast -= DeliverClientMessage; m_scene.EventManager.OnChatBroadcast -= DeliverClientMessage; } public void Close() { } public string Name { get { return "WorldCommModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion #region IWorldComm Members public int ListenerCount { get { return m_listenerManager.ListenerCount; } } /// <summary> /// Create a listen event callback with the specified filters. /// The parameters localID,itemID are needed to uniquely identify /// the script during 'peek' time. Parameter hostID is needed to /// determine the position of the script. /// </summary> /// <param name="localID">localID of the script engine</param> /// <param name="itemID">UUID of the script engine</param> /// <param name="hostID">UUID of the SceneObjectPart</param> /// <param name="channel">channel to listen on</param> /// <param name="name">name to filter on</param> /// <param name="id"> /// key to filter on (user given, could be totally faked) /// </param> /// <param name="msg">msg to filter on</param> /// <returns>number of the scripts handle</returns> public int Listen(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg) { return m_listenerManager.AddListener(localID, itemID, hostID, channel, name, id, msg); } /// <summary> /// Create a listen event callback with the specified filters. /// The parameters localID,itemID are needed to uniquely identify /// the script during 'peek' time. Parameter hostID is needed to /// determine the position of the script. /// </summary> /// <param name="localID">localID of the script engine</param> /// <param name="itemID">UUID of the script engine</param> /// <param name="hostID">UUID of the SceneObjectPart</param> /// <param name="channel">channel to listen on</param> /// <param name="name">name to filter on</param> /// <param name="id"> /// key to filter on (user given, could be totally faked) /// </param> /// <param name="msg">msg to filter on</param> /// <param name="regexBitfield"> /// Bitfield indicating which strings should be processed as regex. /// </param> /// <returns>number of the scripts handle</returns> public int Listen(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg, int regexBitfield) { return m_listenerManager.AddListener(localID, itemID, hostID, channel, name, id, msg, regexBitfield); } /// <summary> /// Sets the listen event with handle as active (active = TRUE) or inactive (active = FALSE). /// The handle used is returned from Listen() /// </summary> /// <param name="itemID">UUID of the script engine</param> /// <param name="handle">handle returned by Listen()</param> /// <param name="active">temp. activate or deactivate the Listen()</param> public void ListenControl(UUID itemID, int handle, int active) { if (active == 1) m_listenerManager.Activate(itemID, handle); else if (active == 0) m_listenerManager.Dectivate(itemID, handle); } /// <summary> /// Removes the listen event callback with handle /// </summary> /// <param name="itemID">UUID of the script engine</param> /// <param name="handle">handle returned by Listen()</param> public void ListenRemove(UUID itemID, int handle) { m_listenerManager.Remove(itemID, handle); } /// <summary> /// Removes all listen event callbacks for the given itemID /// (script engine) /// </summary> /// <param name="itemID">UUID of the script engine</param> public void DeleteListener(UUID itemID) { m_listenerManager.DeleteListener(itemID); } protected static Vector3 CenterOfRegion = new Vector3(128, 128, 20); public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg) { Vector3 position; SceneObjectPart source; ScenePresence avatar; if ((source = m_scene.GetSceneObjectPart(id)) != null) position = source.AbsolutePosition; else if ((avatar = m_scene.GetScenePresence(id)) != null) position = avatar.AbsolutePosition; else if (ChatTypeEnum.Region == type) position = CenterOfRegion; else return; DeliverMessage(type, channel, name, id, msg, position); } /// <summary> /// This method scans over the objects which registered an interest in listen callbacks. /// For everyone it finds, it checks if it fits the given filter. If it does, then /// enqueue the message for delivery to the objects listen event handler. /// The enqueued ListenerInfo no longer has filter values, but the actually trigged values. /// Objects that do an llSay have their messages delivered here and for nearby avatars, /// the OnChatFromClient event is used. /// </summary> /// <param name="type">type of delvery (whisper,say,shout or regionwide)</param> /// <param name="channel">channel to sent on</param> /// <param name="name">name of sender (object or avatar)</param> /// <param name="id">key of sender (object or avatar)</param> /// <param name="msg">msg to sent</param> public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg, Vector3 position) { // m_log.DebugFormat("[WorldComm] got[2] type {0}, channel {1}, name {2}, id {3}, msg {4}", // type, channel, name, id, msg); // Determine which listen event filters match the given set of arguments, this results // in a limited set of listeners, each belonging a host. If the host is in range, add them // to the pending queue. foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg)) { // Dont process if this message is from yourself! if (li.GetHostID().Equals(id)) continue; SceneObjectPart sPart = m_scene.GetSceneObjectPart( li.GetHostID()); if (sPart == null) continue; double dis = Util.GetDistanceTo(sPart.AbsolutePosition, position); switch (type) { case ChatTypeEnum.Whisper: if (dis < m_whisperdistance) QueueMessage(new ListenerInfo(li, name, id, msg)); break; case ChatTypeEnum.Say: if (dis < m_saydistance) QueueMessage(new ListenerInfo(li, name, id, msg)); break; case ChatTypeEnum.Shout: if (dis < m_shoutdistance) QueueMessage(new ListenerInfo(li, name, id, msg)); break; case ChatTypeEnum.Region: QueueMessage(new ListenerInfo(li, name, id, msg)); break; } } } /// <summary> /// Delivers the message to a scene entity. /// </summary> /// <param name='target'> /// Target. /// </param> /// <param name='channel'> /// Channel. /// </param> /// <param name='name'> /// Name. /// </param> /// <param name='id'> /// Identifier. /// </param> /// <param name='msg'> /// Message. /// </param> public void DeliverMessageTo(UUID target, int channel, Vector3 pos, string name, UUID id, string msg) { if (channel == DEBUG_CHANNEL) return; if(target == UUID.Zero) return; // Is target an avatar? ScenePresence sp = m_scene.GetScenePresence(target); if (sp != null) { // Send message to avatar if (channel == 0) { // Channel 0 goes to viewer ONLY m_scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Broadcast, 0, pos, name, id, target, false, false); return; } // for now messages to prims don't cross regions if(sp.IsChildAgent) return; List<SceneObjectGroup> attachments = sp.GetAttachments(); if (attachments.Count == 0) return; // Get uuid of attachments List<UUID> targets = new List<UUID>(); foreach (SceneObjectGroup sog in attachments) { if (!sog.IsDeleted) { SceneObjectPart[] parts = sog.Parts; foreach(SceneObjectPart p in parts) targets.Add(p.UUID); } } foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg)) { UUID liHostID = li.GetHostID(); if (liHostID.Equals(id)) continue; if (m_scene.GetSceneObjectPart(liHostID) == null) continue; if (targets.Contains(liHostID)) QueueMessage(new ListenerInfo(li, name, id, msg)); } return; } SceneObjectPart part = m_scene.GetSceneObjectPart(target); if (part == null) // Not even an object return; // No error foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg)) { UUID liHostID = li.GetHostID(); // Dont process if this message is from yourself! if (liHostID.Equals(id)) continue; if (m_scene.GetSceneObjectPart(liHostID) == null) continue; if (liHostID.Equals(target)) { QueueMessage(new ListenerInfo(li, name, id, msg)); break; } } } protected void QueueMessage(ListenerInfo li) { lock (m_pending.SyncRoot) { m_pending.Enqueue(li); } } /// <summary> /// Are there any listen events ready to be dispatched? /// </summary> /// <returns>boolean indication</returns> public bool HasMessages() { return (m_pending.Count > 0); } /// <summary> /// Pop the first availlable listen event from the queue /// </summary> /// <returns>ListenerInfo with filter filled in</returns> public IWorldCommListenerInfo GetNextMessage() { ListenerInfo li = null; lock (m_pending.SyncRoot) { li = (ListenerInfo)m_pending.Dequeue(); } return li; } #endregion /******************************************************************** * * Listener Stuff * * *****************************************************************/ private void DeliverClientMessage(Object sender, OSChatMessage e) { if (null != e.Sender) { DeliverMessage(e.Type, e.Channel, e.Sender.Name, e.Sender.AgentId, e.Message, e.Position); } else { DeliverMessage(e.Type, e.Channel, e.From, UUID.Zero, e.Message, e.Position); } } public Object[] GetSerializationData(UUID itemID) { return m_listenerManager.GetSerializationData(itemID); } public void CreateFromData(uint localID, UUID itemID, UUID hostID, Object[] data) { m_listenerManager.AddFromData(localID, itemID, hostID, data); } } public class ListenerManager { private Dictionary<int, List<ListenerInfo>> m_listeners = new Dictionary<int, List<ListenerInfo>>(); private int m_maxlisteners; private int m_maxhandles; private int m_curlisteners; /// <summary> /// Total number of listeners /// </summary> public int ListenerCount { get { lock (m_listeners) return m_listeners.Count; } } public ListenerManager(int maxlisteners, int maxhandles) { m_maxlisteners = maxlisteners; m_maxhandles = maxhandles; m_curlisteners = 0; } public int AddListener(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg) { return AddListener(localID, itemID, hostID, channel, name, id, msg, 0); } public int AddListener(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg, int regexBitfield) { // do we already have a match on this particular filter event? List<ListenerInfo> coll = GetListeners(itemID, channel, name, id, msg); if (coll.Count > 0) { // special case, called with same filter settings, return same // handle (2008-05-02, tested on 1.21.1 server, still holds) return coll[0].GetHandle(); } lock (m_listeners) { if (m_curlisteners < m_maxlisteners) { int newHandle = GetNewHandle(itemID); if (newHandle > 0) { ListenerInfo li = new ListenerInfo(newHandle, localID, itemID, hostID, channel, name, id, msg, regexBitfield); List<ListenerInfo> listeners; if (!m_listeners.TryGetValue( channel, out listeners)) { listeners = new List<ListenerInfo>(); m_listeners.Add(channel, listeners); } listeners.Add(li); m_curlisteners++; return newHandle; } } } return -1; } public void Remove(UUID itemID, int handle) { lock (m_listeners) { foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle().Equals(handle)) { lis.Value.Remove(li); if (lis.Value.Count == 0) { m_listeners.Remove(lis.Key); m_curlisteners--; } // there should be only one, so we bail out early return; } } } } } public void DeleteListener(UUID itemID) { List<int> emptyChannels = new List<int>(); List<ListenerInfo> removedListeners = new List<ListenerInfo>(); lock (m_listeners) { foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID)) { // store them first, else the enumerated bails on // us removedListeners.Add(li); } } foreach (ListenerInfo li in removedListeners) { lis.Value.Remove(li); m_curlisteners--; } removedListeners.Clear(); if (lis.Value.Count == 0) { // again, store first, remove later emptyChannels.Add(lis.Key); } } foreach (int channel in emptyChannels) { m_listeners.Remove(channel); } } } public void Activate(UUID itemID, int handle) { lock (m_listeners) { foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle() == handle) { li.Activate(); // only one, bail out return; } } } } } public void Dectivate(UUID itemID, int handle) { lock (m_listeners) { foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle() == handle) { li.Deactivate(); // only one, bail out return; } } } } } /// <summary> /// non-locked access, since its always called in the context of the /// lock /// </summary> /// <param name="itemID"></param> /// <returns></returns> private int GetNewHandle(UUID itemID) { List<int> handles = new List<int>(); // build a list of used keys for this specific itemID... foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID)) handles.Add(li.GetHandle()); } } // Note: 0 is NOT a valid handle for llListen() to return for (int i = 1; i <= m_maxhandles; i++) { if (!handles.Contains(i)) return i; } return -1; } /// These are duplicated from ScriptBaseClass /// http://opensimulator.org/mantis/view.php?id=6106#c21945 #region Constants for the bitfield parameter of osListenRegex /// <summary> /// process name parameter as regex /// </summary> public const int OS_LISTEN_REGEX_NAME = 0x1; /// <summary> /// process message parameter as regex /// </summary> public const int OS_LISTEN_REGEX_MESSAGE = 0x2; #endregion /// <summary> /// Get listeners matching the input parameters. /// </summary> /// <remarks> /// Theres probably a more clever and efficient way to do this, maybe /// with regex. /// PM2008: Ha, one could even be smart and define a specialized /// Enumerator. /// </remarks> /// <param name="itemID"></param> /// <param name="channel"></param> /// <param name="name"></param> /// <param name="id"></param> /// <param name="msg"></param> /// <returns></returns> public List<ListenerInfo> GetListeners(UUID itemID, int channel, string name, UUID id, string msg) { List<ListenerInfo> collection = new List<ListenerInfo>(); lock (m_listeners) { List<ListenerInfo> listeners; if (!m_listeners.TryGetValue(channel, out listeners)) { return collection; } foreach (ListenerInfo li in listeners) { if (!li.IsActive()) { continue; } if (!itemID.Equals(UUID.Zero) && !li.GetItemID().Equals(itemID)) { continue; } if (li.GetName().Length > 0 && ( ((li.RegexBitfield & OS_LISTEN_REGEX_NAME) != OS_LISTEN_REGEX_NAME && !li.GetName().Equals(name)) || ((li.RegexBitfield & OS_LISTEN_REGEX_NAME) == OS_LISTEN_REGEX_NAME && !Regex.IsMatch(name, li.GetName())) )) { continue; } if (!li.GetID().Equals(UUID.Zero) && !li.GetID().Equals(id)) { continue; } if (li.GetMessage().Length > 0 && ( ((li.RegexBitfield & OS_LISTEN_REGEX_MESSAGE) != OS_LISTEN_REGEX_MESSAGE && !li.GetMessage().Equals(msg)) || ((li.RegexBitfield & OS_LISTEN_REGEX_MESSAGE) == OS_LISTEN_REGEX_MESSAGE && !Regex.IsMatch(msg, li.GetMessage())) )) { continue; } collection.Add(li); } } return collection; } public Object[] GetSerializationData(UUID itemID) { List<Object> data = new List<Object>(); lock (m_listeners) { foreach (List<ListenerInfo> list in m_listeners.Values) { foreach (ListenerInfo l in list) { if (l.GetItemID() == itemID) data.AddRange(l.GetSerializationData()); } } } return (Object[])data.ToArray(); } public void AddFromData(uint localID, UUID itemID, UUID hostID, Object[] data) { int idx = 0; Object[] item = new Object[6]; int dataItemLength = 6; while (idx < data.Length) { dataItemLength = (idx + 7 == data.Length || (idx + 7 < data.Length && data[idx + 7] is bool)) ? 7 : 6; item = new Object[dataItemLength]; Array.Copy(data, idx, item, 0, dataItemLength); ListenerInfo info = ListenerInfo.FromData(localID, itemID, hostID, item); lock (m_listeners) { if (!m_listeners.ContainsKey((int)item[2])) { m_listeners.Add((int)item[2], new List<ListenerInfo>()); } m_listeners[(int)item[2]].Add(info); } idx += dataItemLength; } } } public class ListenerInfo : IWorldCommListenerInfo { /// <summary> /// Listener is active or not /// </summary> private bool m_active; /// <summary> /// Assigned handle of this listener /// </summary> private int m_handle; /// <summary> /// Local ID from script engine /// </summary> private uint m_localID; /// <summary> /// ID of the host script engine /// </summary> private UUID m_itemID; /// <summary> /// ID of the host/scene part /// </summary> private UUID m_hostID; /// <summary> /// Channel /// </summary> private int m_channel; /// <summary> /// ID to filter messages from /// </summary> private UUID m_id; /// <summary> /// Object name to filter messages from /// </summary> private string m_name; /// <summary> /// The message /// </summary> private string m_message; public ListenerInfo(int handle, uint localID, UUID ItemID, UUID hostID, int channel, string name, UUID id, string message) { Initialise(handle, localID, ItemID, hostID, channel, name, id, message, 0); } public ListenerInfo(int handle, uint localID, UUID ItemID, UUID hostID, int channel, string name, UUID id, string message, int regexBitfield) { Initialise(handle, localID, ItemID, hostID, channel, name, id, message, regexBitfield); } public ListenerInfo(ListenerInfo li, string name, UUID id, string message) { Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID, li.m_channel, name, id, message, 0); } public ListenerInfo(ListenerInfo li, string name, UUID id, string message, int regexBitfield) { Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID, li.m_channel, name, id, message, regexBitfield); } private void Initialise(int handle, uint localID, UUID ItemID, UUID hostID, int channel, string name, UUID id, string message, int regexBitfield) { m_active = true; m_handle = handle; m_localID = localID; m_itemID = ItemID; m_hostID = hostID; m_channel = channel; m_name = name; m_id = id; m_message = message; RegexBitfield = regexBitfield; } public Object[] GetSerializationData() { Object[] data = new Object[7]; data[0] = m_active; data[1] = m_handle; data[2] = m_channel; data[3] = m_name; data[4] = m_id; data[5] = m_message; data[6] = RegexBitfield; return data; } public static ListenerInfo FromData(uint localID, UUID ItemID, UUID hostID, Object[] data) { ListenerInfo linfo = new ListenerInfo((int)data[1], localID, ItemID, hostID, (int)data[2], (string)data[3], (UUID)data[4], (string)data[5]); linfo.m_active = (bool)data[0]; if (data.Length >= 7) { linfo.RegexBitfield = (int)data[6]; } return linfo; } public UUID GetItemID() { return m_itemID; } public UUID GetHostID() { return m_hostID; } public int GetChannel() { return m_channel; } public uint GetLocalID() { return m_localID; } public int GetHandle() { return m_handle; } public string GetMessage() { return m_message; } public string GetName() { return m_name; } public bool IsActive() { return m_active; } public void Deactivate() { m_active = false; } public void Activate() { m_active = true; } public UUID GetID() { return m_id; } public int RegexBitfield { get; private set; } } }
#region --- License --- /* Copyright (c) 2006, 2007 Stefanos Apostolopoulos * See license.txt for license info */ #endregion using System; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; namespace Bind.Structures { /// <summary> /// Represents an opengl constant in C# format. Both the constant name and value /// can be retrieved or set. The value can be either a number, another constant /// or an alias to a constant /// </summary> public class Constant : IComparable<Constant> { static StringBuilder translator = new StringBuilder(); static readonly int MaxReferenceDepth = 8; static int CurrentReferenceDepth = 0; #region PreviousName string original_name; // Gets the name prior to translation. public string OriginalName { get { return original_name; } private set { original_name = value; } } #endregion #region public string Name string _name; /// <summary> /// Gets or sets the name of the opengl constant (eg. GL_LINES). /// Undergoes processing unless the Settings.Legacy.NoAdvancedEnumProcessing flag is set. /// </summary> public string Name { get { return _name; } set { if (String.IsNullOrEmpty(value)) throw new ArgumentNullException("value"); if (OriginalName == null) OriginalName = _name; _name = value; } } #endregion #region public string Value string _value; /// <summary> /// Gets or sets the value of the opengl constant (eg. 0x00000001). /// </summary> public string Value { get { return _value; } set { if (String.IsNullOrEmpty(value)) throw new ArgumentNullException("value"); _value = value; } } #endregion #region public string Reference string _reference; /// <summary> /// Gets or sets a string indicating the OpenGL enum reference by this constant. /// Can be null. /// </summary> public string Reference { get { return _reference; } set { if (!String.IsNullOrEmpty(value)) _reference = EnumProcessor.TranslateEnumName(value.Trim()); else _reference = value; } } #endregion #region public bool Unchecked public bool Unchecked { get { // Check if the value is a number larger than Int32.MaxValue. ulong number; string test = Value; return UInt64.TryParse(test.ToLower().Replace("0x", String.Empty), NumberStyles.AllowHexSpecifier, null, out number) && number > Int32.MaxValue; } } #endregion #region Constructors /// <summary> /// Creates an empty Constant. /// </summary> public Constant() { } /// <summary> /// Creates a Constant with the given name and value. /// </summary> /// <param name="name">The Name of the Constant.</param> /// <param name="value">The Type of the Constant.</param> public Constant(string name, string value) { Name = name; Value = value; } #endregion #region Translate [Obsolete] public static string Translate(string s, bool isValue) { translator.Remove(0, translator.Length); // Translate the constant's name to match .Net naming conventions bool name_is_all_caps = s.AsEnumerable().All(c => Char.IsLetter(c) ? Char.IsUpper(c) : true); bool name_contains_underscore = s.Contains("_"); if ((Settings.Compatibility & Settings.Legacy.NoAdvancedEnumProcessing) == Settings.Legacy.None && (name_is_all_caps || name_contains_underscore)) { bool next_char_uppercase = true; bool is_after_digit = false; if (!isValue && Char.IsDigit(s[0])) translator.Insert(0, Settings.ConstantPrefix); foreach (char c in s) { if (c == '_') next_char_uppercase = true; else if (Char.IsDigit(c)) { is_after_digit = true; translator.Append(c); } else { translator.Append(next_char_uppercase || (is_after_digit && c == 'd') ? Char.ToUpper(c) : Char.ToLower(c)); is_after_digit = next_char_uppercase = false; } } translator[0] = Char.ToUpper(translator[0]); } else translator.Append(s); return translator.ToString(); } #endregion /// <summary> /// Replces the Value of the given constant with the value referenced by the [c.Reference, c.Value] pair. /// </summary> /// <param name="c">The Constant to translate</param> /// <param name="enums">The list of enums to check.</param> /// <param name="auxEnums">The list of auxilliary enums to check.</param> /// <returns>True if the reference was found; false otherwise.</returns> public static bool TranslateConstantWithReference(Constant c, EnumCollection enums, EnumCollection auxEnums) { if (c == null) throw new ArgumentNullException("c"); if (enums == null) throw new ArgumentNullException("enums"); if (++CurrentReferenceDepth >= MaxReferenceDepth) throw new InvalidOperationException("Enum specification contains cycle"); if (!String.IsNullOrEmpty(c.Reference)) { Constant referenced_constant; if (enums.ContainsKey(c.Reference) && enums[c.Reference].ConstantCollection.ContainsKey(c.Value)) { // Transitively translate the referenced token // Todo: this may cause loops if two tokens reference each other. // Add a max reference depth and bail out? TranslateConstantWithReference(enums[c.Reference].ConstantCollection[c.Value], enums, auxEnums); referenced_constant = (enums[c.Reference].ConstantCollection[c.Value]); } else if (auxEnums != null && auxEnums.ContainsKey(c.Reference) && auxEnums[c.Reference].ConstantCollection.ContainsKey(c.Value)) { // Legacy from previous generator incarnation. // Todo: merge everything into enums and get rid of auxEnums. TranslateConstantWithReference(auxEnums[c.Reference].ConstantCollection[c.Value], enums, auxEnums); referenced_constant = (auxEnums[c.Reference].ConstantCollection[c.Value]); } else if (enums.ContainsKey(Settings.CompleteEnumName) && enums[Settings.CompleteEnumName].ConstantCollection.ContainsKey(c.Value)) { // Try the All enum var reference = enums[Settings.CompleteEnumName].ConstantCollection[c.Value]; if (reference.Reference == null) referenced_constant = (enums[Settings.CompleteEnumName].ConstantCollection[c.Value]); else { --CurrentReferenceDepth; return false; } } else { --CurrentReferenceDepth; return false; } //else throw new InvalidOperationException(String.Format("Unknown Enum \"{0}\" referenced by Constant \"{1}\"", // c.Reference, c.ToString())); c.Value = referenced_constant.Value; c.Reference = null; } --CurrentReferenceDepth; return true; } #region public override string ToString() /// <summary> /// Returns a string that represents the full constant declaration without decorations /// (eg GL_XXX_YYY = (int)0xDEADBEEF or GL_XXX_YYY = GL_ZZZ.FOOBAR). /// </summary> /// <returns></returns> [Obsolete("This belongs to the language-specific ISpecWriter implementations.")] public override string ToString() { if (String.IsNullOrEmpty(Name)) return ""; return String.Format("{0} = {1}((int){2}{3})", Name, Unchecked ? "unchecked" : "", !String.IsNullOrEmpty(Reference) ? Reference + Settings.NamespaceSeparator : "", Value); //return String.Format("{0} = {1}((int){2})", Name, Unchecked ? "unchecked" : "", Value); } #endregion #region IComparable <Constant>Members public int CompareTo(Constant other) { int ret = Value.CompareTo(other.Value); if (ret == 0) return Name.CompareTo(other.Name); return ret; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogicalInt6464() { var test = new SimpleUnaryOpTest__ShiftRightLogicalInt6464(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogicalInt6464 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int64); private const int RetElementCount = VectorSize / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector256<Int64> _clsVar; private Vector256<Int64> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; static SimpleUnaryOpTest__ShiftRightLogicalInt6464() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftRightLogicalInt6464() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.ShiftRightLogical( Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.ShiftRightLogical( Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.ShiftRightLogical( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.ShiftRightLogical( _clsVar, 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftRightLogicalInt6464(); var result = Avx2.ShiftRightLogical(test._fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.ShiftRightLogical(_fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { if (0 != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0 != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<Int64>(Vector256<Int64><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Tests.Common; using Umbraco.Cms.Tests.Common.Testing; using Umbraco.Cms.Tests.Integration.Testing; using Umbraco.Extensions; using Constants = Umbraco.Cms.Core.Constants; using FileSystems = Umbraco.Cms.Core.IO.FileSystems; namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Scoping { [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewEmptyPerTest)] public class ScopeFileSystemsTests : UmbracoIntegrationTest { private MediaFileManager MediaFileManager => GetRequiredService<MediaFileManager>(); private IHostingEnvironment HostingEnvironment => GetRequiredService<IHostingEnvironment>(); [SetUp] public void SetUp() => ClearFiles(IOHelper); [TearDown] public void Teardown() { ClearFiles(IOHelper); } private void ClearFiles(IIOHelper ioHelper) { TestHelper.DeleteDirectory(ioHelper.MapPath("media")); TestHelper.DeleteDirectory(ioHelper.MapPath("FileSysTests")); TestHelper.DeleteDirectory(ioHelper.MapPath(Constants.SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs")); } [Test] public void MediaFileManager_does_not_write_to_physical_file_system_when_scoped_if_scope_does_not_complete() { string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPhysicalRootPath); string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService<ILogger<PhysicalFileSystem>>(), rootPath, rootUrl); MediaFileManager mediaFileManager = MediaFileManager; Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); using (ScopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { MediaFileManager.FileSystem.AddFile("f1.txt", ms); } Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); } // After scope is disposed ensure shadow wrapper didn't commit to physical Assert.IsFalse(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); } [Test] public void MediaFileManager_writes_to_physical_file_system_when_scoped_and_scope_is_completed() { string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPhysicalRootPath); string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService<ILogger<PhysicalFileSystem>>(), rootPath, rootUrl); MediaFileManager mediaFileManager = MediaFileManager; Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); using (IScope scope = ScopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { mediaFileManager.FileSystem.AddFile("f1.txt", ms); } Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); scope.Complete(); Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); } // After scope is disposed ensure shadow wrapper writes to physical file system Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsTrue(physMediaFileSystem.FileExists("f1.txt")); } [Test] public void MultiThread() { string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPhysicalRootPath); string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService<ILogger<PhysicalFileSystem>>(), rootPath, rootUrl); MediaFileManager mediaFileManager = MediaFileManager; var taskHelper = new TaskHelper(Mock.Of<ILogger<TaskHelper>>()); IScopeProvider scopeProvider = ScopeProvider; using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { mediaFileManager.FileSystem.AddFile("f1.txt", ms); } Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); // execute on another disconnected thread (execution context will not flow) Task t = taskHelper.ExecuteBackgroundTask(() => { Assert.IsFalse(mediaFileManager.FileSystem.FileExists("f1.txt")); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { mediaFileManager.FileSystem.AddFile("f2.txt", ms); } Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f2.txt")); Assert.IsTrue(physMediaFileSystem.FileExists("f2.txt")); return Task.CompletedTask; }); Task.WaitAll(t); Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f2.txt")); Assert.IsTrue(physMediaFileSystem.FileExists("f2.txt")); } } [Test] public void SingleShadow() { var taskHelper = new TaskHelper(Mock.Of<ILogger<TaskHelper>>()); IScopeProvider scopeProvider = ScopeProvider; bool isThrown = false; using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { // This is testing when another thread concurrently tries to create a scoped file system // because at the moment we don't support concurrent scoped filesystems. Task t = taskHelper.ExecuteBackgroundTask(() => { // ok to create a 'normal' other scope using (IScope other = scopeProvider.CreateScope()) { other.Complete(); } // not ok to create a 'scoped filesystems' other scope // we will get a "Already shadowing." exception. Assert.Throws<InvalidOperationException>(() => { using IScope other = scopeProvider.CreateScope(scopeFileSystems: true); }); isThrown = true; return Task.CompletedTask; }); Task.WaitAll(t); } Assert.IsTrue(isThrown); } [Test] public void SingleShadowEvenDetached() { var taskHelper = new TaskHelper(Mock.Of<ILogger<TaskHelper>>()); var scopeProvider = (ScopeProvider)ScopeProvider; using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { // This is testing when another thread concurrently tries to create a scoped file system // because at the moment we don't support concurrent scoped filesystems. Task t = taskHelper.ExecuteBackgroundTask(() => { // not ok to create a 'scoped filesystems' other scope // because at the moment we don't support concurrent scoped filesystems // even a detached one // we will get a "Already shadowing." exception. Assert.Throws<InvalidOperationException>(() => { using IScope other = scopeProvider.CreateDetachedScope(scopeFileSystems: true); }); return Task.CompletedTask; }); Task.WaitAll(t); } IScope detached = scopeProvider.CreateDetachedScope(scopeFileSystems: true); Assert.IsNull(scopeProvider.AmbientScope); Assert.Throws<InvalidOperationException>(() => { // even if there is no ambient scope, there's a single shadow using IScope other = scopeProvider.CreateScope(scopeFileSystems: true); }); scopeProvider.AttachScope(detached); detached.Dispose(); } } }
/////////////////////////////////////////////////////////////////////////////// //File: ViewSystemSelector.cs // //Description: Contains the Zegeger.Decal.VVS.ViewSystemSelector class, // which is used to determine whether the Virindi View Service is enabled. // As with all the VVS wrappers, the VVS_REFERENCED compilation symbol must be // defined for the VVS code to be compiled. Otherwise, only Decal views are used. // //References required: // VirindiViewService (if VVS_REFERENCED is defined) // Decal.Adapter // Decal.Interop.Core // //This file is Copyright (c) 2009 VirindiPlugins // //Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; using System.Reflection; using Decal.Adapter.Wrappers; #if METAVIEW_PUBLIC_NS namespace Zegeger.Decal.VVS #else namespace Zegeger.Decal.VVS #endif { public static class ViewSystemSelector { public enum eViewSystem { DecalInject, VirindiViewService, } ///////////////////////////////System presence detection/////////////////////////////// public static bool IsPresent(PluginHost pHost, eViewSystem VSystem) { switch (VSystem) { case eViewSystem.DecalInject: return true; case eViewSystem.VirindiViewService: return VirindiViewsPresent(pHost); default: return false; } } static bool VirindiViewsPresent(PluginHost pHost) { #if VVS_REFERENCED System.Reflection.Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies(); foreach (System.Reflection.Assembly a in asms) { AssemblyName nmm = a.GetName(); if ((nmm.Name == "VirindiViewService") && (nmm.Version >= new System.Version("1.0.0.18"))) { try { return Curtain_VVS_Running(); } catch { return false; } } } return false; #else return false; #endif } public static bool VirindiViewsPresent(PluginHost pHost, Version minver) { #if VVS_REFERENCED System.Reflection.Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies(); foreach (System.Reflection.Assembly a in asms) { AssemblyName nm = a.GetName(); if ((nm.Name == "VirindiViewService") && (nm.Version >= minver)) { try { return Curtain_VVS_Running(); } catch { return false; } } } return false; #else return false; #endif } #if VVS_REFERENCED static bool Curtain_VVS_Running() { return VirindiViewService.Service.Running; } #endif ///////////////////////////////CreateViewResource/////////////////////////////// internal static IView CreateViewResource(PluginHost pHost, string pXMLResource) { #if VVS_REFERENCED if (IsPresent(pHost, eViewSystem.VirindiViewService)) return CreateViewResource(pHost, pXMLResource, eViewSystem.VirindiViewService); else #endif return CreateViewResource(pHost, pXMLResource, eViewSystem.DecalInject); } internal static IView CreateViewResource(PluginHost pHost, string pXML, eViewSystem VSystem) { if (!IsPresent(pHost, VSystem)) return null; switch (VSystem) { case eViewSystem.DecalInject: return CreateDecalViewResource(pHost, pXML); case eViewSystem.VirindiViewService: #if VVS_REFERENCED return CreateMyHudViewResource(pHost, pXML); #else break; #endif } return null; } static IView CreateDecalViewResource(PluginHost pHost, string pXML) { IView ret = new DecalControls.View(); ret.InitializeRawXML(pHost, pXML); return ret; } #if VVS_REFERENCED static IView CreateMyHudViewResource(PluginHost pHost, string pXML) { IView ret = new VirindiViewServiceHudControls.View(); ret.InitializeRawXML(pHost, pXML); return ret; } #endif ///////////////////////////////CreateViewXML/////////////////////////////// internal static IView CreateViewXML(PluginHost pHost, string pXML) { #if VVS_REFERENCED if (IsPresent(pHost, eViewSystem.VirindiViewService)) return CreateViewXML(pHost, pXML, eViewSystem.VirindiViewService); else #endif return CreateViewXML(pHost, pXML, eViewSystem.DecalInject); } internal static IView CreateViewXML(PluginHost pHost, string pXML, eViewSystem VSystem) { if (!IsPresent(pHost, VSystem)) return null; switch (VSystem) { case eViewSystem.DecalInject: return CreateDecalViewXML(pHost, pXML); case eViewSystem.VirindiViewService: #if VVS_REFERENCED return CreateMyHudViewXML(pHost, pXML); #else break; #endif } return null; } static IView CreateDecalViewXML(PluginHost pHost, string pXML) { IView ret = new DecalControls.View(); ret.InitializeRawXML(pHost, pXML); return ret; } #if VVS_REFERENCED static IView CreateMyHudViewXML(PluginHost pHost, string pXML) { IView ret = new VirindiViewServiceHudControls.View(); ret.InitializeRawXML(pHost, pXML); return ret; } #endif ///////////////////////////////HasChatOpen/////////////////////////////// public static bool AnySystemHasChatOpen(PluginHost pHost) { if (IsPresent(pHost, eViewSystem.VirindiViewService)) if (HasChatOpen_VirindiViews()) return true; if (pHost.Actions.ChatState) return true; return false; } static bool HasChatOpen_VirindiViews() { #if VVS_REFERENCED if (VirindiViewService.HudView.FocusControl != null) { if (VirindiViewService.HudView.FocusControl.GetType() == typeof(VirindiViewService.Controls.HudTextBox)) return true; } return false; #else return false; #endif } } }
//------------------------------------------------------------------------------ // <copyright file="ProtocolReflector.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Services.Description { using System.Web.Services; using System.Web.Services.Protocols; using System.Xml; using System.Xml.Serialization; using System.Xml.Schema; using System.Collections; using System; using System.Reflection; using System.Security.Permissions; using System.Collections.Generic; /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")] [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public abstract class ProtocolReflector { ServiceDescriptionReflector reflector; LogicalMethodInfo method; Operation operation; OperationBinding operationBinding; Port port; PortType portType; Binding binding; WebMethodAttribute methodAttr; Message inputMessage; Message outputMessage; MessageCollection headerMessages; ServiceDescription bindingServiceDescription; CodeIdentifiers portNames; bool emptyBinding; internal void Initialize(ServiceDescriptionReflector reflector) { this.reflector = reflector; } internal bool IsEmptyBinding { get { return emptyBinding; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.Service"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Service Service { get { return reflector.Service; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.ServiceDescription"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ServiceDescription ServiceDescription { get { return reflector.ServiceDescription; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.ServiceDescriptions"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ServiceDescriptionCollection ServiceDescriptions { get { return reflector.ServiceDescriptions; } } internal List<Action<Uri>> UriFixups { get { return this.reflector.UriFixups; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.Schemas"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSchemas Schemas { get { return reflector.Schemas; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.SchemaExporter"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSchemaExporter SchemaExporter { get { return reflector.SchemaExporter; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.ReflectionImporter"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlReflectionImporter ReflectionImporter { get { return reflector.ReflectionImporter; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.DefaultNamespace"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string DefaultNamespace { get { return reflector.ServiceAttribute.Namespace; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.ServiceUrl"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string ServiceUrl { get { return reflector.ServiceUrl; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.ServiceType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Type ServiceType { get { return reflector.ServiceType; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.Method"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public LogicalMethodInfo Method { get { return method; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.Binding"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Binding Binding { get { return binding; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.PortType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public PortType PortType { get { return portType; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.Port"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Port Port { get { return port; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.Operation"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Operation Operation { get { return operation; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.OperationBinding"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public OperationBinding OperationBinding { get { return operationBinding; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.MethodAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public WebMethodAttribute MethodAttribute { get { return methodAttr; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.Methods"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public LogicalMethodInfo[] Methods { get { return reflector.Methods; } } internal Hashtable ReflectionContext { get { return reflector.ReflectionContext; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.InputMessage"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Message InputMessage { get { if (inputMessage == null) { string messageName = XmlConvert.EncodeLocalName(methodAttr.MessageName.Length == 0 ? Method.Name : methodAttr.MessageName); bool diffNames = messageName != Method.Name; inputMessage = new Message(); inputMessage.Name = messageName + ProtocolName + "In"; OperationInput input = new OperationInput(); if (diffNames) input.Name = messageName; input.Message = new XmlQualifiedName(inputMessage.Name, bindingServiceDescription.TargetNamespace); operation.Messages.Add(input); OperationBinding.Input = new InputBinding(); if (diffNames) OperationBinding.Input.Name = messageName; } return inputMessage; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.OutputMessage"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Message OutputMessage { get { if (outputMessage == null) { string messageName = XmlConvert.EncodeLocalName(methodAttr.MessageName.Length == 0 ? Method.Name : methodAttr.MessageName); bool diffNames = messageName != Method.Name; outputMessage = new Message(); outputMessage.Name = messageName + ProtocolName + "Out"; OperationOutput output = new OperationOutput(); if (diffNames) output.Name = messageName; output.Message = new XmlQualifiedName(outputMessage.Name, bindingServiceDescription.TargetNamespace); operation.Messages.Add(output); OperationBinding.Output = new OutputBinding(); if (diffNames) OperationBinding.Output.Name = messageName; } return outputMessage; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.HeaderMessages"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public MessageCollection HeaderMessages { get { if (headerMessages == null) { headerMessages = new MessageCollection(bindingServiceDescription); } return headerMessages; } } void MoveToMethod(LogicalMethodInfo method) { this.method = method; this.methodAttr = method.MethodAttribute; } class ReflectedBinding { internal ReflectedBinding() { } internal ReflectedBinding(WebServiceBindingAttribute bindingAttr) { this.bindingAttr = bindingAttr; } public WebServiceBindingAttribute bindingAttr; public ArrayList methodList; } internal void Reflect() { emptyBinding = false; Hashtable bindings = new Hashtable(); Hashtable reflectedBindings = new Hashtable(); for (int i = 0; i < reflector.Methods.Length; i++) { MoveToMethod(reflector.Methods[i]); string bindingName = ReflectMethodBinding(); if (bindingName == null) bindingName = string.Empty; ReflectedBinding reflectedBinding = (ReflectedBinding)reflectedBindings[bindingName]; if (reflectedBinding == null) { reflectedBinding = new ReflectedBinding(); reflectedBinding.bindingAttr = WebServiceBindingReflector.GetAttribute(method, bindingName); if (reflectedBinding.bindingAttr == null || (bindingName.Length == 0 && reflectedBinding.bindingAttr.Location.Length > 0)) { reflectedBinding.bindingAttr = new WebServiceBindingAttribute(); } reflectedBindings.Add(bindingName, reflectedBinding); } if (reflectedBinding.bindingAttr.Location.Length == 0) { if (reflectedBinding.methodList == null) reflectedBinding.methodList = new ArrayList(); reflectedBinding.methodList.Add(method); bindings[reflectedBinding.bindingAttr.Name] = method; } else { AddImport(reflectedBinding.bindingAttr.Namespace, reflectedBinding.bindingAttr.Location); } } foreach (ReflectedBinding reflectedBinding in reflectedBindings.Values) { ReflectBinding(reflectedBinding); } // Only check for empty binding if we do not have real bindings if (reflectedBindings.Count == 0) { // It should be possible to get the value for WebReference.ServiceLocationUrl even if the web service has no web methods. // This is a common scenario for Whitehorse during the early stages of development when a user is defining the web // components and their inter-connections, but not the details of whatmethods will be present on each web service. // get all WebServiceBindings emptyBinding = true; ReflectedBinding binding = null; object[] attrs = ServiceType.GetCustomAttributes(typeof(WebServiceBindingAttribute), false); for (int i = 0; i < attrs.Length; i++) { WebServiceBindingAttribute bindingAttribute = (WebServiceBindingAttribute)attrs[i]; if (bindings[bindingAttribute.Name] != null) continue; if (binding != null) { binding = null; break; } binding = new ReflectedBinding(bindingAttribute); } if (binding != null) ReflectBinding(binding); } Type[] interfaces = ServiceType.GetInterfaces(); // iterate through all the interfaces for this type foreach (Type bindingInterface in interfaces) { object[] attrs = bindingInterface.GetCustomAttributes(typeof(WebServiceBindingAttribute), false); for (int i = 0; i < attrs.Length; i++) { WebServiceBindingAttribute bindingAttribute = (WebServiceBindingAttribute)attrs[i]; if (bindings[bindingAttribute.Name] != null) continue; ReflectBinding(new ReflectedBinding(bindingAttribute)); } } ReflectDescription(); } void AddImport(string ns, string location) { foreach (Import import in ServiceDescription.Imports) { if (import.Namespace == ns && import.Location == location) { return; } } Import newImport = new Import(); newImport.Namespace = ns; newImport.Location = location; ServiceDescription.Imports.Add(newImport); } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.GetServiceDescription"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ServiceDescription GetServiceDescription(string ns) { ServiceDescription description = ServiceDescriptions[ns]; if (description == null) { description = new ServiceDescription(); description.TargetNamespace = ns; ServiceDescriptions.Add(description); } return description; } void ReflectBinding(ReflectedBinding reflectedBinding) { string bindingName = XmlConvert.EncodeLocalName(reflectedBinding.bindingAttr.Name); string bindingNamespace = reflectedBinding.bindingAttr.Namespace; if (bindingName.Length == 0) bindingName = Service.Name + ProtocolName; if (bindingNamespace.Length == 0) bindingNamespace = ServiceDescription.TargetNamespace; WsiProfiles claims = WsiProfiles.None; if (reflectedBinding.bindingAttr.Location.Length > 0) { // If a URL is specified for the WSDL, file, then we just import the // binding from there instead of generating it in this WSDL file. portType = null; binding = null; } else { bindingServiceDescription = GetServiceDescription(bindingNamespace); CodeIdentifiers bindingNames = new CodeIdentifiers(); foreach (Binding b in bindingServiceDescription.Bindings) bindingNames.AddReserved(b.Name); bindingName = bindingNames.AddUnique(bindingName, binding); portType = new PortType(); binding = new Binding(); portType.Name = bindingName; binding.Name = bindingName; binding.Type = new XmlQualifiedName(portType.Name, bindingNamespace); claims = reflectedBinding.bindingAttr.ConformsTo & this.ConformsTo; if (reflectedBinding.bindingAttr.EmitConformanceClaims && claims != WsiProfiles.None) { ServiceDescription.AddConformanceClaims(binding.GetDocumentationElement(), claims); } bindingServiceDescription.Bindings.Add(binding); bindingServiceDescription.PortTypes.Add(portType); } if (portNames == null) { portNames = new CodeIdentifiers(); foreach (Port p in Service.Ports) portNames.AddReserved(p.Name); } port = new Port(); port.Binding = new XmlQualifiedName(bindingName, bindingNamespace); port.Name = portNames.AddUnique(bindingName, port); Service.Ports.Add(port); BeginClass(); if (reflectedBinding.methodList != null && reflectedBinding.methodList.Count > 0) { foreach (LogicalMethodInfo method in reflectedBinding.methodList) { MoveToMethod(method); operation = new Operation(); operation.Name = XmlConvert.EncodeLocalName(method.Name); if (methodAttr.Description != null && methodAttr.Description.Length > 0) operation.Documentation = methodAttr.Description; operationBinding = new OperationBinding(); operationBinding.Name = operation.Name; inputMessage = null; outputMessage = null; headerMessages = null; if (ReflectMethod()) { if (inputMessage != null) bindingServiceDescription.Messages.Add(inputMessage); if (outputMessage != null) bindingServiceDescription.Messages.Add(outputMessage); if (headerMessages != null) { foreach (Message headerMessage in headerMessages) { bindingServiceDescription.Messages.Add(headerMessage); } } binding.Operations.Add(operationBinding); portType.Operations.Add(operation); } } } if (binding != null && claims == WsiProfiles.BasicProfile1_1 && ProtocolName == "Soap") { BasicProfileViolationCollection warnings = new BasicProfileViolationCollection(); WebServicesInteroperability.AnalyzeBinding(binding, bindingServiceDescription, ServiceDescriptions, warnings); if (warnings.Count > 0) { throw new InvalidOperationException(Res.GetString(Res.WebWsiViolation, ServiceType.FullName, warnings.ToString())); } } EndClass(); } internal virtual WsiProfiles ConformsTo { get { return WsiProfiles.None; } } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.ProtocolName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract string ProtocolName { get; } // These overridable methods have no parameters. The subclass uses properties on this // base object to obtain the information. This allows us to grow the set of // information passed to the methods over time w/o breaking anyone. They are protected // instead of public because this object is passed to extensions and we don't want // those calling these methods. /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.BeginClass"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected virtual void BeginClass() { } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.ReflectMethod"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected abstract bool ReflectMethod(); /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.ReflectMethodBinding"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected virtual string ReflectMethodBinding() { return string.Empty; } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.EndClass"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected virtual void EndClass() { } /// <include file='doc\ProtocolReflector.uex' path='docs/doc[@for="ProtocolReflector.ReflectDescription"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected virtual void ReflectDescription() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace System.IO.Compression { // DeflateManagedStream supports decompression of Deflate64 format only. internal sealed partial class DeflateManagedStream : Stream { internal const int DefaultBufferSize = 8192; private Stream? _stream; private InflaterManaged _inflater; private readonly byte[] _buffer; private int _asyncOperations; // A specific constructor to allow decompression of Deflate64 internal DeflateManagedStream(Stream stream, ZipArchiveEntry.CompressionMethodValues method, long uncompressedSize = -1) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (!stream.CanRead) throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream)); if (!stream.CanRead) throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream)); Debug.Assert(method == ZipArchiveEntry.CompressionMethodValues.Deflate64); _inflater = new InflaterManaged(null, method == ZipArchiveEntry.CompressionMethodValues.Deflate64 ? true : false, uncompressedSize); _stream = stream; _buffer = new byte[DefaultBufferSize]; } public override bool CanRead { get { if (_stream == null) { return false; } return _stream.CanRead; } } public override bool CanWrite { get { return false; } } public override bool CanSeek => false; public override long Length { get { throw new NotSupportedException(SR.NotSupported); } } public override long Position { get { throw new NotSupportedException(SR.NotSupported); } set { throw new NotSupportedException(SR.NotSupported); } } public override void Flush() { EnsureNotDisposed(); } public override Task FlushAsync(CancellationToken cancellationToken) { EnsureNotDisposed(); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.NotSupported); } public override void SetLength(long value) { throw new NotSupportedException(SR.NotSupported); } public override int Read(byte[] array, int offset, int count) { ValidateParameters(array, offset, count); EnsureNotDisposed(); int bytesRead; int currentOffset = offset; int remainingCount = count; while (true) { bytesRead = _inflater.Inflate(array, currentOffset, remainingCount); currentOffset += bytesRead; remainingCount -= bytesRead; if (remainingCount == 0) { break; } if (_inflater.Finished()) { // if we finished decompressing, we can't have anything left in the outputwindow. Debug.Assert(_inflater.AvailableOutput == 0, "We should have copied all stuff out!"); break; } int bytes = _stream!.Read(_buffer, 0, _buffer.Length); if (bytes <= 0) { break; } else if (bytes > _buffer.Length) { // The stream is either malicious or poorly implemented and returned a number of // bytes larger than the buffer supplied to it. throw new InvalidDataException(SR.GenericInvalidData); } _inflater.SetInput(_buffer, 0, bytes); } return count - remainingCount; } private void ValidateParameters(byte[] array, int offset, int count) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (array.Length - offset < count) throw new ArgumentException(SR.InvalidArgumentOffsetCount); } private void EnsureNotDisposed() { if (_stream == null) ThrowStreamClosedException(); } private static void ThrowStreamClosedException() { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); public override Task<int> ReadAsync(byte[] array, int offset, int count, CancellationToken cancellationToken) { // We use this checking order for compat to earlier versions: if (_asyncOperations != 0) throw new InvalidOperationException(SR.InvalidBeginCall); ValidateParameters(array, offset, count); EnsureNotDisposed(); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } Interlocked.Increment(ref _asyncOperations); Task<int>? readTask = null; try { // Try to read decompressed data in output buffer int bytesRead = _inflater.Inflate(array, offset, count); if (bytesRead != 0) { // If decompression output buffer is not empty, return immediately. return Task.FromResult(bytesRead); } if (_inflater.Finished()) { // end of compression stream return Task.FromResult(0); } // If there is no data on the output buffer and we are not at // the end of the stream, we need to get more data from the base stream readTask = _stream!.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken); if (readTask == null) { throw new InvalidOperationException(SR.NotSupported_UnreadableStream); } return ReadAsyncCore(readTask, array, offset, count, cancellationToken); } finally { // if we haven't started any async work, decrement the counter to end the transaction if (readTask == null) { Interlocked.Decrement(ref _asyncOperations); } } } private async Task<int> ReadAsyncCore(Task<int> readTask, byte[] array, int offset, int count, CancellationToken cancellationToken) { try { while (true) { int bytesRead = await readTask.ConfigureAwait(false); EnsureNotDisposed(); if (bytesRead <= 0) { // This indicates the base stream has received EOF return 0; } else if (bytesRead > _buffer.Length) { // The stream is either malicious or poorly implemented and returned a number of // bytes larger than the buffer supplied to it. throw new InvalidDataException(SR.GenericInvalidData); } cancellationToken.ThrowIfCancellationRequested(); // Feed the data from base stream into decompression engine _inflater.SetInput(_buffer, 0, bytesRead); bytesRead = _inflater.Inflate(array, offset, count); if (bytesRead == 0 && !_inflater.Finished()) { // We could have read in head information and didn't get any data. // Read from the base stream again. readTask = _stream!.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken); if (readTask == null) { throw new InvalidOperationException(SR.NotSupported_UnreadableStream); } } else { return bytesRead; } } } finally { Interlocked.Decrement(ref _asyncOperations); } } public override void Write(byte[] array, int offset, int count) { throw new InvalidOperationException(SR.CannotWriteToDeflateStream); } // This is called by Dispose: private void PurgeBuffers(bool disposing) { if (!disposing) return; if (_stream == null) return; Flush(); } protected override void Dispose(bool disposing) { try { PurgeBuffers(disposing); } finally { // Close the underlying stream even if PurgeBuffers threw. // Stream.Close() may throw here (may or may not be due to the same error). // In this case, we still need to clean up internal resources, hence the inner finally blocks. try { if (disposing && _stream != null) _stream.Dispose(); } finally { _stream = null!; try { _inflater?.Dispose(); } finally { _inflater = null!; base.Dispose(disposing); } } } } } }
// Node.cs // using System; using System.Collections.Generic; using System.Html; using System.Runtime.CompilerServices; namespace Kinetic { //http://kineticjs.com/docs/symbols/Kinetic.Node.php public class Node { /// <summary> /// Node constructor. /// </summary> public Node(NodeConfig config) { } public NodeAttributes attrs; /// <summary> /// Clone node. /// </summary> /// <param name="attrs"></param> public void clone(object attrs) { } /// <summary> /// Create node with JSON string. De-serializtion does not generate custom shape drawing functions, images, or event handlers (this would make the serialized object huge). If your app uses custom shapes, images, and event handlers (it probably does), then you need to select the appropriate shapes after loading the stage and set these properties via on(), setDrawFunc(), and setImage() methods /// </summary> /// <param name="JSON">String</param> /// <param name="container">Optional container dom element used only if you're creating a stage node</param> /// <returns></returns> public static Node create(string JSON, Element container) { return null; } /// <summary> /// Remove and destroy node /// </summary> public void Destroy() { } /// <summary> /// Synthetically fire an event. /// </summary> /// <param name="eventType"></param> /// <param name="obj">optional object which can be used to pass parameters</param> public void fire(string eventType, Object obj) { } /// <summary> /// Get absolute opacity /// </summary> /// <returns></returns> public Number getAbsoluteOpacity() { return -1; } /// <summary> /// Get absolute position relative to the top left corner of the stage container div /// </summary> /// <returns></returns> public Number getAbsolutePosition() { return -1; } /// <summary> /// Get absolute transform of the node which takes into account its ancestor transforms /// </summary> /// <returns></returns> public Number getAbsoluteTransform() { return -1; } /// <summary> /// Get absolute z-index which takes into account sibling and ancestor indices /// </summary> /// <returns></returns> public Number getAbsoluteZIndex() { return -1; } /// <summary> /// Get attrs /// </summary> /// <returns></returns> public object getAttrs() { return null; } /// <summary> /// Get dragBoundFunc /// </summary> /// <returns></returns> public Delegate getDragBoundFunc() { return null; } /// <summary> /// Get draggable /// </summary> /// <returns></returns> public object getDraggable() { return null; } /// <summary> /// get flag which enables or disables automatically moving the draggable node to a temporary top layer to improve performance. /// </summary> /// <returns></returns> public object getDragOnTop() { return null; } /// <summary> /// get height /// </summary> /// <returns></returns> public Number getHeight() { return -1; } /// <summary> /// Get id /// </summary> /// <returns></returns> public string getId() { return null; } /// <summary> /// Get layer ancestor /// </summary> /// <returns></returns> public object getLayer() { return null; } /// <summary> /// Get node level in node tree. Returns an integer. /// e.g. Stage level will always be 0. Layers will always be 1. Groups and Shapes will always be >= 2 /// </summary> /// <returns></returns> public Number getLevel() { return -1; } /// <summary> /// Determine if node is listening or not. /// </summary> /// <returns></returns> public object getListening() { return null; } /// <summary> /// Get name /// </summary> /// <returns></returns> public string getName() { return null; } /// <summary> /// Get offset /// </summary> /// <returns></returns> public Number getOffset() { return null; } /// <summary> /// get opacity. /// </summary> /// <returns></returns> public Number getOpacity() { return -1; } /// <summary> /// Get parent container /// </summary> /// <returns></returns> public Container getParent() { return null; } /// <summary> /// Get node position relative to parent /// </summary> /// <returns></returns> public Number getPosition() { return -1; } /// <summary> /// Get rotation in radians /// </summary> /// <returns></returns> public Number getRotation() { return -1; } /// <summary> /// Get rotation in degrees /// </summary> /// <returns></returns> public Number getRotationDeg() { return -1; } /// <summary> /// Gt scale /// </summary> /// <returns></returns> public Number getScale() { return -1; } /// <summary> /// Get size /// </summary> /// <returns></returns> public Custom.Size getSize() { return null; } /// <summary> /// Get stage ancestor /// </summary> /// <returns></returns> public Stage getStage() { return null; } /// <summary> /// Get transform of the node /// </summary> /// <returns></returns> public Transform getTransform() { return null; } /// <summary> /// Determine if node is visible or not. /// </summary> /// <returns></returns> public bool getVisible() { return false; } /// <summary> /// get width /// </summary> /// <returns></returns> public Number getWidth() { return -1; } /// <summary> /// get x position /// </summary> /// <returns></returns> public Number getX() { return -1; } /// <summary> /// get y position /// </summary> /// <returns></returns> public Number getY() { return -1; } /// <summary> /// Get zIndex relative to the node's siblings who share the same parent /// </summary> /// <returns></returns> public int getZIndex() { return -1; } /// <summary> /// Hide node. /// </summary> public void hide() { } /// <summary> /// Get draggable. /// </summary> /// <returns></returns> public bool isDraggable() { return false; } /// <summary> /// Determine if node is currently in drag and drop mode /// </summary> /// <returns></returns> public bool isDragging() { return false; } /// <summary> /// Alias of getListening() /// </summary> /// <returns></returns> public bool isListening() { return false; } /// <summary> /// Alias of getVisible() /// </summary> /// <returns></returns> public bool isVisible() { return false; } /// <summary> /// Move node by an amount relative to its current position /// </summary> /// <param name="x"></param> /// <param name="y"></param> public void move(Number x, Number y) { } /// <summary> /// Move node down /// </summary> public void moveDown() { } /// <summary> /// Move node to another container /// </summary> /// <param name="newContainer"></param> public void moveTo(Container newContainer) { } /// <summary> /// Move node to the bottom of its siblings /// </summary> public void moveToBottom() { } /// <summary> /// Move node to the top of its siblings /// </summary> public void moveToTop() { } /// <summary> /// Move node up /// </summary> public void moveUp() { } /// <summary> /// Remove event bindings from the node. /// </summary> /// <param name="typesStr"></param> public void off(string typesStr) { } /// <summary> /// Bind events to the node. /// </summary> /// <param name="typesStr"></param> /// <param name="handler"></param> public void on(string typesStr, Delegate handler) { } /// <summary> /// Remove child from container, but don't destroy it /// </summary> public void remove() { } /// <summary> /// Rotate node by an amount in radians relative to its current rotation /// </summary> /// <param name="theta"></param> public void rotate(Number theta) { } /// <summary> /// Rotate node by an amount in degrees relative to its current rotation /// </summary> /// <param name="deg"></param> public void rotateDeg(Number deg) { } /// <summary> /// Set absolute position /// </summary> /// <param name="x"></param> /// <param name="y"></param> public void setAbsolutePosition(Number x, Number y) { } /// <summary> /// Set attrs /// </summary> /// <param name="?"></param> public void setAttrs(object config) { } /// <summary> /// Set default attrs. /// </summary> /// <param name="confic"></param> public void setDefaultAttrs(object confic) { } /// <summary> /// Set drag bound function. /// </summary> /// <param name="dragBoundFunc"></param> public void setDragBoundFunc(Delegate dragBoundFunc) { } /// <summary> /// set draggable /// </summary> /// <param name="draggable"></param> public void setDraggable(object draggable) { } /// <summary> /// set flag which enables or disables automatically moving the draggable node to a temporary top layer to improve performance. /// </summary> /// <param name="dragOnTop"></param> public void setDragOnTop(object dragOnTop) { } /// <summary> /// Set height /// </summary> /// <param name="height"></param> public void setHeight(Number height) { } /// <summary> /// Set id /// </summary> /// <param name="id"></param> public void setId(string id) { } /// <summary> /// Listen or don't listen to events /// </summary> /// <param name="listening"></param> public void setListening(object listening) { } /// <summary> /// Set name /// </summary> /// <param name="name"></param> public void setName(string name) { } /// <summary> /// Set offset. /// </summary> /// <param name="x"></param> /// <param name="y"></param> public void setOffset(Number x, Number y) { } /// <summary> /// Set opacity. /// </summary> /// <param name="opacity"></param> public void setOpacity(Number opacity) { } /// <summary> /// Set node position relative to parent /// </summary> /// <param name="x"></param> /// <param name="y"></param> public void setPosition(Number x, Number y) { } /// <summary> /// Set rotation in radians /// </summary> /// <param name="theta"></param> public void setRotation(Number theta) { } /// <summary> /// Set rotation in degrees /// </summary> /// <param name="deg"></param> public void setRotationDeg(Number deg) { } /// <summary> /// Set scale /// </summary> /// <param name="x"></param> /// <param name="y"></param> public void setScale(Number x, Number y) { } /// <summary> /// Set size /// </summary> /// <param name="width"></param> /// <param name="height"></param> public void setSize(Number width, Number height) { } /// <summary> /// Set visible /// </summary> /// <param name="visible"></param> public void setVisible(bool visible) { } /// <summary> /// Set width /// </summary> /// <param name="width"></param> public void setWidth(Number width) { } /// <summary> /// Set x position /// </summary> /// <param name="x"></param> public void setX(Number x) { } /// <summary> /// Set y position /// </summary> /// <param name="y"></param> public void setY(Number y) { } /// <summary> /// Set zIndex relative to siblings /// </summary> /// <param name="zIndex"></param> public void setZIndex(int zIndex) { } /// <summary> /// Show node /// </summary> public void show() { } /// <summary> /// Simulate event with event bubbling /// </summary> /// <param name="eventType"></param> /// <param name="evt"></param> public void simulate(object eventType, ElementEvent evt) { } /// <summary> /// Creates a composite data URL and requires a callback because the composite is generated asynchronously. /// </summary> /// <param name="config"></param> /// <returns></returns> public string toDataURL(ToImageConfig config) { return null; } /// <summary> /// Converts node into an image. /// </summary> /// <param name="config"></param> /// <returns></returns> public object toImage(ToImageConfig config) { return null; } /// <summary> /// Convert Node into a JSON string. /// </summary> /// <returns></returns> public string toJSON() { return null; } /// <summary> /// Convert Node into an object for serialization. /// </summary> /// <returns></returns> public object toObject() { return null; } /// <summary> /// transition node to another state. /// </summary> /// <param name="config"></param> public Transition transitionTo(TransitionConfig config) { return null; } } [Imported, IgnoreNamespace, ScriptName("Object")] public class NodeConfig { /// <summary> /// Optional /// </summary> public bool x; /// <summary> /// Optional /// </summary> public bool y; /// <summary> /// Optional /// </summary> public bool width; /// <summary> /// Optional /// </summary> public bool height; /// <summary> /// Optional /// </summary> public bool visible; /// <summary> /// Optional, whether or not the node is listening for events /// </summary> public bool listening; /// <summary> /// Optional, unique id /// </summary> public string id; /// <summary> /// Optional, non-unique name /// </summary> public string name; /// <summary> /// Optional, determines node opacity. Can be any number between 0 and 1 /// </summary> public bool opacity; /// <summary> /// Optional /// </summary> public Custom.Vector scale; /// <summary> /// Optional, rotation in radians /// </summary> public bool rotation; /// <summary> /// Optional, rotation in degrees /// </summary> public bool rotationDeg; /// <summary> /// Optional, offset from center point and rotation point /// </summary> public Custom.Vector offset; /// <summary> /// Optional /// </summary> public bool draggable; /// <summary> /// Optional /// </summary> public Delegate dragBoundFunc; public NodeConfig(params object[] nameValuePairs) { } } [Imported, IgnoreNamespace, ScriptName("Object")] public class ToImageConfig { /// <summary> /// function executed when the composite has completed /// </summary> public Delegate callback; /// <summary> /// Optional. Can be "image/png" or "image/jpeg". "image/png" is the default /// </summary> public string mimeType; /// <summary> /// Optional. X position of canvas section. /// </summary> public Number x; /// <summary> /// Optional. Y position of canvas section. /// </summary> public Number y; /// <summary> /// Optional. Width of canvas section. /// </summary> public Number width; /// <summary> /// Optional. Height of canvas section. /// </summary> public Number height; /// <summary> /// Optional. Jpeg quality. If using an "image/jpeg" mimeType, you can specify the quality from 0 to 1, where 0 is very poor quality and 1 is very high quality /// </summary> public Number quality; public ToImageConfig(params object[] nameValuePairs) { } } [Imported, IgnoreNamespace, ScriptName("Object")] public class NodeAttributes { public Number startScale; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/proto/grpc/testing/test.proto // Original file comments: // Copyright 2015-2016 gRPC authors. // // 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. // // An integration test service that covers all the method signature permutations // of unary/streaming requests/responses. // #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace Grpc.Testing { /// <summary> /// A simple service to test the various types of RPCs and experiment with /// performance with various types of payload. /// </summary> public static partial class TestService { static readonly string __ServiceName = "grpc.testing.TestService"; static readonly grpc::Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::Grpc.Testing.SimpleRequest> __Marshaller_SimpleRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Grpc.Testing.SimpleResponse> __Marshaller_SimpleResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Grpc.Testing.StreamingOutputCallRequest> __Marshaller_StreamingOutputCallRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Grpc.Testing.StreamingOutputCallResponse> __Marshaller_StreamingOutputCallResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Grpc.Testing.StreamingInputCallRequest> __Marshaller_StreamingInputCallRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Grpc.Testing.StreamingInputCallResponse> __Marshaller_StreamingInputCallResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallResponse.Parser.ParseFrom); static readonly grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_EmptyCall = new grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>( grpc::MethodType.Unary, __ServiceName, "EmptyCall", __Marshaller_Empty, __Marshaller_Empty); static readonly grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_UnaryCall = new grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>( grpc::MethodType.Unary, __ServiceName, "UnaryCall", __Marshaller_SimpleRequest, __Marshaller_SimpleResponse); static readonly grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_CacheableUnaryCall = new grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>( grpc::MethodType.Unary, __ServiceName, "CacheableUnaryCall", __Marshaller_SimpleRequest, __Marshaller_SimpleResponse); static readonly grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_StreamingOutputCall = new grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>( grpc::MethodType.ServerStreaming, __ServiceName, "StreamingOutputCall", __Marshaller_StreamingOutputCallRequest, __Marshaller_StreamingOutputCallResponse); static readonly grpc::Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> __Method_StreamingInputCall = new grpc::Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse>( grpc::MethodType.ClientStreaming, __ServiceName, "StreamingInputCall", __Marshaller_StreamingInputCallRequest, __Marshaller_StreamingInputCallResponse); static readonly grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_FullDuplexCall = new grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>( grpc::MethodType.DuplexStreaming, __ServiceName, "FullDuplexCall", __Marshaller_StreamingOutputCallRequest, __Marshaller_StreamingOutputCallResponse); static readonly grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_HalfDuplexCall = new grpc::Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>( grpc::MethodType.DuplexStreaming, __ServiceName, "HalfDuplexCall", __Marshaller_StreamingOutputCallRequest, __Marshaller_StreamingOutputCallResponse); static readonly grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_UnimplementedCall = new grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>( grpc::MethodType.Unary, __ServiceName, "UnimplementedCall", __Marshaller_Empty, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grpc.Testing.TestReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of TestService</summary> public abstract partial class TestServiceBase { /// <summary> /// One empty request followed by one empty response. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> EmptyCall(global::Grpc.Testing.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// One request followed by one response. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.SimpleResponse> UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// One request followed by one response. Response has cache control /// headers set such that a caching HTTP proxy (such as GFE) can /// satisfy subsequent requests. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.SimpleResponse> CacheableUnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// One request followed by a sequence of responses (streamed download). /// The server returns the payload with client desired type and sizes. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="responseStream">Used for sending responses back to the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>A task indicating completion of the handler.</returns> public virtual global::System.Threading.Tasks.Task StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, grpc::IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// A sequence of requests followed by one response (streamed upload). /// The server returns the aggregated size of client payload as the result. /// </summary> /// <param name="requestStream">Used for reading requests from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(grpc::IAsyncStreamReader<global::Grpc.Testing.StreamingInputCallRequest> requestStream, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// A sequence of requests with each request served by the server immediately. /// As one request could lead to multiple responses, this interface /// demonstrates the idea of full duplexing. /// </summary> /// <param name="requestStream">Used for reading requests from the client.</param> /// <param name="responseStream">Used for sending responses back to the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>A task indicating completion of the handler.</returns> public virtual global::System.Threading.Tasks.Task FullDuplexCall(grpc::IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// A sequence of requests followed by a sequence of responses. /// The server buffers all the client requests and then serves them in order. A /// stream of responses are returned to the client when the server starts with /// first request. /// </summary> /// <param name="requestStream">Used for reading requests from the client.</param> /// <param name="responseStream">Used for sending responses back to the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>A task indicating completion of the handler.</returns> public virtual global::System.Threading.Tasks.Task HalfDuplexCall(grpc::IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// The test server will not implement this method. It will be used /// to test the behavior when clients call unimplemented methods. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> UnimplementedCall(global::Grpc.Testing.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for TestService</summary> public partial class TestServiceClient : grpc::ClientBase<TestServiceClient> { /// <summary>Creates a new client for TestService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public TestServiceClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for TestService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public TestServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected TestServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected TestServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// One empty request followed by one empty response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return EmptyCall(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One empty request followed by one empty response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_EmptyCall, null, options, request); } /// <summary> /// One empty request followed by one empty response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return EmptyCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One empty request followed by one empty response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_EmptyCall, null, options, request); } /// <summary> /// One request followed by one response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnaryCall(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One request followed by one response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UnaryCall, null, options, request); } /// <summary> /// One request followed by one response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnaryCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One request followed by one response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UnaryCall, null, options, request); } /// <summary> /// One request followed by one response. Response has cache control /// headers set such that a caching HTTP proxy (such as GFE) can /// satisfy subsequent requests. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grpc.Testing.SimpleResponse CacheableUnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CacheableUnaryCall(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One request followed by one response. Response has cache control /// headers set such that a caching HTTP proxy (such as GFE) can /// satisfy subsequent requests. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grpc.Testing.SimpleResponse CacheableUnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CacheableUnaryCall, null, options, request); } /// <summary> /// One request followed by one response. Response has cache control /// headers set such that a caching HTTP proxy (such as GFE) can /// satisfy subsequent requests. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> CacheableUnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CacheableUnaryCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One request followed by one response. Response has cache control /// headers set such that a caching HTTP proxy (such as GFE) can /// satisfy subsequent requests. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> CacheableUnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CacheableUnaryCall, null, options, request); } /// <summary> /// One request followed by a sequence of responses (streamed download). /// The server returns the payload with client desired type and sizes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return StreamingOutputCall(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One request followed by a sequence of responses (streamed download). /// The server returns the payload with client desired type and sizes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, grpc::CallOptions options) { return CallInvoker.AsyncServerStreamingCall(__Method_StreamingOutputCall, null, options, request); } /// <summary> /// A sequence of requests followed by one response (streamed upload). /// The server returns the aggregated size of client payload as the result. /// </summary> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return StreamingInputCall(new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A sequence of requests followed by one response (streamed upload). /// The server returns the aggregated size of client payload as the result. /// </summary> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(grpc::CallOptions options) { return CallInvoker.AsyncClientStreamingCall(__Method_StreamingInputCall, null, options); } /// <summary> /// A sequence of requests with each request served by the server immediately. /// As one request could lead to multiple responses, this interface /// demonstrates the idea of full duplexing. /// </summary> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return FullDuplexCall(new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A sequence of requests with each request served by the server immediately. /// As one request could lead to multiple responses, this interface /// demonstrates the idea of full duplexing. /// </summary> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(grpc::CallOptions options) { return CallInvoker.AsyncDuplexStreamingCall(__Method_FullDuplexCall, null, options); } /// <summary> /// A sequence of requests followed by a sequence of responses. /// The server buffers all the client requests and then serves them in order. A /// stream of responses are returned to the client when the server starts with /// first request. /// </summary> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return HalfDuplexCall(new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A sequence of requests followed by a sequence of responses. /// The server buffers all the client requests and then serves them in order. A /// stream of responses are returned to the client when the server starts with /// first request. /// </summary> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(grpc::CallOptions options) { return CallInvoker.AsyncDuplexStreamingCall(__Method_HalfDuplexCall, null, options); } /// <summary> /// The test server will not implement this method. It will be used /// to test the behavior when clients call unimplemented methods. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnimplementedCall(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// The test server will not implement this method. It will be used /// to test the behavior when clients call unimplemented methods. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UnimplementedCall, null, options, request); } /// <summary> /// The test server will not implement this method. It will be used /// to test the behavior when clients call unimplemented methods. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnimplementedCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// The test server will not implement this method. It will be used /// to test the behavior when clients call unimplemented methods. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UnimplementedCall, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override TestServiceClient NewInstance(ClientBaseConfiguration configuration) { return new TestServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(TestServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_EmptyCall, serviceImpl.EmptyCall) .AddMethod(__Method_UnaryCall, serviceImpl.UnaryCall) .AddMethod(__Method_CacheableUnaryCall, serviceImpl.CacheableUnaryCall) .AddMethod(__Method_StreamingOutputCall, serviceImpl.StreamingOutputCall) .AddMethod(__Method_StreamingInputCall, serviceImpl.StreamingInputCall) .AddMethod(__Method_FullDuplexCall, serviceImpl.FullDuplexCall) .AddMethod(__Method_HalfDuplexCall, serviceImpl.HalfDuplexCall) .AddMethod(__Method_UnimplementedCall, serviceImpl.UnimplementedCall).Build(); } } /// <summary> /// A simple service NOT implemented at servers so clients can test for /// that case. /// </summary> public static partial class UnimplementedService { static readonly string __ServiceName = "grpc.testing.UnimplementedService"; static readonly grpc::Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom); static readonly grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_UnimplementedCall = new grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>( grpc::MethodType.Unary, __ServiceName, "UnimplementedCall", __Marshaller_Empty, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grpc.Testing.TestReflection.Descriptor.Services[1]; } } /// <summary>Base class for server-side implementations of UnimplementedService</summary> public abstract partial class UnimplementedServiceBase { /// <summary> /// A call that no server should implement /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> UnimplementedCall(global::Grpc.Testing.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for UnimplementedService</summary> public partial class UnimplementedServiceClient : grpc::ClientBase<UnimplementedServiceClient> { /// <summary>Creates a new client for UnimplementedService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public UnimplementedServiceClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for UnimplementedService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public UnimplementedServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected UnimplementedServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected UnimplementedServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// A call that no server should implement /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnimplementedCall(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A call that no server should implement /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UnimplementedCall, null, options, request); } /// <summary> /// A call that no server should implement /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnimplementedCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A call that no server should implement /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UnimplementedCall, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override UnimplementedServiceClient NewInstance(ClientBaseConfiguration configuration) { return new UnimplementedServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(UnimplementedServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_UnimplementedCall, serviceImpl.UnimplementedCall).Build(); } } /// <summary> /// A service used to control reconnect server. /// </summary> public static partial class ReconnectService { static readonly string __ServiceName = "grpc.testing.ReconnectService"; static readonly grpc::Marshaller<global::Grpc.Testing.ReconnectParams> __Marshaller_ReconnectParams = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ReconnectParams.Parser.ParseFrom); static readonly grpc::Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::Grpc.Testing.ReconnectInfo> __Marshaller_ReconnectInfo = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ReconnectInfo.Parser.ParseFrom); static readonly grpc::Method<global::Grpc.Testing.ReconnectParams, global::Grpc.Testing.Empty> __Method_Start = new grpc::Method<global::Grpc.Testing.ReconnectParams, global::Grpc.Testing.Empty>( grpc::MethodType.Unary, __ServiceName, "Start", __Marshaller_ReconnectParams, __Marshaller_Empty); static readonly grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.ReconnectInfo> __Method_Stop = new grpc::Method<global::Grpc.Testing.Empty, global::Grpc.Testing.ReconnectInfo>( grpc::MethodType.Unary, __ServiceName, "Stop", __Marshaller_Empty, __Marshaller_ReconnectInfo); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grpc.Testing.TestReflection.Descriptor.Services[2]; } } /// <summary>Base class for server-side implementations of ReconnectService</summary> public abstract partial class ReconnectServiceBase { public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> Start(global::Grpc.Testing.ReconnectParams request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.ReconnectInfo> Stop(global::Grpc.Testing.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for ReconnectService</summary> public partial class ReconnectServiceClient : grpc::ClientBase<ReconnectServiceClient> { /// <summary>Creates a new client for ReconnectService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public ReconnectServiceClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for ReconnectService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public ReconnectServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected ReconnectServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected ReconnectServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } public virtual global::Grpc.Testing.Empty Start(global::Grpc.Testing.ReconnectParams request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Start(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Grpc.Testing.Empty Start(global::Grpc.Testing.ReconnectParams request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Start, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.ReconnectParams request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return StartAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.ReconnectParams request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Start, null, options, request); } public virtual global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Stop(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Stop, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return StopAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Stop, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override ReconnectServiceClient NewInstance(ClientBaseConfiguration configuration) { return new ReconnectServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(ReconnectServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_Start, serviceImpl.Start) .AddMethod(__Method_Stop, serviceImpl.Stop).Build(); } } } #endregion
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic; using System.Dynamic.Utils; using System.Linq.Expressions; using System.Reflection; #if FEATURE_COMPILE using System.Linq.Expressions.Compiler; #endif namespace System.Runtime.CompilerServices { // // A CallSite provides a fast mechanism for call-site caching of dynamic dispatch // behvaior. Each site will hold onto a delegate that provides a fast-path dispatch // based on previous types that have been seen at the call-site. This delegate will // call UpdateAndExecute if it is called with types that it hasn't seen before. // Updating the binding will typically create (or lookup) a new delegate // that supports fast-paths for both the new type and for any types that // have been seen previously. // // DynamicSites will generate the fast-paths specialized for sets of runtime argument // types. However, they will generate exactly the right amount of code for the types // that are seen in the program so that int addition will remain as fast as it would // be with custom implementation of the addition, and the user-defined types can be // as fast as ints because they will all have the same optimal dynamically generated // fast-paths. // // DynamicSites don't encode any particular caching policy, but use their // CallSiteBinding to encode a caching policy. // /// <summary> /// A Dynamic Call Site base class. This type is used as a parameter type to the /// dynamic site targets. The first parameter of the delegate (T) below must be /// of this type. /// </summary> public class CallSite { // Cache of CallSite constructors for a given delegate type private static volatile CacheDict<Type, Func<CallSiteBinder, CallSite>> s_siteCtors; /// <summary> /// The Binder responsible for binding operations at this call site. /// This binder is invoked by the UpdateAndExecute below if all Level 0, /// Level 1 and Level 2 caches experience cache miss. /// </summary> internal readonly CallSiteBinder _binder; // only CallSite<T> derives from this internal CallSite(CallSiteBinder binder) { _binder = binder; } /// <summary> /// used by Matchmaker sites to indicate rule match. /// </summary> internal bool _match; /// <summary> /// Class responsible for binding dynamic operations on the dynamic site. /// </summary> public CallSiteBinder Binder { get { return _binder; } } /// <summary> /// Creates a CallSite with the given delegate type and binder. /// </summary> /// <param name="delegateType">The CallSite delegate type.</param> /// <param name="binder">The CallSite binder.</param> /// <returns>The new CallSite.</returns> public static CallSite Create(Type delegateType, CallSiteBinder binder) { ContractUtils.RequiresNotNull(delegateType, "delegateType"); ContractUtils.RequiresNotNull(binder, "binder"); if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate(); var ctors = s_siteCtors; if (ctors == null) { // It's okay to just set this, worst case we're just throwing away some data s_siteCtors = ctors = new CacheDict<Type, Func<CallSiteBinder, CallSite>>(100); } Func<CallSiteBinder, CallSite> ctor; MethodInfo method = null; if (!ctors.TryGetValue(delegateType, out ctor)) { method = typeof(CallSite<>).MakeGenericType(delegateType).GetMethod("Create"); if (TypeUtils.CanCache(delegateType)) { ctor = (Func<CallSiteBinder, CallSite>)method.CreateDelegate(typeof(Func<CallSiteBinder, CallSite>)); ctors.Add(delegateType, ctor); } } if (ctor != null) { return ctor(binder); } // slow path return (CallSite)method.Invoke(null, new object[] { binder }); } } /// <summary> /// Dynamic site type. /// </summary> /// <typeparam name="T">The delegate type.</typeparam> public partial class CallSite<T> : CallSite where T : class { /// <summary> /// The update delegate. Called when the dynamic site experiences cache miss. /// </summary> /// <returns>The update delegate.</returns> public T Update { get { // if this site is set up for match making, then use NoMatch as an Update if (_match) { Debug.Assert(s_cachedNoMatch != null, "all normal sites should have Update cached once there is an instance."); return s_cachedNoMatch; } else { Debug.Assert(s_cachedUpdate != null, "all normal sites should have Update cached once there is an instance."); return s_cachedUpdate; } } } /// <summary> /// The Level 0 cache - a delegate specialized based on the site history. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] public T Target; /// <summary> /// The Level 1 cache - a history of the dynamic site. /// </summary> internal T[] Rules; // Cached update delegate for all sites with a given T private static T s_cachedUpdate; // Cached noMatch delegate for all sites with a given T private static volatile T s_cachedNoMatch; private CallSite(CallSiteBinder binder) : base(binder) { Target = GetUpdateDelegate(); } private CallSite() : base(null) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal CallSite<T> CreateMatchMaker() { return new CallSite<T>(); } /// <summary> /// Creates an instance of the dynamic call site, initialized with the binder responsible for the /// runtime binding of the dynamic operations at this call site. /// </summary> /// <param name="binder">The binder responsible for the runtime binding of the dynamic operations at this call site.</param> /// <returns>The new instance of dynamic call site.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static CallSite<T> Create(CallSiteBinder binder) { if (!typeof(T).IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate(); return new CallSite<T>(binder); } private T GetUpdateDelegate() { // This is intentionally non-static to speed up creation - in particular MakeUpdateDelegate // as static generic methods are more expensive than instance methods. We call a ref helper // so we only access the generic static field once. return GetUpdateDelegate(ref s_cachedUpdate); } private T GetUpdateDelegate(ref T addr) { if (addr == null) { // reduce creation cost by not using Interlocked.CompareExchange. Calling I.CE causes // us to spend 25% of our creation time in JIT_GenericHandle. Instead we'll rarely // create 2 delegates with no other harm caused. addr = MakeUpdateDelegate(); } return addr; } /// <summary> /// Clears the rule cache ... used by the call site tests. /// </summary> private void ClearRuleCache() { // make sure it initialized/atomized etc... Binder.GetRuleCache<T>(); var cache = Binder.Cache; if (cache != null) { lock (cache) { cache.Clear(); } } } private const int MaxRules = 10; internal void AddRule(T newRule) { T[] rules = Rules; if (rules == null) { Rules = new[] { newRule }; return; } T[] temp; if (rules.Length < (MaxRules - 1)) { temp = new T[rules.Length + 1]; Array.Copy(rules, 0, temp, 1, rules.Length); } else { temp = new T[MaxRules]; Array.Copy(rules, 0, temp, 1, MaxRules - 1); } temp[0] = newRule; Rules = temp; } // moves rule +2 up. internal void MoveRule(int i) { if (i > 1) { var rules = Rules; var rule = rules[i]; rules[i] = rules[i - 1]; rules[i - 1] = rules[i - 2]; rules[i - 2] = rule; } } internal T MakeUpdateDelegate() { #if !FEATURE_COMPILE Type target = typeof(T); MethodInfo invoke = target.GetMethod("Invoke"); s_cachedNoMatch = CreateCustomNoMatchDelegate(invoke); return CreateCustomUpdateDelegate(invoke); #else Type target = typeof(T); Type[] args; MethodInfo invoke = target.GetMethod("Invoke"); if (target.GetTypeInfo().IsGenericType && IsSimpleSignature(invoke, out args)) { MethodInfo method = null; MethodInfo noMatchMethod = null; if (invoke.ReturnType == typeof(void)) { if (target == DelegateHelpers.GetActionType(args.AddFirst(typeof(CallSite)))) { method = typeof(UpdateDelegates).GetMethod("UpdateAndExecuteVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static); noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatchVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static); } } else { if (target == DelegateHelpers.GetFuncType(args.AddFirst(typeof(CallSite)))) { method = typeof(UpdateDelegates).GetMethod("UpdateAndExecute" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static); noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatch" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static); } } if (method != null) { s_cachedNoMatch = (T)(object)CreateDelegateHelper(target, noMatchMethod.MakeGenericMethod(args)); return (T)(object)CreateDelegateHelper(target, method.MakeGenericMethod(args)); } } s_cachedNoMatch = CreateCustomNoMatchDelegate(invoke); return CreateCustomUpdateDelegate(invoke); #endif } #if FEATURE_COMPILE // This needs to be SafeCritical to allow access to // internal types from user code as generic parameters. // // It's safe for a few reasons: // 1. The internal types are coming from a lower trust level (app code) // 2. We got the internal types from our own generic parameter: T // 3. The UpdateAndExecute methods don't do anything with the types, // we just want the CallSite args to be strongly typed to avoid // casting. // 4. Works on desktop CLR with AppDomain that has only Execute // permission. In theory it might require RestrictedMemberAccess, // but it's unclear because we have tests passing without RMA. // // When Silverlight gets RMA we may be able to remove this. [System.Security.SecuritySafeCritical] private static Delegate CreateDelegateHelper(Type delegateType, MethodInfo method) { return method.CreateDelegate(delegateType); } private static bool IsSimpleSignature(MethodInfo invoke, out Type[] sig) { ParameterInfo[] pis = invoke.GetParametersCached(); ContractUtils.Requires(pis.Length > 0 && pis[0].ParameterType == typeof(CallSite), "T"); Type[] args = new Type[invoke.ReturnType != typeof(void) ? pis.Length : pis.Length - 1]; bool supported = true; for (int i = 1; i < pis.Length; i++) { ParameterInfo pi = pis[i]; if (pi.IsByRefParameter()) { supported = false; } args[i - 1] = pi.ParameterType; } if (invoke.ReturnType != typeof(void)) { args[args.Length - 1] = invoke.ReturnType; } sig = args; return supported; } #endif [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private T CreateCustomUpdateDelegate(MethodInfo invoke) { var body = new List<Expression>(); var vars = new List<ParameterExpression>(); var @params = invoke.GetParametersCached().Map(p => Expression.Parameter(p.ParameterType, p.Name)); var @return = Expression.Label(invoke.GetReturnType()); var typeArgs = new[] { typeof(T) }; var site = @params[0]; var arguments = @params.RemoveFirst(); var @this = Expression.Variable(typeof(CallSite<T>), "this"); vars.Add(@this); body.Add(Expression.Assign(@this, Expression.Convert(site, @this.Type))); var applicable = Expression.Variable(typeof(T[]), "applicable"); vars.Add(applicable); var rule = Expression.Variable(typeof(T), "rule"); vars.Add(rule); var originalRule = Expression.Variable(typeof(T), "originalRule"); vars.Add(originalRule); body.Add(Expression.Assign(originalRule, Expression.Field(@this, "Target"))); ParameterExpression result = null; if (@return.Type != typeof(void)) { vars.Add(result = Expression.Variable(@return.Type, "result")); } var count = Expression.Variable(typeof(int), "count"); vars.Add(count); var index = Expression.Variable(typeof(int), "index"); vars.Add(index); body.Add( Expression.Assign( site, Expression.Call( typeof(CallSiteOps), "CreateMatchmaker", typeArgs, @this ) ) ); Expression invokeRule; Expression getMatch = Expression.Call( typeof(CallSiteOps).GetMethod("GetMatch"), site ); Expression resetMatch = Expression.Call( typeof(CallSiteOps).GetMethod("ClearMatch"), site ); var onMatch = Expression.Call( typeof(CallSiteOps), "UpdateRules", typeArgs, @this, index ); if (@return.Type == typeof(void)) { invokeRule = Expression.Block( Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params)), Expression.IfThen( getMatch, Expression.Block(onMatch, Expression.Return(@return)) ) ); } else { invokeRule = Expression.Block( Expression.Assign(result, Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params))), Expression.IfThen( getMatch, Expression.Block(onMatch, Expression.Return(@return, result)) ) ); } Expression getRule = Expression.Assign(rule, Expression.ArrayAccess(applicable, index)); var @break = Expression.Label(); var breakIfDone = Expression.IfThen( Expression.Equal(index, count), Expression.Break(@break) ); var incrementIndex = Expression.PreIncrementAssign(index); body.Add( Expression.IfThen( Expression.NotEqual( Expression.Assign(applicable, Expression.Call(typeof(CallSiteOps), "GetRules", typeArgs, @this)), Expression.Constant(null, applicable.Type) ), Expression.Block( Expression.Assign(count, Expression.ArrayLength(applicable)), Expression.Assign(index, Expression.Constant(0)), Expression.Loop( Expression.Block( breakIfDone, getRule, Expression.IfThen( Expression.NotEqual( Expression.Convert(rule, typeof(object)), Expression.Convert(originalRule, typeof(object)) ), Expression.Block( Expression.Assign( Expression.Field(@this, "Target"), rule ), invokeRule, resetMatch ) ), incrementIndex ), @break, null ) ) ) ); //// //// Level 2 cache lookup //// // //// //// Any applicable rules in level 2 cache? //// var cache = Expression.Variable(typeof(RuleCache<T>), "cache"); vars.Add(cache); body.Add( Expression.Assign( cache, Expression.Call(typeof(CallSiteOps), "GetRuleCache", typeArgs, @this) ) ); body.Add( Expression.Assign( applicable, Expression.Call(typeof(CallSiteOps), "GetCachedRules", typeArgs, cache) ) ); // L2 invokeRule is different (no onMatch) if (@return.Type == typeof(void)) { invokeRule = Expression.Block( Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params)), Expression.IfThen( getMatch, Expression.Return(@return) ) ); } else { invokeRule = Expression.Block( Expression.Assign(result, Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params))), Expression.IfThen( getMatch, Expression.Return(@return, result) ) ); } var tryRule = Expression.TryFinally( invokeRule, Expression.IfThen( getMatch, Expression.Block( Expression.Call(typeof(CallSiteOps), "AddRule", typeArgs, @this, rule), Expression.Call(typeof(CallSiteOps), "MoveRule", typeArgs, cache, rule, index) ) ) ); getRule = Expression.Assign( Expression.Field(@this, "Target"), Expression.Assign(rule, Expression.ArrayAccess(applicable, index)) ); body.Add(Expression.Assign(index, Expression.Constant(0))); body.Add(Expression.Assign(count, Expression.ArrayLength(applicable))); body.Add( Expression.Loop( Expression.Block( breakIfDone, getRule, tryRule, resetMatch, incrementIndex ), @break, null ) ); //// //// Miss on Level 0, 1 and 2 caches. Create new rule //// body.Add(Expression.Assign(rule, Expression.Constant(null, rule.Type))); var args = Expression.Variable(typeof(object[]), "args"); vars.Add(args); body.Add( Expression.Assign( args, Expression.NewArrayInit(typeof(object), arguments.Map(p => Convert(p, typeof(object)))) ) ); Expression setOldTarget = Expression.Assign( Expression.Field(@this, "Target"), originalRule ); getRule = Expression.Assign( Expression.Field(@this, "Target"), Expression.Assign( rule, Expression.Call( typeof(CallSiteOps), "Bind", typeArgs, Expression.Property(@this, "Binder"), @this, args ) ) ); tryRule = Expression.TryFinally( invokeRule, Expression.IfThen( getMatch, Expression.Call(typeof(CallSiteOps), "AddRule", typeArgs, @this, rule) ) ); body.Add( Expression.Loop( Expression.Block(setOldTarget, getRule, tryRule, resetMatch), null, null ) ); body.Add(Expression.Default(@return.Type)); var lambda = Expression.Lambda<T>( Expression.Label( @return, Expression.Block( new ReadOnlyCollection<ParameterExpression>(vars), new ReadOnlyCollection<Expression>(body) ) ), "CallSite.Target", true, // always compile the rules with tail call optimization new ReadOnlyCollection<ParameterExpression>(@params) ); // Need to compile with forceDynamic because T could be invisible, // or one of the argument types could be invisible return lambda.Compile(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private T CreateCustomNoMatchDelegate(MethodInfo invoke) { var @params = invoke.GetParametersCached().Map(p => Expression.Parameter(p.ParameterType, p.Name)); return Expression.Lambda<T>( Expression.Block( Expression.Call( typeof(CallSiteOps).GetMethod("SetNotMatched"), @params.First() ), Expression.Default(invoke.GetReturnType()) ), @params ).Compile(); } private static Expression Convert(Expression arg, Type type) { if (TypeUtils.AreReferenceAssignable(type, arg.Type)) { return arg; } return Expression.Convert(arg, type); } } }
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Amazon; using Amazon.Glacier.Transfer; using Amazon.Runtime; using Amazon.Runtime.CredentialManagement; using GlacierBackup.FileSearchers; using GlacierBackup.Writers; namespace GlacierBackup { public class Program { const int RETRY_COUNT = 3; const int START_WAIT_TIME_MS = 5000; static readonly object _lockObj = new object(); static readonly Random _rand = new Random(); readonly Options _opts; readonly IResultWriter _resultWriter; readonly IFileSearcher _searcher; readonly int _vpus; readonly ArchiveTransferManager _atm; internal Program(Options opts) { _opts = opts; _searcher = GetFileSearcher(); _resultWriter = GetResultWriter(); _vpus = GetVpus(); _atm = new ArchiveTransferManager(_opts.Credentials, _opts.Region); } public static void Main(string[] args) { if(args.Length != 8) { ShowUsage(); Environment.Exit(1); } var profile = args[0]; var awsRegion = RegionEndpoint.GetBySystemName(args[1]); var vaultName = args[2]; var backupType = args[3]; var backupSource = args[4]; // individual file / or folder var relativeRoot = args[5]; var outputType = args[6]; var output = args[7]; // sql file to write AWSCredentials credentials = null; var sharedFile = new SharedCredentialsFile(); try { if (sharedFile.TryGetProfile(profile, out CredentialProfile theProfile)) { credentials = AWSCredentialsFactory.GetAWSCredentials(theProfile, sharedFile); } else { throw new ApplicationException("Unable to access profile."); } } catch (System.Exception) { Console.WriteLine($"Unable to obtain credentials for profile [{profile}]. Please make sure this is properly configured in ~/.aws/credentials."); Environment.Exit(2); } if(string.Equals(awsRegion.DisplayName, "Unknown", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine($"The specified region [{awsRegion.SystemName}] was unknown! Please select a valid region."); Environment.Exit(2); } BackupType theBackupType; if(!Enum.TryParse<BackupType>(backupType, true, out theBackupType)) { Console.WriteLine($"Please specify a valid backup type [Full, Assets, File]."); Environment.Exit(2); } if(theBackupType == BackupType.File && !File.Exists(backupSource)) { Console.WriteLine($"The specified backup file [{backupSource}] does not exist. Please enter a valid directory path to backup."); Environment.Exit(2); } else if((theBackupType == BackupType.Assets || theBackupType == BackupType.Full) && !Directory.Exists(backupSource)) { Console.WriteLine($"The specified backup directory [{backupSource}] does not exist. Please enter a valid directory path to backup."); Environment.Exit(2); } else if(theBackupType == BackupType.List && !File.Exists(backupSource)) { Console.WriteLine($"The specified file containing the list of files to backup [{backupSource}] does not exist. Please enter a valid path to the list file."); Environment.Exit(2); } if(theBackupType != BackupType.List && relativeRoot.Length > backupSource.Length) { Console.WriteLine("The relative_root path should be the starting part of the path to the backup to remove, such that the remaining path is tracked as the archive description."); Environment.Exit(2); } if(theBackupType != BackupType.List && !backupSource.StartsWith(relativeRoot)) { Console.WriteLine("The relative_root should exactly match the same starting path to the backup_source."); Environment.Exit(2); } OutputType theOutputType; if(!Enum.TryParse<OutputType>(outputType, true, out theOutputType)) { Console.WriteLine($"Please specify a valid output type [PhotoSql, VideoSql, Csv]."); Environment.Exit(2); } if(File.Exists(output)) { Console.WriteLine("Output file already exists - exiting!"); Environment.Exit(2); } var program = new Program(new Options { Credentials = credentials, Region = awsRegion, VaultName = vaultName, BackupType = theBackupType, BackupSource = backupSource, RelativeRoot = relativeRoot, OutputType = theOutputType, Output = output }); program.Execute(); } void Execute() { _resultWriter.Initialize(); BackupFiles(); _resultWriter.Complete(); } void BackupFiles() { var files = _searcher.FindFiles(_opts.BackupSource); // try to leave a couple threads available for the GC var opts = new ParallelOptions { MaxDegreeOfParallelism = _vpus }; Parallel.ForEach(files, opts, BackupFile); } void BackupFile(string file) { var backupFile = new BackupFile(file, _opts.RelativeRoot); var result = new BackupResult { Region = _opts.Region, Vault = _opts.VaultName, Backup = backupFile }; for(var i = 1; i <= RETRY_COUNT; i++) { var attempt = i > 1 ? $" (attempt {i})" : string.Empty; try { Console.WriteLine($" - backing up {backupFile.GlacierDescription}{attempt}"); result.Result = _atm.UploadAsync(_opts.VaultName, backupFile.GlacierDescription, backupFile.FullPath).Result; lock(_lockObj) { _resultWriter.WriteResult(result); } return; } catch(Exception ex) { Console.WriteLine($" - error backing up {backupFile.GlacierDescription}{attempt}: {ex.Message}"); var ms = _rand.Next(START_WAIT_TIME_MS) * i; // wait for a random amount of time, and increase as the number of tries increases Thread.Sleep(ms); } } Console.WriteLine($" ** unable to backup {backupFile.GlacierDescription} **"); } IFileSearcher GetFileSearcher() { switch(_opts.BackupType) { case BackupType.Assets: { if(string.Equals(_opts.VaultName, "photos", StringComparison.OrdinalIgnoreCase)) { return new PhotoAssetFileSearcher(); } if(string.Equals(_opts.VaultName, "videos", StringComparison.OrdinalIgnoreCase)) { return new VideoAssetFileSearcher(); } throw new ApplicationException($"Unknown Asset Type for vault { _opts.VaultName }"); } case BackupType.Full: { return new AllFileSearcher(); } case BackupType.File: { return new SingleFileSearcher(); } case BackupType.List: { return new ListFileSearcher(); } } throw new InvalidOperationException("This backup type is not properly supported"); } IResultWriter GetResultWriter() { switch(_opts.OutputType) { case OutputType.PhotoSql: return new PhotosPgSqlResultWriter(_opts.Output); case OutputType.VideoSql: return new VideosPgSqlResultWriter(_opts.Output); case OutputType.Csv: return new CsvResultWriter(_opts.Output); } throw new InvalidOperationException("This output type is not properly supported"); } int GetVpus() { return Math.Max(1, Environment.ProcessorCount - 1); } static void ShowUsage() { Console.WriteLine("GlacierBackup <aws_profile> <aws_region> <aws_vault> <backup_type> <backup_source> <relative_root> <output_type> <output_file>"); Console.WriteLine(" where:"); Console.WriteLine(" aws_profile = name of AWS profile from your credentials file"); Console.WriteLine(" aws_region = name of AWS region (i.e. us-east-1, us-west-2)"); Console.WriteLine(" aws_vault = name of the already created vault to store archives in"); Console.WriteLine(" backup_type = one of the following:"); Console.WriteLine(" assets: backup all files contained in 'src' directories "); Console.WriteLine(" full: backup all files in the specified directory or below"); Console.WriteLine(" file: backup an individual file"); Console.WriteLine(" list: backup all files contained in the specified file (1 per line)"); Console.WriteLine(" backup_source = file or directory containing files to backup"); Console.WriteLine(" relative_root = starting part of path to remove when building Glacier description"); Console.WriteLine(" output_type = type of file to generate: [PhotoSql, VideoSql, Csv]"); Console.WriteLine(" photosql: sql update script for photos"); Console.WriteLine(" videosql: sql update script for videos"); Console.WriteLine(" csv: generic CSV file"); Console.WriteLine(" output_file = path where the sql should be written that maps archive details to the asset"); Console.WriteLine(); } } }
// Copyright 2018 Esri. // // 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.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks.Offline; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using Foundation; using UIKit; namespace ArcGISRuntime.Samples.ExportTiles { [Register("ExportTiles")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Export tiles", category: "Layers", description: "Download tiles to a local tile cache file stored on the device.", instructions: "Pan and zoom into the desired area, making sure the area is within the red boundary. Tap the 'Export tiles' button to start the process. On successful completion you will see a preview of the downloaded tile package.", tags: new[] { "cache", "download", "export", "local", "offline", "package", "tiles" })] public class ExportTiles : UIViewController { // Hold references to UI controls. private MapView _myMapView; private UIBarButtonItem _exportTilesButton; private UIActivityIndicatorView _statusIndicator; // URL to the service tiles will be exported from. private readonly Uri _serviceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer"); // Path to exported tiles on disk. private string _tilePath; public ExportTiles() { Title = "Export tiles"; } private async void Initialize() { try { // Create the tile layer. ArcGISTiledLayer myLayer = new ArcGISTiledLayer(_serviceUri); // Load the layer. await myLayer.LoadAsync(); // Create and show the basemap with the layer. _myMapView.Map = new Map(new Basemap(myLayer)) { // Set the min and max scale - export task fails if the scale is too big or small. MaxScale = 5000000, MinScale = 10000000 }; // Create a new symbol for the extent graphic. // This is the red box that visualizes the extent for which tiles will be exported. SimpleLineSymbol myExtentSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2); // Create a graphics overlay for the extent graphic and apply a renderer. GraphicsOverlay extentOverlay = new GraphicsOverlay { Renderer = new SimpleRenderer(myExtentSymbol) }; // Add the graphics overlay to the map view. _myMapView.GraphicsOverlays.Add(extentOverlay); // Update the graphic - needed in case the user decides not to interact before pressing the button. UpdateMapExtentGraphic(); // Enable the export button now that sample is ready. _exportTilesButton.Enabled = true; // Set viewpoint of the map. _myMapView.SetViewpoint(new Viewpoint(-4.853791, 140.983598, _myMapView.Map.MinScale)); } catch (Exception ex) { ShowStatusMessage(ex.ToString()); } } private void MyMapView_ViewpointChanged(object sender, EventArgs e) { UpdateMapExtentGraphic(); } /// <summary> /// Function used to keep the overlaid preview area marker in position. /// This is called by MyMapView_ViewpointChanged every time the user pans/zooms /// and updates the red box graphic to outline 70% of the current view. /// </summary> private void UpdateMapExtentGraphic() { // Get the new viewpoint. Viewpoint myViewPoint = _myMapView?.GetCurrentViewpoint(ViewpointType.BoundingGeometry); // Get the updated extent for the new viewpoint. Envelope extent = myViewPoint?.TargetGeometry as Envelope; // Return if extent is null. if (extent == null) { return; } // Create an envelope that is a bit smaller than the extent. EnvelopeBuilder envelopeBldr = new EnvelopeBuilder(extent); envelopeBldr.Expand(0.70); // Get the (only) graphics overlay in the map view. GraphicsOverlay extentOverlay = _myMapView.GraphicsOverlays.FirstOrDefault(); // Return if the extent overlay is null. if (extentOverlay == null) { return; } // Get the extent graphic. Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault(); // Create the extent graphic and add it to the overlay if it doesn't exist. if (extentGraphic == null) { extentGraphic = new Graphic(envelopeBldr.ToGeometry()); extentOverlay.Graphics.Add(extentGraphic); } else { // Otherwise, update the graphic's geometry. extentGraphic.Geometry = envelopeBldr.ToGeometry(); } } private async Task StartExport() { // Get the parameters for the job. ExportTileCacheParameters parameters = GetExportParameters(); // Create the task. ExportTileCacheTask exportTask = await ExportTileCacheTask.CreateAsync(_serviceUri); // Update tile cache path. _tilePath = $"{Path.GetTempFileName()}.tpk"; // Create the export job. ExportTileCacheJob job = exportTask.ExportTileCache(parameters, _tilePath); // Start the export job. job.Start(); // Get the result. TileCache resultTileCache = await job.GetResultAsync(); // Do the rest of the work. HandleExportCompletion(job, resultTileCache); } private ExportTileCacheParameters GetExportParameters() { // Create a new parameters instance. ExportTileCacheParameters parameters = new ExportTileCacheParameters(); // Get the (only) graphics overlay in the map view. GraphicsOverlay extentOverlay = _myMapView.GraphicsOverlays.First(); // Get the area selection graphic's extent. Graphic extentGraphic = extentOverlay.Graphics.First(); // Set the area for the export. parameters.AreaOfInterest = extentGraphic.Geometry; // Get the highest possible export quality. parameters.CompressionQuality = 100; // Add level IDs 1-9. // Note: Failing to add at least one Level ID will result in job failure. for (int x = 1; x < 10; x++) { parameters.LevelIds.Add(x); } // Return the parameters. return parameters; } private void HandleExportCompletion(ExportTileCacheJob job, TileCache cache) { // Hide the progress bar. _statusIndicator.StopAnimating(); switch (job.Status) { // Update the view if the job is complete. case Esri.ArcGISRuntime.Tasks.JobStatus.Succeeded: // Dispatcher is necessary due to the threading implementation; // this method is called from a thread other than the UI thread. InvokeOnMainThread(async () => { // Show the exported tiles on the preview map. try { await UpdatePreviewMap(cache); } catch (Exception ex) { ShowStatusMessage(ex.ToString()); } }); break; case Esri.ArcGISRuntime.Tasks.JobStatus.Failed: // Notify the user. ShowStatusMessage("Job failed"); // Dispatcher is necessary due to the threading implementation; // this method is called from a thread other than the UI thread. InvokeOnMainThread(() => { // Re-enable the export button. _exportTilesButton.Enabled = true; }); break; } } private async Task UpdatePreviewMap(TileCache cache) { // Load the cache. await cache.LoadAsync(); // Create a tile layer with the cache. ArcGISTiledLayer myLayer = new ArcGISTiledLayer(cache); // Show the exported tiles in new map. var vc = new UIViewController(); Map previewMap = new Map(); previewMap.OperationalLayers.Add(myLayer); vc.View = new MapView {Map = previewMap}; vc.Title = "Exported tiles"; NavigationController.PushViewController(vc, true); } private async void MyExportButton_Click(object sender, EventArgs e) { // If preview isn't open, start an export. try { // Disable the export button. _exportTilesButton.Enabled = false; // Show the progress bar. _statusIndicator.StartAnimating(); // Start the export. await StartExport(); } catch (Exception ex) { _statusIndicator.StopAnimating(); ShowStatusMessage(ex.ToString()); } } private void ShowStatusMessage(string message) { // Display the message to the user. UIAlertView alertView = new UIAlertView("alert", message, (IUIAlertViewDelegate) null, "OK", null); alertView.Show(); } public override void ViewDidLoad() { base.ViewDidLoad(); Initialize(); } public override void LoadView() { // Create the views. View = new UIView {BackgroundColor = ApplicationTheme.BackgroundColor}; _myMapView = new MapView(); _myMapView.TranslatesAutoresizingMaskIntoConstraints = false; _exportTilesButton = new UIBarButtonItem(); _exportTilesButton.Title = "Export tiles"; UIToolbar toolbar = new UIToolbar(); toolbar.TranslatesAutoresizingMaskIntoConstraints = false; toolbar.Items = new[] { new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), _exportTilesButton, new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace) }; _statusIndicator = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.WhiteLarge); _statusIndicator.TranslatesAutoresizingMaskIntoConstraints = false; _statusIndicator.HidesWhenStopped = true; _statusIndicator.BackgroundColor = UIColor.FromWhiteAlpha(0f, .8f); // Add the views. View.AddSubviews(_myMapView, toolbar, _statusIndicator); // Lay out the views. NSLayoutConstraint.ActivateConstraints(new[] { _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), _myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor), toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor), toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), _statusIndicator.TopAnchor.ConstraintEqualTo(View.TopAnchor), _statusIndicator.BottomAnchor.ConstraintEqualTo(View.BottomAnchor), _statusIndicator.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _statusIndicator.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor) }); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); // Subscribe to events. _myMapView.ViewpointChanged += MyMapView_ViewpointChanged; _exportTilesButton.Clicked += MyExportButton_Click; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Unsubscribe from events, per best practice. _myMapView.ViewpointChanged -= MyMapView_ViewpointChanged; _exportTilesButton.Clicked -= MyExportButton_Click; } } }
/*============================================================================ * Copyright (C) Microsoft Corporation, All rights reserved. *============================================================================ */ #region Using directives using System.Collections; using System; using System.Collections.Generic; using System.Globalization; using System.Management.Automation; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// Containing all necessary information originated from /// the parameters of <see cref="InvokeCimMethodCommand"/> /// </summary> internal class CimSetCimInstanceContext : XOperationContextBase { /// <summary> /// <para> /// Constructor /// </para> /// </summary> /// <param name="theNamespace"></param> /// <param name="theCollection"></param> /// <param name="theProxy"></param> internal CimSetCimInstanceContext(string theNamespace, IDictionary theProperty, CimSessionProxy theProxy, string theParameterSetName, bool passThru) { this.proxy = theProxy; this.property = theProperty; this.nameSpace = theNamespace; this.parameterSetName = theParameterSetName; this.passThru = passThru; } /// <summary> /// <para>property value</para> /// </summary> internal IDictionary Property { get { return this.property; } } private IDictionary property; /// <summary> /// <para>prameter set name</para> /// </summary> internal string ParameterSetName { get { return this.parameterSetName; } } private string parameterSetName; /// <summary> /// <para>PassThru value</para> /// </summary> internal bool PassThru { get { return this.passThru; } } private bool passThru; } /// <summary> /// <para> /// Implements operations of set-ciminstance cmdlet. /// </para> /// </summary> internal sealed class CimSetCimInstance : CimGetInstance { /// <summary> /// <para> /// Constructor /// </para> /// </summary> public CimSetCimInstance() : base() { } /// <summary> /// <para> /// Base on parametersetName to set ciminstances /// </para> /// </summary> /// <param name="cmdlet"><see cref="SetCimInstanceCommand"/> object</param> public void SetCimInstance(SetCimInstanceCommand cmdlet) { IEnumerable<string> computerNames = ConstValue.GetComputerNames( GetComputerName(cmdlet)); List<CimSessionProxy> proxys = new List<CimSessionProxy>(); switch (cmdlet.ParameterSetName) { case CimBaseCommand.CimInstanceComputerSet: foreach (string computerName in computerNames) { // create CimSessionProxySetCimInstance object internally proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet, cmdlet.PassThru)); } break; case CimBaseCommand.CimInstanceSessionSet: foreach (CimSession session in GetCimSession(cmdlet)) { // create CimSessionProxySetCimInstance object internally proxys.Add(CreateSessionProxy(session, cmdlet, cmdlet.PassThru)); } break; default: break; } switch (cmdlet.ParameterSetName) { case CimBaseCommand.CimInstanceComputerSet: case CimBaseCommand.CimInstanceSessionSet: string nameSpace = ConstValue.GetNamespace(GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace); string target = cmdlet.CimInstance.ToString(); foreach (CimSessionProxy proxy in proxys) { if (!cmdlet.ShouldProcess(target, action)) { return; } Exception exception = null; CimInstance intance = cmdlet.CimInstance; // For CimInstance parameter sets, Property is an optional parameter if (cmdlet.Property != null) { if (!SetProperty(cmdlet.Property, ref intance, ref exception)) { cmdlet.ThrowTerminatingError(exception, action); return; } } proxy.ModifyInstanceAsync(nameSpace, intance); } break; case CimBaseCommand.QueryComputerSet: case CimBaseCommand.QuerySessionSet: GetCimInstanceInternal(cmdlet); break; default: break; } } /// <summary> /// <para> /// Set <see cref="CimInstance"/> with properties specified in cmdlet /// </para> /// </summary> /// <param name="cimInstance"></param> public void SetCimInstance(CimInstance cimInstance, CimSetCimInstanceContext context, CmdletOperationBase cmdlet) { DebugHelper.WriteLog("CimSetCimInstance::SetCimInstance", 4); if (!cmdlet.ShouldProcess(cimInstance.ToString(), action)) { return; } Exception exception = null; if (!SetProperty(context.Property, ref cimInstance, ref exception)) { cmdlet.ThrowTerminatingError(exception, action); return; } CimSessionProxy proxy = CreateCimSessionProxy(context.Proxy, context.PassThru); proxy.ModifyInstanceAsync(cimInstance.CimSystemProperties.Namespace, cimInstance); } #region private members /// <summary> /// <para> /// Set the properties value to be modified to the given /// <see cref="CimInstanace"/> /// </para> /// </summary> /// <param name="properties"></param> /// <param name="cimInstance"></param> /// <param name="terminationMessage"></param> /// <returns></returns> private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, ref Exception exception) { DebugHelper.WriteLogEx(); if (properties.Count == 0) { // simply ignore if empty properties was provided return true; } IDictionaryEnumerator enumerator = properties.GetEnumerator(); while (enumerator.MoveNext()) { object value = GetBaseObject(enumerator.Value); string key = enumerator.Key.ToString(); DebugHelper.WriteLog("Input property name '{0}' with value '{1}'", 1, key, value); try { CimProperty property = cimInstance.CimInstanceProperties[key]; // modify existing property value if found if (property != null) { if ((property.Flags & CimFlags.ReadOnly) == CimFlags.ReadOnly) { // can not modify ReadOnly property exception = new CimException(String.Format(CultureInfo.CurrentUICulture, Strings.CouldNotModifyReadonlyProperty, key, cimInstance)); return false; } // allow modify the key property value as long as it is not readonly, // then the modified ciminstance is stand for a different CimInstance DebugHelper.WriteLog("Set property name '{0}' has old value '{1}'", 4, key, property.Value); property.Value = value; } else // For dynamic instance, it is valid to add a new property { CimProperty newProperty; if( value == null ) { newProperty = CimProperty.Create( key, value, CimType.String, CimFlags.Property); } else { CimType referenceType = CimType.Unknown; object referenceObject = GetReferenceOrReferenceArrayObject(value, ref referenceType); if (referenceObject != null) { newProperty = CimProperty.Create( key, referenceObject, referenceType, CimFlags.Property); } else { newProperty = CimProperty.Create( key, value, CimFlags.Property); } } try { cimInstance.CimInstanceProperties.Add(newProperty); } catch (CimException e) { if (e.NativeErrorCode == NativeErrorCode.Failed) { string errorMessage = String.Format(CultureInfo.CurrentUICulture, Strings.UnableToAddPropertyToInstance, newProperty.Name, cimInstance); exception = new CimException(errorMessage, e); } else { exception = e; } return false; } DebugHelper.WriteLog("Add non-key property name '{0}' with value '{1}'.", 3, key, value); } } catch (Exception e) { DebugHelper.WriteLog("Exception {0}", 4, e); exception = e; return false; } } return true; } #endregion #region const strings /// <summary> /// action /// </summary> private const string action = @"Set-CimInstance"; #endregion }//End Class }//End namespace
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; public partial class PolicyClient : Microsoft.Rest.ServiceClient<PolicyClient>, IPolicyClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IPolicyAssignmentsOperations. /// </summary> public virtual IPolicyAssignmentsOperations PolicyAssignments { get; private set; } /// <summary> /// Gets the IPolicyDefinitionsOperations. /// </summary> public virtual IPolicyDefinitionsOperations PolicyDefinitions { get; private set; } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected PolicyClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected PolicyClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected PolicyClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected PolicyClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PolicyClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PolicyClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PolicyClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PolicyClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.PolicyAssignments = new PolicyAssignmentsOperations(this); this.PolicyDefinitions = new PolicyDefinitionsOperations(this); this.BaseUri = new System.Uri("https://management.azure.com"); this.ApiVersion = "2016-04-01"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter()); DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter()); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } } }
// Copyright 2019 Esri. // // 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 Android.App; using Android.OS; using Android.Views; using Android.Widget; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Portal; using Esri.ArcGISRuntime.UI.Controls; using System; using System.Linq; namespace ArcGISRuntimeXamarin.Samples.MapReferenceScale { [Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Map reference scale", category: "Map", description: "Set the map's reference scale and which feature layers should honor the reference scale.", instructions: "Use the control at the top to set the map's reference scale (1:500,000 1:250,000 1:100,000 1:50,000). Use the menu checkboxes in the layer menu to set which feature layers should honor the reference scale.", tags: new[] { "map", "reference scale", "scene" })] public class MapReferenceScale : Activity { // Hold references to the UI controls. private MapView _myMapView; private TextView _currentScaleLabel; private TextView _referenceScaleSelectionLabel; private Button _layersButton; // List of reference scale options. private readonly double[] _referenceScales = { 50000, 100000, 250000, 500000 }; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Map reference scale"; CreateLayout(); Initialize(); } private async void Initialize() { // Create a portal and an item; the map will be loaded from portal item. ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri("https://runtime.maps.arcgis.com")); PortalItem mapItem = await PortalItem.CreateAsync(portal, "3953413f3bd34e53a42bf70f2937a408"); // Create the map from the item. Map webMap = new Map(mapItem); // Update the UI when the map navigates. _myMapView.ViewpointChanged += (o, e) => _currentScaleLabel.Text = $"Current map scale: 1:{_myMapView.MapScale:n0}"; // Display the map. _myMapView.Map = webMap; // Wait for the map to load. await webMap.LoadAsync(); // Enable the button now that the map is ready. _layersButton.Enabled = true; } private void ChooseScale_Clicked(object sender, EventArgs e) { try { Button scaleButton = (Button) sender; // Create menu for showing layer controls. PopupMenu sublayersMenu = new PopupMenu(this, scaleButton); sublayersMenu.MenuItemClick += ScaleSelection_Changed; // Create menu options. int index = 0; foreach (double scale in _referenceScales) { // Add the menu item. sublayersMenu.Menu.Add(0, index, index, $"1:{scale:n0}"); index++; } // Show menu in the view sublayersMenu.Show(); } catch (Exception ex) { new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show(); } } private void ScaleSelection_Changed(object sender, PopupMenu.MenuItemClickEventArgs e) { // Find the index of the selected scale. int selectionIndex = e.Item.Order; // Apply the selected scale. _myMapView.Map.ReferenceScale = _referenceScales[selectionIndex]; // Update the UI. _referenceScaleSelectionLabel.Text = $"1:{_referenceScales[selectionIndex]:n0}"; } private void ChooseLayers_Clicked(object sender, EventArgs e) { try { Button layersButton = (Button) sender; // Create menu for showing layer controls. PopupMenu sublayersMenu = new PopupMenu(this, layersButton); sublayersMenu.MenuItemClick += LayerScaleSelection_Changed; // Create menu options. int index = 0; foreach (FeatureLayer layer in _myMapView.Map.OperationalLayers.OfType<FeatureLayer>()) { // Add the menu item. sublayersMenu.Menu.Add(0, index, index, layer.Name); // Configure the menu item. sublayersMenu.Menu.GetItem(index).SetCheckable(true).SetChecked(layer.ScaleSymbols); index++; } // Show menu in the view sublayersMenu.Show(); } catch (Exception ex) { new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show(); } } private void LayerScaleSelection_Changed(object sender, PopupMenu.MenuItemClickEventArgs e) { // Get the checked item. int selectedLayerIndex = e.Item.Order; // Find the layer. FeatureLayer selectedLayer = _myMapView.Map.OperationalLayers.OfType<FeatureLayer>().ElementAt(selectedLayerIndex); // Set the symbol scale mode. selectedLayer.ScaleSymbols = !selectedLayer.ScaleSymbols; // Update the UI. e.Item.SetChecked(selectedLayer.ScaleSymbols); } private void CreateLayout() { // Create a new vertical layout for the app. var layout = new LinearLayout(this) {Orientation = Orientation.Vertical}; // Button for choosing the map's reference scale. Button chooseScaleButton = new Button(this); chooseScaleButton.Text = "Choose map reference scale"; chooseScaleButton.Click += ChooseScale_Clicked; layout.AddView(chooseScaleButton); // Label for showing current reference scale. _referenceScaleSelectionLabel = new TextView(this); _referenceScaleSelectionLabel.Text = "Choose a reference scale"; layout.AddView(_referenceScaleSelectionLabel); // Button for selecting which layers will have symbol scaling enabled. _layersButton = new Button(this); _layersButton.Text = "Manage scaling for layers"; _layersButton.Click += ChooseLayers_Clicked; layout.AddView(_layersButton); // Add a horizontal line separator. View separatorView = new View(this); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 1); separatorView.LayoutParameters = lp; layout.AddView(separatorView); // Add a label that shows the current map scale. _currentScaleLabel = new TextView(this); _currentScaleLabel.Text = "Current map scale: "; layout.AddView(_currentScaleLabel); // Add the map view to the layout. _myMapView = new MapView(this); layout.AddView(_myMapView); // Show the layout in the app. SetContentView(layout); } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using OpenTK.Audio.OpenAL; namespace OpenTK.Audio { /// <summary> /// Provides methods to instantiate, use and destroy an audio device for recording. /// Static methods are provided to list available devices known by the driver. /// </summary> public sealed class AudioCapture : IDisposable { #region Fields // This must stay private info so the end-user cannot call any Alc commands for the recording device. IntPtr Handle; // Alc.CaptureStop should be called prior to device shutdown, this keeps track of Alc.CaptureStart/Stop calls. bool _isrecording = false; ALFormat sample_format; int sample_frequency; #endregion #region Constructors static AudioCapture() { if (AudioDeviceEnumerator.IsOpenALSupported) // forces enumeration { } } /// <summary> /// Opens the default device for audio recording. /// Implicitly set parameters are: 22050Hz, 16Bit Mono, 4096 samples ringbuffer. /// </summary> public AudioCapture() : this(AudioCapture.DefaultDevice, 22050, ALFormat.Mono16, 4096) { } /// <summary>Opens a device for audio recording.</summary> /// <param name="deviceName">The device name.</param> /// <param name="frequency">The frequency that the data should be captured at.</param> /// <param name="sampleFormat">The requested capture buffer format.</param> /// <param name="bufferSize">The size of OpenAL's capture internal ring-buffer. This value expects number of samples, not bytes.</param> public AudioCapture(string deviceName, int frequency, ALFormat sampleFormat, int bufferSize) { if (!AudioDeviceEnumerator.IsOpenALSupported) throw new DllNotFoundException("soft_oal.dll"); if (frequency <= 0) throw new ArgumentOutOfRangeException("frequency"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); // Try to open specified device. If it fails, try to open default device. device_name = deviceName; Handle = Alc.CaptureOpenDevice(deviceName, frequency, sampleFormat, bufferSize); if (Handle == IntPtr.Zero) { Debug.WriteLine(ErrorMessage(deviceName, frequency, sampleFormat, bufferSize)); device_name = "IntPtr.Zero"; Handle = Alc.CaptureOpenDevice(null, frequency, sampleFormat, bufferSize); } if (Handle == IntPtr.Zero) { Debug.WriteLine(ErrorMessage("IntPtr.Zero", frequency, sampleFormat, bufferSize)); device_name = AudioDeviceEnumerator.DefaultRecordingDevice; Handle = Alc.CaptureOpenDevice(AudioDeviceEnumerator.DefaultRecordingDevice, frequency, sampleFormat, bufferSize); } if (Handle == IntPtr.Zero) { // Everything we tried failed. Capture may not be supported, bail out. Debug.WriteLine(ErrorMessage(AudioDeviceEnumerator.DefaultRecordingDevice, frequency, sampleFormat, bufferSize)); device_name = "None"; throw new AudioDeviceException("All attempts to open capture devices returned IntPtr.Zero. See debug log for verbose list."); } // handle is not null, check for some Alc Error CheckErrors(); SampleFormat = sampleFormat; SampleFrequency = frequency; } #endregion Constructor #region Public Members #region CurrentDevice private string device_name; /// <summary> /// The name of the device associated with this instance. /// </summary> public string CurrentDevice { get { return device_name; } } #endregion #region AvailableDevices /// <summary> /// Returns a list of strings containing all known recording devices. /// </summary> public static IList<string> AvailableDevices { get { return AudioDeviceEnumerator.AvailableRecordingDevices; } } #endregion #region DefaultDevice /// <summary> /// Returns the name of the device that will be used as recording default. /// </summary> public static string DefaultDevice { get { return AudioDeviceEnumerator.DefaultRecordingDevice; } } #endregion #region CheckErrors /// <summary> /// Checks for ALC error conditions. /// </summary> /// <exception cref="OutOfMemoryException">Raised when an out of memory error is detected.</exception> /// <exception cref="AudioValueException">Raised when an invalid value is detected.</exception> /// <exception cref="AudioDeviceException">Raised when an invalid device is detected.</exception> /// <exception cref="AudioContextException">Raised when an invalid context is detected.</exception> public void CheckErrors() { new AudioDeviceErrorChecker(Handle).Dispose(); } #endregion #region CurrentError /// <summary>Returns the ALC error code for this device.</summary> public AlcError CurrentError { get { return Alc.GetError(Handle); } } #endregion #region Start & Stop /// <summary> /// Start recording samples. /// The number of available samples can be obtained through the <see cref="AvailableSamples"/> property. /// The data can be queried with any <see cref="ReadSamples(IntPtr, int)"/> method. /// </summary> public void Start() { Alc.CaptureStart(Handle); _isrecording = true; } /// <summary>Stop recording samples. This will not clear previously recorded samples.</summary> public void Stop() { Alc.CaptureStop(Handle); _isrecording = false; } #endregion Start & Stop Capture #region AvailableSamples /// <summary>Returns the number of available samples for capture.</summary> public int AvailableSamples { get { // TODO: Investigate inconsistency between documentation and actual usage. // Doc claims the 3rd param is Number-of-Bytes, but it appears to be Number-of-Int32s int result; Alc.GetInteger(Handle, AlcGetInteger.CaptureSamples, 1, out result); return result; } } #endregion Available samples property #region ReadSamples /// <summary>Fills the specified buffer with samples from the internal capture ring-buffer. This method does not block: it is an error to specify a sampleCount larger than AvailableSamples.</summary> /// <param name="buffer">A pointer to a previously initialized and pinned array.</param> /// <param name="sampleCount">The number of samples to be written to the buffer.</param> public void ReadSamples(IntPtr buffer, int sampleCount) { Alc.CaptureSamples(Handle, buffer, sampleCount); } /// <summary>Fills the specified buffer with samples from the internal capture ring-buffer. This method does not block: it is an error to specify a sampleCount larger than AvailableSamples.</summary> /// <param name="buffer">The buffer to fill.</param> /// <param name="sampleCount">The number of samples to be written to the buffer.</param> /// <exception cref="System.ArgumentNullException">Raised when buffer is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Raised when sampleCount is larger than the buffer.</exception> public void ReadSamples<TBuffer>(TBuffer[] buffer, int sampleCount) where TBuffer : struct { if (buffer == null) throw new ArgumentNullException("buffer"); int buffer_size = BlittableValueType<TBuffer>.Stride * buffer.Length; // This is more of a heuristic than a 100% valid check. However, it will work // correctly for 99.9% of all use cases. // This should never produce a false positive, but a false negative might // be produced with compressed sample formats (which are very rare). // Still, this is better than no check at all. if (sampleCount * GetSampleSize(SampleFormat) > buffer_size) throw new ArgumentOutOfRangeException("sampleCount"); GCHandle buffer_ptr = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { ReadSamples(buffer_ptr.AddrOfPinnedObject(), sampleCount); } finally { buffer_ptr.Free(); } } #endregion #region SampleFormat & SampleFrequency /// <summary> /// Gets the OpenTK.Audio.ALFormat for this instance. /// </summary> public ALFormat SampleFormat { get { return sample_format; } private set { sample_format = value; } } /// <summary> /// Gets the sampling rate for this instance. /// </summary> public int SampleFrequency { get { return sample_frequency; } private set { sample_frequency = value; } } #endregion #region IsRunning /// <summary> /// Gets a value indicating whether this instance is currently capturing samples. /// </summary> public bool IsRunning { get { return _isrecording; } } #endregion #endregion #region Private Members // Retrieves the sample size in bytes for various ALFormats. // Compressed formats always return 1. static int GetSampleSize(ALFormat format) { switch (format) { case ALFormat.Mono8: return 1; case ALFormat.Mono16: return 2; case ALFormat.Stereo8: return 2; case ALFormat.Stereo16: return 4; case ALFormat.MonoFloat32Ext: return 4; case ALFormat.MonoDoubleExt: return 8; case ALFormat.StereoFloat32Ext: return 8; case ALFormat.StereoDoubleExt: return 16; case ALFormat.MultiQuad8Ext: return 4; case ALFormat.MultiQuad16Ext: return 8; case ALFormat.MultiQuad32Ext: return 16; case ALFormat.Multi51Chn8Ext: return 6; case ALFormat.Multi51Chn16Ext: return 12; case ALFormat.Multi51Chn32Ext: return 24; case ALFormat.Multi61Chn8Ext: return 7; case ALFormat.Multi71Chn16Ext: return 14; case ALFormat.Multi71Chn32Ext: return 28; case ALFormat.MultiRear8Ext: return 1; case ALFormat.MultiRear16Ext: return 2; case ALFormat.MultiRear32Ext: return 4; default: return 1; // Unknown sample size. } } // Converts an error code to an error string with additional information. string ErrorMessage(string devicename, int frequency, ALFormat bufferformat, int buffersize) { string alcerrmsg; AlcError alcerrcode = CurrentError; switch (alcerrcode) { case AlcError.OutOfMemory: alcerrmsg = alcerrcode.ToString() + ": The specified device is invalid, or can not capture audio."; break; case AlcError.InvalidValue: alcerrmsg = alcerrcode.ToString() + ": One of the parameters has an invalid value."; break; default: alcerrmsg = alcerrcode.ToString(); break; } return "The handle returned by Alc.CaptureOpenDevice is null." + "\nAlc Error: " + alcerrmsg + "\nDevice Name: " + devicename + "\nCapture frequency: " + frequency + "\nBuffer format: " + bufferformat + "\nBuffer Size: " + buffersize; } #endregion #region IDisposable Members /// <summary> /// Finalizes this instance. /// </summary> ~AudioCapture() { Dispose(); } private bool IsDisposed; /// <summary>Closes the device and disposes the instance.</summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool manual) { if (!this.IsDisposed) { if (this.Handle != IntPtr.Zero) { if (this._isrecording) this.Stop(); Alc.CaptureCloseDevice(this.Handle); } this.IsDisposed = true; } } #endregion Destructor } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Finland.Hackathon.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// 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.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Primitives; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNetCore.Authentication.Test.OpenIdConnect { public class OpenIdConnectChallengeTests { private static readonly string ChallengeEndpoint = TestServerBuilder.TestHost + TestServerBuilder.Challenge; [Fact] public async Task ChallengeRedirectIsIssuedCorrectly() { var settings = new TestSettings( opt => { opt.Authority = TestServerBuilder.DefaultAuthority; opt.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet; opt.ClientId = "Test Id"; }); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); Assert.NotNull(res.Headers.Location); settings.ValidateChallengeRedirect( res.Headers.Location, OpenIdConnectParameterNames.ClientId, OpenIdConnectParameterNames.ResponseType, OpenIdConnectParameterNames.ResponseMode, OpenIdConnectParameterNames.Scope, OpenIdConnectParameterNames.RedirectUri, OpenIdConnectParameterNames.SkuTelemetry, OpenIdConnectParameterNames.VersionTelemetry); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ChallengeIncludesPkceIfRequested(bool include) { var settings = new TestSettings( opt => { opt.Authority = TestServerBuilder.DefaultAuthority; opt.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet; opt.ResponseType = OpenIdConnectResponseType.Code; opt.ClientId = "Test Id"; opt.UsePkce = include; }); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); Assert.NotNull(res.Headers.Location); if (include) { Assert.Contains("code_challenge=", res.Headers.Location.Query); Assert.Contains("code_challenge_method=S256", res.Headers.Location.Query); } else { Assert.DoesNotContain("code_challenge=", res.Headers.Location.Query); Assert.DoesNotContain("code_challenge_method=", res.Headers.Location.Query); } } [Theory] [InlineData(OpenIdConnectResponseType.Token)] [InlineData(OpenIdConnectResponseType.IdToken)] [InlineData(OpenIdConnectResponseType.CodeIdToken)] public async Task ChallengeDoesNotIncludePkceForOtherResponseTypes(string responseType) { var settings = new TestSettings( opt => { opt.Authority = TestServerBuilder.DefaultAuthority; opt.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet; opt.ResponseType = responseType; opt.ClientId = "Test Id"; opt.UsePkce = true; }); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); Assert.NotNull(res.Headers.Location); Assert.DoesNotContain("code_challenge=", res.Headers.Location.Query); Assert.DoesNotContain("code_challenge_method=", res.Headers.Location.Query); } [Fact] public async Task AuthorizationRequestDoesNotIncludeTelemetryParametersWhenDisabled() { var settings = new TestSettings(opt => { opt.ClientId = "Test Id"; opt.Authority = TestServerBuilder.DefaultAuthority; opt.DisableTelemetry = true; }); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); Assert.DoesNotContain(OpenIdConnectParameterNames.SkuTelemetry, res.Headers.Location.Query); Assert.DoesNotContain(OpenIdConnectParameterNames.VersionTelemetry, res.Headers.Location.Query); } /* Example of a form post <body> <form name=\ "form\" method=\ "post\" action=\ "https://login.microsoftonline.com/common/oauth2/authorize\"> <input type=\ "hidden\" name=\ "client_id\" value=\ "51e38103-238f-410f-a5d5-61991b203e50\" /> <input type=\ "hidden\" name=\ "redirect_uri\" value=\ "https://example.com/signin-oidc\" /> <input type=\ "hidden\" name=\ "response_type\" value=\ "id_token\" /> <input type=\ "hidden\" name=\ "scope\" value=\ "openid profile\" /> <input type=\ "hidden\" name=\ "response_mode\" value=\ "form_post\" /> <input type=\ "hidden\" name=\ "nonce\" value=\ "636072461997914230.NTAwOGE1MjQtM2VhYS00ZDU0LWFkYzYtNmZiYWE2MDRkODg3OTlkMDFmOWUtOTMzNC00ZmI2LTg1Y2YtOWM4OTlhNjY0Yjli\" /> <input type=\ "hidden\" name=\ "state\" value=\ "CfDJ8Jh1NKaF0T5AnK4qsqzzIs89srKe4iEaBWd29MNph4Ki887QKgkD24wjhZ0ciH-ar6A_jUmRI2O5haXN2-YXbC0ZRuRAvNsx5LqbPTdh4MJBIwXWkG_rM0T0tI3h5Y2pDttWSaku6a_nzFLUYBrKfsE7sDLVoTDrzzOcHrRQhdztqOOeNUuu2wQXaKwlOtNI21ShtN9EVxvSGFOxUUOwVih4nFdF40fBcbsuPpcpCPkLARQaFRJSYsNKiP7pcFMnRwzZhnISHlyGKkzwJ1DIx7nsmdiQFBGljimw5GnYAs-5ru9L3w8NnPjkl96OyQ8MJOcayMDmOY26avs2sYP_Zw0\" /> <noscript>Click here to finish the process: <input type=\"submit\" /></noscript> </form> <script> document.form.submit(); </script> </body> */ [Fact] public async Task ChallengeFormPostIssuedCorrectly() { var settings = new TestSettings( opt => { opt.Authority = TestServerBuilder.DefaultAuthority; opt.AuthenticationMethod = OpenIdConnectRedirectBehavior.FormPost; opt.ClientId = "Test Id"; }); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.OK, res.StatusCode); Assert.Equal("text/html", transaction.Response.Content.Headers.ContentType.MediaType); var body = await res.Content.ReadAsStringAsync(); settings.ValidateChallengeFormPost( body, OpenIdConnectParameterNames.ClientId, OpenIdConnectParameterNames.ResponseType, OpenIdConnectParameterNames.ResponseMode, OpenIdConnectParameterNames.Scope, OpenIdConnectParameterNames.RedirectUri); } [Theory] [InlineData("sample_user_state")] [InlineData(null)] public async Task ChallengeCanSetUserStateThroughProperties(string userState) { var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("OIDCTest")); var settings = new TestSettings(o => { o.ClientId = "Test Id"; o.Authority = TestServerBuilder.DefaultAuthority; o.StateDataFormat = stateFormat; }); var properties = new AuthenticationProperties(); properties.Items.Add(OpenIdConnectDefaults.UserstatePropertiesKey, userState); var server = settings.CreateTestServer(properties); var transaction = await server.SendAsync(TestServerBuilder.TestHost + TestServerBuilder.ChallengeWithProperties); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); Assert.NotNull(res.Headers.Location); var values = settings.ValidateChallengeRedirect(res.Headers.Location); var actualState = values[OpenIdConnectParameterNames.State]; var actualProperties = stateFormat.Unprotect(actualState); Assert.Equal(userState ?? string.Empty, actualProperties.Items[OpenIdConnectDefaults.UserstatePropertiesKey]); } [Theory] [InlineData("sample_user_state")] [InlineData(null)] public async Task OnRedirectToIdentityProviderEventCanSetState(string userState) { var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("OIDCTest")); var settings = new TestSettings(opt => { opt.StateDataFormat = stateFormat; opt.ClientId = "Test Id"; opt.Authority = TestServerBuilder.DefaultAuthority; opt.Events = new OpenIdConnectEvents() { OnRedirectToIdentityProvider = context => { context.ProtocolMessage.State = userState; return Task.FromResult(0); } }; }); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); Assert.NotNull(res.Headers.Location); var values = settings.ValidateChallengeRedirect(res.Headers.Location); var actualState = values[OpenIdConnectParameterNames.State]; var actualProperties = stateFormat.Unprotect(actualState); if (userState != null) { Assert.Equal(userState, actualProperties.Items[OpenIdConnectDefaults.UserstatePropertiesKey]); } else { Assert.False(actualProperties.Items.ContainsKey(OpenIdConnectDefaults.UserstatePropertiesKey)); } } [Fact] public async Task OnRedirectToIdentityProviderEventIsHit() { var eventIsHit = false; var settings = new TestSettings( opts => { opts.ClientId = "Test Id"; opts.Authority = TestServerBuilder.DefaultAuthority; opts.Events = new OpenIdConnectEvents() { OnRedirectToIdentityProvider = context => { eventIsHit = true; return Task.FromResult(0); } }; } ); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); Assert.True(eventIsHit); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); Assert.NotNull(res.Headers.Location); settings.ValidateChallengeRedirect( res.Headers.Location, OpenIdConnectParameterNames.ClientId, OpenIdConnectParameterNames.ResponseType, OpenIdConnectParameterNames.ResponseMode, OpenIdConnectParameterNames.Scope, OpenIdConnectParameterNames.RedirectUri); } [Fact] public async Task OnRedirectToIdentityProviderEventCanReplaceValues() { var newClientId = Guid.NewGuid().ToString(); var settings = new TestSettings( opts => { opts.ClientId = "Test Id"; opts.Authority = TestServerBuilder.DefaultAuthority; opts.Events = new OpenIdConnectEvents() { OnRedirectToIdentityProvider = context => { context.ProtocolMessage.ClientId = newClientId; return Task.FromResult(0); } }; } ); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); Assert.NotNull(res.Headers.Location); settings.ValidateChallengeRedirect( res.Headers.Location, OpenIdConnectParameterNames.ResponseType, OpenIdConnectParameterNames.ResponseMode, OpenIdConnectParameterNames.Scope, OpenIdConnectParameterNames.RedirectUri); var actual = res.Headers.Location.Query.Trim('?').Split('&').Single(seg => seg.StartsWith($"{OpenIdConnectParameterNames.ClientId}=", StringComparison.Ordinal)); Assert.Equal($"{OpenIdConnectParameterNames.ClientId}={newClientId}", actual); } [Fact] public async Task OnRedirectToIdentityProviderEventCanReplaceMessage() { var newMessage = new MockOpenIdConnectMessage { IssuerAddress = "http://example.com/", TestAuthorizeEndpoint = $"http://example.com/{Guid.NewGuid()}/oauth2/signin" }; var settings = new TestSettings( opts => { opts.ClientId = "Test Id"; opts.Authority = TestServerBuilder.DefaultAuthority; opts.Events = new OpenIdConnectEvents() { OnRedirectToIdentityProvider = context => { context.ProtocolMessage = newMessage; return Task.FromResult(0); } }; } ); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); Assert.NotNull(res.Headers.Location); // The CreateAuthenticationRequestUrl method is overridden MockOpenIdConnectMessage where // query string is not generated and the authorization endpoint is replaced. Assert.Equal(newMessage.TestAuthorizeEndpoint, res.Headers.Location.AbsoluteUri); } [Fact] public async Task OnRedirectToIdentityProviderEventHandlesResponse() { var settings = new TestSettings( opts => { opts.ClientId = "Test Id"; opts.Authority = TestServerBuilder.DefaultAuthority; opts.Events = new OpenIdConnectEvents() { OnRedirectToIdentityProvider = context => { context.Response.StatusCode = 410; context.Response.Headers.Add("tea", "Oolong"); context.HandleResponse(); return Task.FromResult(0); } }; } ); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.Gone, res.StatusCode); Assert.Equal("Oolong", res.Headers.GetValues("tea").Single()); Assert.Null(res.Headers.Location); } // This test can be further refined. When one auth handler skips, the authentication responsibility // will be flowed to the next one. A dummy auth handler can be added to ensure the correct logic. [Fact] public async Task OnRedirectToIdentityProviderEventHandleResponse() { var settings = new TestSettings( opts => { opts.ClientId = "Test Id"; opts.Authority = TestServerBuilder.DefaultAuthority; opts.Events = new OpenIdConnectEvents() { OnRedirectToIdentityProvider = context => { context.HandleResponse(); return Task.FromResult(0); } }; } ); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.OK, res.StatusCode); Assert.Null(res.Headers.Location); } [Theory] [InlineData(OpenIdConnectRedirectBehavior.RedirectGet)] [InlineData(OpenIdConnectRedirectBehavior.FormPost)] public async Task ChallengeSetsNonceAndStateCookies(OpenIdConnectRedirectBehavior method) { var settings = new TestSettings(o => { o.AuthenticationMethod = method; o.ClientId = "Test Id"; o.Authority = TestServerBuilder.DefaultAuthority; }); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); Assert.Contains("samesite=none", transaction.SetCookie.First()); var challengeCookies = SetCookieHeaderValue.ParseList(transaction.SetCookie); var nonceCookie = challengeCookies.Where(cookie => cookie.Name.StartsWith(OpenIdConnectDefaults.CookieNoncePrefix, StringComparison.Ordinal)).Single(); Assert.True(nonceCookie.Expires.HasValue); Assert.True(nonceCookie.Expires > DateTime.UtcNow); Assert.True(nonceCookie.HttpOnly); Assert.Equal("/signin-oidc", nonceCookie.Path); Assert.Equal("N", nonceCookie.Value); Assert.Equal(Net.Http.Headers.SameSiteMode.None, nonceCookie.SameSite); var correlationCookie = challengeCookies.Where(cookie => cookie.Name.StartsWith(".AspNetCore.Correlation.", StringComparison.Ordinal)).Single(); Assert.True(correlationCookie.Expires.HasValue); Assert.True(nonceCookie.Expires > DateTime.UtcNow); Assert.True(correlationCookie.HttpOnly); Assert.Equal("/signin-oidc", correlationCookie.Path); Assert.False(StringSegment.IsNullOrEmpty(correlationCookie.Value)); Assert.Equal(Net.Http.Headers.SameSiteMode.None, correlationCookie.SameSite); Assert.Equal(2, challengeCookies.Count); } [Fact] public async Task Challenge_WithEmptyConfig_Fails() { var settings = new TestSettings( opt => { opt.ClientId = "Test Id"; opt.Configuration = new OpenIdConnectConfiguration(); }); var server = settings.CreateTestServer(); var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => server.SendAsync(ChallengeEndpoint)); Assert.Equal("Cannot redirect to the authorization endpoint, the configuration may be missing or invalid.", exception.Message); } [Fact] public async Task Challenge_WithDefaultMaxAge_HasExpectedMaxAgeParam() { var settings = new TestSettings( opt => { opt.ClientId = "Test Id"; opt.Authority = TestServerBuilder.DefaultAuthority; }); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); settings.ValidateChallengeRedirect( res.Headers.Location, OpenIdConnectParameterNames.MaxAge); } [Fact] public async Task Challenge_WithSpecificMaxAge_HasExpectedMaxAgeParam() { var settings = new TestSettings( opt => { opt.ClientId = "Test Id"; opt.Authority = TestServerBuilder.DefaultAuthority; opt.MaxAge = TimeSpan.FromMinutes(20); }); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); settings.ValidateChallengeRedirect( res.Headers.Location, OpenIdConnectParameterNames.MaxAge); } [Fact] public async Task Challenge_HasExpectedPromptParam() { var settings = new TestSettings(opt => { opt.ClientId = "Test Id"; opt.Authority = TestServerBuilder.DefaultAuthority; opt.Prompt = "consent"; }); var server = settings.CreateTestServer(); var transaction = await server.SendAsync(ChallengeEndpoint); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); settings.ValidateChallengeRedirect(res.Headers.Location, OpenIdConnectParameterNames.Prompt); Assert.Contains("prompt=consent", res.Headers.Location.Query); } [Fact] public async Task Challenge_HasOverwrittenPromptParam() { var settings = new TestSettings(opt => { opt.ClientId = "Test Id"; opt.Authority = TestServerBuilder.DefaultAuthority; opt.Prompt = "consent"; }); var properties = new OpenIdConnectChallengeProperties() { Prompt = "login", }; var server = settings.CreateTestServer(properties); var transaction = await server.SendAsync(TestServerBuilder.TestHost + TestServerBuilder.ChallengeWithProperties); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); settings.ValidateChallengeRedirect(res.Headers.Location); Assert.Contains("prompt=login", res.Headers.Location.Query); } [Fact] public async Task Challenge_HasOverwrittenPromptParamFromBaseAuthenticationProperties() { var settings = new TestSettings(opt => { opt.ClientId = "Test Id"; opt.Authority = TestServerBuilder.DefaultAuthority; opt.Prompt = "consent"; }); var properties = new AuthenticationProperties(); properties.SetParameter(OpenIdConnectChallengeProperties.PromptKey, "login"); var server = settings.CreateTestServer(properties); var transaction = await server.SendAsync(TestServerBuilder.TestHost + TestServerBuilder.ChallengeWithProperties); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); settings.ValidateChallengeRedirect(res.Headers.Location); Assert.Contains("prompt=login", res.Headers.Location.Query); } [Fact] public async Task Challenge_HasOverwrittenScopeParam() { var settings = new TestSettings(opt => { opt.ClientId = "Test Id"; opt.Authority = TestServerBuilder.DefaultAuthority; opt.Scope.Clear(); opt.Scope.Add("foo"); opt.Scope.Add("bar"); }); var properties = new OpenIdConnectChallengeProperties(); properties.SetScope("baz", "qux"); var server = settings.CreateTestServer(properties); var transaction = await server.SendAsync(TestServerBuilder.TestHost + TestServerBuilder.ChallengeWithProperties); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); settings.ValidateChallengeRedirect(res.Headers.Location); Assert.Contains("scope=baz%20qux", res.Headers.Location.Query); } [Fact] public async Task Challenge_HasOverwrittenScopeParamFromBaseAuthenticationProperties() { var settings = new TestSettings(opt => { opt.ClientId = "Test Id"; opt.Authority = TestServerBuilder.DefaultAuthority; opt.Scope.Clear(); opt.Scope.Add("foo"); opt.Scope.Add("bar"); }); var properties = new AuthenticationProperties(); properties.SetParameter(OpenIdConnectChallengeProperties.ScopeKey, new string[] { "baz", "qux" }); var server = settings.CreateTestServer(properties); var transaction = await server.SendAsync(TestServerBuilder.TestHost + TestServerBuilder.ChallengeWithProperties); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); settings.ValidateChallengeRedirect(res.Headers.Location); Assert.Contains("scope=baz%20qux", res.Headers.Location.Query); } [Fact] public async Task Challenge_HasOverwrittenMaxAgeParam() { var settings = new TestSettings(opt => { opt.ClientId = "Test Id"; opt.Authority = TestServerBuilder.DefaultAuthority; opt.MaxAge = TimeSpan.FromSeconds(500); }); var properties = new OpenIdConnectChallengeProperties() { MaxAge = TimeSpan.FromSeconds(1234), }; var server = settings.CreateTestServer(properties); var transaction = await server.SendAsync(TestServerBuilder.TestHost + TestServerBuilder.ChallengeWithProperties); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); settings.ValidateChallengeRedirect(res.Headers.Location); Assert.Contains("max_age=1234", res.Headers.Location.Query); } [Fact] public async Task Challenge_HasOverwrittenMaxAgeParaFromBaseAuthenticationPropertiesm() { var settings = new TestSettings(opt => { opt.ClientId = "Test Id"; opt.Authority = TestServerBuilder.DefaultAuthority; opt.MaxAge = TimeSpan.FromSeconds(500); }); var properties = new AuthenticationProperties(); properties.SetParameter(OpenIdConnectChallengeProperties.MaxAgeKey, TimeSpan.FromSeconds(1234)); var server = settings.CreateTestServer(properties); var transaction = await server.SendAsync(TestServerBuilder.TestHost + TestServerBuilder.ChallengeWithProperties); var res = transaction.Response; Assert.Equal(HttpStatusCode.Redirect, res.StatusCode); settings.ValidateChallengeRedirect(res.Headers.Location); Assert.Contains("max_age=1234", res.Headers.Location.Query); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace ParquetSharp.IO { using System; using System.Collections.Generic; using System.Linq; using ParquetSharp.Column; using ParquetSharp.Column.Impl; using ParquetSharp.External; using ParquetSharp.IO.Api; using ParquetSharp.Schema; /** * used to read reassembled records * @author Julien Le Dem * * @param <T> the type of the materialized record */ class RecordReaderImplementation<T> : RecordReader<T> { private static readonly Log LOG = Log.getLog(typeof(RecordReaderImplementation<>)); public class Case : IComparable<Case> { private int id; private readonly int startLevel; private readonly int depth; private readonly int nextLevel; private readonly bool goingUp; private readonly bool goingDown; private readonly int nextState; private readonly bool defined; public Case(int startLevel, int depth, int nextLevel, int nextState, bool defined) { this.startLevel = startLevel; this.depth = depth; this.nextLevel = nextLevel; this.nextState = nextState; this.defined = defined; // means going up the tree (towards the leaves) of the record // true if we need to open up groups in this case goingUp = startLevel <= depth; // means going down the tree (towards the root) of the record // true if we need to close groups in this case goingDown = depth + 1 > nextLevel; } public void setID(int id) { this.id = id; } // this implementation is buggy but the simpler one bellow has duplicates. // it still works but generates more code than necessary // a middle ground is necessary // public override int GetHashCode() { // int hashCode = 0; // if (goingUp) { // hashCode += 1 * (1 + startLevel) + 2 * (1 + depth); // } // if (goingDown) { // hashCode += 3 * (1 + depth) + 5 * (1 + nextLevel); // } // return hashCode; // } public override int GetHashCode() { int hashCode = 17; hashCode += 31 * startLevel; hashCode += 31 * depth; hashCode += 31 * nextLevel; hashCode += 31 * nextState; hashCode += 31 * (defined ? 0 : 1); return hashCode; } public override bool Equals(object obj) { if (obj is Case) { return Equals((Case)obj); } return false; } // see comment for hashCode above // public bool Equals(Case other) { // if (goingUp && !other.goingUp || !goingUp && other.goingUp) { // return false; // } // if (goingUp && other.goingUp && (startLevel != other.startLevel || depth != other.depth)) { // return false; // } // if (goingDown && !other.goingDown || !goingDown && other.goingDown) { // return false; // } // if (goingDown && other.goingDown && (depth != other.depth || nextLevel != other.nextLevel)) { // return false; // } // return true; // } public bool Equals(Case other) { return startLevel == other.startLevel && depth == other.depth && nextLevel == other.nextLevel && nextState == other.nextState && ((defined && other.defined) || (!defined && !other.defined)); } public int getID() { return id; } public int getStartLevel() { return startLevel; } public int getDepth() { return depth; } public int getNextLevel() { return nextLevel; } public int getNextState() { return nextState; } public bool isGoingUp() { return goingUp; } public bool isGoingDown() { return goingDown; } public bool isDefined() { return defined; } public override string ToString() { return "Case " + startLevel + " -> " + depth + " -> " + nextLevel + "; goto sate_" + getNextState(); } public int CompareTo(Case other) { return this.id - other.id; } } public class State { public readonly int id; public readonly PrimitiveColumnIO primitiveColumnIO; public readonly int maxDefinitionLevel; public readonly int maxRepetitionLevel; public readonly PrimitiveType.PrimitiveTypeName primitive; public readonly ColumnReader column; public readonly string[] fieldPath; // indexed by currentLevel public readonly int[] indexFieldPath; // indexed by currentLevel public readonly GroupConverter[] groupConverterPath; public readonly PrimitiveConverter primitiveConverter; public readonly string primitiveField; public readonly int primitiveFieldIndex; public readonly int[] nextLevel; //indexed by next r internal int[] definitionLevelToDepth; // indexed by current d internal State[] nextState; // indexed by next r internal Case[][][] caseLookup; internal List<Case> definedCases; internal List<Case> undefinedCases; internal State(int id, PrimitiveColumnIO primitiveColumnIO, ColumnReader column, int[] nextLevel, GroupConverter[] groupConverterPath, PrimitiveConverter primitiveConverter) { this.id = id; this.primitiveColumnIO = primitiveColumnIO; this.maxDefinitionLevel = primitiveColumnIO.getDefinitionLevel(); this.maxRepetitionLevel = primitiveColumnIO.getRepetitionLevel(); this.column = column; this.nextLevel = nextLevel; this.groupConverterPath = groupConverterPath; this.primitiveConverter = primitiveConverter; this.primitive = primitiveColumnIO.getType().asPrimitiveType().getPrimitiveTypeName(); this.fieldPath = primitiveColumnIO.getFieldPath(); this.primitiveField = fieldPath[fieldPath.Length - 1]; this.indexFieldPath = primitiveColumnIO.getIndexFieldPath(); this.primitiveFieldIndex = indexFieldPath[indexFieldPath.Length - 1]; } public int getDepth(int definitionLevel) { return definitionLevelToDepth[definitionLevel]; } public List<Case> getDefinedCases() { return definedCases; } public List<Case> getUndefinedCases() { return undefinedCases; } public Case getCase(int currentLevel, int d, int nextR) { return caseLookup[currentLevel][d][nextR]; } public State getNextState(int nextR) { return nextState[nextR]; } } private readonly GroupConverter recordRootConverter; private readonly RecordMaterializer<T> recordMaterializer; private State[] states; private ColumnReader[] columnReaders; private bool _shouldSkipCurrentRecord = false; /** * @param root the root of the schema * @param recordMaterializer responsible of materializing the records * @param validating whether we should validate against the schema * @param columnStore where to read the column data from */ public RecordReaderImplementation(MessageColumnIO root, RecordMaterializer<T> recordMaterializer, bool validating, ColumnReadStoreImpl columnStore) { this.recordMaterializer = recordMaterializer; this.recordRootConverter = recordMaterializer.getRootConverter(); // TODO: validator(wrap(recordMaterializer), validating, root.getType()); PrimitiveColumnIO[] leaves = root.getLeaves().ToArray(); columnReaders = new ColumnReader[leaves.Length]; int[][] nextColumnIdxForRepLevel = new int[leaves.Length][]; int[][] levelToClose = new int[leaves.Length][]; GroupConverter[][] groupConverterPaths = new GroupConverter[leaves.Length][]; PrimitiveConverter[] leafConverters = new PrimitiveConverter[leaves.Length]; int[] firstIndexForLevel = new int[256]; // "256 levels of nesting ought to be enough for anybody" // build the automaton for (int i = 0; i < leaves.Length; i++) { PrimitiveColumnIO leafColumnIO = leaves[i]; //generate converters along the path from root to leaf int[] indexFieldPath = leafColumnIO.getIndexFieldPath(); groupConverterPaths[i] = new GroupConverter[indexFieldPath.Length - 1]; GroupConverter current = this.recordRootConverter; for (int j = 0; j < indexFieldPath.Length - 1; j++) { current = current.getConverter(indexFieldPath[j]).asGroupConverter(); groupConverterPaths[i][j] = current; } leafConverters[i] = current.getConverter(indexFieldPath[indexFieldPath.Length - 1]).asPrimitiveConverter(); columnReaders[i] = columnStore.getColumnReader(leafColumnIO.getColumnDescriptor()); int maxRepetitionLevel = leafColumnIO.getRepetitionLevel(); nextColumnIdxForRepLevel[i] = new int[maxRepetitionLevel + 1]; levelToClose[i] = new int[maxRepetitionLevel + 1]; //next level for (int nextRepLevel = 0; nextRepLevel <= maxRepetitionLevel; ++nextRepLevel) { // remember which is the first for this level if (leafColumnIO.isFirst(nextRepLevel)) { firstIndexForLevel[nextRepLevel] = i; } int nextColIdx; //TODO: when we use nextColumnIdxForRepLevel, should we provide current rep level or the rep level for next item // figure out automaton transition if (nextRepLevel == 0) { // 0 always means jump to the next (the last one being a special case) nextColIdx = i + 1; } else if (leafColumnIO.isLast(nextRepLevel)) { // when we are at the last of the next repetition level we jump back to the first nextColIdx = firstIndexForLevel[nextRepLevel]; } else { // otherwise we just go back to the next. nextColIdx = i + 1; } // figure out which level down the tree we need to go back if (nextColIdx == leaves.Length) { // reached the end of the record => close all levels levelToClose[i][nextRepLevel] = 0; } else if (leafColumnIO.isLast(nextRepLevel)) { // reached the end of this level => close the repetition level ColumnIO parent = leafColumnIO.getParent(nextRepLevel); levelToClose[i][nextRepLevel] = parent.getFieldPath().Length - 1; } else { // otherwise close until the next common parent levelToClose[i][nextRepLevel] = getCommonParentLevel( leafColumnIO.getFieldPath(), leaves[nextColIdx].getFieldPath()); } // sanity check: that would be a bug if (levelToClose[i][nextRepLevel] > leaves[i].getFieldPath().Length - 1) { throw new ParquetEncodingException(Arrays.toString(leaves[i].getFieldPath()) + " -(" + nextRepLevel + ")-> " + levelToClose[i][nextRepLevel]); } nextColumnIdxForRepLevel[i][nextRepLevel] = nextColIdx; } } states = new State[leaves.Length]; for (int i = 0; i < leaves.Length; i++) { states[i] = new State(i, leaves[i], columnReaders[i], levelToClose[i], groupConverterPaths[i], leafConverters[i]); int[] definitionLevelToDepth = new int[states[i].primitiveColumnIO.getDefinitionLevel() + 1]; // for each possible definition level, determine the depth at which to create groups ColumnIO[] path = states[i].primitiveColumnIO.getPath(); int depth = 0; for (int d = 0; d < definitionLevelToDepth.Length; ++d) { while (depth < (states[i].fieldPath.Length - 1) && d >= path[depth + 1].getDefinitionLevel() ) { ++depth; } definitionLevelToDepth[d] = depth - 1; } states[i].definitionLevelToDepth = definitionLevelToDepth; } for (int i = 0; i < leaves.Length; i++) { State state = states[i]; int[] nextStateIds = nextColumnIdxForRepLevel[i]; state.nextState = new State[nextStateIds.Length]; for (int j = 0; j < nextStateIds.Length; j++) { state.nextState[j] = nextStateIds[j] == states.Length ? null : states[nextStateIds[j]]; } } for (int i = 0; i < states.Length; i++) { State state = states[i]; Dictionary<Case, Case> definedCases = new Dictionary<Case, Case>(); Dictionary<Case, Case> undefinedCases = new Dictionary<Case, Case>(); Case[][][] caseLookup = new Case[state.fieldPath.Length][][]; for (int currentLevel = 0; currentLevel < state.fieldPath.Length; ++currentLevel) { caseLookup[currentLevel] = new Case[state.maxDefinitionLevel + 1][]; for (int d = 0; d <= state.maxDefinitionLevel; ++d) { caseLookup[currentLevel][d] = new Case[state.maxRepetitionLevel + 1]; for (int nextR = 0; nextR <= state.maxRepetitionLevel; ++nextR) { int caseStartLevel = currentLevel; int caseDepth = Math.Max(state.getDepth(d), caseStartLevel - 1); int caseNextLevel = Math.Min(state.nextLevel[nextR], caseDepth + 1); Case currentCase = new Case(caseStartLevel, caseDepth, caseNextLevel, getNextReader(state.id, nextR), d == state.maxDefinitionLevel); Dictionary<Case, Case> cases = currentCase.isDefined() ? definedCases : undefinedCases; Case nextCase; if (!cases.TryGetValue(currentCase, out nextCase)) { currentCase.setID(cases.Count); cases.Add(currentCase, currentCase); } else { currentCase = nextCase; } caseLookup[currentLevel][d][nextR] = currentCase; } } } state.caseLookup = caseLookup; state.definedCases = definedCases.Values.ToList(); state.definedCases.Sort(); state.undefinedCases = undefinedCases.Values.ToList(); state.undefinedCases.Sort(); } } //TODO: have those wrappers for a converter private RecordConsumer validator(RecordConsumer recordConsumer, bool validating, MessageType schema) { return validating ? new ValidatingRecordConsumer(recordConsumer, schema) : recordConsumer; } private RecordConsumer wrap(RecordConsumer recordConsumer) { if (Log.DEBUG) { return new RecordConsumerLoggingWrapper(recordConsumer); } return recordConsumer; } /** * @see org.apache.parquet.io.RecordReader#read() */ public override T read() { int currentLevel = 0; recordRootConverter.start(); State currentState = states[0]; do { ColumnReader columnReader = currentState.column; int d = columnReader.getCurrentDefinitionLevel(); // creating needed nested groups until the current field (opening tags) int depth = currentState.definitionLevelToDepth[d]; for (; currentLevel <= depth; ++currentLevel) { currentState.groupConverterPath[currentLevel].start(); } // currentLevel = depth + 1 at this point // set the current value if (d >= currentState.maxDefinitionLevel) { // not null columnReader.writeCurrentValueToConverter(); } columnReader.consume(); int nextR = currentState.maxRepetitionLevel == 0 ? 0 : columnReader.getCurrentRepetitionLevel(); // level to go to close current groups int next = currentState.nextLevel[nextR]; for (; currentLevel > next; currentLevel--) { currentState.groupConverterPath[currentLevel - 1].end(); } currentState = currentState.nextState[nextR]; } while (currentState != null); recordRootConverter.end(); T record = recordMaterializer.getCurrentRecord(); _shouldSkipCurrentRecord = record == null; if (_shouldSkipCurrentRecord) { recordMaterializer.skipCurrentRecord(); } return record; } public override bool shouldSkipCurrentRecord() { return _shouldSkipCurrentRecord; } private static void log(string @string) { LOG.debug(@string); } internal int getNextReader(int current, int nextRepetitionLevel) { State nextState = states[current].nextState[nextRepetitionLevel]; return nextState == null ? states.Length : nextState.id; } internal int getNextLevel(int current, int nextRepetitionLevel) { return states[current].nextLevel[nextRepetitionLevel]; } private int getCommonParentLevel(string[] previous, string[] next) { int i = 0; while (i < Math.Min(previous.Length, next.Length) && previous[i].Equals(next[i])) { ++i; } return i; } protected int getStateCount() { return states.Length; } protected State getState(int i) { return states[i]; } protected RecordMaterializer<T> getMaterializer() { return recordMaterializer; } protected Converter getRecordConsumer() { return recordRootConverter; } protected IEnumerable<ColumnReader> getColumnReaders() { // Converting the array to an iterable ensures that the array cannot be altered return columnReaders.ToList(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // TypeDelegator // // This class wraps a Type object and delegates all methods to that Type. namespace System.Reflection { using System; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class TypeDelegator : TypeInfo { public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){ if(typeInfo==null) return false; return IsAssignableFrom(typeInfo.AsType()); } protected Type typeImpl; #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated #endif protected TypeDelegator() {} public TypeDelegator(Type delegatingType) { if (delegatingType == null) throw new ArgumentNullException("delegatingType"); Contract.EndContractBlock(); typeImpl = delegatingType; } public override Guid GUID { get {return typeImpl.GUID;} } public override int MetadataToken { get { return typeImpl.MetadataToken; } } public override Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder,Object target, Object[] args,ParameterModifier[] modifiers,CultureInfo culture,String[] namedParameters) { return typeImpl.InvokeMember(name,invokeAttr,binder,target,args,modifiers,culture,namedParameters); } public override Module Module { get {return typeImpl.Module;} } public override Assembly Assembly { get {return typeImpl.Assembly;} } public override RuntimeTypeHandle TypeHandle { get{return typeImpl.TypeHandle;} } public override String Name { get{return typeImpl.Name;} } public override String FullName { get{return typeImpl.FullName;} } public override String Namespace { get{return typeImpl.Namespace;} } public override String AssemblyQualifiedName { get { return typeImpl.AssemblyQualifiedName; } } public override Type BaseType { get{return typeImpl.BaseType;} } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { return typeImpl.GetConstructor(bindingAttr,binder,callConvention,types,modifiers); } [System.Runtime.InteropServices.ComVisible(true)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return typeImpl.GetConstructors(bindingAttr); } protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { // This is interesting there are two paths into the impl. One that validates // type as non-null and one where type may be null. if (types == null) return typeImpl.GetMethod(name,bindingAttr); else return typeImpl.GetMethod(name,bindingAttr,binder,callConvention,types,modifiers); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return typeImpl.GetMethods(bindingAttr); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { return typeImpl.GetField(name,bindingAttr); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return typeImpl.GetFields(bindingAttr); } public override Type GetInterface(String name, bool ignoreCase) { return typeImpl.GetInterface(name,ignoreCase); } public override Type[] GetInterfaces() { return typeImpl.GetInterfaces(); } public override EventInfo GetEvent(String name,BindingFlags bindingAttr) { return typeImpl.GetEvent(name,bindingAttr); } public override EventInfo[] GetEvents() { return typeImpl.GetEvents(); } protected override PropertyInfo GetPropertyImpl(String name,BindingFlags bindingAttr,Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { if (returnType == null && types == null) return typeImpl.GetProperty(name,bindingAttr); else return typeImpl.GetProperty(name,bindingAttr,binder,returnType,types,modifiers); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return typeImpl.GetProperties(bindingAttr); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { return typeImpl.GetEvents(bindingAttr); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { return typeImpl.GetNestedTypes(bindingAttr); } public override Type GetNestedType(String name, BindingFlags bindingAttr) { return typeImpl.GetNestedType(name,bindingAttr); } public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { return typeImpl.GetMember(name,type,bindingAttr); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return typeImpl.GetMembers(bindingAttr); } protected override TypeAttributes GetAttributeFlagsImpl() { return typeImpl.Attributes; } protected override bool IsArrayImpl() { return typeImpl.IsArray; } protected override bool IsPrimitiveImpl() { return typeImpl.IsPrimitive; } protected override bool IsByRefImpl() { return typeImpl.IsByRef; } protected override bool IsPointerImpl() { return typeImpl.IsPointer; } protected override bool IsValueTypeImpl() { return typeImpl.IsValueType; } protected override bool IsCOMObjectImpl() { return typeImpl.IsCOMObject; } public override bool IsConstructedGenericType { get { return typeImpl.IsConstructedGenericType; } } public override Type GetElementType() { return typeImpl.GetElementType(); } protected override bool HasElementTypeImpl() { return typeImpl.HasElementType; } public override Type UnderlyingSystemType { get {return typeImpl.UnderlyingSystemType;} } // ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return typeImpl.GetCustomAttributes(inherit); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return typeImpl.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return typeImpl.IsDefined(attributeType, inherit); } [System.Runtime.InteropServices.ComVisible(true)] public override InterfaceMapping GetInterfaceMap(Type interfaceType) { return typeImpl.GetInterfaceMap(interfaceType); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for VirtualNetworkGatewayConnectionsOperations. /// </summary> public static partial class VirtualNetworkGatewayConnectionsOperationsExtensions { /// <summary> /// Creates or updates a virtual network gateway connection in the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network gateway /// connection operation. /// </param> public static VirtualNetworkGatewayConnection CreateOrUpdate(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a virtual network gateway connection in the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network gateway /// connection operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGatewayConnection> CreateOrUpdateAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the specified virtual network gateway connection by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> public static VirtualNetworkGatewayConnection Get(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName) { return operations.GetAsync(resourceGroupName, virtualNetworkGatewayConnectionName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified virtual network gateway connection by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGatewayConnection> GetAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified virtual network Gateway connection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> public static void Delete(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName) { operations.DeleteAsync(resourceGroupName, virtualNetworkGatewayConnectionName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network Gateway connection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual /// network gateway connection shared key for passed virtual network gateway /// connection in the specified resource group through Network resource /// provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway connection /// Shared key operation throughNetwork resource provider. /// </param> public static ConnectionSharedKey SetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters) { return operations.SetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult(); } /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual /// network gateway connection shared key for passed virtual network gateway /// connection in the specified resource group through Network resource /// provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway connection /// Shared key operation throughNetwork resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConnectionSharedKey> SetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.SetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves /// information about the specified virtual network gateway connection shared /// key through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection shared key name. /// </param> public static ConnectionSharedKey GetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName) { return operations.GetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName).GetAwaiter().GetResult(); } /// <summary> /// The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves /// information about the specified virtual network gateway connection shared /// key through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection shared key name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConnectionSharedKey> GetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all the /// virtual network gateways connections created. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<VirtualNetworkGatewayConnection> List(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all the /// virtual network gateways connections created. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkGatewayConnection>> ListAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network resource /// provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the begin reset virtual network gateway connection /// shared key operation through network resource provider. /// </param> public static ConnectionResetSharedKey ResetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters) { return operations.ResetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult(); } /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network resource /// provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the begin reset virtual network gateway connection /// shared key operation through network resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConnectionResetSharedKey> ResetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ResetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a virtual network gateway connection in the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network gateway /// connection operation. /// </param> public static VirtualNetworkGatewayConnection BeginCreateOrUpdate(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a virtual network gateway connection in the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network gateway /// connection operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGatewayConnection> BeginCreateOrUpdateAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified virtual network Gateway connection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> public static void BeginDelete(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName) { operations.BeginDeleteAsync(resourceGroupName, virtualNetworkGatewayConnectionName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network Gateway connection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual /// network gateway connection shared key for passed virtual network gateway /// connection in the specified resource group through Network resource /// provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway connection /// Shared key operation throughNetwork resource provider. /// </param> public static ConnectionSharedKey BeginSetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters) { return operations.BeginSetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult(); } /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual /// network gateway connection shared key for passed virtual network gateway /// connection in the specified resource group through Network resource /// provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway connection /// Shared key operation throughNetwork resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConnectionSharedKey> BeginSetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginSetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network resource /// provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the begin reset virtual network gateway connection /// shared key operation through network resource provider. /// </param> public static ConnectionResetSharedKey BeginResetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters) { return operations.BeginResetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult(); } /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network resource /// provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the begin reset virtual network gateway connection /// shared key operation through network resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConnectionResetSharedKey> BeginResetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginResetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all the /// virtual network gateways connections created. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<VirtualNetworkGatewayConnection> ListNext(this IVirtualNetworkGatewayConnectionsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all the /// virtual network gateways connections created. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkGatewayConnection>> ListNextAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Deflater.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace ICSharpCode.SharpZipLib.Silverlight.Zip.Compression { /// <summary> /// This is the Deflater class. The deflater class compresses input /// with the deflate algorithm described in RFC 1951. It has several /// compression levels and three different strategies described below. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of deflate and setInput. /// /// author of the original java version : Jochen Hoenicke /// </summary> public class Deflater { #region Deflater Documentation /* * The Deflater can do the following state transitions: * * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---. * / | (2) (5) | * / v (5) | * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3) * \ | (3) | ,--------' * | | | (3) / * v v (5) v v * (1) -> BUSY_STATE ----> FINISHING_STATE * | (6) * v * FINISHED_STATE * \_____________________________________/ * | (7) * v * CLOSED_STATE * * (1) If we should produce a header we start in INIT_STATE, otherwise * we start in BUSY_STATE. * (2) A dictionary may be set only when we are in INIT_STATE, then * we change the state as indicated. * (3) Whether a dictionary is set or not, on the first call of deflate * we change to BUSY_STATE. * (4) -- intentionally left blank -- :) * (5) FINISHING_STATE is entered, when flush() is called to indicate that * there is no more INPUT. There are also states indicating, that * the header wasn't written yet. * (6) FINISHED_STATE is entered, when everything has been flushed to the * internal pending output buffer. * (7) At any time (7) * */ #endregion #region Public Constants /// <summary> /// The best and slowest compression level. This tries to find very /// long and distant string repetitions. /// </summary> public const int BEST_COMPRESSION = 9; /// <summary> /// The worst but fastest compression level. /// </summary> public const int BEST_SPEED = 1; /// <summary> /// The default compression level. /// </summary> public const int DEFAULT_COMPRESSION = -1; /// <summary> /// This level won't compress at all but output uncompressed blocks. /// </summary> public const int NO_COMPRESSION = 0; /// <summary> /// The compression method. This is the only method supported so far. /// There is no need to use this constant at all. /// </summary> public const int DEFLATED = 8; #endregion #region Local Constants private const int IS_SETDICT = 0x01; private const int IS_FLUSHING = 0x04; private const int IS_FINISHING = 0x08; private const int INIT_STATE = 0x00; private const int SETDICT_STATE = 0x01; // private static int INIT_FINISHING_STATE = 0x08; // private static int SETDICT_FINISHING_STATE = 0x09; private const int BUSY_STATE = 0x10; private const int FLUSHING_STATE = 0x14; private const int FINISHING_STATE = 0x1c; private const int FINISHED_STATE = 0x1e; private const int CLOSED_STATE = 0x7f; #endregion #region Constructors /// <summary> /// Creates a new deflater with default compression level. /// </summary> public Deflater() : this(DEFAULT_COMPRESSION, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level) : this(level, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION. /// </param> /// <param name="noZlibHeaderOrFooter"> /// true, if we should suppress the Zlib/RFC1950 header at the /// beginning and the adler checksum at the end of the output. This is /// useful for the GZIP/PKZIP formats. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level, bool noZlibHeaderOrFooter) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException("level"); } pending = new DeflaterPending(); engine = new DeflaterEngine(pending); this.noZlibHeaderOrFooter = noZlibHeaderOrFooter; SetStrategy(DeflateStrategy.Default); SetLevel(level); Reset(); } #endregion /// <summary> /// Resets the deflater. The deflater acts afterwards as if it was /// just created with the same compression level and strategy as it /// had before. /// </summary> public void Reset() { state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE); totalOut = 0; pending.Reset(); engine.Reset(); } /// <summary> /// Gets the current adler checksum of the data that was processed so far. /// </summary> public int Adler { get { return engine.Adler; } } /// <summary> /// Gets the number of input bytes processed so far. /// </summary> public int TotalIn { get { return engine.TotalIn; } } /// <summary> /// Gets the number of output bytes so far. /// </summary> public long TotalOut { get { return totalOut; } } /// <summary> /// Flushes the current input block. Further calls to deflate() will /// produce enough output to inflate everything in the current input /// block. This is not part of Sun's JDK so I have made it package /// private. It is used by DeflaterOutputStream to implement /// flush(). /// </summary> public void Flush() { state |= IS_FLUSHING; } /// <summary> /// Finishes the deflater with the current input block. It is an error /// to give more input after this method was called. This method must /// be called to force all bytes to be flushed. /// </summary> public void Finish() { state |= (IS_FLUSHING | IS_FINISHING); } /// <summary> /// Returns true if the stream was finished and no more output bytes /// are available. /// </summary> public bool IsFinished { get { return (state == FINISHED_STATE) && pending.IsFlushed; } } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method can also return true when the stream /// was finished. /// </summary> public bool IsNeedingInput { get { return engine.NeedsInput(); } } /// <summary> /// Sets the data which should be compressed next. This should be only /// called when needsInput indicates that more input is needed. /// If you call setInput when needsInput() returns false, the /// previous input that is still pending will be thrown away. /// The given byte array should not be changed, before needsInput() returns /// true again. /// This call is equivalent to <code>setInput(input, 0, input.length)</code>. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was finished() or ended(). /// </exception> public void SetInput(byte[] input) { SetInput(input, 0, input.Length); } /// <summary> /// Sets the data which should be compressed next. This should be /// only called when needsInput indicates that more input is needed. /// The given byte array should not be changed, before needsInput() returns /// true again. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <param name="offset"> /// the start of the data. /// </param> /// <param name="count"> /// the number of data bytes of input. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was Finish()ed or if previous input is still pending. /// </exception> public void SetInput(byte[] input, int offset, int count) { if ((state & IS_FINISHING) != 0) { throw new InvalidOperationException("Finish() already called"); } engine.SetInput(input, offset, count); } /// <summary> /// Sets the compression level. There is no guarantee of the exact /// position of the change, but if you call this when needsInput is /// true the change of compression level will occur somewhere near /// before the end of the so far given input. /// </summary> /// <param name="level"> /// the new compression level. /// </param> public void SetLevel(int level) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException("level"); } if (this.level != level) { this.level = level; engine.SetLevel(level); } } /// <summary> /// Get current compression level /// </summary> /// <returns>Returns the current compression level</returns> public int GetLevel() { return level; } /// <summary> /// Sets the compression strategy. Strategy is one of /// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact /// position where the strategy is changed, the same as for /// SetLevel() applies. /// </summary> /// <param name="strategy"> /// The new compression strategy. /// </param> public void SetStrategy(DeflateStrategy strategy) { engine.Strategy = strategy; } /// <summary> /// Deflates the current input block with to the given array. /// </summary> /// <param name="output"> /// The buffer where compressed data is stored /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// IsNeedingInput() or IsFinished returns true or length is zero. /// </returns> public int Deflate(byte[] output) { return Deflate(output, 0, output.Length); } /// <summary> /// Deflates the current input block to the given array. /// </summary> /// <param name="output"> /// Buffer to store the compressed data. /// </param> /// <param name="offset"> /// Offset into the output array. /// </param> /// <param name="length"> /// The maximum number of bytes that may be stored. /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// needsInput() or finished() returns true or length is zero. /// </returns> /// <exception cref="System.InvalidOperationException"> /// If Finish() was previously called. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// If offset or length don't match the array length. /// </exception> public int Deflate(byte[] output, int offset, int length) { int origLength = length; if (state == CLOSED_STATE) { throw new InvalidOperationException("Deflater closed"); } if (state < BUSY_STATE) { // output header int header = (DEFLATED + ((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8; int level_flags = (level - 1) >> 1; if (level_flags < 0 || level_flags > 3) { level_flags = 3; } header |= level_flags << 6; if ((state & IS_SETDICT) != 0) { // Dictionary was set header |= DeflaterConstants.PRESET_DICT; } header += 31 - (header % 31); pending.WriteShortMSB(header); if ((state & IS_SETDICT) != 0) { int chksum = engine.Adler; engine.ResetAdler(); pending.WriteShortMSB(chksum >> 16); pending.WriteShortMSB(chksum & 0xffff); } state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING)); } for (;;) { int count = pending.Flush(output, offset, length); offset += count; totalOut += count; length -= count; if (length == 0 || state == FINISHED_STATE) { break; } if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) { if (state == BUSY_STATE) { // We need more input now return origLength - length; } else if (state == FLUSHING_STATE) { if (level != NO_COMPRESSION) { /* We have to supply some lookahead. 8 bit lookahead * is needed by the zlib inflater, and we must fill * the next byte, so that all bits are flushed. */ int neededbits = 8 + ((-pending.BitCount) & 7); while (neededbits > 0) { /* write a static tree block consisting solely of * an EOF: */ pending.WriteBits(2, 10); neededbits -= 10; } } state = BUSY_STATE; } else if (state == FINISHING_STATE) { pending.AlignToByte(); // Compressed data is complete. Write footer information if required. if (!noZlibHeaderOrFooter) { int adler = engine.Adler; pending.WriteShortMSB(adler >> 16); pending.WriteShortMSB(adler & 0xffff); } state = FINISHED_STATE; } } } return origLength - length; } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>. /// </summary> /// <param name="dictionary"> /// the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// if SetInput () or Deflate () were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary) { SetDictionary(dictionary, 0, dictionary.Length); } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// The dictionary is a byte array containing strings that are /// likely to occur in the data which should be compressed. The /// dictionary is not stored in the compressed output, only a /// checksum. To decompress the output you need to supply the same /// dictionary again. /// </summary> /// <param name="dictionary"> /// The dictionary data /// </param> /// <param name="index"> /// The index where dictionary information commences. /// </param> /// <param name="count"> /// The number of bytes in the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// If SetInput () or Deflate() were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary, int index, int count) { if (state != INIT_STATE) { throw new InvalidOperationException(); } state = SETDICT_STATE; engine.SetDictionary(dictionary, index, count); } #region Instance Fields /// <summary> /// Compression level. /// </summary> int level; /// <summary> /// If true no Zlib/RFC1950 headers or footers are generated /// </summary> bool noZlibHeaderOrFooter; /// <summary> /// The current state. /// </summary> int state; /// <summary> /// The total bytes of output written. /// </summary> long totalOut; /// <summary> /// The pending output. /// </summary> DeflaterPending pending; /// <summary> /// The deflater engine. /// </summary> DeflaterEngine engine; #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Cloud.Dialogflow.Cx.V3 { /// <summary>Resource name for the <c>Session</c> resource.</summary> public sealed partial class SessionName : gax::IResourceName, sys::IEquatable<SessionName> { /// <summary>The possible contents of <see cref="SessionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}</c>. /// </summary> ProjectLocationAgentSession = 1, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}</c> /// . /// </summary> ProjectLocationAgentEnvironmentSession = 2, } private static gax::PathTemplate s_projectLocationAgentSession = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/sessions/{session}"); private static gax::PathTemplate s_projectLocationAgentEnvironmentSession = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}"); /// <summary>Creates a <see cref="SessionName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="SessionName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static SessionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SessionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SessionName"/> with the pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SessionName"/> constructed from the provided ids.</returns> public static SessionName FromProjectLocationAgentSession(string projectId, string locationId, string agentId, string sessionId) => new SessionName(ResourceNameType.ProjectLocationAgentSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId))); /// <summary> /// Creates a <see cref="SessionName"/> with the pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SessionName"/> constructed from the provided ids.</returns> public static SessionName FromProjectLocationAgentEnvironmentSession(string projectId, string locationId, string agentId, string environmentId, string sessionId) => new SessionName(ResourceNameType.ProjectLocationAgentEnvironmentSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SessionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}</c>. /// </returns> public static string Format(string projectId, string locationId, string agentId, string sessionId) => FormatProjectLocationAgentSession(projectId, locationId, agentId, sessionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SessionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}</c>. /// </returns> public static string FormatProjectLocationAgentSession(string projectId, string locationId, string agentId, string sessionId) => s_projectLocationAgentSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SessionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}</c>. /// </returns> public static string FormatProjectLocationAgentEnvironmentSession(string projectId, string locationId, string agentId, string environmentId, string sessionId) => s_projectLocationAgentEnvironmentSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId))); /// <summary>Parses the given resource name string into a new <see cref="SessionName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SessionName"/> if successful.</returns> public static SessionName Parse(string sessionName) => Parse(sessionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SessionName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="SessionName"/> if successful.</returns> public static SessionName Parse(string sessionName, bool allowUnparsed) => TryParse(sessionName, allowUnparsed, out SessionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SessionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SessionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string sessionName, out SessionName result) => TryParse(sessionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SessionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/sessions/{session}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="SessionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string sessionName, bool allowUnparsed, out SessionName result) { gax::GaxPreconditions.CheckNotNull(sessionName, nameof(sessionName)); gax::TemplatedResourceName resourceName; if (s_projectLocationAgentSession.TryParseName(sessionName, out resourceName)) { result = FromProjectLocationAgentSession(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (s_projectLocationAgentEnvironmentSession.TryParseName(sessionName, out resourceName)) { result = FromProjectLocationAgentEnvironmentSession(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(sessionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SessionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string environmentId = null, string locationId = null, string projectId = null, string sessionId = null) { Type = type; UnparsedResource = unparsedResourceName; AgentId = agentId; EnvironmentId = environmentId; LocationId = locationId; ProjectId = projectId; SessionId = sessionId; } /// <summary> /// Constructs a new instance of a <see cref="SessionName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/sessions/{session}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> public SessionName(string projectId, string locationId, string agentId, string sessionId) : this(ResourceNameType.ProjectLocationAgentSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Agent</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string AgentId { get; } /// <summary> /// The <c>Environment</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string EnvironmentId { get; } /// <summary> /// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Session</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string SessionId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationAgentSession: return s_projectLocationAgentSession.Expand(ProjectId, LocationId, AgentId, SessionId); case ResourceNameType.ProjectLocationAgentEnvironmentSession: return s_projectLocationAgentEnvironmentSession.Expand(ProjectId, LocationId, AgentId, EnvironmentId, SessionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as SessionName); /// <inheritdoc/> public bool Equals(SessionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SessionName a, SessionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SessionName a, SessionName b) => !(a == b); } public partial class DetectIntentRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property. /// </summary> public SessionName SessionAsSessionName { get => string.IsNullOrEmpty(Session) ? null : SessionName.Parse(Session, allowUnparsed: true); set => Session = value?.ToString() ?? ""; } } public partial class StreamingDetectIntentRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property. /// </summary> public SessionName SessionAsSessionName { get => string.IsNullOrEmpty(Session) ? null : SessionName.Parse(Session, allowUnparsed: true); set => Session = value?.ToString() ?? ""; } } public partial class QueryParameters { /// <summary> /// <see cref="PageName"/>-typed view over the <see cref="CurrentPage"/> resource name property. /// </summary> public PageName CurrentPageAsPageName { get => string.IsNullOrEmpty(CurrentPage) ? null : PageName.Parse(CurrentPage, allowUnparsed: true); set => CurrentPage = value?.ToString() ?? ""; } /// <summary> /// <see cref="VersionName"/>-typed view over the <see cref="FlowVersions"/> resource name property. /// </summary> public gax::ResourceNameList<VersionName> FlowVersionsAsVersionNames { get => new gax::ResourceNameList<VersionName>(FlowVersions, s => string.IsNullOrEmpty(s) ? null : VersionName.Parse(s, allowUnparsed: true)); } } public partial class QueryResult { /// <summary> /// <see cref="IntentName"/>-typed view over the <see cref="TriggerIntent"/> resource name property. /// </summary> public IntentName TriggerIntentAsIntentName { get => string.IsNullOrEmpty(TriggerIntent) ? null : IntentName.Parse(TriggerIntent, allowUnparsed: true); set => TriggerIntent = value?.ToString() ?? ""; } } public partial class IntentInput { /// <summary><see cref="IntentName"/>-typed view over the <see cref="Intent"/> resource name property.</summary> public IntentName IntentAsIntentName { get => string.IsNullOrEmpty(Intent) ? null : IntentName.Parse(Intent, allowUnparsed: true); set => Intent = value?.ToString() ?? ""; } } public partial class MatchIntentRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property. /// </summary> public SessionName SessionAsSessionName { get => string.IsNullOrEmpty(Session) ? null : SessionName.Parse(Session, allowUnparsed: true); set => Session = value?.ToString() ?? ""; } } public partial class MatchIntentResponse { /// <summary> /// <see cref="IntentName"/>-typed view over the <see cref="TriggerIntent"/> resource name property. /// </summary> public IntentName TriggerIntentAsIntentName { get => string.IsNullOrEmpty(TriggerIntent) ? null : IntentName.Parse(TriggerIntent, allowUnparsed: true); set => TriggerIntent = value?.ToString() ?? ""; } } }
//------------------------------------------------------------------------------ // <copyright file="Command.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing.Design; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Security.Permissions; namespace System.Web.UI.MobileControls { /* * Mobile Command class. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\Command.uex' path='docs/doc[@for="Command"]/*' /> [ DataBindingHandler("System.Web.UI.Design.TextDataBindingHandler, " + AssemblyRef.SystemDesign), DefaultEvent("Click"), DefaultProperty("Text"), Designer(typeof(System.Web.UI.Design.MobileControls.CommandDesigner)), DesignerAdapter(typeof(System.Web.UI.Design.MobileControls.Adapters.DesignerCommandAdapter)), ToolboxData("<{0}:Command runat=\"server\">Command</{0}:Command>"), ToolboxItem("System.Web.UI.Design.WebControlToolboxItem, " + AssemblyRef.SystemDesign) ] [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class Command : TextControl, IPostBackEventHandler, IPostBackDataHandler { private static readonly Object EventClick = new Object (); private static readonly Object EventItemCommand = new Object (); /// <include file='doc\Command.uex' path='docs/doc[@for="Command.OnPreRender"]/*' /> protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); // If this control will be rendered as an image Debug.Assert(ImageUrl != null); if (MobilePage != null && ImageUrl.Length != 0 && MobilePage.Device.SupportsImageSubmit) { // HTML input controls of type image postback as name.x and // name.y which is not associated with this control by default // in Page.ProcessPostData(). MobilePage.RegisterRequiresPostBack(this); } } /// <internalonly/> protected bool LoadPostData(String key, NameValueCollection data) { bool dataChanged; bool handledByAdapter = Adapter.LoadPostData(key, data, null, out dataChanged); // If the adapter handled the post back and set dataChanged this // was an image button (responds with ID.x and ID.y). if (handledByAdapter) { if(dataChanged) { Page.RegisterRequiresRaiseEvent(this); } } // Otherwise if the adapter did not handle the past back, use // the same method as Page.ProcessPostData(). else if(data[key] != null) { Page.RegisterRequiresRaiseEvent(this); } return false; // no need to raise PostDataChangedEvent. } /// <internalonly/> protected void RaisePostDataChangedEvent() { } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.SoftkeyLabel"]/*' /> [ Bindable(true), DefaultValue(""), MobileCategory(SR.Category_Behavior), MobileSysDescription(SR.Command_SoftkeyLabel) ] public String SoftkeyLabel { get { String s = (String) ViewState["Softkeylabel"]; return((s != null) ? s : String.Empty); } set { ViewState["Softkeylabel"] = value; } } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.CommandName"]/*' /> [ Bindable(true), DefaultValue(""), MobileCategory(SR.Category_Behavior), MobileSysDescription(SR.Command_CommandName) ] public String CommandName { get { String s = (String) ViewState["CommandName"]; return((s != null) ? s : String.Empty); } set { ViewState["CommandName"] = value; } } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.CommandArgument"]/*' /> [ Bindable(true), DefaultValue(""), MobileCategory(SR.Category_Behavior), MobileSysDescription(SR.Command_CommandArgument) ] public String CommandArgument { get { String s = (String) ViewState["CommandArgument"]; return((s != null) ? s : String.Empty); } set { ViewState["CommandArgument"] = value; } } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.ImageUrl"]/*' /> [ Bindable(true), DefaultValue(""), Editor(typeof(System.Web.UI.Design.MobileControls.ImageUrlEditor), typeof(UITypeEditor)), MobileCategory(SR.Category_Appearance), MobileSysDescription(SR.Image_ImageUrl) ] public String ImageUrl { get { String s = (String) ViewState["ImageUrl"]; return((s != null) ? s : String.Empty); } set { ViewState["ImageUrl"] = value; } } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.CausesValidation"]/*' /> [ Bindable(false), DefaultValue(true), MobileCategory(SR.Category_Behavior), MobileSysDescription(SR.Command_CausesValidation) ] public bool CausesValidation { get { object b = ViewState["CausesValidation"]; return((b == null) ? true : (bool)b); } set { ViewState["CausesValidation"] = value; } } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.Format"]/*' /> [ Bindable(true), DefaultValue(CommandFormat.Button), MobileCategory(SR.Category_Appearance), MobileSysDescription(SR.Command_Format) ] public CommandFormat Format { get { Object o = ViewState["Format"]; return((o == null) ? CommandFormat.Button : (CommandFormat)o); } set { ViewState["Format"] = value; } } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.OnClick"]/*' /> protected virtual void OnClick(EventArgs e) { EventHandler onClickHandler = (EventHandler)Events[EventClick]; if (onClickHandler != null) { onClickHandler(this,e); } } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.OnItemCommand"]/*' /> protected virtual void OnItemCommand(CommandEventArgs e) { CommandEventHandler onItemCommandHandler = (CommandEventHandler)Events[EventItemCommand]; if (onItemCommandHandler != null) { onItemCommandHandler(this,e); } RaiseBubbleEvent (this, e); } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.Click"]/*' /> [ MobileCategory(SR.Category_Action), MobileSysDescription(SR.Command_OnClick) ] public event EventHandler Click { add { Events.AddHandler(EventClick, value); } remove { Events.RemoveHandler(EventClick, value); } } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.ItemCommand"]/*' /> [ MobileCategory(SR.Category_Action), MobileSysDescription(SR.Command_OnItemCommand) ] public event CommandEventHandler ItemCommand { add { Events.AddHandler(EventItemCommand, value); } remove { Events.RemoveHandler(EventItemCommand, value); } } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.IPostBackEventHandler.RaisePostBackEvent"]/*' /> /// <internalonly/> protected void RaisePostBackEvent(String argument) { if (CausesValidation) { MobilePage.Validate(); } // It is legitimate to reset the form back to the first page // after a form submit. Form.CurrentPage = 1; OnClick (EventArgs.Empty); OnItemCommand (new CommandEventArgs(CommandName, CommandArgument)); } /// <include file='doc\Command.uex' path='docs/doc[@for="Command.IsFormSubmitControl"]/*' /> protected override bool IsFormSubmitControl() { return true; } #region IPostBackEventHandler implementation void IPostBackEventHandler.RaisePostBackEvent(String eventArgument) { RaisePostBackEvent(eventArgument); } #endregion #region IPostBackDataHandler implementation bool IPostBackDataHandler.LoadPostData(String key, NameValueCollection data) { return LoadPostData(key, data); } void IPostBackDataHandler.RaisePostDataChangedEvent() { RaisePostDataChangedEvent(); } #endregion } }
/*************************************************************************** * BatchTranscoder.cs * * Copyright (C) 2005-2006 Novell, Inc. * Written by Aaron Bockover <[email protected]> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.IO; using System.Collections; using System.Collections.Generic; using Mono.Unix; using Banshee.Widgets; using Banshee.AudioProfiles; namespace Banshee.Base { public delegate void FileCompleteHandler(object o, FileCompleteArgs args); public class FileCompleteArgs : EventArgs { public TrackInfo Track; public SafeUri InputUri; public SafeUri EncodedFileUri; } public class BatchTranscoder { private static Dictionary<string, Type> alternate_wav_transcoders = new Dictionary<string, Type>(); public static void RegisterAlternateWavTranscoder(string extension, Type type) { lock(alternate_wav_transcoders) { if(alternate_wav_transcoders.ContainsKey(extension)) { alternate_wav_transcoders[extension] = type; } else { alternate_wav_transcoders.Add(extension, type); } } } public class QueueItem { private object source; private SafeUri destination; public QueueItem(object source, SafeUri destination) { this.source = source; this.destination = destination; } public object Source { get { return source; } } public SafeUri Destination { get { return destination; } } } private ArrayList error_list = new ArrayList(); private Queue batch_queue = new Queue(); private QueueItem current = null; private Transcoder transcoder; private Transcoder default_transcoder; private Profile profile; private int finished_count; private int total_count; private string desired_profile_name; private ActiveUserEvent user_event; public event FileCompleteHandler FileFinished; public event EventHandler BatchFinished; public event EventHandler Canceled; private const int progress_precision = 1000; public BatchTranscoder(Profile profile) : this(profile, null) { } public BatchTranscoder(Profile profile, string desiredProfileName) { transcoder = new GstTranscoder(); transcoder.Progress += OnTranscoderProgress; transcoder.Error += OnTranscoderError; transcoder.Finished += OnTranscoderFinished; default_transcoder = transcoder; this.desired_profile_name = desiredProfileName; this.profile = profile; } public void AddTrack(TrackInfo track, SafeUri outputUri) { batch_queue.Enqueue(new QueueItem(track, outputUri)); } public void AddTrack(SafeUri inputUri, SafeUri outputUri) { batch_queue.Enqueue(new QueueItem(inputUri, outputUri)); } public void Start() { if(user_event == null) { user_event = new ActiveUserEvent(Catalog.GetString("Converting Files")); user_event.Header = Catalog.GetString("Converting Files"); user_event.CancelMessage = Catalog.GetString( "Files are currently being converted to another audio format. Would you like to stop this?"); user_event.CancelRequested += OnCancelRequested; user_event.Icon = IconThemeUtils.LoadIcon("encode-action-24", 22); user_event.Message = Catalog.GetString("Initializing Transcoder..."); } total_count = batch_queue.Count; finished_count = 0; error_list.Clear(); try { TranscodeNext(); } catch(Exception e) { Console.WriteLine(e); error_list.Add(e.Message); if(user_event != null) { user_event.Dispose(); } OnBatchFinished(); } } private void TranscodeNext() { if(batch_queue.Count <= 0) { return; } current = batch_queue.Dequeue() as QueueItem; if(current == null) { return; } SafeUri output_uri = current.Destination; SafeUri input_uri = null; if(current.Source is TrackInfo) { TrackInfo track = current.Source as TrackInfo; user_event.Message = String.Format("{0} - {1}", track.DisplayArtist, track.DisplayTitle); input_uri = track.Uri; } else if(current.Source is SafeUri) { input_uri = current.Source as SafeUri; user_event.Message = Path.GetFileName(input_uri.LocalPath); } else { return; } if(user_event.IsCancelRequested) { return; } string input_extension = Path.GetExtension(input_uri.LocalPath).Substring(1); transcoder = default_transcoder; if(profile.OutputFileExtension == "wav" && alternate_wav_transcoders.ContainsKey(input_extension)) { Transcoder alt_transcoder = (Transcoder)Activator.CreateInstance(alternate_wav_transcoders[input_extension]); alt_transcoder.Progress += OnTranscoderProgress; alt_transcoder.Error += OnTranscoderError; alt_transcoder.Finished += OnTranscoderFinished; transcoder = alt_transcoder; } if(input_extension != profile.OutputFileExtension) { transcoder.BeginTranscode(input_uri, output_uri, profile); } else if(desired_profile_name != null && profile.Name != desired_profile_name) { OnTranscoderError(this, new EventArgs()); } else { OnTranscoderFinished(this, new EventArgs()); } if(transcoder != default_transcoder) { transcoder.Dispose(); transcoder = default_transcoder; } } private void PostTranscode() { current = null; finished_count++; if(batch_queue.Count > 0) { TranscodeNext(); } else { if(user_event != null) { user_event.Dispose(); } OnBatchFinished(); } } private void OnBatchFinished() { EventHandler handler = BatchFinished; if(handler != null) { handler(this, new EventArgs()); } } private void OnTranscoderFinished(object o, EventArgs args) { FileCompleteHandler handler = FileFinished; if(handler != null && current != null) { FileCompleteArgs cargs = new FileCompleteArgs(); cargs.EncodedFileUri = current.Destination; if(current.Source is TrackInfo) { cargs.Track = current.Source as TrackInfo; cargs.InputUri = cargs.Track.Uri; } else if(current.Source is SafeUri) { cargs.InputUri = (current.Source as SafeUri); } handler(this, cargs); } PostTranscode(); } private void OnTranscoderError(object o, EventArgs args) { error_list.Add(current); PostTranscode(); } private void OnTranscoderProgress(object o, TranscoderProgressArgs args) { user_event.Progress = ((double)(progress_precision * finished_count) + (args.Progress * (double)progress_precision)) / (double)(progress_precision * total_count); } private void OnCancelRequested(object o, EventArgs args) { if(user_event == null) { return; } if(transcoder != null) { transcoder.Cancel(); } error_list.Clear(); batch_queue.Clear(); current = null; user_event.Dispose(); user_event = null; if(Canceled != null) { Canceled(this, new EventArgs()); } } public IEnumerable ErrorList { get { return error_list; } } public int ErrorCount { get { return error_list.Count; } } } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.Threading; using dnlib.DotNet.MD; namespace dnlib.DotNet { /// <summary> /// A high-level representation of a row in the MemberRef table /// </summary> public abstract class MemberRef : IHasCustomAttribute, IMethodDefOrRef, ICustomAttributeType, IField { /// <summary> /// The row id in its table /// </summary> protected uint rid; /// <summary> /// The owner module /// </summary> protected ModuleDef module; /// <inheritdoc/> public MDToken MDToken { get { return new MDToken(Table.MemberRef, rid); } } /// <inheritdoc/> public uint Rid { get { return rid; } set { rid = value; } } /// <inheritdoc/> public int HasCustomAttributeTag { get { return 6; } } /// <inheritdoc/> public int MethodDefOrRefTag { get { return 1; } } /// <inheritdoc/> public int CustomAttributeTypeTag { get { return 3; } } /// <summary> /// From column MemberRef.Class /// </summary> public IMemberRefParent Class { get { return @class; } set { @class = value; } } /// <summary/> protected IMemberRefParent @class; /// <summary> /// From column MemberRef.Name /// </summary> public UTF8String Name { get { return name; } set { name = value; } } /// <summary>Name</summary> protected UTF8String name; /// <summary> /// From column MemberRef.Signature /// </summary> public CallingConventionSig Signature { get { return signature; } set { signature = value; } } /// <summary/> protected CallingConventionSig signature; /// <summary> /// Gets all custom attributes /// </summary> public CustomAttributeCollection CustomAttributes { get { if (customAttributes == null) InitializeCustomAttributes(); return customAttributes; } } /// <summary/> protected CustomAttributeCollection customAttributes; /// <summary>Initializes <see cref="customAttributes"/></summary> protected virtual void InitializeCustomAttributes() { Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null); } /// <inheritdoc/> public bool HasCustomAttributes { get { return CustomAttributes.Count > 0; } } /// <inheritdoc/> public ITypeDefOrRef DeclaringType { get { var owner = @class; var tdr = owner as ITypeDefOrRef; if (tdr != null) return tdr; var method = owner as MethodDef; if (method != null) return method.DeclaringType; var mr = owner as ModuleRef; if (mr != null) { var tr = GetGlobalTypeRef(mr); if (module != null) return module.UpdateRowId(tr); return tr; } return null; } } TypeRefUser GetGlobalTypeRef(ModuleRef mr) { if (module == null) return CreateDefaultGlobalTypeRef(mr); var globalType = module.GlobalType; if (globalType != null && new SigComparer().Equals(module, mr)) return new TypeRefUser(module, globalType.Namespace, globalType.Name, mr); var asm = module.Assembly; if (asm == null) return CreateDefaultGlobalTypeRef(mr); var mod = asm.FindModule(mr.Name); if (mod == null) return CreateDefaultGlobalTypeRef(mr); globalType = mod.GlobalType; if (globalType == null) return CreateDefaultGlobalTypeRef(mr); return new TypeRefUser(module, globalType.Namespace, globalType.Name, mr); } TypeRefUser CreateDefaultGlobalTypeRef(ModuleRef mr) { return new TypeRefUser(module, string.Empty, "<Module>", mr); } bool IIsTypeOrMethod.IsType { get { return false; } } bool IIsTypeOrMethod.IsMethod { get { return IsMethodRef; } } bool IMemberRef.IsField { get { return IsFieldRef; } } bool IMemberRef.IsTypeSpec { get { return false; } } bool IMemberRef.IsTypeRef { get { return false; } } bool IMemberRef.IsTypeDef { get { return false; } } bool IMemberRef.IsMethodSpec { get { return false; } } bool IMemberRef.IsMethodDef { get { return false; } } bool IMemberRef.IsMemberRef { get { return true; } } bool IMemberRef.IsFieldDef { get { return false; } } bool IMemberRef.IsPropertyDef { get { return false; } } bool IMemberRef.IsEventDef { get { return false; } } bool IMemberRef.IsGenericParam { get { return false; } } /// <summary> /// <c>true</c> if this is a method reference (<see cref="MethodSig"/> != <c>null</c>) /// </summary> public bool IsMethodRef { get { return MethodSig != null; } } /// <summary> /// <c>true</c> if this is a field reference (<see cref="FieldSig"/> != <c>null</c>) /// </summary> public bool IsFieldRef { get { return FieldSig != null; } } /// <summary> /// Gets/sets the method sig /// </summary> public MethodSig MethodSig { get { return signature as MethodSig; } set { signature = value; } } /// <summary> /// Gets/sets the field sig /// </summary> public FieldSig FieldSig { get { return signature as FieldSig; } set { signature = value; } } /// <inheritdoc/> public ModuleDef Module { get { return module; } } /// <summary> /// <c>true</c> if the method has a hidden 'this' parameter /// </summary> public bool HasThis { get { var ms = MethodSig; return ms == null ? false : ms.HasThis; } } /// <summary> /// <c>true</c> if the method has an explicit 'this' parameter /// </summary> public bool ExplicitThis { get { var ms = MethodSig; return ms == null ? false : ms.ExplicitThis; } } /// <summary> /// Gets the calling convention /// </summary> public CallingConvention CallingConvention { get { var ms = MethodSig; return ms == null ? 0 : ms.CallingConvention & CallingConvention.Mask; } } /// <summary> /// Gets/sets the method return type /// </summary> public TypeSig ReturnType { get { var ms = MethodSig; return ms == null ? null : ms.RetType; } set { var ms = MethodSig; if (ms != null) ms.RetType = value; } } /// <inheritdoc/> int IGenericParameterProvider.NumberOfGenericParameters { get { var sig = MethodSig; return sig == null ? 0 : (int)sig.GenParamCount; } } /// <summary> /// Gets the full name /// </summary> public string FullName { get { var parent = @class; IList<TypeSig> typeGenArgs = null; if (parent is TypeSpec) { var sig = ((TypeSpec)parent).TypeSig as GenericInstSig; if (sig != null) typeGenArgs = sig.GenericArguments; } var methodSig = MethodSig; if (methodSig != null) return FullNameCreator.MethodFullName(GetDeclaringTypeFullName(parent), name, methodSig, typeGenArgs, null); var fieldSig = FieldSig; if (fieldSig != null) return FullNameCreator.FieldFullName(GetDeclaringTypeFullName(parent), name, fieldSig, typeGenArgs); return string.Empty; } } /// <summary> /// Get the declaring type's full name /// </summary> /// <returns>Full name or <c>null</c> if there's no declaring type</returns> public string GetDeclaringTypeFullName() { return GetDeclaringTypeFullName(@class); } string GetDeclaringTypeFullName(IMemberRefParent parent) { if (parent == null) return null; if (parent is ITypeDefOrRef) return ((ITypeDefOrRef)parent).FullName; if (parent is ModuleRef) return string.Format("[module:{0}]<Module>", ((ModuleRef)parent).ToString()); if (parent is MethodDef) { var declaringType = ((MethodDef)parent).DeclaringType; return declaringType == null ? null : declaringType.FullName; } return null; // Should never be reached } /// <summary> /// Resolves the method/field /// </summary> /// <returns>A <see cref="MethodDef"/> or a <see cref="FieldDef"/> instance or <c>null</c> /// if it couldn't be resolved.</returns> public IMemberForwarded Resolve() { if (module == null) return null; return module.Context.Resolver.Resolve(this); } /// <summary> /// Resolves the method/field /// </summary> /// <returns>A <see cref="MethodDef"/> or a <see cref="FieldDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the method/field couldn't be resolved</exception> public IMemberForwarded ResolveThrow() { var memberDef = Resolve(); if (memberDef != null) return memberDef; throw new MemberRefResolveException(string.Format("Could not resolve method/field: {0} ({1})", this, this.GetDefinitionAssembly())); } /// <summary> /// Resolves the field /// </summary> /// <returns>A <see cref="FieldDef"/> instance or <c>null</c> if it couldn't be resolved.</returns> public FieldDef ResolveField() { return Resolve() as FieldDef; } /// <summary> /// Resolves the field /// </summary> /// <returns>A <see cref="FieldDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the field couldn't be resolved</exception> public FieldDef ResolveFieldThrow() { var field = ResolveField(); if (field != null) return field; throw new MemberRefResolveException(string.Format("Could not resolve field: {0} ({1})", this, this.GetDefinitionAssembly())); } /// <summary> /// Resolves the method /// </summary> /// <returns>A <see cref="MethodDef"/> instance or <c>null</c> if it couldn't be resolved.</returns> public MethodDef ResolveMethod() { return Resolve() as MethodDef; } /// <summary> /// Resolves the method /// </summary> /// <returns>A <see cref="MethodDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the method couldn't be resolved</exception> public MethodDef ResolveMethodThrow() { var method = ResolveMethod(); if (method != null) return method; throw new MemberRefResolveException(string.Format("Could not resolve method: {0} ({1})", this, this.GetDefinitionAssembly())); } /// <inheritdoc/> public override string ToString() { return FullName; } } /// <summary> /// A MemberRef row created by the user and not present in the original .NET file /// </summary> public class MemberRefUser : MemberRef { /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> public MemberRefUser(ModuleDef module) { this.module = module; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of ref</param> public MemberRefUser(ModuleDef module, UTF8String name) { this.module = module; this.name = name; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of field ref</param> /// <param name="sig">Field sig</param> public MemberRefUser(ModuleDef module, UTF8String name, FieldSig sig) : this(module, name, sig, null) { } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of field ref</param> /// <param name="sig">Field sig</param> /// <param name="class">Owner of field</param> public MemberRefUser(ModuleDef module, UTF8String name, FieldSig sig, IMemberRefParent @class) { this.module = module; this.name = name; this.@class = @class; this.signature = sig; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of method ref</param> /// <param name="sig">Method sig</param> public MemberRefUser(ModuleDef module, UTF8String name, MethodSig sig) : this(module, name, sig, null) { } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of method ref</param> /// <param name="sig">Method sig</param> /// <param name="class">Owner of method</param> public MemberRefUser(ModuleDef module, UTF8String name, MethodSig sig, IMemberRefParent @class) { this.module = module; this.name = name; this.@class = @class; this.signature = sig; } } /// <summary> /// Created from a row in the MemberRef table /// </summary> sealed class MemberRefMD : MemberRef, IMDTokenProviderMD, IContainsGenericParameter { /// <summary>The module where this instance is located</summary> readonly ModuleDefMD readerModule; readonly uint origRid; /// <inheritdoc/> public uint OrigRid { get { return origRid; } } /// <inheritdoc/> protected override void InitializeCustomAttributes() { var list = readerModule.MetaData.GetCustomAttributeRidList(Table.MemberRef, origRid); var tmp = new CustomAttributeCollection((int)list.Length, list, (list2, index) => readerModule.ReadCustomAttribute(((RidList)list2)[index])); Interlocked.CompareExchange(ref customAttributes, tmp, null); } bool IContainsGenericParameter.ContainsGenericParameter { get { return TypeHelper.ContainsGenericParameter(this); } } /// <summary> /// Constructor /// </summary> /// <param name="readerModule">The module which contains this <c>MemberRef</c> row</param> /// <param name="rid">Row ID</param> /// <param name="gpContext">Generic parameter context</param> /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception> /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception> public MemberRefMD(ModuleDefMD readerModule, uint rid, GenericParamContext gpContext) { #if DEBUG if (readerModule == null) throw new ArgumentNullException("readerModule"); if (readerModule.TablesStream.MemberRefTable.IsInvalidRID(rid)) throw new BadImageFormatException(string.Format("MemberRef rid {0} does not exist", rid)); #endif this.origRid = rid; this.rid = rid; this.readerModule = readerModule; this.module = readerModule; uint @class, name; uint signature = readerModule.TablesStream.ReadMemberRefRow(origRid, out @class, out name); this.name = readerModule.StringsStream.ReadNoNull(name); this.@class = readerModule.ResolveMemberRefParent(@class, gpContext); this.signature = readerModule.ReadSignature(signature, gpContext); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Configuration.ConfigurationManagerTest.cs - Unit tests // for System.Configuration.ConfigurationManager. // // Author: // Chris Toshok <[email protected]> // Atsushi Enomoto <[email protected]> // // Copyright (C) 2005-2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Specialized; using System.Configuration; using System.IO; using Xunit; using SysConfig = System.Configuration.Configuration; namespace MonoTests.System.Configuration { using Util; public class ConfigurationManagerTest { [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetNativeRunningAsConsoleApp))] // OpenExeConfiguration (ConfigurationUserLevel) [ActiveIssue("dotnet/corefx #19384", TargetFrameworkMonikers.NetFramework)] public void OpenExeConfiguration1_UserLevel_None() { SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal(TestUtil.ThisConfigFileName, fi.Name); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetNativeRunningAsConsoleApp))] public void OpenExeConfiguration1_UserLevel_PerUserRoaming() { string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // If there is not ApplicationData folder PerUserRoaming won't work if (string.IsNullOrEmpty(applicationData)) return; SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); Assert.False(string.IsNullOrEmpty(config.FilePath), "should have some file path"); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("user.config", fi.Name); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetNativeRunningAsConsoleApp), nameof(PlatformDetection.IsNotWindowsNanoServer))] // ActiveIssue: https://github.com/dotnet/corefx/issues/29752 [ActiveIssue(15065, TestPlatforms.AnyUnix)] public void OpenExeConfiguration1_UserLevel_PerUserRoamingAndLocal() { SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("user.config", fi.Name); } [Fact] // OpenExeConfiguration (String) public void OpenExeConfiguration2() { using (var temp = new TempDirectory()) { string exePath; SysConfig config; exePath = Path.Combine(temp.Path, "DoesNotExist.whatever"); File.Create(exePath).Close(); config = ConfigurationManager.OpenExeConfiguration(exePath); Assert.Equal(exePath + ".config", config.FilePath); exePath = Path.Combine(temp.Path, "SomeExecutable.exe"); File.Create(exePath).Close(); config = ConfigurationManager.OpenExeConfiguration(exePath); Assert.Equal(exePath + ".config", config.FilePath); exePath = Path.Combine(temp.Path, "Foo.exe.config"); File.Create(exePath).Close(); config = ConfigurationManager.OpenExeConfiguration(exePath); Assert.Equal(exePath + ".config", config.FilePath); } } [Fact] // OpenExeConfiguration (String) public void OpenExeConfiguration2_ExePath_DoesNotExist() { using (var temp = new TempDirectory()) { string exePath = Path.Combine(temp.Path, "DoesNotExist.exe"); ConfigurationErrorsException ex = Assert.Throws<ConfigurationErrorsException>( () => ConfigurationManager.OpenExeConfiguration(exePath)); // An error occurred loading a configuration file: // The parameter 'exePath' is invalid Assert.Equal(typeof(ConfigurationErrorsException), ex.GetType()); Assert.Null(ex.Filename); Assert.NotNull(ex.InnerException); Assert.Equal(0, ex.Line); Assert.NotNull(ex.Message); // The parameter 'exePath' is invalid ArgumentException inner = ex.InnerException as ArgumentException; Assert.NotNull(inner); Assert.Equal(typeof(ArgumentException), inner.GetType()); Assert.Null(inner.InnerException); Assert.NotNull(inner.Message); Assert.Equal("exePath", inner.ParamName); } } [Fact] [ActiveIssue("dotnet/corefx #18831", TargetFrameworkMonikers.NetFramework)] public void exePath_UserLevelNone() { string name = TestUtil.ThisApplicationPath; SysConfig config = ConfigurationManager.OpenExeConfiguration(name); Assert.Equal(TestUtil.ThisApplicationPath + ".config", config.FilePath); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetNativeRunningAsConsoleApp))] public void exePath_UserLevelPerRoaming() { string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // If there is not ApplicationData folder PerUserRoaming won't work if (string.IsNullOrEmpty(applicationData)) return; SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); string filePath = config.FilePath; Assert.False(string.IsNullOrEmpty(filePath), "should have some file path"); Assert.Equal("user.config", Path.GetFileName(filePath)); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetNativeRunningAsConsoleApp), nameof(PlatformDetection.IsNotWindowsNanoServer))] // ActiveIssue: https://github.com/dotnet/corefx/issues/29752 [ActiveIssue(15066, TestPlatforms.AnyUnix)] public void exePath_UserLevelPerRoamingAndLocal() { SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); string filePath = config.FilePath; string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); Assert.True(filePath.StartsWith(applicationData), "#1:" + filePath); Assert.Equal("user.config", Path.GetFileName(filePath)); } [Fact] public void mapped_UserLevelNone() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("execonfig", fi.Name); } [Fact] public void mapped_UserLevelPerRoaming() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; map.RoamingUserConfigFilename = "roaminguser"; SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoaming); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("roaminguser", fi.Name); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_UserLevelPerRoaming_no_execonfig() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.RoamingUserConfigFilename = "roaminguser"; AssertExtensions.Throws<ArgumentException>("fileMap.ExeConfigFilename", () => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoaming)); } [Fact] public void mapped_UserLevelPerRoamingAndLocal() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; map.RoamingUserConfigFilename = "roaminguser"; map.LocalUserConfigFilename = "localuser"; SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("localuser", fi.Name); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_UserLevelPerRoamingAndLocal_no_execonfig() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.RoamingUserConfigFilename = "roaminguser"; map.LocalUserConfigFilename = "localuser"; AssertExtensions.Throws<ArgumentException>("fileMap.ExeConfigFilename", () => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal)); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_UserLevelPerRoamingAndLocal_no_roaminguser() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; map.LocalUserConfigFilename = "localuser"; AssertExtensions.Throws<ArgumentException>("fileMap.RoamingUserConfigFilename", () => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal)); } [Fact] public void MachineConfig() { SysConfig config = ConfigurationManager.OpenMachineConfiguration(); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("machine.config", fi.Name); } [Fact] public void mapped_MachineConfig() { ConfigurationFileMap map = new ConfigurationFileMap(); map.MachineConfigFilename = "machineconfig"; SysConfig config = ConfigurationManager.OpenMappedMachineConfiguration(map); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("machineconfig", fi.Name); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetNativeRunningAsConsoleApp))] // Doesn't pass on Mono // [Category("NotWorking")] [ActiveIssue("dotnet/corefx #19384", TargetFrameworkMonikers.NetFramework)] public void mapped_ExeConfiguration_null() { SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(null, ConfigurationUserLevel.None); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal(TestUtil.ThisConfigFileName, fi.Name); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_MachineConfig_null() { SysConfig config = ConfigurationManager.OpenMappedMachineConfiguration(null); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("machine.config", fi.Name); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetNativeRunningAsConsoleApp))] public void GetSectionReturnsNativeObject() { Assert.True(ConfigurationManager.GetSection("appSettings") is NameValueCollection); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetNativeRunningAsConsoleApp))] // Test for bug #3412 // Doesn't pass on Mono // [Category("NotWorking")] public void TestAddRemoveSection() { const string name = "testsection"; var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // ensure not present if (config.Sections.Get(name) != null) { config.Sections.Remove(name); } // add config.Sections.Add(name, new TestSection()); // remove var section = config.Sections.Get(name); Assert.NotNull(section); Assert.NotNull(section as TestSection); config.Sections.Remove(name); // add config.Sections.Add(name, new TestSection()); // remove section = config.Sections.Get(name); Assert.NotNull(section); Assert.NotNull(section as TestSection); config.Sections.Remove(name); } [Fact] public void TestFileMap() { using (var temp = new TempDirectory()) { string configPath = Path.Combine(temp.Path, Path.GetRandomFileName() + ".config"); Assert.False(File.Exists(configPath)); var map = new ExeConfigurationFileMap(); map.ExeConfigFilename = configPath; var config = ConfigurationManager.OpenMappedExeConfiguration( map, ConfigurationUserLevel.None); config.Sections.Add("testsection", new TestSection()); config.Save(); Assert.True(File.Exists(configPath), "#1"); Assert.True(File.Exists(Path.GetFullPath(configPath)), "#2"); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetNativeRunningAsConsoleApp))] public void TestContext() { var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); const string name = "testsection"; // ensure not present if (config.GetSection(name) != null) config.Sections.Remove(name); var section = new TestContextSection(); // Can't access EvaluationContext .... Assert.Throws<ConfigurationErrorsException>(() => section.TestContext(null)); // ... until it's been added to a section. config.Sections.Add(name, section); section.TestContext("#2"); // Remove ... config.Sections.Remove(name); // ... and it doesn't lose its context section.TestContext(null); } [Fact] public void TestContext2() { using (var temp = new TempDirectory()) { string configPath = Path.Combine(temp.Path, Path.GetRandomFileName() + ".config"); Assert.False(File.Exists(configPath)); var map = new ExeConfigurationFileMap(); map.ExeConfigFilename = configPath; var config = ConfigurationManager.OpenMappedExeConfiguration( map, ConfigurationUserLevel.None); config.Sections.Add("testsection", new TestSection()); config.Sections.Add("testcontext", new TestContextSection()); config.Save(); Assert.True(File.Exists(configPath), "#1"); } } class TestSection : ConfigurationSection { } class TestContextSection : ConfigurationSection { public void TestContext(string label) { Assert.NotNull(EvaluationContext); } } [Fact] public void BadConfig() { using (var temp = new TempDirectory()) { string xml = @" badXml"; var file = Path.Combine(temp.Path, "badConfig.config"); File.WriteAllText(file, xml); var fileMap = new ConfigurationFileMap(file); Assert.Equal(file, Assert.Throws<ConfigurationErrorsException>(() => ConfigurationManager.OpenMappedMachineConfiguration(fileMap)).Filename); } } } }
using System.Collections.Generic; using System.Linq; namespace Lucene.Net.Search { /* * 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 BooleanWeight = Lucene.Net.Search.BooleanQuery.BooleanWeight; /// <summary> /// See the description in <see cref="BooleanScorer"/> comparing /// <see cref="BooleanScorer"/> &amp; <see cref="BooleanScorer2"/>. /// <para/> /// An alternative to <see cref="BooleanScorer"/> that also allows a minimum number /// of optional scorers that should match. /// <para/>Implements SkipTo(), and has no limitations on the numbers of added scorers. /// <para/>Uses <see cref="ConjunctionScorer"/>, <see cref="DisjunctionScorer"/>, <see cref="ReqOptSumScorer"/> and <see cref="ReqExclScorer"/>. /// </summary> internal class BooleanScorer2 : Scorer { private readonly IList<Scorer> requiredScorers; private readonly IList<Scorer> optionalScorers; private readonly IList<Scorer> prohibitedScorers; private class Coordinator { private readonly BooleanScorer2 outerInstance; internal readonly float[] coordFactors; internal Coordinator(BooleanScorer2 outerInstance, int maxCoord, bool disableCoord) { this.outerInstance = outerInstance; coordFactors = new float[outerInstance.optionalScorers.Count + outerInstance.requiredScorers.Count + 1]; for (int i = 0; i < coordFactors.Length; i++) { coordFactors[i] = disableCoord ? 1.0f : ((BooleanWeight)outerInstance.m_weight).Coord(i, maxCoord); } } internal int nrMatchers; // to be increased by score() of match counting scorers. } private readonly Coordinator coordinator; /// <summary> /// The scorer to which all scoring will be delegated, /// except for computing and using the coordination factor. /// </summary> private readonly Scorer countingSumScorer; /// <summary> /// The number of optionalScorers that need to match (if there are any) </summary> private readonly int minNrShouldMatch; private int doc = -1; /// <summary> /// Creates a <see cref="Scorer"/> with the given similarity and lists of required, /// prohibited and optional scorers. In no required scorers are added, at least /// one of the optional scorers will have to match during the search. /// </summary> /// <param name="weight"> /// The <see cref="BooleanWeight"/> to be used. </param> /// <param name="disableCoord"> /// If this parameter is <c>true</c>, coordination level matching /// (<see cref="Similarities.Similarity.Coord(int, int)"/>) is not used. </param> /// <param name="minNrShouldMatch"> /// The minimum number of optional added scorers that should match /// during the search. In case no required scorers are added, at least /// one of the optional scorers will have to match during the search. </param> /// <param name="required"> /// The list of required scorers. </param> /// <param name="prohibited"> /// The list of prohibited scorers. </param> /// <param name="optional"> /// The list of optional scorers. </param> /// <param name="maxCoord"> /// The max coord. </param> public BooleanScorer2(BooleanWeight weight, bool disableCoord, int minNrShouldMatch, IList<Scorer> required, IList<Scorer> prohibited, IList<Scorer> optional, int maxCoord) : base(weight) { if (minNrShouldMatch < 0) { throw new System.ArgumentException("Minimum number of optional scorers should not be negative"); } this.minNrShouldMatch = minNrShouldMatch; optionalScorers = optional; requiredScorers = required; prohibitedScorers = prohibited; coordinator = new Coordinator(this, maxCoord, disableCoord); countingSumScorer = MakeCountingSumScorer(disableCoord); } /// <summary> /// Count a scorer as a single match. </summary> private class SingleMatchScorer : Scorer { private readonly BooleanScorer2 outerInstance; internal Scorer scorer; internal int lastScoredDoc = -1; // Save the score of lastScoredDoc, so that we don't compute it more than // once in score(). internal float lastDocScore = float.NaN; internal SingleMatchScorer(BooleanScorer2 outerInstance, Scorer scorer) : base(scorer.m_weight) { this.outerInstance = outerInstance; this.scorer = scorer; } public override float GetScore() { int doc = DocID; if (doc >= lastScoredDoc) { if (doc > lastScoredDoc) { lastDocScore = scorer.GetScore(); lastScoredDoc = doc; } outerInstance.coordinator.nrMatchers++; } return lastDocScore; } public override int Freq { get { return 1; } } public override int DocID { get { return scorer.DocID; } } public override int NextDoc() { return scorer.NextDoc(); } public override int Advance(int target) { return scorer.Advance(target); } public override long GetCost() { return scorer.GetCost(); } } private Scorer CountingDisjunctionSumScorer(IList<Scorer> scorers, int minNrShouldMatch) { // each scorer from the list counted as a single matcher if (minNrShouldMatch > 1) { return new MinShouldMatchSumScorerAnonymousInnerClassHelper(this, m_weight, scorers, minNrShouldMatch); } else { // we pass null for coord[] since we coordinate ourselves and override score() return new DisjunctionSumScorerAnonymousInnerClassHelper(this, m_weight, scorers.ToArray(), null); } } private class MinShouldMatchSumScorerAnonymousInnerClassHelper : MinShouldMatchSumScorer { private readonly BooleanScorer2 outerInstance; public MinShouldMatchSumScorerAnonymousInnerClassHelper(BooleanScorer2 outerInstance, Lucene.Net.Search.Weight weight, IList<Scorer> scorers, int minNrShouldMatch) : base(weight, scorers, minNrShouldMatch) { this.outerInstance = outerInstance; } public override float GetScore() { outerInstance.coordinator.nrMatchers += base.m_nrMatchers; return base.GetScore(); } } private class DisjunctionSumScorerAnonymousInnerClassHelper : DisjunctionSumScorer { private readonly BooleanScorer2 outerInstance; public DisjunctionSumScorerAnonymousInnerClassHelper(BooleanScorer2 outerInstance, Weight weight, Scorer[] subScorers, float[] coord) : base(weight, subScorers, coord) { this.outerInstance = outerInstance; } public override float GetScore() { outerInstance.coordinator.nrMatchers += base.m_nrMatchers; return (float)base.m_score; } } private Scorer CountingConjunctionSumScorer(bool disableCoord, IList<Scorer> requiredScorers) { // each scorer from the list counted as a single matcher int requiredNrMatchers = requiredScorers.Count; return new ConjunctionScorerAnonymousInnerClassHelper(this, m_weight, requiredScorers.ToArray(), requiredNrMatchers); } private class ConjunctionScorerAnonymousInnerClassHelper : ConjunctionScorer { private readonly BooleanScorer2 outerInstance; private int requiredNrMatchers; public ConjunctionScorerAnonymousInnerClassHelper(BooleanScorer2 outerInstance, Weight weight, Scorer[] scorers, int requiredNrMatchers) : base(weight, scorers) { this.outerInstance = outerInstance; this.requiredNrMatchers = requiredNrMatchers; lastScoredDoc = -1; lastDocScore = float.NaN; } private int lastScoredDoc; // Save the score of lastScoredDoc, so that we don't compute it more than // once in score(). private float lastDocScore; public override float GetScore() { int doc = outerInstance.DocID; if (doc >= lastScoredDoc) { if (doc > lastScoredDoc) { lastDocScore = base.GetScore(); lastScoredDoc = doc; } outerInstance.coordinator.nrMatchers += requiredNrMatchers; } // All scorers match, so defaultSimilarity super.score() always has 1 as // the coordination factor. // Therefore the sum of the scores of the requiredScorers // is used as score. return lastDocScore; } } private Scorer DualConjunctionSumScorer(bool disableCoord, Scorer req1, Scorer req2) // non counting. { return new ConjunctionScorer(m_weight, new Scorer[] { req1, req2 }); // All scorers match, so defaultSimilarity always has 1 as // the coordination factor. // Therefore the sum of the scores of two scorers // is used as score. } /// <summary> /// Returns the scorer to be used for match counting and score summing. /// Uses requiredScorers, optionalScorers and prohibitedScorers. /// </summary> private Scorer MakeCountingSumScorer(bool disableCoord) // each scorer counted as a single matcher { return (requiredScorers.Count == 0) ? MakeCountingSumScorerNoReq(disableCoord) : MakeCountingSumScorerSomeReq(disableCoord); } private Scorer MakeCountingSumScorerNoReq(bool disableCoord) // No required scorers { // minNrShouldMatch optional scorers are required, but at least 1 int nrOptRequired = (minNrShouldMatch < 1) ? 1 : minNrShouldMatch; Scorer requiredCountingSumScorer; if (optionalScorers.Count > nrOptRequired) { requiredCountingSumScorer = CountingDisjunctionSumScorer(optionalScorers, nrOptRequired); } else if (optionalScorers.Count == 1) { requiredCountingSumScorer = new SingleMatchScorer(this, optionalScorers[0]); } else { requiredCountingSumScorer = CountingConjunctionSumScorer(disableCoord, optionalScorers); } return AddProhibitedScorers(requiredCountingSumScorer); } private Scorer MakeCountingSumScorerSomeReq(bool disableCoord) // At least one required scorer. { if (optionalScorers.Count == minNrShouldMatch) // all optional scorers also required. { List<Scorer> allReq = new List<Scorer>(requiredScorers); allReq.AddRange(optionalScorers); return AddProhibitedScorers(CountingConjunctionSumScorer(disableCoord, allReq)); } // optionalScorers.size() > minNrShouldMatch, and at least one required scorer else { Scorer requiredCountingSumScorer = requiredScorers.Count == 1 ? new SingleMatchScorer(this, requiredScorers[0]) : CountingConjunctionSumScorer(disableCoord, requiredScorers); if (minNrShouldMatch > 0) // use a required disjunction scorer over the optional scorers { return AddProhibitedScorers(DualConjunctionSumScorer(disableCoord, requiredCountingSumScorer, CountingDisjunctionSumScorer(optionalScorers, minNrShouldMatch))); // non counting } // minNrShouldMatch == 0 else { return new ReqOptSumScorer(AddProhibitedScorers(requiredCountingSumScorer), optionalScorers.Count == 1 ? new SingleMatchScorer(this, optionalScorers[0]) // require 1 in combined, optional scorer. : CountingDisjunctionSumScorer(optionalScorers, 1)); } } } /// <summary> /// Returns the scorer to be used for match counting and score summing. /// Uses the given required scorer and the prohibitedScorers. </summary> /// <param name="requiredCountingSumScorer"> A required scorer already built. </param> private Scorer AddProhibitedScorers(Scorer requiredCountingSumScorer) { return (prohibitedScorers.Count == 0) ? requiredCountingSumScorer : new ReqExclScorer(requiredCountingSumScorer, ((prohibitedScorers.Count == 1) ? prohibitedScorers[0] : new MinShouldMatchSumScorer(m_weight, prohibitedScorers))); // no prohibited } public override int DocID { get { return doc; } } public override int NextDoc() { return doc = countingSumScorer.NextDoc(); } public override float GetScore() { coordinator.nrMatchers = 0; float sum = countingSumScorer.GetScore(); return sum * coordinator.coordFactors[coordinator.nrMatchers]; } public override int Freq { get { return countingSumScorer.Freq; } } public override int Advance(int target) { return doc = countingSumScorer.Advance(target); } public override long GetCost() { return countingSumScorer.GetCost(); } public override ICollection<ChildScorer> GetChildren() { List<ChildScorer> children = new List<ChildScorer>(); foreach (Scorer s in optionalScorers) { children.Add(new ChildScorer(s, "SHOULD")); } foreach (Scorer s in prohibitedScorers) { children.Add(new ChildScorer(s, "MUST_NOT")); } foreach (Scorer s in requiredScorers) { children.Add(new ChildScorer(s, "MUST")); } return children; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: MemoryStream ** ** <OWNER>[....]</OWNER> ** ** ** Purpose: A Stream whose backing store is memory. Great ** for temporary storage without creating a temp file. Also ** lets users expose a byte[] as a stream. ** ** ===========================================================*/ using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; #if FEATURE_ASYNC_IO using System.Threading; using System.Threading.Tasks; using System.Security.Permissions; #endif namespace System.IO { // A MemoryStream represents a Stream in memory (ie, it has no backing store). // This stream may reduce the need for temporary buffers and files in // an application. // // There are two ways to create a MemoryStream. You can initialize one // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. [Serializable] [ComVisible(true)] public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. private int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. [ContractPublicPropertyName("Length")] private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream // Note that _capacity == _buffer.Length for non-user-provided byte[]'s private bool _expandable; // User-provided buffers aren't expandable. private bool _writable; // Can user write to this stream? private bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? #if FEATURE_ASYNC_IO [NonSerialized] private Task<int> _lastReadTask; // The last successful task returned from ReadAsync #endif // < private const int MemStreamMaxLength = Int32.MaxValue; public MemoryStream() : this(0) { } public MemoryStream(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity")); } Contract.EndContractBlock(); _buffer = new byte[capacity]; _capacity = capacity; _expandable = true; _writable = true; _exposable = true; _origin = 0; // Must be 0 for byte[]'s created by MemoryStream _isOpen = true; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public MemoryStream(byte[] buffer) : this(buffer, true) { } public MemoryStream(byte[] buffer, bool writable) { if (buffer == null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); Contract.EndContractBlock(); _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; _exposable = false; _origin = 0; _isOpen = true; } public MemoryStream(byte[] buffer, int index, int count) : this(buffer, index, count, true, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable) : this(buffer, index, count, writable, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); _buffer = buffer; _origin = _position = index; _length = _capacity = index + count; _writable = writable; _exposable = publiclyVisible; // Can GetBuffer return the array? _expandable = false; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _writable; } } private void EnsureWriteable() { // Previously, instead of calling CanWrite we just checked the _writable field directly, and some code // took a dependency on that behavior. #if FEATURE_CORECLR if (IsAppEarlierThanSl4) { if (!_writable) __Error.WriteNotSupported(); } else { if (!CanWrite) __Error.WriteNotSupported(); } #else if (!CanWrite) __Error.WriteNotSupported(); #endif } protected override void Dispose(bool disposing) { try { if (disposing) { _isOpen = false; _writable = false; _expandable = false; // Don't set buffer to null - allow GetBuffer & ToArray to work. #if FEATURE_ASYNC_IO _lastReadTask = null; #endif } } finally { // Call base.Close() to cleanup async IO resources base.Dispose(disposing); } } // returns a bool saying whether we allocated a new array. private bool EnsureCapacity(int value) { // Check for overflow if (value < 0) throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); if (value > _capacity) { int newCapacity = value; if (newCapacity < 256) newCapacity = 256; if (newCapacity < _capacity * 2) newCapacity = _capacity * 2; Capacity = newCapacity; return true; } return false; } public override void Flush() { } #if FEATURE_ASYNC_IO [HostProtection(ExternalThreading=true)] [ComVisible(false)] public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCancellation(cancellationToken); try { Flush(); return Task.CompletedTask; } catch(Exception ex) { return Task.FromException(ex); } } #endif // FEATURE_ASYNC_IO #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public virtual byte[] GetBuffer() { if (!_exposable) throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer")); return _buffer; } // -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) --------------- // PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer()) #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif internal byte[] InternalGetBuffer() { return _buffer; } // PERF: Get origin and length - used in ResourceWriter. #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif [FriendAccessAllowed] internal void InternalGetOriginAndLength(out int origin, out int length) { if (!_isOpen) __Error.StreamIsClosed(); origin = _origin; length = _length; } // PERF: True cursor position, we don't need _origin for direct access #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif internal int InternalGetPosition() { if (!_isOpen) __Error.StreamIsClosed(); return _position; } // PERF: Takes out Int32 as fast as possible internal int InternalReadInt32() { if (!_isOpen) __Error.StreamIsClosed(); int pos = (_position += 4); // use temp to avoid ---- if (pos > _length) { _position = _length; __Error.EndOfFile(); } return (int)(_buffer[pos-4] | _buffer[pos-3] << 8 | _buffer[pos-2] << 16 | _buffer[pos-1] << 24); } // PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes internal int InternalEmulateRead(int count) { if (!_isOpen) __Error.StreamIsClosed(); int n = _length - _position; if (n > count) n = count; if (n < 0) n = 0; Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. _position += n; return n; } // Gets & sets the capacity (number of bytes allocated) for this stream. // The capacity cannot be set to a value less than the current length // of the stream. // public virtual int Capacity { get { if (!_isOpen) __Error.StreamIsClosed(); return _capacity - _origin; } set { // Only update the capacity if the MS is expandable and the value is different than the current capacity. // Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity #if !FEATURE_CORECLR if (value < Length) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); #endif Contract.Ensures(_capacity - _origin == value); Contract.EndContractBlock(); #if FEATURE_CORECLR if (IsAppEarlierThanSl4) { if (value < _length) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); } else { if (value < Length) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); } #endif if (!_isOpen) __Error.StreamIsClosed(); if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable(); // MemoryStream has this invariant: _origin > 0 => !expandable (see ctors) if (_expandable && value != _capacity) { if (value > 0) { byte[] newBuffer = new byte[value]; if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length); _buffer = newBuffer; } else { _buffer = null; } _capacity = value; } } } public override long Length { #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif get { if (!_isOpen) __Error.StreamIsClosed(); return _length - _origin; } } public override long Position { #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif get { if (!_isOpen) __Error.StreamIsClosed(); return _position - _origin; } set { if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.Ensures(Position == value); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); if (value > MemStreamMaxLength) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); _position = _origin + (int)value; } } #if FEATURE_CORECLR private static bool IsAppEarlierThanSl4 { get { return CompatibilitySwitches.IsAppEarlierThanSilverlight4; } } #endif public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); int n = _length - _position; if (n > count) n = count; if (n <= 0) return 0; Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. if (n <= 8) { int byteCount = n; while (--byteCount >= 0) buffer[offset + byteCount] = _buffer[_position + byteCount]; } else Buffer.InternalBlockCopy(_buffer, _position, buffer, offset, n); _position += n; return n; } #if FEATURE_ASYNC_IO [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // contract validation copied from Read(...) // If cancellation was requested, bail early if (cancellationToken.IsCancellationRequested) return Task.FromCancellation<int>(cancellationToken); try { int n = Read(buffer, offset, count); var t = _lastReadTask; Contract.Assert(t == null || t.Status == TaskStatus.RanToCompletion, "Expected that a stored last task completed successfully"); return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n)); } catch (OperationCanceledException oce) { return Task.FromCancellation<int>(oce); } catch (Exception exception) { return Task.FromException<int>(exception); } } #endif //FEATURE_ASYNC_IO public override int ReadByte() { if (!_isOpen) __Error.StreamIsClosed(); if (_position >= _length) return -1; return _buffer[_position++]; } #if FEATURE_ASYNC_IO public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { // This implementation offers beter performance compared to the base class version. // The parameter checks must be in [....] with the base version: if (destination == null) throw new ArgumentNullException("destination"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); if (!CanRead && !CanWrite) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed")); if (!destination.CanRead && !destination.CanWrite) throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed")); if (!CanRead) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream")); if (!destination.CanWrite) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream")); Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() or Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read/Write) when we are not sure. if (this.GetType() != typeof(MemoryStream)) return base.CopyToAsync(destination, bufferSize, cancellationToken); // If cancelled - return fast: if (cancellationToken.IsCancellationRequested) return Task.FromCancellation(cancellationToken); // Avoid copying data from this buffer into a temp buffer: // (require that InternalEmulateRead does not throw, // otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below) Int32 pos = _position; Int32 n = InternalEmulateRead(_length - _position); // If destination is not a memory stream, write there asynchronously: MemoryStream memStrDest = destination as MemoryStream; if (memStrDest == null) return destination.WriteAsync(_buffer, pos, n, cancellationToken); try { // If destination is a MemoryStream, CopyTo synchronously: memStrDest.Write(_buffer, pos, n); return Task.CompletedTask; } catch(Exception ex) { return Task.FromException(ex); } } #endif //FEATURE_ASYNC_IO public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) __Error.StreamIsClosed(); if (offset > MemStreamMaxLength) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); switch(loc) { case SeekOrigin.Begin: { int tempPosition = unchecked(_origin + (int)offset); if (offset < 0 || tempPosition < _origin) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); _position = tempPosition; break; } case SeekOrigin.Current: { int tempPosition = unchecked(_position + (int)offset); if (unchecked(_position + offset) < _origin || tempPosition < _origin) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); _position = tempPosition; break; } case SeekOrigin.End: { int tempPosition = unchecked(_length + (int)offset); if ( unchecked(_length + offset) < _origin || tempPosition < _origin ) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); _position = tempPosition; break; } default: throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin")); } Contract.Assert(_position >= 0, "_position >= 0"); return _position; } // Sets the length of the stream to a given value. The new // value must be nonnegative and less than the space remaining in // the array, Int32.MaxValue - origin // Origin is 0 in all cases other than a MemoryStream created on // top of an existing array and a specific starting offset was passed // into the MemoryStream constructor. The upper bounds prevents any // situations where a stream may be created on top of an array then // the stream is made longer than the maximum possible length of the // array (Int32.MaxValue). // public override void SetLength(long value) { if (value < 0 || value > Int32.MaxValue) { throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } Contract.Ensures(_length - _origin == value); Contract.EndContractBlock(); EnsureWriteable(); // Origin wasn't publicly exposed above. Contract.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails. if (value > (Int32.MaxValue - _origin)) { throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } int newLength = _origin + (int)value; bool allocatedNewArray = EnsureCapacity(newLength); if (!allocatedNewArray && newLength > _length) Array.Clear(_buffer, _length, newLength - _length); _length = newLength; if (_position > newLength) _position = newLength; } public virtual byte[] ToArray() { #if MONO // Bug fix for BCL bug when _buffer is null if (_length - _origin == 0) return EmptyArray<byte>.Value; #endif BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy."); byte[] copy = new byte[_length - _origin]; Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin); return copy; } public override void Write(byte[] buffer, int offset, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); EnsureWriteable(); int i = _position + count; // Check for overflow if (i < 0) throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); if (i > _length) { bool mustZero = _position > _length; if (i > _capacity) { bool allocatedNewArray = EnsureCapacity(i); if (allocatedNewArray) mustZero = false; } if (mustZero) Array.Clear(_buffer, _length, i - _length); _length = i; } if ((count <= 8) && (buffer != _buffer)) { int byteCount = count; while (--byteCount >= 0) _buffer[_position + byteCount] = buffer[offset + byteCount]; } else Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count); _position = i; } #if FEATURE_ASYNC_IO [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // contract validation copied from Write(...) // If cancellation is already requested, bail early if (cancellationToken.IsCancellationRequested) return Task.FromCancellation(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (OperationCanceledException oce) { return Task.FromCancellation<VoidTaskResult>(oce); } catch (Exception exception) { return Task.FromException(exception); } } #endif // FEATURE_ASYNC_IO public override void WriteByte(byte value) { if (!_isOpen) __Error.StreamIsClosed(); EnsureWriteable(); if (_position >= _length) { int newLength = _position + 1; bool mustZero = _position > _length; if (newLength >= _capacity) { bool allocatedNewArray = EnsureCapacity(newLength); if (allocatedNewArray) mustZero = false; } if (mustZero) Array.Clear(_buffer, _length, _position - _length); _length = newLength; } _buffer[_position++] = value; } // Writes this MemoryStream to another stream. public virtual void WriteTo(Stream stream) { if (stream==null) throw new ArgumentNullException("stream", Environment.GetResourceString("ArgumentNull_Stream")); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); stream.Write(_buffer, _origin, _length - _origin); } #if CONTRACTS_FULL [ContractInvariantMethod] private void ObjectInvariantMS() { Contract.Invariant(_origin >= 0); Contract.Invariant(_origin <= _position); Contract.Invariant(_length <= _capacity); // equivalent to _origin > 0 => !expandable, and using fact that _origin is non-negative. Contract.Invariant(_origin == 0 || !_expandable); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Scripting; using Microsoft.Scripting.Ast; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime { /// <summary> /// Python module. Stores classes, functions, and data. Usually a module /// is created by importing a file or package from disk. But a module can also /// be directly created by calling the module type and providing a name or /// optionally a documentation string. /// </summary> [PythonType("module"), DebuggerTypeProxy(typeof(PythonModule.DebugProxy)), DebuggerDisplay("module: {GetName()}")] public class PythonModule : IDynamicMetaObjectProvider, IPythonMembersList { private readonly PythonDictionary _dict; private Scope _scope; public PythonModule() { _dict = new PythonDictionary(); if (GetType() != typeof(PythonModule) && this is IPythonObject) { // we should share the user dict w/ our dict. ((IPythonObject)this).ReplaceDict(_dict); } } /// <summary> /// Creates a new module backed by a Scope. Used for creating modules for foreign Scope's. /// </summary> internal PythonModule(PythonContext context, Scope scope) { _dict = new PythonDictionary(new ScopeDictionaryStorage(context, scope)); _scope = scope; } /// <summary> /// Creates a new PythonModule with the specified dictionary. /// /// Used for creating modules for builtin modules which don't have any code associated with them. /// </summary> internal PythonModule(PythonDictionary dict) { _dict = dict; } public static PythonModule/*!*/ __new__(CodeContext/*!*/ context, PythonType/*!*/ cls, params object[]/*!*/ args\u00F8) { PythonModule res; if (cls == TypeCache.Module) { res = new PythonModule(); } else if (cls.IsSubclassOf(TypeCache.Module)) { res = (PythonModule)cls.CreateInstance(context); } else { throw PythonOps.TypeError("{0} is not a subtype of module", cls.Name); } return res; } [StaticExtensionMethod] public static PythonModule/*!*/ __new__(CodeContext/*!*/ context, PythonType/*!*/ cls, [ParamDictionary]IDictionary<object, object> kwDict0, params object[]/*!*/ args\u00F8) { return __new__(context, cls, args\u00F8); } public void __init__(string name) { __init__(name, null); } public void __init__(string name, string doc) { _dict["__doc__"] = doc; _dict["__loader__"] = null; _dict["__name__"] = name; _dict["__package__"] = null; _dict["__spec__"] = null; } public object __getattribute__(CodeContext/*!*/ context, string name) { PythonTypeSlot slot; object res; if (GetType() != typeof(PythonModule) && DynamicHelpers.GetPythonType(this).TryResolveSlot(context, name, out slot) && slot.TryGetValue(context, this, DynamicHelpers.GetPythonType(this), out res)) { return res; } switch (name) { // never look in the dict for these... case "__dict__": return __dict__; case "__class__": return DynamicHelpers.GetPythonType(this); } if (_dict.TryGetValue(name, out res)) { return res; } // fall back to object to provide all of our other attributes (e.g. __setattr__, etc...) return ObjectOps.__getattribute__(context, this, name); } internal object GetAttributeNoThrow(CodeContext/*!*/ context, string name) { PythonTypeSlot slot; object res; if (GetType() != typeof(PythonModule) && DynamicHelpers.GetPythonType(this).TryResolveSlot(context, name, out slot) && slot.TryGetValue(context, this, DynamicHelpers.GetPythonType(this), out res)) { return res; } switch (name) { // never look in the dict for these... case "__dict__": return __dict__; case "__class__": return DynamicHelpers.GetPythonType(this); } if (_dict.TryGetValue(name, out res)) { return res; } else if (DynamicHelpers.GetPythonType(this).TryGetNonCustomMember(context, this, name, out res)) { return res; } else if (DynamicHelpers.GetPythonType(this).TryResolveSlot(context, "__getattr__", out slot) && slot.TryGetValue(context, this, DynamicHelpers.GetPythonType(this), out res)) { return PythonCalls.Call(context, res, name); } return OperationFailed.Value; } public void __setattr__(CodeContext/*!*/ context, string name, object value) { PythonTypeSlot slot; if (GetType() != typeof(PythonModule) && DynamicHelpers.GetPythonType(this).TryResolveSlot(context, name, out slot) && slot.TrySetValue(context, this, DynamicHelpers.GetPythonType(this), value)) { return; } switch (name) { case "__dict__": throw PythonOps.AttributeError("readonly attribute"); case "__class__": throw PythonOps.TypeError("__class__ assignment: only for heap types"); } Debug.Assert(value != Uninitialized.Instance); _dict[name] = value; } public void __delattr__(CodeContext/*!*/ context, string name) { PythonTypeSlot slot; if (GetType() != typeof(PythonModule) && DynamicHelpers.GetPythonType(this).TryResolveSlot(context, name, out slot) && slot.TryDeleteValue(context, this, DynamicHelpers.GetPythonType(this))) { return; } switch (name) { case "__dict__": throw PythonOps.AttributeError("readonly attribute"); case "__class__": throw PythonOps.TypeError("can't delete __class__ attribute"); } object value; if (!_dict.TryRemoveValue(name, out value)) { throw PythonOps.AttributeErrorForMissingAttribute("module", name); } } public string/*!*/ __repr__() { return __str__(); } public string/*!*/ __str__() { object fileObj, nameObj; if (!_dict.TryGetValue("__file__", out fileObj)) { fileObj = null; } if (!_dict._storage.TryGetName(out nameObj)) { nameObj = null; } string file = fileObj as string; string name = nameObj as string ?? "?"; if (file == null) { return String.Format("<module '{0}' (built-in)>", name); } return String.Format("<module '{0}' from '{1}'>", name, file); } internal PythonDictionary __dict__ { get { return _dict; } } [SpecialName, PropertyMethod] public PythonDictionary Get__dict__() { return _dict; } [SpecialName, PropertyMethod] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public void Set__dict__(object value) { throw PythonOps.AttributeError("readonly attribute"); } [SpecialName, PropertyMethod] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public void Delete__dict__() { throw PythonOps.AttributeError("readonly attribute"); } public Scope Scope { get { if (_scope == null) { Interlocked.CompareExchange(ref _scope, new Scope(new ObjectDictionaryExpando(_dict)), null); } return _scope; } } #region IDynamicMetaObjectProvider Members [PythonHidden] // needs to be public so that we can override it. public DynamicMetaObject GetMetaObject(Expression parameter) { return new MetaModule(this, parameter); } #endregion private class MetaModule : MetaPythonObject, IPythonGetable { public MetaModule(PythonModule module, Expression self) : base(self, BindingRestrictions.Empty, module) { } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { return GetMemberWorker(binder, PythonContext.GetCodeContextMO(binder)); } #region IPythonGetable Members public DynamicMetaObject GetMember(PythonGetMemberBinder member, DynamicMetaObject codeContext) { return GetMemberWorker(member, codeContext); } #endregion private DynamicMetaObject GetMemberWorker(DynamicMetaObjectBinder binder, DynamicMetaObject codeContext) { string name = GetGetMemberName(binder); var tmp = Expression.Variable(typeof(object), "res"); return new DynamicMetaObject( Expression.Block( new[] { tmp }, Expression.Condition( Expression.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.ModuleTryGetMember)), PythonContext.GetCodeContext(binder), Utils.Convert(Expression, typeof(PythonModule)), Expression.Constant(name), tmp ), tmp, Expression.Convert(GetMemberFallback(this, binder, codeContext).Expression, typeof(object)) ) ), BindingRestrictions.GetTypeRestriction(Expression, Value.GetType()) ); } public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) { return BindingHelpers.GenericInvokeMember(action, null, this, args); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { Debug.Assert(value.Value != Uninitialized.Instance); return new DynamicMetaObject( Expression.Block( Expression.Call( Utils.Convert(Expression, typeof(PythonModule)), typeof(PythonModule).GetMethod(nameof(PythonModule.__setattr__)), PythonContext.GetCodeContext(binder), Expression.Constant(binder.Name), Expression.Convert(value.Expression, typeof(object)) ), Expression.Convert(value.Expression, typeof(object)) ), BindingRestrictions.GetTypeRestriction(Expression, Value.GetType()) ); } public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { return new DynamicMetaObject( Expression.Call( Utils.Convert(Expression, typeof(PythonModule)), typeof(PythonModule).GetMethod(nameof(PythonModule.__delattr__)), PythonContext.GetCodeContext(binder), Expression.Constant(binder.Name) ), BindingRestrictions.GetTypeRestriction(Expression, Value.GetType()) ); } public override IEnumerable<string> GetDynamicMemberNames() { foreach (object o in ((PythonModule)Value).__dict__.Keys) { if (o is string str) { yield return str; } } } } internal bool IsBuiltin => GetFile() is null; internal string GetFile() { object res; if (_dict.TryGetValue("__file__", out res)) { return res as string; } return null; } internal string GetName() { object res; if (_dict._storage.TryGetName(out res)) { return res as string; } return null; } #region IPythonMembersList Members IList<object> IPythonMembersList.GetMemberNames(CodeContext context) { return new List<object>(__dict__.Keys); } #endregion #region IMembersList Members IList<string> IMembersList.GetMemberNames() { var keys = __dict__.Keys; List<string> res = new List<string>(keys.Count); foreach (object o in keys) { if (o is string strKey) { res.Add(strKey); } } return res; } #endregion internal class DebugProxy { private readonly PythonModule _module; public DebugProxy(PythonModule module) { _module = module; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public List<ObjectDebugView> Members { get { var res = new List<ObjectDebugView>(); foreach (var v in _module._dict) { res.Add(new ObjectDebugView(v.Key, v.Value)); } return res; } } } } }
using System.Collections.Generic; using AsmResolver.DotNet.Signatures; using AsmResolver.DotNet.Signatures.Types; using AsmResolver.PE.DotNet.Metadata.Tables.Rows; using Xunit; namespace AsmResolver.DotNet.Tests.Signatures { public class GenericContextTest { private readonly ReferenceImporter _importer; public GenericContextTest() { var module = new ModuleDefinition("TempModule"); _importer = new ReferenceImporter(module); } [Theory] [InlineData(GenericParameterType.Type)] [InlineData(GenericParameterType.Method)] public void ResolveGenericParameterWithEmptyType(GenericParameterType parameterType) { var context = new GenericContext(); var parameter = new GenericParameterSignature(parameterType, 0); Assert.Equal(parameter, context.GetTypeArgument(parameter)); } [Fact] public void ResolveMethodGenericParameterWithMethod() { var genericInstance = new GenericInstanceMethodSignature(); genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var context = new GenericContext(null, genericInstance); var parameter = new GenericParameterSignature(GenericParameterType.Method, 0); Assert.Equal("System.String", context.GetTypeArgument(parameter).FullName); } [Fact] public void ResolveTypeGenericParameterWithType() { var genericInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false); genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var context = new GenericContext(genericInstance, null); var parameter = new GenericParameterSignature(GenericParameterType.Type, 0); Assert.Equal("System.String", context.GetTypeArgument(parameter).FullName); } [Fact] public void ResolveTypeGenericParameterWithTypeAndMethod() { var genericType = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false); genericType.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var genericMethod = new GenericInstanceMethodSignature(); genericMethod.TypeArguments.Add(_importer.ImportTypeSignature(typeof(int))); var context = new GenericContext(genericType, genericMethod); var parameter = new GenericParameterSignature(GenericParameterType.Type, 0); Assert.Equal("System.String", context.GetTypeArgument(parameter).FullName); } [Fact] public void ResolveMethodGenericParameterWithTypeAndMethod() { var genericType = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false); genericType.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var genericMethod = new GenericInstanceMethodSignature(); genericMethod.TypeArguments.Add(_importer.ImportTypeSignature(typeof(int))); var context = new GenericContext(genericType, genericMethod); var parameter = new GenericParameterSignature(GenericParameterType.Method, 0); Assert.Equal("System.Int32", context.GetTypeArgument(parameter).FullName); } [Fact] public void ResolveTypeGenericParameterWithOnlyMethod() { var genericInstance = new GenericInstanceMethodSignature(); genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var context = new GenericContext(null, genericInstance); var parameter = new GenericParameterSignature(GenericParameterType.Type, 0); Assert.Equal(parameter, context.GetTypeArgument(parameter)); } [Fact] public void ResolveMethodGenericParameterWithOnlyType() { var genericInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false); genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var context = new GenericContext(genericInstance, null); var parameter = new GenericParameterSignature(GenericParameterType.Method, 0); Assert.Equal(parameter, context.GetTypeArgument(parameter)); } [Fact] public void ParseGenericFromTypeSignature() { var genericInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false); genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var context = GenericContext.FromType(genericInstance); var context2 = GenericContext.FromMember(genericInstance); var context3 = GenericContext.FromType((ITypeDescriptor) genericInstance); Assert.Equal(context, context3); Assert.Equal(context, context2); Assert.False(context.IsEmpty); Assert.Equal(genericInstance, context.Type); Assert.Null(context.Method); } [Fact] public void ParseGenericFromNonGenericTypeSignature() { var type = new TypeDefinition("", "Test type", TypeAttributes.Public); var notGenericSignature = new TypeDefOrRefSignature(type); var context = GenericContext.FromType(notGenericSignature); var context2 = GenericContext.FromMember(notGenericSignature); Assert.Equal(context, context2); Assert.True(context.IsEmpty); } [Fact] public void ParseGenericFromTypeSpecification() { var genericInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false); genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var typeSpecification = new TypeSpecification(genericInstance); var context = GenericContext.FromType(typeSpecification); var context2 = GenericContext.FromMember(typeSpecification); var context3 = GenericContext.FromType((ITypeDescriptor) typeSpecification); Assert.Equal(context, context3); Assert.Equal(context, context2); Assert.False(context.IsEmpty); Assert.Equal(genericInstance, context.Type); Assert.Null(context.Method); } [Fact] public void ParseGenericFromMethodSpecification() { var genericParameter = new GenericParameterSignature(GenericParameterType.Method, 0); var method = new MethodDefinition("TestMethod", MethodAttributes.Private, MethodSignature.CreateStatic(genericParameter)); var genericInstance = new GenericInstanceMethodSignature(); genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(int))); var methodSpecification = new MethodSpecification(method, genericInstance); var context = GenericContext.FromMethod(methodSpecification); var context2 = GenericContext.FromMember(methodSpecification); var context3 = GenericContext.FromMethod((IMethodDescriptor) methodSpecification); Assert.Equal(context, context3); Assert.Equal(context, context2); Assert.False(context.IsEmpty); Assert.Null(context.Type); Assert.Equal(genericInstance, context.Method); } [Fact] public void ParseGenericFromMethodSpecificationWithTypeSpecification() { var genericTypeInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false); genericTypeInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var typeSpecification = new TypeSpecification(genericTypeInstance); var genericParameter = new GenericParameterSignature(GenericParameterType.Method, 0); var method = new MemberReference(typeSpecification, "TestMethod", MethodSignature.CreateStatic(genericParameter)); var genericMethodInstance = new GenericInstanceMethodSignature(); genericMethodInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(int))); var methodSpecification = new MethodSpecification(method, genericMethodInstance); var context = GenericContext.FromMethod(methodSpecification); var context2 = GenericContext.FromMember(methodSpecification); var context3 = GenericContext.FromMethod((IMethodDescriptor) methodSpecification); Assert.Equal(context, context3); Assert.Equal(context, context2); Assert.False(context.IsEmpty); Assert.Equal(genericTypeInstance, context.Type); Assert.Equal(genericMethodInstance, context.Method); } [Fact] public void ParseGenericFromNotGenericTypeSpecification() { var type = new TypeDefinition("", "Test type", TypeAttributes.Public); var notGenericSignature = new TypeDefOrRefSignature(type); var typeSpecification = new TypeSpecification(notGenericSignature); var context = GenericContext.FromType(typeSpecification); var context2 = GenericContext.FromMember(typeSpecification); var context3 = GenericContext.FromType((ITypeDescriptor) typeSpecification); Assert.Equal(context, context3); Assert.Equal(context, context2); Assert.True(context.IsEmpty); } [Fact] public void ParseGenericFromNotGenericMethodSpecification() { var type = new TypeDefinition("", "Test type", TypeAttributes.Public); var notGenericSignature = new TypeDefOrRefSignature(type); var method = new MethodDefinition("TestMethod", MethodAttributes.Private, MethodSignature.CreateStatic(notGenericSignature)); var methodSpecification = new MethodSpecification(method, null); var context = GenericContext.FromMethod(methodSpecification); var context2 = GenericContext.FromMember(methodSpecification); var context3 = GenericContext.FromMethod((IMethodDescriptor) methodSpecification); Assert.Equal(context, context3); Assert.Equal(context, context2); Assert.True(context.IsEmpty); } [Fact] public void ParseGenericFromNotGenericMethodSpecificationWithTypeSpecification() { var genericTypeInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false); genericTypeInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var typeSpecification = new TypeSpecification(genericTypeInstance); var type = new TypeDefinition("", "Test type", TypeAttributes.Public); var notGenericSignature = new TypeDefOrRefSignature(type); var method = new MemberReference(typeSpecification, "TestMethod", MethodSignature.CreateStatic(notGenericSignature)); var methodSpecification = new MethodSpecification(method, null); var context = GenericContext.FromMethod(methodSpecification); var context2 = GenericContext.FromMember(methodSpecification); var context3 = GenericContext.FromMethod((IMethodDescriptor) methodSpecification); Assert.Equal(context, context3); Assert.Equal(context, context2); Assert.False(context.IsEmpty); Assert.Equal(genericTypeInstance, context.Type); Assert.Null(context.Method); } [Fact] public void ParseGenericFromField() { var genericTypeInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false); genericTypeInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var typeSpecification = new TypeSpecification(genericTypeInstance); var genericParameter = new GenericParameterSignature(GenericParameterType.Type, 0); var field = new FieldDefinition("Field", FieldAttributes.Private, FieldSignature.CreateStatic(genericParameter)); var member = new MemberReference(typeSpecification, field.Name, field.Signature); var context = GenericContext.FromField(member); var context2 = GenericContext.FromMember(member); Assert.Equal(context, context2); Assert.False(context.IsEmpty); Assert.Equal(genericTypeInstance, context.Type); Assert.Null(context.Method); } [Fact] public void ParseGenericFromNotGenericField() { var type = new TypeDefinition("", "Test type", TypeAttributes.Public); var notGenericSignature = new TypeDefOrRefSignature(type); var field = new FieldDefinition("Field", FieldAttributes.Private, FieldSignature.CreateStatic(notGenericSignature)); var member = new MemberReference(type, field.Name, field.Signature); var context = GenericContext.FromField(member); var context2 = GenericContext.FromMember(member); Assert.Equal(context, context2); Assert.True(context.IsEmpty); } [Fact] public void ParseGenericFromMethod() { var genericTypeInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false); genericTypeInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var typeSpecification = new TypeSpecification(genericTypeInstance); var genericParameter = new GenericParameterSignature(GenericParameterType.Type, 0); var method = new MethodDefinition("Method", MethodAttributes.Private, MethodSignature.CreateStatic(genericParameter)); var member = new MemberReference(typeSpecification, method.Name, method.Signature); var context = GenericContext.FromMethod(member); var context2 = GenericContext.FromMember(member); Assert.Equal(context, context2); Assert.False(context.IsEmpty); Assert.Equal(genericTypeInstance, context.Type); Assert.Null(context.Method); } [Fact] public void ParseGenericFromNotGenericMethod() { var type = new TypeDefinition("", "Test type", TypeAttributes.Public); var notGenericSignature = new TypeDefOrRefSignature(type); var method = new MethodDefinition("Method", MethodAttributes.Private, MethodSignature.CreateStatic(notGenericSignature)); var member = new MemberReference(type, method.Name, method.Signature); var context = GenericContext.FromMethod(member); var context2 = GenericContext.FromMember(member); Assert.Equal(context, context2); Assert.True(context.IsEmpty); } [Fact] public void ParseGenericFromProperty() { var genericTypeInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false); genericTypeInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var typeSpecification = new TypeSpecification(genericTypeInstance); var genericParameter = new GenericParameterSignature(GenericParameterType.Type, 0); var property = new PropertyDefinition("Property", PropertyAttributes.None, PropertySignature.CreateStatic(genericParameter)); var member = new MemberReference(typeSpecification, property.Name, property.Signature); var context = GenericContext.FromMethod(member); var context2 = GenericContext.FromMember(member); Assert.Equal(context, context2); Assert.False(context.IsEmpty); Assert.Equal(genericTypeInstance, context.Type); Assert.Null(context.Method); } [Fact] public void ParseGenericFromNotGenericProperty() { var type = new TypeDefinition("", "Test type", TypeAttributes.Public); var notGenericSignature = new TypeDefOrRefSignature(type); var property = new PropertyDefinition("Property", PropertyAttributes.None, PropertySignature.CreateStatic(notGenericSignature)); var member = new MemberReference(type, property.Name, property.Signature); var context = GenericContext.FromMethod(member); var context2 = GenericContext.FromMember(member); Assert.Equal(context, context2); Assert.True(context.IsEmpty); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace Invoices.Business { /// <summary> /// SupplierProductItem (editable child object).<br/> /// This is a generated <see cref="SupplierProductItem"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="SupplierProductColl"/> collection. /// </remarks> [Serializable] public partial class SupplierProductItem : BusinessBase<SupplierProductItem> { #region Static Fields private static int _lastId; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="ProductSupplierId"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<int> ProductSupplierIdProperty = RegisterProperty<int>(p => p.ProductSupplierId, "Product Supplier Id"); /// <summary> /// Gets the Product Supplier Id. /// </summary> /// <value>The Product Supplier Id.</value> public int ProductSupplierId { get { return GetProperty(ProductSupplierIdProperty); } } /// <summary> /// Maintains metadata about <see cref="ProductId"/> property. /// </summary> public static readonly PropertyInfo<Guid> ProductIdProperty = RegisterProperty<Guid>(p => p.ProductId, "Product Id"); /// <summary> /// Gets or sets the Product Id. /// </summary> /// <value>The Product Id.</value> public Guid ProductId { get { return GetProperty(ProductIdProperty); } set { SetProperty(ProductIdProperty, value); } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="SupplierProductItem"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public SupplierProductItem() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="SupplierProductItem"/> object properties. /// </summary> [RunLocal] protected override void Child_Create() { LoadProperty(ProductSupplierIdProperty, System.Threading.Interlocked.Decrement(ref _lastId)); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="SupplierProductItem"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Child_Fetch(SafeDataReader dr) { // Value properties LoadProperty(ProductSupplierIdProperty, dr.GetInt32("ProductSupplierId")); LoadProperty(ProductIdProperty, dr.GetGuid("ProductId")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); // check all object rules and property rules BusinessRules.CheckRules(); } /// <summary> /// Inserts a new <see cref="SupplierProductItem"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(SupplierEdit parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.AddSupplierProductItem", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SupplierId", parent.SupplierId).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@ProductSupplierId", ReadProperty(ProductSupplierIdProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@ProductId", ReadProperty(ProductIdProperty)).DbType = DbType.Guid; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(ProductSupplierIdProperty, (int) cmd.Parameters["@ProductSupplierId"].Value); } } } /// <summary> /// Updates in the database all changes made to the <see cref="SupplierProductItem"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.UpdateSupplierProductItem", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductSupplierId", ReadProperty(ProductSupplierIdProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@ProductId", ReadProperty(ProductIdProperty)).DbType = DbType.Guid; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="SupplierProductItem"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.DeleteSupplierProductItem", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductSupplierId", ReadProperty(ProductSupplierIdProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright 2016 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 Google.Api.Gax; using Google.Apis.Bigquery.v2.Data; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.BigQuery.V2 { public abstract partial class BigQueryClient { #region ExecuteQuery /// <summary> /// Executes a query. /// </summary> /// <remarks> /// <para> /// This method will only return when the query has completed. It simply delegates to <see cref="CreateQueryJob(string, IEnumerable{BigQueryParameter}, QueryOptions)"/> /// and then <see cref="BigQueryJob.GetQueryResults(GetQueryResultsOptions)"/>. /// </para> /// </remarks> /// <param name="sql">The SQL query. Must not be null.</param> /// <param name="parameters">The parameters for the query. May be null, which is equivalent to specifying an empty list of parameters. Must not contain null elements.</param> /// <param name="queryOptions">The options for the query. May be null, in which case defaults will be supplied.</param> /// <param name="resultsOptions">The options for retrieving query results. May be null, in which case defaults will be supplied.</param> /// <returns>The result of the query.</returns> public virtual BigQueryResults ExecuteQuery(string sql, IEnumerable<BigQueryParameter> parameters, QueryOptions queryOptions = null, GetQueryResultsOptions resultsOptions = null) => CreateQueryJob(sql, parameters, queryOptions).GetQueryResults(resultsOptions); /// <summary> /// Asynchronously executes a query. /// </summary> /// <remarks> /// <para> /// The task returned by this method will only complete when the query has completed. /// This method simply delegates to <see cref="CreateQueryJobAsync(string, IEnumerable{BigQueryParameter}, QueryOptions, CancellationToken)"/> /// and then <see cref="BigQueryJob.GetQueryResultsAsync(GetQueryResultsOptions, CancellationToken)"/>. /// </para> /// </remarks> /// <param name="sql">The SQL query. Must not be null.</param> /// <param name="parameters">The parameters for the query. May be null, which is equivalent to specifying an empty list of parameters. Must not contain null elements.</param> /// <param name="queryOptions">The options for the query. May be null, in which case defaults will be supplied.</param> /// <param name="resultsOptions">The options for retrieving query results. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the <see cref="BigQueryResults"/> representing the query.</returns> public virtual async Task<BigQueryResults> ExecuteQueryAsync(string sql, IEnumerable<BigQueryParameter> parameters, QueryOptions queryOptions = null, GetQueryResultsOptions resultsOptions = null, CancellationToken cancellationToken = default) { var job = await CreateQueryJobAsync(sql, parameters, queryOptions, cancellationToken).ConfigureAwait(false); return await job.GetQueryResultsAsync(resultsOptions, cancellationToken).ConfigureAwait(false); } #endregion #region CreateQueryJob /// <summary> /// Creates a job for a SQL query. /// </summary> /// <param name="sql">The SQL query. Must not be null.</param> /// <param name="parameters">The parameters for the query. May be null, which is equivalent to specifying an empty list of parameters. Must not contain null elements.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The query job created. Use <see cref="GetQueryResults(JobReference,GetQueryResultsOptions)"/> to retrieve /// the results of the query.</returns> public virtual BigQueryJob CreateQueryJob(string sql, IEnumerable<BigQueryParameter> parameters, QueryOptions options = null) { throw new NotImplementedException(); } /// <summary> /// Asynchronously creates a job for a SQL query. /// </summary> /// <param name="sql">The SQL query. Must not be null.</param> /// <param name="parameters">The parameters for the query. May be null, which is equivalent to specifying an empty list of parameters. Must not contain null elements.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the query job created. Use <see cref="GetQueryResultsAsync(JobReference,GetQueryResultsOptions,CancellationToken)"/> to retrieve /// the results of the query.</returns> public virtual Task<BigQueryJob> CreateQueryJobAsync(string sql, IEnumerable<BigQueryParameter> parameters, QueryOptions options = null, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } #endregion #region GetQueryResults (autogenerated - do not edit manually) /// <summary> /// Retrieves the results of the specified job within this client's project, which must be a query job. /// This method just creates a <see cref="JobReference"/> and delegates to <see cref="GetQueryResults(JobReference, GetQueryResultsOptions)"/>. /// </summary> /// <remarks> /// <para> /// This operation will only complete when the specified query has completed. /// </para> /// </remarks> /// <param name="jobId">The job ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The results of the query.</returns> public virtual BigQueryResults GetQueryResults(string jobId, GetQueryResultsOptions options = null) => GetQueryResults(GetJobReference(jobId), options); /// <summary> /// Retrieves the results of the specified job, which must be a query job. /// This method just creates a <see cref="JobReference"/> and delegates to <see cref="GetQueryResults(JobReference, GetQueryResultsOptions)"/>. /// </summary> /// <remarks> /// <para> /// This operation will only complete when the specified query has completed. /// </para> /// </remarks> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="jobId">The job ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The results of the query.</returns> public virtual BigQueryResults GetQueryResults(string projectId, string jobId, GetQueryResultsOptions options = null) => GetQueryResults(GetJobReference(projectId, jobId), options); /// <summary> /// Retrieves the results of the specified job, which must be a query job. /// </summary> /// <remarks> /// <para> /// This operation will only complete when the specified query has completed. /// </para> /// </remarks> /// <param name="jobReference">A fully-qualified identifier for the job. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The results of the query.</returns> public virtual BigQueryResults GetQueryResults(JobReference jobReference, GetQueryResultsOptions options = null) => throw new NotImplementedException(); /// <summary> /// Asynchronously retrieves the results of the specified job within this client's project, which must be a query job. /// This method just creates a <see cref="JobReference"/> and delegates to <see cref="GetQueryResultsAsync(JobReference, GetQueryResultsOptions, CancellationToken)"/>. /// </summary> /// <remarks> /// <para> /// This operation will only complete when the specified query has completed. /// </para> /// </remarks> /// <param name="jobId">The job ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the results of the query.</returns> public virtual Task<BigQueryResults> GetQueryResultsAsync(string jobId, GetQueryResultsOptions options = null, CancellationToken cancellationToken = default) => GetQueryResultsAsync(GetJobReference(jobId), options, cancellationToken); /// <summary> /// Asynchronously retrieves the results of the specified job, which must be a query job. /// This method just creates a <see cref="JobReference"/> and delegates to <see cref="GetQueryResultsAsync(JobReference, GetQueryResultsOptions, CancellationToken)"/>. /// </summary> /// <remarks> /// <para> /// This operation will only complete when the specified query has completed. /// </para> /// </remarks> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="jobId">The job ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the results of the query.</returns> public virtual Task<BigQueryResults> GetQueryResultsAsync(string projectId, string jobId, GetQueryResultsOptions options = null, CancellationToken cancellationToken = default) => GetQueryResultsAsync(GetJobReference(projectId, jobId), options, cancellationToken); /// <summary> /// Asynchronously retrieves the results of the specified job, which must be a query job. /// </summary> /// <remarks> /// <para> /// This operation will only complete when the specified query has completed. /// </para> /// </remarks> /// <param name="jobReference">A fully-qualified identifier for the job. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the results of the query.</returns> public virtual Task<BigQueryResults> GetQueryResultsAsync(JobReference jobReference, GetQueryResultsOptions options = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); #endregion #region ListRows /// <summary> /// Lists the rows within a table specified by project ID, dataset ID and table ID, similar to a <c>SELECT * FROM ...</c> query. /// This method just creates a <see cref="TableReference"/> and delegates to <see cref="ListRows(TableReference, TableSchema, ListRowsOptions)"/>. /// </summary> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="tableId">The table ID. Must not be null.</param> /// <param name="schema">The schema to use when interpreting results. This may be null, in which case it will be fetched from /// the table first.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The results of listing the rows within the table.</returns> public virtual PagedEnumerable<TableDataList, BigQueryRow> ListRows(string projectId, string datasetId, string tableId, TableSchema schema = null, ListRowsOptions options = null) => ListRows(GetTableReference(projectId, datasetId, tableId), schema, options); /// <summary> /// Lists the rows within a table within this client's project specified by dataset ID and table ID, similar to a <c>SELECT * FROM ...</c> query. /// This method just creates a <see cref="TableReference"/> and delegates to <see cref="ListRows(TableReference, TableSchema, ListRowsOptions)"/>. /// </summary> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="tableId">The table ID. Must not be null.</param> /// <param name="schema">The schema to use when interpreting results. This may be null, in which case it will be fetched from /// the table first.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The results of listing the rows within the table.</returns> public virtual PagedEnumerable<TableDataList, BigQueryRow> ListRows(string datasetId, string tableId, TableSchema schema = null, ListRowsOptions options = null) => ListRows(GetTableReference(datasetId, tableId), schema, options); /// <summary> /// Lists the rows within a table, similar to a <c>SELECT * FROM ...</c> query. /// </summary> /// <param name="tableReference">A fully-qualified identifier for the table. Must not be null.</param> /// <param name="schema">The schema to use when interpreting results. This may be null, in which case it will be fetched from /// the table first.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The results of listing the rows within the table.</returns> public virtual PagedEnumerable<TableDataList, BigQueryRow> ListRows(TableReference tableReference, TableSchema schema = null, ListRowsOptions options = null) { throw new NotImplementedException(); } /// <summary> /// Lists the rows within a table specified by project ID, dataset ID and table ID, similar to a <c>SELECT * FROM ...</c> query. /// This method just creates a <see cref="TableReference"/> and delegates to <see cref="ListRowsAsync(TableReference, TableSchema, ListRowsOptions)"/>. /// </summary> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="tableId">The table ID. Must not be null.</param> /// <param name="schema">The schema to use when interpreting results. This may be null, in which case it will be fetched from /// the table first.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>An asynchronous sequence of the rows within the table.</returns> public virtual PagedAsyncEnumerable<TableDataList, BigQueryRow> ListRowsAsync(string projectId, string datasetId, string tableId, TableSchema schema = null, ListRowsOptions options = null) => ListRowsAsync(GetTableReference(projectId, datasetId, tableId), schema, options); /// <summary> /// Lists the rows within a table within this client's project specified by dataset ID and table ID, similar to a <c>SELECT * FROM ...</c> query. /// This method just creates a <see cref="TableReference"/> and delegates to <see cref="ListRowsAsync(TableReference, TableSchema, ListRowsOptions)"/>. /// </summary> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="tableId">The table ID. Must not be null.</param> /// <param name="schema">The schema to use when interpreting results. This may be null, in which case it will be fetched from /// the table first.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>An asynchronous sequence of the rows within the table.</returns> public virtual PagedAsyncEnumerable<TableDataList, BigQueryRow> ListRowsAsync(string datasetId, string tableId, TableSchema schema = null, ListRowsOptions options = null) => ListRowsAsync(GetTableReference(datasetId, tableId), schema, options); /// <summary> /// Lists the rows within a table, similar to a <c>SELECT * FROM ...</c> query. /// </summary> /// <param name="tableReference">A fully-qualified identifier for the table. Must not be null.</param> /// <param name="schema">The schema to use when interpreting results. This may be null, in which case it will be fetched from /// the table first.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>An asynchronous sequence of the rows within the table.</returns> public virtual PagedAsyncEnumerable<TableDataList, BigQueryRow> ListRowsAsync(TableReference tableReference, TableSchema schema = null, ListRowsOptions options = null) { throw new NotImplementedException(); } #endregion // Note - these methods are not part of the regular "pattern", so are not in the GetQueryResults region above. // We want to remove them, if the underlying GetQueryResultsResponse starts including the table reference. // These methods allow us to call GetQueryResultsAsync from BigQueryJob without fetching the job again. internal virtual BigQueryResults GetQueryResults(JobReference jobReference, TableReference tableReference, GetQueryResultsOptions options) => throw new NotImplementedException(); internal virtual Task<BigQueryResults> GetQueryResultsAsync(JobReference jobReference, TableReference tableReference, GetQueryResultsOptions options, CancellationToken cancellationToken) => throw new NotImplementedException(); } }
#region Copyright (c) 2004 Ian Davis and James Carlyle /*------------------------------------------------------------------------------ COPYRIGHT AND PERMISSION NOTICE Copyright (c) 2004 Ian Davis and James Carlyle 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 namespace SemPlan.Spiral.Utility { using SemPlan.Spiral.Core; using System; using System.Collections; /// <summary> /// Represents a query on a TripleStore /// </summary> /// <remarks> /// $Id: BacktrackingQuerySolver.cs,v 1.3 2006/03/08 22:42:36 ian Exp $ ///</remarks> public class BacktrackingQuerySolver : QuerySolver, IEnumerator { private Hashtable itsRequestedVariables; private Hashtable itsDistinctSolutions; private Query itsQuery; private ArrayList itsSolutions; private int itsSolutionIndex; private bool itsExplain; public bool Explain { get { return itsExplain; } set { itsExplain = value; } } public BacktrackingQuerySolver( Query query, TripleStore triples ) :this( query, triples, false) { } public BacktrackingQuerySolver( Query query, TripleStore triples, bool explain ) { itsExplain = explain; itsQuery = query; itsSolutions = new ArrayList(); itsDistinctSolutions = new Hashtable(); itsRequestedVariables = new Hashtable(); if (Explain) Console.WriteLine("Collecting variables"); CollectVariablesToBeSelected(); try { ArrayList bindingsList = GetSolutions( triples, itsQuery.ResolveQueryGroup( triples ), new Bindings() ); if ( query.IsOrdered ) { if (Explain) Console.WriteLine("Sorting results"); bindingsList.Sort( new BindingsComparer( query.OrderBy ) ); if ( query.OrderDirection == Query.SortOrder.Descending ) { bindingsList.Reverse(); } } foreach ( Bindings bindings in bindingsList ) { QuerySolution solution = GetSolution( bindings, itsRequestedVariables, triples); if ( IsDistinctSolution( solution ) ) { if (Explain) Console.WriteLine("Reporting solution " + solution); itsSolutions.Add( solution ); } } } catch (UnknownGraphMemberException) { } itsSolutionIndex = -1; } public ArrayList GetSolutions( TripleStore store, QueryGroup group, Bindings bindings) { if (Explain) Console.WriteLine("Solving " + group.GetType()); if ( group is QueryGroupOr ) { if (Explain) Console.WriteLine("Solving QueryGroupOr"); ArrayList solutions = new ArrayList(); foreach (QueryGroup subgroup in ((QueryGroupOr)group).Groups) { solutions.AddRange( GetSolutions( store, subgroup, bindings) ); } if (Explain) Console.WriteLine("Have " + solutions.Count + " candidate solutions after or"); return solutions; } else if (group is QueryGroupAnd) { ArrayList solutions = new ArrayList(); solutions.Add( bindings ); foreach (QueryGroup subgroup in ((QueryGroupAnd)group).Groups) { ArrayList filteredSolutions = new ArrayList(); foreach (Bindings tempBindings in solutions) { filteredSolutions.AddRange( GetSolutions( store, subgroup, tempBindings ) ); } solutions = filteredSolutions; if (Explain) Console.WriteLine("Have " + solutions.Count + " candidate solutions after " + subgroup.GetType()); } return solutions; } else if ( group is QueryGroupOptional) { if (Explain) Console.WriteLine("Solving QueryGroupOptional"); ArrayList augmentedSolutions = GetSolutions( store, ((QueryGroupOptional)group).Group, bindings ); if ( augmentedSolutions.Count == 0) { augmentedSolutions.Add( bindings ); } return augmentedSolutions; } else if ( group is QueryGroupConstraints ) { if (Explain) Console.WriteLine("Solving QueryGroupConstraints"); ArrayList solutions = new ArrayList(); foreach ( Constraint constraint in ((QueryGroupConstraints)group).Constraints) { if (Explain) Console.WriteLine("Testing solution against constraint {0}", constraint); if (! constraint.SatisfiedBy( bindings ) ) { if (Explain) Console.WriteLine("Failed to satisfy constraint"); return solutions; } } solutions.Add( bindings ); return solutions; } else if (group is QueryGroupPatterns) { if (Explain) Console.WriteLine("Solving QueryGroupPatterns"); ArrayList solutions = new ArrayList(); if ( ((QueryGroupPatterns)group).Patterns.Count == 0) { return solutions; } Bindings answers = new Bindings(); Pattern firstGoal = ((QueryGroupPatterns)group).First(); Pattern newGoal = firstGoal.Substitute( bindings ); IEnumerator statements = store.GetStatementEnumerator(); while ( statements.MoveNext() ) { ResourceStatement statement = (ResourceStatement)statements.Current; if (Explain) Console.WriteLine("Trying for a binding for {0} with {1}", statement, newGoal); answers = statement.Unify(newGoal, bindings, store); if ( answers != null ) { if (Explain) Console.WriteLine("Got a binding for {0} with {1}", statement, newGoal); if (((QueryGroupPatterns)group).Patterns.Count == 1) { if (Explain) Console.WriteLine("Got a candidate solution {0}", answers); solutions.Add( answers ); } else { solutions.AddRange( GetSolutions(store, ((QueryGroupPatterns)group).Rest(), answers) ); } } } return solutions; } else { return new ArrayList(); } } private QuerySolution GetSolution(Bindings bindings, Hashtable requiredVariables, TripleStore store) { QuerySolution solution = new QuerySolution(); IDictionaryEnumerator en = bindings.GetEnumerator(); while (en.MoveNext() ) { if ( requiredVariables.ContainsKey( ((Variable)en.Key).Name ) ) { solution[ ((Variable)en.Key).Name ] = (Resource)en.Value; solution.SetNode( ((Variable)en.Key).Name , store.GetBestDenotingNode( (Resource)en.Value ) ); } } return solution; } public ArrayList GenerateGoals(PatternGroup group, TripleStore store) { ArrayList goals = new ArrayList(); foreach (Pattern pattern in group.Patterns) { Pattern goal = pattern.Resolve( store ); if ( null != goal ) { goals.Add( goal ); } else { if (Explain) Console.WriteLine("Pattern {0} cannot be matched in this triple store since it contains unknown terms", pattern); return new ArrayList(); } } return goals; } public bool MoveNext( ) { ++itsSolutionIndex; return ( itsSolutionIndex < itsSolutions.Count ); } public bool IsDistinctSolution(QuerySolution solution) { if (! itsQuery.IsDistinct) { return true; } if (itsDistinctSolutions.ContainsKey( solution ) ) { return false; } else { itsDistinctSolutions[solution] = solution; return true; } } public object Current { get { return (QuerySolution)itsSolutions[itsSolutionIndex]; } } public void Reset() { throw new NotSupportedException("Reset not supported"); } public void CollectVariablesToBeSelected() { foreach (Variable variable in itsQuery.Variables ) { itsRequestedVariables[ variable.Name ] = variable; } } } }
using System; using System.Reflection; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using JustGestures.Properties; using JustGestures.OptionItems; using JustGestures.Features; using JustGestures.Languages; namespace JustGestures.GUI { public partial class Form_options : Form, ITranslation { private enum Options { General, AutoBehaviour, BlackList, WhiteList, Gesture, Visual, } UC_generalOptions ucGeneralOptions; UC_autoBehaviour ucAutoBehaviour; UC_blackList ucBlackList; UC_whiteList ucWhiteList; UC_visualisation ucVisualisation; UC_gestureOptions ucGestureOptions; List<PrgNamePath> blackList; List<PrgNamePath> whiteList; List<PrgNamePath> finalList; List<PrgNamePath> backUpBlackList; List<PrgNamePath> backUpWhiteList; List<PrgNamePath> backUpFinalList; bool m_okClick = false; public delegate void DlgApplySettings(); public DlgApplySettings ApplySettings; protected void OnApplySettings() { if (ApplySettings != null) ApplySettings(); } #region ITranslation Members public void Translate() { Form_engine.Instance.Translate(); // do not translate options when user clicked on OK (it will be closed) if (m_okClick) return; this.Text = Translation.GetText("O_caption"); btn_ok.Text = Translation.Btn_ok; btn_cancel.Text = Translation.Btn_cancel; btn_apply.Text = Translation.Btn_apply; foreach (BaseOptionControl control in panel_fill.Controls) control.Translate(); foreach (TreeNode node in tW_options.Nodes) TranslateTreeNode(node); } public void TranslateTreeNode(TreeNode root) { foreach (TreeNode node in root.Nodes) TranslateTreeNode(node); Options selectedOption = (Options)Enum.Parse(typeof(Options), root.Name); switch (selectedOption) { case Options.General: root.Text = ucGeneralOptions.ControlName; break; case Options.AutoBehaviour: root.Text = ucAutoBehaviour.ControlName; break; case Options.BlackList: root.Text = ucBlackList.ControlName; break; case Options.WhiteList: root.Text = ucWhiteList.ControlName; break; case Options.Visual: root.Text = ucVisualisation.ControlName; break; case Options.Gesture: root.Text = ucGestureOptions.ControlName; break; } } #endregion public Form_options() { InitializeComponent(); MyInitializing(); } private void MyInitializing() { typeof(Panel).InvokeMember("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, panel_fill, new object[] { true }); this.Icon = Properties.Resources.options16; ucGeneralOptions = new UC_generalOptions(); ucAutoBehaviour = new UC_autoBehaviour(); ucWhiteList = new UC_whiteList(); ucBlackList = new UC_blackList(); ucVisualisation = new UC_visualisation(); ucGestureOptions = new UC_gestureOptions(); ucGeneralOptions.TranslateTexts = Translate; panel_fill.Controls.Add(ucGeneralOptions); panel_fill.Controls.Add(ucAutoBehaviour); panel_fill.Controls.Add(ucWhiteList); panel_fill.Controls.Add(ucBlackList); panel_fill.Controls.Add(ucGestureOptions); panel_fill.Controls.Add(ucVisualisation); foreach (BaseOptionControl control in panel_fill.Controls) { control.Dock = DockStyle.Fill; control.ChangeInfoText += new BaseOptionControl.DlgChangeInfoText(uC_infoIcon1.ChangeInfoText); } tW_options.Nodes.Add(Options.General.ToString(), ucGeneralOptions.ControlName); TreeNode nodeGestureOptions = new TreeNode(ucGestureOptions.ControlName); nodeGestureOptions.Name = Options.Gesture.ToString(); nodeGestureOptions.Nodes.Add(Options.Visual.ToString(), ucVisualisation.ControlName); tW_options.Nodes.Add(nodeGestureOptions); TreeNode nodeAutoBehave = new TreeNode(ucAutoBehaviour.ControlName); nodeAutoBehave.Name = Options.AutoBehaviour.ToString(); nodeAutoBehave.Nodes.Add(Options.WhiteList.ToString(), ucWhiteList.ControlName); nodeAutoBehave.Nodes.Add(Options.BlackList.ToString(), ucBlackList.ControlName); tW_options.Nodes.Add(nodeAutoBehave); tW_options.ExpandAll(); //tW_options.Nodes.Add(Options.Visual.ToString(), ucVisualisation.About); foreach (BaseOptionControl control in panel_fill.Controls) { control.Visible = false; control.ChangeCaption += new BaseOptionControl.DlgChangeCaption(ChangeCaption); control.EnableApply += new BaseOptionControl.DlgEnableApply(EnableBtnApply); } ucGeneralOptions.Visible = true; btn_apply.Enabled = false; Translate(); } private void ChangeCaption(string text) { StringFormat strFormat = new StringFormat(); strFormat.LineAlignment = StringAlignment.Center; //strFormat.Alignment = StringAlignment.Center; Font strFont = new Font(FontFamily.GenericSansSerif, 11, FontStyle.Bold); Rectangle r = new Rectangle(0, 0, pB_caption.Width, pB_caption.Height); Bitmap bmp = new Bitmap(pB_caption.Width, pB_caption.Height); Graphics gp = Graphics.FromImage(bmp); Pen pen = new Pen(Brushes.Gray, 1); gp.FillRectangle(new SolidBrush(pB_caption.BackColor), r); gp.DrawLine(pen, 0, 0, pB_caption.Width, 0); gp.DrawLine(new Pen(Brushes.Gray, 1), 0, pB_caption.Height - 2, pB_caption.Width, pB_caption.Height - 2); //gp.DrawLine(new Pen(Brushes.Black, 1), 0, pB_caption.Height - 2, pB_caption.Width, pB_caption.Height - 2); gp.DrawLine(new Pen(Brushes.White, 1), 0, pB_caption.Height - 1, pB_caption.Width, pB_caption.Height - 1); r.X += 10; //r.Width -= 6; r.Y += 2; r.Height -= 7; gp.DrawString(text, strFont, Brushes.Black, r, strFormat); gp.Dispose(); pB_caption.Image = bmp; } private void EnableBtnApply(bool enable) { btn_apply.Enabled = enable; } private void SaveSettings() { foreach (BaseOptionControl control in panel_fill.Controls) control.SaveSettings(); blackList = ucBlackList.Programs; whiteList = ucWhiteList.Programs; finalList = ucAutoBehaviour.FinalList; backUpBlackList = blackList; backUpWhiteList = whiteList; backUpFinalList = finalList; FileOptions.SaveLists(whiteList, blackList, finalList); Config.User.Save(); OnApplySettings(); } private void ReturnSettings() { blackList = backUpBlackList; whiteList = backUpWhiteList; finalList = backUpFinalList; } private void btn_ok_Click(object sender, EventArgs e) { m_okClick = true; SaveSettings(); } private void tW_options_AfterSelect(object sender, TreeViewEventArgs e) { foreach (Control control in panel_fill.Controls) control.Visible = false; Options selectedOption = (Options)Enum.Parse(typeof(Options), e.Node.Name); switch (selectedOption) { case Options.General: ucGeneralOptions.Visible = true; break; case Options.AutoBehaviour: //autoBehaviour.BlackList = blackList; //autoBehaviour.WhiteList = whiteList; //autoBehaviour.FinalList = finalList; ucAutoBehaviour.Visible = true; break; case Options.BlackList: //ucBlackList.Programs = blackList; ucBlackList.Visible = true; break; case Options.WhiteList: //ucWhiteList.Programs = whiteList; ucWhiteList.Visible = true; break; case Options.Gesture: ucGestureOptions.Visible = true; break; case Options.Visual: ucVisualisation.Visible = true; break; } } private void btn_apply_Click(object sender, EventArgs e) { SaveSettings(); btn_apply.Enabled = false; } //public List<PrgNamePath> BlackList { get { return blackList; } set { blackList = value; } } //public List<PrgNamePath> WhiteList { get { return whiteList; } set { whiteList = value; } } public List<PrgNamePath> FinalList { get { return finalList; } set { finalList = value; } } private void Form_options_Load(object sender, EventArgs e) { FileOptions.LoadLists(out whiteList, out blackList, out finalList); ucBlackList.Programs = blackList; ucWhiteList.Programs = whiteList; ucAutoBehaviour.BlackList = blackList; ucAutoBehaviour.WhiteList = whiteList; ucAutoBehaviour.FinalList = finalList; backUpWhiteList = new List<PrgNamePath>(whiteList); backUpBlackList = new List<PrgNamePath>(blackList); backUpFinalList = new List<PrgNamePath>(finalList); } private void btn_cancel_Click(object sender, EventArgs e) { ReturnSettings(); } private void Form_options_FormClosing(object sender, FormClosingEventArgs e) { ReturnSettings(); } private void panel_down_Paint(object sender, PaintEventArgs e) { Graphics g = panel_down.CreateGraphics(); g.DrawLine(new Pen(Brushes.Gray, 1), 0, 2, panel_down.Width, 2); g.DrawLine(new Pen(Brushes.White, 1), 0, 1, panel_down.Width, 1); g.Dispose(); } private void tW_options_BeforeCollapse(object sender, TreeViewCancelEventArgs e) { e.Cancel = 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. /*============================================================ ** ** ** ** ** ** Purpose: A Stream whose backing store is memory. Great ** for temporary storage without creating a temp file. Also ** lets users expose a byte[] as a stream. ** ** ===========================================================*/ using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.IO { // A MemoryStream represents a Stream in memory (ie, it has no backing store). // This stream may reduce the need for temporary buffers and files in // an application. // // There are two ways to create a MemoryStream. You can initialize one // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. [Serializable] public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. private int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. [ContractPublicPropertyName("Length")] private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream // Note that _capacity == _buffer.Length for non-user-provided byte[]'s private bool _expandable; // User-provided buffers aren't expandable. private bool _writable; // Can user write to this stream? private bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? [NonSerialized] private Task<int> _lastReadTask; // The last successful task returned from ReadAsync private const int MemStreamMaxLength = Int32.MaxValue; public MemoryStream() : this(0) { } public MemoryStream(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity); } Contract.EndContractBlock(); _buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>(); _capacity = capacity; _expandable = true; _writable = true; _exposable = true; _origin = 0; // Must be 0 for byte[]'s created by MemoryStream _isOpen = true; } public MemoryStream(byte[] buffer) : this(buffer, true) { } public MemoryStream(byte[] buffer, bool writable) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); Contract.EndContractBlock(); _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; _exposable = false; _origin = 0; _isOpen = true; } public MemoryStream(byte[] buffer, int index, int count) : this(buffer, index, count, true, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable) : this(buffer, index, count, writable, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); _buffer = buffer; _origin = _position = index; _length = _capacity = index + count; _writable = writable; _exposable = publiclyVisible; // Can TryGetBuffer/GetBuffer return the array? _expandable = false; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _writable; } } private void EnsureWriteable() { if (!CanWrite) __Error.WriteNotSupported(); } protected override void Dispose(bool disposing) { try { if (disposing) { _isOpen = false; _writable = false; _expandable = false; // Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work. _lastReadTask = null; } } finally { // Call base.Close() to cleanup async IO resources base.Dispose(disposing); } } // returns a bool saying whether we allocated a new array. private bool EnsureCapacity(int value) { // Check for overflow if (value < 0) throw new IOException(SR.IO_StreamTooLong); if (value > _capacity) { int newCapacity = value; if (newCapacity < 256) newCapacity = 256; // We are ok with this overflowing since the next statement will deal // with the cases where _capacity*2 overflows. if (newCapacity < _capacity * 2) newCapacity = _capacity * 2; // We want to expand the array up to Array.MaxArrayLengthOneDimensional // And we want to give the user the value that they asked for if ((uint)(_capacity * 2) > Array.MaxByteArrayLength) newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength; Capacity = newCapacity; return true; } return false; } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Flush(); return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } public virtual byte[] GetBuffer() { if (!_exposable) throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer); return _buffer; } public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) { if (!_exposable) { buffer = default(ArraySegment<byte>); return false; } buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin)); return true; } // -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) --------------- // PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer()) internal byte[] InternalGetBuffer() { return _buffer; } // PERF: Get origin and length - used in ResourceWriter. [FriendAccessAllowed] internal void InternalGetOriginAndLength(out int origin, out int length) { if (!_isOpen) __Error.StreamIsClosed(); origin = _origin; length = _length; } // PERF: True cursor position, we don't need _origin for direct access internal int InternalGetPosition() { if (!_isOpen) __Error.StreamIsClosed(); return _position; } // PERF: Takes out Int32 as fast as possible internal int InternalReadInt32() { if (!_isOpen) __Error.StreamIsClosed(); int pos = (_position += 4); // use temp to avoid a race condition if (pos > _length) { _position = _length; __Error.EndOfFile(); } return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24); } // PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes internal int InternalEmulateRead(int count) { if (!_isOpen) __Error.StreamIsClosed(); int n = _length - _position; if (n > count) n = count; if (n < 0) n = 0; Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. _position += n; return n; } // Gets & sets the capacity (number of bytes allocated) for this stream. // The capacity cannot be set to a value less than the current length // of the stream. // public virtual int Capacity { get { if (!_isOpen) __Error.StreamIsClosed(); return _capacity - _origin; } set { // Only update the capacity if the MS is expandable and the value is different than the current capacity. // Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); Contract.Ensures(_capacity - _origin == value); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable(); // MemoryStream has this invariant: _origin > 0 => !expandable (see ctors) if (_expandable && value != _capacity) { if (value > 0) { byte[] newBuffer = new byte[value]; if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length); _buffer = newBuffer; } else { _buffer = null; } _capacity = value; } } } public override long Length { get { if (!_isOpen) __Error.StreamIsClosed(); return _length - _origin; } } public override long Position { get { if (!_isOpen) __Error.StreamIsClosed(); return _position - _origin; } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.Ensures(Position == value); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); if (value > MemStreamMaxLength) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); _position = _origin + (int)value; } } public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); int n = _length - _position; if (n > count) n = count; if (n <= 0) return 0; Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. if (n <= 8) { int byteCount = n; while (--byteCount >= 0) buffer[offset + byteCount] = _buffer[_position + byteCount]; } else Buffer.InternalBlockCopy(_buffer, _position, buffer, offset, n); _position += n; return n; } public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Read(...) // If cancellation was requested, bail early if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); try { int n = Read(buffer, offset, count); var t = _lastReadTask; Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion, "Expected that a stored last task completed successfully"); return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n)); } catch (OperationCanceledException oce) { return Task.FromCancellation<int>(oce); } catch (Exception exception) { return Task.FromException<int>(exception); } } public override int ReadByte() { if (!_isOpen) __Error.StreamIsClosed(); if (_position >= _length) return -1; return _buffer[_position++]; } public override void CopyTo(Stream destination, int bufferSize) { // Since we did not originally override this method, validate the arguments // the same way Stream does for back-compat. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read) when we are not sure. if (GetType() != typeof(MemoryStream)) { base.CopyTo(destination, bufferSize); return; } int originalPosition = _position; // Seek to the end of the MemoryStream. int remaining = InternalEmulateRead(_length - originalPosition); // If we were already at or past the end, there's no copying to do so just quit. if (remaining > 0) { // Call Write() on the other Stream, using our internal buffer and avoiding any // intermediary allocations. destination.Write(_buffer, originalPosition, remaining); } } public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { // This implementation offers beter performance compared to the base class version. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to ReadAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into ReadAsync) when we are not sure. if (this.GetType() != typeof(MemoryStream)) return base.CopyToAsync(destination, bufferSize, cancellationToken); // If cancelled - return fast: if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); // Avoid copying data from this buffer into a temp buffer: // (require that InternalEmulateRead does not throw, // otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below) Int32 pos = _position; Int32 n = InternalEmulateRead(_length - _position); // If destination is not a memory stream, write there asynchronously: MemoryStream memStrDest = destination as MemoryStream; if (memStrDest == null) return destination.WriteAsync(_buffer, pos, n, cancellationToken); try { // If destination is a MemoryStream, CopyTo synchronously: memStrDest.Write(_buffer, pos, n); return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) __Error.StreamIsClosed(); if (offset > MemStreamMaxLength) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength); switch (loc) { case SeekOrigin.Begin: { int tempPosition = unchecked(_origin + (int)offset); if (offset < 0 || tempPosition < _origin) throw new IOException(SR.IO_SeekBeforeBegin); _position = tempPosition; break; } case SeekOrigin.Current: { int tempPosition = unchecked(_position + (int)offset); if (unchecked(_position + offset) < _origin || tempPosition < _origin) throw new IOException(SR.IO_SeekBeforeBegin); _position = tempPosition; break; } case SeekOrigin.End: { int tempPosition = unchecked(_length + (int)offset); if (unchecked(_length + offset) < _origin || tempPosition < _origin) throw new IOException(SR.IO_SeekBeforeBegin); _position = tempPosition; break; } default: throw new ArgumentException(SR.Argument_InvalidSeekOrigin); } Debug.Assert(_position >= 0, "_position >= 0"); return _position; } // Sets the length of the stream to a given value. The new // value must be nonnegative and less than the space remaining in // the array, Int32.MaxValue - origin // Origin is 0 in all cases other than a MemoryStream created on // top of an existing array and a specific starting offset was passed // into the MemoryStream constructor. The upper bounds prevents any // situations where a stream may be created on top of an array then // the stream is made longer than the maximum possible length of the // array (Int32.MaxValue). // public override void SetLength(long value) { if (value < 0 || value > Int32.MaxValue) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } Contract.Ensures(_length - _origin == value); Contract.EndContractBlock(); EnsureWriteable(); // Origin wasn't publicly exposed above. Debug.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails. if (value > (Int32.MaxValue - _origin)) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } int newLength = _origin + (int)value; bool allocatedNewArray = EnsureCapacity(newLength); if (!allocatedNewArray && newLength > _length) Array.Clear(_buffer, _length, newLength - _length); _length = newLength; if (_position > newLength) _position = newLength; } public virtual byte[] ToArray() { BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy."); byte[] copy = new byte[_length - _origin]; Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin); return copy; } public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); EnsureWriteable(); int i = _position + count; // Check for overflow if (i < 0) throw new IOException(SR.IO_StreamTooLong); if (i > _length) { bool mustZero = _position > _length; if (i > _capacity) { bool allocatedNewArray = EnsureCapacity(i); if (allocatedNewArray) mustZero = false; } if (mustZero) Array.Clear(_buffer, _length, i - _length); _length = i; } if ((count <= 8) && (buffer != _buffer)) { int byteCount = count; while (--byteCount >= 0) _buffer[_position + byteCount] = buffer[offset + byteCount]; } else Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count); _position = i; } public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Write(...) // If cancellation is already requested, bail early if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (OperationCanceledException oce) { return Task.FromCancellation<VoidTaskResult>(oce); } catch (Exception exception) { return Task.FromException(exception); } } public override void WriteByte(byte value) { if (!_isOpen) __Error.StreamIsClosed(); EnsureWriteable(); if (_position >= _length) { int newLength = _position + 1; bool mustZero = _position > _length; if (newLength >= _capacity) { bool allocatedNewArray = EnsureCapacity(newLength); if (allocatedNewArray) mustZero = false; } if (mustZero) Array.Clear(_buffer, _length, _position - _length); _length = newLength; } _buffer[_position++] = value; } // Writes this MemoryStream to another stream. public virtual void WriteTo(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); stream.Write(_buffer, _origin, _length - _origin); } } }
namespace AutoMapper.Internal { using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using TypeInfo = AutoMapper.TypeInfo; public class MappingExpression : IMappingExpression, IMemberConfigurationExpression { private readonly TypeMap _typeMap; private readonly Func<Type, object> _typeConverterCtor; private PropertyMap _propertyMap; public MappingExpression(TypeMap typeMap, Func<Type, object> typeConverterCtor) { _typeMap = typeMap; _typeConverterCtor = typeConverterCtor; } public void ConvertUsing<TTypeConverter>() { ConvertUsing(typeof(TTypeConverter)); } public void ConvertUsing(Type typeConverterType) { var interfaceType = typeof(ITypeConverter<,>).MakeGenericType(_typeMap.SourceType, _typeMap.DestinationType); var convertMethodType = interfaceType.IsAssignableFrom(typeConverterType) ? interfaceType : typeConverterType; var converter = new DeferredInstantiatedConverter(convertMethodType, BuildCtor<object>(typeConverterType)); _typeMap.UseCustomMapper(converter.Convert); } public void As(Type typeOverride) { _typeMap.DestinationTypeOverride = typeOverride; } public IMappingExpression WithProfile(string profileName) { _typeMap.Profile = profileName; return this; } public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions) { IMemberAccessor destMember = null; var propertyInfo = _typeMap.DestinationType.GetProperty(name); if (propertyInfo != null) { destMember = new PropertyAccessor(propertyInfo); } if (destMember == null) { var fieldInfo = _typeMap.DestinationType.GetField(name); destMember = new FieldAccessor(fieldInfo); } ForDestinationMember(destMember, memberOptions); return new MappingExpression(_typeMap, _typeConverterCtor); } public IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions) { MemberInfo srcMember = _typeMap.SourceType.GetMember(sourceMemberName).First(); var srcConfig = new SourceMappingExpression(_typeMap, srcMember); memberOptions(srcConfig); return new MappingExpression(_typeMap, _typeConverterCtor); } private void ForDestinationMember(IMemberAccessor destinationProperty, Action<IMemberConfigurationExpression> memberOptions) { _propertyMap = _typeMap.FindOrCreatePropertyMapFor(destinationProperty); memberOptions(this); } public void MapFrom(string sourceMember) { var members = _typeMap.SourceType.GetMember(sourceMember); if (!members.Any()) throw new AutoMapperConfigurationException( $"Unable to find source member {sourceMember} on type {_typeMap.SourceType.FullName}"); if (members.Skip(1).Any()) throw new AutoMapperConfigurationException( $"Source member {sourceMember} is ambiguous on type {_typeMap.SourceType.FullName}"); var member = members.Single(); _propertyMap.SourceMember = member; _propertyMap.AssignCustomValueResolver(member.ToMemberGetter()); } public IResolutionExpression ResolveUsing(IValueResolver valueResolver) { _propertyMap.AssignCustomValueResolver(valueResolver); return new ResolutionExpression(_typeMap.SourceType, _propertyMap); } public IResolverConfigurationExpression ResolveUsing(Type valueResolverType) { var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>(valueResolverType)); ResolveUsing(resolver); return new ResolutionExpression(_typeMap.SourceType, _propertyMap); } public IResolverConfigurationExpression ResolveUsing<TValueResolver>() { var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>((typeof(TValueResolver)))); ResolveUsing(resolver); return new ResolutionExpression(_typeMap.SourceType, _propertyMap); } public void Ignore() { _propertyMap.Ignore(); } public void UseDestinationValue() { _propertyMap.UseDestinationValue = true; } private Func<ResolutionContext, TServiceType> BuildCtor<TServiceType>(Type type) { return context => { if(type.IsGenericTypeDefinition()) { type = type.MakeGenericType(context.SourceType.GetGenericArguments()); } var obj = context.Options.ServiceCtor?.Invoke(type); if (obj != null) return (TServiceType)obj; return (TServiceType)_typeConverterCtor(type); }; } private class SourceMappingExpression : ISourceMemberConfigurationExpression { private readonly SourceMemberConfig _sourcePropertyConfig; public SourceMappingExpression(TypeMap typeMap, MemberInfo sourceMember) { _sourcePropertyConfig = typeMap.FindOrCreateSourceMemberConfigFor(sourceMember); } public void Ignore() { _sourcePropertyConfig.Ignore(); } } } public class MappingExpression<TSource, TDestination> : IMappingExpression<TSource, TDestination>, IMemberConfigurationExpression<TSource> { private readonly Func<Type, object> _serviceCtor; private readonly IProfileExpression _configurationContainer; private PropertyMap _propertyMap; public MappingExpression(TypeMap typeMap, Func<Type, object> serviceCtor, IProfileExpression configurationContainer) { TypeMap = typeMap; _serviceCtor = serviceCtor; _configurationContainer = configurationContainer; } public TypeMap TypeMap { get; } public IMappingExpression<TSource, TDestination> ForMember(Expression<Func<TDestination, object>> destinationMember, Action<IMemberConfigurationExpression<TSource>> memberOptions) { var memberInfo = ReflectionHelper.FindProperty(destinationMember); IMemberAccessor destProperty = memberInfo.ToMemberAccessor(); ForDestinationMember(destProperty, memberOptions); return new MappingExpression<TSource, TDestination>(TypeMap, _serviceCtor, _configurationContainer); } public IMappingExpression<TSource, TDestination> ForMember(string name, Action<IMemberConfigurationExpression<TSource>> memberOptions) { IMemberAccessor destMember = null; var propertyInfo = TypeMap.DestinationType.GetProperty(name); if (propertyInfo != null) { destMember = new PropertyAccessor(propertyInfo); } if (destMember == null) { var fieldInfo = TypeMap.DestinationType.GetField(name); if(fieldInfo == null) { throw new ArgumentOutOfRangeException("name", "Cannot find a field or property named " + name); } destMember = new FieldAccessor(fieldInfo); } ForDestinationMember(destMember, memberOptions); return new MappingExpression<TSource, TDestination>(TypeMap, _serviceCtor, _configurationContainer); } public void ForAllMembers(Action<IMemberConfigurationExpression<TSource>> memberOptions) { var typeInfo = new TypeInfo(TypeMap.DestinationType); typeInfo.PublicWriteAccessors.Each(acc => ForDestinationMember(acc.ToMemberAccessor(), memberOptions)); } public IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter() { var properties = typeof(TDestination).GetDeclaredProperties().Where(HasAnInaccessibleSetter); foreach (var property in properties) ForMember(property.Name, opt => opt.Ignore()); return new MappingExpression<TSource, TDestination>(TypeMap, _serviceCtor, _configurationContainer); } public IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter() { var properties = typeof(TSource).GetDeclaredProperties().Where(HasAnInaccessibleSetter); foreach (var property in properties) ForSourceMember(property.Name, opt => opt.Ignore()); return new MappingExpression<TSource, TDestination>(TypeMap, _serviceCtor, _configurationContainer); } private bool HasAnInaccessibleSetter(PropertyInfo property) { var setMethod = property.GetSetMethod(true); return setMethod == null || setMethod.IsPrivate || setMethod.IsFamily; } public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>() where TOtherSource : TSource where TOtherDestination : TDestination { return Include(typeof(TOtherSource), typeof(TOtherDestination)); } public IMappingExpression<TSource, TDestination> Include(Type otherSourceType, Type otherDestinationType) { TypeMap.IncludeDerivedTypes(otherSourceType, otherDestinationType); return this; } public IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>() { TypeMap baseTypeMap = _configurationContainer.CreateMap<TSourceBase, TDestinationBase>().TypeMap; baseTypeMap.IncludeDerivedTypes(typeof(TSource), typeof(TDestination)); TypeMap.ApplyInheritedMap(baseTypeMap); return this; } public IMappingExpression<TSource, TDestination> WithProfile(string profileName) { TypeMap.Profile = profileName; return this; } public void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression) { TypeMap.UseCustomProjection(projectionExpression); } public void NullSubstitute(object nullSubstitute) { _propertyMap.SetNullSubstitute(nullSubstitute); } public IResolverConfigurationExpression<TSource, TValueResolver> ResolveUsing<TValueResolver>() where TValueResolver : IValueResolver { var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>(typeof(TValueResolver))); ResolveUsing(resolver); return new ResolutionExpression<TSource, TValueResolver>(_propertyMap); } public IResolverConfigurationExpression<TSource> ResolveUsing(Type valueResolverType) { var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>(valueResolverType)); ResolveUsing(resolver); return new ResolutionExpression<TSource>(_propertyMap); } public IResolutionExpression<TSource> ResolveUsing(IValueResolver valueResolver) { _propertyMap.AssignCustomValueResolver(valueResolver); return new ResolutionExpression<TSource>(_propertyMap); } public void ResolveUsing(Func<TSource, object> resolver) { _propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(r => resolver((TSource)r.Value))); } public void ResolveUsing(Func<ResolutionResult, object> resolver) { _propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(resolver)); } public void MapFrom<TMember>(Expression<Func<TSource, TMember>> sourceMember) { _propertyMap.SetCustomValueResolverExpression(sourceMember); } public void MapFrom<TMember>(string property) { var par = Expression.Parameter(typeof (TSource)); var prop = Expression.Property(par, property); var lambda = Expression.Lambda<Func<TSource, TMember>>(prop, par); _propertyMap.SetCustomValueResolverExpression(lambda); } public void UseValue<TValue>(TValue value) { MapFrom(src => value); } public void UseValue(object value) { _propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(src => value)); } public void Condition(Func<TSource, bool> condition) { Condition(context => condition((TSource)context.Parent.SourceValue)); } public void Condition(Func<ResolutionContext, bool> condition) { _propertyMap.ApplyCondition(condition); } public void PreCondition(Func<TSource, bool> condition) { PreCondition(context => condition((TSource)context.Parent.SourceValue)); } public void PreCondition(Func<ResolutionContext, bool> condition) { _propertyMap.ApplyPreCondition(condition); } public void ExplicitExpansion() { _propertyMap.ExplicitExpansion = true; } public IMappingExpression<TSource, TDestination> MaxDepth(int depth) { TypeMap.MaxDepth = depth; return this; } public IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator() { TypeMap.ConstructDestinationUsingServiceLocator = true; return this; } public IMappingExpression<TDestination, TSource> ReverseMap() { var mappingExpression = _configurationContainer.CreateMap<TDestination, TSource>(MemberList.Source); foreach (var destProperty in TypeMap.GetPropertyMaps().Where(pm => pm.IsIgnored())) { mappingExpression.ForSourceMember(destProperty.DestinationProperty.Name, opt => opt.Ignore()); } foreach (var includedDerivedType in TypeMap.IncludedDerivedTypes) { mappingExpression.Include(includedDerivedType.DestinationType, includedDerivedType.SourceType); } return mappingExpression; } public IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember, Action<ISourceMemberConfigurationExpression<TSource>> memberOptions) { var memberInfo = ReflectionHelper.FindProperty(sourceMember); var srcConfig = new SourceMappingExpression(TypeMap, memberInfo); memberOptions(srcConfig); return this; } public IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression<TSource>> memberOptions) { var memberInfo = TypeMap.SourceType.GetMember(sourceMemberName).First(); var srcConfig = new SourceMappingExpression(TypeMap, memberInfo); memberOptions(srcConfig); return this; } public IMappingExpression<TSource, TDestination> Substitute(Func<TSource, object> substituteFunc) { TypeMap.Substitution = src => substituteFunc((TSource) src); return this; } public void Ignore() { _propertyMap.Ignore(); } public void UseDestinationValue() { _propertyMap.UseDestinationValue = true; } public void DoNotUseDestinationValue() { _propertyMap.UseDestinationValue = false; } public void SetMappingOrder(int mappingOrder) { _propertyMap.SetMappingOrder(mappingOrder); } public void ConvertUsing(Func<TSource, TDestination> mappingFunction) { TypeMap.UseCustomMapper(source => mappingFunction((TSource)source.SourceValue)); } public void ConvertUsing(Func<ResolutionContext, TDestination> mappingFunction) { TypeMap.UseCustomMapper(context => mappingFunction(context)); } public void ConvertUsing(Func<ResolutionContext, TSource, TDestination> mappingFunction) { TypeMap.UseCustomMapper(source => mappingFunction(source, (TSource)source.SourceValue)); } public void ConvertUsing(ITypeConverter<TSource, TDestination> converter) { ConvertUsing(converter.Convert); } public void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination> { var converter = new DeferredInstantiatedConverter<TSource, TDestination>(BuildCtor<ITypeConverter<TSource, TDestination>>(typeof(TTypeConverter))); ConvertUsing(converter.Convert); } public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction) { TypeMap.AddBeforeMapAction((src, dest) => beforeFunction((TSource)src, (TDestination)dest)); return this; } public IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination> { Action<TSource, TDestination> beforeFunction = (src, dest) => ((TMappingAction)_serviceCtor(typeof(TMappingAction))).Process(src, dest); return BeforeMap(beforeFunction); } public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction) { TypeMap.AddAfterMapAction((src, dest) => afterFunction((TSource)src, (TDestination)dest)); return this; } public IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination> { Action<TSource, TDestination> afterFunction = (src, dest) => ((TMappingAction)_serviceCtor(typeof(TMappingAction))).Process(src, dest); return AfterMap(afterFunction); } public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor) { return ConstructUsing(ctxt => ctor((TSource)ctxt.SourceValue)); } public IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor) { TypeMap.DestinationCtor = ctxt => ctor(ctxt); return this; } public IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor) { var func = ctor.Compile(); TypeMap.ConstructExpression = ctor; return ConstructUsing(ctxt => func((TSource)ctxt.SourceValue)); } private void ForDestinationMember(IMemberAccessor destinationProperty, Action<IMemberConfigurationExpression<TSource>> memberOptions) { _propertyMap = TypeMap.FindOrCreatePropertyMapFor(destinationProperty); memberOptions(this); } public void As<T>() { TypeMap.DestinationTypeOverride = typeof(T); } private Func<ResolutionContext, TServiceType> BuildCtor<TServiceType>(Type type) { return context => { var obj = context.Options.ServiceCtor?.Invoke(type); if (obj != null) return (TServiceType)obj; return (TServiceType)_serviceCtor(type); }; } private class SourceMappingExpression : ISourceMemberConfigurationExpression<TSource> { private readonly SourceMemberConfig _sourcePropertyConfig; public SourceMappingExpression(TypeMap typeMap, MemberInfo memberInfo) { _sourcePropertyConfig = typeMap.FindOrCreateSourceMemberConfigFor(memberInfo); } public void Ignore() { _sourcePropertyConfig.Ignore(); } } } }
// DataEditor.cs // using jQueryApi; using jQueryApi.UI.Widgets; using Slick; using SparkleXrm.CustomBinding; using System; using System.Collections.Generic; using Xrm.Sdk; namespace SparkleXrm.GridEditor { public class XrmDateEditor : GridEditorBase { public static EditorFactory CrmDateEditor; static XrmDateEditor() { CrmDateEditor = delegate(EditorArguments args) { XrmDateEditor editor = new XrmDateEditor(args); return editor; }; } public static string FormatterDateOnly(int row, int cell, object value, Column columnDef, object dataContext) { string dateFormat = GetDateFormat(columnDef); DateTime dateValue = (DateTime)value; return DateTimeEx.FormatDateSpecific(dateValue, dateFormat); } public static XrmDateBindingOptions GetDateBindingOptions(Column columnDef) { object options = columnDef.Options; XrmDateBindingOptions dateOptions = null; if (options != null && options.GetType() == typeof(string)) { dateOptions = new XrmDateBindingOptions(); dateOptions.OverrideUserDateFormat = (string)columnDef.Options; return dateOptions; } else if (options!=null) { dateOptions = (XrmDateBindingOptions)options; } else { dateOptions = new XrmDateBindingOptions(); } return dateOptions; } public static string GetDateFormat(Column columnDef) { string dateFormat = GetDateBindingOptions(columnDef).OverrideUserDateFormat; if (dateFormat == null && OrganizationServiceProxy.UserSettings != null) { dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString; } return dateFormat; } public static string FormatterDateAndTime(int row, int cell, object value, Column columnDef, object dataContext) { string dateFormat = GetDateFormat(columnDef); if (dateFormat!=null && OrganizationServiceProxy.UserSettings != null) { dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString + " " + OrganizationServiceProxy.UserSettings.TimeFormatString; } DateTime dateValue = (DateTime)value; return DateTimeEx.FormatDateSpecific(dateValue, dateFormat); } private jQueryObject _input; private jQueryObject _container; private DateTime _defaultValue=null; private bool _calendarOpen = false; private DateTime _selectedValue = null; private string _dateFormat = "dd/mm/yy"; public XrmDateEditor(EditorArguments args) : base(args) { XrmDateEditor self = this; _container = jQuery.FromHtml("<div ><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr>" + "<td><INPUT type=text class='sparkle-input-inline' /></td>" + "<td class='lookup-button-td'><input type=button class='sparkle-imagestrip-inlineedit_calendar_icon' /></td></tr></table></div>"); _container.AppendTo(_args.Container); _input = _container.Find(".sparkle-input-inline"); _input.Bind("keydown.nav", delegate(jQueryEvent e) { if (!_calendarOpen && (e.Which == 38 || e.Which == 40) && e.CtrlKey) // Ctrl-Up/Down shows date picker { _input.Plugin<DatePickerPlugIn>().DatePicker(DatePickerMethod2.Show); e.StopImmediatePropagation(); } else if (_calendarOpen && e.Which == 13) { e.PreventDefault(); } }); jQueryObject selectButton = _container.Find(".sparkle-imagestrip-inlineedit_calendar_icon"); _input.Focus().Select(); DatePickerOptions2 options2 = new DatePickerOptions2(); options2.ShowOtherMonths = true; options2.ShowOn = ""; // Date Pickers in CRM do not show when they are focused - you click the button options2.FirstDay = OrganizationServiceProxy.OrganizationSettings != null ? OrganizationServiceProxy.OrganizationSettings.WeekStartDayCode.Value.Value : 0; options2.BeforeShow = delegate() { this._calendarOpen = true; }; options2.OnClose = delegate() { this._calendarOpen = false; _selectedValue = GetSelectedValue(); }; options2.OnSelect = delegate(string dateString, object instance) { // Select the date text field when selecting a date Focus(); }; if (OrganizationServiceProxy.UserSettings != null) { _dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString; } options2.DateFormat = _dateFormat; _input.Plugin<DatePickerPlugIn>().DatePicker(options2); // Wire up the date picker button selectButton.Click(delegate(jQueryEvent e){ _input.Plugin<DatePickerPlugIn>().DatePicker(DatePickerMethod2.Show); Focus(); }); } public override void Destroy() { ((jQueryObject)Script.Literal("$.datepicker.dpDiv")).Stop(true, true); _input.Plugin<DatePickerPlugIn>().DatePicker(DatePickerMethod2.Hide); _input.Plugin<DatePickerPlugIn>().DatePicker(DatePickerMethod2.Destroy); Hide(); // Ensure the calendar is hidden when ending an edit _container.Remove(); } public override void Show() { if (_calendarOpen) { ((jQueryObject)Script.Literal("$.datepicker.dpDiv")).Stop(true, true).Show(); } } public override void Hide() { if (_calendarOpen) { ((jQueryObject)Script.Literal("$.datepicker.dpDiv")).Stop(true, true).Hide(); } } public override void Position(jQueryPosition position) { if (!_calendarOpen) { return; } ((jQueryObject)Script.Literal("$.datepicker.dpDiv")).CSS("top", (position.Top + 30).ToString()).CSS("left", position.Left.ToString()); } public override void Focus() { _input.Focus(); } public override void LoadValue(Dictionary<string, object> item) { DateTime currentValue = (DateTime)item[_args.Column.Field]; _defaultValue = currentValue!=null ? currentValue : null; string valueFormated = _defaultValue != null ? _defaultValue.ToLocaleDateString() : String.Empty; if (_args.Column.Formatter != null) { valueFormated = _args.Column.Formatter(0, 0, _defaultValue, _args.Column, null); } SetSelectedValue(_defaultValue); _input.Select(); } public override object SerializeValue() { return GetSelectedValue(); } public override void ApplyValue(Dictionary<string, object> item, object state) { DateTime previousValue = (DateTime)item[_args.Column.Field]; DateTime newValue = (DateTime)state; // If the existing value is null, set the default time if (previousValue == null) { XrmDateBindingOptions options = GetDateBindingOptions(_args.Column); previousValue = new DateTime(1900, 1, 1, options.Hour!=null ? options.Hour.Value :0, options.Minute!=null? options.Minute.Value : 0); } DateTimeEx.SetTime(newValue, previousValue); item[_args.Column.Field] = newValue; this.RaiseOnChange(item); } public override bool IsValueChanged() { DateTime selectedValue = GetSelectedValue(); string selected = selectedValue == null ? "" : selectedValue.ToString(); string defaultValueString = _defaultValue == null ? "" : _defaultValue.ToString(); return (selected!=defaultValueString); } private DateTime GetSelectedValue() { DateTime selectedValue = null; if (!_calendarOpen) { selectedValue = DateTimeEx.ParseDateSpecific(_input.GetValue(), _dateFormat); } else { selectedValue = (DateTime)_input.Plugin<DatePickerObject>().DatePicker(DatePickerMethod.GetDate); } return selectedValue; } private void SetSelectedValue(DateTime date) { _input.Plugin<DatePickerObject>().DatePicker(DatePickerMethod.SetDate, date); } public static Column BindColumn(Column column, bool dateOnly) { column.Editor = CrmDateEditor; column.Formatter = FormatterDateOnly; return column; } public static Column BindReadOnlyColumn(Column column, bool dateOnly) { column.Formatter = FormatterDateOnly; return column; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; namespace Microsoft.PythonTools.Profiling { [Serializable] public sealed class ProfilingTarget { internal static XmlSerializer Serializer = new XmlSerializer(typeof(ProfilingTarget)); [XmlElement("ProjectTarget")] public ProjectTarget ProjectTarget { get; set; } [XmlElement("StandaloneTarget")] public StandaloneTarget StandaloneTarget { get; set; } [XmlElement("Reports")] public Reports Reports { get; set; } internal string GetProfilingName(IServiceProvider serviceProvider, out bool save) { string baseName = null; if (ProjectTarget != null) { if (!String.IsNullOrEmpty(ProjectTarget.FriendlyName)) { baseName = ProjectTarget.FriendlyName; } } else if (StandaloneTarget != null) { if (!String.IsNullOrEmpty(StandaloneTarget.Script)) { baseName = Path.GetFileNameWithoutExtension(StandaloneTarget.Script); } } if (baseName == null) { baseName = "Performance"; } baseName = baseName + ".pyperf"; var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE)); if (dte.Solution.IsOpen && !String.IsNullOrEmpty(dte.Solution.FullName)) { save = true; return Path.Combine(Path.GetDirectoryName(dte.Solution.FullName), baseName); } save = false; return baseName; } internal ProfilingTarget Clone() { var res = new ProfilingTarget(); if (ProjectTarget != null) { res.ProjectTarget = ProjectTarget.Clone(); } if (StandaloneTarget != null) { res.StandaloneTarget = StandaloneTarget.Clone(); } if (Reports != null) { res.Reports = Reports.Clone(); } return res; } internal static bool IsSame(ProfilingTarget self, ProfilingTarget other) { if (self == null) { return other == null; } else if (other != null) { return ProjectTarget.IsSame(self.ProjectTarget, other.ProjectTarget) && StandaloneTarget.IsSame(self.StandaloneTarget, other.StandaloneTarget); } return false; } } [Serializable] public sealed class ProjectTarget { [XmlElement("TargetProject")] public Guid TargetProject { get; set; } [XmlElement("FriendlyName")] public string FriendlyName { get; set; } internal ProjectTarget Clone() { var res = new ProjectTarget(); res.TargetProject = TargetProject; res.FriendlyName = FriendlyName; return res; } internal static bool IsSame(ProjectTarget self, ProjectTarget other) { if (self == null) { return other == null; } else if (other != null) { return self.TargetProject == other.TargetProject; } return false; } } [Serializable] public sealed class StandaloneTarget { [XmlElement(ElementName = "PythonInterpreter")] public PythonInterpreter PythonInterpreter { get; set; } [XmlElement(ElementName = "InterpreterPath")] public string InterpreterPath { get; set; } [XmlElement("WorkingDirectory")] public string WorkingDirectory { get; set; } [XmlElement("Script")] public string Script { get; set; } [XmlElement("Arguments")] public string Arguments { get; set; } internal StandaloneTarget Clone() { var res = new StandaloneTarget(); if (PythonInterpreter != null) { res.PythonInterpreter = PythonInterpreter.Clone(); } res.InterpreterPath = InterpreterPath; res.WorkingDirectory = WorkingDirectory; res.Script = Script; res.Arguments = Arguments; return res; } internal static bool IsSame(StandaloneTarget self, StandaloneTarget other) { if (self == null) { return other == null; } else if (other != null) { return PythonInterpreter.IsSame(self.PythonInterpreter, other.PythonInterpreter) && self.InterpreterPath == other.InterpreterPath && self.WorkingDirectory == other.WorkingDirectory && self.Script == other.Script && self.Arguments == other.Arguments; } return false; } } public sealed class PythonInterpreter { [XmlElement("Id")] public Guid Id { get; set; } [XmlElement("Version")] public string Version { get; set; } internal PythonInterpreter Clone() { var res = new PythonInterpreter(); res.Id = Id; res.Version = Version; return res; } internal static bool IsSame(PythonInterpreter self, PythonInterpreter other) { if (self == null) { return other == null; } else if (other != null) { return self.Id == other.Id && self.Version == other.Version; } return false; } } public sealed class Reports { public Reports() { } public Reports(Profiling.Report[] reports) { Report = reports; } [XmlElement("Report")] public Report[] Report { get { return AllReports.Values.ToArray(); } set { AllReports = new SortedDictionary<uint, Report>(); for (uint i = 0; i < value.Length; i++) { AllReports[i + SessionNode.StartingReportId] = value[i]; } } } internal SortedDictionary<uint, Report> AllReports { get; set; } internal Reports Clone() { var res = new Reports(); if (Report != null) { res.Report = new Report[Report.Length]; for (int i = 0; i < res.Report.Length; i++) { res.Report[i] = Report[i].Clone(); } } return res; } } public sealed class Report { public Report() { } public Report(string filename) { Filename = filename; } [XmlElement("Filename")] public string Filename { get; set; } internal Report Clone() { var res = new Report(); res.Filename = Filename; return res; } } }