context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System.Collections; namespace NAssert.Constraints { /// <summary> /// Delegate used to delay evaluation of the actual value /// to be used in evaluating a constraint /// </summary> public delegate object ActualValueDelegate(); /// <summary> /// The Constraint class is the base of all built-in constraints /// within NUnit. It provides the operator overloads used to combine /// constraints. /// </summary> public abstract class Constraint : IResolveConstraint { #region UnsetObject Class /// <summary> /// Class used to detect any derived constraints /// that fail to set the actual value in their /// Matches override. /// </summary> private class UnsetObject { public override string ToString() { return "UNSET"; } } #endregion #region Static and Instance Fields /// <summary> /// Static UnsetObject used to detect derived constraints /// failing to set the actual value. /// </summary> protected static object UNSET = new UnsetObject(); /// <summary> /// The actual value being tested against a constraint /// </summary> protected object actual = UNSET; /// <summary> /// The display name of this Constraint for use by ToString() /// </summary> private string displayName; /// <summary> /// Argument fields used by ToString(); /// </summary> private readonly int argcnt; private readonly object arg1; private readonly object arg2; /// <summary> /// The builder holding this constraint /// </summary> private ConstraintBuilder builder; #endregion #region Constructors /// <summary> /// Construct a constraint with no arguments /// </summary> public Constraint() { argcnt = 0; } /// <summary> /// Construct a constraint with one argument /// </summary> public Constraint(object arg) { argcnt = 1; this.arg1 = arg; } /// <summary> /// Construct a constraint with two arguments /// </summary> public Constraint(object arg1, object arg2) { argcnt = 2; this.arg1 = arg1; this.arg2 = arg2; } #endregion #region Set Containing ConstraintBuilder /// <summary> /// Sets the ConstraintBuilder holding this constraint /// </summary> internal void SetBuilder(ConstraintBuilder builder) { this.builder = builder; } #endregion #region Properties /// <summary> /// The display name of this Constraint for use by ToString(). /// The default value is the name of the constraint with /// trailing "Constraint" removed. Derived classes may set /// this to another name in their constructors. /// </summary> public string DisplayName { get { if (displayName == null) { displayName = this.GetType().Name.ToLower(); if (displayName.EndsWith("`1") || displayName.EndsWith("`2")) displayName = displayName.Substring(0, displayName.Length - 2); if (displayName.EndsWith("constraint")) displayName = displayName.Substring(0, displayName.Length - 10); } return displayName; } set { displayName = value; } } #endregion #region Abstract and Virtual Methods /// <summary> /// Write the failure message to the MessageWriter provided /// as an argument. The default implementation simply passes /// the constraint and the actual value to the writer, which /// then displays the constraint description and the value. /// /// Constraints that need to provide additional details, /// such as where the error occured can override this. /// </summary> /// <param name="writer">The MessageWriter on which to display the message</param> public virtual void WriteMessageTo(MessageWriter writer) { writer.DisplayDifferences(this); } /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public abstract bool Matches(object actual); /// <summary> /// Test whether the constraint is satisfied by an /// ActualValueDelegate that returns the value to be tested. /// The default implementation simply evaluates the delegate /// but derived classes may override it to provide for delayed /// processing. /// </summary> /// <param name="del">An ActualValueDelegate</param> /// <returns>True for success, false for failure</returns> public virtual bool Matches(ActualValueDelegate del) { return Matches(del()); } #if NET_2_0 /// <summary> /// Test whether the constraint is satisfied by a given reference. /// The default implementation simply dereferences the value but /// derived classes may override it to provide for delayed processing. /// </summary> /// <param name="actual">A reference to the value to be tested</param> /// <returns>True for success, false for failure</returns> public virtual bool Matches<T>(ref T actual) { return Matches(actual); } #else /// <summary> /// Test whether the constraint is satisfied by a given bool reference. /// The default implementation simply dereferences the value but /// derived classes may override it to provide for delayed processing. /// </summary> /// <param name="actual">A reference to the value to be tested</param> /// <returns>True for success, false for failure</returns> public virtual bool Matches(ref bool actual) { return Matches(actual); } #endif /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public abstract void WriteDescriptionTo(MessageWriter writer); /// <summary> /// Write the actual value for a failing constraint test to a /// MessageWriter. The default implementation simply writes /// the raw value of actual, leaving it to the writer to /// perform any formatting. /// </summary> /// <param name="writer">The writer on which the actual value is displayed</param> public virtual void WriteActualValueTo(MessageWriter writer) { writer.WriteActualValue( actual ); } #endregion #region ToString Override /// <summary> /// Default override of ToString returns the constraint DisplayName /// followed by any arguments within angle brackets. /// </summary> /// <returns></returns> public override string ToString() { string rep = GetStringRepresentation(); return this.builder == null ? rep : string.Format("<unresolved {0}>", rep); } /// <summary> /// Returns the string representation of this constraint /// </summary> protected virtual string GetStringRepresentation() { switch (argcnt) { default: case 0: return string.Format("<{0}>", DisplayName); case 1: return string.Format("<{0} {1}>", DisplayName, _displayable(arg1)); case 2: return string.Format("<{0} {1} {2}>", DisplayName, _displayable(arg1), _displayable(arg2)); } } private string _displayable(object o) { if (o == null) return "null"; string fmt = o is string ? "\"{0}\"" : "{0}"; return string.Format(System.Globalization.CultureInfo.InvariantCulture, fmt, o); } #endregion #region Operator Overloads /// <summary> /// This operator creates a constraint that is satisfied only if both /// argument constraints are satisfied. /// </summary> public static Constraint operator &(Constraint left, Constraint right) { IResolveConstraint l = (IResolveConstraint)left; IResolveConstraint r = (IResolveConstraint)right; return new AndConstraint(l.Resolve(), r.Resolve()); } /// <summary> /// This operator creates a constraint that is satisfied if either /// of the argument constraints is satisfied. /// </summary> public static Constraint operator |(Constraint left, Constraint right) { IResolveConstraint l = (IResolveConstraint)left; IResolveConstraint r = (IResolveConstraint)right; return new OrConstraint(l.Resolve(), r.Resolve()); } /// <summary> /// This operator creates a constraint that is satisfied if the /// argument constraint is not satisfied. /// </summary> public static Constraint operator !(Constraint constraint) { IResolveConstraint r = constraint as IResolveConstraint; return new NotConstraint(r == null ? new NullConstraint() : r.Resolve()); } #endregion #region Binary Operators /// <summary> /// Returns a ConstraintExpression by appending And /// to the current constraint. /// </summary> public ConstraintExpression And { get { ConstraintBuilder builder = this.builder; if (builder == null) { builder = new ConstraintBuilder(); builder.Append(this); } builder.Append(new AndOperator()); return new ConstraintExpression(builder); } } /// <summary> /// Returns a ConstraintExpression by appending And /// to the current constraint. /// </summary> public ConstraintExpression With { get { return this.And; } } /// <summary> /// Returns a ConstraintExpression by appending Or /// to the current constraint. /// </summary> public ConstraintExpression Or { get { ConstraintBuilder builder = this.builder; if (builder == null) { builder = new ConstraintBuilder(); builder.Append(this); } builder.Append(new OrOperator()); return new ConstraintExpression(builder); } } #endregion #region After Modifier /// <summary> /// Returns a DelayedConstraint with the specified delay time. /// </summary> /// <param name="delayInMilliseconds">The delay in milliseconds.</param> /// <returns></returns> public DelayedConstraint After(int delayInMilliseconds) { return new DelayedConstraint( builder == null ? this : builder.Resolve(), delayInMilliseconds); } /// <summary> /// Returns a DelayedConstraint with the specified delay time /// and polling interval. /// </summary> /// <param name="delayInMilliseconds">The delay in milliseconds.</param> /// <param name="pollingInterval">The interval at which to test the constraint.</param> /// <returns></returns> public DelayedConstraint After(int delayInMilliseconds, int pollingInterval) { return new DelayedConstraint( builder == null ? this : builder.Resolve(), delayInMilliseconds, pollingInterval); } #endregion #region IResolveConstraint Members Constraint IResolveConstraint.Resolve() { return builder == null ? this : builder.Resolve(); } #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.Data.Common; using System.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Data.SqlClient { sealed internal class SqlSequentialTextReader : System.IO.TextReader { private SqlDataReader _reader; // The SqlDataReader that we are reading data from private int _columnIndex; // The index of out column in the table private Encoding _encoding; // Encoding for this character stream private Decoder _decoder; // Decoder based on the encoding (NOTE: Decoders are stateful as they are designed to process streams of data) private byte[] _leftOverBytes; // Bytes leftover from the last Read() operation - this can be null if there were no bytes leftover (Possible optimization: re-use the same array?) private int _peekedChar; // The last character that we peeked at (or -1 if we haven't peeked at anything) private Task _currentTask; // The current async task private CancellationTokenSource _disposalTokenSource; // Used to indicate that a cancellation is requested due to disposal internal SqlSequentialTextReader(SqlDataReader reader, int columnIndex, Encoding encoding) { Debug.Assert(reader != null, "Null reader when creating sequential textreader"); Debug.Assert(columnIndex >= 0, "Invalid column index when creating sequential textreader"); Debug.Assert(encoding != null, "Null encoding when creating sequential textreader"); _reader = reader; _columnIndex = columnIndex; _encoding = encoding; _decoder = encoding.GetDecoder(); _leftOverBytes = null; _peekedChar = -1; _currentTask = null; _disposalTokenSource = new CancellationTokenSource(); } internal int ColumnIndex { get { return _columnIndex; } } public override int Peek() { if (_currentTask != null) { throw ADP.AsyncOperationPending(); } if (IsClosed) { throw ADP.ObjectDisposed(this); } if (!HasPeekedChar) { _peekedChar = Read(); } Debug.Assert(_peekedChar == -1 || ((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue)), $"Bad peeked character: {_peekedChar}"); return _peekedChar; } public override int Read() { if (_currentTask != null) { throw ADP.AsyncOperationPending(); } if (IsClosed) { throw ADP.ObjectDisposed(this); } int readChar = -1; // If there is already a peeked char, then return it if (HasPeekedChar) { readChar = _peekedChar; _peekedChar = -1; } // If there is data available try to read a char else { char[] tempBuffer = new char[1]; int charsRead = InternalRead(tempBuffer, 0, 1); if (charsRead == 1) { readChar = tempBuffer[0]; } } Debug.Assert(readChar == -1 || ((readChar >= char.MinValue) && (readChar <= char.MaxValue)), $"Bad read character: {readChar}"); return readChar; } public override int Read(char[] buffer, int index, int count) { ValidateReadParameters(buffer, index, count); if (IsClosed) { throw ADP.ObjectDisposed(this); } if (_currentTask != null) { throw ADP.AsyncOperationPending(); } int charsRead = 0; int charsNeeded = count; // Load in peeked char if ((charsNeeded > 0) && (HasPeekedChar)) { Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), $"Bad peeked character: {_peekedChar}"); buffer[index + charsRead] = (char)_peekedChar; charsRead++; charsNeeded--; _peekedChar = -1; } // If we need more data and there is data available, read charsRead += InternalRead(buffer, index + charsRead, charsNeeded); return charsRead; } public override Task<int> ReadAsync(char[] buffer, int index, int count) { ValidateReadParameters(buffer, index, count); TaskCompletionSource<int> completion = new TaskCompletionSource<int>(); if (IsClosed) { completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this))); } else { try { Task original = Interlocked.CompareExchange<Task>(ref _currentTask, completion.Task, null); if (original != null) { completion.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending())); } else { bool completedSynchronously = true; int charsRead = 0; int adjustedIndex = index; int charsNeeded = count; // Load in peeked char if ((HasPeekedChar) && (charsNeeded > 0)) { // Take a copy of _peekedChar in case it is cleared during close int peekedChar = _peekedChar; if (peekedChar >= char.MinValue) { Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), $"Bad peeked character: {_peekedChar}"); buffer[adjustedIndex] = (char)peekedChar; adjustedIndex++; charsRead++; charsNeeded--; _peekedChar = -1; } } int byteBufferUsed; byte[] byteBuffer = PrepareByteBuffer(charsNeeded, out byteBufferUsed); // Permit a 0 byte read in order to advance the reader to the correct column if ((byteBufferUsed < byteBuffer.Length) || (byteBuffer.Length == 0)) { int bytesRead; var reader = _reader; if (reader != null) { Task<int> getBytesTask = reader.GetBytesAsync(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed, Timeout.Infinite, _disposalTokenSource.Token, out bytesRead); if (getBytesTask == null) { byteBufferUsed += bytesRead; } else { // We need more data - setup the callback, and mark this as not completed sync completedSynchronously = false; getBytesTask.ContinueWith((t) => { _currentTask = null; // If we completed but the textreader is closed, then report cancellation if ((t.Status == TaskStatus.RanToCompletion) && (!IsClosed)) { try { int bytesReadFromStream = t.Result; byteBufferUsed += bytesReadFromStream; if (byteBufferUsed > 0) { charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded); } completion.SetResult(charsRead); } catch (Exception ex) { completion.SetException(ex); } } else if (IsClosed) { completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this))); } else if (t.Status == TaskStatus.Faulted) { if (t.Exception.InnerException is SqlException) { // ReadAsync can't throw a SqlException, so wrap it in an IOException completion.SetException(ADP.ExceptionWithStackTrace(ADP.ErrorReadingFromStream(t.Exception.InnerException))); } else { completion.SetException(t.Exception.InnerException); } } else { completion.SetCanceled(); } }, TaskScheduler.Default); } if ((completedSynchronously) && (byteBufferUsed > 0)) { // No more data needed, decode what we have charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded); } } else { // Reader is null, close must of happened in the middle of this read completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this))); } } if (completedSynchronously) { _currentTask = null; if (IsClosed) { completion.SetCanceled(); } else { completion.SetResult(charsRead); } } } } catch (Exception ex) { // In case of any errors, ensure that the completion is completed and the task is set back to null if we switched it completion.TrySetException(ex); Interlocked.CompareExchange(ref _currentTask, null, completion.Task); throw; } } return completion.Task; } protected override void Dispose(bool disposing) { if (disposing) { // Set the textreader as closed SetClosed(); } base.Dispose(disposing); } /// <summary> /// Forces the TextReader to act as if it was closed /// This does not actually close the stream, read off the rest of the data or dispose this /// </summary> internal void SetClosed() { _disposalTokenSource.Cancel(); _reader = null; _peekedChar = -1; // Wait for pending task var currentTask = _currentTask; if (currentTask != null) { ((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne(); } } /// <summary> /// Performs the actual reading and converting /// NOTE: This assumes that buffer, index and count are all valid, we're not closed (!IsClosed) and that there is data left (IsDataLeft()) /// </summary> /// <param name="buffer"></param> /// <param name="index"></param> /// <param name="count"></param> /// <returns></returns> private int InternalRead(char[] buffer, int index, int count) { Debug.Assert(buffer != null, "Null output buffer"); Debug.Assert((index >= 0) && (count >= 0) && (index + count <= buffer.Length), $"Bad count: {count} or index: {index}"); Debug.Assert(!IsClosed, "Can't read while textreader is closed"); try { int byteBufferUsed; byte[] byteBuffer = PrepareByteBuffer(count, out byteBufferUsed); byteBufferUsed += _reader.GetBytesInternalSequential(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed); if (byteBufferUsed > 0) { return DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, index, count); } else { // Nothing to read, or nothing read return 0; } } catch (SqlException ex) { // Read can't throw a SqlException - so wrap it in an IOException throw ADP.ErrorReadingFromStream(ex); } } /// <summary> /// Creates a byte array large enough to store all bytes for the characters in the current encoding, then fills it with any leftover bytes /// </summary> /// <param name="numberOfChars">Number of characters that are to be read</param> /// <param name="byteBufferUsed">Number of bytes pre-filled by the leftover bytes</param> /// <returns>A byte array of the correct size, pre-filled with leftover bytes</returns> private byte[] PrepareByteBuffer(int numberOfChars, out int byteBufferUsed) { Debug.Assert(numberOfChars >= 0, "Can't prepare a byte buffer for negative characters"); byte[] byteBuffer; if (numberOfChars == 0) { byteBuffer = Array.Empty<byte>(); byteBufferUsed = 0; } else { int byteBufferSize = _encoding.GetMaxByteCount(numberOfChars); if (_leftOverBytes != null) { // If we have more leftover bytes than we need for this conversion, then just re-use the leftover buffer if (_leftOverBytes.Length > byteBufferSize) { byteBuffer = _leftOverBytes; byteBufferUsed = byteBuffer.Length; } else { // Otherwise, copy over the leftover buffer byteBuffer = new byte[byteBufferSize]; Buffer.BlockCopy(_leftOverBytes, 0, byteBuffer, 0, _leftOverBytes.Length); byteBufferUsed = _leftOverBytes.Length; } } else { byteBuffer = new byte[byteBufferSize]; byteBufferUsed = 0; } } return byteBuffer; } /// <summary> /// Decodes the given bytes into characters, and stores the leftover bytes for later use /// </summary> /// <param name="inBuffer">Buffer of bytes to decode</param> /// <param name="inBufferCount">Number of bytes to decode from the inBuffer</param> /// <param name="outBuffer">Buffer to write the characters to</param> /// <param name="outBufferOffset">Offset to start writing to outBuffer at</param> /// <param name="outBufferCount">Maximum number of characters to decode</param> /// <returns>The actual number of characters decoded</returns> private int DecodeBytesToChars(byte[] inBuffer, int inBufferCount, char[] outBuffer, int outBufferOffset, int outBufferCount) { Debug.Assert(inBuffer != null, "Null input buffer"); Debug.Assert((inBufferCount > 0) && (inBufferCount <= inBuffer.Length), $"Bad inBufferCount: {inBufferCount}"); Debug.Assert(outBuffer != null, "Null output buffer"); Debug.Assert((outBufferOffset >= 0) && (outBufferCount > 0) && (outBufferOffset + outBufferCount <= outBuffer.Length), $"Bad outBufferCount: {outBufferCount} or outBufferOffset: {outBufferOffset}"); int charsRead; int bytesUsed; bool completed; _decoder.Convert(inBuffer, 0, inBufferCount, outBuffer, outBufferOffset, outBufferCount, false, out bytesUsed, out charsRead, out completed); // completed may be false and there is no spare bytes if the Decoder has stored bytes to use later if ((!completed) && (bytesUsed < inBufferCount)) { _leftOverBytes = new byte[inBufferCount - bytesUsed]; Buffer.BlockCopy(inBuffer, bytesUsed, _leftOverBytes, 0, _leftOverBytes.Length); } else { // If Convert() sets completed to true, then it must have used all of the bytes we gave it Debug.Assert(bytesUsed >= inBufferCount, "Converted completed, but not all bytes were used"); _leftOverBytes = null; } Debug.Assert(((_reader == null) || (_reader.ColumnDataBytesRemaining() > 0) || (!completed) || (_leftOverBytes == null)), "Stream has run out of data and the decoder finished, but there are leftover bytes"); Debug.Assert(charsRead > 0, "Converted no chars. Bad encoding?"); return charsRead; } /// <summary> /// True if this TextReader is supposed to be closed /// </summary> private bool IsClosed { get { return (_reader == null); } } /// <summary> /// True if there is a peeked character available /// </summary> private bool HasPeekedChar { get { return (_peekedChar >= char.MinValue); } } /// <summary> /// Checks the parameters passed into a Read() method are valid /// </summary> /// <param name="buffer"></param> /// <param name="index"></param> /// <param name="count"></param> internal static void ValidateReadParameters(char[] buffer, int index, int count) { if (buffer == null) { throw ADP.ArgumentNull(nameof(buffer)); } if (index < 0) { throw ADP.ArgumentOutOfRange(nameof(index)); } if (count < 0) { throw ADP.ArgumentOutOfRange(nameof(count)); } try { if (checked(index + count) > buffer.Length) { throw ExceptionBuilder.InvalidOffsetLength(); } } catch (OverflowException) { // If we've overflowed when adding index and count, then they never would have fit into buffer anyway throw ExceptionBuilder.InvalidOffsetLength(); } } } sealed internal class SqlUnicodeEncoding : UnicodeEncoding { private static SqlUnicodeEncoding s_singletonEncoding = new SqlUnicodeEncoding(); private SqlUnicodeEncoding() : base(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: false) { } public override Decoder GetDecoder() { return new SqlUnicodeDecoder(); } public override int GetMaxByteCount(int charCount) { // SQL Server never sends a BOM, so we can assume that its 2 bytes per char return charCount * 2; } public static Encoding SqlUnicodeEncodingInstance { get { return s_singletonEncoding; } } sealed private class SqlUnicodeDecoder : Decoder { public override int GetCharCount(byte[] bytes, int index, int count) { // SQL Server never sends a BOM, so we can assume that its 2 bytes per char return count / 2; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // This method is required - simply call Convert() int bytesUsed; int charsUsed; bool completed; Convert(bytes, byteIndex, byteCount, chars, charIndex, chars.Length - charIndex, true, out bytesUsed, out charsUsed, out completed); return charsUsed; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Assume 2 bytes per char and no BOM charsUsed = Math.Min(charCount, byteCount / 2); bytesUsed = charsUsed * 2; completed = (bytesUsed == byteCount); // BlockCopy uses offsets\length measured in bytes, not the actual array index Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * 2, bytesUsed); } } } }
#region License /* * HttpListenerRequest.cs * * This code is derived from HttpListenerRequest.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2018 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Text; namespace WebSocketSharp.Net { /// <summary> /// Represents an incoming HTTP request to a <see cref="HttpListener"/> /// instance. /// </summary> /// <remarks> /// This class cannot be inherited. /// </remarks> public sealed class HttpListenerRequest { #region Private Fields private static readonly byte[] _100continue; private string[] _acceptTypes; private bool _chunked; private HttpConnection _connection; private Encoding _contentEncoding; private long _contentLength; private HttpListenerContext _context; private CookieCollection _cookies; private WebHeaderCollection _headers; private string _httpMethod; private Stream _inputStream; private Version _protocolVersion; private NameValueCollection _queryString; private string _rawUrl; private Guid _requestTraceIdentifier; private Uri _url; private Uri _urlReferrer; private bool _urlSet; private string _userHostName; private string[] _userLanguages; #endregion #region Static Constructor static HttpListenerRequest () { _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n"); } #endregion #region Internal Constructors internal HttpListenerRequest (HttpListenerContext context) { _context = context; _connection = context.Connection; _contentLength = -1; _headers = new WebHeaderCollection (); _requestTraceIdentifier = Guid.NewGuid (); } #endregion #region Public Properties /// <summary> /// Gets the media types that are acceptable for the client. /// </summary> /// <value> /// <para> /// An array of <see cref="string"/> that contains the names of the media /// types specified in the value of the Accept header. /// </para> /// <para> /// <see langword="null"/> if the header is not present. /// </para> /// </value> public string[] AcceptTypes { get { var val = _headers["Accept"]; if (val == null) return null; if (_acceptTypes == null) { _acceptTypes = val .SplitHeaderValue (',') .Trim () .ToList () .ToArray (); } return _acceptTypes; } } /// <summary> /// Gets an error code that identifies a problem with the certificate /// provided by the client. /// </summary> /// <value> /// An <see cref="int"/> that represents an error code. /// </value> /// <exception cref="NotSupportedException"> /// This property is not supported. /// </exception> public int ClientCertificateError { get { throw new NotSupportedException (); } } /// <summary> /// Gets the encoding for the entity body data included in the request. /// </summary> /// <value> /// <para> /// A <see cref="Encoding"/> converted from the charset value of the /// Content-Type header. /// </para> /// <para> /// <see cref="Encoding.UTF8"/> if the charset value is not available. /// </para> /// </value> public Encoding ContentEncoding { get { if (_contentEncoding == null) _contentEncoding = getContentEncoding () ?? Encoding.UTF8; return _contentEncoding; } } /// <summary> /// Gets the length in bytes of the entity body data included in the /// request. /// </summary> /// <value> /// <para> /// A <see cref="long"/> converted from the value of the Content-Length /// header. /// </para> /// <para> /// -1 if the header is not present. /// </para> /// </value> public long ContentLength64 { get { return _contentLength; } } /// <summary> /// Gets the media type of the entity body data included in the request. /// </summary> /// <value> /// <para> /// A <see cref="string"/> that represents the value of the Content-Type /// header. /// </para> /// <para> /// <see langword="null"/> if the header is not present. /// </para> /// </value> public string ContentType { get { return _headers["Content-Type"]; } } /// <summary> /// Gets the cookies included in the request. /// </summary> /// <value> /// <para> /// A <see cref="CookieCollection"/> that contains the cookies. /// </para> /// <para> /// An empty collection if not included. /// </para> /// </value> public CookieCollection Cookies { get { if (_cookies == null) _cookies = _headers.GetCookies (false); return _cookies; } } /// <summary> /// Gets a value indicating whether the request has the entity body data. /// </summary> /// <value> /// <c>true</c> if the request has the entity body data; otherwise, /// <c>false</c>. /// </value> public bool HasEntityBody { get { return _contentLength > 0 || _chunked; } } /// <summary> /// Gets the headers included in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the headers. /// </value> public NameValueCollection Headers { get { return _headers; } } /// <summary> /// Gets the HTTP method specified by the client. /// </summary> /// <value> /// A <see cref="string"/> that represents the HTTP method specified in /// the request line. /// </value> public string HttpMethod { get { return _httpMethod; } } /// <summary> /// Gets a stream that contains the entity body data included in /// the request. /// </summary> /// <value> /// <para> /// A <see cref="Stream"/> that contains the entity body data. /// </para> /// <para> /// <see cref="Stream.Null"/> if the entity body data is not available. /// </para> /// </value> public Stream InputStream { get { if (_inputStream == null) _inputStream = getInputStream () ?? Stream.Null; return _inputStream; } } /// <summary> /// Gets a value indicating whether the client is authenticated. /// </summary> /// <value> /// <c>true</c> if the client is authenticated; otherwise, <c>false</c>. /// </value> public bool IsAuthenticated { get { return _context.User != null; } } /// <summary> /// Gets a value indicating whether the request is sent from the local /// computer. /// </summary> /// <value> /// <c>true</c> if the request is sent from the same computer as the server; /// otherwise, <c>false</c>. /// </value> public bool IsLocal { get { return _connection.IsLocal; } } /// <summary> /// Gets a value indicating whether a secure connection is used to send /// the request. /// </summary> /// <value> /// <c>true</c> if the connection is secure; otherwise, <c>false</c>. /// </value> public bool IsSecureConnection { get { return _connection.IsSecure; } } /// <summary> /// Gets a value indicating whether the request is a WebSocket handshake /// request. /// </summary> /// <value> /// <c>true</c> if the request is a WebSocket handshake request; otherwise, /// <c>false</c>. /// </value> public bool IsWebSocketRequest { get { return _httpMethod == "GET" && _protocolVersion > HttpVersion.Version10 && _headers.Upgrades ("websocket"); } } /// <summary> /// Gets a value indicating whether a persistent connection is requested. /// </summary> /// <value> /// <c>true</c> if the request specifies that the connection is kept open; /// otherwise, <c>false</c>. /// </value> public bool KeepAlive { get { return _headers.KeepsAlive (_protocolVersion); } } /// <summary> /// Gets the endpoint to which the request is sent. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the server IP /// address and port number. /// </value> public System.Net.IPEndPoint LocalEndPoint { get { return _connection.LocalEndPoint; } } /// <summary> /// Gets the HTTP version specified by the client. /// </summary> /// <value> /// A <see cref="Version"/> that represents the HTTP version specified in /// the request line. /// </value> public Version ProtocolVersion { get { return _protocolVersion; } } /// <summary> /// Gets the query string included in the request. /// </summary> /// <value> /// <para> /// A <see cref="NameValueCollection"/> that contains the query /// parameters. /// </para> /// <para> /// An empty collection if not included. /// </para> /// </value> public NameValueCollection QueryString { get { if (_queryString == null) { var url = Url; _queryString = QueryStringCollection.Parse ( url != null ? url.Query : null, Encoding.UTF8 ); } return _queryString; } } /// <summary> /// Gets the raw URL specified by the client. /// </summary> /// <value> /// A <see cref="string"/> that represents the request target specified in /// the request line. /// </value> public string RawUrl { get { return _rawUrl; } } /// <summary> /// Gets the endpoint from which the request is sent. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the client IP /// address and port number. /// </value> public System.Net.IPEndPoint RemoteEndPoint { get { return _connection.RemoteEndPoint; } } /// <summary> /// Gets the trace identifier of the request. /// </summary> /// <value> /// A <see cref="Guid"/> that represents the trace identifier. /// </value> public Guid RequestTraceIdentifier { get { return _requestTraceIdentifier; } } /// <summary> /// Gets the URL requested by the client. /// </summary> /// <value> /// <para> /// A <see cref="Uri"/> that represents the URL parsed from the request. /// </para> /// <para> /// <see langword="null"/> if the URL cannot be parsed. /// </para> /// </value> public Uri Url { get { if (!_urlSet) { _url = HttpUtility.CreateRequestUrl ( _rawUrl, _userHostName ?? UserHostAddress, IsWebSocketRequest, IsSecureConnection ); _urlSet = true; } return _url; } } /// <summary> /// Gets the URI of the resource from which the requested URL was obtained. /// </summary> /// <value> /// <para> /// A <see cref="Uri"/> converted from the value of the Referer header. /// </para> /// <para> /// <see langword="null"/> if the header value is not available. /// </para> /// </value> public Uri UrlReferrer { get { var val = _headers["Referer"]; if (val == null) return null; if (_urlReferrer == null) _urlReferrer = val.ToUri (); return _urlReferrer; } } /// <summary> /// Gets the user agent from which the request is originated. /// </summary> /// <value> /// <para> /// A <see cref="string"/> that represents the value of the User-Agent /// header. /// </para> /// <para> /// <see langword="null"/> if the header is not present. /// </para> /// </value> public string UserAgent { get { return _headers["User-Agent"]; } } /// <summary> /// Gets the IP address and port number to which the request is sent. /// </summary> /// <value> /// A <see cref="string"/> that represents the server IP address and port /// number. /// </value> public string UserHostAddress { get { return _connection.LocalEndPoint.ToString (); } } /// <summary> /// Gets the server host name requested by the client. /// </summary> /// <value> /// <para> /// A <see cref="string"/> that represents the value of the Host header. /// </para> /// <para> /// It includes the port number if provided. /// </para> /// <para> /// <see langword="null"/> if the header is not present. /// </para> /// </value> public string UserHostName { get { return _userHostName; } } /// <summary> /// Gets the natural languages that are acceptable for the client. /// </summary> /// <value> /// <para> /// An array of <see cref="string"/> that contains the names of the /// natural languages specified in the value of the Accept-Language /// header. /// </para> /// <para> /// <see langword="null"/> if the header is not present. /// </para> /// </value> public string[] UserLanguages { get { var val = _headers["Accept-Language"]; if (val == null) return null; if (_userLanguages == null) _userLanguages = val.Split (',').Trim ().ToList ().ToArray (); return _userLanguages; } } #endregion #region Private Methods private void finishInitialization10 () { var transferEnc = _headers["Transfer-Encoding"]; if (transferEnc != null) { _context.ErrorMessage = "Invalid Transfer-Encoding header"; return; } if (_httpMethod == "POST") { if (_contentLength == -1) { _context.ErrorMessage = "Content-Length header required"; return; } if (_contentLength == 0) { _context.ErrorMessage = "Invalid Content-Length header"; return; } } } private Encoding getContentEncoding () { var val = _headers["Content-Type"]; if (val == null) return null; Encoding ret; HttpUtility.TryGetEncoding (val, out ret); return ret; } private RequestStream getInputStream () { return _contentLength > 0 || _chunked ? _connection.GetRequestStream (_contentLength, _chunked) : null; } #endregion #region Internal Methods internal void AddHeader (string headerField) { var start = headerField[0]; if (start == ' ' || start == '\t') { _context.ErrorMessage = "Invalid header field"; return; } var colon = headerField.IndexOf (':'); if (colon < 1) { _context.ErrorMessage = "Invalid header field"; return; } var name = headerField.Substring (0, colon).Trim (); if (name.Length == 0 || !name.IsToken ()) { _context.ErrorMessage = "Invalid header name"; return; } var val = colon < headerField.Length - 1 ? headerField.Substring (colon + 1).Trim () : String.Empty; _headers.InternalSet (name, val, false); var lower = name.ToLower (CultureInfo.InvariantCulture); if (lower == "host") { if (_userHostName != null) { _context.ErrorMessage = "Invalid Host header"; return; } if (val.Length == 0) { _context.ErrorMessage = "Invalid Host header"; return; } _userHostName = val; return; } if (lower == "content-length") { if (_contentLength > -1) { _context.ErrorMessage = "Invalid Content-Length header"; return; } long len; if (!Int64.TryParse (val, out len)) { _context.ErrorMessage = "Invalid Content-Length header"; return; } if (len < 0) { _context.ErrorMessage = "Invalid Content-Length header"; return; } _contentLength = len; return; } } internal void FinishInitialization () { if (_protocolVersion == HttpVersion.Version10) { finishInitialization10 (); return; } if (_userHostName == null) { _context.ErrorMessage = "Host header required"; return; } var transferEnc = _headers["Transfer-Encoding"]; if (transferEnc != null) { var comparison = StringComparison.OrdinalIgnoreCase; if (!transferEnc.Equals ("chunked", comparison)) { _context.ErrorMessage = String.Empty; _context.ErrorStatus = 501; return; } _chunked = true; } if (_httpMethod == "POST" || _httpMethod == "PUT") { if (_contentLength <= 0 && !_chunked) { _context.ErrorMessage = String.Empty; _context.ErrorStatus = 411; return; } } var expect = _headers["Expect"]; if (expect != null) { var comparison = StringComparison.OrdinalIgnoreCase; if (!expect.Equals ("100-continue", comparison)) { _context.ErrorMessage = "Invalid Expect header"; return; } var output = _connection.GetResponseStream (); output.InternalWrite (_100continue, 0, _100continue.Length); } } internal bool FlushInput () { var input = InputStream; if (input == Stream.Null) return true; var len = 2048; if (_contentLength > 0 && _contentLength < len) len = (int) _contentLength; var buff = new byte[len]; while (true) { try { var ares = input.BeginRead (buff, 0, len, null, null); if (!ares.IsCompleted) { var timeout = 100; if (!ares.AsyncWaitHandle.WaitOne (timeout)) return false; } if (input.EndRead (ares) <= 0) return true; } catch { return false; } } } internal bool IsUpgradeRequest (string protocol) { return _headers.Upgrades (protocol); } internal void SetRequestLine (string requestLine) { var parts = requestLine.Split (new[] { ' ' }, 3); if (parts.Length < 3) { _context.ErrorMessage = "Invalid request line (parts)"; return; } var method = parts[0]; if (method.Length == 0) { _context.ErrorMessage = "Invalid request line (method)"; return; } var target = parts[1]; if (target.Length == 0) { _context.ErrorMessage = "Invalid request line (target)"; return; } var rawVer = parts[2]; if (rawVer.Length != 8) { _context.ErrorMessage = "Invalid request line (version)"; return; } if (rawVer.IndexOf ("HTTP/") != 0) { _context.ErrorMessage = "Invalid request line (version)"; return; } Version ver; if (!rawVer.Substring (5).TryCreateVersion (out ver)) { _context.ErrorMessage = "Invalid request line (version)"; return; } if (ver.Major < 1) { _context.ErrorMessage = "Invalid request line (version)"; return; } if (!method.IsHttpMethod (ver)) { _context.ErrorMessage = "Invalid request line (method)"; return; } _httpMethod = method; _rawUrl = target; _protocolVersion = ver; } #endregion #region Public Methods /// <summary> /// Begins getting the certificate provided by the client asynchronously. /// </summary> /// <returns> /// An <see cref="IAsyncResult"/> instance that indicates the status of the /// operation. /// </returns> /// <param name="requestCallback"> /// An <see cref="AsyncCallback"/> delegate that invokes the method called /// when the operation is complete. /// </param> /// <param name="state"> /// An <see cref="object"/> that represents a user defined object to pass to /// the callback delegate. /// </param> /// <exception cref="NotSupportedException"> /// This method is not supported. /// </exception> public IAsyncResult BeginGetClientCertificate ( AsyncCallback requestCallback, object state ) { throw new NotSupportedException (); } /// <summary> /// Ends an asynchronous operation to get the certificate provided by the /// client. /// </summary> /// <returns> /// A <see cref="X509Certificate2"/> that represents an X.509 certificate /// provided by the client. /// </returns> /// <param name="asyncResult"> /// An <see cref="IAsyncResult"/> instance returned when the operation /// started. /// </param> /// <exception cref="NotSupportedException"> /// This method is not supported. /// </exception> public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult) { throw new NotSupportedException (); } /// <summary> /// Gets the certificate provided by the client. /// </summary> /// <returns> /// A <see cref="X509Certificate2"/> that represents an X.509 certificate /// provided by the client. /// </returns> /// <exception cref="NotSupportedException"> /// This method is not supported. /// </exception> public X509Certificate2 GetClientCertificate () { throw new NotSupportedException (); } /// <summary> /// Returns a string that represents the current instance. /// </summary> /// <returns> /// A <see cref="string"/> that contains the request line and headers /// included in the request. /// </returns> public override string ToString () { var buff = new StringBuilder (64); buff .AppendFormat ( "{0} {1} HTTP/{2}\r\n", _httpMethod, _rawUrl, _protocolVersion ) .Append (_headers.ToString ()); return buff.ToString (); } #endregion } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** namespace NUnit.Util { using System; using System.Globalization; using System.IO; using System.Xml; using System.Collections; using System.Reflection; using NUnit.Core; /// <summary> /// Summary description for XmlResultWriter. /// </summary> public class XmlResultWriter { private XmlTextWriter xmlWriter; private TextWriter writer; private MemoryStream memoryStream; #region Constructors public XmlResultWriter(string fileName) { xmlWriter = new XmlTextWriter( new StreamWriter(fileName, false, System.Text.Encoding.UTF8) ); } public XmlResultWriter( TextWriter writer ) { this.memoryStream = new MemoryStream(); this.writer = writer; this.xmlWriter = new XmlTextWriter( new StreamWriter( memoryStream, System.Text.Encoding.UTF8 ) ); } #endregion private void InitializeXmlFile(TestResult result) { ResultSummarizer summaryResults = new ResultSummarizer(result); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartDocument(false); xmlWriter.WriteComment("This file represents the results of running a test suite"); xmlWriter.WriteStartElement("test-results"); xmlWriter.WriteAttributeString("name", summaryResults.Name); xmlWriter.WriteAttributeString("total", summaryResults.TestsRun.ToString()); xmlWriter.WriteAttributeString("errors", summaryResults.Errors.ToString()); xmlWriter.WriteAttributeString("failures", summaryResults.Failures.ToString()); xmlWriter.WriteAttributeString("not-run", summaryResults.TestsNotRun.ToString()); xmlWriter.WriteAttributeString("inconclusive", summaryResults.Inconclusive.ToString()); xmlWriter.WriteAttributeString("ignored", summaryResults.Ignored.ToString()); xmlWriter.WriteAttributeString("skipped", summaryResults.Skipped.ToString()); xmlWriter.WriteAttributeString("invalid", summaryResults.NotRunnable.ToString()); DateTime now = DateTime.Now; xmlWriter.WriteAttributeString("date", XmlConvert.ToString( now, "yyyy-MM-dd" ) ); xmlWriter.WriteAttributeString("time", XmlConvert.ToString( now, "HH:mm:ss" )); WriteEnvironment(); WriteCultureInfo(); } private void WriteCultureInfo() { xmlWriter.WriteStartElement("culture-info"); xmlWriter.WriteAttributeString("current-culture", CultureInfo.CurrentCulture.ToString()); xmlWriter.WriteAttributeString("current-uiculture", CultureInfo.CurrentUICulture.ToString()); xmlWriter.WriteEndElement(); } private void WriteEnvironment() { xmlWriter.WriteStartElement("environment"); xmlWriter.WriteAttributeString("nunit-version", Assembly.GetExecutingAssembly().GetName().Version.ToString()); xmlWriter.WriteAttributeString("clr-version", Environment.Version.ToString()); xmlWriter.WriteAttributeString("os-version", Environment.OSVersion.ToString()); xmlWriter.WriteAttributeString("platform", Environment.OSVersion.Platform.ToString()); xmlWriter.WriteAttributeString("cwd", Environment.CurrentDirectory); xmlWriter.WriteAttributeString("machine-name", Environment.MachineName); xmlWriter.WriteAttributeString("user", Environment.UserName); xmlWriter.WriteAttributeString("user-domain", Environment.UserDomainName); xmlWriter.WriteEndElement(); } #region Public Methods public void SaveTestResult( TestResult result ) { InitializeXmlFile( result ); WriteResultElement( result ); TerminateXmlFile(); } private void WriteResultElement( TestResult result ) { StartTestElement( result ); WriteCategoriesElement(result); WritePropertiesElement(result); switch (result.ResultState) { case ResultState.Ignored: case ResultState.NotRunnable: case ResultState.Skipped: WriteReasonElement(result); break; case ResultState.Failure: case ResultState.Error: case ResultState.Cancelled: if (!result.Test.IsSuite || result.FailureSite == FailureSite.SetUp) WriteFailureElement(result); break; case ResultState.Success: case ResultState.Inconclusive: if (result.Message != null) WriteReasonElement(result); break; } if ( result.HasResults ) WriteChildResults( result ); xmlWriter.WriteEndElement(); // test element } private void TerminateXmlFile() { try { xmlWriter.WriteEndElement(); // test-results xmlWriter.WriteEndDocument(); xmlWriter.Flush(); if ( memoryStream != null && writer != null ) { memoryStream.Position = 0; using ( StreamReader rdr = new StreamReader( memoryStream ) ) { writer.Write( rdr.ReadToEnd() ); } } xmlWriter.Close(); } finally { //writer.Close(); } } #endregion #region Element Creation Helpers private void StartTestElement(TestResult result) { if (result.Test.IsSuite) { xmlWriter.WriteStartElement("test-suite"); xmlWriter.WriteAttributeString("type", result.Test.TestType); xmlWriter.WriteAttributeString("name", result.Name); } else { xmlWriter.WriteStartElement("test-case"); xmlWriter.WriteAttributeString("name", result.FullName); } if (result.Description != null) xmlWriter.WriteAttributeString("description", result.Description); xmlWriter.WriteAttributeString("executed", result.Executed.ToString()); xmlWriter.WriteAttributeString("result", result.ResultState.ToString()); if ( result.Executed ) { xmlWriter.WriteAttributeString("success", result.IsSuccess.ToString()); xmlWriter.WriteAttributeString("time", result.Time.ToString("#####0.000", NumberFormatInfo.InvariantInfo)); xmlWriter.WriteAttributeString("asserts", result.AssertCount.ToString()); } } private void WriteCategoriesElement(TestResult result) { if (result.Test.Categories != null && result.Test.Categories.Count > 0) { xmlWriter.WriteStartElement("categories"); foreach (string category in result.Test.Categories) { xmlWriter.WriteStartElement("category"); xmlWriter.WriteAttributeString("name", category); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } } private void WritePropertiesElement(TestResult result) { IDictionary props = result.Test.Properties; if (result.Test.Properties != null && props.Count > 0) { int nprops = 0; foreach (string key in result.Test.Properties.Keys) { if ( !key.StartsWith("_") ) { object val = result.Test.Properties[key]; if (val != null) { if ( nprops == 0 ) xmlWriter.WriteStartElement("properties"); xmlWriter.WriteStartElement("property"); xmlWriter.WriteAttributeString("name", key); xmlWriter.WriteAttributeString("value", val.ToString()); xmlWriter.WriteEndElement(); ++nprops; } } } if ( nprops > 0 ) xmlWriter.WriteEndElement(); } } private void WriteReasonElement(TestResult result) { xmlWriter.WriteStartElement("reason"); xmlWriter.WriteStartElement("message"); xmlWriter.WriteCData(result.Message); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); } private void WriteFailureElement(TestResult result) { xmlWriter.WriteStartElement("failure"); xmlWriter.WriteStartElement("message"); WriteCData(result.Message); xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("stack-trace"); if (result.StackTrace != null) WriteCData(StackTraceFilter.Filter(result.StackTrace)); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); } private void WriteChildResults(TestResult result) { xmlWriter.WriteStartElement("results"); if ( result.HasResults ) foreach (TestResult childResult in result.Results) WriteResultElement( childResult ); xmlWriter.WriteEndElement(); } #endregion #region Output Helpers /// <summary> /// Makes string safe for xml parsing, replacing control chars with '?' /// </summary> /// <param name="encodedString">string to make safe</param> /// <returns>xml safe string</returns> private static string CharacterSafeString(string encodedString) { /*The default code page for the system will be used. Since all code pages use the same lower 128 bytes, this should be sufficient for finding uprintable control characters that make the xslt processor error. We use characters encoded by the default code page to avoid mistaking bytes as individual characters on non-latin code pages.*/ char[] encodedChars = System.Text.Encoding.Default.GetChars(System.Text.Encoding.Default.GetBytes(encodedString)); System.Collections.ArrayList pos = new System.Collections.ArrayList(); for(int x = 0 ; x < encodedChars.Length ; x++) { char currentChar = encodedChars[x]; //unprintable characters are below 0x20 in Unicode tables //some control characters are acceptable. (carriage return 0x0D, line feed 0x0A, horizontal tab 0x09) if(currentChar < 32 && (currentChar != 9 && currentChar != 10 && currentChar != 13)) { //save the array index for later replacement. pos.Add(x); } } foreach(int index in pos) { encodedChars[index] = '?';//replace unprintable control characters with ?(3F) } return System.Text.Encoding.Default.GetString(System.Text.Encoding.Default.GetBytes(encodedChars)); } private void WriteCData(string text) { int start = 0; while (true) { int illegal = text.IndexOf("]]>", start); if (illegal < 0) break; xmlWriter.WriteCData(text.Substring(start, illegal - start + 2)); start = illegal + 2; if (start >= text.Length) return; } if (start > 0) xmlWriter.WriteCData(text.Substring(start)); else xmlWriter.WriteCData(text); } #endregion } }
// // <copyright file="TableStorageSessionStateProvider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // This file contains an implementation of a session state provider that uses both blob and table storage. using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Configuration.Provider; using System.Data.Services.Client; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Security; using System.Web; using System.Web.SessionState; using Microsoft.WindowsAzure.StorageClient; using Microsoft.WindowsAzure; namespace Microsoft.Samples.ServiceHosting.AspProviders { /// <summary> /// This class allows DevtableGen to generate the correct table (named 'Sessions') /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification="Class is used by the devtablegen tool to generate a database for the development storage tool")] internal class SessionDataServiceContext : TableServiceContext { public SessionDataServiceContext() : base(null, null) { } public IQueryable<SessionRow> Sessions { get { return this.CreateQuery<SessionRow>("Sessions"); } } } [CLSCompliant(false)] public class SessionRow : TableServiceEntity { private string _id; private string _applicationName; private string _blobName; private DateTime _expires; private DateTime _created; private DateTime _lockDate; // application name + session id is partitionKey public SessionRow(string sessionId, string applicationName) : base() { SecUtility.CheckParameter(ref sessionId, true, true, true, Configuration.MaxStringPropertySizeInChars, "sessionId"); SecUtility.CheckParameter(ref applicationName, true, true, true, Constants.MaxTableApplicationNameLength, "applicationName"); PartitionKey = SecUtility.CombineToKey(applicationName, sessionId); RowKey = string.Empty; Id = sessionId; ApplicationName = applicationName; ExpiresUtc = Configuration.MinSupportedDateTime; LockDateUtc = Configuration.MinSupportedDateTime; CreatedUtc = Configuration.MinSupportedDateTime; Timeout = 0; BlobName = string.Empty; } public SessionRow() : base() { } public string Id { set { if (value == null) { throw new ArgumentException("To ensure string values are always updated, this implementation does not allow null as a string value."); } _id = value; PartitionKey = SecUtility.CombineToKey(ApplicationName, Id); } get { return _id; } } public string ApplicationName { set { if (value == null) { throw new ArgumentException("To ensure string values are always updated, this implementation does not allow null as a string value."); } _applicationName = value; PartitionKey = SecUtility.CombineToKey(ApplicationName, Id); } get { return _applicationName; } } public int Timeout { set; get; } public DateTime ExpiresUtc { set { SecUtility.SetUtcTime(value, out _expires); } get { return _expires; } } public DateTime CreatedUtc { set { SecUtility.SetUtcTime(value, out _created); } get { return _created; } } public DateTime LockDateUtc { set { SecUtility.SetUtcTime(value, out _lockDate); } get { return _lockDate; } } public bool Locked { set; get; } public int Lock { set; get; } public string BlobName { set { if (value == null) { throw new ArgumentException("To ensure string values are always updated, this implementation does not allow null as a string value."); } _blobName = value; } get { return _blobName; } } public bool Initialized { set; get; } } public class TableStorageSessionStateProvider : SessionStateStoreProviderBase { #region Member variables and constants private string _applicationName; private string _tableName; private string _containerName; private CloudTableClient _tableStorage; private BlobProvider _blobProvider; private const int NumRetries = 3; private RetryPolicy _tableRetry = RetryPolicies.Retry(NumRetries, TimeSpan.FromSeconds(1)); private ProviderRetryPolicy _providerRetry = ProviderRetryPolicies.RetryN(NumRetries, TimeSpan.FromSeconds(1)); #endregion private static object thisLock = new Object(); #region public methods public override void Initialize(string name, NameValueCollection config) { // Verify that config isn't null if (config == null) { throw new ArgumentNullException("config"); } // Assign the provider a default name if it doesn't have one if (String.IsNullOrEmpty(name)) { name = "TableServiceSessionStateProvider"; } // Add a default "description" attribute to config if the // attribute doesn't exist or is empty if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Session state provider using table storage"); } // Call the base class's Initialize method base.Initialize(name, config); bool allowInsecureRemoteEndpoints = Configuration.GetBooleanValue(config, "allowInsecureRemoteEndpoints", false); // structure storage-related properties _applicationName = Configuration.GetStringValueWithGlobalDefault(config, "applicationName", Configuration.DefaultProviderApplicationNameConfigurationString, Configuration.DefaultProviderApplicationName, false); _tableName = Configuration.GetStringValueWithGlobalDefault(config, "sessionTableName", Configuration.DefaultSessionTableNameConfigurationString, Configuration.DefaultSessionTableName, false); _containerName = Configuration.GetStringValueWithGlobalDefault(config, "containerName", Configuration.DefaultSessionContainerNameConfigurationString, Configuration.DefaultSessionContainerName, false); if (!SecUtility.IsValidContainerName(_containerName)) { throw new ProviderException("The provider configuration for the TableStorageSessionStateProvider does not contain a valid container name. " + "Please refer to the documentation for the concrete rules for valid container names." + "The current container name is: " + _containerName); } config.Remove("allowInsecureRemoteEndpoints"); config.Remove("containerName"); config.Remove("applicationName"); config.Remove("sessionTableName"); // Throw an exception if unrecognized attributes remain if (config.Count > 0) { string attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) throw new ProviderException ("Unrecognized attribute: " + attr); } CloudStorageAccount account = null; try { account = Configuration.GetStorageAccount(Configuration.DefaultStorageConfigurationString); SecUtility.CheckAllowInsecureEndpoints(allowInsecureRemoteEndpoints, account.Credentials, account.TableEndpoint); SecUtility.CheckAllowInsecureEndpoints(allowInsecureRemoteEndpoints, account.Credentials, account.BlobEndpoint); _tableStorage = account.CreateCloudTableClient(); _tableStorage.RetryPolicy = _tableRetry; lock (thisLock) { _tableStorage.CreateTableIfNotExist<SessionRow>(_tableName); } _blobProvider = new BlobProvider(account.Credentials, account.BlobEndpoint, _containerName); } catch (SecurityException) { throw; } // catch InvalidOperationException as well as StorageException catch (Exception e) { string exceptionDescription = Configuration.GetInitExceptionDescription(account.Credentials, account.TableEndpoint, account.BlobEndpoint); string tableName = (_tableName == null) ? "no session table name specified" : _tableName; string containerName = (_containerName == null) ? "no container name specified" : _containerName; Log.Write(EventKind.Error, "Initialization of data service structures (tables and/or blobs) failed!" + exceptionDescription + Environment.NewLine + "Configured blob container: " + containerName + Environment.NewLine + "Configured table name: " + tableName + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace); throw new ProviderException("Initialization of data service structures (tables and/or blobs) failed!" + "The most probable reason for this is that " + "the storage endpoints are not configured correctly. Please look at the configuration settings " + "in your .cscfg and Web.config files. More information about this error " + "can be found in the logs when running inside the hosting environment or in the output " + "window of Visual Studio.", e); } Debug.Assert(_blobProvider != null); } public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout) { Debug.Assert(context != null); return new SessionStateStoreData(new SessionStateItemCollection(), SessionStateUtility.GetSessionStaticObjects(context), timeout); } public override void CreateUninitializedItem(HttpContext context, string id, int timeout) { Debug.Assert(context != null); SecUtility.CheckParameter(ref id, true, true, false, Configuration.MaxStringPropertySizeInChars, "id"); if (timeout < 0) { throw new ArgumentException("Parameter timeout must be a non-negative integer!"); } try { TableServiceContext svc = CreateDataServiceContext(); SessionRow session = new SessionRow(id, _applicationName); session.Lock = 0; // no lock session.Initialized = false; session.Id = id; session.Timeout = timeout; session.ExpiresUtc = DateTime.UtcNow.AddMinutes(timeout); svc.AddObject(_tableName, session); svc.SaveChangesWithRetries(); } catch (InvalidOperationException e) { throw new ProviderException("Error accessing the data store.", e); } } public override SessionStateStoreData GetItem(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { Debug.Assert(context != null); SecUtility.CheckParameter(ref id, true, true, false, Configuration.MaxStringPropertySizeInChars, "id"); return GetSession(context, id, out locked, out lockAge, out lockId, out actions, false); } public override SessionStateStoreData GetItemExclusive(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { Debug.Assert(context != null); SecUtility.CheckParameter(ref id, true, true, false, Configuration.MaxStringPropertySizeInChars, "id"); return GetSession(context, id, out locked, out lockAge, out lockId, out actions, true); } public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem) { Debug.Assert(context != null); SecUtility.CheckParameter(ref id, true, true, false, Configuration.MaxStringPropertySizeInChars, "id"); _providerRetry(() => { TableServiceContext svc = CreateDataServiceContext(); SessionRow session; if (!newItem) { session = GetSession(id, svc); if (session == null || session.Lock != (int)lockId) { Debug.Assert(false); return; } } else { session = new SessionRow(id, _applicationName); session.Lock = 1; session.LockDateUtc = DateTime.UtcNow; } session.Initialized = true; Debug.Assert(session.Timeout >= 0); session.Timeout = item.Timeout; session.ExpiresUtc = DateTime.UtcNow.AddMinutes(session.Timeout); session.Locked = false; // yes, we always create a new blob here session.BlobName = GetBlobNamePrefix(id) + Guid.NewGuid().ToString("N"); // Serialize the session and write the blob byte[] items, statics; SerializeSession(item, out items, out statics); string serializedItems = Convert.ToBase64String(items); string serializedStatics = Convert.ToBase64String(statics); MemoryStream output = new MemoryStream(); StreamWriter writer = new StreamWriter(output); try { writer.WriteLine(serializedItems); writer.WriteLine(serializedStatics); writer.Flush(); // for us, it shouldn't matter whether newItem is set to true or false // because we always create the entire blob and cannot append to an // existing one _blobProvider.UploadStream(session.BlobName, output); writer.Close(); output.Close(); } catch (Exception e) { if (!newItem) { ReleaseItemExclusive(svc, session, lockId); } throw new ProviderException("Error accessing the data store.", e); } finally { if (writer != null) { writer.Close(); } if (output != null) { output.Close(); } } if (newItem) { svc.AddObject(_tableName, session); svc.SaveChangesWithRetries(); } else { // Unlock the session and save changes ReleaseItemExclusive(svc, session, lockId); } }); } public override void ReleaseItemExclusive(HttpContext context, string id, object lockId) { Debug.Assert(context != null); Debug.Assert(lockId != null); SecUtility.CheckParameter(ref id, true, true, false, Configuration.MaxStringPropertySizeInChars, "id"); try { TableServiceContext svc = CreateDataServiceContext(); SessionRow session = GetSession(id, svc); ReleaseItemExclusive(svc, session, lockId); } catch (InvalidOperationException e) { throw new ProviderException("Error accessing the data store!", e); } } public override void ResetItemTimeout(HttpContext context, string id) { Debug.Assert(context != null); SecUtility.CheckParameter(ref id, true, true, false, Configuration.MaxStringPropertySizeInChars, "id"); _providerRetry(() => { TableServiceContext svc = CreateDataServiceContext(); SessionRow session = GetSession(id, svc); session.ExpiresUtc = DateTime.UtcNow.AddMinutes(session.Timeout); svc.UpdateObject(session); svc.SaveChangesWithRetries(); }); } public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item) { Debug.Assert(context != null); Debug.Assert(lockId != null); Debug.Assert(_blobProvider != null); SecUtility.CheckParameter(ref id, true, true, false, Configuration.MaxStringPropertySizeInChars, "id"); try { TableServiceContext svc = CreateDataServiceContext(); SessionRow session = GetSession(id, svc); if (session == null) { Debug.Assert(false); return; } if (session.Lock != (int)lockId) { Debug.Assert(false); return; } svc.DeleteObject(session); svc.SaveChangesWithRetries(); } catch (InvalidOperationException e) { throw new ProviderException("Error accessing the data store!", e); } // delete associated blobs try { IEnumerable<IListBlobItem> e = _blobProvider.ListBlobs(GetBlobNamePrefix(id)); if (e == null) { return; } IEnumerator<IListBlobItem> props = e.GetEnumerator(); if (props == null) { return; } while (props.MoveNext()) { if (props.Current != null) { if (!_blobProvider.DeleteBlob(props.Current.Uri.ToString())) { // ignore this; it is possible that another thread could try to delete the blob // at the same time } } } } catch(Exception e) { throw new ProviderException("Error accessing blob storage.", e); } } public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback) { // This provider doesn't support expiration callbacks // so simply return false here return false; } public override void InitializeRequest(HttpContext context) { // no specific logic for initializing requests in this provider } public override void EndRequest(HttpContext context) { // no specific logic for ending requests in this provider } // nothing can be done here because there might be session managers at different machines involved in // handling sessions public override void Dispose() { } #endregion #region Helper methods private TableServiceContext CreateDataServiceContext() { return _tableStorage.GetDataServiceContext(); } private static void ReleaseItemExclusive(TableServiceContext svc, SessionRow session, object lockId) { if ((int)lockId != session.Lock) { // obviously that can happen, but let's see when at least in Debug mode Debug.Assert(false); return; } session.ExpiresUtc = DateTime.UtcNow.AddMinutes(session.Timeout); session.Locked = false; svc.UpdateObject(session); svc.SaveChangesWithRetries(); } private SessionRow GetSession(string id) { DataServiceContext svc = CreateDataServiceContext(); return GetSession(id, svc); } private SessionRow GetSession(string id, DataServiceContext context) { Debug.Assert(context != null); Debug.Assert(id != null && id.Length <= Configuration.MaxStringPropertySizeInChars); try { DataServiceQuery<SessionRow> queryObj = context.CreateQuery<SessionRow>(_tableName); var query = (from session in queryObj where session.PartitionKey == SecUtility.CombineToKey(_applicationName, id) select session).AsTableServiceQuery(); IEnumerable<SessionRow> sessions = query.Execute(); // enumerate the result and store it in a list List<SessionRow> sessionList = new List<SessionRow>(sessions); if (sessionList != null && sessionList.Count() == 1) { return sessionList.First(); } else if (sessionList != null && sessionList.Count() > 1) { throw new ProviderException("Multiple sessions with the same name!"); } else { return null; } } catch (Exception e) { throw new ProviderException("Error accessing storage.", e); } } // we don't use the retry policy itself in this function because out parameters are not well handled by // retry policies private SessionStateStoreData GetSession(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions, bool exclusive) { Debug.Assert(context != null); SecUtility.CheckParameter(ref id, true, true, false, Configuration.MaxStringPropertySizeInChars, "id"); SessionRow session = null; int curRetry = 0; bool retry = false; // Assign default values to out parameters locked = false; lockId = null; lockAge = TimeSpan.Zero; actions = SessionStateActions.None; do { retry = false; try { TableServiceContext svc = CreateDataServiceContext(); session = GetSession(id, svc); // Assign default values to out parameters locked = false; lockId = null; lockAge = TimeSpan.Zero; actions = SessionStateActions.None; // if the blob does not exist, we return null // ASP.NET will call the corresponding method for creating the session if (session == null) { return null; } if (session.Initialized == false) { Debug.Assert(session.Locked == false); actions = SessionStateActions.InitializeItem; session.Initialized = true; } session.ExpiresUtc = DateTime.UtcNow.AddMinutes(session.Timeout); if (exclusive) { if (!session.Locked) { if (session.Lock == Int32.MaxValue) { session.Lock = 0; } else { session.Lock++; } session.LockDateUtc = DateTime.UtcNow; } lockId = session.Lock; locked = session.Locked; session.Locked = true; } lockAge = DateTime.UtcNow.Subtract(session.LockDateUtc); lockId = session.Lock; if (locked == true) { return null; } // let's try to write this back to the data store // in between, someone else could have written something to the store for the same session // we retry a number of times; if all fails, we throw an exception svc.UpdateObject(session); svc.SaveChangesWithRetries(); } catch (InvalidOperationException e) { // precondition fails indicates problems with the status code if (e.InnerException is DataServiceClientException && (e.InnerException as DataServiceClientException).StatusCode == (int)HttpStatusCode.PreconditionFailed) { retry = true; } else { throw new ProviderException("Error accessing the data store.", e); } } } while (retry && curRetry++ < NumRetries); // ok, now we have successfully written back our state // we can now read the blob // note that we do not need to care about read/write locking when accessing the // blob because each time we write a new session we create a new blob with a different name SessionStateStoreData result = null; MemoryStream stream = null; StreamReader reader = null; BlobProperties properties; try { try { stream = _blobProvider.GetBlobContent(session.BlobName, out properties); } catch (Exception e) { throw new ProviderException("Couldn't read session blob!", e); } reader = new StreamReader(stream); if (actions == SessionStateActions.InitializeItem) { // Return an empty SessionStateStoreData result = new SessionStateStoreData(new SessionStateItemCollection(), SessionStateUtility.GetSessionStaticObjects(context), session.Timeout); } else { // Read Items, StaticObjects, and Timeout from the file byte[] items = Convert.FromBase64String(reader.ReadLine()); byte[] statics = Convert.FromBase64String(reader.ReadLine()); int timeout = session.Timeout; // Deserialize the session result = DeserializeSession(items, statics, timeout); } } finally { if (stream != null) { stream.Close(); } if (reader != null) { reader.Close(); } } return result; } private string GetBlobNamePrefix(string id) { return string.Format(CultureInfo.InstalledUICulture, "{0}{1}", id, _applicationName); } private static void SerializeSession(SessionStateStoreData store, out byte[] items, out byte[] statics) { bool hasItems = (store.Items != null && store.Items.Count > 0); bool hasStaticObjects = (store.StaticObjects != null && store.StaticObjects.Count > 0 && !store.StaticObjects.NeverAccessed); items = null; statics = new byte [0]; using (MemoryStream stream1 = new MemoryStream()) { using (BinaryWriter writer1 = new BinaryWriter(stream1)) { writer1.Write(hasItems); if (hasItems) { ((SessionStateItemCollection)store.Items).Serialize(writer1); } items = stream1.ToArray(); } } if (hasStaticObjects) { throw new ProviderException("Static objects are not supported in this provider because of security-related hosting constraints."); } } private static SessionStateStoreData DeserializeSession(byte[] items, byte[] statics, int timeout) { SessionStateItemCollection itemCol = null; HttpStaticObjectsCollection staticCol = null; using (MemoryStream stream1 = new MemoryStream(items)) { using (BinaryReader reader1 = new BinaryReader(stream1)) { bool hasItems = reader1.ReadBoolean(); if (hasItems) { itemCol = SessionStateItemCollection.Deserialize(reader1); } else { itemCol = new SessionStateItemCollection(); } } } if (HttpContext.Current != null && HttpContext.Current.Application != null && HttpContext.Current.Application.StaticObjects != null && HttpContext.Current.Application.StaticObjects.Count > 0) { throw new ProviderException("This provider does not support static session objects because of security-related hosting constraints."); } if (statics != null && statics.Count() > 0) { throw new ProviderException("This provider does not support static session objects because of security-related hosting constraints."); } return new SessionStateStoreData(itemCol, staticCol, timeout); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using DotVVM.Framework.Utils; using Newtonsoft.Json; using System.Reflection; using DotVVM.Framework.Configuration; using FastExpressionCompiler; namespace DotVVM.Framework.ViewModel.Serialization { /// <summary> /// Performs the JSON serialization for specified type. /// </summary> public class ViewModelSerializationMap { private readonly DotvvmConfiguration configuration; public delegate void ReaderDelegate(JsonReader reader, JsonSerializer serializer, object value, EncryptedValuesReader encryptedValuesReader); public delegate void WriterDelegate(JsonWriter writer, object obj, JsonSerializer serializer, EncryptedValuesWriter evWriter, bool isPostback); /// <summary> /// Gets or sets the object type for this serialization map. /// </summary> public Type Type { get; private set; } public IEnumerable<ViewModelPropertyMap> Properties { get; private set; } /// <summary> Rough structure of Properties when the object was initialized. This is used for hot reload to judge if it can be flushed from the cache. </summary> internal (string name, Type t, Direction direction, ProtectMode protection)[] OriginalProperties { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="ViewModelSerializationMap"/> class. /// </summary> public ViewModelSerializationMap(Type type, IEnumerable<ViewModelPropertyMap> properties, DotvvmConfiguration configuration) { this.configuration = configuration; Type = type; Properties = properties.ToList(); OriginalProperties = Properties.Select(p => (p.Name, p.Type, p.BindDirection, p.ViewModelProtection)).ToArray(); } public void ResetFunctions() { readerFactory = null; writerFactory = null; } private ReaderDelegate? readerFactory; /// <summary> /// Gets the JSON reader factory. /// </summary> public ReaderDelegate ReaderFactory => readerFactory ?? (readerFactory = CreateReaderFactory()); private WriterDelegate? writerFactory; /// <summary> /// Gets the JSON writer factory. /// </summary> public WriterDelegate WriterFactory => writerFactory ?? (writerFactory = CreateWriterFactory()); private Func<IServiceProvider, object>? constructorFactory; /// <summary> /// Gets the constructor factory. /// </summary> public Func<IServiceProvider, object> ConstructorFactory => constructorFactory ?? (constructorFactory = CreateConstructorFactory()); public void SetConstructor(Func<IServiceProvider, object> constructor) => constructorFactory = constructor; /// <summary> /// Creates the constructor for this object. /// </summary> public Func<IServiceProvider, object> CreateConstructorFactory() { var ex = Expression.Lambda<Func<IServiceProvider, object>>(Expression.New(Type), new [] { Expression.Parameter(typeof(IServiceProvider)) }); return ex.CompileFast(flags: CompilerFlags.ThrowOnNotSupportedExpression); } /// <summary> /// Creates the reader factory. /// </summary> public ReaderDelegate CreateReaderFactory() { var block = new List<Expression>(); var reader = Expression.Parameter(typeof(JsonReader), "reader"); var serializer = Expression.Parameter(typeof(JsonSerializer), "serializer"); var valueParam = Expression.Parameter(typeof(object), "valueParam"); var encryptedValuesReader = Expression.Parameter(typeof(EncryptedValuesReader), "encryptedValuesReader"); var value = Expression.Variable(Type, "value"); var currentProperty = Expression.Variable(typeof(string), "currentProperty"); var readerTmp = Expression.Variable(typeof(JsonReader), "readerTmp"); // add current object to encrypted values, this is needed because one property can potentially contain more objects (is a collection) block.Add(Expression.Call(encryptedValuesReader, nameof(EncryptedValuesReader.Nest), Type.EmptyTypes)); // curly brackets are used for variables and methods from the context of this factory method // value = ({Type})valueParam; block.Add(Expression.Assign(value, Expression.Convert(valueParam, Type))); // if the reader is in an invalid state, throw an exception // TODO: Change exception type, just Exception is not exactly descriptive block.Add(ExpressionUtils.Replace((JsonReader rdr) => rdr.TokenType == JsonToken.StartObject ? rdr.Read() : ExpressionUtils.Stub.Throw<bool>(new Exception($"TokenType = StartObject was expected.")), reader)); var propertiesSwitch = new List<SwitchCase>(); // iterate through all properties even if they're gonna get skipped // it's important for the index to count with all the properties that viewModel contains because the client will send some of them only sometimes for (int propertyIndex = 0; propertyIndex < Properties.Count(); propertyIndex++) { var property = Properties.ElementAt(propertyIndex); if (!property.TransferToServer || property.PropertyInfo.SetMethod == null) { continue; } var existingValue = property.Populate ? (Expression)Expression.Convert(Expression.Property(value, property.PropertyInfo), typeof(object)) : Expression.Constant(null, typeof(object)); // when suppressed, we read from the standard properties, because the object is nested in the var isEVSuppressed = Expression.Property(encryptedValuesReader, "Suppressed"); var readEncrypted = property.ViewModelProtection == ProtectMode.EncryptData || property.ViewModelProtection == ProtectMode.SignData; if (readEncrypted) { // encryptedValuesReader.Suppress() // value.{property} = ({property.Type})Deserialize(serializer, encryptedValuesReader.ReadValue({propertyIndex}), {property}, (object)value.{PropertyInfo}); // encryptedValuesReader.EndSuppress() Expression readEncryptedValue = Expression.Block( Expression.Assign( readerTmp, ExpressionUtils.Replace( (EncryptedValuesReader ev) => ev.ReadValue(propertyIndex).CreateReader(), encryptedValuesReader).OptimizeConstants() ), Expression.Call(encryptedValuesReader, "Suppress", Type.EmptyTypes), Expression.Assign( Expression.Property(value, property.PropertyInfo), Expression.Convert( ExpressionUtils.Replace( (JsonSerializer s, JsonReader reader, object existing) => Deserialize(s, reader, property, existing), serializer, readerTmp, existingValue), property.Type) ).OptimizeConstants() ); readEncryptedValue = Expression.TryFinally( readEncryptedValue, Expression.Call(encryptedValuesReader, "EndSuppress", Type.EmptyTypes) ); // if (!encryptedValuesReader.Suppressed) block.Add(Expression.IfThen( Expression.Not(isEVSuppressed), readEncryptedValue )); } // propertyBlock is the body of this currentProperty's switch case var propertyblock = new List<Expression>(); var checkEV = CanContainEncryptedValues(property.Type) && !readEncrypted; if (checkEV) { // encryptedValuesReader.Nest({propertyIndex}); propertyblock.Add(Expression.Call(encryptedValuesReader, nameof(EncryptedValuesReader.Nest), Type.EmptyTypes, Expression.Constant(propertyIndex))); } // existing value is either null or the value {property} depending on property.Populate // value.{property} = ({property.Type})Deserialize(serializer, reader, existing value); propertyblock.Add( Expression.Assign( Expression.Property(value, property.PropertyInfo), Expression.Convert( ExpressionUtils.Replace((JsonSerializer s, JsonReader j, object existingValue) => Deserialize(s, j, property, existingValue), serializer, reader, existingValue), property.Type) )); // reader.Read(); propertyblock.Add( Expression.Call(reader, "Read", Type.EmptyTypes)); if (checkEV) { // encryptedValuesReader.AssertEnd(); propertyblock.Add(Expression.Call(encryptedValuesReader, nameof(EncryptedValuesReader.AssertEnd), Type.EmptyTypes)); } Expression body = Expression.Block(typeof(void), propertyblock); if (readEncrypted) { // only read the property when the reader is suppressed, otherwise do nothing body = Expression.IfThenElse( isEVSuppressed, body, Expression.Block( Expression.IfThen( ExpressionUtils.Replace((JsonReader rdr) => rdr.TokenType == JsonToken.StartArray || rdr.TokenType == JsonToken.StartConstructor || rdr.TokenType == JsonToken.StartObject, reader), Expression.Call(reader, "Skip", Type.EmptyTypes)), Expression.Call(reader, "Read", Type.EmptyTypes)) ); } // create this currentProperty's switch case // case {property.Name}: // {propertyBlock} propertiesSwitch.Add(Expression.SwitchCase( body, Expression.Constant(property.Name) )); } // WARNING: the following code is not commented out. It's a transcription of the expression below it. Yes, it's long. // while(reader reads properties and assigns them to currentProperty) // { // switch(currentProperty) // { // {propertiesSwitch} // default: // if(reader.TokenType == JsonToken.StartArray || reader.TokenType == JsonToken.Start) // { // reader.Skip(); // } // reader.Read(); // } // } block.Add(ExpressionUtils.While( ExpressionUtils.Replace((JsonReader rdr, string val) => rdr.TokenType == JsonToken.PropertyName && ExpressionUtils.Stub.Assign(val, rdr.Value as string) != null && rdr.Read(), reader, currentProperty), ExpressionUtils.Switch(currentProperty, Expression.Block(typeof(void), Expression.IfThen( ExpressionUtils.Replace((JsonReader rdr) => rdr.TokenType == JsonToken.StartArray || rdr.TokenType == JsonToken.StartConstructor || rdr.TokenType == JsonToken.StartObject, reader), Expression.Call(reader, "Skip", Type.EmptyTypes)), Expression.Call(reader, "Read", Type.EmptyTypes)), propertiesSwitch.ToArray()) )); // close encrypted values // encryptedValuesReader.AssertEnd(); block.Add(Expression.Call(encryptedValuesReader, nameof(EncryptedValuesReader.AssertEnd), Type.EmptyTypes)); // return value block.Add(value); // build the lambda expression var ex = Expression.Lambda<ReaderDelegate>( Expression.Convert( Expression.Block(Type, new[] { value, currentProperty, readerTmp }, block), typeof(object)).OptimizeConstants(), reader, serializer, valueParam, encryptedValuesReader); return ex.CompileFast(flags: CompilerFlags.ThrowOnNotSupportedExpression); //return null; } private static Dictionary<Type, MethodInfo> writeValueMethods = (from method in typeof(JsonWriter).GetMethods(BindingFlags.Public | BindingFlags.Instance) where method.Name == nameof(JsonWriter.WriteValue) let parameters = method.GetParameters() where parameters.Length == 1 let parameterType = parameters[0].ParameterType where parameterType != typeof(object) && parameterType != typeof(byte[]) where parameterType != typeof(DateTime) && parameterType != typeof(DateTime?) where parameterType != typeof(DateTimeOffset) && parameterType != typeof(DateTimeOffset?) select new { key = parameterType, value = method } ).ToDictionary(x => x.key, x => x.value); private static Expression GetSerializeExpression(ViewModelPropertyMap property, Expression jsonWriter, Expression value, Expression serializer) { if (property.JsonConverter?.CanWrite == true) { // maybe use the converter. It can't be easily inlined because polymorphism return ExpressionUtils.Replace((JsonSerializer s, JsonWriter w, object v) => Serialize(s, w, property, v), serializer, jsonWriter, Expression.Convert(value, typeof(object))); } else if (writeValueMethods.TryGetValue(value.Type, out var method)) { return Expression.Call(jsonWriter, method, new [] { value }); } else { return Expression.Call(serializer, "Serialize", Type.EmptyTypes, new [] { jsonWriter, Expression.Convert(value, typeof(object)) }); } } private static void Serialize(JsonSerializer serializer, JsonWriter writer, ViewModelPropertyMap property, object value) { if (property.JsonConverter != null && property.JsonConverter.CanWrite && property.JsonConverter.CanConvert(property.Type)) { property.JsonConverter.WriteJson(writer, value, serializer); } else { serializer.Serialize(writer, value); } } private static object? Deserialize(JsonSerializer serializer, JsonReader reader, ViewModelPropertyMap property, object existingValue) { if (property.JsonConverter != null && property.JsonConverter.CanRead && property.JsonConverter.CanConvert(property.Type)) { return property.JsonConverter.ReadJson(reader, property.Type, existingValue, serializer); } else if (existingValue != null && property.Populate) { if (reader.TokenType == JsonToken.Null) return null; else if (reader.TokenType == JsonToken.StartObject) { serializer.Converters.OfType<ViewModelJsonConverter>().First().Populate(reader, serializer, existingValue); return existingValue; } else { serializer.Populate(reader, existingValue); return existingValue; } } else { if (property.Type.IsValueType && reader.TokenType == JsonToken.Null) { return Activator.CreateInstance(property.Type); } else { return serializer.Deserialize(reader, property.Type); } } } /// Gets if this object require $type to be serialized. public bool RequiredTypeField() => true; // possible optimization - types can be inferred from parent metadata in some cases /// <summary> /// Creates the writer factory. /// </summary> public WriterDelegate CreateWriterFactory() { var block = new List<Expression>(); var writer = Expression.Parameter(typeof(JsonWriter), "writer"); var valueParam = Expression.Parameter(typeof(object), "valueParam"); var serializer = Expression.Parameter(typeof(JsonSerializer), "serializer"); var encryptedValuesWriter = Expression.Parameter(typeof(EncryptedValuesWriter), "encryptedValuesWriter"); var isPostback = Expression.Parameter(typeof(bool), "isPostback"); var value = Expression.Variable(Type, "value"); // curly brackets are used for variables and methods from the scope of this factory method // value = ({Type})valueParam; block.Add(Expression.Assign(value, Expression.Convert(valueParam, Type))); // writer.WriteStartObject(); block.Add(Expression.Call(writer, nameof(JsonWriter.WriteStartObject), Type.EmptyTypes)); // encryptedValuesWriter.Nest(); block.Add(Expression.Call(encryptedValuesWriter, nameof(EncryptedValuesWriter.Nest), Type.EmptyTypes)); if (this.RequiredTypeField()) { // writer.WritePropertyName("$type"); block.Add(ExpressionUtils.Replace((JsonWriter w) => w.WritePropertyName("$type"), writer)); // serializer.Serialize(writer, value.GetType().FullName) block.Add(ExpressionUtils.Replace((JsonSerializer s, JsonWriter w, string t) => w.WriteValue(t), serializer, writer, Expression.Constant(Type.GetTypeHash()))); } // go through all properties that should be serialized for (int propertyIndex = 0; propertyIndex < Properties.Count(); propertyIndex++) { var property = Properties.ElementAt(propertyIndex); var endPropertyLabel = Expression.Label("end_property_" + property.Name); if (property.TransferToClient && property.PropertyInfo.GetMethod != null) { if (property.TransferFirstRequest != property.TransferAfterPostback) { if (property.ViewModelProtection != ProtectMode.None) { throw new NotSupportedException($"The {Type}.{property.Name} property cannot user viewmodel protection because it is sent to the client only in some requests."); } Expression condition = isPostback; if (property.TransferAfterPostback) { condition = Expression.Not(condition); } block.Add(Expression.IfThen(condition, Expression.Goto(endPropertyLabel))); } // (object)value.{property.PropertyInfo.Name} var prop = Expression.Property(value, property.PropertyInfo); var writeEV = property.ViewModelProtection == ProtectMode.EncryptData || property.ViewModelProtection == ProtectMode.SignData; if (writeEV) { // encryptedValuesWriter.WriteValue({propertyIndex}, (object)value.{property.PropertyInfo.Name}); block.Add( Expression.Call(encryptedValuesWriter, nameof(EncryptedValuesWriter.WriteValue), Type.EmptyTypes, Expression.Constant(propertyIndex), Expression.Convert(prop, typeof(object)))); } if (property.ViewModelProtection == ProtectMode.None || property.ViewModelProtection == ProtectMode.SignData) { var propertyBlock = new List<Expression>(); var checkEV = CanContainEncryptedValues(property.Type); if (checkEV) { if (writeEV) { // encryptedValuesWriter.Suppress(); propertyBlock.Add(Expression.Call(encryptedValuesWriter, nameof(EncryptedValuesWriter.Suppress), Type.EmptyTypes)); } else { // encryptedValuesWriter.Nest({propertyIndex}); propertyBlock.Add(Expression.Call(encryptedValuesWriter, nameof(EncryptedValuesWriter.Nest), Type.EmptyTypes, Expression.Constant(propertyIndex))); } } // writer.WritePropertyName({property.Name}); propertyBlock.Add(Expression.Call(writer, nameof(JsonWriter.WritePropertyName), Type.EmptyTypes, Expression.Constant(property.Name))); // serializer.Serialize(serializer, writer, {property}, (object)value.{property.PropertyInfo.Name}); propertyBlock.Add(GetSerializeExpression(property, writer, prop, serializer)); Expression propertyFinally = Expression.Default(typeof(void)); if (checkEV) { if (writeEV) { // encryptedValuesWriter.EndSuppress(); propertyFinally = Expression.Call(encryptedValuesWriter, nameof(EncryptedValuesWriter.EndSuppress), Type.EmptyTypes); } // encryption is worthless if the property is not being transferred both ways // therefore ClearEmptyNest throws exception if the property contains encrypted values else if (!property.IsFullyTransferred()) { // encryptedValuesWriter.ClearEmptyNest(); propertyFinally = Expression.Call(encryptedValuesWriter, nameof(EncryptedValuesWriter.ClearEmptyNest), Type.EmptyTypes); } else { // encryptedValuesWriter.End(); propertyFinally = Expression.Call(encryptedValuesWriter, nameof(EncryptedValuesWriter.End), Type.EmptyTypes); } } block.Add( Expression.TryFinally( Expression.Block(propertyBlock), propertyFinally ) ); } } block.Add(Expression.Label(endPropertyLabel)); } // writer.WriteEndObject(); block.Add(ExpressionUtils.Replace<JsonWriter>(w => w.WriteEndObject(), writer)); // encryptedValuesWriter.End(); block.Add(Expression.Call(encryptedValuesWriter, nameof(EncryptedValuesWriter.End), Type.EmptyTypes)); // compile the expression var ex = Expression.Lambda<WriterDelegate>( Expression.Block(new[] { value }, block).OptimizeConstants(), writer, valueParam, serializer, encryptedValuesWriter, isPostback); return ex.CompileFast(flags: CompilerFlags.ThrowOnNotSupportedExpression); } /// <summary> /// Determines whether type can contain encrypted fields /// </summary> private bool CanContainEncryptedValues(Type type) { return !( // primitives can't contain encrypted fields type.IsPrimitive || type.IsEnum || type == typeof(string) ); } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Collections.Generic; using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using System.Runtime.CompilerServices; namespace NLog.UnitTests.LayoutRenderers { using System; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; public class CallSiteTests : NLogTestBase { #if !NETSTANDARD [Fact] public void HiddenAssemblyTest() { const string code = @" namespace Foo { public class HiddenAssemblyLogger { public void LogDebug(NLog.Logger logger) { logger.Debug(""msg""); } } } "; var provider = new Microsoft.CSharp.CSharpCodeProvider(); var parameters = new System.CodeDom.Compiler.CompilerParameters(); // reference the NLog dll parameters.ReferencedAssemblies.Add("NLog.dll"); // the assembly should be generated in memory parameters.GenerateInMemory = true; // generate a dll instead of an executable parameters.GenerateExecutable = false; // compile code and generate assembly System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); Assert.False(results.Errors.HasErrors, "Compiler errors: " + string.Join(";", results.Errors)); // create nlog configuration LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); // create logger Logger logger = LogManager.GetLogger("A"); // load HiddenAssemblyLogger type Assembly compiledAssembly = results.CompiledAssembly; Type hiddenAssemblyLoggerType = compiledAssembly.GetType("Foo.HiddenAssemblyLogger"); Assert.NotNull(hiddenAssemblyLoggerType); // load methodinfo MethodInfo logDebugMethod = hiddenAssemblyLoggerType.GetMethod("LogDebug"); Assert.NotNull(logDebugMethod); // instantiate the HiddenAssemblyLogger from previously generated assembly object instance = Activator.CreateInstance(hiddenAssemblyLoggerType); // Add the previously generated assembly to the "blacklist" LogManager.AddHiddenAssembly(compiledAssembly); // call the log method logDebugMethod.Invoke(instance, new object[] { logger }); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg"); } #endif #if !DEBUG [Fact(Skip = "RELEASE not working, only DEBUG")] #else [Fact] #endif public void LineNumberTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:filename=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); #if !NET4_5 && !MONO #line 100000 #endif logger.Debug("msg"); var linenumber = GetPrevLineNumber(); string lastMessage = GetDebugLastMessage("debug"); // There's a difference in handling line numbers between .NET and Mono // We're just interested in checking if it's above 100000 Assert.True(lastMessage.IndexOf("callsitetests.cs:" + linenumber, StringComparison.OrdinalIgnoreCase) >= 0, "Invalid line number. Expected prefix of 10000, got: " + lastMessage); #if !NET4_5 && !MONO #line default #endif } [Fact] public void MethodNameTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg"); } [Fact] public void MethodNameInChainTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug,debug2' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg2"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug2", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg2"); } [Fact] public void ClassNameTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests msg"); } [Fact] public void ClassNameTestWithoutNamespace() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:includeNamespace=false} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "CallSiteTests msg"); } [Fact] public void ClassNameTestWithOverride() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:includeNamespace=false} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); var logEvent = LogEventInfo.Create(LogLevel.Debug, logger.Name, "msg"); logEvent.SetCallerInfo("NLog.UnitTests.LayoutRenderers.OverrideClassName", nameof(ClassNameTestWithOverride), null, 0); logger.Log(logEvent); AssertDebugLastMessage("debug", "OverrideClassName msg"); } [Fact] public void ClassNameWithPaddingTestPadLeftAlignLeftTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=3:fixedlength=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName.Substring(0, 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadLeftAlignRightTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=3:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); var typeName = currentMethod.DeclaringType.FullName; AssertDebugLastMessage("debug", typeName.Substring(typeName.Length - 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadRightAlignLeftTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=-3:fixedlength=true:alignmentOnTruncation=left} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName.Substring(0, 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadRightAlignRightTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=-3:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); var typeName = currentMethod.DeclaringType.FullName; AssertDebugLastMessage("debug", typeName.Substring(typeName.Length - 3) + " msg"); } [Fact] public void MethodNameWithPaddingTestPadLeftAlignLeftTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=16:fixedlength=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "MethodNameWithPa msg"); } [Fact] public void MethodNameWithPaddingTestPadLeftAlignRightTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=16:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "ftAlignRightTest msg"); } [Fact] public void MethodNameWithPaddingTestPadRightAlignLeftTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=-16:fixedlength=true:alignmentOnTruncation=left} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "MethodNameWithPa msg"); } [Fact] public void MethodNameWithPaddingTestPadRightAlignRightTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=-16:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "htAlignRightTest msg"); } [Fact] public void GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame msg"); } #if !DEBUG [Fact(Skip = "RELEASE not working, only DEBUG")] #else [Fact] #endif public void GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:skipframes=1} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); Action action = () => logger.Debug("msg"); action.Invoke(); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame msg"); } [Fact] public void CleanMethodNamesOfAnonymousDelegatesTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { AssertDebugLastMessage("debug", "CleanMethodNamesOfAnonymousDelegatesTest"); } } [Fact] public void DontCleanMethodNamesOfAnonymousDelegatesTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=false}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { string lastMessage = GetDebugLastMessage("debug"); Assert.StartsWith("<DontCleanMethodNamesOfAnonymousDelegatesTest>", lastMessage); } } [Fact] public void CleanClassNamesOfAnonymousDelegatesTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests"); } } [Fact] public void DontCleanClassNamesOfAnonymousDelegatesTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=false}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { string lastMessage = GetDebugLastMessage("debug"); Assert.Contains("+<>", lastMessage); } } [Fact] public void When_NotIncludeNameSpace_Then_CleanAnonymousDelegateClassNameShouldReturnParentClassName() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:IncludeNamespace=false:CleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { AssertDebugLastMessage("debug", "CallSiteTests"); } } [Fact] public void When_Wrapped_Ignore_Wrapper_Methods_In_Callstack() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_Wrapped_Ignore_Wrapper_Methods_In_Callstack"; LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Warn("direct"); AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct"); LoggerTests.BaseWrapper wrappedLogger = new LoggerTests.MyWrapper(); wrappedLogger.Log("wrapped"); AssertDebugLastMessage("debug", $"{currentMethodFullName}|wrapped"); } [Fact] public void CheckStackTraceUsageForTwoRules() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug2' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForTwoRules msg"); } [Fact] public void CheckStackTraceUsageForTwoRules_chained() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug,debug2' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForTwoRules_chained msg"); } [Fact] public void CheckStackTraceUsageForMultipleRules() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug,debug2' /> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForMultipleRules msg"); } #region Compositio unit test [Fact] public void When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack"; LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Warn("direct"); AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct"); CompositeWrapper wrappedLogger = new CompositeWrapper(); wrappedLogger.Log("wrapped"); AssertDebugLastMessage("debug", $"{currentMethodFullName}|wrapped"); } #if NET3_5 || NET4_0 [Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")] #else [Fact] #endif public void Show_correct_method_with_async() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod"; LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod().Wait(); AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct"); new InnerClassAsyncMethod().AsyncMethod().Wait(); AssertDebugLastMessage("debug", $"{typeof(InnerClassAsyncMethod).ToString()}.AsyncMethod|direct"); } private async Task AsyncMethod() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); } private class InnerClassAsyncMethod { public async Task AsyncMethod() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); } } #if NET3_5 || NET4_0 [Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")] #elif MONO [Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void Show_correct_filename_with_async() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:className=False:fileName=True:includeSourcePath=False:methodName=False}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod().Wait(); Assert.Contains("CallSiteTests.cs", GetDebugLastMessage("debug")); Assert.Contains("|direct", GetDebugLastMessage("debug")); } #if NET3_5 || NET4_0 [Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")] #else [Fact] #endif public void Show_correct_method_with_async2() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod2b"; LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod2a().Wait(); AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct"); new InnerClassAsyncMethod2().AsyncMethod2a().Wait(); AssertDebugLastMessage("debug", $"{typeof(InnerClassAsyncMethod2).ToString()}.AsyncMethod2b|direct"); } private async Task AsyncMethod2a() { await AsyncMethod2b(); } private async Task AsyncMethod2b() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); } private class InnerClassAsyncMethod2 { public async Task AsyncMethod2a() { await AsyncMethod2b(); } public async Task AsyncMethod2b() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); } } #if NET3_5 [Fact(Skip = "NET3_5 not supporting async callstack")] #elif !DEBUG [Fact(Skip = "RELEASE not working, only DEBUG")] #else [Fact] #endif public void Show_correct_method_with_async3() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod3b"; LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod3a().Wait(); AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct"); new InnerClassAsyncMethod3().AsyncMethod3a().Wait(); AssertDebugLastMessage("debug", $"{typeof(InnerClassAsyncMethod3).ToString()}.AsyncMethod3b|direct"); } private async Task AsyncMethod3a() { var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); AsyncMethod3b(); } private void AsyncMethod3b() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); } private class InnerClassAsyncMethod3 { public async Task AsyncMethod3a() { var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); AsyncMethod3b(); } public void AsyncMethod3b() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); } } #if NET3_5 || NET4_0 [Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")] #elif MONO [Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void Show_correct_method_with_async4() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod4"; LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Info' writeTo='debug' /> </rules> </nlog>"); AsyncMethod4().Wait(); AssertDebugLastMessage("debug", $"{currentMethodFullName}|Direct, async method"); new InnerClassAsyncMethod4().AsyncMethod4().Wait(); AssertDebugLastMessage("debug", $"{typeof(InnerClassAsyncMethod4).ToString()}.AsyncMethod4|Direct, async method"); } private async Task<IEnumerable<string>> AsyncMethod4() { Logger logger = LogManager.GetLogger("AnnonTest"); logger.Info("Direct, async method"); return await Task.FromResult(new string[] { "value1", "value2" }); } private class InnerClassAsyncMethod4 { public async Task<IEnumerable<string>> AsyncMethod4() { Logger logger = LogManager.GetLogger("AnnonTest"); logger.Info("Direct, async method"); return await Task.FromResult(new string[] { "value1", "value2" }); } } #if NET3_5 || NET4_0 || NETSTANDARD1_5 [Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")] #elif MONO [Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void CallSiteShouldWorkForAsyncMethodsWithReturnValue() { var callSite = GetAsyncCallSite().GetAwaiter().GetResult(); Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.GetAsyncCallSite", callSite); } public async Task<string> GetAsyncCallSite() { var logEvent = new LogEventInfo(LogLevel.Error, "logger1", "message1"); #if !NETSTANDARD1_5 Type loggerType = typeof(Logger); var stacktrace = new System.Diagnostics.StackTrace(); var stackFrames = stacktrace.GetFrames(); var index = LoggerImpl.FindCallingMethodOnStackTrace(stackFrames, loggerType) ?? 0; int? indexLegacy = LoggerImpl.SkipToUserStackFrameLegacy(stackFrames, index); logEvent.GetCallSiteInformationInternal().SetStackTrace(stacktrace, index, indexLegacy); #endif await Task.Delay(0); Layout l = "${callsite}"; var callSite = l.Render(logEvent); return callSite; } #if !DEBUG [Fact(Skip = "RELEASE not working, only DEBUG")] #else [Fact] #endif public void Show_correct_method_for_moveNext() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.MoveNext"; LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); MoveNext(); AssertDebugLastMessage("debug", $"{currentMethodFullName}|direct"); } private void MoveNext() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); } public class CompositeWrapper { private readonly MyWrapper wrappedLogger; public CompositeWrapper() { wrappedLogger = new MyWrapper(); } [MethodImpl(MethodImplOptions.NoInlining)] public void Log(string what) { wrappedLogger.Log(typeof(CompositeWrapper), what); } } public abstract class BaseWrapper { public void Log(string what) { InternalLog(typeof(BaseWrapper), what); } public void Log(Type type, string what) //overloaded with type for composition { InternalLog(type, what); } protected abstract void InternalLog(Type type, string what); } public class MyWrapper : BaseWrapper { private readonly ILogger wrapperLogger; public MyWrapper() { wrapperLogger = LogManager.GetLogger("WrappedLogger"); } protected override void InternalLog(Type type, string what) //added type for composition { LogEventInfo info = new LogEventInfo(LogLevel.Warn, wrapperLogger.Name, what); // Provide BaseWrapper as wrapper type. // Expected: UserStackFrame should point to the method that calls a // method of BaseWrapper. wrapperLogger.Log(type, info); } } #endregion private class MyLogger : Logger { } [Fact] public void CallsiteBySubclass_interface() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)); Assert.True(logger is MyLogger, "logger isn't MyLogger"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_interface msg"); } [Fact] public void CallsiteBySubclass_mylogger() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); MyLogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as MyLogger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_mylogger msg"); } [Fact] public void CallsiteBySubclass_logger() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as Logger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_logger msg"); } [Fact] public void Should_preserve_correct_callsite_information() { // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var target = new MemoryTarget(); var wrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper(target) { TimeToSleepBetweenBatches = 0 }; config.AddTarget("target", wrapper); // Step 3. Set target properties target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; // Step 4. Define rules var rule = new LoggingRule("*", LogLevel.Debug, wrapper); config.LoggingRules.Add(rule); LogManager.Configuration = config; var factory = new NLogFactory(config); var logger = factory.Create("MyLoggerName"); WriteLogMessage(logger); LogManager.Flush(); var logMessage = target.Logs[0]; Assert.Contains("MyLoggerName", logMessage); // See that LogManager.ReconfigExistingLoggers() is able to upgrade the Logger target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${callsite} ${message}"; LogManager.ReconfigExistingLoggers(); WriteLogMessage(logger); LogManager.Flush(); logMessage = target.Logs[1]; Assert.Contains("CallSiteTests.WriteLogMessage", logMessage); // See that LogManager.ReconfigExistingLoggers() is able to upgrade the Logger target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${callsite} ${message} ThreadId=${threadid}"; LogManager.ReconfigExistingLoggers(); WriteLogMessage(logger); LogManager.Flush(); logMessage = target.Logs[2]; Assert.Contains("ThreadId=" + Thread.CurrentThread.ManagedThreadId.ToString(), logMessage); // See that interface logging also works (Improve support for Microsoft.Extension.Logging.ILogger replacement) INLogLogger ilogger = logger; WriteLogMessage(ilogger); LogManager.Flush(); logMessage = target.Logs[3]; Assert.Contains("CallSiteTests.WriteLogMessage", logMessage); } [MethodImpl(MethodImplOptions.NoInlining)] private void WriteLogMessage(NLogLogger logger) { logger.Debug("something"); } [MethodImpl(MethodImplOptions.NoInlining)] private void WriteLogMessage(INLogLogger logger) { logger.Log(LogLevel.Debug, "something"); } /// <summary> /// /// </summary> public class NLogFactory { internal const string defaultConfigFileName = "nlog.config"; /// <summary> /// Initializes a new instance of the <see cref="NLogFactory" /> class. /// </summary> /// <param name="loggingConfiguration"> The NLog Configuration </param> public NLogFactory(LoggingConfiguration loggingConfiguration) { LogManager.Configuration = loggingConfiguration; } /// <summary> /// Creates a logger with specified <paramref name="name" />. /// </summary> /// <param name="name"> The name. </param> /// <returns> </returns> public NLogLogger Create(string name) { var log = LogManager.GetLogger(name); return new NLogLogger(log); } } #if !NETSTANDARD1_5 /// <summary> /// If some calls got inlined, we can't find LoggerType anymore. We should fallback if loggerType can be found /// /// Example of those stacktraces: /// at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory) in c:\temp\NLog\src\NLog\LoggerImpl.cs:line 68 /// at NLog.UnitTests.LayoutRenderers.NLogLogger.ErrorWithoutLoggerTypeArg(String message) in c:\temp\NLog\tests\NLog.UnitTests\LayoutRenderers\CallSiteTests.cs:line 989 /// at NLog.UnitTests.LayoutRenderers.CallSiteTests.TestCallsiteWhileCallsGotInlined() in c:\temp\NLog\tests\NLog.UnitTests\LayoutRenderers\CallSiteTests.cs:line 893 /// /// </summary> [Fact] public void CallSiteShouldWorkEvenInlined() { var logEvent = new LogEventInfo(LogLevel.Error, "logger1", "message1"); Type loggerType = typeof(Logger); var stacktrace = new System.Diagnostics.StackTrace(); var stackFrames = stacktrace.GetFrames(); var index = LoggerImpl.FindCallingMethodOnStackTrace(stackFrames, loggerType) ?? 0; int? indexLegacy = LoggerImpl.SkipToUserStackFrameLegacy(stackFrames, index); logEvent.GetCallSiteInformationInternal().SetStackTrace(stacktrace, index, indexLegacy); Layout l = "${callsite}"; var callSite = l.Render(logEvent); Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.CallSiteShouldWorkEvenInlined", callSite); } #endif #if NET3_5 || NET4_0 [Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")] #elif MONO [Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void LogAfterAwait_ShouldCleanMethodNameAsync5() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod5"; LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Debug' writeTo='debug' /> </rules> </nlog>"); AsyncMethod5().Wait(); AssertDebugLastMessage("debug", $"{currentMethodFullName}|dude"); new InnerClassAsyncMethod5().AsyncMethod5().Wait(); AssertDebugLastMessage("debug", $"{typeof(InnerClassAsyncMethod5).ToString()}.AsyncMethod5|dude"); } private async Task AsyncMethod5() { await AMinimalAsyncMethod(); var logger = LogManager.GetCurrentClassLogger(); logger.Debug("dude"); } private class InnerClassAsyncMethod5 { public async Task AsyncMethod5() { await AMinimalAsyncMethod(); var logger = LogManager.GetCurrentClassLogger(); logger.Debug("dude"); } private async Task AMinimalAsyncMethod() { await Task.Delay(1); // Ensure it always becomes async, and it is not inlined } } private async Task AMinimalAsyncMethod() { await Task.Delay(1); // Ensure it always becomes async, and it is not inlined } #if NET3_5 || NET4_0 [Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")] #elif MONO [Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void LogAfterTaskRunAwait_CleanNamesOfAsyncContinuationsIsTrue_ShouldCleanMethodName() { // name of the logging method const string callsiteMethodName = nameof(LogAfterTaskRunAwait_CleanNamesOfAsyncContinuationsIsTrue_ShouldCleanMethodName); LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:cleannamesofasynccontinuations=true}' /></targets> <rules> <logger name='*' levels='Debug' writeTo='debug' /> </rules> </nlog>"); Task.Run(async () => { await AMinimalAsyncMethod(); var logger = LogManager.GetCurrentClassLogger(); logger.Debug("dude"); }).Wait(); AssertDebugLastMessage("debug", callsiteMethodName); } #if NET3_5 || NET4_0 [Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")] #elif MONO [Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void LogAfterTaskRunAwait_CleanNamesOfAsyncContinuationsIsTrue_ShouldCleanClassName() { // full name of the logging method string callsiteMethodFullName = $"{GetType()}.{nameof(LogAfterTaskRunAwait_CleanNamesOfAsyncContinuationsIsTrue_ShouldCleanClassName)}"; LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:includenamespace=true:cleannamesofasynccontinuations=true:cleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Debug' writeTo='debug' /> </rules> </nlog>"); Task.Run(async () => { await AMinimalAsyncMethod(); var logger = LogManager.GetCurrentClassLogger(); logger.Debug("dude"); }).Wait(); AssertDebugLastMessage("debug", callsiteMethodFullName); new InnerClassAsyncMethod6().AsyncMethod6a().Wait(); AssertDebugLastMessage("debug", $"{typeof(InnerClassAsyncMethod6).ToString()}.AsyncMethod6a"); new InnerClassAsyncMethod6().AsyncMethod6b(); AssertDebugLastMessage("debug", $"{typeof(InnerClassAsyncMethod6).ToString()}.AsyncMethod6b"); } #if NET3_5 || NET4_0 [Fact(Skip = "NET3_5 + NET4_0 not supporting async callstack")] #elif MONO [Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void LogAfterTaskRunAwait_CleanNamesOfAsyncContinuationsIsFalse_ShouldNotCleanNames() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:includenamespace=true:cleannamesofasynccontinuations=false}' /></targets> <rules> <logger name='*' levels='Debug' writeTo='debug' /> </rules> </nlog>"); Task.Run(async () => { await AMinimalAsyncMethod(); var logger = LogManager.GetCurrentClassLogger(); logger.Debug("dude"); }).Wait(); AssertDebugLastMessageContains("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests"); AssertDebugLastMessageContains("debug", "MoveNext"); AssertDebugLastMessageContains("debug", "b__"); } private class InnerClassAsyncMethod6 { public virtual async Task AsyncMethod6a() { await Task.Run(async () => { await AMinimalAsyncMethod(); var logger = LogManager.GetCurrentClassLogger(); logger.Debug("dude"); }); } public virtual void AsyncMethod6b() { Task.Run(async () => { await AMinimalAsyncMethod(); var logger = LogManager.GetCurrentClassLogger(); logger.Debug("dude"); }).Wait(); } private async Task AMinimalAsyncMethod() { await Task.Delay(1); // Ensure it always becomes async, and it is not inlined } } public interface INLogLogger { void Log(LogLevel logLevel, string message); } public abstract class NLogLoggerBase : INLogLogger { protected abstract Logger Logger { get; } void INLogLogger.Log(LogLevel logLevel, string message) { Logger.Log(typeof(INLogLogger), new LogEventInfo(logLevel, Logger.Name, message)); } } /// <summary> /// Implementation of <see cref="ILogger" /> for NLog. /// </summary> public class NLogLogger : NLogLoggerBase { /// <summary> /// Initializes a new instance of the <see cref="NLogLogger" /> class. /// </summary> /// <param name="logger"> The logger. </param> public NLogLogger(Logger logger) { Logger = logger; } /// <summary> /// Gets or sets the logger. /// </summary> /// <value> The logger. </value> protected override Logger Logger { get; } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> A <see cref="string" /> that represents this instance. </returns> public override string ToString() { return Logger.ToString(); } /// <summary> /// Logs a debug message. /// </summary> /// <param name="message"> The message to log </param> public void Debug(string message) { Log(LogLevel.Debug, message); } public void Log(LogLevel logLevel, string message) { Logger.Log(typeof(NLogLogger), new LogEventInfo(logLevel, Logger.Name, message)); } } [Theory] [InlineData(false)] [InlineData(true)] public void CallsiteTargetUsesStackTraceTest(bool includeStackTraceUsage) { var target = new MyTarget() { StackTraceUsage = includeStackTraceUsage ? StackTraceUsage.WithoutSource : StackTraceUsage.None }; SimpleConfigurator.ConfigureForTargetLogging(target); var logger = LogManager.GetLogger(nameof(CallsiteTargetUsesStackTraceTest)); string t = null; logger.Info("Testing null:{0}", t); Assert.NotNull(target.LastEvent); if (includeStackTraceUsage) Assert.NotNull(target.LastEvent.StackTrace); else Assert.Null(target.LastEvent.StackTrace); } public class MyTarget : TargetWithLayout, IUsesStackTrace { public MyTarget() { } public MyTarget(string name) : this() { Name = name; } public LogEventInfo LastEvent { get; private set; } public new StackTraceUsage StackTraceUsage { get; set; } protected override void Write(LogEventInfo logEvent) { LastEvent = logEvent; base.Write(logEvent); } } } }
//------------------------------------------------------------------------------ // <copyright file="SizeConverter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.Drawing { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.Win32; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Globalization; using System.Reflection; /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter"]/*' /> /// <devdoc> /// SizeConverter is a class that can be used to convert /// Size from one data type to another. Access this /// class through the TypeDescriptor. /// </devdoc> public class SizeConverter : TypeConverter { /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CanConvertFrom"]/*' /> /// <devdoc> /// Determines if this converter can convert an object in the given source /// type to the native type of the converter. /// </devdoc> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CanConvertTo"]/*' /> /// <devdoc> /// <para>Gets a value indicating whether this converter can /// convert an object to the given destination type using the context.</para> /// </devdoc> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) { return true; } return base.CanConvertTo(context, destinationType); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.ConvertFrom"]/*' /> /// <devdoc> /// Converts the given object to the converter's native type. /// </devdoc> [SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")] public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string strValue = value as string; if (strValue != null) { string text = strValue.Trim(); if (text.Length == 0) { return null; } else { // Parse 2 integer values. // if (culture == null) { culture = CultureInfo.CurrentCulture; } char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(new char[] {sep}); int[] values = new int[tokens.Length]; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); for (int i = 0; i < values.Length; i++) { // Note: ConvertFromString will raise exception if value cannot be converted. values[i] = (int)intConverter.ConvertFromString(context, culture, tokens[i]); } if (values.Length == 2) { return new Size(values[0], values[1]); } else { throw new ArgumentException(SR.Format(SR.TextParseFailedFormat, text, "Width,Height")); } } } return base.ConvertFrom(context, culture, value); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.ConvertTo"]/*' /> /// <devdoc> /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call /// to ToString on the object if the object is valid and if the destination /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// </devdoc> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if(value is Size){ if (destinationType == typeof(string)) { Size size = (Size)value; if (culture == null) { culture = CultureInfo.CurrentCulture; } string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); string[] args = new string[2]; int nArg = 0; // Note: ConvertToString will raise exception if value cannot be converted. args[nArg++] = intConverter.ConvertToString(context, culture, size.Width); args[nArg++] = intConverter.ConvertToString(context, culture, size.Height); return string.Join(sep, args); } if (destinationType == typeof(InstanceDescriptor)) { Size size = (Size)value; ConstructorInfo ctor = typeof(Size).GetConstructor(new Type[] {typeof(int), typeof(int)}); if (ctor != null) { return new InstanceDescriptor(ctor, new object[] {size.Width, size.Height}); } } } return base.ConvertTo(context, culture, value, destinationType); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CreateInstance"]/*' /> /// <devdoc> /// Creates an instance of this type given a set of property values /// for the object. This is useful for objects that are immutable, but still /// want to provide changable properties. /// </devdoc> [SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")] [SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")] public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { if( propertyValues == null ){ throw new ArgumentNullException( "propertyValues" ); } object width = propertyValues["Width"]; object height = propertyValues["Height"]; if(width == null || height == null || !(width is int) || !(height is int)) { throw new ArgumentException(SR.Format(SR.PropertyValueInvalidEntry)); } return new Size((int)width, (int)height); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetCreateInstanceSupported"]/*' /> /// <devdoc> /// Determines if changing a value on this object should require a call to /// CreateInstance to create a new value. /// </devdoc> public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) { return true; } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetProperties"]/*' /> /// <devdoc> /// Retrieves the set of properties for this type. By default, a type has /// does not return any properties. An easy implementation of this method /// can just call TypeDescriptor.GetProperties for the correct data type. /// </devdoc> public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(Size), attributes); return props.Sort(new string[] {"Width", "Height"}); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetPropertiesSupported"]/*' /> /// <devdoc> /// Determines if this object supports properties. By default, this /// is false. /// </devdoc> public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return true; } } }
namespace Schema.NET.Tool.Services; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Schema.NET.Tool.CustomOverrides; using Schema.NET.Tool.GeneratorModels; using Schema.NET.Tool.Repositories; public class SchemaService { private static readonly Regex StartsWithNumber = new("^[0-9]", RegexOptions.Compiled); private readonly IEnumerable<IClassOverride> classOverrides; private readonly IEnumerable<IEnumerationOverride> enumerationOverrides; private readonly ISchemaRepository schemaRepository; private readonly bool includePending; public SchemaService( IEnumerable<IClassOverride> classOverrides, IEnumerable<IEnumerationOverride> enumerationOverrides, ISchemaRepository schemaRepository, bool includePending) { this.classOverrides = classOverrides; this.enumerationOverrides = enumerationOverrides; this.schemaRepository = schemaRepository; this.includePending = includePending; } public async Task<IEnumerable<GeneratorSchemaObject>> GetObjectsAsync() { var (schemaClasses, schemaProperties, schemaValues) = await this.schemaRepository .GetObjectsAsync() .ConfigureAwait(false); var isEnumMap = new HashSet<string>( schemaClasses.Where(c => c.IsEnum).Select(c => c.Label), StringComparer.Ordinal); var knownSchemaClasses = new HashSet<Uri>( schemaClasses.Where(c => this.includePending || !c.IsPending).Select(c => c.Id)); var classPropertyMap = schemaProperties .Where(p => !p.IsArchived && !p.IsMeta && (this.includePending || !p.IsPending)) .SelectMany(p => p.DomainIncludes.Select(i => (Id: i, Property: p))) .GroupBy(x => x.Id) .ToDictionary(g => g.Key, g => g.Select(p => p.Property).ToArray()); var enumerations = new List<GeneratorSchemaEnumeration>(); var classes = new List<GeneratorSchemaClass>(); foreach (var schemaClass in schemaClasses .Where(x => !x.IsPrimitive && !x.IsArchived && !x.IsMeta && (this.includePending || !x.IsPending))) { if (schemaClass.IsEnum) { var enumeration = TranslateEnumeration(schemaClass, schemaValues); enumerations.Add(enumeration); } else { if (!classPropertyMap.TryGetValue(schemaClass.Id, out var classProperties)) { classProperties = Array.Empty<Models.SchemaProperty>(); } var @class = TranslateClass(schemaClass, schemaClasses, classProperties, isEnumMap, knownSchemaClasses, this.includePending); classes.Add(@class); } } SetParentAndChildren(classes); CombineMultipleParentsIntoCombinedClass(classes); this.ApplyEnumerationOverrides(enumerations); this.ApplyClassOverrides(classes); SetPropertyOrder(classes); return (enumerations as IEnumerable<GeneratorSchemaObject>).Concat(classes); } private static void CombineMultipleParentsIntoCombinedClass(List<GeneratorSchemaClass> classes) { while (classes.Any(x => x.Parents.Count > 1)) { // Remove Thing types from classes with multiple parents. foreach (var @class in classes.Where(x => x.Parents.Count > 1 && x.Parents.Any(y => y.IsThingType)).ToArray()) { var thingParent = @class.Parents.First(x => x.IsThingType); @class.Parents.Remove(thingParent); thingParent.Children.Remove(@class); } foreach (var @class in classes.Where(x => x.Parents.Count > 1).ToArray()) { foreach (var parent in @class.Parents.ToArray()) { if (@class.Parents.Where(x => x != parent).Any(x => x.Ancestors.Any(y => y.Id == parent.Id))) { @class.Parents.Remove(parent); parent.Children.Remove(@class); } if (@class.Parents.Where(x => x != parent && x.IsCombined).Any(x => x.CombinationOf.Any(y => y.Id == parent.Id))) { @class.Parents.Remove(parent); parent.Children.Remove(@class); } } } foreach (var @class in classes.Where(x => x.Parents.Count > 1).ToArray()) { var className = string.Join("And", @class.Parents.Select(x => x.Name).OrderBy(x => x)); var combinedClass = classes.FirstOrDefault(x => string.Equals(x.Name, className, StringComparison.Ordinal)); if (combinedClass is null) { var classDescription = "See " + string.Join(", ", @class.Parents.Select(x => x.Name).OrderBy(x => x)) + " for more information."; var parents = @class.Parents.SelectMany(x => x.Parents).GroupBy(x => x.Name).Select(x => x.First()).ToArray(); var layerName = @class.IsCombined ? @class.Layer : $"{@class.Layer}.combined"; combinedClass = new GeneratorSchemaClass(layerName, new Uri($"https://CombinedClass/{className}"), className, classDescription, isCombined: true); combinedClass.CombinationOf.AddRange(@class.Parents); combinedClass.Properties.AddRange(@class .Parents .SelectMany(x => x.Properties) .Select(x => x.Clone(combinedClass)) .GroupBy(x => x.Name) .Select(x => x.First()) .OrderBy(x => x.Name)); foreach (var parent in parents) { parent.Children.Add(combinedClass); combinedClass.Parents.Add(parent); } classes.Add(combinedClass); } @class.Parents.Clear(); @class.Parents.Add(combinedClass); combinedClass.Children.Add(@class); } } } private static void SetPropertyOrder(List<GeneratorSchemaClass> classes) { foreach (var @class in classes) { var propertyOrder = PropertyNameComparer.KnownPropertyNameOrders.Values.Max() + 1 + (@class.Ancestors.Count() * 100); foreach (var property in @class.Properties) { property.Order = propertyOrder; var upperPropertyName = property.Name.ToUpperInvariant(); if (PropertyNameComparer.KnownPropertyNameOrders.ContainsKey(upperPropertyName)) { property.Order = PropertyNameComparer.KnownPropertyNameOrders[upperPropertyName]; } ++propertyOrder; } } } private static string CamelCase(string value) { var stringBuilder = new StringBuilder(value); stringBuilder[0] = char.ToLower(stringBuilder[0], CultureInfo.InvariantCulture); return stringBuilder.ToString(); } private static void SetParentAndChildren(List<GeneratorSchemaClass> classes) { foreach (var @class in classes) { foreach (var parentClassId in @class.Parents.Select(x => x.Id).Distinct().ToArray()) { var parentClass = classes.FirstOrDefault(x => x.Id == parentClassId); if (parentClass is null) { #pragma warning disable CA2201 // Do not raise reserved exception types throw new Exception(Resources.CheckThatNewPrimitiveTypeNotAdded); #pragma warning restore CA2201 // Do not raise reserved exception types } else { parentClass.Children.Add(@class); @class.Parents.Remove(@class.Parents.First(x => x.Id == parentClassId)); @class.Parents.Add(parentClass); } } } } private static GeneratorSchemaEnumeration TranslateEnumeration( Models.SchemaClass schemaClass, IEnumerable<Models.SchemaEnumerationValue> schemaValues) { var enumeration = new GeneratorSchemaEnumeration($"{schemaClass.Layer}.enumerations", schemaClass.Label, schemaClass.Comment); enumeration.Values.AddRange(schemaValues .Where(x => x.Types.Contains(schemaClass.Id.ToString())) .Select(x => new GeneratorSchemaEnumerationValue(x.Label, x.Id, x.Comment)) .OrderBy(x => x.Name, new EnumerationValueComparer())); return enumeration; } private static GeneratorSchemaClass TranslateClass( Models.SchemaClass schemaClass, IEnumerable<Models.SchemaClass> schemaClasses, IEnumerable<Models.SchemaProperty> schemaProperties, HashSet<string> isEnumMap, HashSet<Uri> knownSchemaClasses, bool includePending) { var className = StartsWithNumber.IsMatch(schemaClass.Label) ? $"Type{schemaClass.Label}" : schemaClass.Label; var @class = new GeneratorSchemaClass(schemaClass.Layer, schemaClass.Id, className, schemaClass.Comment); @class.Parents.AddRange(schemaClass.SubClassOfIds .Where(id => knownSchemaClasses.Contains(id)) .Select(id => new GeneratorSchemaClass(id))); var properties = schemaProperties .Select(x => { var propertyName = GetPropertyName(x.Label); var property = new GeneratorSchemaProperty(@class, CamelCase(propertyName), propertyName, x.Comment); property.Types.AddRange(x.RangeIncludes .Where(id => { var propertyTypeClass = schemaClasses.FirstOrDefault(z => z.Id == id); return propertyTypeClass is null || (!propertyTypeClass.IsArchived && !propertyTypeClass.IsMeta && (includePending || !propertyTypeClass.IsPending)); }) .Select(id => { #if NETSTANDARD2_0 var propertyTypeName = id.ToString().Replace("https://schema.org/", string.Empty); #else var propertyTypeName = id.ToString().Replace("https://schema.org/", string.Empty, StringComparison.Ordinal); #endif var isPropertyTypeEnum = isEnumMap.Contains(propertyTypeName); var csharpTypeStrings = GetCSharpTypeStrings( propertyName, propertyTypeName, isPropertyTypeEnum); return new GeneratorSchemaPropertyType(propertyTypeName, csharpTypeStrings); }) .Where(y => !string.Equals(y.Name, "Enumeration", StringComparison.Ordinal) && !string.Equals(y.Name, "QualitativeValue", StringComparison.Ordinal)) .GroupBy(y => y.CSharpTypeStrings) .Select(y => y.First()) .OrderBy(y => y.Name)); return property; }) .Where(x => x.Types.Count > 0) .OrderBy(x => x.Name, new PropertyNameComparer()) .GroupBy(x => x.Name) // Remove duplicates. .Select(x => x.First()) .ToList(); @class.Properties.AddRange(properties); return @class; } private static string GetPropertyName(string name) { var stringBuilder = new StringBuilder(); var upper = true; for (var i = 0; i < name.Length; ++i) { var character = name[i]; if (upper && !char.IsUpper(character)) { stringBuilder.Append(char.ToUpper(character, CultureInfo.InvariantCulture)); upper = false; } else if (character == '-') { upper = true; } else { stringBuilder.Append(character); upper = false; } } return stringBuilder.ToString(); } private static IEnumerable<string> GetCSharpTypeStrings(string propertyName, string typeName, bool isTypeEnum) { switch (typeName) { case "Boolean": return new string[] { "bool?" }; case "DataType": return new string[] { "bool?", "int?", "decimal?", "double?", "DateTime?", "TimeSpan?", "string" }; case "Date": return new string[] { "int?", "DateTime?" }; case "DateTime": return new string[] { "DateTimeOffset?" }; case "Integer": case "Number" when #if NETSTANDARD2_0 propertyName.Contains("NumberOf") || propertyName.Contains("Year") || propertyName.Contains("Count") || propertyName.Contains("Age"): #else propertyName.Contains("NumberOf", StringComparison.Ordinal) || propertyName.Contains("Year", StringComparison.Ordinal) || propertyName.Contains("Count", StringComparison.Ordinal) || propertyName.Contains("Age", StringComparison.Ordinal): #endif return new string[] { "int?" }; case "Number" when #if NETSTANDARD2_0 propertyName.Contains("Price") || propertyName.Contains("Amount") || propertyName.Contains("Salary") || propertyName.Contains("Discount"): #else propertyName.Contains("Price", StringComparison.Ordinal) || propertyName.Contains("Amount", StringComparison.Ordinal) || propertyName.Contains("Salary", StringComparison.Ordinal) || propertyName.Contains("Discount", StringComparison.Ordinal): #endif return new string[] { "decimal?" }; case "Number": return new string[] { "double?" }; case "Text": case "Distance": case "Energy": case "Mass": case "XPathType": case "CssSelectorType": case "PronounceableText": return new string[] { "string" }; case "Time": case "Duration": return new string[] { "TimeSpan?" }; case "URL": return new string[] { "Uri" }; default: if (isTypeEnum) { return new string[] { typeName + "?" }; } else { return new string[] { "I" + typeName }; } } } private void ApplyClassOverrides(IEnumerable<GeneratorSchemaClass> classes) { foreach (var @class in classes) { foreach (var classOverride in this.classOverrides) { if (classOverride.CanOverride(@class)) { classOverride.Override(@class); } } } } private void ApplyEnumerationOverrides(IEnumerable<GeneratorSchemaEnumeration> enumerations) { foreach (var enumeration in enumerations) { foreach (var enumerationOverride in this.enumerationOverrides) { if (enumerationOverride.CanOverride(enumeration)) { enumerationOverride.Override(enumeration); } } } } }
using UnityEngine; using System.Collections.Generic; namespace UMA { /// <summary> /// Gloal container for various UMA objects in the scene. Marked as partial so the developer can add to this if necessary /// </summary> public partial class UMAContext : MonoBehaviour { public static UMAContext Instance; /// <summary> /// The race library. /// </summary> public RaceLibraryBase raceLibrary; /// <summary> /// The slot library. /// </summary> public SlotLibraryBase slotLibrary; /// <summary> /// The overlay library. /// </summary> public OverlayLibraryBase overlayLibrary; #pragma warning disable 618 public void Start() { if (!slotLibrary) { slotLibrary = GameObject.Find("SlotLibrary").GetComponent<SlotLibraryBase>(); } if (!raceLibrary) { raceLibrary = GameObject.Find("RaceLibrary").GetComponent<RaceLibraryBase>(); } if (!overlayLibrary) { overlayLibrary = GameObject.Find("OverlayLibrary").GetComponent<OverlayLibraryBase>(); } // Note: Removed null check so that this is always assigned if you have a UMAContext in your scene // This will avoid those occasions where someone drops in a bogus context in a test scene, and then // later loads a valid scene (and everything breaks) Instance = this; } /// <summary> /// Validates the library contents. /// </summary> public void ValidateDictionaries() { slotLibrary.ValidateDictionary(); raceLibrary.ValidateDictionary(); overlayLibrary.ValidateDictionary(); } /// <summary> /// Gets a race by name, if it has been added to the library /// </summary> /// <returns>The race.</returns> /// <param name="name">Name.</param> public RaceData HasRace(string name) { return raceLibrary.HasRace(name); } /// <summary> /// Gets a race by name hash, if it has been added to the library. /// </summary> /// <returns>The race.</returns> /// <param name="nameHash">Name hash.</param> public RaceData HasRace(int nameHash) { return raceLibrary.HasRace(nameHash); } /// <summary> /// Gets a race by name, if the library is a DynamicRaceLibrary it will try to find it. /// </summary> /// <returns>The race.</returns> /// <param name="name">Name.</param> public RaceData GetRace(string name) { return raceLibrary.GetRace(name); } /// <summary> /// Gets a race by name hash, if the library is a DynamicRaceLibrary it will try to find it. /// </summary> /// <returns>The race.</returns> /// <param name="nameHash">Name hash.</param> public RaceData GetRace(int nameHash) { return raceLibrary.GetRace(nameHash); } /// <summary> /// Array of all races in the context. /// </summary> /// <returns>The array of race data.</returns> public RaceData[] GetAllRaces() { return raceLibrary.GetAllRaces(); } /// <summary> /// Add a race to the context. /// </summary> /// <param name="race">New race.</param> public void AddRace(RaceData race) { raceLibrary.AddRace(race); } /// <summary> /// Instantiate a slot by name. /// </summary> /// <returns>The slot.</returns> /// <param name="name">Name.</param> public SlotData InstantiateSlot(string name) { return slotLibrary.InstantiateSlot(name); } /// <summary> /// Instantiate a slot by name hash. /// </summary> /// <returns>The slot.</returns> /// <param name="nameHash">Name hash.</param> public SlotData InstantiateSlot(int nameHash) { return slotLibrary.InstantiateSlot(nameHash); } /// <summary> /// Instantiate a slot by name, with overlays. /// </summary> /// <returns>The slot.</returns> /// <param name="name">Name.</param> /// <param name="overlayList">Overlay list.</param> public SlotData InstantiateSlot(string name, List<OverlayData> overlayList) { return slotLibrary.InstantiateSlot(name, overlayList); } /// <summary> /// Instantiate a slot by name hash, with overlays. /// </summary> /// <returns>The slot.</returns> /// <param name="nameHash">Name hash.</param> /// <param name="overlayList">Overlay list.</param> public SlotData InstantiateSlot(int nameHash, List<OverlayData> overlayList) { return slotLibrary.InstantiateSlot(nameHash, overlayList); } /// <summary> /// Check for presence of a slot by name. /// </summary> /// <returns><c>True</c> if the slot exists in this context.</returns> /// <param name="name">Name.</param> public bool HasSlot(string name) { return slotLibrary.HasSlot(name); } /// <summary> /// Check for presence of a slot by name hash. /// </summary> /// <returns><c>True</c> if the slot exists in this context.</returns> /// <param name="nameHash">Name hash.</param> public bool HasSlot(int nameHash) { return slotLibrary.HasSlot(nameHash); } /// <summary> /// Add a slot asset to the context. /// </summary> /// <param name="slot">New slot asset.</param> public void AddSlotAsset(SlotDataAsset slot) { slotLibrary.AddSlotAsset(slot); } /// <summary> /// Check for presence of an overlay by name. /// </summary> /// <returns><c>True</c> if the overlay exists in this context.</returns> /// <param name="name">Name.</param> public bool HasOverlay(string name) { return overlayLibrary.HasOverlay(name); } /// <summary> /// Check for presence of an overlay by name hash. /// </summary> /// <returns><c>True</c> if the overlay exists in this context.</returns> /// <param name="nameHash">Name hash.</param> public bool HasOverlay(int nameHash) { return overlayLibrary.HasOverlay(nameHash); } /// <summary> /// Instantiate an overlay by name. /// </summary> /// <returns>The overlay.</returns> /// <param name="name">Name.</param> public OverlayData InstantiateOverlay(string name) { return overlayLibrary.InstantiateOverlay(name); } /// <summary> /// Instantiate an overlay by name hash. /// </summary> /// <returns>The overlay.</returns> /// <param name="nameHash">Name hash.</param> public OverlayData InstantiateOverlay(int nameHash) { return overlayLibrary.InstantiateOverlay(nameHash); } /// <summary> /// Instantiate a tinted overlay by name. /// </summary> /// <returns>The overlay.</returns> /// <param name="name">Name.</param> /// <param name="color">Color.</param> public OverlayData InstantiateOverlay(string name, Color color) { return overlayLibrary.InstantiateOverlay(name, color); } /// <summary> /// Instantiate a tinted overlay by name hash. /// </summary> /// <returns>The overlay.</returns> /// <param name="nameHash">Name hash.</param> /// <param name="color">Color.</param> public OverlayData InstantiateOverlay(int nameHash, Color color) { return overlayLibrary.InstantiateOverlay(nameHash, color); } /// <summary> /// Add an overlay asset to the context. /// </summary> /// <param name="overlay">New overlay asset.</param> public void AddOverlayAsset(OverlayDataAsset overlay) { overlayLibrary.AddOverlayAsset(overlay); } #pragma warning restore 618 /// <summary> /// Finds the singleton context in the scene. /// </summary> /// <returns>The UMA context.</returns> public static UMAContext FindInstance() { if (Instance == null) { var contextGO = GameObject.Find("UMAContext"); if (contextGO != null) Instance = contextGO.GetComponent<UMAContext>(); } if (Instance == null) { Instance = Component.FindObjectOfType<UMAContext>(); } return Instance; } } }
// ------------------------------------------------------------------------------------------------------------------- // Generated code, do not edit // Command Line: DomGen "DomGenVS" "VisualScriptBasicSchema.xsd" "VisualScriptBasicSchema.cs" "VisualScriptBasicSchema" "VisualScript" "-enums" // ------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using Sce.Atf; using Sce.Atf.Dom; namespace Sce.Atf.Controls.Adaptable.Graphs.CircuitBasicSchema { public static class circuitDocumentType { static circuitDocumentType() { Type = new DomNodeType("CircuitDocumentType", circuitType.Type); versionAttribute = Type.DefineNewAttributeInfo("version", AttributeType.StringType, "0.1"); moduleChild = Type.DefineNewChildInfo("module", moduleType.Type, true); connectionChild = Type.DefineNewChildInfo("connection", connectionType.Type, true); layerFolderChild = Type.DefineNewChildInfo("layerFolder", layerFolderType.Type, true); expressionChild = Type.DefineNewChildInfo("expression", expressionType.Type, true); annotationChild = Type.DefineNewChildInfo("annotation", annotationType.Type, true); prototypeFolderChild = Type.DefineNewChildInfo("prototypeFolder", prototypeFolderType.Type, false); templateFolderChild = Type.DefineNewChildInfo("templateFolder", templateFolderType.Type, false); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("version".Localize(), versionAttribute, null, "version".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo versionAttribute; public static ChildInfo moduleChild; public static ChildInfo connectionChild; public static ChildInfo layerFolderChild; public static ChildInfo expressionChild; public static ChildInfo annotationChild; public static ChildInfo prototypeFolderChild; public static ChildInfo templateFolderChild; } public static class circuitType { static circuitType() { Type = new DomNodeType("circuitType", moduleType.Type); moduleChild = Type.DefineNewChildInfo("module", moduleType.Type, true); connectionChild = Type.DefineNewChildInfo("connection", connectionType.Type, true); layerFolderChild = Type.DefineNewChildInfo("layerFolder", layerFolderType.Type, true); expressionChild = Type.DefineNewChildInfo("expression", expressionType.Type, true); annotationChild = Type.DefineNewChildInfo("annotation", annotationType.Type, true); } public static DomNodeType Type; public static ChildInfo moduleChild; public static ChildInfo connectionChild; public static ChildInfo layerFolderChild; public static ChildInfo expressionChild; public static ChildInfo annotationChild; } public static class moduleType { static moduleType() { Type = new DomNodeType("moduleType"); nameAttribute = Type.DefineNewAttributeInfo("name", AttributeType.StringType, defaultValue:"module"); labelAttribute = Type.DefineNewAttributeInfo("label", AttributeType.StringType); xAttribute = Type.DefineNewAttributeInfo("x", AttributeType.IntType); yAttribute = Type.DefineNewAttributeInfo("y", AttributeType.IntType); visibleAttribute = Type.DefineNewAttributeInfo("visible", AttributeType.BooleanType, defaultValue:true); showUnconnectedPinsAttribute = Type.DefineNewAttributeInfo("showUnconnectedPins", AttributeType.BooleanType, defaultValue: true); sourceGuidAttribute = Type.DefineNewAttributeInfo("sourceGuid", AttributeType.StringType); validatedAttribute = Type.DefineNewAttributeInfo("validated", AttributeType.BooleanType, true); dynamicPropertyChild = Type.DefineNewChildInfo("dynamicProperty", dynamicPropertyType.Type, true); Type.SetIdAttribute(nameAttribute); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), nameAttribute, null, "name".Localize(), false, null, null ), new AttributePropertyDescriptor("label".Localize(), labelAttribute, null, "label".Localize(), false, null, null ), new AttributePropertyDescriptor("x".Localize(), xAttribute, null, "x".Localize(), false, null, null ), new AttributePropertyDescriptor("y".Localize(), yAttribute, null, "y".Localize(), false, null, null ), new AttributePropertyDescriptor("visible".Localize(), visibleAttribute, null, "visible".Localize(), false, null, null ), new AttributePropertyDescriptor("showUnconnectedPins".Localize(), showUnconnectedPinsAttribute, null, "showUnconnectedPins".Localize(), false, null, null ), new AttributePropertyDescriptor("sourceGuid".Localize(), sourceGuidAttribute, null, "sourceGuid".Localize(), false, null, null ), new AttributePropertyDescriptor("validated".Localize(), validatedAttribute, null, "validated".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo labelAttribute; public static AttributeInfo xAttribute; public static AttributeInfo yAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo showUnconnectedPinsAttribute; public static AttributeInfo sourceGuidAttribute; public static AttributeInfo validatedAttribute; public static ChildInfo dynamicPropertyChild; } public static class dynamicPropertyType { static dynamicPropertyType() { Type = new DomNodeType("dynamicPropertyType"); nameAttribute = Type.DefineNewAttributeInfo("name", AttributeType.StringType); categoryAttribute = Type.DefineNewAttributeInfo("category", AttributeType.StringType); descriptionAttribute = Type.DefineNewAttributeInfo("description", AttributeType.StringType); converterAttribute = Type.DefineNewAttributeInfo("converter", AttributeType.StringType); editorAttribute = Type.DefineNewAttributeInfo("editor", AttributeType.StringType); valueTypeAttribute = Type.DefineNewAttributeInfo("valueType", AttributeType.StringType); stringValueAttribute = Type.DefineNewAttributeInfo("stringValue", AttributeType.StringType); floatValueAttribute = Type.DefineNewAttributeInfo("floatValue", AttributeType.FloatType); vector3ValueAttribute = Type.DefineNewAttributeInfo("vector3Value", AttributeType.FloatArrayType); boolValueAttribute = Type.DefineNewAttributeInfo("boolValue", AttributeType.BooleanType); intValueAttribute = Type.DefineNewAttributeInfo("intValue", AttributeType.IntType); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), nameAttribute, null, "name".Localize(), false, null, null ), new AttributePropertyDescriptor("category".Localize(), categoryAttribute, null, "category".Localize(), false, null, null ), new AttributePropertyDescriptor("description".Localize(), descriptionAttribute, null, "description".Localize(), false, null, null ), new AttributePropertyDescriptor("converter".Localize(), converterAttribute, null, "converter".Localize(), false, null, null ), new AttributePropertyDescriptor("editor".Localize(), editorAttribute, null, "editor".Localize(), false, null, null ), new AttributePropertyDescriptor("valueType".Localize(), valueTypeAttribute, null, "valueType".Localize(), false, null, null ), new AttributePropertyDescriptor("stringValue".Localize(), stringValueAttribute, null, "stringValue".Localize(), false, null, null ), new AttributePropertyDescriptor("floatValue".Localize(), floatValueAttribute, null, "floatValue".Localize(), false, null, null ), new AttributePropertyDescriptor("vector3Value".Localize(), vector3ValueAttribute, null, "vector3Value".Localize(), false, null, null ), new AttributePropertyDescriptor("boolValue".Localize(), boolValueAttribute, null, "boolValue".Localize(), false, null, null ), new AttributePropertyDescriptor("intValue".Localize(), intValueAttribute, null, "intValue".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo categoryAttribute; public static AttributeInfo descriptionAttribute; public static AttributeInfo converterAttribute; public static AttributeInfo editorAttribute; public static AttributeInfo valueTypeAttribute; public static AttributeInfo stringValueAttribute; public static AttributeInfo floatValueAttribute; public static AttributeInfo vector3ValueAttribute; public static AttributeInfo boolValueAttribute; public static AttributeInfo intValueAttribute; } public static class connectionType { static connectionType() { Type = new DomNodeType("connectionType"); labelAttribute = Type.DefineNewAttributeInfo("label", AttributeType.StringType); outputModuleAttribute = Type.DefineNewAttributeInfo("outputModule", AttributeType.DomNodeRefType); outputPinAttribute = Type.DefineNewAttributeInfo("outputPin", AttributeType.NameStringType); inputModuleAttribute = Type.DefineNewAttributeInfo("inputModule", AttributeType.DomNodeRefType); inputPinAttribute = Type.DefineNewAttributeInfo("inputPin", AttributeType.NameStringType); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("label".Localize(), labelAttribute, null, "label".Localize(), false, null, null ), new AttributePropertyDescriptor("outputModule".Localize(), outputModuleAttribute, null, "outputModule".Localize(), false, null, null ), new AttributePropertyDescriptor("outputPin".Localize(), outputPinAttribute, null, "outputPin".Localize(), false, null, null ), new AttributePropertyDescriptor("inputModule".Localize(), inputModuleAttribute, null, "inputModule".Localize(), false, null, null ), new AttributePropertyDescriptor("inputPin".Localize(), inputPinAttribute, null, "inputPin".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo labelAttribute; public static AttributeInfo outputModuleAttribute; public static AttributeInfo outputPinAttribute; public static AttributeInfo inputModuleAttribute; public static AttributeInfo inputPinAttribute; } public static class layerFolderType { static layerFolderType() { Type = new DomNodeType("layerFolderType"); nameAttribute = Type.DefineNewAttributeInfo("name", AttributeType.StringType); layerFolderChild = Type.DefineNewChildInfo("layerFolder", layerFolderType.Type, true); moduleRefChild = Type.DefineNewChildInfo("moduleRef", moduleRefType.Type, true); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), nameAttribute, null, "name".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo layerFolderChild; public static ChildInfo moduleRefChild; } public static class moduleRefType { static moduleRefType() { Type = new DomNodeType("moduleRefType"); refAttribute = Type.DefineNewAttributeInfo("ref", AttributeType.DomNodeRefType); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("ref".Localize(), refAttribute, null, "ref".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo refAttribute; } public static class expressionType { static expressionType() { Type = new DomNodeType("expressionType"); idAttribute = Type.DefineNewAttributeInfo("id", AttributeType.StringType); labelAttribute = Type.DefineNewAttributeInfo("label", AttributeType.StringType); scriptAttribute = Type.DefineNewAttributeInfo("script", AttributeType.StringType); Type.SetIdAttribute(idAttribute); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("id".Localize(), idAttribute, null, "id".Localize(), false, null, null ), new AttributePropertyDescriptor("label".Localize(), labelAttribute, null, "label".Localize(), false, null, null ), new AttributePropertyDescriptor("script".Localize(), scriptAttribute, null, "script".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo idAttribute; public static AttributeInfo labelAttribute; public static AttributeInfo scriptAttribute; } public static class annotationType { static annotationType() { Type = new DomNodeType("annotationType"); textAttribute = Type.DefineNewAttributeInfo("text", AttributeType.StringType); xAttribute = Type.DefineNewAttributeInfo("x", AttributeType.IntType); yAttribute = Type.DefineNewAttributeInfo("y", AttributeType.IntType); widthAttribute = Type.DefineNewAttributeInfo("width", AttributeType.IntType); heightAttribute = Type.DefineNewAttributeInfo("height", AttributeType.IntType); backcolorAttribute = Type.DefineNewAttributeInfo("backcolor", AttributeType.IntType, defaultValue:-31); foreColorAttribute = Type.DefineNewAttributeInfo("foreColor", AttributeType.IntType, defaultValue:-16777216); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("text".Localize(), textAttribute, null, "text".Localize(), false, null, null ), new AttributePropertyDescriptor("x".Localize(), xAttribute, null, "x".Localize(), false, null, null ), new AttributePropertyDescriptor("y".Localize(), yAttribute, null, "y".Localize(), false, null, null ), new AttributePropertyDescriptor("width".Localize(), widthAttribute, null, "width".Localize(), false, null, null ), new AttributePropertyDescriptor("height".Localize(), heightAttribute, null, "height".Localize(), false, null, null ), new AttributePropertyDescriptor("backcolor".Localize(), backcolorAttribute, null, "backcolor".Localize(), false, null, null ), new AttributePropertyDescriptor("foreColor".Localize(), foreColorAttribute, null, "foreColor".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo textAttribute; public static AttributeInfo xAttribute; public static AttributeInfo yAttribute; public static AttributeInfo widthAttribute; public static AttributeInfo heightAttribute; public static AttributeInfo backcolorAttribute; public static AttributeInfo foreColorAttribute; } public static class prototypeFolderType { static prototypeFolderType() { Type = new DomNodeType("prototypeFolderType"); nameAttribute = Type.DefineNewAttributeInfo("name", AttributeType.StringType); prototypeFolderChild = Type.DefineNewChildInfo("prototypeFolder", prototypeFolderType.Type, true); prototypeChild = Type.DefineNewChildInfo("prototype", prototypeType.Type, true); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), nameAttribute, null, "name".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo prototypeFolderChild; public static ChildInfo prototypeChild; } public static class prototypeType { static prototypeType() { Type = new DomNodeType("prototypeType"); nameAttribute = prototypeType.Type.DefineNewAttributeInfo("name", AttributeType.StringType); moduleChild = prototypeType.Type.DefineNewChildInfo("module", moduleType.Type, true); connectionChild = prototypeType.Type.DefineNewChildInfo("connection", connectionType.Type, true); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), prototypeType.nameAttribute, null, "name".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo moduleChild; public static ChildInfo connectionChild; } public static class templateFolderType { static templateFolderType() { Type = new DomNodeType("templateFolderType"); nameAttribute = templateFolderType.Type.DefineNewAttributeInfo("name", AttributeType.StringType); referenceFileAttribute = templateFolderType.Type.DefineNewAttributeInfo("referenceFile", AttributeType.UriType); templateFolderChild = templateFolderType.Type.DefineNewChildInfo("templateFolder", templateFolderType.Type, true); templateChild = templateFolderType.Type.DefineNewChildInfo("template", templateType.Type, true); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), templateFolderType.nameAttribute, null, "name".Localize(), false, null, null ), new AttributePropertyDescriptor("referenceFile".Localize(), templateFolderType.referenceFileAttribute, null, "referenceFile".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo referenceFileAttribute; public static ChildInfo templateFolderChild; public static ChildInfo templateChild; } public static class templateType { static templateType() { Type = new DomNodeType("templateType"); guidAttribute = Type.DefineNewAttributeInfo("guid", AttributeType.StringType); labelAttribute = Type.DefineNewAttributeInfo("label", AttributeType.StringType); moduleChild = Type.DefineNewChildInfo("module", moduleType.Type); Type.SetIdAttribute(guidAttribute); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection( new PropertyDescriptor[] { new AttributePropertyDescriptor("guid".Localize(), templateType.guidAttribute, null, "guid".Localize(), false, null, null ), new AttributePropertyDescriptor("label".Localize(), templateType.labelAttribute, null, "label".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo guidAttribute; public static AttributeInfo labelAttribute; public static ChildInfo moduleChild; } public static class socketType { static socketType() { Type = new DomNodeType("socketType"); nameAttribute = Type.DefineNewAttributeInfo("name", AttributeType.NameStringType); typeAttribute = Type.DefineNewAttributeInfo("type", AttributeType.NameStringType); isInputAttribute = Type.DefineNewAttributeInfo("isInput", AttributeType.BooleanType); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), nameAttribute, null, "name".Localize(), false, null, null ), new AttributePropertyDescriptor("type".Localize(), typeAttribute, null, "type".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo typeAttribute; public static AttributeInfo isInputAttribute; } public static class groupSocketType { static groupSocketType() { Type = new DomNodeType("groupSocketType", socketType.Type); nameAttribute = socketType.nameAttribute; typeAttribute = socketType.typeAttribute; moduleAttribute = Type.DefineNewAttributeInfo("module", AttributeType.DomNodeRefType); pinAttribute = Type.DefineNewAttributeInfo("pin", AttributeType.NameStringType); visibleAttribute = Type.DefineNewAttributeInfo("visible", AttributeType.BooleanType, defaultValue: true); indexAttribute = Type.DefineNewAttributeInfo("index", AttributeType.IntType); pinNameAttribute = Type.DefineNewAttributeInfo("pinName", AttributeType.NameStringType); pinnedAttribute = Type.DefineNewAttributeInfo("pinned", AttributeType.BooleanType, defaultValue: true); pinYAttribute = Type.DefineNewAttributeInfo("pinY", AttributeType.IntType); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), nameAttribute, null, "name".Localize(), false, null, null ), new AttributePropertyDescriptor("type".Localize(), typeAttribute, null, "type".Localize(), false, null, null ), new AttributePropertyDescriptor("module".Localize(), moduleAttribute, null, "module".Localize(), false, null, null ), new AttributePropertyDescriptor("pin".Localize(), pinAttribute, null, "pin".Localize(), false, null, null ), new AttributePropertyDescriptor("visible".Localize(), visibleAttribute, null, "visible".Localize(), false, null, null ), new AttributePropertyDescriptor("index".Localize(), indexAttribute, null, "index".Localize(), false, null, null ), new AttributePropertyDescriptor("pinName".Localize(), pinNameAttribute, null, "pinName".Localize(), false, null, null ), new AttributePropertyDescriptor("pinned".Localize(), pinnedAttribute, null, "pinned".Localize(), false, null, null ), new AttributePropertyDescriptor("pinY".Localize(), pinYAttribute, null, "pinY".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo typeAttribute; public static AttributeInfo moduleAttribute; public static AttributeInfo pinAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo indexAttribute; public static AttributeInfo pinNameAttribute; public static AttributeInfo pinnedAttribute; public static AttributeInfo pinYAttribute; } public static class groupType { static groupType() { Type = new DomNodeType("groupType", moduleType.Type); nameAttribute = Type.DefineNewAttributeInfo("name", AttributeType.StringType, defaultValue: "group"); //nameAttribute = moduleType.nameAttribute; labelAttribute = moduleType.labelAttribute; xAttribute = moduleType.xAttribute; yAttribute = moduleType.yAttribute; visibleAttribute = moduleType.visibleAttribute; showUnconnectedPinsAttribute = moduleType.showUnconnectedPinsAttribute; sourceGuidAttribute = moduleType.sourceGuidAttribute; validatedAttribute = moduleType.validatedAttribute; expandedAttribute = Type.DefineNewAttributeInfo("expanded", AttributeType.BooleanType, defaultValue: true); showExpandedGroupPinsAttribute = Type.DefineNewAttributeInfo("showExpandedGroupPins", AttributeType.BooleanType, defaultValue: true); autosizeAttribute = Type.DefineNewAttributeInfo("autosize", AttributeType.BooleanType, defaultValue:true); widthAttribute = Type.DefineNewAttributeInfo("width", AttributeType.IntType); heightAttribute = Type.DefineNewAttributeInfo("height", AttributeType.IntType); minwidthAttribute = Type.DefineNewAttributeInfo("minwidth", AttributeType.IntType); minheightAttribute = Type.DefineNewAttributeInfo("minheight", AttributeType.IntType); dynamicPropertyChild = moduleType.dynamicPropertyChild; inputChild = Type.DefineNewChildInfo("input", groupSocketType.Type, true); outputChild = Type.DefineNewChildInfo("output", groupSocketType.Type, true); moduleChild = Type.DefineNewChildInfo("module", moduleType.Type, true); connectionChild = Type.DefineNewChildInfo("connection", connectionType.Type, true); annotationChild = Type.DefineNewChildInfo("annotation", annotationType.Type, true); Type.SetIdAttribute(nameAttribute); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), nameAttribute, null, "name".Localize(), false, null, null ), new AttributePropertyDescriptor("label".Localize(), labelAttribute, null, "label".Localize(), false, null, null ), new AttributePropertyDescriptor("x".Localize(), xAttribute, null, "x".Localize(), false, null, null ), new AttributePropertyDescriptor("y".Localize(), yAttribute, null, "y".Localize(), false, null, null ), new AttributePropertyDescriptor("visible".Localize(), visibleAttribute, null, "visible".Localize(), false, null, null ), new AttributePropertyDescriptor("showUnconnectedPins".Localize(), showUnconnectedPinsAttribute, null, "showUnconnectedPins".Localize(), false, null, null ), new AttributePropertyDescriptor("sourceGuid".Localize(), sourceGuidAttribute, null, "sourceGuid".Localize(), false, null, null ), new AttributePropertyDescriptor("validated".Localize(), validatedAttribute, null, "validated".Localize(), false, null, null ), new AttributePropertyDescriptor("expanded".Localize(), expandedAttribute, null, "expanded".Localize(), false, null, null ), new AttributePropertyDescriptor("showExpandedGroupPins".Localize(), showExpandedGroupPinsAttribute, null, "showExpandedGroupPins".Localize(), false, null, null ), new AttributePropertyDescriptor("autosize".Localize(), autosizeAttribute, null, "autosize".Localize(), false, null, null ), new AttributePropertyDescriptor("width".Localize(), widthAttribute, null, "width".Localize(), false, null, null ), new AttributePropertyDescriptor("height".Localize(), heightAttribute, null, "height".Localize(), false, null, null ), new AttributePropertyDescriptor("minwidth".Localize(), minwidthAttribute, null, "minwidth".Localize(), false, null, null ), new AttributePropertyDescriptor("minheight".Localize(), minheightAttribute, null, "minheight".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo labelAttribute; public static AttributeInfo xAttribute; public static AttributeInfo yAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo showUnconnectedPinsAttribute; public static AttributeInfo sourceGuidAttribute; public static AttributeInfo validatedAttribute; public static AttributeInfo expandedAttribute; public static AttributeInfo showExpandedGroupPinsAttribute; public static AttributeInfo autosizeAttribute; public static AttributeInfo widthAttribute; public static AttributeInfo heightAttribute; public static AttributeInfo minwidthAttribute; public static AttributeInfo minheightAttribute; public static ChildInfo dynamicPropertyChild; public static ChildInfo inputChild; public static ChildInfo outputChild; public static ChildInfo moduleChild; public static ChildInfo connectionChild; public static ChildInfo annotationChild; } public static class missingTemplateType { static missingTemplateType() { Type = new DomNodeType("missingTemplateType", templateType.Type); guidAttribute = templateType.guidAttribute; labelAttribute = templateType.labelAttribute; moduleChild = templateType.moduleChild; Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("guid".Localize(), guidAttribute, null, "guid".Localize(), false, null, null ), new AttributePropertyDescriptor("label".Localize(), labelAttribute, null, "label".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo guidAttribute; public static AttributeInfo labelAttribute; public static ChildInfo moduleChild; } public static class missingModuleType { static missingModuleType() { Type = new DomNodeType("missingModuleType", moduleType.Type); nameAttribute = Type.DefineNewAttributeInfo("name", AttributeType.StringType, defaultValue: "missingType"); //nameAttribute = moduleType.nameAttribute; labelAttribute = moduleType.labelAttribute; xAttribute = moduleType.xAttribute; yAttribute = moduleType.yAttribute; visibleAttribute = moduleType.visibleAttribute; showUnconnectedPinsAttribute = moduleType.showUnconnectedPinsAttribute; sourceGuidAttribute = moduleType.sourceGuidAttribute; validatedAttribute = moduleType.validatedAttribute; dynamicPropertyChild = moduleType.dynamicPropertyChild; Type.SetIdAttribute(nameAttribute); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), nameAttribute, null, "name".Localize(), false, null, null ), new AttributePropertyDescriptor("label".Localize(), labelAttribute, null, "label".Localize(), false, null, null ), new AttributePropertyDescriptor("x".Localize(), xAttribute, null, "x".Localize(), false, null, null ), new AttributePropertyDescriptor("y".Localize(), yAttribute, null, "y".Localize(), false, null, null ), new AttributePropertyDescriptor("visible".Localize(), visibleAttribute, null, "visible".Localize(), false, null, null ), new AttributePropertyDescriptor("showUnconnectedPins".Localize(), showUnconnectedPinsAttribute, null, "showUnconnectedPins".Localize(), false, null, null ), new AttributePropertyDescriptor("sourceGuid".Localize(), sourceGuidAttribute, null, "sourceGuid".Localize(), false, null, null ), new AttributePropertyDescriptor("validated".Localize(), validatedAttribute, null, "validated".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo labelAttribute; public static AttributeInfo xAttribute; public static AttributeInfo yAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo showUnconnectedPinsAttribute; public static AttributeInfo sourceGuidAttribute; public static AttributeInfo validatedAttribute; public static ChildInfo dynamicPropertyChild; } public static class moduleTemplateRefType { static moduleTemplateRefType() { Type = new DomNodeType("moduleTemplateRefType"); nameAttribute = moduleType.nameAttribute; labelAttribute = moduleType.labelAttribute; xAttribute = moduleType.xAttribute; yAttribute = moduleType.yAttribute; visibleAttribute = moduleType.visibleAttribute; showUnconnectedPinsAttribute = moduleType.showUnconnectedPinsAttribute; sourceGuidAttribute = moduleType.sourceGuidAttribute; validatedAttribute = moduleType.validatedAttribute; dynamicPropertyChild = moduleType.dynamicPropertyChild; guidRefAttribute = Type.DefineNewAttributeInfo("guidRef", AttributeType.DomNodeRefType); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), nameAttribute, null, "name".Localize(), false, null, null ), new AttributePropertyDescriptor("label".Localize(), labelAttribute, null, "label".Localize(), false, null, null ), new AttributePropertyDescriptor("x".Localize(), xAttribute, null, "x".Localize(), false, null, null ), new AttributePropertyDescriptor("y".Localize(), yAttribute, null, "y".Localize(), false, null, null ), new AttributePropertyDescriptor("visible".Localize(), visibleAttribute, null, "visible".Localize(), false, null, null ), new AttributePropertyDescriptor("showUnconnectedPins".Localize(), showUnconnectedPinsAttribute, null, "showUnconnectedPins".Localize(), false, null, null ), new AttributePropertyDescriptor("sourceGuid".Localize(), sourceGuidAttribute, null, "sourceGuid".Localize(), false, null, null ), new AttributePropertyDescriptor("validated".Localize(), validatedAttribute, null, "validated".Localize(), false, null, null ), new AttributePropertyDescriptor("guidRef".Localize(), guidRefAttribute, null, "guidRef".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo labelAttribute; public static AttributeInfo xAttribute; public static AttributeInfo yAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo showUnconnectedPinsAttribute; public static AttributeInfo sourceGuidAttribute; public static AttributeInfo validatedAttribute; public static AttributeInfo guidRefAttribute; public static ChildInfo dynamicPropertyChild; } public static class groupTemplateRefType { static groupTemplateRefType() { Type = new DomNodeType("groupTemplateRefType", groupType.Type); nameAttribute = groupType.nameAttribute; labelAttribute = groupType.labelAttribute; xAttribute = groupType.xAttribute; yAttribute = groupType.yAttribute; visibleAttribute = groupType.visibleAttribute; showUnconnectedPinsAttribute = groupType.showUnconnectedPinsAttribute; sourceGuidAttribute = groupType.sourceGuidAttribute; validatedAttribute = groupType.validatedAttribute; dynamicPropertyChild = groupType.dynamicPropertyChild; expandedAttribute = groupType.expandedAttribute; showExpandedGroupPinsAttribute = groupType.showExpandedGroupPinsAttribute; autosizeAttribute = groupType.autosizeAttribute; widthAttribute = groupType.widthAttribute; heightAttribute = groupType.heightAttribute; minwidthAttribute = groupType.minwidthAttribute; minheightAttribute = groupType.minheightAttribute; inputChild = groupType.inputChild; outputChild = groupType.outputChild; moduleChild = groupType.moduleChild; connectionChild = groupType.connectionChild; annotationChild = groupType.annotationChild; guidRefAttribute = Type.DefineNewAttributeInfo("guidRef", AttributeType.DomNodeRefType); refExpandedAttribute = Type.DefineNewAttributeInfo("refExpanded", AttributeType.BooleanType, defaultValue:false); refShowExpandedGroupPinsAttribute = Type.DefineNewAttributeInfo("refShowExpandedGroupPins", AttributeType.BooleanType, defaultValue:true); Type.SetTag(new System.ComponentModel.PropertyDescriptorCollection(new PropertyDescriptor[] { new AttributePropertyDescriptor("name".Localize(), nameAttribute, null, "name".Localize(), false, null, null ), new AttributePropertyDescriptor("label".Localize(), labelAttribute, null, "label".Localize(), false, null, null ), new AttributePropertyDescriptor("x".Localize(), xAttribute, null, "x".Localize(), false, null, null ), new AttributePropertyDescriptor("y".Localize(), yAttribute, null, "y".Localize(), false, null, null ), new AttributePropertyDescriptor("visible".Localize(), visibleAttribute, null, "visible".Localize(), false, null, null ), new AttributePropertyDescriptor("showUnconnectedPins".Localize(), showUnconnectedPinsAttribute, null, "showUnconnectedPins".Localize(), false, null, null ), new AttributePropertyDescriptor("sourceGuid".Localize(), sourceGuidAttribute, null, "sourceGuid".Localize(), false, null, null ), new AttributePropertyDescriptor("validated".Localize(), validatedAttribute, null, "validated".Localize(), false, null, null ), new AttributePropertyDescriptor("expanded".Localize(), expandedAttribute, null, "expanded".Localize(), false, null, null ), new AttributePropertyDescriptor("showExpandedGroupPins".Localize(), showExpandedGroupPinsAttribute, null, "showExpandedGroupPins".Localize(), false, null, null ), new AttributePropertyDescriptor("autosize".Localize(), autosizeAttribute, null, "autosize".Localize(), false, null, null ), new AttributePropertyDescriptor("width".Localize(), widthAttribute, null, "width".Localize(), false, null, null ), new AttributePropertyDescriptor("height".Localize(), heightAttribute, null, "height".Localize(), false, null, null ), new AttributePropertyDescriptor("minwidth".Localize(), minwidthAttribute, null, "minwidth".Localize(), false, null, null ), new AttributePropertyDescriptor("minheight".Localize(), minheightAttribute, null, "minheight".Localize(), false, null, null ), new AttributePropertyDescriptor("guidRef".Localize(), guidRefAttribute, null, "guidRef".Localize(), false, null, null ), new AttributePropertyDescriptor("refExpanded".Localize(), refExpandedAttribute, null, "refExpanded".Localize(), false, null, null ), new AttributePropertyDescriptor("refShowExpandedGroupPins".Localize(), refShowExpandedGroupPinsAttribute, null, "refShowExpandedGroupPins".Localize(), false, null, null ), })); } public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo labelAttribute; public static AttributeInfo xAttribute; public static AttributeInfo yAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo showUnconnectedPinsAttribute; public static AttributeInfo sourceGuidAttribute; public static AttributeInfo validatedAttribute; public static AttributeInfo expandedAttribute; public static AttributeInfo showExpandedGroupPinsAttribute; public static AttributeInfo autosizeAttribute; public static AttributeInfo widthAttribute; public static AttributeInfo heightAttribute; public static AttributeInfo minwidthAttribute; public static AttributeInfo minheightAttribute; public static AttributeInfo guidRefAttribute; public static AttributeInfo refExpandedAttribute; public static AttributeInfo refShowExpandedGroupPinsAttribute; public static ChildInfo dynamicPropertyChild; public static ChildInfo inputChild; public static ChildInfo outputChild; public static ChildInfo moduleChild; public static ChildInfo connectionChild; public static ChildInfo annotationChild; } //public static ChildInfo circuitRootElement; }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnDistrito class. /// </summary> [Serializable] public partial class PnDistritoCollection : ActiveList<PnDistrito, PnDistritoCollection> { public PnDistritoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnDistritoCollection</returns> public PnDistritoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnDistrito o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_distrito table. /// </summary> [Serializable] public partial class PnDistrito : ActiveRecord<PnDistrito>, IActiveRecord { #region .ctors and Default Settings public PnDistrito() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnDistrito(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnDistrito(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnDistrito(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_distrito", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdDistrito = new TableSchema.TableColumn(schema); colvarIdDistrito.ColumnName = "id_distrito"; colvarIdDistrito.DataType = DbType.Int32; colvarIdDistrito.MaxLength = 0; colvarIdDistrito.AutoIncrement = true; colvarIdDistrito.IsNullable = false; colvarIdDistrito.IsPrimaryKey = true; colvarIdDistrito.IsForeignKey = false; colvarIdDistrito.IsReadOnly = false; colvarIdDistrito.DefaultSetting = @""; colvarIdDistrito.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdDistrito); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = -1; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = true; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema); colvarObservaciones.ColumnName = "observaciones"; colvarObservaciones.DataType = DbType.AnsiString; colvarObservaciones.MaxLength = -1; colvarObservaciones.AutoIncrement = false; colvarObservaciones.IsNullable = true; colvarObservaciones.IsPrimaryKey = false; colvarObservaciones.IsForeignKey = false; colvarObservaciones.IsReadOnly = false; colvarObservaciones.DefaultSetting = @""; colvarObservaciones.ForeignKeyTableName = ""; schema.Columns.Add(colvarObservaciones); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_distrito",schema); } } #endregion #region Props [XmlAttribute("IdDistrito")] [Bindable(true)] public int IdDistrito { get { return GetColumnValue<int>(Columns.IdDistrito); } set { SetColumnValue(Columns.IdDistrito, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("Observaciones")] [Bindable(true)] public string Observaciones { get { return GetColumnValue<string>(Columns.Observaciones); } set { SetColumnValue(Columns.Observaciones, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre,string varObservaciones) { PnDistrito item = new PnDistrito(); item.Nombre = varNombre; item.Observaciones = varObservaciones; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdDistrito,string varNombre,string varObservaciones) { PnDistrito item = new PnDistrito(); item.IdDistrito = varIdDistrito; item.Nombre = varNombre; item.Observaciones = varObservaciones; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdDistritoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn ObservacionesColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdDistrito = @"id_distrito"; public static string Nombre = @"nombre"; public static string Observaciones = @"observaciones"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Linq.Tests { public class RangeTests : EnumerableTests { [Fact] public void Range_ProduceCorrectSequence() { var rangeSequence = Enumerable.Range(1, 100); int expected = 0; foreach (var val in rangeSequence) { expected++; Assert.Equal(expected, val); } Assert.Equal(100, expected); } [Fact] public void Range_ToArray_ProduceCorrectResult() { var array = Enumerable.Range(1, 100).ToArray(); Assert.Equal(100, array.Length); for (var i = 0; i < array.Length; i++) Assert.Equal(i + 1, array[i]); } [Fact] public void Range_ToList_ProduceCorrectResult() { var list = Enumerable.Range(1, 100).ToList(); Assert.Equal(100, list.Count); for (var i = 0; i < list.Count; i++) Assert.Equal(i + 1, list[i]); } [Fact] public void Range_ZeroCountLeadToEmptySequence() { var array = Enumerable.Range(1, 0).ToArray(); var array2 = Enumerable.Range(int.MinValue, 0).ToArray(); var array3 = Enumerable.Range(int.MaxValue, 0).ToArray(); Assert.Equal(0, array.Length); Assert.Equal(0, array2.Length); Assert.Equal(0, array3.Length); } [Fact] public void Range_ThrowExceptionOnNegativeCount() { AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Enumerable.Range(1, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Enumerable.Range(1, int.MinValue)); } [Fact] public void Range_ThrowExceptionOnOverflow() { AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Enumerable.Range(1000, int.MaxValue)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Enumerable.Range(int.MaxValue, 1000)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Enumerable.Range(int.MaxValue - 10, 20)); } [Fact] public void Range_NotEnumerateAfterEnd() { using (var rangeEnum = Enumerable.Range(1, 1).GetEnumerator()) { Assert.True(rangeEnum.MoveNext()); Assert.False(rangeEnum.MoveNext()); Assert.False(rangeEnum.MoveNext()); } } [Fact] public void Range_EnumerableAndEnumeratorAreSame() { var rangeEnumerable = Enumerable.Range(1, 1); using (var rangeEnumerator = rangeEnumerable.GetEnumerator()) { Assert.Same(rangeEnumerable, rangeEnumerator); } } [Fact] public void Range_GetEnumeratorReturnUniqueInstances() { var rangeEnumerable = Enumerable.Range(1, 1); using (var enum1 = rangeEnumerable.GetEnumerator()) using (var enum2 = rangeEnumerable.GetEnumerator()) { Assert.NotSame(enum1, enum2); } } [Fact] public void Range_ToInt32MaxValue() { int from = int.MaxValue - 3; int count = 4; var rangeEnumerable = Enumerable.Range(from, count); Assert.Equal(count, rangeEnumerable.Count()); int[] expected = { int.MaxValue - 3, int.MaxValue - 2, int.MaxValue - 1, int.MaxValue }; Assert.Equal(expected, rangeEnumerable); } [Fact] public void RepeatedCallsSameResults() { Assert.Equal(Enumerable.Range(-1, 2), Enumerable.Range(-1, 2)); Assert.Equal(Enumerable.Range(0, 0), Enumerable.Range(0, 0)); } [Fact] public void NegativeStart() { int start = -5; int count = 1; int[] expected = { -5 }; Assert.Equal(expected, Enumerable.Range(start, count)); } [Fact] public void ArbitraryStart() { int start = 12; int count = 6; int[] expected = { 12, 13, 14, 15, 16, 17 }; Assert.Equal(expected, Enumerable.Range(start, count)); } [Fact] public void Take() { Assert.Equal(Enumerable.Range(0, 10), Enumerable.Range(0, 20).Take(10)); } [Fact] public void TakeExcessive() { Assert.Equal(Enumerable.Range(0, 10), Enumerable.Range(0, 10).Take(int.MaxValue)); } [Fact] public void Skip() { Assert.Equal(Enumerable.Range(10, 10), Enumerable.Range(0, 20).Skip(10)); } [Fact] public void SkipExcessive() { Assert.Empty(Enumerable.Range(10, 10).Skip(20)); } [Fact] public void SkipTakeCanOnlyBeOne() { Assert.Equal(new[] { 1 }, Enumerable.Range(1, 10).Take(1)); Assert.Equal(new[] { 2 }, Enumerable.Range(1, 10).Skip(1).Take(1)); Assert.Equal(new[] { 3 }, Enumerable.Range(1, 10).Take(3).Skip(2)); Assert.Equal(new[] { 1 }, Enumerable.Range(1, 10).Take(3).Take(1)); } [Fact] public void ElementAt() { Assert.Equal(4, Enumerable.Range(0, 10).ElementAt(4)); } [Fact] public void ElementAtExcessiveThrows() { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => Enumerable.Range(0, 10).ElementAt(100)); } [Fact] public void ElementAtOrDefault() { Assert.Equal(4, Enumerable.Range(0, 10).ElementAtOrDefault(4)); } [Fact] public void ElementAtOrDefaultExcessiveIsDefault() { Assert.Equal(0, Enumerable.Range(52, 10).ElementAtOrDefault(100)); } [Fact] public void First() { Assert.Equal(57, Enumerable.Range(57, 1000000000).First()); } [Fact] public void FirstOrDefault() { Assert.Equal(-100, Enumerable.Range(-100, int.MaxValue).FirstOrDefault()); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.Netcoreapp, ".NET Core optimizes Enumerable.Range().Last(). Without this optimization, this test takes a long time. See https://github.com/dotnet/corefx/pull/2401.")] public void Last() { Assert.Equal(1000000056, Enumerable.Range(57, 1000000000).Last()); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.Netcoreapp, ".NET Core optimizes Enumerable.Range().LastOrDefault(). Without this optimization, this test takes a long time. See https://github.com/dotnet/corefx/pull/2401.")] public void LastOrDefault() { Assert.Equal(int.MaxValue - 101, Enumerable.Range(-100, int.MaxValue).LastOrDefault()); } } }
/* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. */ /****************************************************************************** * * You may not use the identified files except in compliance with The MIT * License (the "License.") * * You may obtain a copy of the License at * https://github.com/oracle/Oracle.NET/blob/master/LICENSE * * 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.Data; using System.Text; using Oracle.ManagedDataAccess.Client; using Oracle.ManagedDataAccess.Types; namespace Sample4 { /// <summary> /// Sample 4: Demonstrates how a DataSet can be populated from a /// REF Cursor. The sample also demonstrates how a REF /// Cursor can be updated. /// </summary> class Sample4 { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { // Connect string constr = "User Id=scott;Password=<PASSWORD>;Data Source=oracle"; OracleConnection con = Connect(constr); // Setup Setup(con); // Set the command OracleCommand cmd = new OracleCommand("TEST.Ret1Cur", con); cmd.CommandType = CommandType.StoredProcedure; // Bind // TEST.Ret1Cur is a function so ParameterDirection is ReturnValue. OracleParameter param = cmd.Parameters.Add("refcursor", OracleDbType.RefCursor); param.Direction = ParameterDirection.ReturnValue; // Create an OracleDataAdapter OracleDataAdapter da = new OracleDataAdapter(cmd); try { // 1. Demostrate populating a DataSet with RefCursor // Populate a DataSet DataSet ds = new DataSet(); da.FillSchema(ds, SchemaType.Source, "myRefCursor"); da.Fill(ds, "myRefCursor"); // Obtain the row which we want to modify DataRow[] rowsWanted = ds.Tables["myRefCursor"].Select("THEKEY = 1"); // 2. Demostrate how to update with RefCursor // Update the "story" column rowsWanted[0]["story"] = "New story"; // Setup the update command on the DataAdapter OracleCommand updcmd = new OracleCommand("TEST.UpdateREFCur", con); updcmd.CommandType = CommandType.StoredProcedure; OracleParameter param1 = updcmd.Parameters.Add("myStory", OracleDbType.Varchar2, 32); param1.SourceVersion = DataRowVersion.Current; param1.SourceColumn = "STORY"; OracleParameter param2 = updcmd.Parameters.Add("myClipId", OracleDbType.Decimal); param2.SourceColumn = "THEKEY"; param2.SourceVersion = DataRowVersion.Original; da.UpdateCommand = updcmd; // Update da.Update(ds, "myRefCursor"); Console.WriteLine("Data has been updated."); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } finally { // Dispose OracleCommand object cmd.Dispose(); // Close and Dispose OracleConnection object con.Close(); con.Dispose(); } } /// <summary> /// Wrapper for Opening a new Connection /// </summary> /// <param name="connectStr"></param> /// <returns></returns> public static OracleConnection Connect(string connectStr) { OracleConnection con = new OracleConnection(connectStr); try { con.Open(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } return con; } /// <summary> /// Setup the necessary Tables & Test Data /// </summary> /// <param name="connectStr"></param> public static void Setup(OracleConnection con) { StringBuilder blr; OracleCommand cmd = new OracleCommand("",con); // Create multimedia table blr = new StringBuilder(); blr.Append("DROP TABLE multimedia_tab"); cmd.CommandText = blr.ToString(); try { cmd.ExecuteNonQuery(); } catch { } blr = new StringBuilder(); blr.Append("CREATE TABLE multimedia_tab(thekey NUMBER(4) PRIMARY KEY,"); blr.Append("story CLOB, sound BLOB)"); cmd.CommandText = blr.ToString(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } blr = new StringBuilder(); blr.Append("INSERT INTO multimedia_tab values("); blr.Append("1,"); blr.Append("'This is a long story. Once upon a time ...',"); blr.Append("'656667686970717273747576777879808182838485')"); cmd.CommandText = blr.ToString(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } // Create Package Header blr = new StringBuilder(); blr.Append("CREATE OR REPLACE PACKAGE TEST is "); blr.Append("TYPE refcursor is ref cursor;"); blr.Append("FUNCTION Ret1Cur return refCursor;"); blr.Append("PROCEDURE Get1CurOut(p_cursor1 out refCursor);"); blr.Append("FUNCTION Get3Cur (p_cursor1 out refCursor,"); blr.Append("p_cursor2 out refCursor)"); blr.Append("return refCursor;"); blr.Append("FUNCTION Get1Cur return refCursor;"); blr.Append("PROCEDURE UpdateRefCur(new_story in VARCHAR,"); blr.Append("clipid in NUMBER);"); blr.Append("PROCEDURE GetStoryForClip1(p_cursor out refCursor);"); blr.Append("PROCEDURE GetRefCurData (p_cursor out refCursor,myStory out VARCHAR2);"); blr.Append("end TEST;"); cmd.CommandText = blr.ToString(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } // Create Package Body blr = new StringBuilder(); blr.Append("create or replace package body TEST is "); blr.Append("FUNCTION Ret1Cur return refCursor is "); blr.Append("p_cursor refCursor; "); blr.Append("BEGIN "); blr.Append("open p_cursor for select * from multimedia_tab; "); blr.Append("return (p_cursor); "); blr.Append("END Ret1Cur; "); blr.Append("PROCEDURE Get1CurOut(p_cursor1 out refCursor) is "); blr.Append("BEGIN "); blr.Append("OPEN p_cursor1 for select * from emp; "); blr.Append("END Get1CurOut; "); blr.Append("FUNCTION Get3Cur (p_cursor1 out refCursor, "); blr.Append("p_cursor2 out refCursor)"); blr.Append("return refCursor is "); blr.Append("p_cursor refCursor; "); blr.Append("BEGIN "); blr.Append("open p_cursor for select * from multimedia_tab; "); blr.Append("open p_cursor1 for select * from emp; "); blr.Append("open p_cursor2 for select * from dept; "); blr.Append("return (p_cursor); "); blr.Append("END Get3Cur; "); blr.Append("FUNCTION Get1Cur return refCursor is "); blr.Append("p_cursor refCursor; "); blr.Append("BEGIN "); blr.Append("open p_cursor for select * from multimedia_tab; "); blr.Append("return (p_cursor); "); blr.Append("END Get1Cur; "); blr.Append("PROCEDURE UpdateRefCur(new_story in VARCHAR, "); blr.Append("clipid in NUMBER) is "); blr.Append("BEGIN "); blr.Append("Update multimedia_tab set story = new_story where thekey = clipid; "); blr.Append("END UpdateRefCur; "); blr.Append("PROCEDURE GetStoryForClip1(p_cursor out refCursor) is "); blr.Append("BEGIN "); blr.Append("open p_cursor for "); blr.Append("Select story from multimedia_tab where thekey = 1; "); blr.Append("END GetStoryForClip1; "); blr.Append("PROCEDURE GetRefCurData (p_cursor out refCursor,"); blr.Append("myStory out VARCHAR2) is "); blr.Append("BEGIN "); blr.Append("FETCH p_cursor into myStory; "); blr.Append("END GetRefCurData; "); blr.Append("end TEST;"); cmd.CommandText = blr.ToString(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } } } }
using System; using System.Collections.Generic; using System.Reflection; namespace ALinq.SqlClient { internal class SqlDeflator { // Fields private SqlAliasDeflator aDeflator = new SqlAliasDeflator(); private SqlColumnDeflator cDeflator = new SqlColumnDeflator(); private SqlDuplicateColumnDeflator dupColumnDeflator = new SqlDuplicateColumnDeflator(); private SqlTopSelectDeflator tsDeflator = new SqlTopSelectDeflator(); private SqlValueDeflator vDeflator = new SqlValueDeflator(); // Methods internal SqlDeflator() { } internal SqlNode Deflate(SqlNode node) { node = this.vDeflator.Visit(node); node = this.cDeflator.Visit(node); node = this.aDeflator.Visit(node); node = this.tsDeflator.Visit(node); node = this.dupColumnDeflator.Visit(node); return node; } // Nested Types private class SqlAliasDeflator : SqlVisitor { // Fields private Dictionary<SqlAlias, SqlAlias> removedMap = new Dictionary<SqlAlias, SqlAlias>(); // Methods internal SqlAliasDeflator() { } private bool HasEmptySource(SqlSource node) { SqlAlias alias = node as SqlAlias; if (alias == null) { return false; } SqlSelect select = alias.Node as SqlSelect; if (select == null) { return false; } return (((((select.Row.Columns.Count == 0) && (select.From == null)) && ((select.Where == null) && (select.GroupBy.Count == 0))) && (select.Having == null)) && (select.OrderBy.Count == 0)); } private bool HasTrivialProjection(SqlSelect select) { foreach (SqlColumn column in select.Row.Columns) { if ((column.Expression != null) && (column.Expression.NodeType != SqlNodeType.ColumnRef)) { return false; } } return true; } private bool HasTrivialSource(SqlSource node) { SqlJoin join = node as SqlJoin; if (join == null) { return (node is SqlAlias); } return (this.HasTrivialSource(join.Left) && this.HasTrivialSource(join.Right)); } private bool IsTrivialSelect(SqlSelect select) { if ((((select.OrderBy.Count != 0) || (select.GroupBy.Count != 0)) || ((select.Having != null) || (select.Top != null))) || (select.IsDistinct || (select.Where != null))) { return false; } return (this.HasTrivialSource(select.From) && this.HasTrivialProjection(select)); } internal override SqlExpression VisitAliasRef(SqlAliasRef aref) { SqlAlias alias2; SqlAlias key = aref.Alias; if (this.removedMap.TryGetValue(key, out alias2)) { throw Error.InvalidReferenceToRemovedAliasDuringDeflation(); } return aref; } internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { if ((cref.Column.Alias == null) || !this.removedMap.ContainsKey(cref.Column.Alias)) { return cref; } SqlColumnRef expression; //if (cref.Column is SqlDynamicColumn) // expression = cref; //else expression = cref.Column.Expression as SqlColumnRef; if ((expression != null) && (expression.ClrType != cref.ClrType)) { expression.SetClrType(cref.ClrType); return this.VisitColumnRef(expression); } return expression; } internal override SqlSource VisitJoin(SqlJoin join) { base.VisitJoin(join); switch (join.JoinType) { case SqlJoinType.Cross: case SqlJoinType.Inner: return join; case SqlJoinType.LeftOuter: case SqlJoinType.CrossApply: case SqlJoinType.OuterApply: { if (!this.HasEmptySource(join.Right)) { return join; } SqlAlias right = (SqlAlias)join.Right; this.removedMap[right] = right; return join.Left; } } return join; } internal override SqlSource VisitSource(SqlSource node) { node = (SqlSource)this.Visit(node); SqlAlias alias = node as SqlAlias; if (alias != null) { SqlSelect select = alias.Node as SqlSelect; if ((select != null) && this.IsTrivialSelect(select)) { this.removedMap[alias] = alias; node = select.From; } } return node; } } private class SqlColumnDeflator : SqlVisitor { // Fields private SqlAggregateChecker aggregateChecker = new SqlAggregateChecker(); private bool forceReferenceAll; private bool isTopLevel = true; private Dictionary<SqlNode, SqlNode> referenceMap = new Dictionary<SqlNode, SqlNode>(); // Methods internal SqlColumnDeflator() { } internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { this.referenceMap[cref.Column] = cref.Column; return cref; } internal override SqlExpression VisitExists(SqlSubSelect ss) { SqlExpression expression; bool isTopLevel = this.isTopLevel; this.isTopLevel = false; try { expression = base.VisitExists(ss); } finally { this.isTopLevel = isTopLevel; } return expression; } internal override SqlSource VisitJoin(SqlJoin join) { join.Condition = this.VisitExpression(join.Condition); join.Right = this.VisitSource(join.Right); join.Left = this.VisitSource(join.Left); return join; } internal override SqlNode VisitLink(SqlLink link) { int num = 0; int count = link.KeyExpressions.Count; while (num < count) { link.KeyExpressions[num] = this.VisitExpression(link.KeyExpressions[num]); num++; } return link; } internal override SqlExpression VisitScalarSubSelect(SqlSubSelect ss) { SqlExpression expression; bool isTopLevel = this.isTopLevel; this.isTopLevel = false; bool forceReferenceAll = this.forceReferenceAll; this.forceReferenceAll = true; try { expression = base.VisitScalarSubSelect(ss); } finally { this.isTopLevel = isTopLevel; this.forceReferenceAll = forceReferenceAll; } return expression; } internal override SqlSelect VisitSelect(SqlSelect select) { bool forceReferenceAll = this.forceReferenceAll; this.forceReferenceAll = false; bool isTopLevel = this.isTopLevel; try { if (this.isTopLevel) { select.Selection = this.VisitExpression(select.Selection); } this.isTopLevel = false; for (int i = select.Row.Columns.Count - 1; i >= 0; i--) { SqlColumn key = select.Row.Columns[i]; if (((!forceReferenceAll && !this.referenceMap.ContainsKey(key)) && !select.IsDistinct) && ((select.GroupBy.Count != 0) || !this.aggregateChecker.HasAggregates(key.Expression))) { select.Row.Columns.RemoveAt(i); } else { this.VisitExpression(key.Expression); } } select.Top = this.VisitExpression(select.Top); for (int j = select.OrderBy.Count - 1; j >= 0; j--) { select.OrderBy[j].Expression = this.VisitExpression(select.OrderBy[j].Expression); } select.Having = this.VisitExpression(select.Having); for (int k = select.GroupBy.Count - 1; k >= 0; k--) { select.GroupBy[k] = this.VisitExpression(select.GroupBy[k]); } select.Where = this.VisitExpression(select.Where); select.From = this.VisitSource(select.From); } finally { this.isTopLevel = isTopLevel; this.forceReferenceAll = forceReferenceAll; } return select; } internal override SqlNode VisitUnion(SqlUnion su) { bool forceReferenceAll = this.forceReferenceAll; this.forceReferenceAll = true; su.Left = this.Visit(su.Left); su.Right = this.Visit(su.Right); this.forceReferenceAll = forceReferenceAll; return su; } } private class SqlColumnEqualizer : SqlVisitor { // Fields private Dictionary<SqlColumn, SqlColumn> map; // Methods internal SqlColumnEqualizer() { } internal bool AreEquivalent(SqlExpression e1, SqlExpression e2) { SqlColumn column3; if (SqlComparer.AreEqual(e1, e2)) { return true; } SqlColumnRef ref2 = e1 as SqlColumnRef; SqlColumnRef ref3 = e2 as SqlColumnRef; if ((ref2 == null) || (ref3 == null)) { return false; } SqlColumn rootColumn = ref2.GetRootColumn(); SqlColumn column2 = ref3.GetRootColumn(); return (this.map.TryGetValue(rootColumn, out column3) && (column3 == column2)); } internal void BuildEqivalenceMap(SqlSource scope) { this.map = new Dictionary<SqlColumn, SqlColumn>(); this.Visit(scope); } private void CheckJoinCondition(SqlExpression expr) { switch (expr.NodeType) { case SqlNodeType.EQ: case SqlNodeType.EQ2V: { SqlBinary binary2 = (SqlBinary)expr; SqlColumnRef left = binary2.Left as SqlColumnRef; SqlColumnRef right = binary2.Right as SqlColumnRef; if ((left != null) && (right != null)) { SqlColumn rootColumn = left.GetRootColumn(); SqlColumn column2 = right.GetRootColumn(); this.map[rootColumn] = column2; this.map[column2] = rootColumn; } return; } case SqlNodeType.And: { SqlBinary binary = (SqlBinary)expr; this.CheckJoinCondition(binary.Left); this.CheckJoinCondition(binary.Right); return; } } } internal override SqlSource VisitJoin(SqlJoin join) { base.VisitJoin(join); if (join.Condition != null) { this.CheckJoinCondition(join.Condition); } return join; } internal override SqlSelect VisitSelect(SqlSelect select) { base.VisitSelect(select); if (select.Where != null) { this.CheckJoinCondition(select.Where); } return select; } internal override SqlExpression VisitSubSelect(SqlSubSelect ss) { return ss; } } private class SqlDuplicateColumnDeflator : SqlVisitor { // Fields private SqlDeflator.SqlColumnEqualizer equalizer = new SqlDeflator.SqlColumnEqualizer(); // Methods internal override SqlSelect VisitSelect(SqlSelect select) { select.From = this.VisitSource(select.From); select.Where = this.VisitExpression(select.Where); int num = 0; int count = select.GroupBy.Count; while (num < count) { select.GroupBy[num] = this.VisitExpression(select.GroupBy[num]); num++; } for (int i = select.GroupBy.Count - 1; i >= 0; i--) { for (int j = i - 1; j >= 0; j--) { if (SqlComparer.AreEqual(select.GroupBy[i], select.GroupBy[j])) { select.GroupBy.RemoveAt(i); break; } } } select.Having = this.VisitExpression(select.Having); int num5 = 0; int num6 = select.OrderBy.Count; while (num5 < num6) { select.OrderBy[num5].Expression = this.VisitExpression(select.OrderBy[num5].Expression); num5++; } if (select.OrderBy.Count > 0) { this.equalizer.BuildEqivalenceMap(select.From); for (int k = select.OrderBy.Count - 1; k >= 0; k--) { for (int m = k - 1; m >= 0; m--) { if (this.equalizer.AreEquivalent(select.OrderBy[k].Expression, select.OrderBy[m].Expression)) { select.OrderBy.RemoveAt(k); break; } } } } select.Top = this.VisitExpression(select.Top); select.Row = (SqlRow)this.Visit(select.Row); select.Selection = this.VisitExpression(select.Selection); return select; } } private class SqlTopSelectDeflator : SqlVisitor { // Methods private bool HasTrivialProjection(SqlSelect select) { foreach (SqlColumn column in select.Row.Columns) { if ((column.Expression != null) && (column.Expression.NodeType != SqlNodeType.ColumnRef)) { return false; } } return true; } private bool HasTrivialSource(SqlSource node) { SqlAlias alias = node as SqlAlias; if (alias == null) { return false; } return (alias.Node is SqlSelect); } private bool IsTrivialSelect(SqlSelect select) { if ((((select.OrderBy.Count != 0) || (select.GroupBy.Count != 0)) || ((select.Having != null) || (select.Top != null))) || (select.IsDistinct || (select.Where != null))) { return false; } return (this.HasTrivialSource(select.From) && this.HasTrivialProjection(select)); } internal override SqlSelect VisitSelect(SqlSelect select) { if (!this.IsTrivialSelect(select)) { return select; } SqlSelect node = (SqlSelect)((SqlAlias)select.From).Node; Dictionary<SqlColumn, SqlColumnRef> map = new Dictionary<SqlColumn, SqlColumnRef>(); foreach (SqlColumn column in select.Row.Columns) { SqlColumnRef expression; //if (column is SqlDynamicColumn) //{ // expression = new SqlColumnRef(column); //} //else //{ expression = (SqlColumnRef)column.Expression; //} map.Add(column, expression); if (!string.IsNullOrEmpty(column.Name)) { expression.Column.Name = column.Name; } } node.Selection = new ColumnMapper(map).VisitExpression(select.Selection); return node; } // Nested Types private class ColumnMapper : SqlVisitor { // Fields private Dictionary<SqlColumn, SqlColumnRef> map; // Methods internal ColumnMapper(Dictionary<SqlColumn, SqlColumnRef> map) { this.map = map; } internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { SqlColumnRef ref2; if (this.map.TryGetValue(cref.Column, out ref2)) { return ref2; } return cref; } } } private class SqlValueDeflator : SqlVisitor { // Fields private bool isTopLevel = true; private SelectionDeflator sDeflator = new SelectionDeflator(); // Methods internal SqlValueDeflator() { } internal override SqlSelect VisitSelect(SqlSelect select) { if (this.isTopLevel) { select.Selection = this.sDeflator.VisitExpression(select.Selection); } return select; } internal override SqlExpression VisitSubSelect(SqlSubSelect ss) { SqlExpression expression; bool isTopLevel = this.isTopLevel; try { expression = base.VisitSubSelect(ss); } finally { this.isTopLevel = isTopLevel; } return expression; } // Nested Types private class SelectionDeflator : SqlVisitor { // Methods private SqlValue GetLiteralValue(SqlExpression expr) { while ((expr != null) && (expr.NodeType == SqlNodeType.ColumnRef)) { expr = ((SqlColumnRef)expr).Column.Expression; } return (expr as SqlValue); } internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { SqlExpression literalValue = this.GetLiteralValue(cref); if (literalValue != null) { return literalValue; } return cref; } } } } }
using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using RestSharp; using NUnit.Framework; using HostMe.Sdk.Client; using HostMe.Sdk.Api; using HostMe.Sdk.Model; namespace HostMe.Sdk.Test { /// <summary> /// Class for testing AdminTableManagementApi /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the API endpoint. /// </remarks> [TestFixture] public class AdminTableManagementApiTests { private AdminTableManagementApi instance; /// <summary> /// Setup before each unit test /// </summary> [SetUp] public void Init() { instance = new AdminTableManagementApi(); } /// <summary> /// Clean up after each unit test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of AdminTableManagementApi /// </summary> [Test] public void InstanceTest() { Assert.IsInstanceOf<AdminTableManagementApi> (instance, "instance is a AdminTableManagementApi"); } /// <summary> /// Test CreateNewFloor /// </summary> [Test] public void CreateNewFloorTest() { // TODO: add unit test for the method 'CreateNewFloor' int? restaurantId = null; // TODO: replace null with proper value Floor floor = null; // TODO: replace null with proper value var response = instance.CreateNewFloor(restaurantId, floor); Assert.IsInstanceOf<Floor> (response, "response is Floor"); } /// <summary> /// Test DeleteFloor /// </summary> [Test] public void DeleteFloorTest() { // TODO: add unit test for the method 'DeleteFloor' int? restaurantId = null; // TODO: replace null with proper value string floorId = null; // TODO: replace null with proper value instance.DeleteFloor(restaurantId, floorId); } /// <summary> /// Test GetAllTableCombinations /// </summary> [Test] public void GetAllTableCombinationsTest() { // TODO: add unit test for the method 'GetAllTableCombinations' int? restaurantId = null; // TODO: replace null with proper value var response = instance.GetAllTableCombinations(restaurantId); Assert.IsInstanceOf<List<TableInfo>> (response, "response is List<TableInfo>"); } /// <summary> /// Test GetApprovedTableCombinations /// </summary> [Test] public void GetApprovedTableCombinationsTest() { // TODO: add unit test for the method 'GetApprovedTableCombinations' int? restaurantId = null; // TODO: replace null with proper value var response = instance.GetApprovedTableCombinations(restaurantId); Assert.IsInstanceOf<List<TableInfo>> (response, "response is List<TableInfo>"); } /// <summary> /// Test GetAvailableTables /// </summary> [Test] public void GetAvailableTablesTest() { // TODO: add unit test for the method 'GetAvailableTables' int? restaurantId = null; // TODO: replace null with proper value DateTimeOffset? date = null; // TODO: replace null with proper value int? partySize = null; // TODO: replace null with proper value string areas = null; // TODO: replace null with proper value var response = instance.GetAvailableTables(restaurantId, date, partySize, areas); Assert.IsInstanceOf<List<TableInfo>> (response, "response is List<TableInfo>"); } /// <summary> /// Test GetFloorDetails /// </summary> [Test] public void GetFloorDetailsTest() { // TODO: add unit test for the method 'GetFloorDetails' int? restaurantId = null; // TODO: replace null with proper value string floorId = null; // TODO: replace null with proper value var response = instance.GetFloorDetails(restaurantId, floorId); Assert.IsInstanceOf<Floor> (response, "response is Floor"); } /// <summary> /// Test GetRestaurantFloors /// </summary> [Test] public void GetRestaurantFloorsTest() { // TODO: add unit test for the method 'GetRestaurantFloors' int? restaurantId = null; // TODO: replace null with proper value var response = instance.GetRestaurantFloors(restaurantId); Assert.IsInstanceOf<List<FloorInfo>> (response, "response is List<FloorInfo>"); } /// <summary> /// Test GetTableMonitors /// </summary> [Test] public void GetTableMonitorsTest() { // TODO: add unit test for the method 'GetTableMonitors' int? restaurantId = null; // TODO: replace null with proper value double? tableTurnOver = null; // TODO: replace null with proper value DateTimeOffset? time = null; // TODO: replace null with proper value var response = instance.GetTableMonitors(restaurantId, tableTurnOver, time); Assert.IsInstanceOf<List<TableMonitor>> (response, "response is List<TableMonitor>"); } /// <summary> /// Test GetTableUsersList /// </summary> [Test] public void GetTableUsersListTest() { // TODO: add unit test for the method 'GetTableUsersList' int? restaurantId = null; // TODO: replace null with proper value int? partySize = null; // TODO: replace null with proper value DateTimeOffset? time = null; // TODO: replace null with proper value var response = instance.GetTableUsersList(restaurantId, partySize, time); Assert.IsInstanceOf<List<TableUser>> (response, "response is List<TableUser>"); } /// <summary> /// Test GetTables /// </summary> [Test] public void GetTablesTest() { // TODO: add unit test for the method 'GetTables' int? restaurantId = null; // TODO: replace null with proper value var response = instance.GetTables(restaurantId); Assert.IsInstanceOf<List<Table>> (response, "response is List<Table>"); } /// <summary> /// Test ReleaseTable /// </summary> [Test] public void ReleaseTableTest() { // TODO: add unit test for the method 'ReleaseTable' int? restaurantId = null; // TODO: replace null with proper value string tableNumber = null; // TODO: replace null with proper value var response = instance.ReleaseTable(restaurantId, tableNumber); Assert.IsInstanceOf<TableMonitor> (response, "response is TableMonitor"); } /// <summary> /// Test SeatPartyAtTable /// </summary> [Test] public void SeatPartyAtTableTest() { // TODO: add unit test for the method 'SeatPartyAtTable' int? restaurantId = null; // TODO: replace null with proper value string tableNumber = null; // TODO: replace null with proper value int? partySize = null; // TODO: replace null with proper value var response = instance.SeatPartyAtTable(restaurantId, tableNumber, partySize); Assert.IsInstanceOf<TableMonitor> (response, "response is TableMonitor"); } /// <summary> /// Test SetApprovedTableCombinations /// </summary> [Test] public void SetApprovedTableCombinationsTest() { // TODO: add unit test for the method 'SetApprovedTableCombinations' int? restaurantId = null; // TODO: replace null with proper value List<Table> combinations = null; // TODO: replace null with proper value instance.SetApprovedTableCombinations(restaurantId, combinations); } /// <summary> /// Test SetTableState /// </summary> [Test] public void SetTableStateTest() { // TODO: add unit test for the method 'SetTableState' int? restaurantId = null; // TODO: replace null with proper value string tableNumber = null; // TODO: replace null with proper value ChangeTableState stateContract = null; // TODO: replace null with proper value instance.SetTableState(restaurantId, tableNumber, stateContract); } /// <summary> /// Test UpdateFloor /// </summary> [Test] public void UpdateFloorTest() { // TODO: add unit test for the method 'UpdateFloor' int? restaurantId = null; // TODO: replace null with proper value string floorId = null; // TODO: replace null with proper value Floor floor = null; // TODO: replace null with proper value var response = instance.UpdateFloor(restaurantId, floorId, floor); Assert.IsInstanceOf<Object> (response, "response is Object"); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Orleans.Internal; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans.CodeGeneration { /// <summary> /// Functionality for invoking calls on a generic instance method. /// </summary> /// <remarks> /// Each instance of this class can invoke calls on one generic method. /// </remarks> public class GenericMethodInvoker : IEqualityComparer<object[]> { private static readonly ConcurrentDictionary<Type, MethodInfo> BoxMethods = new ConcurrentDictionary<Type, MethodInfo>(); private static readonly Func<Type, MethodInfo> CreateBoxMethod = GetTaskConversionMethod; private static readonly MethodInfo GenericMethodInvokerDelegateMethodInfo = TypeUtils.Method((GenericMethodInvokerDelegate del) => del.Invoke(null, null)); private static readonly ILFieldBuilder FieldBuilder = new ILFieldBuilder(); private readonly Type grainInterfaceType; private readonly string methodName; private readonly int typeParameterCount; private readonly ConcurrentDictionary<object[], GenericMethodInvokerDelegate> invokers; private readonly Func<object[], GenericMethodInvokerDelegate> createInvoker; /// <summary> /// Invoke the generic method described by this instance on the provided <paramref name="grain"/>. /// </summary> /// <param name="grain">The grain.</param> /// <param name="arguments">The arguments, including the method's type parameters.</param> /// <returns>The method result.</returns> private delegate Task<object> GenericMethodInvokerDelegate(IAddressable grain, object[] arguments); /// <summary> /// Initializes a new instance of the <see cref="GenericMethodInvoker"/> class. /// </summary> /// <param name="grainInterfaceType">The grain interface type which the method exists on.</param> /// <param name="methodName">The name of the method.</param> /// <param name="typeParameterCount">The number of type parameters which the method has.</param> public GenericMethodInvoker(Type grainInterfaceType, string methodName, int typeParameterCount) { this.grainInterfaceType = grainInterfaceType; this.methodName = methodName; this.typeParameterCount = typeParameterCount; this.invokers = new ConcurrentDictionary<object[], GenericMethodInvokerDelegate>(this); this.createInvoker = this.CreateInvoker; } /// <summary> /// Invoke the defined method on the provided <paramref name="grain"/> instance with the given <paramref name="arguments"/>. /// </summary> /// <param name="grain">The grain.</param> /// <param name="arguments">The arguments to the method with the type parameters first, followed by the method parameters types, and finally the parameter values..</param> /// <returns>The invocation result.</returns> public Task<object> Invoke(IAddressable grain, object[] arguments) { var argc = (arguments.Length - typeParameterCount) / 2; // As this is on a hot path, avoid allocating (LINQ) as much as possible var argv = arguments.AsSpan(); // generic parameter type(s) + argument type(s) -- this is our invokers' cache-key var types = argv.Slice(0, typeParameterCount + argc); // argument values to be passed var argValues = argv.Slice(typeParameterCount + argc, argc); var invoker = this.invokers.GetOrAdd(types.ToArray(), this.createInvoker); return invoker(grain, argValues.ToArray()); } /// <summary> /// Creates an invoker delegate for the type arguments specified in <paramref name="arguments"/>. /// </summary> /// <param name="arguments">The method arguments, including one or more type parameter(s) at the head of the array..</param> /// <returns>A new invoker delegate.</returns> private GenericMethodInvokerDelegate CreateInvoker(object[] arguments) { // obtain the generic type parameter(s) var typeParameters = arguments.Take(this.typeParameterCount).Cast<Type>().ToArray(); // obtain the method argument type(s) var parameterTypes = arguments .Skip(typeParameterCount) .Cast<Type>() .ToArray(); // get open generic method for this arity/parameter combination var openGenericMethodInfo = GetMethod( grainInterfaceType, methodName, typeParameters, parameterTypes); // close the generic type var concreteMethod = openGenericMethodInfo.MakeGenericMethod(typeParameters); // Next, create a delegate which will call the method on the grain, pushing each of the arguments, var il = new ILDelegateBuilder<GenericMethodInvokerDelegate>( FieldBuilder, $"GenericMethodInvoker_{this.grainInterfaceType}_{concreteMethod.Name}", GenericMethodInvokerDelegateMethodInfo); // Load the grain and cast it to the type the concrete method is declared on. // Eg: cast from IAddressable to IGrainWithGenericMethod. il.LoadArgument(0); il.CastOrUnbox(this.grainInterfaceType); // Load each of the method parameters from the argument array, skipping the type parameters. var methodParameters = concreteMethod.GetParameters(); for (var i = 0; i < methodParameters.Length; i++) { il.LoadArgument(1); // Load the argument array. // load the particular argument. il.LoadConstant(i); il.LoadReferenceElement(); // Cast the argument from 'object' to the type expected by the concrete method. il.CastOrUnbox(methodParameters[i].ParameterType); } // Call the concrete method. il.Call(concreteMethod); // If the result type is Task or Task<T>, convert it to Task<object>. var returnType = concreteMethod.ReturnType; if (returnType != typeof(Task<object>)) { var boxMethod = BoxMethods.GetOrAdd(returnType, CreateBoxMethod); il.Call(boxMethod); } // Return the resulting Task<object>. il.Return(); return il.CreateDelegate(); } /// <summary> /// Returns a suitable <see cref="MethodInfo"/> for a method which will convert an argument of type <paramref name="taskType"/> /// into <see cref="Task{Object}"/>. /// </summary> /// <param name="taskType">The type to convert.</param> /// <returns>A suitable conversion method.</returns> private static MethodInfo GetTaskConversionMethod(Type taskType) { if (taskType == typeof(Task)) return TypeUtils.Method((Task task) => task.ToUntypedTask()); if (taskType == typeof(Task<object>)) return TypeUtils.Method((Task<object> task) => task.ToUntypedTask()); if (taskType == typeof(void)) return TypeUtils.Property(() => Task.CompletedTask).GetMethod; if (taskType.GetGenericTypeDefinition() != typeof(Task<>)) throw new ArgumentException($"Unsupported return type {taskType}."); var innerType = taskType.GenericTypeArguments[0]; var methods = typeof(OrleansTaskExtentions).GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (var method in methods) { if (method.Name != nameof(OrleansTaskExtentions.ToUntypedTask) || !method.ContainsGenericParameters) continue; return method.MakeGenericMethod(innerType); } throw new ArgumentException($"Could not find conversion method for type {taskType}"); } /// <summary> /// Performs equality comparison for the purpose of comparing type parameters only. /// </summary> /// <param name="x">One argument list.</param> /// <param name="y">The other argument list.</param> /// <returns><see langword="true"/> if the type parameters in the respective arguments are equal, <see langword="false"/> otherwise.</returns> bool IEqualityComparer<object[]>.Equals(object[] x, object[] y) { if (ReferenceEquals(x, y)) return true; if (ReferenceEquals(x, null)) return false; if (ReferenceEquals(null, y)) return false; return x.SequenceEqual(y); } /// <summary> /// Returns a hash code for the provided argument list. /// </summary> /// <param name="obj">The argument list.</param> /// <returns>A hash code.</returns> int IEqualityComparer<object[]>.GetHashCode(object[] obj) { if (obj.Length == 0) return 0; unchecked { var result = 0; foreach (var type in obj) { result = (result * 367) ^ type.GetHashCode(); } return result; } } /// <summary> /// Returns the <see cref="MethodInfo"/> for the method on <paramref name="declaringType"/> with the provided name /// and number of generic type parameters. /// </summary> /// <param name="declaringType">The type which the method is declared on.</param> /// <param name="methodName">The method name.</param> /// <param name="typeParameters">The generic type parameters to use.</param> /// <param name="parameterTypes"></param> /// <returns>The identified method.</returns> private static MethodInfo GetMethod( Type declaringType, string methodName, Type[] typeParameters, Type[] parameterTypes ) { MethodInfo methodInfo = null; var typeParameterCount = typeParameters.Length; bool skipMethod = false; var methods = declaringType.GetMethods(BindingFlags.Instance | BindingFlags.Public); foreach (var openMethod in methods) { if (!openMethod.IsGenericMethodDefinition) continue; // same name? if (!string.Equals(openMethod.Name, methodName, StringComparison.Ordinal)) continue; // same type parameter count? if (openMethod.GetGenericArguments().Length != typeParameterCount) continue; // close the definition MethodInfo closedMethod = openMethod.MakeGenericMethod(typeParameters); // obtain list of closed parameters (no generic placeholders any more) var parameterInfos = closedMethod.GetParameters(); // same number of params? if (parameterInfos.Length == parameterTypes.Length) { for (int i = 0; i < parameterInfos.Length; ++i) { // validate compatibility - assignable/covariant array etc. if (!parameterInfos[i].ParameterType.IsAssignableFrom(parameterTypes[i])) { skipMethod = true; break; } } if (skipMethod) { skipMethod = false; continue; } // found compatible overload; return generic definition, not closed method methodInfo = openMethod; break; } } // next method if (methodInfo is null) { var signature = string.Join(",", parameterTypes.Select(t => t.Name)); var typeParams = string.Join(",", typeParameters.Select(t => t.Name)); throw new ArgumentException( $"Could not find exact match for generic method {declaringType}.{methodName}" + $"<{typeParams}>({signature})."); } return methodInfo; } } }
// 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.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Threading; namespace System.Linq.Expressions.Compiler { /// <summary> /// Dynamic Language Runtime Compiler. /// This part compiles lambdas. /// </summary> internal partial class LambdaCompiler { private static int s_counter; internal void EmitConstantArray<T>(T[] array) { // Emit as runtime constant if possible // if not, emit into IL if (_method is DynamicMethod) { EmitConstant(array, typeof(T[])); } else if (_typeBuilder != null) { // store into field in our type builder, we will initialize // the value only once. FieldBuilder fb = CreateStaticField("ConstantArray", typeof(T[])); Label l = _ilg.DefineLabel(); _ilg.Emit(OpCodes.Ldsfld, fb); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Bne_Un, l); _ilg.EmitArray(array); _ilg.Emit(OpCodes.Stsfld, fb); _ilg.MarkLabel(l); _ilg.Emit(OpCodes.Ldsfld, fb); } else { _ilg.EmitArray(array); } } private void EmitClosureCreation(LambdaCompiler inner) { bool closure = inner._scope.NeedsClosure; bool boundConstants = inner._boundConstants.Count > 0; if (!closure && !boundConstants) { _ilg.EmitNull(); return; } // new Closure(constantPool, currentHoistedLocals) if (boundConstants) { _boundConstants.EmitConstant(this, inner._boundConstants.ToArray(), typeof(object[])); } else { _ilg.EmitNull(); } if (closure) { _scope.EmitGet(_scope.NearestHoistedLocals.SelfVariable); } else { _ilg.EmitNull(); } _ilg.EmitNew(typeof(Closure).GetConstructor(new Type[] { typeof(object[]), typeof(object[]) })); } /// <summary> /// Emits code which creates new instance of the delegateType delegate. /// /// Since the delegate is getting closed over the "Closure" argument, this /// cannot be used with virtual/instance methods (inner must be static method) /// </summary> private void EmitDelegateConstruction(LambdaCompiler inner) { Type delegateType = inner._lambda.Type; DynamicMethod dynamicMethod = inner._method as DynamicMethod; if (dynamicMethod != null) { // Emit MethodInfo.CreateDelegate instead because DynamicMethod is not in Windows 8 Profile _boundConstants.EmitConstant(this, dynamicMethod, typeof(MethodInfo)); _ilg.EmitType(delegateType); EmitClosureCreation(inner); _ilg.Emit(OpCodes.Callvirt, typeof(MethodInfo).GetMethod("CreateDelegate", new Type[] { typeof(Type), typeof(object) })); _ilg.Emit(OpCodes.Castclass, delegateType); } else { // new DelegateType(closure) EmitClosureCreation(inner); _ilg.Emit(OpCodes.Ldftn, (MethodInfo)inner._method); _ilg.Emit(OpCodes.Newobj, (ConstructorInfo)(delegateType.GetMember(".ctor")[0])); } } /// <summary> /// Emits a delegate to the method generated for the LambdaExpression. /// May end up creating a wrapper to match the requested delegate type. /// </summary> /// <param name="lambda">Lambda for which to generate a delegate</param> /// private void EmitDelegateConstruction(LambdaExpression lambda) { // 1. Create the new compiler LambdaCompiler impl; if (_method is DynamicMethod) { impl = new LambdaCompiler(_tree, lambda); } else { // When the lambda does not have a name or the name is empty, generate a unique name for it. string name = String.IsNullOrEmpty(lambda.Name) ? GetUniqueMethodName() : lambda.Name; MethodBuilder mb = _typeBuilder.DefineMethod(name, MethodAttributes.Private | MethodAttributes.Static); impl = new LambdaCompiler(_tree, lambda, mb); } // 2. emit the lambda // Since additional ILs are always emitted after the lambda's body, should not emit with tail call optimization. impl.EmitLambdaBody(_scope, false, CompilationFlags.EmitAsNoTail); // 3. emit the delegate creation in the outer lambda EmitDelegateConstruction(impl); } private static Type[] GetParameterTypes(LambdaExpression lambda) { return lambda.Parameters.Map(p => p.IsByRef ? p.Type.MakeByRefType() : p.Type); } private static string GetUniqueMethodName() { return "<ExpressionCompilerImplementationDetails>{" + Interlocked.Increment(ref s_counter) + "}lambda_method"; } private void EmitLambdaBody() { // The lambda body is the "last" expression of the lambda CompilationFlags tailCallFlag = _lambda.TailCall ? CompilationFlags.EmitAsTail : CompilationFlags.EmitAsNoTail; EmitLambdaBody(null, false, tailCallFlag); } /// <summary> /// Emits the lambda body. If inlined, the parameters should already be /// pushed onto the IL stack. /// </summary> /// <param name="parent">The parent scope.</param> /// <param name="inlined">true if the lambda is inlined; false otherwise.</param> /// <param name="flags"> /// The emum to specify if the lambda is compiled with the tail call optimization. /// </param> private void EmitLambdaBody(CompilerScope parent, bool inlined, CompilationFlags flags) { _scope.Enter(this, parent); if (inlined) { // The arguments were already pushed onto the IL stack. // Store them into locals, popping in reverse order. // // If any arguments were ByRef, the address is on the stack and // we'll be storing it into the variable, which has a ref type. for (int i = _lambda.Parameters.Count - 1; i >= 0; i--) { _scope.EmitSet(_lambda.Parameters[i]); } } // Need to emit the expression start for the lambda body flags = UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart); if (_lambda.ReturnType == typeof(void)) { EmitExpressionAsVoid(_lambda.Body, flags); } else { EmitExpression(_lambda.Body, flags); } // Return must be the last instruction in a CLI method. // But if we're inlining the lambda, we want to leave the return // value on the IL stack. if (!inlined) { _ilg.Emit(OpCodes.Ret); } _scope.Exit(); // Validate labels Debug.Assert(_labelBlock.Parent == null && _labelBlock.Kind == LabelScopeKind.Lambda); foreach (LabelInfo label in _labelInfo.Values) { label.ValidateFinish(); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace Simple.OData.Client { /// <summary> /// Provides access to OData operations. /// </summary> public partial class ODataClient : IODataClient { private readonly ODataClientSettings _settings; private readonly Session _session; private readonly RequestRunner _requestRunner; private readonly Lazy<IBatchWriter> _lazyBatchWriter; private readonly ConcurrentDictionary<object, IDictionary<string, object>> _batchEntries; private readonly ODataResponse _batchResponse; /// <summary> /// Initializes a new instance of the <see cref="ODataClient"/> class. /// </summary> /// <param name="baseUri">The OData service URL.</param> /// <remarks> /// This constructor overload is obsolete. Use <see cref="ODataClient(Uri)"/> constructor overload./> /// </remarks> public ODataClient(string baseUri) : this(new ODataClientSettings {BaseUri = new Uri(baseUri)}) { } /// <summary> /// Initializes a new instance of the <see cref="ODataClient"/> class. /// </summary> /// <param name="baseUri">The OData service URL.</param> public ODataClient(Uri baseUri) : this(new ODataClientSettings { BaseUri = baseUri }) { } /// <summary> /// Initializes a new instance of the <see cref="ODataClient"/> class. /// </summary> /// <param name="settings">The OData client settings.</param> public ODataClient(ODataClientSettings settings) { _settings = settings; _session = Session.FromSettings(_settings); _requestRunner = new RequestRunner(_session); } internal ODataClient(ODataClientSettings settings, ConcurrentDictionary<object, IDictionary<string, object>> batchEntries) : this(settings) { if (batchEntries != null) { _batchEntries = batchEntries; _lazyBatchWriter = new Lazy<IBatchWriter>(() => _session.Adapter.GetBatchWriter(_batchEntries)); } } internal ODataClient(ODataClient client, ConcurrentDictionary<object, IDictionary<string, object>> batchEntries) { _settings = client._settings; _session = client.Session; _requestRunner = client._requestRunner; if (batchEntries != null) { _batchEntries = batchEntries; _lazyBatchWriter = new Lazy<IBatchWriter>(() => _session.Adapter.GetBatchWriter(_batchEntries)); } } internal ODataClient(ODataClient client, ODataResponse batchResponse) { _settings = client._settings; _session = client.Session; _batchResponse = batchResponse; } internal Session Session => _session; internal ODataResponse BatchResponse => _batchResponse; internal bool IsBatchRequest => _lazyBatchWriter != null; internal bool IsBatchResponse => _batchResponse != null; internal ConcurrentDictionary<object, IDictionary<string, object>> BatchEntries => _batchEntries; internal Lazy<IBatchWriter> BatchWriter => _lazyBatchWriter; /// <summary> /// Parses the OData service metadata string. /// </summary> /// <typeparam name="T">OData protocol specific metadata interface</typeparam> /// <param name="metadataString">The metadata string.</param> /// <returns> /// The service metadata. /// </returns> public static T ParseMetadataString<T>(string metadataString) { var session = Session.FromMetadata(new Uri("http://localhost/" + metadataString.GetHashCode() + "$metadata"), metadataString); return (T)session.Adapter.Model; } /// <summary> /// Clears service metadata cache. /// </summary> public static void ClearMetadataCache() { EdmMetadataCache.Clear(); } /// <summary> /// Returns an instance of a fluent OData client for the specified collection. /// </summary> /// <param name="collectionName">Name of the collection.</param> /// <returns> /// The fluent OData client instance. /// </returns> public IBoundClient<IDictionary<string, object>> For(string collectionName) { return GetBoundClient().For(collectionName); } /// <summary> /// Returns an instance of a fluent OData client for the specified collection. /// </summary> /// <param name="expression">Collection expression.</param> /// <returns> /// The fluent OData client instance. /// </returns> public IBoundClient<ODataEntry> For(ODataExpression expression) { return new BoundClient<ODataEntry>(this, _session).For(expression); } /// <summary> /// Returns an instance of a fluent OData client for the specified collection. /// </summary> /// <typeparam name="T">The entity type.</typeparam> /// <param name="collectionName">Name of the collection.</param> /// <returns> /// The fluent OData client instance. /// </returns> public IBoundClient<T> For<T>(string collectionName = null) where T : class { return new BoundClient<T>(this, _session).For(collectionName); } /// <summary> /// Returns an instance of a fluent OData client for unbound operations (functions and actions). /// </summary> /// <returns>The fluent OData client instance.</returns> public IUnboundClient<object> Unbound() { return GetUnboundClient<object>(); } /// <summary> /// Returns an instance of a fluent OData client for unbound operations (functions and actions). /// </summary> /// <returns>The fluent OData client instance.</returns> public IUnboundClient<T> Unbound<T>() where T : class { return GetUnboundClient<T>(); } private BoundClient<IDictionary<string, object>> GetBoundClient() { return new BoundClient<IDictionary<string, object>>(this, _session); } private UnboundClient<T> GetUnboundClient<T>() where T : class { return new UnboundClient<T>(this, _session); } /// <summary> /// Allows callers to manipulate the request headers in between request executions. /// Useful for retrieval of x-csrf-tokens when you want to update the request header /// with the retrieved token on subsequent requests. /// <para> /// Note that this overrides any current <see cref="ODataClientSettings.BeforeRequest"/> method. /// </para> /// </summary> /// <param name="headers">The list of headers to update.</param> public void UpdateRequestHeaders(Dictionary<string, IEnumerable<string>> headers) { _settings.BeforeRequest += (request) => { foreach (var header in headers) { if (request.Headers.Contains(header.Key)) { request.Headers.Remove(header.Key); } request.Headers.Add(header.Key, header.Value); } }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.ApplicationModel.Background; using Windows.ApplicationModel.Store; using Windows.Storage; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; using AppStudio.Common; using AppStudio.Common.Services; using AppStudio.Common.Navigation; using ContosoLtd.Services; #if WINDOWS_APP using Windows.System; using Windows.UI.Core; using Windows.UI.ApplicationSettings; using ContosoLtd.AppFlyouts; #endif #if WINDOWS_PHONE_APP using Windows.Phone.UI.Input; #endif namespace ContosoLtd { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Windows.UI.Xaml.Application { private Guid APP_ID = new Guid("dd1bf21f-bb58-4f15-977e-4adbf1889a3b"); public const string APP_NAME = "Contoso Ltd"; #if WINDOWS_PHONE_APP private TransitionCollection transitions; #endif /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; #if WINDOWS_PHONE_APP Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.ContextInitializers .Add(new Telemetry.TelemetryInitializer("Windows Phone 8.1")); #else Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.ContextInitializers .Add(new Telemetry.TelemetryInitializer("Windows 8.1")); #endif } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif GetAppData(); UpdateAppTiles(); Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } NavigationService.Initialize(this.GetType(), rootFrame); if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; #endif #if WINDOWS_PHONE_APP Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed; #else //// Keyboard and mouse navigation only apply when occupying the entire window //if (Page.ActualHeight == Window.Current.Bounds.Height && // Page.ActualWidth == Window.Current.Bounds.Width) //{ // Listen to the window directly so focus isn't required Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += CoreDispatcher_AcceleratorKeyActivated; Window.Current.CoreWindow.PointerPressed += this.CoreWindow_PointerPressed; //} #endif // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); } #if WINDOWS_PHONE_APP /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } #endif private void GetAppData() { #if WINDOWS_PHONE_APP string deviceType = LocalSettingNames.PhoneValue; #else string deviceType = LocalSettingNames.WindowsValue; #endif ApplicationData.Current.LocalSettings.Values[LocalSettingNames.DeviceTypeSetting] = deviceType; ApplicationData.Current.LocalSettings.Values[LocalSettingNames.StoreIdSetting] = ValidateStoreId(); } private Guid ValidateStoreId() { try { Guid storeId = CurrentApp.AppId; if (storeId != Guid.Empty && storeId != APP_ID) { return storeId; } return Guid.Empty; } catch (Exception) { return Guid.Empty; } } private void UpdateAppTiles() { var init = ApplicationData.Current.LocalSettings.Values[LocalSettingNames.TilesInitialized]; if (init == null || (init is bool && !(bool)init)) { Dictionary<string, string> tiles = new Dictionary<string, string>(); tiles.Add("2f829599e0301ff8", "DataImages/Tile1.jpg"); tiles.Add("2f829599e0301ff9", "DataImages/Tile2.jpg"); tiles.Add("2f829599e0301ffa", "DataImages/Tile3.jpg"); tiles.Add("2f829599e0301ffb", "DataImages/Tile4.jpg"); TileServices.CreateCycleTile(tiles); ApplicationData.Current.LocalSettings.Values[LocalSettingNames.TilesInitialized] = true; } } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity deferral.Complete(); } #if WINDOWS_APP protected override void OnWindowCreated(WindowCreatedEventArgs args) { SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested; base.OnWindowCreated(args); } private void OnCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args) { args.Request.ApplicationCommands.Add(new SettingsCommand("Privacy", "Privacy", (handler) => ShowPrivacySettingFlyout())); args.Request.ApplicationCommands.Add(new SettingsCommand("About", "About", (handler) => ShowAboutSettingFlyout())); } private void ShowPrivacySettingFlyout() { var flyout = new PrivacyFlyout(); flyout.Show(); } private void ShowAboutSettingFlyout() { var flyout = new AboutFlyout(); flyout.Show(); } #endif #if WINDOWS_PHONE_APP /// <summary> /// Invoked when the hardware back button is pressed. For Windows Phone only. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e) { if (NavigationService.CanGoBack()) { e.Handled = true; NavigationService.GoBack(); } } #else /// <summary> /// Invoked on every keystroke, including system keys such as Alt key combinations, when /// this page is active and occupies the entire window. Used to detect keyboard navigation /// between pages even when the page itself doesn't have focus. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs e) { var virtualKey = e.VirtualKey; // Only investigate further when Left, Right, or the dedicated Previous or Next keys // are pressed if ((e.EventType == CoreAcceleratorKeyEventType.SystemKeyDown || e.EventType == CoreAcceleratorKeyEventType.KeyDown) && (virtualKey == VirtualKey.Left || virtualKey == VirtualKey.Right || (int)virtualKey == 166 || (int)virtualKey == 167)) { var coreWindow = Window.Current.CoreWindow; var downState = CoreVirtualKeyStates.Down; bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState; bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState; bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState; bool noModifiers = !menuKey && !controlKey && !shiftKey; bool onlyAlt = menuKey && !controlKey && !shiftKey; if (((int)virtualKey == 166 && noModifiers) || (virtualKey == VirtualKey.Left && onlyAlt)) { // When the previous key or Alt+Left are pressed navigate back e.Handled = true; NavigationService.GoBack(); } else if (((int)virtualKey == 167 && noModifiers) || (virtualKey == VirtualKey.Right && onlyAlt)) { // When the next key or Alt+Right are pressed navigate forward e.Handled = true; NavigationService.GoForward(); } } } /// <summary> /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this /// page is active and occupies the entire window. Used to detect browser-style next and /// previous mouse button clicks to navigate between pages. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private void CoreWindow_PointerPressed(CoreWindow sender, PointerEventArgs e) { var properties = e.CurrentPoint.Properties; // Ignore button chords with the left, right, and middle buttons if (properties.IsLeftButtonPressed || properties.IsRightButtonPressed || properties.IsMiddleButtonPressed) return; // If back or foward are pressed (but not both) navigate appropriately bool backPressed = properties.IsXButton1Pressed; bool forwardPressed = properties.IsXButton2Pressed; if (backPressed ^ forwardPressed) { e.Handled = true; if (backPressed) NavigationService.GoBack(); if (forwardPressed) NavigationService.GoForward(); } } #endif } }
namespace Reporting.RdlDesign { partial class StaticSeriesCtl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.lbDataSeries = new System.Windows.Forms.ListBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.chkShowLabels = new System.Windows.Forms.CheckBox(); this.txtSeriesName = new System.Windows.Forms.TextBox(); this.txtLabelValue = new System.Windows.Forms.TextBox(); this.btnAdd = new System.Windows.Forms.Button(); this.btnDel = new System.Windows.Forms.Button(); this.btnLabelValue = new System.Windows.Forms.Button(); this.btnDataValue = new System.Windows.Forms.Button(); this.btnSeriesName = new System.Windows.Forms.Button(); this.txtDataValue = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.cbPlotType = new System.Windows.Forms.ComboBox(); this.chkLeft = new System.Windows.Forms.RadioButton(); this.chkRight = new System.Windows.Forms.RadioButton(); this.label5 = new System.Windows.Forms.Label(); this.btnUp = new System.Windows.Forms.Button(); this.btnDown = new System.Windows.Forms.Button(); this.txtX = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.btnX = new System.Windows.Forms.Button(); this.chkMarker = new System.Windows.Forms.CheckBox(); this.label7 = new System.Windows.Forms.Label(); this.cbLine = new System.Windows.Forms.ComboBox(); this.label8 = new System.Windows.Forms.Label(); this.colorPicker1 = new Reporting.RdlDesign.ColorPicker(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(62, 13); this.label1.TabIndex = 0; this.label1.Text = "Data Series"; // // lbDataSeries // this.lbDataSeries.FormattingEnabled = true; this.lbDataSeries.Location = new System.Drawing.Point(16, 28); this.lbDataSeries.Name = "lbDataSeries"; this.lbDataSeries.Size = new System.Drawing.Size(120, 134); this.lbDataSeries.TabIndex = 1; this.lbDataSeries.SelectedIndexChanged += new System.EventHandler(this.lbDataSeries_SelectedIndexChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(139, 12); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(67, 13); this.label2.TabIndex = 2; this.label2.Text = "Series Name"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(142, 51); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(60, 13); this.label3.TabIndex = 3; this.label3.Text = "Data Value"; // // chkShowLabels // this.chkShowLabels.AutoSize = true; this.chkShowLabels.Location = new System.Drawing.Point(145, 132); this.chkShowLabels.Name = "chkShowLabels"; this.chkShowLabels.Size = new System.Drawing.Size(93, 17); this.chkShowLabels.TabIndex = 4; this.chkShowLabels.Text = "Show Labels?"; this.chkShowLabels.UseVisualStyleBackColor = true; this.chkShowLabels.CheckedChanged += new System.EventHandler(this.chkShowLabels_CheckedChanged); // // txtSeriesName // this.txtSeriesName.Location = new System.Drawing.Point(142, 28); this.txtSeriesName.Name = "txtSeriesName"; this.txtSeriesName.Size = new System.Drawing.Size(184, 20); this.txtSeriesName.TabIndex = 5; this.txtSeriesName.TextChanged += new System.EventHandler(this.txtSeriesName_TextChanged); // // txtLabelValue // this.txtLabelValue.Enabled = false; this.txtLabelValue.Location = new System.Drawing.Point(142, 152); this.txtLabelValue.Name = "txtLabelValue"; this.txtLabelValue.Size = new System.Drawing.Size(184, 20); this.txtLabelValue.TabIndex = 7; this.txtLabelValue.TextChanged += new System.EventHandler(this.txtLabelValue_TextChanged); // // btnAdd // this.btnAdd.Location = new System.Drawing.Point(86, 168); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(50, 31); this.btnAdd.TabIndex = 8; this.btnAdd.Text = "New"; this.btnAdd.UseVisualStyleBackColor = true; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnDel // this.btnDel.Location = new System.Drawing.Point(16, 168); this.btnDel.Name = "btnDel"; this.btnDel.Size = new System.Drawing.Size(50, 31); this.btnDel.TabIndex = 9; this.btnDel.Text = "Delete"; this.btnDel.UseVisualStyleBackColor = true; this.btnDel.Click += new System.EventHandler(this.btnDel_Click); // // btnLabelValue // this.btnLabelValue.Enabled = false; this.btnLabelValue.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic)))); this.btnLabelValue.Location = new System.Drawing.Point(332, 152); this.btnLabelValue.Name = "btnLabelValue"; this.btnLabelValue.Size = new System.Drawing.Size(24, 21); this.btnLabelValue.TabIndex = 21; this.btnLabelValue.Text = "fx"; this.btnLabelValue.UseVisualStyleBackColor = true; this.btnLabelValue.Click += new System.EventHandler(this.FunctionButtonClick); // // btnDataValue // this.btnDataValue.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic)))); this.btnDataValue.Location = new System.Drawing.Point(332, 67); this.btnDataValue.Name = "btnDataValue"; this.btnDataValue.Size = new System.Drawing.Size(24, 21); this.btnDataValue.TabIndex = 22; this.btnDataValue.Text = "fx"; this.btnDataValue.UseVisualStyleBackColor = true; this.btnDataValue.Click += new System.EventHandler(this.FunctionButtonClick); // // btnSeriesName // this.btnSeriesName.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic)))); this.btnSeriesName.Location = new System.Drawing.Point(332, 28); this.btnSeriesName.Name = "btnSeriesName"; this.btnSeriesName.Size = new System.Drawing.Size(24, 21); this.btnSeriesName.TabIndex = 23; this.btnSeriesName.Text = "fx"; this.btnSeriesName.UseVisualStyleBackColor = true; this.btnSeriesName.Click += new System.EventHandler(this.FunctionButtonClick); // // txtDataValue // this.txtDataValue.Location = new System.Drawing.Point(142, 67); this.txtDataValue.Name = "txtDataValue"; this.txtDataValue.Size = new System.Drawing.Size(184, 20); this.txtDataValue.TabIndex = 24; this.txtDataValue.TextChanged += new System.EventHandler(this.txtDataValue_TextChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(142, 175); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(84, 13); this.label4.TabIndex = 25; this.label4.Text = "Series Plot Type"; // // cbPlotType // this.cbPlotType.FormattingEnabled = true; this.cbPlotType.Items.AddRange(new object[] { "Auto", "Line"}); this.cbPlotType.Location = new System.Drawing.Point(142, 191); this.cbPlotType.Name = "cbPlotType"; this.cbPlotType.Size = new System.Drawing.Size(134, 21); this.cbPlotType.TabIndex = 26; this.cbPlotType.SelectedIndexChanged += new System.EventHandler(this.cbPlotType_SelectedIndexChanged); // // chkLeft // this.chkLeft.AutoSize = true; this.chkLeft.Location = new System.Drawing.Point(246, 229); this.chkLeft.Name = "chkLeft"; this.chkLeft.Size = new System.Drawing.Size(43, 17); this.chkLeft.TabIndex = 27; this.chkLeft.TabStop = true; this.chkLeft.Text = "Left"; this.chkLeft.UseVisualStyleBackColor = true; this.chkLeft.CheckedChanged += new System.EventHandler(this.chkLeft_CheckedChanged); // // chkRight // this.chkRight.AutoSize = true; this.chkRight.Location = new System.Drawing.Point(309, 229); this.chkRight.Name = "chkRight"; this.chkRight.Size = new System.Drawing.Size(50, 17); this.chkRight.TabIndex = 28; this.chkRight.TabStop = true; this.chkRight.Text = "Right"; this.chkRight.UseVisualStyleBackColor = true; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(280, 215); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(36, 13); this.label5.TabIndex = 29; this.label5.Text = "Y Axis"; // // btnUp // this.btnUp.Location = new System.Drawing.Point(0, 28); this.btnUp.Name = "btnUp"; this.btnUp.Size = new System.Drawing.Size(17, 23); this.btnUp.TabIndex = 30; this.btnUp.Text = "^"; this.btnUp.UseVisualStyleBackColor = true; this.btnUp.Click += new System.EventHandler(this.btnUp_Click); // // btnDown // this.btnDown.Location = new System.Drawing.Point(0, 139); this.btnDown.Name = "btnDown"; this.btnDown.Size = new System.Drawing.Size(17, 23); this.btnDown.TabIndex = 31; this.btnDown.Text = "v"; this.btnDown.UseVisualStyleBackColor = true; this.btnDown.Click += new System.EventHandler(this.btnDown_Click); // // txtX // this.txtX.Location = new System.Drawing.Point(142, 106); this.txtX.Name = "txtX"; this.txtX.Size = new System.Drawing.Size(184, 20); this.txtX.TabIndex = 32; this.txtX.TextChanged += new System.EventHandler(this.txtX_TextChanged); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(142, 90); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(106, 13); this.label6.TabIndex = 33; this.label6.Text = "X Value(Scatter only)"; // // btnX // this.btnX.Enabled = false; this.btnX.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic)))); this.btnX.Location = new System.Drawing.Point(332, 106); this.btnX.Name = "btnX"; this.btnX.Size = new System.Drawing.Size(24, 21); this.btnX.TabIndex = 34; this.btnX.Text = "fx"; this.btnX.UseVisualStyleBackColor = true; this.btnX.Click += new System.EventHandler(this.FunctionButtonClick); // // chkMarker // this.chkMarker.AutoSize = true; this.chkMarker.Location = new System.Drawing.Point(244, 132); this.chkMarker.Name = "chkMarker"; this.chkMarker.Size = new System.Drawing.Size(100, 17); this.chkMarker.TabIndex = 35; this.chkMarker.Text = "Show Markers?"; this.chkMarker.UseVisualStyleBackColor = true; this.chkMarker.CheckedChanged += new System.EventHandler(this.chkMarker_CheckedChanged); // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(286, 175); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(58, 13); this.label7.TabIndex = 36; this.label7.Text = "Line Width"; // // cbLine // this.cbLine.FormattingEnabled = true; this.cbLine.Items.AddRange(new object[] { "Small", "Regular", "Large", "Extra Large", "Super Size"}); this.cbLine.Location = new System.Drawing.Point(283, 191); this.cbLine.Name = "cbLine"; this.cbLine.Size = new System.Drawing.Size(75, 21); this.cbLine.TabIndex = 37; this.cbLine.SelectedIndexChanged += new System.EventHandler(this.cbLine_SelectedIndexChanged); // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(142, 215); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(69, 13); this.label8.TabIndex = 39; this.label8.Text = "Series Colour"; // // colorPicker1 // this.colorPicker1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.colorPicker1.DropDownHeight = 1; this.colorPicker1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.colorPicker1.Font = new System.Drawing.Font("Arial", 8F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic)))); this.colorPicker1.FormattingEnabled = true; this.colorPicker1.IntegralHeight = false; this.colorPicker1.Items.AddRange(new object[] { "Aliceblue", "Antiquewhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "Blanchedalmond", "Blue", "Blueviolet", "Brown", "Burlywood", "Cadetblue", "Chartreuse", "Chocolate", "Coral", "Cornflowerblue", "Cornsilk", "Crimson", "Cyan", "Darkblue", "Darkcyan", "Darkgoldenrod", "Darkgray", "Darkgreen", "Darkkhaki", "Darkmagenta", "Darkolivegreen", "Darkorange", "Darkorchid", "Darkred", "Darksalmon", "Darkseagreen", "Darkslateblue", "Darkslategray", "Darkturquoise", "Darkviolet", "Deeppink", "Deepskyblue", "Dimgray", "Dodgerblue", "Firebrick", "Floralwhite", "Forestgreen", "Fuchsia", "Gainsboro", "Ghostwhite", "Gold", "Goldenrod", "Gray", "Green", "Greenyellow", "Honeydew", "Hotpink", "Indianred", "Indigo", "Ivory", "Khaki", "Lavender", "Lavenderblush", "Lawngreen", "Lemonchiffon", "Lightblue", "Lightcoral", "Lightcyan", "Lightgoldenrodyellow", "Lightgreen", "Lightgrey", "Lightpink", "Lightsalmon", "Lightseagreen", "Lightskyblue", "Lightslategrey", "Lightsteelblue", "Lightyellow", "Lime", "Limegreen", "Linen", "Magenta", "Maroon", "Mediumaquamarine", "Mediumblue", "Mediumorchid", "Mediumpurple", "Mediumseagreen", "Mediumslateblue", "Mediumspringgreen", "Mediumturquoise", "Mediumvioletred", "Midnightblue", "Mintcream", "Mistyrose", "Moccasin", "Navajowhite", "Navy", "Oldlace", "Olive", "Olivedrab", "Orange", "Orangered", "Orchid", "Palegoldenrod", "Palegreen", "Paleturquoise", "Palevioletred", "Papayawhip", "Peachpuff", "Peru", "Pink", "Plum", "Powderblue", "Purple", "Red", "Rosybrown", "Royalblue", "Saddlebrown", "Salmon", "Sandybrown", "Seagreen", "Seashell", "Sienna", "Silver", "Skyblue", "Slateblue", "Slategray", "Snow", "Springgreen", "Steelblue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "Whitesmoke", "Yellow", "Yellowgreen", "Aliceblue", "Antiquewhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "Blanchedalmond", "Blue", "Blueviolet", "Brown", "Burlywood", "Cadetblue", "Chartreuse", "Chocolate", "Coral", "Cornflowerblue", "Cornsilk", "Crimson", "Cyan", "Darkblue", "Darkcyan", "Darkgoldenrod", "Darkgray", "Darkgreen", "Darkkhaki", "Darkmagenta", "Darkolivegreen", "Darkorange", "Darkorchid", "Darkred", "Darksalmon", "Darkseagreen", "Darkslateblue", "Darkslategray", "Darkturquoise", "Darkviolet", "Deeppink", "Deepskyblue", "Dimgray", "Dodgerblue", "Firebrick", "Floralwhite", "Forestgreen", "Fuchsia", "Gainsboro", "Ghostwhite", "Gold", "Goldenrod", "Gray", "Green", "Greenyellow", "Honeydew", "Hotpink", "Indianred", "Indigo", "Ivory", "Khaki", "Lavender", "Lavenderblush", "Lawngreen", "Lemonchiffon", "Lightblue", "Lightcoral", "Lightcyan", "Lightgoldenrodyellow", "Lightgreen", "Lightgrey", "Lightpink", "Lightsalmon", "Lightseagreen", "Lightskyblue", "Lightslategrey", "Lightsteelblue", "Lightyellow", "Lime", "Limegreen", "Linen", "Magenta", "Maroon", "Mediumaquamarine", "Mediumblue", "Mediumorchid", "Mediumpurple", "Mediumseagreen", "Mediumslateblue", "Mediumspringgreen", "Mediumturquoise", "Mediumvioletred", "Midnightblue", "Mintcream", "Mistyrose", "Moccasin", "Navajowhite", "Navy", "Oldlace", "Olive", "Olivedrab", "Orange", "Orangered", "Orchid", "Palegoldenrod", "Palegreen", "Paleturquoise", "Palevioletred", "Papayawhip", "Peachpuff", "Peru", "Pink", "Plum", "Powderblue", "Purple", "Red", "Rosybrown", "Royalblue", "Saddlebrown", "Salmon", "Sandybrown", "Seagreen", "Seashell", "Sienna", "Silver", "Skyblue", "Slateblue", "Slategray", "Snow", "Springgreen", "Steelblue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "Whitesmoke", "Yellow", "Yellowgreen", "Aliceblue", "Antiquewhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "Blanchedalmond", "Blue", "Blueviolet", "Brown", "Burlywood", "Cadetblue", "Chartreuse", "Chocolate", "Coral", "Cornflowerblue", "Cornsilk", "Crimson", "Cyan", "Darkblue", "Darkcyan", "Darkgoldenrod", "Darkgray", "Darkgreen", "Darkkhaki", "Darkmagenta", "Darkolivegreen", "Darkorange", "Darkorchid", "Darkred", "Darksalmon", "Darkseagreen", "Darkslateblue", "Darkslategray", "Darkturquoise", "Darkviolet", "Deeppink", "Deepskyblue", "Dimgray", "Dodgerblue", "Firebrick", "Floralwhite", "Forestgreen", "Fuchsia", "Gainsboro", "Ghostwhite", "Gold", "Goldenrod", "Gray", "Green", "Greenyellow", "Honeydew", "Hotpink", "Indianred", "Indigo", "Ivory", "Khaki", "Lavender", "Lavenderblush", "Lawngreen", "Lemonchiffon", "Lightblue", "Lightcoral", "Lightcyan", "Lightgoldenrodyellow", "Lightgreen", "Lightgrey", "Lightpink", "Lightsalmon", "Lightseagreen", "Lightskyblue", "Lightslategrey", "Lightsteelblue", "Lightyellow", "Lime", "Limegreen", "Linen", "Magenta", "Maroon", "Mediumaquamarine", "Mediumblue", "Mediumorchid", "Mediumpurple", "Mediumseagreen", "Mediumslateblue", "Mediumspringgreen", "Mediumturquoise", "Mediumvioletred", "Midnightblue", "Mintcream", "Mistyrose", "Moccasin", "Navajowhite", "Navy", "Oldlace", "Olive", "Olivedrab", "Orange", "Orangered", "Orchid", "Palegoldenrod", "Palegreen", "Paleturquoise", "Palevioletred", "Papayawhip", "Peachpuff", "Peru", "Pink", "Plum", "Powderblue", "Purple", "Red", "Rosybrown", "Royalblue", "Saddlebrown", "Salmon", "Sandybrown", "Seagreen", "Seashell", "Sienna", "Silver", "Skyblue", "Slateblue", "Slategray", "Snow", "Springgreen", "Steelblue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "Whitesmoke", "Yellow", "Yellowgreen", "Aliceblue", "Antiquewhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "Blanchedalmond", "Blue", "Blueviolet", "Brown", "Burlywood", "Cadetblue", "Chartreuse", "Chocolate", "Coral", "Cornflowerblue", "Cornsilk", "Crimson", "Cyan", "Darkblue", "Darkcyan", "Darkgoldenrod", "Darkgray", "Darkgreen", "Darkkhaki", "Darkmagenta", "Darkolivegreen", "Darkorange", "Darkorchid", "Darkred", "Darksalmon", "Darkseagreen", "Darkslateblue", "Darkslategray", "Darkturquoise", "Darkviolet", "Deeppink", "Deepskyblue", "Dimgray", "Dodgerblue", "Firebrick", "Floralwhite", "Forestgreen", "Fuchsia", "Gainsboro", "Ghostwhite", "Gold", "Goldenrod", "Gray", "Green", "Greenyellow", "Honeydew", "Hotpink", "Indianred", "Indigo", "Ivory", "Khaki", "Lavender", "Lavenderblush", "Lawngreen", "Lemonchiffon", "Lightblue", "Lightcoral", "Lightcyan", "Lightgoldenrodyellow", "Lightgreen", "Lightgrey", "Lightpink", "Lightsalmon", "Lightseagreen", "Lightskyblue", "Lightslategrey", "Lightsteelblue", "Lightyellow", "Lime", "Limegreen", "Linen", "Magenta", "Maroon", "Mediumaquamarine", "Mediumblue", "Mediumorchid", "Mediumpurple", "Mediumseagreen", "Mediumslateblue", "Mediumspringgreen", "Mediumturquoise", "Mediumvioletred", "Midnightblue", "Mintcream", "Mistyrose", "Moccasin", "Navajowhite", "Navy", "Oldlace", "Olive", "Olivedrab", "Orange", "Orangered", "Orchid", "Palegoldenrod", "Palegreen", "Paleturquoise", "Palevioletred", "Papayawhip", "Peachpuff", "Peru", "Pink", "Plum", "Powderblue", "Purple", "Red", "Rosybrown", "Royalblue", "Saddlebrown", "Salmon", "Sandybrown", "Seagreen", "Seashell", "Sienna", "Silver", "Skyblue", "Slateblue", "Slategray", "Snow", "Springgreen", "Steelblue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "Whitesmoke", "Yellow", "Yellowgreen", "Aliceblue", "Antiquewhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "Blanchedalmond", "Blue", "Blueviolet", "Brown", "Burlywood", "Cadetblue", "Chartreuse", "Chocolate", "Coral", "Cornflowerblue", "Cornsilk", "Crimson", "Cyan", "Darkblue", "Darkcyan", "Darkgoldenrod", "Darkgray", "Darkgreen", "Darkkhaki", "Darkmagenta", "Darkolivegreen", "Darkorange", "Darkorchid", "Darkred", "Darksalmon", "Darkseagreen", "Darkslateblue", "Darkslategray", "Darkturquoise", "Darkviolet", "Deeppink", "Deepskyblue", "Dimgray", "Dodgerblue", "Firebrick", "Floralwhite", "Forestgreen", "Fuchsia", "Gainsboro", "Ghostwhite", "Gold", "Goldenrod", "Gray", "Green", "Greenyellow", "Honeydew", "Hotpink", "Indianred", "Indigo", "Ivory", "Khaki", "Lavender", "Lavenderblush", "Lawngreen", "Lemonchiffon", "Lightblue", "Lightcoral", "Lightcyan", "Lightgoldenrodyellow", "Lightgreen", "Lightgrey", "Lightpink", "Lightsalmon", "Lightseagreen", "Lightskyblue", "Lightslategrey", "Lightsteelblue", "Lightyellow", "Lime", "Limegreen", "Linen", "Magenta", "Maroon", "Mediumaquamarine", "Mediumblue", "Mediumorchid", "Mediumpurple", "Mediumseagreen", "Mediumslateblue", "Mediumspringgreen", "Mediumturquoise", "Mediumvioletred", "Midnightblue", "Mintcream", "Mistyrose", "Moccasin", "Navajowhite", "Navy", "Oldlace", "Olive", "Olivedrab", "Orange", "Orangered", "Orchid", "Palegoldenrod", "Palegreen", "Paleturquoise", "Palevioletred", "Papayawhip", "Peachpuff", "Peru", "Pink", "Plum", "Powderblue", "Purple", "Red", "Rosybrown", "Royalblue", "Saddlebrown", "Salmon", "Sandybrown", "Seagreen", "Seashell", "Sienna", "Silver", "Skyblue", "Slateblue", "Slategray", "Snow", "Springgreen", "Steelblue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "Whitesmoke", "Yellow", "Yellowgreen", "colorPicker1", ""}); this.colorPicker1.Location = new System.Drawing.Point(142, 236); this.colorPicker1.Name = "colorPicker1"; this.colorPicker1.Size = new System.Drawing.Size(98, 21); this.colorPicker1.TabIndex = 38; this.colorPicker1.SelectedIndexChanged += new System.EventHandler(this.colorPicker1_SelectedIndexChanged); // // StaticSeriesCtl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.label8); this.Controls.Add(this.colorPicker1); this.Controls.Add(this.cbLine); this.Controls.Add(this.label7); this.Controls.Add(this.chkMarker); this.Controls.Add(this.btnX); this.Controls.Add(this.label6); this.Controls.Add(this.txtX); this.Controls.Add(this.btnDown); this.Controls.Add(this.btnUp); this.Controls.Add(this.label5); this.Controls.Add(this.chkRight); this.Controls.Add(this.chkLeft); this.Controls.Add(this.cbPlotType); this.Controls.Add(this.label4); this.Controls.Add(this.txtDataValue); this.Controls.Add(this.btnSeriesName); this.Controls.Add(this.btnDataValue); this.Controls.Add(this.btnLabelValue); this.Controls.Add(this.btnDel); this.Controls.Add(this.btnAdd); this.Controls.Add(this.txtLabelValue); this.Controls.Add(this.txtSeriesName); this.Controls.Add(this.chkShowLabels); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.lbDataSeries); this.Controls.Add(this.label1); this.Name = "StaticSeriesCtl"; this.Size = new System.Drawing.Size(361, 260); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.ListBox lbDataSeries; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.CheckBox chkShowLabels; private System.Windows.Forms.TextBox txtSeriesName; private System.Windows.Forms.TextBox txtLabelValue; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnDel; private System.Windows.Forms.Button btnLabelValue; private System.Windows.Forms.Button btnDataValue; private System.Windows.Forms.Button btnSeriesName; private System.Windows.Forms.TextBox txtDataValue; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox cbPlotType; private System.Windows.Forms.RadioButton chkLeft; private System.Windows.Forms.RadioButton chkRight; private System.Windows.Forms.Label label5; private System.Windows.Forms.Button btnUp; private System.Windows.Forms.Button btnDown; private System.Windows.Forms.TextBox txtX; private System.Windows.Forms.Label label6; private System.Windows.Forms.Button btnX; private System.Windows.Forms.CheckBox chkMarker; private System.Windows.Forms.Label label7; private System.Windows.Forms.ComboBox cbLine; private ColorPicker colorPicker1; private System.Windows.Forms.Label label8; } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnEfeConv class. /// </summary> [Serializable] public partial class PnEfeConvCollection : ActiveList<PnEfeConv, PnEfeConvCollection> { public PnEfeConvCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnEfeConvCollection</returns> public PnEfeConvCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnEfeConv o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_efe_conv table. /// </summary> [Serializable] public partial class PnEfeConv : ActiveRecord<PnEfeConv>, IActiveRecord { #region .ctors and Default Settings public PnEfeConv() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnEfeConv(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnEfeConv(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnEfeConv(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_efe_conv", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdEfeConv = new TableSchema.TableColumn(schema); colvarIdEfeConv.ColumnName = "id_efe_conv"; colvarIdEfeConv.DataType = DbType.Int32; colvarIdEfeConv.MaxLength = 0; colvarIdEfeConv.AutoIncrement = true; colvarIdEfeConv.IsNullable = false; colvarIdEfeConv.IsPrimaryKey = true; colvarIdEfeConv.IsForeignKey = false; colvarIdEfeConv.IsReadOnly = false; colvarIdEfeConv.DefaultSetting = @""; colvarIdEfeConv.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfeConv); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = -1; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = true; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarDomicilio = new TableSchema.TableColumn(schema); colvarDomicilio.ColumnName = "domicilio"; colvarDomicilio.DataType = DbType.AnsiString; colvarDomicilio.MaxLength = -1; colvarDomicilio.AutoIncrement = false; colvarDomicilio.IsNullable = true; colvarDomicilio.IsPrimaryKey = false; colvarDomicilio.IsForeignKey = false; colvarDomicilio.IsReadOnly = false; colvarDomicilio.DefaultSetting = @""; colvarDomicilio.ForeignKeyTableName = ""; schema.Columns.Add(colvarDomicilio); TableSchema.TableColumn colvarDepartamento = new TableSchema.TableColumn(schema); colvarDepartamento.ColumnName = "departamento"; colvarDepartamento.DataType = DbType.AnsiString; colvarDepartamento.MaxLength = -1; colvarDepartamento.AutoIncrement = false; colvarDepartamento.IsNullable = true; colvarDepartamento.IsPrimaryKey = false; colvarDepartamento.IsForeignKey = false; colvarDepartamento.IsReadOnly = false; colvarDepartamento.DefaultSetting = @""; colvarDepartamento.ForeignKeyTableName = ""; schema.Columns.Add(colvarDepartamento); TableSchema.TableColumn colvarLocalidad = new TableSchema.TableColumn(schema); colvarLocalidad.ColumnName = "localidad"; colvarLocalidad.DataType = DbType.Int32; colvarLocalidad.MaxLength = 0; colvarLocalidad.AutoIncrement = false; colvarLocalidad.IsNullable = true; colvarLocalidad.IsPrimaryKey = false; colvarLocalidad.IsForeignKey = false; colvarLocalidad.IsReadOnly = false; colvarLocalidad.DefaultSetting = @""; colvarLocalidad.ForeignKeyTableName = ""; schema.Columns.Add(colvarLocalidad); TableSchema.TableColumn colvarCodPos = new TableSchema.TableColumn(schema); colvarCodPos.ColumnName = "cod_pos"; colvarCodPos.DataType = DbType.Int32; colvarCodPos.MaxLength = 0; colvarCodPos.AutoIncrement = false; colvarCodPos.IsNullable = true; colvarCodPos.IsPrimaryKey = false; colvarCodPos.IsForeignKey = false; colvarCodPos.IsReadOnly = false; colvarCodPos.DefaultSetting = @""; colvarCodPos.ForeignKeyTableName = ""; schema.Columns.Add(colvarCodPos); TableSchema.TableColumn colvarCuidad = new TableSchema.TableColumn(schema); colvarCuidad.ColumnName = "cuidad"; colvarCuidad.DataType = DbType.AnsiString; colvarCuidad.MaxLength = -1; colvarCuidad.AutoIncrement = false; colvarCuidad.IsNullable = true; colvarCuidad.IsPrimaryKey = false; colvarCuidad.IsForeignKey = false; colvarCuidad.IsReadOnly = false; colvarCuidad.DefaultSetting = @""; colvarCuidad.ForeignKeyTableName = ""; schema.Columns.Add(colvarCuidad); TableSchema.TableColumn colvarReferente = new TableSchema.TableColumn(schema); colvarReferente.ColumnName = "referente"; colvarReferente.DataType = DbType.AnsiString; colvarReferente.MaxLength = -1; colvarReferente.AutoIncrement = false; colvarReferente.IsNullable = true; colvarReferente.IsPrimaryKey = false; colvarReferente.IsForeignKey = false; colvarReferente.IsReadOnly = false; colvarReferente.DefaultSetting = @""; colvarReferente.ForeignKeyTableName = ""; schema.Columns.Add(colvarReferente); TableSchema.TableColumn colvarTel = new TableSchema.TableColumn(schema); colvarTel.ColumnName = "tel"; colvarTel.DataType = DbType.AnsiString; colvarTel.MaxLength = -1; colvarTel.AutoIncrement = false; colvarTel.IsNullable = true; colvarTel.IsPrimaryKey = false; colvarTel.IsForeignKey = false; colvarTel.IsReadOnly = false; colvarTel.DefaultSetting = @""; colvarTel.ForeignKeyTableName = ""; schema.Columns.Add(colvarTel); TableSchema.TableColumn colvarComGestion = new TableSchema.TableColumn(schema); colvarComGestion.ColumnName = "com_gestion"; colvarComGestion.DataType = DbType.AnsiString; colvarComGestion.MaxLength = -1; colvarComGestion.AutoIncrement = false; colvarComGestion.IsNullable = true; colvarComGestion.IsPrimaryKey = false; colvarComGestion.IsForeignKey = false; colvarComGestion.IsReadOnly = false; colvarComGestion.DefaultSetting = @""; colvarComGestion.ForeignKeyTableName = ""; schema.Columns.Add(colvarComGestion); TableSchema.TableColumn colvarComGestionFirmante = new TableSchema.TableColumn(schema); colvarComGestionFirmante.ColumnName = "com_gestion_firmante"; colvarComGestionFirmante.DataType = DbType.AnsiString; colvarComGestionFirmante.MaxLength = -1; colvarComGestionFirmante.AutoIncrement = false; colvarComGestionFirmante.IsNullable = true; colvarComGestionFirmante.IsPrimaryKey = false; colvarComGestionFirmante.IsForeignKey = false; colvarComGestionFirmante.IsReadOnly = false; colvarComGestionFirmante.DefaultSetting = @""; colvarComGestionFirmante.ForeignKeyTableName = ""; schema.Columns.Add(colvarComGestionFirmante); TableSchema.TableColumn colvarFechaCompGes = new TableSchema.TableColumn(schema); colvarFechaCompGes.ColumnName = "fecha_comp_ges"; colvarFechaCompGes.DataType = DbType.DateTime; colvarFechaCompGes.MaxLength = 0; colvarFechaCompGes.AutoIncrement = false; colvarFechaCompGes.IsNullable = true; colvarFechaCompGes.IsPrimaryKey = false; colvarFechaCompGes.IsForeignKey = false; colvarFechaCompGes.IsReadOnly = false; colvarFechaCompGes.DefaultSetting = @""; colvarFechaCompGes.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaCompGes); TableSchema.TableColumn colvarFechaFinCompGes = new TableSchema.TableColumn(schema); colvarFechaFinCompGes.ColumnName = "fecha_fin_comp_ges"; colvarFechaFinCompGes.DataType = DbType.DateTime; colvarFechaFinCompGes.MaxLength = 0; colvarFechaFinCompGes.AutoIncrement = false; colvarFechaFinCompGes.IsNullable = true; colvarFechaFinCompGes.IsPrimaryKey = false; colvarFechaFinCompGes.IsForeignKey = false; colvarFechaFinCompGes.IsReadOnly = false; colvarFechaFinCompGes.DefaultSetting = @""; colvarFechaFinCompGes.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaFinCompGes); TableSchema.TableColumn colvarComGestionPagoIndirecto = new TableSchema.TableColumn(schema); colvarComGestionPagoIndirecto.ColumnName = "com_gestion_pago_indirecto"; colvarComGestionPagoIndirecto.DataType = DbType.AnsiString; colvarComGestionPagoIndirecto.MaxLength = -1; colvarComGestionPagoIndirecto.AutoIncrement = false; colvarComGestionPagoIndirecto.IsNullable = true; colvarComGestionPagoIndirecto.IsPrimaryKey = false; colvarComGestionPagoIndirecto.IsForeignKey = false; colvarComGestionPagoIndirecto.IsReadOnly = false; colvarComGestionPagoIndirecto.DefaultSetting = @""; colvarComGestionPagoIndirecto.ForeignKeyTableName = ""; schema.Columns.Add(colvarComGestionPagoIndirecto); TableSchema.TableColumn colvarTerceroAdmin = new TableSchema.TableColumn(schema); colvarTerceroAdmin.ColumnName = "tercero_admin"; colvarTerceroAdmin.DataType = DbType.AnsiString; colvarTerceroAdmin.MaxLength = -1; colvarTerceroAdmin.AutoIncrement = false; colvarTerceroAdmin.IsNullable = true; colvarTerceroAdmin.IsPrimaryKey = false; colvarTerceroAdmin.IsForeignKey = false; colvarTerceroAdmin.IsReadOnly = false; colvarTerceroAdmin.DefaultSetting = @""; colvarTerceroAdmin.ForeignKeyTableName = ""; schema.Columns.Add(colvarTerceroAdmin); TableSchema.TableColumn colvarTerceroAdminFirmante = new TableSchema.TableColumn(schema); colvarTerceroAdminFirmante.ColumnName = "tercero_admin_firmante"; colvarTerceroAdminFirmante.DataType = DbType.AnsiString; colvarTerceroAdminFirmante.MaxLength = -1; colvarTerceroAdminFirmante.AutoIncrement = false; colvarTerceroAdminFirmante.IsNullable = true; colvarTerceroAdminFirmante.IsPrimaryKey = false; colvarTerceroAdminFirmante.IsForeignKey = false; colvarTerceroAdminFirmante.IsReadOnly = false; colvarTerceroAdminFirmante.DefaultSetting = @""; colvarTerceroAdminFirmante.ForeignKeyTableName = ""; schema.Columns.Add(colvarTerceroAdminFirmante); TableSchema.TableColumn colvarFechaTerceroAdmin = new TableSchema.TableColumn(schema); colvarFechaTerceroAdmin.ColumnName = "fecha_tercero_admin"; colvarFechaTerceroAdmin.DataType = DbType.DateTime; colvarFechaTerceroAdmin.MaxLength = 0; colvarFechaTerceroAdmin.AutoIncrement = false; colvarFechaTerceroAdmin.IsNullable = true; colvarFechaTerceroAdmin.IsPrimaryKey = false; colvarFechaTerceroAdmin.IsForeignKey = false; colvarFechaTerceroAdmin.IsReadOnly = false; colvarFechaTerceroAdmin.DefaultSetting = @""; colvarFechaTerceroAdmin.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaTerceroAdmin); TableSchema.TableColumn colvarFechaFinTerceroAdmin = new TableSchema.TableColumn(schema); colvarFechaFinTerceroAdmin.ColumnName = "fecha_fin_tercero_admin"; colvarFechaFinTerceroAdmin.DataType = DbType.DateTime; colvarFechaFinTerceroAdmin.MaxLength = 0; colvarFechaFinTerceroAdmin.AutoIncrement = false; colvarFechaFinTerceroAdmin.IsNullable = true; colvarFechaFinTerceroAdmin.IsPrimaryKey = false; colvarFechaFinTerceroAdmin.IsForeignKey = false; colvarFechaFinTerceroAdmin.IsReadOnly = false; colvarFechaFinTerceroAdmin.DefaultSetting = @""; colvarFechaFinTerceroAdmin.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaFinTerceroAdmin); TableSchema.TableColumn colvarCuie = new TableSchema.TableColumn(schema); colvarCuie.ColumnName = "cuie"; colvarCuie.DataType = DbType.AnsiString; colvarCuie.MaxLength = 10; colvarCuie.AutoIncrement = false; colvarCuie.IsNullable = true; colvarCuie.IsPrimaryKey = false; colvarCuie.IsForeignKey = false; colvarCuie.IsReadOnly = false; colvarCuie.DefaultSetting = @""; colvarCuie.ForeignKeyTableName = ""; schema.Columns.Add(colvarCuie); TableSchema.TableColumn colvarUsuario = new TableSchema.TableColumn(schema); colvarUsuario.ColumnName = "usuario"; colvarUsuario.DataType = DbType.AnsiString; colvarUsuario.MaxLength = -1; colvarUsuario.AutoIncrement = false; colvarUsuario.IsNullable = true; colvarUsuario.IsPrimaryKey = false; colvarUsuario.IsForeignKey = false; colvarUsuario.IsReadOnly = false; colvarUsuario.DefaultSetting = @""; colvarUsuario.ForeignKeyTableName = ""; schema.Columns.Add(colvarUsuario); TableSchema.TableColumn colvarFechaModificacion = new TableSchema.TableColumn(schema); colvarFechaModificacion.ColumnName = "fecha_modificacion"; colvarFechaModificacion.DataType = DbType.DateTime; colvarFechaModificacion.MaxLength = 0; colvarFechaModificacion.AutoIncrement = false; colvarFechaModificacion.IsNullable = true; colvarFechaModificacion.IsPrimaryKey = false; colvarFechaModificacion.IsForeignKey = false; colvarFechaModificacion.IsReadOnly = false; colvarFechaModificacion.DefaultSetting = @""; colvarFechaModificacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaModificacion); TableSchema.TableColumn colvarDniFirmanteActual = new TableSchema.TableColumn(schema); colvarDniFirmanteActual.ColumnName = "dni_firmante_actual"; colvarDniFirmanteActual.DataType = DbType.AnsiString; colvarDniFirmanteActual.MaxLength = -1; colvarDniFirmanteActual.AutoIncrement = false; colvarDniFirmanteActual.IsNullable = true; colvarDniFirmanteActual.IsPrimaryKey = false; colvarDniFirmanteActual.IsForeignKey = false; colvarDniFirmanteActual.IsReadOnly = false; colvarDniFirmanteActual.DefaultSetting = @""; colvarDniFirmanteActual.ForeignKeyTableName = ""; schema.Columns.Add(colvarDniFirmanteActual); TableSchema.TableColumn colvarComGestionFirmanteActual = new TableSchema.TableColumn(schema); colvarComGestionFirmanteActual.ColumnName = "com_gestion_firmante_actual"; colvarComGestionFirmanteActual.DataType = DbType.AnsiString; colvarComGestionFirmanteActual.MaxLength = -1; colvarComGestionFirmanteActual.AutoIncrement = false; colvarComGestionFirmanteActual.IsNullable = true; colvarComGestionFirmanteActual.IsPrimaryKey = false; colvarComGestionFirmanteActual.IsForeignKey = false; colvarComGestionFirmanteActual.IsReadOnly = false; colvarComGestionFirmanteActual.DefaultSetting = @""; colvarComGestionFirmanteActual.ForeignKeyTableName = ""; schema.Columns.Add(colvarComGestionFirmanteActual); TableSchema.TableColumn colvarN2008 = new TableSchema.TableColumn(schema); colvarN2008.ColumnName = "n_2008"; colvarN2008.DataType = DbType.AnsiString; colvarN2008.MaxLength = -1; colvarN2008.AutoIncrement = false; colvarN2008.IsNullable = true; colvarN2008.IsPrimaryKey = false; colvarN2008.IsForeignKey = false; colvarN2008.IsReadOnly = false; colvarN2008.DefaultSetting = @""; colvarN2008.ForeignKeyTableName = ""; schema.Columns.Add(colvarN2008); TableSchema.TableColumn colvarN2009 = new TableSchema.TableColumn(schema); colvarN2009.ColumnName = "n_2009"; colvarN2009.DataType = DbType.AnsiString; colvarN2009.MaxLength = -1; colvarN2009.AutoIncrement = false; colvarN2009.IsNullable = true; colvarN2009.IsPrimaryKey = false; colvarN2009.IsForeignKey = false; colvarN2009.IsReadOnly = false; colvarN2009.DefaultSetting = @""; colvarN2009.ForeignKeyTableName = ""; schema.Columns.Add(colvarN2009); TableSchema.TableColumn colvarIdNomencladorDetalle = new TableSchema.TableColumn(schema); colvarIdNomencladorDetalle.ColumnName = "id_nomenclador_detalle"; colvarIdNomencladorDetalle.DataType = DbType.Int32; colvarIdNomencladorDetalle.MaxLength = 0; colvarIdNomencladorDetalle.AutoIncrement = false; colvarIdNomencladorDetalle.IsNullable = true; colvarIdNomencladorDetalle.IsPrimaryKey = false; colvarIdNomencladorDetalle.IsForeignKey = false; colvarIdNomencladorDetalle.IsReadOnly = false; colvarIdNomencladorDetalle.DefaultSetting = @""; colvarIdNomencladorDetalle.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdNomencladorDetalle); TableSchema.TableColumn colvarIdZonaSani = new TableSchema.TableColumn(schema); colvarIdZonaSani.ColumnName = "id_zona_sani"; colvarIdZonaSani.DataType = DbType.Int32; colvarIdZonaSani.MaxLength = 0; colvarIdZonaSani.AutoIncrement = false; colvarIdZonaSani.IsNullable = true; colvarIdZonaSani.IsPrimaryKey = false; colvarIdZonaSani.IsForeignKey = true; colvarIdZonaSani.IsReadOnly = false; colvarIdZonaSani.DefaultSetting = @""; colvarIdZonaSani.ForeignKeyTableName = "PN_zona_sani"; schema.Columns.Add(colvarIdZonaSani); TableSchema.TableColumn colvarMail = new TableSchema.TableColumn(schema); colvarMail.ColumnName = "mail"; colvarMail.DataType = DbType.AnsiString; colvarMail.MaxLength = -1; colvarMail.AutoIncrement = false; colvarMail.IsNullable = true; colvarMail.IsPrimaryKey = false; colvarMail.IsForeignKey = false; colvarMail.IsReadOnly = false; colvarMail.DefaultSetting = @""; colvarMail.ForeignKeyTableName = ""; schema.Columns.Add(colvarMail); TableSchema.TableColumn colvarIncentivo = new TableSchema.TableColumn(schema); colvarIncentivo.ColumnName = "incentivo"; colvarIncentivo.DataType = DbType.AnsiString; colvarIncentivo.MaxLength = 2; colvarIncentivo.AutoIncrement = false; colvarIncentivo.IsNullable = true; colvarIncentivo.IsPrimaryKey = false; colvarIncentivo.IsForeignKey = false; colvarIncentivo.IsReadOnly = false; colvarIncentivo.DefaultSetting = @""; colvarIncentivo.ForeignKeyTableName = ""; schema.Columns.Add(colvarIncentivo); TableSchema.TableColumn colvarPerAltaCom = new TableSchema.TableColumn(schema); colvarPerAltaCom.ColumnName = "per_alta_com"; colvarPerAltaCom.DataType = DbType.AnsiString; colvarPerAltaCom.MaxLength = 2; colvarPerAltaCom.AutoIncrement = false; colvarPerAltaCom.IsNullable = true; colvarPerAltaCom.IsPrimaryKey = false; colvarPerAltaCom.IsForeignKey = false; colvarPerAltaCom.IsReadOnly = false; colvarPerAltaCom.DefaultSetting = @""; colvarPerAltaCom.ForeignKeyTableName = ""; schema.Columns.Add(colvarPerAltaCom); TableSchema.TableColumn colvarAdendaPer = new TableSchema.TableColumn(schema); colvarAdendaPer.ColumnName = "adenda_per"; colvarAdendaPer.DataType = DbType.AnsiString; colvarAdendaPer.MaxLength = 50; colvarAdendaPer.AutoIncrement = false; colvarAdendaPer.IsNullable = true; colvarAdendaPer.IsPrimaryKey = false; colvarAdendaPer.IsForeignKey = false; colvarAdendaPer.IsReadOnly = false; colvarAdendaPer.DefaultSetting = @""; colvarAdendaPer.ForeignKeyTableName = ""; schema.Columns.Add(colvarAdendaPer); TableSchema.TableColumn colvarFechaAdendaPer = new TableSchema.TableColumn(schema); colvarFechaAdendaPer.ColumnName = "fecha_adenda_per"; colvarFechaAdendaPer.DataType = DbType.DateTime; colvarFechaAdendaPer.MaxLength = 0; colvarFechaAdendaPer.AutoIncrement = false; colvarFechaAdendaPer.IsNullable = true; colvarFechaAdendaPer.IsPrimaryKey = false; colvarFechaAdendaPer.IsForeignKey = false; colvarFechaAdendaPer.IsReadOnly = false; colvarFechaAdendaPer.DefaultSetting = @""; colvarFechaAdendaPer.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaAdendaPer); TableSchema.TableColumn colvarCategoriaPer = new TableSchema.TableColumn(schema); colvarCategoriaPer.ColumnName = "categoria_per"; colvarCategoriaPer.DataType = DbType.AnsiString; colvarCategoriaPer.MaxLength = -1; colvarCategoriaPer.AutoIncrement = false; colvarCategoriaPer.IsNullable = true; colvarCategoriaPer.IsPrimaryKey = false; colvarCategoriaPer.IsForeignKey = false; colvarCategoriaPer.IsReadOnly = false; colvarCategoriaPer.DefaultSetting = @""; colvarCategoriaPer.ForeignKeyTableName = ""; schema.Columns.Add(colvarCategoriaPer); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_efe_conv",schema); } } #endregion #region Props [XmlAttribute("IdEfeConv")] [Bindable(true)] public int IdEfeConv { get { return GetColumnValue<int>(Columns.IdEfeConv); } set { SetColumnValue(Columns.IdEfeConv, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("Domicilio")] [Bindable(true)] public string Domicilio { get { return GetColumnValue<string>(Columns.Domicilio); } set { SetColumnValue(Columns.Domicilio, value); } } [XmlAttribute("Departamento")] [Bindable(true)] public string Departamento { get { return GetColumnValue<string>(Columns.Departamento); } set { SetColumnValue(Columns.Departamento, value); } } [XmlAttribute("Localidad")] [Bindable(true)] public int? Localidad { get { return GetColumnValue<int?>(Columns.Localidad); } set { SetColumnValue(Columns.Localidad, value); } } [XmlAttribute("CodPos")] [Bindable(true)] public int? CodPos { get { return GetColumnValue<int?>(Columns.CodPos); } set { SetColumnValue(Columns.CodPos, value); } } [XmlAttribute("Cuidad")] [Bindable(true)] public string Cuidad { get { return GetColumnValue<string>(Columns.Cuidad); } set { SetColumnValue(Columns.Cuidad, value); } } [XmlAttribute("Referente")] [Bindable(true)] public string Referente { get { return GetColumnValue<string>(Columns.Referente); } set { SetColumnValue(Columns.Referente, value); } } [XmlAttribute("Tel")] [Bindable(true)] public string Tel { get { return GetColumnValue<string>(Columns.Tel); } set { SetColumnValue(Columns.Tel, value); } } [XmlAttribute("ComGestion")] [Bindable(true)] public string ComGestion { get { return GetColumnValue<string>(Columns.ComGestion); } set { SetColumnValue(Columns.ComGestion, value); } } [XmlAttribute("ComGestionFirmante")] [Bindable(true)] public string ComGestionFirmante { get { return GetColumnValue<string>(Columns.ComGestionFirmante); } set { SetColumnValue(Columns.ComGestionFirmante, value); } } [XmlAttribute("FechaCompGes")] [Bindable(true)] public DateTime? FechaCompGes { get { return GetColumnValue<DateTime?>(Columns.FechaCompGes); } set { SetColumnValue(Columns.FechaCompGes, value); } } [XmlAttribute("FechaFinCompGes")] [Bindable(true)] public DateTime? FechaFinCompGes { get { return GetColumnValue<DateTime?>(Columns.FechaFinCompGes); } set { SetColumnValue(Columns.FechaFinCompGes, value); } } [XmlAttribute("ComGestionPagoIndirecto")] [Bindable(true)] public string ComGestionPagoIndirecto { get { return GetColumnValue<string>(Columns.ComGestionPagoIndirecto); } set { SetColumnValue(Columns.ComGestionPagoIndirecto, value); } } [XmlAttribute("TerceroAdmin")] [Bindable(true)] public string TerceroAdmin { get { return GetColumnValue<string>(Columns.TerceroAdmin); } set { SetColumnValue(Columns.TerceroAdmin, value); } } [XmlAttribute("TerceroAdminFirmante")] [Bindable(true)] public string TerceroAdminFirmante { get { return GetColumnValue<string>(Columns.TerceroAdminFirmante); } set { SetColumnValue(Columns.TerceroAdminFirmante, value); } } [XmlAttribute("FechaTerceroAdmin")] [Bindable(true)] public DateTime? FechaTerceroAdmin { get { return GetColumnValue<DateTime?>(Columns.FechaTerceroAdmin); } set { SetColumnValue(Columns.FechaTerceroAdmin, value); } } [XmlAttribute("FechaFinTerceroAdmin")] [Bindable(true)] public DateTime? FechaFinTerceroAdmin { get { return GetColumnValue<DateTime?>(Columns.FechaFinTerceroAdmin); } set { SetColumnValue(Columns.FechaFinTerceroAdmin, value); } } [XmlAttribute("Cuie")] [Bindable(true)] public string Cuie { get { return GetColumnValue<string>(Columns.Cuie); } set { SetColumnValue(Columns.Cuie, value); } } [XmlAttribute("Usuario")] [Bindable(true)] public string Usuario { get { return GetColumnValue<string>(Columns.Usuario); } set { SetColumnValue(Columns.Usuario, value); } } [XmlAttribute("FechaModificacion")] [Bindable(true)] public DateTime? FechaModificacion { get { return GetColumnValue<DateTime?>(Columns.FechaModificacion); } set { SetColumnValue(Columns.FechaModificacion, value); } } [XmlAttribute("DniFirmanteActual")] [Bindable(true)] public string DniFirmanteActual { get { return GetColumnValue<string>(Columns.DniFirmanteActual); } set { SetColumnValue(Columns.DniFirmanteActual, value); } } [XmlAttribute("ComGestionFirmanteActual")] [Bindable(true)] public string ComGestionFirmanteActual { get { return GetColumnValue<string>(Columns.ComGestionFirmanteActual); } set { SetColumnValue(Columns.ComGestionFirmanteActual, value); } } [XmlAttribute("N2008")] [Bindable(true)] public string N2008 { get { return GetColumnValue<string>(Columns.N2008); } set { SetColumnValue(Columns.N2008, value); } } [XmlAttribute("N2009")] [Bindable(true)] public string N2009 { get { return GetColumnValue<string>(Columns.N2009); } set { SetColumnValue(Columns.N2009, value); } } [XmlAttribute("IdNomencladorDetalle")] [Bindable(true)] public int? IdNomencladorDetalle { get { return GetColumnValue<int?>(Columns.IdNomencladorDetalle); } set { SetColumnValue(Columns.IdNomencladorDetalle, value); } } [XmlAttribute("IdZonaSani")] [Bindable(true)] public int? IdZonaSani { get { return GetColumnValue<int?>(Columns.IdZonaSani); } set { SetColumnValue(Columns.IdZonaSani, value); } } [XmlAttribute("Mail")] [Bindable(true)] public string Mail { get { return GetColumnValue<string>(Columns.Mail); } set { SetColumnValue(Columns.Mail, value); } } [XmlAttribute("Incentivo")] [Bindable(true)] public string Incentivo { get { return GetColumnValue<string>(Columns.Incentivo); } set { SetColumnValue(Columns.Incentivo, value); } } [XmlAttribute("PerAltaCom")] [Bindable(true)] public string PerAltaCom { get { return GetColumnValue<string>(Columns.PerAltaCom); } set { SetColumnValue(Columns.PerAltaCom, value); } } [XmlAttribute("AdendaPer")] [Bindable(true)] public string AdendaPer { get { return GetColumnValue<string>(Columns.AdendaPer); } set { SetColumnValue(Columns.AdendaPer, value); } } [XmlAttribute("FechaAdendaPer")] [Bindable(true)] public DateTime? FechaAdendaPer { get { return GetColumnValue<DateTime?>(Columns.FechaAdendaPer); } set { SetColumnValue(Columns.FechaAdendaPer, value); } } [XmlAttribute("CategoriaPer")] [Bindable(true)] public string CategoriaPer { get { return GetColumnValue<string>(Columns.CategoriaPer); } set { SetColumnValue(Columns.CategoriaPer, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a PnZonaSani ActiveRecord object related to this PnEfeConv /// /// </summary> public DalSic.PnZonaSani PnZonaSani { get { return DalSic.PnZonaSani.FetchByID(this.IdZonaSani); } set { SetColumnValue("id_zona_sani", value.IdZonaSani); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre,string varDomicilio,string varDepartamento,int? varLocalidad,int? varCodPos,string varCuidad,string varReferente,string varTel,string varComGestion,string varComGestionFirmante,DateTime? varFechaCompGes,DateTime? varFechaFinCompGes,string varComGestionPagoIndirecto,string varTerceroAdmin,string varTerceroAdminFirmante,DateTime? varFechaTerceroAdmin,DateTime? varFechaFinTerceroAdmin,string varCuie,string varUsuario,DateTime? varFechaModificacion,string varDniFirmanteActual,string varComGestionFirmanteActual,string varN2008,string varN2009,int? varIdNomencladorDetalle,int? varIdZonaSani,string varMail,string varIncentivo,string varPerAltaCom,string varAdendaPer,DateTime? varFechaAdendaPer,string varCategoriaPer) { PnEfeConv item = new PnEfeConv(); item.Nombre = varNombre; item.Domicilio = varDomicilio; item.Departamento = varDepartamento; item.Localidad = varLocalidad; item.CodPos = varCodPos; item.Cuidad = varCuidad; item.Referente = varReferente; item.Tel = varTel; item.ComGestion = varComGestion; item.ComGestionFirmante = varComGestionFirmante; item.FechaCompGes = varFechaCompGes; item.FechaFinCompGes = varFechaFinCompGes; item.ComGestionPagoIndirecto = varComGestionPagoIndirecto; item.TerceroAdmin = varTerceroAdmin; item.TerceroAdminFirmante = varTerceroAdminFirmante; item.FechaTerceroAdmin = varFechaTerceroAdmin; item.FechaFinTerceroAdmin = varFechaFinTerceroAdmin; item.Cuie = varCuie; item.Usuario = varUsuario; item.FechaModificacion = varFechaModificacion; item.DniFirmanteActual = varDniFirmanteActual; item.ComGestionFirmanteActual = varComGestionFirmanteActual; item.N2008 = varN2008; item.N2009 = varN2009; item.IdNomencladorDetalle = varIdNomencladorDetalle; item.IdZonaSani = varIdZonaSani; item.Mail = varMail; item.Incentivo = varIncentivo; item.PerAltaCom = varPerAltaCom; item.AdendaPer = varAdendaPer; item.FechaAdendaPer = varFechaAdendaPer; item.CategoriaPer = varCategoriaPer; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdEfeConv,string varNombre,string varDomicilio,string varDepartamento,int? varLocalidad,int? varCodPos,string varCuidad,string varReferente,string varTel,string varComGestion,string varComGestionFirmante,DateTime? varFechaCompGes,DateTime? varFechaFinCompGes,string varComGestionPagoIndirecto,string varTerceroAdmin,string varTerceroAdminFirmante,DateTime? varFechaTerceroAdmin,DateTime? varFechaFinTerceroAdmin,string varCuie,string varUsuario,DateTime? varFechaModificacion,string varDniFirmanteActual,string varComGestionFirmanteActual,string varN2008,string varN2009,int? varIdNomencladorDetalle,int? varIdZonaSani,string varMail,string varIncentivo,string varPerAltaCom,string varAdendaPer,DateTime? varFechaAdendaPer,string varCategoriaPer) { PnEfeConv item = new PnEfeConv(); item.IdEfeConv = varIdEfeConv; item.Nombre = varNombre; item.Domicilio = varDomicilio; item.Departamento = varDepartamento; item.Localidad = varLocalidad; item.CodPos = varCodPos; item.Cuidad = varCuidad; item.Referente = varReferente; item.Tel = varTel; item.ComGestion = varComGestion; item.ComGestionFirmante = varComGestionFirmante; item.FechaCompGes = varFechaCompGes; item.FechaFinCompGes = varFechaFinCompGes; item.ComGestionPagoIndirecto = varComGestionPagoIndirecto; item.TerceroAdmin = varTerceroAdmin; item.TerceroAdminFirmante = varTerceroAdminFirmante; item.FechaTerceroAdmin = varFechaTerceroAdmin; item.FechaFinTerceroAdmin = varFechaFinTerceroAdmin; item.Cuie = varCuie; item.Usuario = varUsuario; item.FechaModificacion = varFechaModificacion; item.DniFirmanteActual = varDniFirmanteActual; item.ComGestionFirmanteActual = varComGestionFirmanteActual; item.N2008 = varN2008; item.N2009 = varN2009; item.IdNomencladorDetalle = varIdNomencladorDetalle; item.IdZonaSani = varIdZonaSani; item.Mail = varMail; item.Incentivo = varIncentivo; item.PerAltaCom = varPerAltaCom; item.AdendaPer = varAdendaPer; item.FechaAdendaPer = varFechaAdendaPer; item.CategoriaPer = varCategoriaPer; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdEfeConvColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn DomicilioColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn DepartamentoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn LocalidadColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn CodPosColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn CuidadColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn ReferenteColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn TelColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn ComGestionColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn ComGestionFirmanteColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn FechaCompGesColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn FechaFinCompGesColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn ComGestionPagoIndirectoColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn TerceroAdminColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn TerceroAdminFirmanteColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn FechaTerceroAdminColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn FechaFinTerceroAdminColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn CuieColumn { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn UsuarioColumn { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn FechaModificacionColumn { get { return Schema.Columns[20]; } } public static TableSchema.TableColumn DniFirmanteActualColumn { get { return Schema.Columns[21]; } } public static TableSchema.TableColumn ComGestionFirmanteActualColumn { get { return Schema.Columns[22]; } } public static TableSchema.TableColumn N2008Column { get { return Schema.Columns[23]; } } public static TableSchema.TableColumn N2009Column { get { return Schema.Columns[24]; } } public static TableSchema.TableColumn IdNomencladorDetalleColumn { get { return Schema.Columns[25]; } } public static TableSchema.TableColumn IdZonaSaniColumn { get { return Schema.Columns[26]; } } public static TableSchema.TableColumn MailColumn { get { return Schema.Columns[27]; } } public static TableSchema.TableColumn IncentivoColumn { get { return Schema.Columns[28]; } } public static TableSchema.TableColumn PerAltaComColumn { get { return Schema.Columns[29]; } } public static TableSchema.TableColumn AdendaPerColumn { get { return Schema.Columns[30]; } } public static TableSchema.TableColumn FechaAdendaPerColumn { get { return Schema.Columns[31]; } } public static TableSchema.TableColumn CategoriaPerColumn { get { return Schema.Columns[32]; } } #endregion #region Columns Struct public struct Columns { public static string IdEfeConv = @"id_efe_conv"; public static string Nombre = @"nombre"; public static string Domicilio = @"domicilio"; public static string Departamento = @"departamento"; public static string Localidad = @"localidad"; public static string CodPos = @"cod_pos"; public static string Cuidad = @"cuidad"; public static string Referente = @"referente"; public static string Tel = @"tel"; public static string ComGestion = @"com_gestion"; public static string ComGestionFirmante = @"com_gestion_firmante"; public static string FechaCompGes = @"fecha_comp_ges"; public static string FechaFinCompGes = @"fecha_fin_comp_ges"; public static string ComGestionPagoIndirecto = @"com_gestion_pago_indirecto"; public static string TerceroAdmin = @"tercero_admin"; public static string TerceroAdminFirmante = @"tercero_admin_firmante"; public static string FechaTerceroAdmin = @"fecha_tercero_admin"; public static string FechaFinTerceroAdmin = @"fecha_fin_tercero_admin"; public static string Cuie = @"cuie"; public static string Usuario = @"usuario"; public static string FechaModificacion = @"fecha_modificacion"; public static string DniFirmanteActual = @"dni_firmante_actual"; public static string ComGestionFirmanteActual = @"com_gestion_firmante_actual"; public static string N2008 = @"n_2008"; public static string N2009 = @"n_2009"; public static string IdNomencladorDetalle = @"id_nomenclador_detalle"; public static string IdZonaSani = @"id_zona_sani"; public static string Mail = @"mail"; public static string Incentivo = @"incentivo"; public static string PerAltaCom = @"per_alta_com"; public static string AdendaPer = @"adenda_per"; public static string FechaAdendaPer = @"fecha_adenda_per"; public static string CategoriaPer = @"categoria_per"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Text; using PalmeralGenNHibernate.CEN.Default_; using NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Exceptions; using PalmeralGenNHibernate.EN.Default_; using PalmeralGenNHibernate.Exceptions; namespace PalmeralGenNHibernate.CAD.Default_ { public partial class PedidoCAD : BasicCAD, IPedidoCAD { public PedidoCAD() : base () { } public PedidoCAD(ISession sessionAux) : base (sessionAux) { } public PedidoEN ReadOIDDefault (string id) { PedidoEN pedidoEN = null; try { SessionInitializeTransaction (); pedidoEN = (PedidoEN)session.Get (typeof(PedidoEN), id); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } return pedidoEN; } public string Crear (PedidoEN pedido) { try { SessionInitializeTransaction (); if (pedido.Lineas != null) { foreach (PalmeralGenNHibernate.EN.Default_.LineaPedidoEN item in pedido.Lineas) { item.Pedido = pedido; session.Save (item); } } if (pedido.Proveedor != null) { pedido.Proveedor = (PalmeralGenNHibernate.EN.Default_.ProveedorEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.ProveedorEN), pedido.Proveedor.Id); pedido.Proveedor.Pedido.Add (pedido); } session.Save (pedido); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } return pedido.Id; } public string New_ (PedidoEN pedido) { try { SessionInitializeTransaction (); if (pedido.Lineas != null) { foreach (PalmeralGenNHibernate.EN.Default_.LineaPedidoEN item in pedido.Lineas) { item.Pedido = pedido; session.Save (item); } } if (pedido.Proveedor != null) { pedido.Proveedor = (PalmeralGenNHibernate.EN.Default_.ProveedorEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.ProveedorEN), pedido.Proveedor.Id); pedido.Proveedor.Pedido.Add (pedido); } session.Save (pedido); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } return pedido.Id; } public void Editar (PedidoEN pedido) { try { SessionInitializeTransaction (); PedidoEN pedidoEN = (PedidoEN)session.Load (typeof(PedidoEN), pedido.Id); pedidoEN.Fecha = pedido.Fecha; pedidoEN.Estado = pedido.Estado; pedidoEN.TipoPago = pedido.TipoPago; session.Update (pedidoEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } } public void Eliminar (string id) { try { SessionInitializeTransaction (); PedidoEN pedidoEN = (PedidoEN)session.Load (typeof(PedidoEN), id); session.Delete (pedidoEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } } public System.Collections.Generic.IList<PedidoEN> ObtenerTodos (int first, int size) { System.Collections.Generic.IList<PedidoEN> result = null; try { SessionInitializeTransaction (); if (size > 0) result = session.CreateCriteria (typeof(PedidoEN)). SetFirstResult (first).SetMaxResults (size).List<PedidoEN>(); else result = session.CreateCriteria (typeof(PedidoEN)).List<PedidoEN>(); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } return result; } public System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> BuscarPedidoPorAnyo (string p_anyo) { System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> result; try { SessionInitializeTransaction (); //String sql = @"FROM PedidoEN self where FROM PedidoEN AS ped WHERE year(ped.Fecha) LIKE CONTAT('%', :p_anyo , '%')"; //IQuery query = session.CreateQuery(sql); IQuery query = (IQuery)session.GetNamedQuery ("PedidoENbuscarPedidoPorAnyoHQL"); query.SetParameter ("p_anyo", p_anyo); result = query.List<PalmeralGenNHibernate.EN.Default_.PedidoEN>(); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } return result; } public System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> BuscarPedidoPorMesAnyo (string p_mes, string p_anyo) { System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> result; try { SessionInitializeTransaction (); //String sql = @"FROM PedidoEN self where FROM PedidoEN AS ped WHERE month(ped.Fecha) LIKE CONTAT('%', :p_mes, '%') AND year(ped.Fecha) LIKE CONTAT('%', :p_anyo, '%')"; //IQuery query = session.CreateQuery(sql); IQuery query = (IQuery)session.GetNamedQuery ("PedidoENbuscarPedidoPorMesAnyoHQL"); query.SetParameter ("p_mes", p_mes); query.SetParameter ("p_anyo", p_anyo); result = query.List<PalmeralGenNHibernate.EN.Default_.PedidoEN>(); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } return result; } public System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> BuscarPedidoPorProveedor (string p_proveedor) { System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> result; try { SessionInitializeTransaction (); //String sql = @"FROM PedidoEN self where FROM PedidoEN AS ped WHERE ped.Proveedor = :p_proveedor"; //IQuery query = session.CreateQuery(sql); IQuery query = (IQuery)session.GetNamedQuery ("PedidoENbuscarPedidoPorProveedorHQL"); query.SetParameter ("p_proveedor", p_proveedor); result = query.List<PalmeralGenNHibernate.EN.Default_.PedidoEN>(); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } return result; } public PedidoEN ObtenerPedido (string id) { PedidoEN pedidoEN = null; try { SessionInitializeTransaction (); pedidoEN = (PedidoEN)session.Get (typeof(PedidoEN), id); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } return pedidoEN; } public System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> BuscarPorEstado (string p_estado) { System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> result; try { SessionInitializeTransaction (); //String sql = @"FROM PedidoEN self where FROM PedidoEN AS ped WHERE ped.Estado = :p_estado"; //IQuery query = session.CreateQuery(sql); IQuery query = (IQuery)session.GetNamedQuery ("PedidoENbuscarPorEstadoHQL"); query.SetParameter ("p_estado", p_estado); result = query.List<PalmeralGenNHibernate.EN.Default_.PedidoEN>(); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } return result; } public System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> BuscarPorTipoPago (string p_tipoPago) { System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> result; try { SessionInitializeTransaction (); //String sql = @"FROM PedidoEN self where FROM PedidoEN AS ped WHERE ped.TipoPago = :p_tipoPago"; //IQuery query = session.CreateQuery(sql); IQuery query = (IQuery)session.GetNamedQuery ("PedidoENbuscarPorTipoPagoHQL"); query.SetParameter ("p_tipoPago", p_tipoPago); result = query.List<PalmeralGenNHibernate.EN.Default_.PedidoEN>(); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } return result; } public void Relationer_lineas (string p_pedido, System.Collections.Generic.IList<int> p_lineapedido) { PalmeralGenNHibernate.EN.Default_.PedidoEN pedidoEN = null; try { SessionInitializeTransaction (); pedidoEN = (PedidoEN)session.Load (typeof(PedidoEN), p_pedido); PalmeralGenNHibernate.EN.Default_.LineaPedidoEN lineasENAux = null; if (pedidoEN.Lineas == null) { pedidoEN.Lineas = new System.Collections.Generic.List<PalmeralGenNHibernate.EN.Default_.LineaPedidoEN>(); } foreach (int item in p_lineapedido) { lineasENAux = new PalmeralGenNHibernate.EN.Default_.LineaPedidoEN (); lineasENAux = (PalmeralGenNHibernate.EN.Default_.LineaPedidoEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.LineaPedidoEN), item); lineasENAux.Pedido = pedidoEN; pedidoEN.Lineas.Add (lineasENAux); } session.Update (pedidoEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } } public void Relationer_proveedor (string p_pedido, string p_proveedor) { PalmeralGenNHibernate.EN.Default_.PedidoEN pedidoEN = null; try { SessionInitializeTransaction (); pedidoEN = (PedidoEN)session.Load (typeof(PedidoEN), p_pedido); pedidoEN.Proveedor = (PalmeralGenNHibernate.EN.Default_.ProveedorEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.ProveedorEN), p_proveedor); pedidoEN.Proveedor.Pedido.Add (pedidoEN); session.Update (pedidoEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } } public void Unrelationer_lineas (string p_pedido, System.Collections.Generic.IList<int> p_lineapedido) { try { SessionInitializeTransaction (); PalmeralGenNHibernate.EN.Default_.PedidoEN pedidoEN = null; pedidoEN = (PedidoEN)session.Load (typeof(PedidoEN), p_pedido); PalmeralGenNHibernate.EN.Default_.LineaPedidoEN lineasENAux = null; if (pedidoEN.Lineas != null) { foreach (int item in p_lineapedido) { lineasENAux = (PalmeralGenNHibernate.EN.Default_.LineaPedidoEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.LineaPedidoEN), item); if (pedidoEN.Lineas.Contains (lineasENAux) == true) { pedidoEN.Lineas.Remove (lineasENAux); lineasENAux.Pedido = null; } else throw new ModelException ("The identifier " + item + " in p_lineapedido you are trying to unrelationer, doesn't exist in PedidoEN"); } } session.Update (pedidoEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } } public void Unrelationer_proveedor (string p_pedido, string p_proveedor) { try { SessionInitializeTransaction (); PalmeralGenNHibernate.EN.Default_.PedidoEN pedidoEN = null; pedidoEN = (PedidoEN)session.Load (typeof(PedidoEN), p_pedido); if (pedidoEN.Proveedor.Id == p_proveedor) { pedidoEN.Proveedor = null; } else throw new ModelException ("The identifier " + p_proveedor + " in p_proveedor you are trying to unrelationer, doesn't exist in PedidoEN"); session.Update (pedidoEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in PedidoCAD.", ex); } finally { SessionClose (); } } } }
// 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.Security.Cryptography.Tests; using Xunit; using Test.Cryptography; namespace System.Security.Cryptography.EcDiffieHellman.Tests { public partial class ECDiffieHellmanTests : EccTestBase { private static List<object[]> s_everyKeysize; private static List<object[]> s_mismatchedKeysizes; public static IEnumerable<object[]> EveryKeysize() { if (s_everyKeysize == null) { List<object[]> everyKeysize = new List<object[]>(); using (ECDiffieHellman defaultKeysize = ECDiffieHellmanFactory.Create()) { foreach (KeySizes keySizes in defaultKeysize.LegalKeySizes) { for (int size = keySizes.MinSize; size <= keySizes.MaxSize; size += keySizes.SkipSize) { everyKeysize.Add(new object[] { size }); if (keySizes.SkipSize == 0) { break; } } } } s_everyKeysize = everyKeysize; } return s_everyKeysize; } public static IEnumerable<object[]> MismatchedKeysizes() { if (s_mismatchedKeysizes == null) { int firstSize = -1; List<object[]> mismatchedKeysizes = new List<object[]>(); using (ECDiffieHellman defaultKeysize = ECDiffieHellmanFactory.Create()) { foreach (KeySizes keySizes in defaultKeysize.LegalKeySizes) { for (int size = keySizes.MinSize; size <= keySizes.MaxSize; size += keySizes.SkipSize) { if (firstSize == -1) { firstSize = size; } else if (size != firstSize) { mismatchedKeysizes.Add(new object[] { firstSize, size }); } if (keySizes.SkipSize == 0) { break; } } } } s_mismatchedKeysizes = mismatchedKeysizes; } return s_mismatchedKeysizes; } [Theory] [MemberData(nameof(EveryKeysize))] public static void SupportsKeysize(int keySize) { using (ECDiffieHellman ecdh = ECDiffieHellmanFactory.Create(keySize)) { Assert.Equal(keySize, ecdh.KeySize); } } [Theory] [MemberData(nameof(EveryKeysize))] public static void PublicKey_NotNull(int keySize) { using (ECDiffieHellman ecdh = ECDiffieHellmanFactory.Create(keySize)) using (ECDiffieHellmanPublicKey ecdhPubKey = ecdh.PublicKey) { Assert.NotNull(ecdhPubKey); } } [Fact] public static void PublicKeyIsFactory() { using (ECDiffieHellman ecdh = ECDiffieHellmanFactory.Create()) using (ECDiffieHellmanPublicKey publicKey1 = ecdh.PublicKey) using (ECDiffieHellmanPublicKey publicKey2 = ecdh.PublicKey) { Assert.NotSame(publicKey1, publicKey2); } } [Theory] [InlineData(false)] [InlineData(true)] public static void UseAfterDispose(bool importKey) { ECDiffieHellman key = ECDiffieHellmanFactory.Create(); ECDiffieHellmanPublicKey pubKey; HashAlgorithmName hash = HashAlgorithmName.SHA256; if (importKey) { key.ImportParameters(EccTestData.GetNistP256ReferenceKey()); } // Ensure the key is populated, then dispose it. using (key) { pubKey = key.PublicKey; key.DeriveKeyFromHash(pubKey, hash); pubKey.Dispose(); Assert.Throws<ObjectDisposedException>(() => key.DeriveKeyFromHash(pubKey, hash)); Assert.Throws<ObjectDisposedException>(() => key.DeriveKeyFromHmac(pubKey, hash, null)); Assert.Throws<ObjectDisposedException>(() => key.DeriveKeyFromHmac(pubKey, hash, new byte[3])); Assert.Throws<ObjectDisposedException>(() => key.DeriveKeyTls(pubKey, new byte[4], new byte[64])); pubKey = key.PublicKey; } key.Dispose(); Assert.Throws<ObjectDisposedException>(() => key.DeriveKeyFromHash(pubKey, hash)); Assert.Throws<ObjectDisposedException>(() => key.DeriveKeyFromHmac(pubKey, hash, null)); Assert.Throws<ObjectDisposedException>(() => key.DeriveKeyFromHmac(pubKey, hash, new byte[3])); Assert.Throws<ObjectDisposedException>(() => key.DeriveKeyTls(pubKey, new byte[4], new byte[64])); Assert.Throws<ObjectDisposedException>(() => key.GenerateKey(ECCurve.NamedCurves.nistP256)); Assert.Throws<ObjectDisposedException>(() => key.ImportParameters(EccTestData.GetNistP256ReferenceKey())); // Either set_KeySize or the ExportParameters should throw. Assert.Throws<ObjectDisposedException>( () => { key.KeySize = 384; key.ExportParameters(false); }); } #if NETCOREAPP private static ECDiffieHellman OpenKnownKey() { ECParameters ecParams = new ECParameters { Curve = ECCurve.NamedCurves.nistP521, Q = { X = ( "014AACFCDA18F77EBF11DC0A2D394D3032E86C3AC0B5F558916361163EA6AD3DB27" + "F6476D6C6E5D9C4A77BCCC5C0069D481718DACA3B1B13035AF5D246C4DC0CE0EA").HexToByteArray(), Y = ( "00CA500F75537C782E027DE568F148334BF56F7E24C3830792236B5D20F7A33E998" + "62B1744D2413E4C4AC29DBA42FC48D23AE5B916BED73997EC69B3911C686C5164").HexToByteArray(), }, D = ( "00202F9F5480723D1ACF15372CE0B99B6CC3E8772FFDDCF828EEEB314B3EAA35B19" + "886AAB1E6871E548C261C7708BF561A4C373D3EED13F0749851F57B86DC049D71").HexToByteArray(), }; ECDiffieHellman ecdh = ECDiffieHellmanFactory.Create(); ecdh.ImportParameters(ecParams); return ecdh; } #endif } internal static class EcdhTestExtensions { internal static void Exercise(this ECDiffieHellman e) { // Make a few calls on this to ensure we aren't broken due to bad/prematurely released handles. int keySize = e.KeySize; using (ECDiffieHellmanPublicKey publicKey = e.PublicKey) { byte[] negotiated = e.DeriveKeyFromHash(publicKey, HashAlgorithmName.SHA256); Assert.Equal(256 / 8, negotiated.Length); } } } }
/*************************************************************************** * ImportManager.cs * * Copyright (C) 2005-2006 Novell, Inc. * Written by Aaron Bockover <aaron@abock.org> ****************************************************************************/ /* 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.Threading; #if win32 using System.Windows.Forms; using Banshee.Winforms; using Banshee.Winforms.Controls; #else using Mono.Unix; using Gtk; using Banshee.Widgets; #endif using Banshee.IO; namespace Banshee.Base { public delegate void ImportEventHandler(object o, ImportEventArgs args); public class ImportEventArgs : EventArgs { public string FileName; public string ReturnMessage; } public class ImportManager { private class ImportCanceledException : ApplicationException { } private static ImportManager instance; public static ImportManager Instance { get { if(instance == null) { instance = new ImportManager(); } return instance; } } #if win32 private static System.Drawing.Icon user_event_icon = IconThemeUtils.LoadIcon(ConfigureDefines.ICON_THEME_DIR+@"\system-search.png"); #else private static Gdk.Pixbuf user_event_icon = IconThemeUtils.LoadIcon(22, "system-search", Stock.Find); #endif private static readonly object user_event_mutex = new object(); private Queue path_queue; private ActiveUserEvent user_event; private int total_count; private int processed_count; private int scan_ref_count = 0; private bool processing_queue = false; public event ImportEventHandler ImportRequested; public event EventHandler ImportFinished; public ImportManager() { path_queue = new Queue(); } private void CreateUserEvent() { lock(user_event_mutex) { if(user_event == null) { user_event = new ActiveUserEvent(Title); user_event.CancelMessage = CancelMessage; user_event.Icon = user_event_icon; user_event.Message = Catalog.GetString("Scanning for songs"); total_count = 0; processed_count = 0; } } } private void DestroyUserEvent() { lock(user_event_mutex) { if(user_event != null) { user_event.Invoke((MethodInvoker)delegate(){ user_event.Dispose(); user_event = null; total_count = 0; processed_count = 0; scan_ref_count = 0; }); } } } private void UpdateCount(string message) { CreateUserEvent(); processed_count++; double new_progress = (double)processed_count / (double)total_count; double old_progress = user_event.Progress; if(new_progress >= 0.0 && new_progress <= 1.0 && Math.Abs(new_progress - old_progress) > 0.001) { string disp_progress = String.Format(ProgressMessage, processed_count, total_count); user_event.Header = disp_progress; user_event.Message = message; user_event.Progress = new_progress; user_event.OnUpdateStatus(); } } private void CheckForCanceled() { lock(user_event_mutex) { if(user_event != null && user_event.IsCancelRequested) { throw new ImportCanceledException(); } } } private void FinalizeImport() { path_queue.Clear(); processing_queue = false; DestroyUserEvent(); } private void Enqueue(string path) { if(path_queue.Contains(path)) { return; } total_count++; lock(path_queue.SyncRoot) { path_queue.Enqueue(path); } } public void QueueSource(UriList uris) { CreateUserEvent(); ThreadAssist.Spawn(delegate { try { foreach(string path in uris.LocalPaths) { scan_ref_count++; ScanForFiles(path); scan_ref_count--; } if(scan_ref_count == 0) { ProcessQueue(); } } catch(ImportCanceledException) { FinalizeImport(); } }); } #if !win32 public void QueueSource(Gtk.SelectionData selection) { QueueSource(new UriList(selection)); } #else #endif public void QueueSource(string source) { QueueSource(new UriList(source)); } public void QueueSource(string [] paths) { QueueSource(new UriList(paths)); } private void ScanForFiles(string source) { CheckForCanceled(); scan_ref_count++; bool is_regular_file = false; bool is_directory = false; SafeUri source_uri = new SafeUri(source); try { is_regular_file = IOProxy.File.Exists(source_uri); is_directory = !is_regular_file && IOProxy.Directory.Exists(source); } catch { scan_ref_count--; return; } if(is_regular_file) { try { if(!Path.GetFileName(source).StartsWith(".")) { Enqueue(source); } } catch(System.ArgumentException) { // If there are illegal characters in path } } else if(is_directory) { try { //if(!Path.GetFileName(System.IO.Path.GetDirectoryName(source)).StartsWith(".")) { try { foreach(string file in IOProxy.Directory.GetFiles(source)) { ScanForFiles(file); } foreach(string directory in IOProxy.Directory.GetDirectories(source)) { ScanForFiles(directory); } } catch { } //} } catch(System.ArgumentException) { // If there are illegal characters in path } } scan_ref_count--; } private void ProcessQueue() { if(processing_queue) { return; } processing_queue = true; using(new Banshee.Base.Timer("Importing")) { while(path_queue.Count > 0) { CheckForCanceled(); string filename = path_queue.Dequeue() as string; ImportEventHandler handler = ImportRequested; if(handler != null && filename != null) { ImportEventArgs args = new ImportEventArgs(); args.FileName = filename; handler(this, args); UpdateCount(args.ReturnMessage); } else { UpdateCount(null); } } } path_queue.Clear(); processing_queue = false; if(scan_ref_count == 0) { DestroyUserEvent(); if(ImportFinished != null) { ImportFinished(this, new EventArgs()); } } } private string title = Catalog.GetString("Importing Songs"); public string Title { get { return title; } set { title = value; } } private string cancel_message = Catalog.GetString("The import process is currently running. Would you like to stop it?"); public string CancelMessage { get { return cancel_message; } set { cancel_message = value; } } private string progress_message = Catalog.GetString("Importing {0} of {1}"); public string ProgressMessage { get { return progress_message; } set { progress_message = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Xml.Schema; namespace System.Xml.Xsl { /// <summary> /// XmlQueryType contains static type information that describes the structure and possible values of dynamic /// instances of the Xml data model. /// /// Every XmlQueryType is composed of a Prime type and a cardinality. The Prime type itself may be a union /// between several item types. The XmlQueryType IList<XmlQueryType/> implementation allows callers /// to enumerate the item types. Other properties expose other information about the type. /// </summary> internal abstract class XmlQueryType : ListBase<XmlQueryType> { private static readonly BitMatrix s_typeCodeDerivation; private int _hashCode; //----------------------------------------------- // Static Constructor //----------------------------------------------- static XmlQueryType() { s_typeCodeDerivation = new BitMatrix(s_baseTypeCodes.Length); // Build derivation matrix for (int i = 0; i < s_baseTypeCodes.Length; i++) { int nextAncestor = i; while (true) { s_typeCodeDerivation[i, nextAncestor] = true; if ((int)s_baseTypeCodes[nextAncestor] == nextAncestor) break; nextAncestor = (int)s_baseTypeCodes[nextAncestor]; } } } //----------------------------------------------- // ItemType, OccurrenceIndicator Properties //----------------------------------------------- /// <summary> /// Static data type code. The dynamic type is guaranteed to be this type or a subtype of this code. /// This type code includes support for XQuery types that are not part of Xsd, such as Item, /// Node, AnyAtomicType, and Comment. /// </summary> public abstract XmlTypeCode TypeCode { get; } /// <summary> /// Set of alowed names for element, document{element}, attribute and PI /// Returns XmlQualifiedName.Wildcard for all other types /// </summary> public abstract XmlQualifiedNameTest NameTest { get; } /// <summary> /// Static Xsd schema type. The dynamic type is guaranteed to be this type or a subtype of this type. /// SchemaType will follow these rules: /// 1. If TypeCode is an atomic type code, then SchemaType will be the corresponding non-null simple type /// 2. If TypeCode is Element or Attribute, then SchemaType will be the non-null content type /// 3. If TypeCode is Item, Node, Comment, PI, Text, Document, Namespacce, None, then SchemaType will be AnyType /// </summary> public abstract XmlSchemaType SchemaType { get; } /// <summary> /// Permits the element or document{element} node to have the nilled property. /// Returns false for all other types /// </summary> public abstract bool IsNillable { get; } /// <summary> /// This property is always XmlNodeKindFlags.None unless TypeCode = XmlTypeCode.Node, in which case this /// property lists all node kinds that instances of this type may be. /// </summary> public abstract XmlNodeKindFlags NodeKinds { get; } /// <summary> /// If IsStrict is true, then the dynamic type is guaranteed to be the exact same as the static type, and /// will therefore never be a subtype of the static type. /// </summary> public abstract bool IsStrict { get; } /// <summary> /// This property specifies the possible cardinalities that instances of this type may have. /// </summary> public abstract XmlQueryCardinality Cardinality { get; } /// <summary> /// This property returns this type's Prime type, which is always cardinality One. /// </summary> public abstract XmlQueryType Prime { get; } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be not a subtype of Rtf. /// </summary> public abstract bool IsNotRtf { get; } /// <summary> /// True if items in the sequence are guaranteed to be nodes in document order with no duplicates. /// </summary> public abstract bool IsDod { get; } /// <summary> /// The XmlValueConverter maps each XmlQueryType to various Clr types which are capable of representing it. /// </summary> public abstract XmlValueConverter ClrMapping { get; } //----------------------------------------------- // Type Operations //----------------------------------------------- /// <summary> /// Returns true if every possible dynamic instance of this type is also an instance of "baseType". /// </summary> public bool IsSubtypeOf(XmlQueryType baseType) { XmlQueryType thisPrime, basePrime; // Check cardinality sub-typing rules if (!(Cardinality <= baseType.Cardinality) || (!IsDod && baseType.IsDod)) return false; if (!IsDod && baseType.IsDod) return false; // Check early for common case that two types are the same object thisPrime = Prime; basePrime = baseType.Prime; if ((object)thisPrime == (object)basePrime) return true; // Check early for common case that two prime types are item types if (thisPrime.Count == 1 && basePrime.Count == 1) return thisPrime.IsSubtypeOfItemType(basePrime); // Check that each item type in this type is a subtype of some item type in "baseType" foreach (XmlQueryType thisItem in thisPrime) { bool match = false; foreach (XmlQueryType baseItem in basePrime) { if (thisItem.IsSubtypeOfItemType(baseItem)) { match = true; break; } } if (match == false) return false; } return true; } /// <summary> /// Returns true if a dynamic instance (type None never has an instance) of this type can never be a subtype of "baseType". /// </summary> public bool NeverSubtypeOf(XmlQueryType baseType) { // Check cardinalities if (Cardinality.NeverSubset(baseType.Cardinality)) return true; // If both this type and "other" type might be empty, it doesn't matter what the prime types are if (MaybeEmpty && baseType.MaybeEmpty) return false; // None is subtype of every other type if (Count == 0) return false; // Check item types foreach (XmlQueryType typThis in this) { foreach (XmlQueryType typThat in baseType) { if (typThis.HasIntersectionItemType(typThat)) return false; } } return true; } /// <summary> /// Strongly-typed Equals that returns true if this type and "that" type are equivalent. /// </summary> public bool Equals(XmlQueryType that) { if (that == null) return false; // Check cardinality and DocOrderDistinct property if (Cardinality != that.Cardinality || IsDod != that.IsDod) return false; // Check early for common case that two types are the same object XmlQueryType thisPrime = Prime; XmlQueryType thatPrime = that.Prime; if ((object)thisPrime == (object)thatPrime) return true; // Check that count of item types is equal if (thisPrime.Count != thatPrime.Count) return false; // Check early for common case that two prime types are item types if (thisPrime.Count == 1) { return (thisPrime.TypeCode == thatPrime.TypeCode && thisPrime.NameTest == thatPrime.NameTest && thisPrime.SchemaType == thatPrime.SchemaType && thisPrime.IsStrict == thatPrime.IsStrict && thisPrime.IsNotRtf == thatPrime.IsNotRtf); } // Check that each item type in this type is equal to some item type in "baseType" // (string | int) should be the same type as (int | string) foreach (XmlQueryType thisItem in this) { bool match = false; foreach (XmlQueryType thatItem in that) { if (thisItem.TypeCode == thatItem.TypeCode && thisItem.NameTest == thatItem.NameTest && thisItem.SchemaType == thatItem.SchemaType && thisItem.IsStrict == thatItem.IsStrict && thisItem.IsNotRtf == thatItem.IsNotRtf) { // Found match so proceed to next type match = true; break; } } if (match == false) return false; } return true; } /// <summary> /// Overload == operator to call Equals rather than do reference equality. /// </summary> public static bool operator ==(XmlQueryType left, XmlQueryType right) { if ((object)left == null) return ((object)right == null); return left.Equals(right); } /// <summary> /// Overload != operator to call Equals rather than do reference inequality. /// </summary> public static bool operator !=(XmlQueryType left, XmlQueryType right) { if ((object)left == null) return ((object)right != null); return !left.Equals(right); } //----------------------------------------------- // Convenience Properties //----------------------------------------------- /// <summary> /// True if dynamic cardinality of this sequence is guaranteed to be 0. /// </summary> public bool IsEmpty { get { return Cardinality <= XmlQueryCardinality.Zero; } } /// <summary> /// True if dynamic cardinality of this sequence is guaranteed to be 1. /// </summary> public bool IsSingleton { get { return Cardinality <= XmlQueryCardinality.One; } } /// <summary> /// True if dynamic cardinality of this sequence might be 0. /// </summary> public bool MaybeEmpty { get { return XmlQueryCardinality.Zero <= Cardinality; } } /// <summary> /// True if dynamic cardinality of this sequence might be >1. /// </summary> public bool MaybeMany { get { return XmlQueryCardinality.More <= Cardinality; } } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of Node. /// Equivalent to calling IsSubtypeOf(TypeFactory.NodeS). /// </summary> public bool IsNode { get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsNode) != 0; } } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of AnyAtomicType. /// Equivalent to calling IsSubtypeOf(TypeFactory.AnyAtomicTypeS). /// </summary> public bool IsAtomicValue { get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsAtomicValue) != 0; } } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of Decimal, Double, or Float. /// Equivalent to calling IsSubtypeOf(TypeFactory.NumericS). /// </summary> public bool IsNumeric { get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsNumeric) != 0; } } //----------------------------------------------- // System.Object implementation //----------------------------------------------- /// <summary> /// True if "obj" is an XmlQueryType, and this type is the exact same static type. /// </summary> public override bool Equals(object obj) { XmlQueryType that = obj as XmlQueryType; if (that == null) return false; return Equals(that); } /// <summary> /// Return hash code of this instance. /// </summary> public override int GetHashCode() { if (_hashCode == 0) { int hash; XmlSchemaType schemaType; hash = (int)TypeCode; schemaType = SchemaType; unchecked { if (schemaType != null) hash += (hash << 7) ^ schemaType.GetHashCode(); hash += (hash << 7) ^ (int)NodeKinds; hash += (hash << 7) ^ Cardinality.GetHashCode(); hash += (hash << 7) ^ (IsStrict ? 1 : 0); // Mix hash code a bit more hash -= hash >> 17; hash -= hash >> 11; hash -= hash >> 5; } // Save hashcode. Don't save 0, so that it won't ever be recomputed. _hashCode = (hash == 0) ? 1 : hash; } return _hashCode; } /// <summary> /// Return a user-friendly string representation of the XmlQueryType. /// </summary> public override string ToString() { return ToString("G"); } /// <summary> /// Return a string representation of the XmlQueryType using the specified format. The following formats are /// supported: /// /// "G" (General): This is the default mode, and is used if no other format is recognized. This format is /// easier to read than the canonical format, since it excludes redundant information. /// (e.g. element instead of element(*, xs:anyType)) /// /// "X" (XQuery): Return the canonical XQuery representation, which excludes Qil specific information and /// includes extra, redundant information, such as fully specified types. /// (e.g. element(*, xs:anyType) instead of element) /// /// "S" (Serialized): This format is used to serialize parts of the type which can be serialized easily, in /// a format that is easy to parse. Only the cardinality, type code, and strictness flag /// are serialized. User-defined type information and element/attribute content types /// are lost. /// (e.g. One;Attribute|String|Int;true) /// /// </summary> public string ToString(string format) { string[] sa; StringBuilder sb; bool isXQ; if (format == "S") { sb = new StringBuilder(); sb.Append(Cardinality.ToString(format)); sb.Append(';'); for (int i = 0; i < Count; i++) { if (i != 0) sb.Append("|"); sb.Append(this[i].TypeCode.ToString()); } sb.Append(';'); sb.Append(IsStrict); return sb.ToString(); } isXQ = (format == "X"); if (Cardinality == XmlQueryCardinality.None) { return "none"; } else if (Cardinality == XmlQueryCardinality.Zero) { return "empty"; } sb = new StringBuilder(); switch (Count) { case 0: // This assert depends on the way we are going to represent None // Debug.Assert(false); sb.Append("none"); break; case 1: sb.Append(this[0].ItemTypeToString(isXQ)); break; default: sa = new string[Count]; for (int i = 0; i < Count; i++) sa[i] = this[i].ItemTypeToString(isXQ); Array.Sort(sa); sb = new StringBuilder(); sb.Append('('); sb.Append(sa[0]); for (int i = 1; i < sa.Length; i++) { sb.Append(" | "); sb.Append(sa[i]); } sb.Append(')'); break; } sb.Append(Cardinality.ToString()); if (!isXQ && IsDod) sb.Append('#'); return sb.ToString(); } //----------------------------------------------- // Serialization //----------------------------------------------- /// <summary> /// Serialize the object to BinaryWriter. /// </summary> public abstract void GetObjectData(BinaryWriter writer); //----------------------------------------------- // Helpers //----------------------------------------------- /// <summary> /// Returns true if this item type is a subtype of another item type. /// </summary> private bool IsSubtypeOfItemType(XmlQueryType baseType) { Debug.Assert(Count == 1 && IsSingleton, "This method should only be called for item types."); Debug.Assert(baseType.Count == 1 && baseType.IsSingleton, "This method should only be called for item types."); Debug.Assert(!IsDod && !baseType.IsDod, "Singleton types may not have DocOrderDistinct property"); XmlSchemaType baseSchemaType = baseType.SchemaType; if (TypeCode != baseType.TypeCode) { // If "baseType" is strict, then IsSubtypeOf must be false if (baseType.IsStrict) return false; // If type codes are not the same, then IsSubtypeOf can return true *only* if "baseType" is a built-in type XmlSchemaType builtInType = XmlSchemaType.GetBuiltInSimpleType(baseType.TypeCode); if (builtInType != null && baseSchemaType != builtInType) return false; // Now check whether TypeCode is derived from baseType.TypeCode return s_typeCodeDerivation[TypeCode, baseType.TypeCode]; } else if (baseType.IsStrict) { // only atomic values can be strict Debug.Assert(IsAtomicValue && baseType.IsAtomicValue); // If schema types are not the same, then IsSubtype is false if "baseType" is strict return IsStrict && SchemaType == baseSchemaType; } else { // Otherwise, check derivation tree return (IsNotRtf || !baseType.IsNotRtf) && NameTest.IsSubsetOf(baseType.NameTest) && (baseSchemaType == XmlSchemaComplexType.AnyType || XmlSchemaType.IsDerivedFrom(SchemaType, baseSchemaType, /* except:*/XmlSchemaDerivationMethod.Empty)) && (!IsNillable || baseType.IsNillable); } } /// <summary> /// Returns true if the intersection between this item type and "other" item type is not empty. /// </summary> private bool HasIntersectionItemType(XmlQueryType other) { Debug.Assert(this.Count == 1 && this.IsSingleton, "this should be an item"); Debug.Assert(other.Count == 1 && other.IsSingleton, "other should be an item"); if (this.TypeCode == other.TypeCode && (this.NodeKinds & (XmlNodeKindFlags.Document | XmlNodeKindFlags.Element | XmlNodeKindFlags.Attribute)) != 0) { if (this.TypeCode == XmlTypeCode.Node) return true; // Intersect name tests if (!this.NameTest.HasIntersection(other.NameTest)) return false; if (!XmlSchemaType.IsDerivedFrom(this.SchemaType, other.SchemaType, /* except:*/XmlSchemaDerivationMethod.Empty) && !XmlSchemaType.IsDerivedFrom(other.SchemaType, this.SchemaType, /* except:*/XmlSchemaDerivationMethod.Empty)) { return false; } return true; } else if (this.IsSubtypeOf(other) || other.IsSubtypeOf(this)) { return true; } return false; } /// <summary> /// Return the string representation of an item type (cannot be a union or a sequence). /// </summary> private string ItemTypeToString(bool isXQ) { string s; Debug.Assert(Count == 1, "Do not pass a Union type to this method."); Debug.Assert(IsSingleton, "Do not pass a Sequence type to this method."); if (IsNode) { // Map TypeCode to string s = s_typeNames[(int)TypeCode]; switch (TypeCode) { case XmlTypeCode.Document: if (!isXQ) goto case XmlTypeCode.Element; s += "{(element" + NameAndType(true) + "?&text?&comment?&processing-instruction?)*}"; break; case XmlTypeCode.Element: case XmlTypeCode.Attribute: s += NameAndType(isXQ); break; } } else if (SchemaType != XmlSchemaComplexType.AnyType) { // Get QualifiedName from SchemaType if (SchemaType.QualifiedName.IsEmpty) s = "<:" + s_typeNames[(int)TypeCode]; else s = QNameToString(SchemaType.QualifiedName); } else { // Map TypeCode to string s = s_typeNames[(int)TypeCode]; } if (!isXQ && IsStrict) s += "="; return s; } /// <summary> /// Return "(name-test, type-name)" for this type. If isXQ is false, normalize xs:anySimpleType and /// xs:anyType to "*". /// </summary> private string NameAndType(bool isXQ) { string nodeName = NameTest.ToString(); string typeName = "*"; if (SchemaType.QualifiedName.IsEmpty) { typeName = "typeof(" + nodeName + ")"; } else { if (isXQ || (SchemaType != XmlSchemaComplexType.AnyType && SchemaType != DatatypeImplementation.AnySimpleType)) typeName = QNameToString(SchemaType.QualifiedName); } if (IsNillable) typeName += " nillable"; // Normalize "(*, *)" to "" if (nodeName == "*" && typeName == "*") return ""; return "(" + nodeName + ", " + typeName + ")"; } /// <summary> /// Convert an XmlQualifiedName to a string, using somewhat different rules than XmlQualifiedName.ToString(): /// 1. Empty QNames are assumed to be wildcard names, so return "*" /// 2. Recognize the built-in xs: and xdt: namespaces and print the short prefix rather than the long namespace /// 3. Use brace characters "{", "}" around the namespace portion of the QName /// </summary> private static string QNameToString(XmlQualifiedName name) { if (name.IsEmpty) { return "*"; } else if (name.Namespace.Length == 0) { return name.Name; } else if (name.Namespace == XmlReservedNs.NsXs) { return "xs:" + name.Name; } else if (name.Namespace == XmlReservedNs.NsXQueryDataType) { return "xdt:" + name.Name; } else { return "{" + name.Namespace + "}" + name.Name; } } #region TypeFlags private enum TypeFlags { None = 0, IsNode = 1, IsAtomicValue = 2, IsNumeric = 4, } #endregion #region TypeCodeToFlags private static readonly TypeFlags[] s_typeCodeToFlags = { /* XmlTypeCode.None */ TypeFlags.IsNode | TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Item */ TypeFlags.None, /* XmlTypeCode.Node */ TypeFlags.IsNode, /* XmlTypeCode.Document */ TypeFlags.IsNode, /* XmlTypeCode.Element */ TypeFlags.IsNode, /* XmlTypeCode.Attribute */ TypeFlags.IsNode, /* XmlTypeCode.Namespace */ TypeFlags.IsNode, /* XmlTypeCode.ProcessingInstruction */ TypeFlags.IsNode, /* XmlTypeCode.Comment */ TypeFlags.IsNode, /* XmlTypeCode.Text */ TypeFlags.IsNode, /* XmlTypeCode.AnyAtomicType */ TypeFlags.IsAtomicValue, /* XmlTypeCode.UntypedAtomic */ TypeFlags.IsAtomicValue, /* XmlTypeCode.String */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Boolean */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Decimal */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Float */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Double */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Duration */ TypeFlags.IsAtomicValue, /* XmlTypeCode.DateTime */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Time */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Date */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GYearMonth */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GYear */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GMonthDay */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GDay */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GMonth */ TypeFlags.IsAtomicValue, /* XmlTypeCode.HexBinary */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Base64Binary */ TypeFlags.IsAtomicValue, /* XmlTypeCode.AnyUri */ TypeFlags.IsAtomicValue, /* XmlTypeCode.QName */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Notation */ TypeFlags.IsAtomicValue, /* XmlTypeCode.NormalizedString */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Token */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Language */ TypeFlags.IsAtomicValue, /* XmlTypeCode.NmToken */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Name */ TypeFlags.IsAtomicValue, /* XmlTypeCode.NCName */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Id */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Idref */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Entity */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Integer */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.NonPositiveInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.NegativeInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Long */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Int */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Short */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Byte */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.NonNegativeInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedLong */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedInt */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedShort */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedByte */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.PositiveInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.YearMonthDuration */ TypeFlags.IsAtomicValue, /* XmlTypeCode.DayTimeDuration */ TypeFlags.IsAtomicValue, }; private static readonly XmlTypeCode[] s_baseTypeCodes = { /* None */ XmlTypeCode.None, /* Item */ XmlTypeCode.Item, /* Node */ XmlTypeCode.Item, /* Document */ XmlTypeCode.Node, /* Element */ XmlTypeCode.Node, /* Attribute */ XmlTypeCode.Node, /* Namespace */ XmlTypeCode.Node, /* ProcessingInstruction */ XmlTypeCode.Node, /* Comment */ XmlTypeCode.Node, /* Text */ XmlTypeCode.Node, /* AnyAtomicType */ XmlTypeCode.Item, /* UntypedAtomic */ XmlTypeCode.AnyAtomicType, /* String */ XmlTypeCode.AnyAtomicType, /* Boolean */ XmlTypeCode.AnyAtomicType, /* Decimal */ XmlTypeCode.AnyAtomicType, /* Float */ XmlTypeCode.AnyAtomicType, /* Double */ XmlTypeCode.AnyAtomicType, /* Duration */ XmlTypeCode.AnyAtomicType, /* DateTime */ XmlTypeCode.AnyAtomicType, /* Time */ XmlTypeCode.AnyAtomicType, /* Date */ XmlTypeCode.AnyAtomicType, /* GYearMonth */ XmlTypeCode.AnyAtomicType, /* GYear */ XmlTypeCode.AnyAtomicType, /* GMonthDay */ XmlTypeCode.AnyAtomicType, /* GDay */ XmlTypeCode.AnyAtomicType, /* GMonth */ XmlTypeCode.AnyAtomicType, /* HexBinary */ XmlTypeCode.AnyAtomicType, /* Base64Binary */ XmlTypeCode.AnyAtomicType, /* AnyUri */ XmlTypeCode.AnyAtomicType, /* QName */ XmlTypeCode.AnyAtomicType, /* Notation */ XmlTypeCode.AnyAtomicType, /* NormalizedString */ XmlTypeCode.String, /* Token */ XmlTypeCode.NormalizedString, /* Language */ XmlTypeCode.Token, /* NmToken */ XmlTypeCode.Token, /* Name */ XmlTypeCode.Token, /* NCName */ XmlTypeCode.Name, /* Id */ XmlTypeCode.NCName, /* Idref */ XmlTypeCode.NCName, /* Entity */ XmlTypeCode.NCName, /* Integer */ XmlTypeCode.Decimal, /* NonPositiveInteger */ XmlTypeCode.Integer, /* NegativeInteger */ XmlTypeCode.NonPositiveInteger, /* Long */ XmlTypeCode.Integer, /* Int */ XmlTypeCode.Long, /* Short */ XmlTypeCode.Int, /* Byte */ XmlTypeCode.Short, /* NonNegativeInteger */ XmlTypeCode.Integer, /* UnsignedLong */ XmlTypeCode.NonNegativeInteger, /* UnsignedInt */ XmlTypeCode.UnsignedLong, /* UnsignedShort */ XmlTypeCode.UnsignedInt, /* UnsignedByte */ XmlTypeCode.UnsignedShort, /* PositiveInteger */ XmlTypeCode.NonNegativeInteger, /* YearMonthDuration */ XmlTypeCode.Duration, /* DayTimeDuration */ XmlTypeCode.Duration, }; private static readonly string[] s_typeNames = { /* None */ "none", /* Item */ "item", /* Node */ "node", /* Document */ "document", /* Element */ "element", /* Attribute */ "attribute", /* Namespace */ "namespace", /* ProcessingInstruction */ "processing-instruction", /* Comment */ "comment", /* Text */ "text", /* AnyAtomicType */ "xdt:anyAtomicType", /* UntypedAtomic */ "xdt:untypedAtomic", /* String */ "xs:string", /* Boolean */ "xs:boolean", /* Decimal */ "xs:decimal", /* Float */ "xs:float", /* Double */ "xs:double", /* Duration */ "xs:duration", /* DateTime */ "xs:dateTime", /* Time */ "xs:time", /* Date */ "xs:date", /* GYearMonth */ "xs:gYearMonth", /* GYear */ "xs:gYear", /* GMonthDay */ "xs:gMonthDay", /* GDay */ "xs:gDay", /* GMonth */ "xs:gMonth", /* HexBinary */ "xs:hexBinary", /* Base64Binary */ "xs:base64Binary", /* AnyUri */ "xs:anyUri", /* QName */ "xs:QName", /* Notation */ "xs:NOTATION", /* NormalizedString */ "xs:normalizedString", /* Token */ "xs:token", /* Language */ "xs:language", /* NmToken */ "xs:NMTOKEN", /* Name */ "xs:Name", /* NCName */ "xs:NCName", /* Id */ "xs:ID", /* Idref */ "xs:IDREF", /* Entity */ "xs:ENTITY", /* Integer */ "xs:integer", /* NonPositiveInteger */ "xs:nonPositiveInteger", /* NegativeInteger */ "xs:negativeInteger", /* Long */ "xs:long", /* Int */ "xs:int", /* Short */ "xs:short", /* Byte */ "xs:byte", /* NonNegativeInteger */ "xs:nonNegativeInteger", /* UnsignedLong */ "xs:unsignedLong", /* UnsignedInt */ "xs:unsignedInt", /* UnsignedShort */ "xs:unsignedShort", /* UnsignedByte */ "xs:unsignedByte", /* PositiveInteger */ "xs:positiveInteger", /* YearMonthDuration */ "xdt:yearMonthDuration", /* DayTimeDuration */ "xdt:dayTimeDuration", }; #endregion /// <summary> /// Implements an NxN bit matrix. /// </summary> private sealed class BitMatrix { private ulong[] _bits; /// <summary> /// Create NxN bit matrix, where N = count. /// </summary> public BitMatrix(int count) { Debug.Assert(count < 64, "BitMatrix currently only handles up to 64x64 matrix."); _bits = new ulong[count]; } // /// <summary> // /// Return the number of rows and columns in the matrix. // /// </summary> // public int Size { // get { return bits.Length; } // } // /// <summary> /// Get or set a bit in the matrix at position (index1, index2). /// </summary> public bool this[int index1, int index2] { get { Debug.Assert(index1 < _bits.Length && index2 < _bits.Length, "Index out of range."); return (_bits[index1] & ((ulong)1 << index2)) != 0; } set { Debug.Assert(index1 < _bits.Length && index2 < _bits.Length, "Index out of range."); if (value == true) { _bits[index1] |= (ulong)1 << index2; } else { _bits[index1] &= ~((ulong)1 << index2); } } } /// <summary> /// Strongly typed indexer. /// </summary> public bool this[XmlTypeCode index1, XmlTypeCode index2] { get { return this[(int)index1, (int)index2]; } // set { // this[(int)index1, (int)index2] = value; // } } } } }
using System; using System.Xml; using System.Collections; using System.Web; using System.Net; using System.IO; using System.Text; using ICSharpCode.SharpZipLib.BZip2; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using ICSharpCode.SharpZipLib.GZip; namespace PSWinCom.Gateway.MMS.Client { /// <summary> /// MMS Client implementation for PSWinCom MMS Gateway /// </summary> public class MMSClient { #region Nested Message collection class public class MessageCollection : DictionaryBase { public MessageCollection() : base() { } public MMSMessage this[int key] { get { return( (MMSMessage) Dictionary[key] ); } set { Dictionary[key] = value; } } public ICollection Keys { get { return( Dictionary.Keys ); } } public ICollection Values { get { return( Dictionary.Values ); } } public void Add(int key, MMSMessage value) { Dictionary.Add(key, value); } public bool Contains(int key) { return( Dictionary.Contains(key)); } public void Remove(int key) { Dictionary.Remove(key); } } #endregion #region Nested Delivery Report collection class public class DeliveryReportCollection : DictionaryBase { public DeliveryReportCollection() : base() { } public DeliveryReport this[int key] { get { return( (DeliveryReport) Dictionary[key] ); } set { Dictionary[key] = value; } } public ICollection Keys { get { return( Dictionary.Keys ); } } public ICollection Values { get { return( Dictionary.Values ); } } public void Add(int key, DeliveryReport value) { Dictionary.Add(key, value); } public bool Contains(int key) { return( Dictionary.Contains(key)); } public void Remove(int key) { Dictionary.Remove(key); } } #endregion #region Nested Resolver public class XmlLocalResolver : XmlUrlResolver { override public object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { // Force same folder as assembly int i = absoluteUri.AbsolutePath.LastIndexOf("/"); Uri localUri = null; if(i>0) localUri = new Uri(AppDomain.CurrentDomain.BaseDirectory + absoluteUri.AbsolutePath.Substring(i)); else localUri = absoluteUri; return base.GetEntity(localUri, role, ofObjectToReturn); } } public class XmlEmbeddedResourceResolver : XmlResolver { private XmlResolver fallbackResolver = new XmlUrlResolver(); private ICredentials credentials; public override ICredentials Credentials { set { this.credentials = value; } } public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { int slashIndex = absoluteUri.LocalPath.LastIndexOf('\\'); String resourcePath = absoluteUri.LocalPath.Substring(slashIndex + 1); Object resourceStream = GetType().Assembly.GetManifestResourceStream("PSWinCom.Gateway.MMS.Client." + resourcePath); if (resourceStream == null) resourceStream = fallbackResolver.GetEntity( absoluteUri, role, ofObjectToReturn); return resourceStream; } } #endregion private string _Username; private string _Password; private string _PrimaryGateway; private string _SecondaryGateway; private string _SessionData; private string _AffiliateProgram; private int _ConnectTimeout; private IWebProxy _Proxy; private bool _BulkWithIdenticalContent; /// <summary> /// Collection of outgoing Message objects. Add your Message objects to this collection before /// sending the messages. /// </summary> public MessageCollection Messages; /// <summary> /// Collection of incoming Message objects. This collection will contain the received messages /// after running HandleIncomingMessages. The collection is emptied by the HandleIncomingMessages() method. /// </summary> public MessageCollection ReceivedMessages; /// <summary> /// Collection of received DeliveryReport objects. This collection will contain the received delivery reports /// after running HandleIncomingMessages. The collection is emptied by the HandleIncomingMessages() method. /// </summary> public DeliveryReportCollection DeliveryReports; #region Accessors /// <summary> /// Username on MMS Gateway /// </summary> public string Username { get { return _Username; } set { _Username = value; } } /// <summary> /// Password on MMS Gateway /// </summary> public string Password { get { return _Password; } set { _Password = value; } } /// <summary> /// PSWinCom MMS Gateway Primary address /// </summary> public string PrimaryGateway { get { return _PrimaryGateway; } set { _PrimaryGateway = value; } } /// <summary> /// PSWinCom MMS Gateway Secondary address /// </summary> public string SecondaryGateway { get { return _SecondaryGateway; } set { _SecondaryGateway = value; } } /// <summary> /// SessionData. Leave empty if not required. /// </summary> public string SessionData { get { return _SessionData; } set { _SessionData = value; } } /// <summary> /// Affiliate program identificator. Leave empty if not required. /// </summary> public string AffiliateProgram { get { return _AffiliateProgram; } set { _AffiliateProgram = value; } } /// <summary> /// Set IWebProxy to be used when sending messages. Only required if you access internet through a Proxy. /// </summary> public IWebProxy Proxy { get { return _Proxy; } set { _Proxy = value; } } /// <summary> /// If this property is set, the MMSClient will send the content to the MMS Gateway only once per session. That /// will result in substantial lower transmission time for large sessions. When sending bulk MMS with identical /// content you should therefore set this property to true. Default value is false. /// </summary> public bool BulkWithIdenticalContent { get { return _BulkWithIdenticalContent; } set { _BulkWithIdenticalContent = value; } } #endregion /// <summary> /// Default constructor /// </summary> public MMSClient() { Messages = new MessageCollection(); ReceivedMessages = new MessageCollection(); DeliveryReports = new DeliveryReportCollection(); _Username = null; _Password = null; _PrimaryGateway = null; _SecondaryGateway = null; _ConnectTimeout = 10; _BulkWithIdenticalContent = false; } /// <summary> /// Send all messages in the Messages collection. This operation will block while communicating /// with the Gateway. After it has been completed, the MMSMessage objects in the Messages collection /// is updated with the Status, (and if applicable, also the Reference or FailedReason properties) /// </summary> public void SendMessages() { XmlDocument doc = GetDocumentXml(); XmlDocument docResponse = HttpPost(doc, PrimaryGateway); CheckResponse(docResponse); } /// <summary> /// Reads Xml from given stream and retrieves incoming messages or delivery reports /// within the XML document. The Messages or DeliveryReport are stored in the IncomingMessages /// or DeliveryReports collection. /// </summary> /// <param name="inStream"></param> /// <param name="outStream"></param> public void HandleIncomingMessages(Stream inStream, Stream outStream) { ReceivedMessages.Clear(); DeliveryReports.Clear(); XmlDocument docRequest = new XmlDocument(); XmlEmbeddedResourceResolver res = new XmlEmbeddedResourceResolver(); docRequest.XmlResolver = res; docRequest.Load(inStream); XmlDocument docResponse = CheckRequest(docRequest); string sResponse = "<?xml version=\"1.0\"?>\n" + docResponse.OuterXml; StreamWriter sw = new StreamWriter(outStream, System.Text.Encoding.GetEncoding("ISO-8859-1")); sw.Write(sResponse); sw.Flush(); outStream.Flush(); } /// <summary> /// Build XmlDocument with messages to send. /// </summary> /// <returns>XmlDocument according to DTD for SMS Gateway</returns> private XmlDocument GetDocumentXml() { XmlDocument doc = new XmlDocument(); XmlElement elmSession = doc.CreateElement("SESSION"); elmSession.AppendChild(CreateElement(doc, "CLIENT", _Username)); elmSession.AppendChild(CreateElement(doc, "PW", _Password)); if(_AffiliateProgram != null && _AffiliateProgram.Length > 0) elmSession.AppendChild(CreateElement(doc, "AP", _AffiliateProgram)); if(_SessionData != null && _SessionData.Length > 0) elmSession.AppendChild(CreateElement(doc, "SD", _SessionData)); XmlElement elmMsgList = doc.CreateElement("MSGLST"); bool bFirstElement = true; foreach(int i in Messages.Keys) { if(_BulkWithIdenticalContent && !bFirstElement) elmMsgList.AppendChild(GetMessageXml(doc, Messages[i], i, false)); else elmMsgList.AppendChild(GetMessageXml(doc, Messages[i], i, true)); bFirstElement = false; } elmSession.AppendChild(elmMsgList); doc.AppendChild(elmSession); return doc; } /// <summary> /// Build Xml for a particular message /// </summary> /// <param name="doc">Root Xml Document</param> /// <param name="m">Message object to transform</param> /// <param name="id">index in collection</param> /// <returns>Message as XmlElement</returns> private XmlElement GetMessageXml(XmlDocument doc, MMSMessage m, int id, bool includeContent) { XmlElement elmMsg = doc.CreateElement("MSG"); elmMsg.AppendChild(CreateElement(doc, "ID", id.ToString())); if(m.Network != null && m.Network.Length > 0) elmMsg.AppendChild(CreateElement(doc, "NET", m.Network)); elmMsg.AppendChild(CreateElement(doc, "TARIFF", m.Tariff.ToString())); elmMsg.AppendChild(CreateElement(doc, "TEXT", m.Subject)); elmMsg.AppendChild(CreateElement(doc, "OP", "13")); if(m.RequestReceipt) elmMsg.AppendChild(CreateElement(doc, "RCPREQ", "Y")); elmMsg.AppendChild(CreateElement(doc, "SND", m.SenderNumber)); elmMsg.AppendChild(CreateElement(doc, "RCV", m.ReceiverNumber)); if(includeContent) elmMsg.AppendChild(CreateElement(doc, "MMSFILE", Convert.ToBase64String(m.GetCompressed()))); return elmMsg; } /// <summary> /// Create a XmlElement with given name and value /// </summary> /// <param name="doc">Xml Document context</param> /// <param name="name">Name of element</param> /// <param name="val">Content/value</param> /// <returns>XmlElement as requested</returns> private XmlElement CreateElement(XmlDocument doc, string name, string val) { XmlElement elm = doc.CreateElement(name); if(val != null) elm.InnerText = val; return elm; } /// <summary> /// Check response from Gateway, update Message collection with status /// </summary> /// <param name="doc">XmlDocument with response from Gateway</param> private void CheckResponse(XmlDocument doc) { // Was login ok? string login = GetNodeValue(doc, "SESSION/LOGON"); if(login != null) { if(!login.Equals("OK")) { // Not a valid login, fail all msgs foreach(int i in Messages.Keys) Messages[i]._Status = MessageStatus.Failed; // Throw an appropriate exception string reason = GetNodeValue(doc, "SESSION/REASON"); if(reason != null) throw new MMSException(reason); else throw new MMSException("General error while processing response from SMS Gateway"); } else { // Login OK XmlNode nodMsgList = doc.SelectSingleNode("SESSION/MSGLST"); if(nodMsgList != null) { // Loop through msg list foreach(XmlNode n in nodMsgList.ChildNodes) { if(n.NodeType == XmlNodeType.Element && n.Name.Equals("MSG")) { string id = GetNodeValue(n, "ID"); int i = int.Parse(id); string status = GetNodeValue(n, "STATUS"); if(status.Equals("OK")) { Messages[i]._Status = MessageStatus.Sent; Messages[i]._Reference = GetNodeValue(n, "REF"); } else { string info = GetNodeValue(n, "INFO"); Messages[i]._Status = MessageStatus.Failed; Messages[i]._FailedReason = info; } } } } } } } /// <summary> /// Check request for IncomingMessages/DeliveryReports from Gateway, /// update Message collection or DeliveryReport collection /// </summary> /// <param name="doc">XmlDocument containing request from gateway</param> private XmlDocument CheckRequest(XmlDocument doc) { XmlDocument docResponse = new XmlDocument(); XmlNode nodMsgList = doc.SelectSingleNode("MSGLST"); if(nodMsgList != null) { // Loop through msg list foreach(XmlNode n in nodMsgList.ChildNodes) { if(n.NodeType == XmlNodeType.Element && n.Name.Equals("MSG")) { string id = GetNodeValue(n, "ID"); int i = int.Parse(id); // is this delivery report or incoming msg? string state = GetNodeValue(n, "STATE"); if(state == null) { // Incoming Message ReceivedMessages.Add(i, new MMSMessage()); ReceivedMessages[i].Subject = GetNodeValue(n, "TEXT"); ReceivedMessages[i].SenderNumber = GetNodeValue(n, "SND"); ReceivedMessages[i].ReceiverNumber = GetNodeValue(n, "RCV"); ReceivedMessages[i].Network = GetNodeValue(n, "NET"); ReceivedMessages[i]._Address = GetNodeValue(n, "ADDRESS"); ReceivedMessages[i].Parts = GetParts(GetNodeValue(n, "MMSFILE")); } else { DeliveryReports.Add(i, new DeliveryReport()); DeliveryReports[i].State = GetNodeValue(n, "STATE"); DeliveryReports[i].Reference = GetNodeValue(n, "REF"); DeliveryReports[i].ReceiverNumber = GetNodeValue(n, "RCV"); string sDeliveryTime = GetNodeValue(n, "DELIVERYTIME"); if(sDeliveryTime!= null && sDeliveryTime.Length >0) DeliveryReports[i].DeliveredDate = Convert.ToDateTime(sDeliveryTime); } } } // Build Response XmlElement elmMsgList = docResponse.CreateElement("MSGLST"); foreach(int i in ReceivedMessages.Keys) { XmlElement elmMsg = docResponse.CreateElement("MSG"); elmMsg.AppendChild(CreateElement(docResponse, "ID", i.ToString())); elmMsg.AppendChild(CreateElement(docResponse, "STATUS", "OK")); elmMsgList.AppendChild(elmMsg); } foreach(int i in DeliveryReports.Keys) { XmlElement elmMsg = docResponse.CreateElement("MSG"); elmMsg.AppendChild(CreateElement(docResponse, "ID", i.ToString())); elmMsg.AppendChild(CreateElement(docResponse, "STATUS", "OK")); elmMsgList.AppendChild(elmMsg); } docResponse.AppendChild(elmMsgList); } return docResponse; } /// <summary> /// Return value of given node as by xpath expression, or null if not found /// </summary> /// <param name="doc">XmlNode to search from</param> /// <param name="xpath">XPath expression of desired node</param> /// <returns>Content of node as string or null if not found</returns> private string GetNodeValue(XmlNode doc, string xpath) { XmlNode node = doc.SelectSingleNode(xpath); if(node != null) return node.InnerText; else return null; } /// <summary> /// Decode base 64 data, unzip binary stream and retrieve each part /// </summary> /// <param name="base64data">Base 64 encoded data containing MMS message in ZIP file format</param> /// <returns></returns> private MMSMessage.MessagePartCollection GetParts(string base64data) { MMSMessage.MessagePartCollection coll = new MMSMessage.MessagePartCollection(); MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64data)); // Extract files and add them ZipInputStream s = new ZipInputStream(ms); ZipEntry theEntry; int i = 0; while ((theEntry = s.GetNextEntry()) != null) { MMSMessagePart part = new MMSMessagePart(); part.PartId = i; string fileName = theEntry.Name; if (fileName != String.Empty) { part.Name = fileName; //Read Part into memorystream int size = 2048; int len = 0; MemoryStream mspart = new MemoryStream(size); byte[] partData = new byte[size]; while (true) { size = s.Read(partData, 0, partData.Length); len += size; if (size > 0) { mspart.Write(partData, 0, size); } else { break; } } part.Data = new byte[len]; mspart.Position = 0; // Reset position and read into byte buffer mspart.Read(part.Data, 0, len); mspart.Close(); } coll.Add(i, part); i++; } s.Close(); return coll; } /// <summary> /// Send a HTTP Post request /// </summary> /// <param name="doc">XmlDocument to send</param> /// <param name="url">Destination URL</param> /// <returns>XmlDocument with response</returns> private XmlDocument HttpPost(XmlDocument doc, string url) { try { HttpWebRequest httpReq = (HttpWebRequest) WebRequest.Create(url); httpReq.ContentType = "application/xml"; httpReq.Timeout = 1000 * _ConnectTimeout; httpReq.Method = "POST"; if(_Proxy == null) _Proxy =(IWebProxy)httpReq.Proxy; else httpReq.Proxy = _Proxy; httpReq.KeepAlive = false; UTF8Encoding encoding=new UTF8Encoding(); byte[] bytes=encoding.GetBytes("<?xml version=\"1.0\"?>" + doc.OuterXml + "\n"); Encoding ISO8859 = Encoding.GetEncoding("ISO-8859-1"); Encoding UTF8 = Encoding.GetEncoding("UTF-8"); bytes = Encoding.Convert(UTF8, ISO8859 ,bytes); httpReq.ContentLength = bytes.Length+1; HttpWebResponse httpResponse = null; XmlDocument xmlResult = null; try { Stream dataStream = null; try { dataStream = httpReq.GetRequestStream(); dataStream.Write(bytes,0,bytes.Length); dataStream.WriteByte(0x00); } finally { if(dataStream != null) dataStream.Close(); } httpResponse = (HttpWebResponse) httpReq.GetResponse(); /* byte[] buffer = new byte[2000]; Stream str = httpResponse.GetResponseStream(); int i = str.Read(buffer, 0, 2000); Encoding enc = Encoding.GetEncoding("ISO-8859-1"); string xml = enc.GetString(buffer, 0, i); */ XmlTextReader xmlResultReader = new XmlTextReader(httpResponse.GetResponseStream()); xmlResult = new XmlDocument(); xmlResult.Load(xmlResultReader); string s = xmlResult.OuterXml; } catch(Exception e) { String error = e.Message; throw; } finally { if(httpResponse != null) httpResponse.Close(); } return xmlResult; } catch(Exception) { throw; } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; using DotSpatial.Data; namespace DotSpatial.Symbology.Forms { /// <summary> /// BreakSliderGraph /// </summary> [DefaultEvent("SliderMoved")] public class BreakSliderGraph : Control { #region Fields private readonly ContextMenu _contextMenu; private readonly BarGraph _graph; private readonly Statistics _statistics; private Color _breakColor; private bool _dragCursor; private string _fieldName; private bool _isDragging; private bool _isRaster; private string _normalizationField; private IRaster _raster; private IRasterLayer _rasterLayer; private IRasterSymbolizer _rasterSymbolizer; private IFeatureScheme _scheme; private Color _selectedBreakColor; private BreakSlider _selectedSlider; private IAttributeSource _source; private IDataTable _table; private List<double> _values; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BreakSliderGraph"/> class. /// </summary> public BreakSliderGraph() { _graph = new BarGraph(Width, Height); MaximumSampleSize = 10000; Breaks = new List<BreakSlider>(); _selectedBreakColor = Color.Red; _breakColor = Color.Blue; TitleFont = new Font("Arial", 20, FontStyle.Bold); BorderStyle = BorderStyle.Fixed3D; _contextMenu = new ContextMenu(); _contextMenu.MenuItems.Add("Reset Zoom", ResetZoomClicked); _contextMenu.MenuItems.Add("Zoom To Categories", CategoryZoomClicked); _statistics = new Statistics(); } #endregion #region Events /// <summary> /// Occurs after the slider has been completely repositioned. /// </summary> public event EventHandler<BreakSliderEventArgs> SliderMoved; /// <summary> /// Occurs when manual break sliding begins so that the mode can be /// switched to manual, rather than showing equal breaks or something. /// </summary> public event EventHandler<BreakSliderEventArgs> SliderMoving; /// <summary> /// Occurs when a click in a range changes the slider that is selected. /// </summary> public event EventHandler<BreakSliderEventArgs> SliderSelected; /// <summary> /// Occurs after the statistics have been re-calculated. /// </summary> public event EventHandler<StatisticalEventArgs> StatisticsUpdated; #endregion #region Properties /// <summary> /// Gets or sets the attribute source. /// </summary> public IAttributeSource AttributeSource { get { return _source; } set { _source = value; UpdateBins(); } } /// <summary> /// Gets or sets the border style for this control. /// </summary> public BorderStyle BorderStyle { get; set; } /// <summary> /// Gets or sets the color to use for the moveable breaks. /// </summary> public Color BreakColor { get { return _breakColor; } set { _breakColor = value; if (Breaks == null) return; foreach (BreakSlider slider in Breaks) { slider.Color = value; } } } /// <summary> /// Gets the list of breaks that are currently part of this graph. /// </summary> public List<BreakSlider> Breaks { get; } /// <summary> /// Gets or sets the color to use when a break is selected /// </summary> public Color BreakSelectedColor { get { return _selectedBreakColor; } set { _selectedBreakColor = value; if (Breaks == null) return; foreach (BreakSlider slider in Breaks) { slider.SelectColor = value; } } } /// <summary> /// Gets or sets the string field name. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Fieldname { get { return _fieldName; } set { _fieldName = value; UpdateBins(); } } /// <summary> /// Gets or sets the font color. /// </summary> [Category("Appearance")] [Description("Gets or sets the color for the axis labels")] public Color FontColor { get { if (_graph != null) return _graph.Font.Color; return Color.Black; } set { if (_graph != null) _graph.Font.Color = value; } } /// <summary> /// Gets or sets the method to use when breaks are calculated or reset. /// </summary> public IntervalMethod IntervalMethod { get { if (_scheme?.EditorSettings == null) return IntervalMethod.EqualInterval; return _scheme.EditorSettings.IntervalMethod; } set { if (_scheme?.EditorSettings == null) return; _scheme.EditorSettings.IntervalMethod = value; UpdateBreaks(); } } /// <summary> /// Gets or sets a value indicating whether or not count values should be drawn with /// heights that are proportional to the logarithm of the count, instead of the count itself. /// </summary> public bool LogY { get { return _graph != null && _graph.LogY; } set { if (_graph != null) { _graph.LogY = value; Invalidate(); } } } /// <summary> /// Gets or sets the maximum sample size to use when calculating statistics. /// The default is 10000. /// </summary> [Category("Behavior")] [Description("Gets or sets the maximum sample size to use when calculating statistics.")] public int MaximumSampleSize { get; set; } /// <summary> /// Gets or sets the minimum height. Very small counts frequently dissappear next to big counts. One strategey is to use a /// minimum height, so that the difference between 0 and 1 is magnified on the columns. /// </summary> public int MinHeight { get { return _graph?.MinHeight ?? 20; } set { if (_graph != null) _graph.MinHeight = value; } } /// <summary> /// Gets or sets the string normalization field /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string NormalizationField { get { return _normalizationField; } set { _normalizationField = value; UpdateBins(); } } /// <summary> /// Gets or sets the number of columns. Setting this will recalculate the bins. /// </summary> [Category("Behavior")] [Description("Gets or sets the number of columns representing the data histogram")] public int NumColumns { get { if (_graph == null) return 0; return _graph.NumColumns; } set { if (_graph == null) return; _graph.NumColumns = value; FillBins(); UpdateBreaks(); Invalidate(); } } /// <summary> /// Gets or sets the raster layer. This will also force this control to use /// the raster for calculations, rather than the dataset. /// </summary> public IRasterLayer RasterLayer { get { return _rasterLayer; } set { _rasterLayer = value; if (value == null) return; _isRaster = true; _raster = _rasterLayer.DataSet; _rasterSymbolizer = _rasterLayer.Symbolizer; ResetExtents(); UpdateBins(); } } /// <summary> /// Gets or sets the scheme that is currently being used to symbolize the values. /// Setting this automatically updates the graph extents to the statistical bounds /// of the scheme. /// </summary> public IFeatureScheme Scheme { get { return _scheme; } set { _scheme = value; _isRaster = false; ResetExtents(); UpdateBreaks(); } } /// <summary> /// Gets or sets a value indicating whether the mean will be shown as a blue dotted line. /// </summary> [Category("Appearance")] [Description("Boolean, if this is true, the mean will be shown as a blue dotted line.")] public bool ShowMean { get { return _graph != null && _graph.ShowMean; } set { if (_graph != null) { _graph.ShowMean = value; Invalidate(); } } } /// <summary> /// Gets or sets a value indicating whether the integral standard deviations from the mean will be drawn /// as red dotted lines. /// </summary> [Category("Appearance")] [Description("Boolean, if this is true, the integral standard deviations from the mean will be drawn as red dotted lines.")] public bool ShowStandardDeviation { get { return _graph != null && _graph.ShowStandardDeviation; } set { if (_graph != null) { _graph.ShowStandardDeviation = value; Invalidate(); } } } /// <summary> /// Gets the statistics that have been currently calculated for this graph. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Statistics Statistics { get { if (_isRaster) { return _statistics; } return _scheme?.Statistics; } } /// <summary> /// Gets or sets the data Table for which the statistics should be applied /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IDataTable Table { get { return _table; } set { _table = value; UpdateBins(); } } /// <summary> /// Gets or sets the title of the graph. /// </summary> [Category("Appearance")] [Description("Gets or sets the title of the graph.")] public string Title { get { return _graph?.Title; } set { if (_graph != null) _graph.Title = value; } } /// <summary> /// Gets or sets the color to use for the graph title. /// </summary> [Category("Appearance")] [Description("Gets or sets the color to use for the graph title.")] public Color TitleColor { get { return _graph?.TitleFont.Color ?? Color.Black; } set { if (_graph != null) _graph.TitleFont.Color = value; } } /// <summary> /// Gets or sets the font to use for the graph title /// </summary> [Category("Appearance")] [Description("Gets or sets the font to use for the graph title.")] public Font TitleFont { get { return _graph?.TitleFont.GetFont(); } set { _graph?.TitleFont.SetFont(value); } } #endregion #region Methods /// <summary> /// When the mouse wheel event occurs, this forwards the event to this control. /// </summary> /// <param name="delta">The delta.</param> /// <param name="x">The x.</param> public void DoMouseWheel(int delta, float x) { double val = _graph.GetValue(x); if (delta > 0) { _graph.Minimum = _graph.Minimum + ((val - _graph.Minimum) / 2); _graph.Maximum = _graph.Maximum - ((_graph.Maximum - val) / 2); } else { _graph.Minimum = _graph.Minimum - (val - _graph.Minimum); _graph.Maximum = _graph.Maximum + (_graph.Maximum - val); } if (_isRaster) { if (_graph.Minimum < _rasterSymbolizer.Scheme.Statistics.Minimum) _graph.Minimum = _rasterSymbolizer.Scheme.Statistics.Minimum; if (_graph.Maximum > _rasterSymbolizer.Scheme.Statistics.Maximum) _graph.Maximum = _rasterSymbolizer.Scheme.Statistics.Maximum; } else { if (_graph.Minimum < _scheme.Statistics.Minimum) _graph.Minimum = _scheme.Statistics.Minimum; if (_graph.Maximum > _scheme.Statistics.Maximum) _graph.Maximum = _scheme.Statistics.Maximum; } FillBins(); UpdateBreaks(); Invalidate(); } /// <summary> /// Returns the BreakSlider that corresponds to the specified mouse position, where /// the actual handle and divider represent the maximum of that range. /// </summary> /// <param name="location">The location, which can be anywhere to the left of the slider but to the /// right of any other sliders.</param> /// <returns>The BreakSlider that covers the range that contains the location, or null.</returns> public BreakSlider GetBreakAt(Point location) { if (location.X < 0) return null; foreach (BreakSlider slider in Breaks) { if (slider.Position < location.X) continue; return slider; } return null; } /// <summary> /// Resets the breaks using the current settings, and generates a new set of /// categories using the given interval method. /// </summary> /// <param name="handler">The progress handler.</param> public void ResetBreaks(ICancelProgressHandler handler) { if (_fieldName == null) return; if (_scheme?.EditorSettings == null) return; if (_source != null) { _scheme.CreateCategories(_source, handler); } else { if (_table == null) return; _scheme.CreateCategories(_table); } ResetZoom(); } /// <summary> /// Given a scheme, this resets the graph extents to the statistical bounds. /// </summary> public void ResetExtents() { if (_graph == null) return; Statistics stats; if (_isRaster) { if (_raster == null) return; stats = _rasterSymbolizer.Scheme.Statistics; } else { if (_scheme == null) return; stats = _scheme.Statistics; } _graph.Minimum = stats.Minimum; _graph.Maximum = stats.Maximum; _graph.Mean = stats.Mean; _graph.StandardDeviation = stats.StandardDeviation; } /// <summary> /// Selects one of the specific breaks. /// </summary> /// <param name="slider">The break slider.</param> public void SelectBreak(BreakSlider slider) { if (_selectedSlider != null) _selectedSlider.Selected = false; _selectedSlider = slider; if (_selectedSlider != null) { _selectedSlider.Selected = true; _graph.SelectedRange = _selectedSlider.Range; } } /// <summary> /// Given a scheme, this will build the break list to match approximately. This does not /// force the interval method to build a new scheme. /// </summary> public void UpdateBreaks() { if (_isRaster) { UpdateRasterBreaks(); return; } if (_scheme == null) return; IFeatureCategory selectedCat = null; if (_selectedSlider != null) selectedCat = _selectedSlider.Category as IFeatureCategory; Breaks.Clear(); Statistics stats = _scheme.Statistics; Rectangle gb = _graph.GetGraphBounds(); _graph.ColorRanges.Clear(); foreach (IFeatureCategory category in _scheme.GetCategories()) { ColorRange cr = new ColorRange(category.GetColor(), category.Range); _graph.ColorRanges.Add(cr); BreakSlider bs = new BreakSlider(gb, _graph.Minimum, _graph.Maximum, cr) { Color = _breakColor, SelectColor = _selectedBreakColor }; if (selectedCat != null && category == selectedCat) { bs.Selected = true; _selectedSlider = bs; _graph.SelectedRange = cr; } bs.Value = category.Maximum != null ? double.Parse(category.Maximum.ToString()) : stats.Maximum; bs.Category = category; Breaks.Add(bs); } Breaks.Sort(); // Moving a break generally affects both a maximum and a minimum. // Point to the next category to actuate that. for (int i = 0; i < Breaks.Count - 1; i++) { Breaks[i].NextCategory = Breaks[i + 1].Category; // We use the maximums to set up breaks. Minimums should simply // be set to work with the maximums of the previous category. Breaks[i + 1].Category.Minimum = Breaks[i].Value; } if (Breaks.Count == 0) return; int breakIndex = 0; BreakSlider nextSlider = Breaks[breakIndex]; int count = 0; if (_graph?.Bins == null) return; foreach (double value in _values) { if (value < nextSlider.Value) { count++; continue; } nextSlider.Count = count; while (value > nextSlider.Value) { breakIndex++; if (breakIndex >= Breaks.Count) { break; } nextSlider = Breaks[breakIndex]; } count = 0; } } /// <summary> /// Given a break slider's new position, this will update the category related to that break. /// </summary> /// <param name="slider">The break slider.</param> public void UpdateCategory(BreakSlider slider) { slider.Category.Maximum = slider.Value; slider.Category.ApplyMinMax(_scheme.EditorSettings); int index = Breaks.IndexOf(slider); if (index < 0) return; if (index < Breaks.Count - 1) { Breaks[index + 1].Category.Minimum = slider.Value; Breaks[index + 1].Category.ApplyMinMax(_scheme.EditorSettings); } } /// <summary> /// Updates the raster breaks. /// </summary> public void UpdateRasterBreaks() { if (_rasterLayer == null) return; IColorCategory selectedBrk = null; if (_selectedSlider != null) selectedBrk = _selectedSlider.Category as IColorCategory; Breaks.Clear(); Statistics stats = _rasterSymbolizer.Scheme.Statistics; Rectangle gb = _graph.GetGraphBounds(); _graph.ColorRanges.Clear(); foreach (IColorCategory category in _rasterSymbolizer.Scheme.Categories) { ColorRange cr = new ColorRange(category.LowColor, category.Range); _graph.ColorRanges.Add(cr); BreakSlider bs = new BreakSlider(gb, _graph.Minimum, _graph.Maximum, cr) { Color = _breakColor, SelectColor = _selectedBreakColor }; if (selectedBrk != null && category == selectedBrk) { bs.Selected = true; _selectedSlider = bs; _graph.SelectedRange = cr; } bs.Value = category.Maximum != null ? double.Parse(category.Maximum.ToString()) : stats.Maximum; bs.Category = category; Breaks.Add(bs); } Breaks.Sort(); // Moving a break generally affects both a maximum and a minimum. // Point to the next category to actuate that. for (int i = 0; i < Breaks.Count - 1; i++) { Breaks[i].NextCategory = Breaks[i + 1].Category; // We use the maximums to set up breaks. Minimums should simply // be set to work with the maximums of the previous category. // _breaks[i + 1].Category.Minimum = _breaks[i].Value; REMOVED BY jany_ (2015-07-07) Don't set minimum, because that changes the minimum of the rasters category which causes the colors to change when saving in RasterColorControl without making changes or for example only applying opacity without wanting to use statistics. } if (Breaks.Count == 0) return; int breakIndex = 0; BreakSlider nextSlider = Breaks[breakIndex]; int count = 0; if (_graph?.Bins == null) return; foreach (double value in _values) { if (value < nextSlider.Value) { count++; continue; } nextSlider.Count = count; while (value > nextSlider.Value) { breakIndex++; if (breakIndex >= Breaks.Count) { break; } nextSlider = Breaks[breakIndex]; } count = 0; } } /// <summary> /// Zooms so that the minimum is the minimum of the lowest category or else the /// minimum of the extents, and the maximum is the maximum of the largest category /// or else the maximum of the statistics. /// </summary> public void ZoomToCategoryRange() { if (_graph == null) return; Statistics stats; double? min; double? max; if (_isRaster) { if (_raster == null) return; stats = _rasterSymbolizer.Scheme.Statistics; min = _rasterSymbolizer.Scheme.Categories[0].Minimum; max = _rasterSymbolizer.Scheme.Categories[_rasterSymbolizer.Scheme.Categories.Count - 1].Maximum; } else { if (_scheme == null) return; stats = _scheme.Statistics; var cats = _scheme.GetCategories().ToList(); min = cats.First().Minimum; max = cats.Last().Maximum; } _graph.Minimum = (min == null || min.Value < stats.Minimum) ? stats.Minimum : min.Value; _graph.Maximum = (max == null || max.Value > stats.Maximum) ? stats.Maximum : max.Value; FillBins(); UpdateBreaks(); Invalidate(); } /// <summary> /// Handles disposing to release unmanaged memory. /// </summary> /// <param name="disposing">Indicates whether managed resources should be disposed.</param> protected override void Dispose(bool disposing) { _graph?.Dispose(); base.Dispose(disposing); } /// <summary> /// Occurs during drawing. /// </summary> /// <param name="g">The graphics object used for drawing.</param> /// <param name="clip">The clip rectangle.</param> protected virtual void OnDraw(Graphics g, Rectangle clip) { if (Height <= 1 || Width <= 1) return; // Draw text first because the text is used to auto-fit the remaining graph. _graph.Draw(g, clip); if (BorderStyle == BorderStyle.Fixed3D) { g.DrawLine(Pens.White, 0, Height - 1, Width - 1, Height - 1); g.DrawLine(Pens.White, Width - 1, 0, Width - 1, Height - 1); g.DrawLine(Pens.Gray, 0, 0, 0, Height - 1); g.DrawLine(Pens.Gray, 0, 0, Width - 1, 0); } if (BorderStyle == BorderStyle.FixedSingle) { g.DrawRectangle(Pens.Black, 0, 0, Width - 1, Height - 1); } if (Breaks == null) return; Rectangle gb = _graph.GetGraphBounds(); foreach (BreakSlider slider in Breaks) { slider.Setup(gb, _graph.Minimum, _graph.Maximum); if (slider.Bounds.IntersectsWith(clip)) slider.Draw(g); } } /// <summary> /// Occurs when the mose down occurs. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseDown(MouseEventArgs e) { Focus(); if (e.Button == MouseButtons.Right) { _contextMenu.Show(this, e.Location); return; } foreach (BreakSlider slider in Breaks) { if (!slider.Bounds.Contains(e.Location) && !slider.HandleBounds.Contains(e.Location)) continue; // not sure if this works right. Hopefully, just the little rectangles form a double region. Region rg = new Region(); if (_selectedSlider != null) { rg.Union(_selectedSlider.Bounds); _selectedSlider.Selected = false; } _selectedSlider = slider; slider.Selected = true; rg.Union(_selectedSlider.Bounds); Invalidate(rg); _isDragging = true; OnSliderMoving(); return; } if (_selectedSlider != null) _selectedSlider.Selected = false; _selectedSlider = null; base.OnMouseDown(e); } /// <summary> /// Handles the mouse move event. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseMove(MouseEventArgs e) { if (_isDragging) { Region rg = new Region(); Rectangle gb = _graph.GetGraphBounds(); if (_selectedSlider != null) { rg.Union(_selectedSlider.Bounds); int x = e.X; int index = Breaks.IndexOf(_selectedSlider); if (x > gb.Right) x = gb.Right; if (x < gb.Left) x = gb.Left; if (index > 0) { if (x < Breaks[index - 1].Position + 2) x = (int)Breaks[index - 1].Position + 2; } if (index < Breaks.Count - 1) { if (x > Breaks[index + 1].Position - 2) x = (int)Breaks[index + 1].Position - 2; } _selectedSlider.Position = x; rg.Union(_selectedSlider.Bounds); Invalidate(rg); } return; } bool overSlider = false; foreach (BreakSlider slider in Breaks) { if (slider.Bounds.Contains(e.Location) || slider.HandleBounds.Contains(e.Location)) { overSlider = true; } } if (_dragCursor && !overSlider) { Cursor = Cursors.Arrow; _dragCursor = false; } if (!_dragCursor && overSlider) { _dragCursor = true; Cursor = Cursors.SizeWE; } base.OnMouseMove(e); } /// <summary> /// Handles the mouse up event. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseUp(MouseEventArgs e) { if (_isDragging) { _isDragging = false; _selectedSlider.Category.Maximum = _selectedSlider.Value; if (_isRaster) { _rasterSymbolizer.Scheme.ApplySnapping(_selectedSlider.Category); _selectedSlider.Category.ApplyMinMax(_rasterSymbolizer.Scheme.EditorSettings); } else { _scheme.ApplySnapping(_selectedSlider.Category); _selectedSlider.Category.ApplyMinMax(_scheme.EditorSettings); } if (_selectedSlider.NextCategory != null) { _selectedSlider.NextCategory.Minimum = _selectedSlider.Value; if (_isRaster) { _rasterSymbolizer.Scheme.ApplySnapping(_selectedSlider.NextCategory); _selectedSlider.Category.ApplyMinMax(_rasterSymbolizer.Scheme.EditorSettings); } else { _scheme.ApplySnapping(_selectedSlider.NextCategory); _selectedSlider.NextCategory.ApplyMinMax(_scheme.EditorSettings); } } OnSliderMoved(); Invalidate(); return; } BreakSlider s = GetBreakAt(e.Location); SelectBreak(s); OnSliderSelected(s); Invalidate(); base.OnMouseUp(e); } /// <summary> /// Custom drawing. /// </summary> /// <param name="e">The event args.</param> protected override void OnPaint(PaintEventArgs e) { Rectangle clip = e.ClipRectangle; if (clip.IsEmpty) clip = ClientRectangle; Bitmap bmp = new Bitmap(clip.Width, clip.Height); Graphics g = Graphics.FromImage(bmp); g.TranslateTransform(-clip.X, -clip.Y); g.Clip = new Region(clip); g.Clear(BackColor); g.SmoothingMode = SmoothingMode.AntiAlias; OnDraw(g, clip); g.Dispose(); e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel); } /// <summary> /// Prevents flicker by preventing the white background being drawn here. /// </summary> /// <param name="e">The event args.</param> protected override void OnPaintBackground(PaintEventArgs e) { // base.OnPaintBackground(pevent); } /// <summary> /// Occurs during a resize. /// </summary> /// <param name="e">The event args.</param> protected override void OnResize(EventArgs e) { _graph.Width = Width; _graph.Height = Height; base.OnResize(e); Invalidate(); } /// <summary> /// Fires the slider moved event. /// </summary> protected virtual void OnSliderMoved() { SliderMoved?.Invoke(this, new BreakSliderEventArgs(_selectedSlider)); } /// <summary> /// Occurs when the slider moves. /// </summary> protected virtual void OnSliderMoving() { SliderMoving?.Invoke(this, new BreakSliderEventArgs(_selectedSlider)); } /// <summary> /// Fires the SliderSelected event. /// </summary> /// <param name="slider">The break slider.</param> protected virtual void OnSliderSelected(BreakSlider slider) { SliderSelected?.Invoke(this, new BreakSliderEventArgs(slider)); } /// <summary> /// Fires the statistics updated event. /// </summary> protected virtual void OnStatisticsUpdated() { StatisticsUpdated?.Invoke(this, new StatisticalEventArgs(_scheme.Statistics)); } private void CategoryZoomClicked(object sender, EventArgs e) { ZoomToCategoryRange(); } private void FillBins() { if (_values == null) return; double min = _graph.Minimum; double max = _graph.Maximum; if (min == max) { min = min - 10; max = max + 10; } double binSize = (max - min) / _graph.NumColumns; int numBins = _graph.NumColumns; int[] bins = new int[numBins]; int maxBinCount = 0; foreach (double val in _values) { if (val < min || val > max) continue; int index = (int)Math.Ceiling((val - min) / binSize); if (index >= numBins) index = numBins - 1; bins[index]++; if (bins[index] > maxBinCount) { maxBinCount = bins[index]; } } _graph.MaxBinCount = maxBinCount; _graph.Bins = bins; } private bool IsValidField(string fieldName) { if (fieldName == null) return false; if (_source != null) return _source.GetColumn(fieldName) != null; return _table != null && _table.Columns.Contains(fieldName); } private void ReadValues() { if (_isRaster) { _values = _raster.GetRandomValues(_rasterSymbolizer.EditorSettings.MaxSampleCount); _statistics.Calculate(_values); if (_values == null) return; return; } _values = _scheme.Values; if (_values == null) return; _scheme.Statistics.Calculate(_values); } private void ResetZoom() { ResetExtents(); FillBins(); UpdateBreaks(); Invalidate(); } private void ResetZoomClicked(object sender, EventArgs e) { ResetZoom(); } private void UpdateBins() { if (_isRaster) { if (_raster == null) return; } else { if (_source == null && _table == null) return; if (!IsValidField(_fieldName)) return; } ReadValues(); FillBins(); UpdateBreaks(); } #endregion } }
using System; namespace CocosSharp { public abstract class CCMenuItemLabelBase : CCMenuItem { CCPoint originalScale; #region Properties public CCColor3B DisabledColor { get; set; } protected CCColor3B ColorBackup { get; set; } public override bool Selected { set { if(Enabled) { base.Selected = value; CCPoint zoomScale = (Selected == true) ? originalScale * 1.2f : originalScale; CCAction zoomAction = new CCScaleTo(0.1f, zoomScale.X, zoomScale.Y); if(Selected && (ZoomActionState == null || ZoomActionState.IsDone)) { originalScale.X = ScaleX; originalScale.Y = ScaleY; } if(ZoomActionState !=null) { ZoomActionState.Stop(); } ZoomActionState = RunAction(zoomAction); } } } #endregion Properties #region Constructors protected CCMenuItemLabelBase(Action<object> target = null) : base(target) { originalScale = new CCPoint(1.0f, 1.0f); ColorBackup = CCColor3B.White; DisabledColor = new CCColor3B(126, 126, 126); IsColorCascaded = true; IsOpacityCascaded = true; } #endregion Constructors protected void LabelWillChange(CCNode oldValue, CCNode newValue) { if(newValue != null) { AddChild(newValue); newValue.AnchorPoint = new CCPoint(0, 0); ContentSize = newValue.ContentSize; } if(oldValue != null) { RemoveChild(oldValue, true); } } public override void Activate() { if (Enabled) { StopAllActions(); ScaleX = originalScale.X; ScaleY = originalScale.Y; base.Activate(); } } } #if !WINDOWS_PHONE public class CCMenuItemLabel : CCMenuItemLabelBase { CCLabel label; #region Properties public CCLabel Label { get { return label; } set { LabelWillChange(label, value); label = value; if(label !=null && Scene != null) label.Scene = Scene; } } public override bool Enabled { get { return base.Enabled; } set { if(base.Enabled != value && label != null) { if (!value) { ColorBackup = label.Color; label.Color = DisabledColor; } else { label.Color = ColorBackup; } } base.Enabled = value; } } public override CCScene Scene { get { return base.Scene; } internal set { base.Scene = value; if (value != null && Label != null) { Label.Scene = value; } } } #endregion Properties #region Constructors public CCMenuItemLabel(CCLabel label, Action<object> target = null) : base(target) { Label = label; } #endregion Constructors } #endif public class CCMenuItemLabelAtlas : CCMenuItemLabelBase { CCLabelAtlas labelAtlas; #region Properties public CCLabelAtlas LabelAtlas { get { return labelAtlas; } set { LabelWillChange(labelAtlas, value); labelAtlas = value; if(labelAtlas != null && Scene != null) labelAtlas.Scene = Scene; } } public override bool Enabled { get { return base.Enabled; } set { if(base.Enabled != value && labelAtlas != null) { if (!value) { ColorBackup = labelAtlas.Color; labelAtlas.Color = DisabledColor; } else { labelAtlas.Color = ColorBackup; } } base.Enabled = value; } } public override CCScene Scene { get { return base.Scene; } internal set { base.Scene = value; if (value != null && LabelAtlas != null) { LabelAtlas.Scene = value; } } } #endregion Properties #region Constructors public CCMenuItemLabelAtlas(CCLabelAtlas labelAtlas, Action<object> target = null) : base(target) { LabelAtlas = labelAtlas; } public CCMenuItemLabelAtlas(Action<object> target) : this(null, target) { } public CCMenuItemLabelAtlas(string value, string charMapFile, int itemWidth, int itemHeight, char startCharMap, ICCUpdatable updatable, Action<object> target) : this(new CCLabelAtlas(value, charMapFile, itemWidth, itemHeight, startCharMap), target) { } public CCMenuItemLabelAtlas(string value, string charMapFile, int itemWidth, int itemHeight, char startCharMap) : this(value, charMapFile, itemWidth, itemHeight, startCharMap, null, null) { } #endregion Constructors } public class CCMenuItemLabelTTF : CCMenuItemLabelBase { CCLabelTtf labelTTF; #region Properties public CCLabelTtf LabelTTF { get { return labelTTF; } set { LabelWillChange(labelTTF, value); labelTTF = value; if(labelTTF != null && Scene != null) labelTTF.Scene = Scene; } } public override bool Enabled { get { return base.Enabled; } set { if(base.Enabled != value && labelTTF != null) { if (!value) { ColorBackup = labelTTF.Color; labelTTF.Color = DisabledColor; } else { labelTTF.Color = ColorBackup; } } base.Enabled = value; } } public override CCScene Scene { get { return base.Scene; } internal set { base.Scene = value; if (value != null && LabelTTF != null) { LabelTTF.Scene = value; } } } #endregion Properties #region Constructors public CCMenuItemLabelTTF(CCLabelTtf labelTTF, Action<object> target = null) : base(target) { LabelTTF = labelTTF; } public CCMenuItemLabelTTF(Action<object> target = null) : base(target) { } #endregion Constructors } public class CCMenuItemLabelBMFont : CCMenuItemLabelBase { CCLabelBMFont labelBMFont; #region Properties public CCLabelBMFont LabelBMFont { get { return labelBMFont; } set { LabelWillChange(labelBMFont, value); labelBMFont = value; if(labelBMFont != null && Scene != null) labelBMFont.Scene = Scene; } } public override bool Enabled { get { return base.Enabled; } set { if(base.Enabled != value && labelBMFont != null) { if (!value) { ColorBackup = labelBMFont.Color; labelBMFont.Color = DisabledColor; } else { labelBMFont.Color = ColorBackup; } } base.Enabled = value; } } public override CCScene Scene { get { return base.Scene; } internal set { base.Scene = value; if (value != null && LabelBMFont != null) { LabelBMFont.Scene = value; } } } #endregion Properties #region Constructors public CCMenuItemLabelBMFont(CCLabelBMFont labelBMFont, Action<object> target = null) : base(target) { LabelBMFont = labelBMFont; } #endregion Constructors } }
// 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.Immutable; using System.Collections.ObjectModel; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class TypeNameFormatterTests : CSharpResultProviderTestBase { [Fact] public void Primitives() { Assert.Equal("object", typeof(object).GetTypeName()); Assert.Equal("bool", typeof(bool).GetTypeName()); Assert.Equal("char", typeof(char).GetTypeName()); Assert.Equal("sbyte", typeof(sbyte).GetTypeName()); Assert.Equal("byte", typeof(byte).GetTypeName()); Assert.Equal("short", typeof(short).GetTypeName()); Assert.Equal("ushort", typeof(ushort).GetTypeName()); Assert.Equal("int", typeof(int).GetTypeName()); Assert.Equal("uint", typeof(uint).GetTypeName()); Assert.Equal("long", typeof(long).GetTypeName()); Assert.Equal("ulong", typeof(ulong).GetTypeName()); Assert.Equal("float", typeof(float).GetTypeName()); Assert.Equal("double", typeof(double).GetTypeName()); Assert.Equal("decimal", typeof(decimal).GetTypeName()); Assert.Equal("string", typeof(string).GetTypeName()); } [Fact, WorkItem(1016796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016796")] public void NestedTypes() { var source = @" public class A { public class B { } } namespace N { public class A { public class B { } } public class G1<T> { public class G2<T> { public class G3<U> { } class G4<U, V> { } } } } "; var assembly = GetAssembly(source); Assert.Equal("A", assembly.GetType("A").GetTypeName()); Assert.Equal("A.B", assembly.GetType("A+B").GetTypeName()); Assert.Equal("N.A", assembly.GetType("N.A").GetTypeName()); Assert.Equal("N.A.B", assembly.GetType("N.A+B").GetTypeName()); Assert.Equal("N.G1<int>.G2<float>.G3<double>", assembly.GetType("N.G1`1+G2`1+G3`1").MakeGenericType(typeof(int), typeof(float), typeof(double)).GetTypeName()); Assert.Equal("N.G1<int>.G2<float>.G4<double, ushort>", assembly.GetType("N.G1`1+G2`1+G4`2").MakeGenericType(typeof(int), typeof(float), typeof(double), typeof(ushort)).GetTypeName()); } [Fact] public void GenericTypes() { var source = @" public class A { public class B { } } namespace N { public class C<T, U> { public class D<V, W> { } } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = typeA.GetNestedType("B"); var typeC = assembly.GetType("N.C`2"); var typeD = typeC.GetNestedType("D`2"); var typeInt = typeof(int); var typeString = typeof(string); var typeCIntString = typeC.MakeGenericType(typeInt, typeString); Assert.Equal("N.C<T, U>", typeC.GetTypeName()); Assert.Equal("N.C<int, string>", typeCIntString.GetTypeName()); Assert.Equal("N.C<A, A.B>", typeC.MakeGenericType(typeA, typeB).GetTypeName()); Assert.Equal("N.C<int, string>.D<A, A.B>", typeD.MakeGenericType(typeInt, typeString, typeA, typeB).GetTypeName()); Assert.Equal("N.C<A, N.C<int, string>>.D<N.C<int, string>, A.B>", typeD.MakeGenericType(typeA, typeCIntString, typeCIntString, typeB).GetTypeName()); } [Fact] public void NonGenericInGeneric() { var source = @" public class A<T> { public class B { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A`1"); var typeB = typeA.GetNestedType("B"); Assert.Equal("A<int>.B", typeB.MakeGenericType(typeof(int)).GetTypeName()); } [Fact] public void PrimitiveNullableTypes() { Assert.Equal("int?", typeof(int?).GetTypeName()); Assert.Equal("bool?", typeof(bool?).GetTypeName()); } [Fact] public void NullableTypes() { var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var typeNullable = typeof(System.Nullable<>); var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.Equal("N.C?", typeNullable.MakeGenericType(typeC).GetTypeName()); Assert.Equal("N.A<N.C>?", typeNullable.MakeGenericType(typeA.MakeGenericType(typeC)).GetTypeName()); Assert.Equal("N.A<N.C>.B<N.C>?", typeNullable.MakeGenericType(typeB.MakeGenericType(typeC, typeC)).GetTypeName()); } [Fact] public void PrimitiveArrayTypes() { Assert.Equal("int[]", typeof(int[]).GetTypeName()); Assert.Equal("int[,]", typeof(int[,]).GetTypeName()); Assert.Equal("int[][,]", typeof(int[][,]).GetTypeName()); Assert.Equal("int[,][]", typeof(int[,][]).GetTypeName()); } [Fact] public void ArrayTypes() { var source = @" namespace N { public class A<T> { public class B<U> { } } public class C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.NotEqual(typeC.MakeArrayType(), typeC.MakeArrayType(1)); Assert.Equal("N.C[]", typeC.MakeArrayType().GetTypeName()); Assert.Equal("N.C[]", typeC.MakeArrayType(1).GetTypeName()); // NOTE: Multi-dimensional array that happens to exactly one dimension. Assert.Equal("N.A<N.C>[,]", typeA.MakeGenericType(typeC).MakeArrayType(2).GetTypeName()); Assert.Equal("N.A<N.C[]>.B<N.C>[,,]", typeB.MakeGenericType(typeC.MakeArrayType(), typeC).MakeArrayType(3).GetTypeName()); } [Fact] public void CustomBoundsArrayTypes() { Array instance = Array.CreateInstance(typeof(int), new[] { 1, 2, 3, }, new[] { 4, 5, 6, }); Assert.Equal("int[,,]", instance.GetType().GetTypeName()); Assert.Equal("int[][,,]", instance.GetType().MakeArrayType().GetTypeName()); } [Fact] public void PrimitivePointerTypes() { Assert.Equal("int*", typeof(int).MakePointerType().GetTypeName()); Assert.Equal("int**", typeof(int).MakePointerType().MakePointerType().GetTypeName()); Assert.Equal("int*[]", typeof(int).MakePointerType().MakeArrayType().GetTypeName()); } [Fact] public void PointerTypes() { var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.Equal("N.C*", typeC.MakePointerType().GetTypeName()); Assert.Equal("N.A<N.C>*", typeA.MakeGenericType(typeC).MakePointerType().GetTypeName()); Assert.Equal("N.A<N.C>.B<N.C>*", typeB.MakeGenericType(typeC, typeC).MakePointerType().GetTypeName()); } [Fact] public void Void() { Assert.Equal("void", typeof(void).GetTypeName()); Assert.Equal("void*", typeof(void).MakePointerType().GetTypeName()); } [Fact] public void KeywordIdentifiers() { var source = @" public class @object { public class @true { } } namespace @return { public class @yield<@async> { public class @await { } } namespace @false { public class @null { } } } "; var assembly = GetAssembly(source); var objectType = assembly.GetType("object"); var trueType = objectType.GetNestedType("true"); var nullType = assembly.GetType("return.false.null"); var yieldType = assembly.GetType("return.yield`1"); var constructedYieldType = yieldType.MakeGenericType(nullType); var awaitType = yieldType.GetNestedType("await"); var constructedAwaitType = awaitType.MakeGenericType(nullType); Assert.Equal("object", objectType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("object.true", trueType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.false.null", nullType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<async>", yieldType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<return.false.null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<return.false.null>.await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("@object", objectType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@object.@true", trueType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@false.@null", nullType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@async>", yieldType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@return.@false.@null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@return.@false.@null>.@await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: true)); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_KeywordEscaping() { var attributes = new[] { true }; Assert.Equal("dynamic", typeof(object).GetTypeName(attributes, escapeKeywordIdentifiers: false)); Assert.Equal("dynamic", typeof(object).GetTypeName(attributes, escapeKeywordIdentifiers: true)); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_Locations() { // Standalone. Assert.Equal("dynamic", typeof(object).GetTypeName(new[] { true })); // Array element type. Assert.Equal("dynamic[]", typeof(object[]).GetTypeName(new[] { false, true })); Assert.Equal("dynamic[][]", typeof(object[][]).GetTypeName(new[] { false, false, true })); // Type argument of top-level type. Assert.Equal("System.Func<dynamic>", typeof(Func<object>).GetTypeName(new[] { false, true })); var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeBConstructed = typeB.MakeGenericType(typeof(object), typeof(object)); // Type argument of nested type. Assert.Equal("N.A<object>.B<dynamic>", typeBConstructed.GetTypeName(new[] { false, false, true })); Assert.Equal("N.A<dynamic>.B<object>", typeBConstructed.GetTypeName(new[] { false, true, false })); Assert.Equal("N.A<dynamic>.B<dynamic>[]", typeBConstructed.MakeArrayType().GetTypeName(new[] { false, false, true, true })); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_InvalidFlags() { // Invalid true. Assert.Equal("int", typeof(int).GetTypeName(new[] { true })); Assert.Equal("dynamic[]", typeof(object[]).GetTypeName(new[] { true, true })); // Too many. Assert.Equal("dynamic", typeof(object).GetTypeName(new[] { true, true })); Assert.Equal("object", typeof(object).GetTypeName(new[] { false, true })); // Too few. Assert.Equal("object[]", typeof(object[]).GetTypeName(new[] { true })); Assert.Equal("object[]", typeof(object[]).GetTypeName(new[] { false })); // Type argument of top-level type. Assert.Equal("System.Func<object>", typeof(Func<object>).GetTypeName(new[] { true })); var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeBConstructed = typeB.MakeGenericType(typeof(object), typeof(object)); // Type argument of nested type. Assert.Equal("N.A<object>.B<object>", typeBConstructed.GetTypeName(new[] { false })); Assert.Equal("N.A<dynamic>.B<object>", typeBConstructed.GetTypeName(new[] { false, true })); Assert.Equal("N.A<dynamic>.B<object>[]", typeBConstructed.MakeArrayType().GetTypeName(new[] { false, false, true })); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_OtherGuid() { var typeInfo = DkmClrCustomTypeInfo.Create(Guid.NewGuid(), new ReadOnlyCollection<byte>(new byte[] { 1 })); Assert.Equal("object", typeof(object).GetTypeName(typeInfo)); Assert.Equal("object[]", typeof(object[]).GetTypeName(typeInfo)); } [Fact] public void MangledTypeParameterName() { var il = @" .class public auto ansi beforefieldinit Type`1<'<>Mangled'> extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var type = assembly.GetType("Type`1"); bool sawInvalidIdentifier; var typeName = CSharpFormatter.Instance.GetTypeName(new TypeAndCustomInfo((TypeImpl)type), escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier); Assert.True(sawInvalidIdentifier); Assert.Equal("Type<<>Mangled>", typeName); } } }
// 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.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reactive.Disposables; using System.Runtime.InteropServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.OpenGL; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Threading; using Avalonia.Win32.Input; using Avalonia.Win32.Interop; using static Avalonia.Win32.Interop.UnmanagedMethods; namespace Avalonia.Win32 { public class WindowImpl : IWindowImpl, EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo { private static readonly List<WindowImpl> s_instances = new List<WindowImpl>(); private static readonly IntPtr DefaultCursor = UnmanagedMethods.LoadCursor( IntPtr.Zero, new IntPtr((int)UnmanagedMethods.Cursor.IDC_ARROW)); private UnmanagedMethods.WndProc _wndProcDelegate; private string _className; private IntPtr _hwnd; private IInputRoot _owner; private bool _trackingMouse; private bool _decorated = true; private bool _resizable = true; private bool _topmost = false; private bool _taskbarIcon = true; private double _scaling = 1; private WindowState _showWindowState; private WindowState _lastWindowState; private FramebufferManager _framebuffer; private IGlPlatformSurface _gl; private OleDropTarget _dropTarget; private Size _minSize; private Size _maxSize; private WindowImpl _parent; private readonly List<WindowImpl> _disabledBy = new List<WindowImpl>(); #if USE_MANAGED_DRAG private readonly ManagedWindowResizeDragHelper _managedDrag; #endif public WindowImpl() { #if USE_MANAGED_DRAG _managedDrag = new ManagedWindowResizeDragHelper(this, capture => { if (capture) UnmanagedMethods.SetCapture(Handle.Handle); else UnmanagedMethods.ReleaseCapture(); }); #endif CreateWindow(); _framebuffer = new FramebufferManager(_hwnd); if (Win32GlManager.EglFeature != null) _gl = new EglGlPlatformSurface((EglDisplay)Win32GlManager.EglFeature.Display, Win32GlManager.EglFeature.DeferredContext, this); s_instances.Add(this); } public Action Activated { get; set; } public Func<bool> Closing { get; set; } public Action Closed { get; set; } public Action Deactivated { get; set; } public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size> Resized { get; set; } public Action<double> ScalingChanged { get; set; } public Action<Point> PositionChanged { get; set; } public Action<WindowState> WindowStateChanged { get; set; } public Thickness BorderThickness { get { if (_decorated) { var style = UnmanagedMethods.GetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_STYLE); var exStyle = UnmanagedMethods.GetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_EXSTYLE); var padding = new RECT(); if (UnmanagedMethods.AdjustWindowRectEx(ref padding, style, false, exStyle)) { return new Thickness(-padding.left, -padding.top, padding.right, padding.bottom); } else { throw new Win32Exception(); } } else { return new Thickness(); } } } public Size ClientSize { get { UnmanagedMethods.RECT rect; UnmanagedMethods.GetClientRect(_hwnd, out rect); return new Size(rect.right, rect.bottom) / Scaling; } } public void SetMinMaxSize(Size minSize, Size maxSize) { _minSize = minSize; _maxSize = maxSize; } public IScreenImpl Screen { get; } = new ScreenImpl(); public IRenderer CreateRenderer(IRenderRoot root) { var loop = AvaloniaLocator.Current.GetService<IRenderLoop>(); var customRendererFactory = AvaloniaLocator.Current.GetService<IRendererFactory>(); if (customRendererFactory != null) return customRendererFactory.Create(root, loop); return Win32Platform.UseDeferredRendering ? (IRenderer)new DeferredRenderer(root, loop) : new ImmediateRenderer(root); } public void Resize(Size value) { if (value != ClientSize) { value *= Scaling; UnmanagedMethods.SetWindowPos( _hwnd, IntPtr.Zero, 0, 0, (int)value.Width, (int)value.Height, UnmanagedMethods.SetWindowPosFlags.SWP_RESIZE); } } public double Scaling => _scaling; public IPlatformHandle Handle { get; private set; } void UpdateEnabled() { EnableWindow(_hwnd, _disabledBy.Count == 0); } public Size MaxClientSize { get { return (new Size( UnmanagedMethods.GetSystemMetrics(UnmanagedMethods.SystemMetric.SM_CXMAXTRACK), UnmanagedMethods.GetSystemMetrics(UnmanagedMethods.SystemMetric.SM_CYMAXTRACK)) - BorderThickness) / Scaling; } } public IMouseDevice MouseDevice => WindowsMouseDevice.Instance; public WindowState WindowState { get { var placement = default(UnmanagedMethods.WINDOWPLACEMENT); UnmanagedMethods.GetWindowPlacement(_hwnd, ref placement); switch (placement.ShowCmd) { case UnmanagedMethods.ShowWindowCommand.Maximize: return WindowState.Maximized; case UnmanagedMethods.ShowWindowCommand.Minimize: return WindowState.Minimized; default: return WindowState.Normal; } } set { if (UnmanagedMethods.IsWindowVisible(_hwnd)) { ShowWindow(value); } else { _showWindowState = value; } } } public IEnumerable<object> Surfaces => new object[] { Handle, _gl, _framebuffer }; public void Activate() { UnmanagedMethods.SetActiveWindow(_hwnd); } public IPopupImpl CreatePopup() { return new PopupImpl(); } public void Dispose() { if (_hwnd != IntPtr.Zero) { UnmanagedMethods.DestroyWindow(_hwnd); _hwnd = IntPtr.Zero; } if (_className != null) { UnmanagedMethods.UnregisterClass(_className, UnmanagedMethods.GetModuleHandle(null)); _className = null; } } public void Hide() { if (_parent != null) { _parent._disabledBy.Remove(this); _parent.UpdateEnabled(); _parent = null; } UnmanagedMethods.ShowWindow(_hwnd, UnmanagedMethods.ShowWindowCommand.Hide); } public void SetSystemDecorations(bool value) { if (value == _decorated) { return; } UpdateWMStyles(()=> _decorated = value); } public void Invalidate(Rect rect) { var f = Scaling; var r = new UnmanagedMethods.RECT { left = (int)Math.Floor(rect.X * f), top = (int)Math.Floor(rect.Y * f), right = (int)Math.Ceiling(rect.Right * f), bottom = (int)Math.Ceiling(rect.Bottom * f), }; UnmanagedMethods.InvalidateRect(_hwnd, ref r, false); } public Point PointToClient(Point point) { var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ScreenToClient(_hwnd, ref p); return new Point(p.X, p.Y) / Scaling; } public Point PointToScreen(Point point) { point *= Scaling; var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ClientToScreen(_hwnd, ref p); return new Point(p.X, p.Y); } public void SetInputRoot(IInputRoot inputRoot) { _owner = inputRoot; CreateDropTarget(); } public void SetTitle(string title) { UnmanagedMethods.SetWindowText(_hwnd, title); } public virtual void Show() { SetWindowLongPtr(_hwnd, (int)WindowLongParam.GWL_HWNDPARENT, IntPtr.Zero); ShowWindow(_showWindowState); } public void BeginMoveDrag() { UnmanagedMethods.DefWindowProc(_hwnd, (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN, new IntPtr((int)UnmanagedMethods.HitTestValues.HTCAPTION), IntPtr.Zero); } static readonly Dictionary<WindowEdge, UnmanagedMethods.HitTestValues> EdgeDic = new Dictionary<WindowEdge, UnmanagedMethods.HitTestValues> { {WindowEdge.East, UnmanagedMethods.HitTestValues.HTRIGHT}, {WindowEdge.North, UnmanagedMethods.HitTestValues.HTTOP }, {WindowEdge.NorthEast, UnmanagedMethods.HitTestValues.HTTOPRIGHT }, {WindowEdge.NorthWest, UnmanagedMethods.HitTestValues.HTTOPLEFT }, {WindowEdge.South, UnmanagedMethods.HitTestValues.HTBOTTOM }, {WindowEdge.SouthEast, UnmanagedMethods.HitTestValues.HTBOTTOMRIGHT }, {WindowEdge.SouthWest, UnmanagedMethods.HitTestValues.HTBOTTOMLEFT }, {WindowEdge.West, UnmanagedMethods.HitTestValues.HTLEFT} }; public void BeginResizeDrag(WindowEdge edge) { #if USE_MANAGED_DRAG _managedDrag.BeginResizeDrag(edge, ScreenToClient(MouseDevice.Position)); #else UnmanagedMethods.DefWindowProc(_hwnd, (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN, new IntPtr((int)EdgeDic[edge]), IntPtr.Zero); #endif } public Point Position { get { UnmanagedMethods.RECT rc; UnmanagedMethods.GetWindowRect(_hwnd, out rc); return new Point(rc.left, rc.top); } set { UnmanagedMethods.SetWindowPos( Handle.Handle, IntPtr.Zero, (int)value.X, (int)value.Y, 0, 0, UnmanagedMethods.SetWindowPosFlags.SWP_NOSIZE | UnmanagedMethods.SetWindowPosFlags.SWP_NOACTIVATE); } } public void ShowDialog(IWindowImpl parent) { _parent = (WindowImpl)parent; _parent._disabledBy.Add(this); _parent.UpdateEnabled(); SetWindowLongPtr(_hwnd, (int)WindowLongParam.GWL_HWNDPARENT, ((WindowImpl)parent)._hwnd); ShowWindow(_showWindowState); } public void SetCursor(IPlatformHandle cursor) { var hCursor = cursor?.Handle ?? DefaultCursor; UnmanagedMethods.SetClassLong(_hwnd, UnmanagedMethods.ClassLongIndex.GCLP_HCURSOR, hCursor); if (_owner.IsPointerOver) UnmanagedMethods.SetCursor(hCursor); } protected virtual IntPtr CreateWindowOverride(ushort atom) { return UnmanagedMethods.CreateWindowEx( 0, atom, null, (int)UnmanagedMethods.WindowStyles.WS_OVERLAPPEDWINDOW, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Using Win32 naming for consistency.")] protected virtual IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) { bool unicode = UnmanagedMethods.IsWindowUnicode(hWnd); const double wheelDelta = 120.0; uint timestamp = unchecked((uint)UnmanagedMethods.GetMessageTime()); RawInputEventArgs e = null; WindowsMouseDevice.Instance.CurrentWindow = this; switch ((UnmanagedMethods.WindowsMessage)msg) { case UnmanagedMethods.WindowsMessage.WM_ACTIVATE: var wa = (UnmanagedMethods.WindowActivate)(ToInt32(wParam) & 0xffff); switch (wa) { case UnmanagedMethods.WindowActivate.WA_ACTIVE: case UnmanagedMethods.WindowActivate.WA_CLICKACTIVE: Activated?.Invoke(); break; case UnmanagedMethods.WindowActivate.WA_INACTIVE: Deactivated?.Invoke(); break; } return IntPtr.Zero; case WindowsMessage.WM_NCCALCSIZE: if (ToInt32(wParam) == 1 && !_decorated) { return IntPtr.Zero; } break; case UnmanagedMethods.WindowsMessage.WM_CLOSE: bool? preventClosing = Closing?.Invoke(); if (preventClosing == true) { return IntPtr.Zero; } break; case UnmanagedMethods.WindowsMessage.WM_DESTROY: //Window doesn't exist anymore _hwnd = IntPtr.Zero; //Remove root reference to this class, so unmanaged delegate can be collected s_instances.Remove(this); Closed?.Invoke(); if (_parent != null) { _parent._disabledBy.Remove(this); _parent.UpdateEnabled(); } //Free other resources Dispose(); return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_DPICHANGED: var dpi = ToInt32(wParam) & 0xffff; var newDisplayRect = Marshal.PtrToStructure<UnmanagedMethods.RECT>(lParam); _scaling = dpi / 96.0; ScalingChanged?.Invoke(_scaling); SetWindowPos(hWnd, IntPtr.Zero, newDisplayRect.left, newDisplayRect.top, newDisplayRect.right - newDisplayRect.left, newDisplayRect.bottom - newDisplayRect.top, SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE); return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_KEYDOWN: case UnmanagedMethods.WindowsMessage.WM_SYSKEYDOWN: e = new RawKeyEventArgs( WindowsKeyboardDevice.Instance, timestamp, RawKeyEventType.KeyDown, KeyInterop.KeyFromVirtualKey(ToInt32(wParam)), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_KEYUP: case UnmanagedMethods.WindowsMessage.WM_SYSKEYUP: e = new RawKeyEventArgs( WindowsKeyboardDevice.Instance, timestamp, RawKeyEventType.KeyUp, KeyInterop.KeyFromVirtualKey(ToInt32(wParam)), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_CHAR: // Ignore control chars if (ToInt32(wParam) >= 32) { e = new RawTextInputEventArgs(WindowsKeyboardDevice.Instance, timestamp, new string((char)ToInt32(wParam), 1)); } break; case UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_MBUTTONDOWN: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int)UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN ? RawMouseEventType.LeftButtonDown : msg == (int)UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN ? RawMouseEventType.RightButtonDown : RawMouseEventType.MiddleButtonDown, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_LBUTTONUP: case UnmanagedMethods.WindowsMessage.WM_RBUTTONUP: case UnmanagedMethods.WindowsMessage.WM_MBUTTONUP: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int)UnmanagedMethods.WindowsMessage.WM_LBUTTONUP ? RawMouseEventType.LeftButtonUp : msg == (int)UnmanagedMethods.WindowsMessage.WM_RBUTTONUP ? RawMouseEventType.RightButtonUp : RawMouseEventType.MiddleButtonUp, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSEMOVE: if (!_trackingMouse) { var tm = new UnmanagedMethods.TRACKMOUSEEVENT { cbSize = Marshal.SizeOf<UnmanagedMethods.TRACKMOUSEEVENT>(), dwFlags = 2, hwndTrack = _hwnd, dwHoverTime = 0, }; UnmanagedMethods.TrackMouseEvent(ref tm); } e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, RawMouseEventType.Move, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSEWHEEL: e = new RawMouseWheelEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, PointToClient(PointFromLParam(lParam)), new Vector(0, (ToInt32(wParam) >> 16) / wheelDelta), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSEHWHEEL: e = new RawMouseWheelEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, PointToClient(PointFromLParam(lParam)), new Vector(-(ToInt32(wParam) >> 16) / wheelDelta, 0), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSELEAVE: _trackingMouse = false; e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, RawMouseEventType.LeaveWindow, new Point(), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_NCMBUTTONDOWN: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN ? RawMouseEventType.NonClientLeftButtonDown : msg == (int)UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN ? RawMouseEventType.RightButtonDown : RawMouseEventType.MiddleButtonDown, new Point(0, 0), GetMouseModifiers(wParam)); break; case WindowsMessage.WM_NCPAINT: if (!_decorated) { return IntPtr.Zero; } break; case WindowsMessage.WM_NCACTIVATE: if (!_decorated) { return new IntPtr(1); } break; case UnmanagedMethods.WindowsMessage.WM_PAINT: UnmanagedMethods.PAINTSTRUCT ps; if (UnmanagedMethods.BeginPaint(_hwnd, out ps) != IntPtr.Zero) { var f = Scaling; var r = ps.rcPaint; Paint?.Invoke(new Rect(r.left / f, r.top / f, (r.right - r.left) / f, (r.bottom - r.top) / f)); UnmanagedMethods.EndPaint(_hwnd, ref ps); } return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_SIZE: var size = (UnmanagedMethods.SizeCommand)wParam; if (Resized != null && (size == UnmanagedMethods.SizeCommand.Restored || size == UnmanagedMethods.SizeCommand.Maximized)) { var clientSize = new Size(ToInt32(lParam) & 0xffff, ToInt32(lParam) >> 16); Resized(clientSize / Scaling); } var windowState = size == SizeCommand.Maximized ? WindowState.Maximized : (size == SizeCommand.Minimized ? WindowState.Minimized : WindowState.Normal); if (windowState != _lastWindowState) { _lastWindowState = windowState; WindowStateChanged?.Invoke(windowState); } return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_MOVE: PositionChanged?.Invoke(new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16))); return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_GETMINMAXINFO: MINMAXINFO mmi = Marshal.PtrToStructure<UnmanagedMethods.MINMAXINFO>(lParam); if (_minSize.Width > 0) mmi.ptMinTrackSize.X = (int)((_minSize.Width * Scaling) + BorderThickness.Left + BorderThickness.Right); if (_minSize.Height > 0) mmi.ptMinTrackSize.Y = (int)((_minSize.Height * Scaling) + BorderThickness.Top + BorderThickness.Bottom); if (!Double.IsInfinity(_maxSize.Width) && _maxSize.Width > 0) mmi.ptMaxTrackSize.X = (int)((_maxSize.Width * Scaling) + BorderThickness.Left + BorderThickness.Right); if (!Double.IsInfinity(_maxSize.Height) && _maxSize.Height > 0) mmi.ptMaxTrackSize.Y = (int)((_maxSize.Height * Scaling) + BorderThickness.Top + BorderThickness.Bottom); Marshal.StructureToPtr(mmi, lParam, true); return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_DISPLAYCHANGE: (Screen as ScreenImpl)?.InvalidateScreensCache(); return IntPtr.Zero; } #if USE_MANAGED_DRAG if (_managedDrag.PreprocessInputEvent(ref e)) return UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam); #endif if (e != null && Input != null) { Input(e); if (e.Handled) { return IntPtr.Zero; } } return UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam); } static InputModifiers GetMouseModifiers(IntPtr wParam) { var keys = (UnmanagedMethods.ModifierKeys)ToInt32(wParam); var modifiers = WindowsKeyboardDevice.Instance.Modifiers; if (keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_LBUTTON)) modifiers |= InputModifiers.LeftMouseButton; if (keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_RBUTTON)) modifiers |= InputModifiers.RightMouseButton; if (keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_MBUTTON)) modifiers |= InputModifiers.MiddleMouseButton; return modifiers; } private void CreateWindow() { // Ensure that the delegate doesn't get garbage collected by storing it as a field. _wndProcDelegate = new UnmanagedMethods.WndProc(WndProc); _className = "Avalonia-" + Guid.NewGuid(); UnmanagedMethods.WNDCLASSEX wndClassEx = new UnmanagedMethods.WNDCLASSEX { cbSize = Marshal.SizeOf<UnmanagedMethods.WNDCLASSEX>(), style = (int)(ClassStyles.CS_OWNDC | ClassStyles.CS_HREDRAW | ClassStyles.CS_VREDRAW), // Unique DC helps with performance when using Gpu based rendering lpfnWndProc = _wndProcDelegate, hInstance = UnmanagedMethods.GetModuleHandle(null), hCursor = DefaultCursor, hbrBackground = IntPtr.Zero, lpszClassName = _className }; ushort atom = UnmanagedMethods.RegisterClassEx(ref wndClassEx); if (atom == 0) { throw new Win32Exception(); } _hwnd = CreateWindowOverride(atom); if (_hwnd == IntPtr.Zero) { throw new Win32Exception(); } Handle = new PlatformHandle(_hwnd, PlatformConstants.WindowHandleType); if (UnmanagedMethods.ShCoreAvailable) { uint dpix, dpiy; var monitor = UnmanagedMethods.MonitorFromWindow( _hwnd, UnmanagedMethods.MONITOR.MONITOR_DEFAULTTONEAREST); if (UnmanagedMethods.GetDpiForMonitor( monitor, UnmanagedMethods.MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI, out dpix, out dpiy) == 0) { _scaling = dpix / 96.0; } } } private void CreateDropTarget() { OleDropTarget odt = new OleDropTarget(this, _owner); if (OleContext.Current?.RegisterDragDrop(Handle, odt) ?? false) _dropTarget = odt; } private Point DipFromLParam(IntPtr lParam) { return new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16)) / Scaling; } private Point PointFromLParam(IntPtr lParam) { return new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16)); } private Point ScreenToClient(Point point) { var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ScreenToClient(_hwnd, ref p); return new Point(p.X, p.Y); } private void ShowWindow(WindowState state) { UnmanagedMethods.ShowWindowCommand command; switch (state) { case WindowState.Minimized: command = ShowWindowCommand.Minimize; break; case WindowState.Maximized: command = ShowWindowCommand.Maximize; break; case WindowState.Normal: command = ShowWindowCommand.Restore; break; default: throw new ArgumentException("Invalid WindowState."); } UnmanagedMethods.ShowWindow(_hwnd, command); if (state == WindowState.Maximized) { MaximizeWithoutCoveringTaskbar(); } if (!Design.IsDesignMode) { SetFocus(_hwnd); } } private void MaximizeWithoutCoveringTaskbar() { IntPtr monitor = MonitorFromWindow(_hwnd, MONITOR.MONITOR_DEFAULTTONEAREST); if (monitor != IntPtr.Zero) { MONITORINFO monitorInfo = MONITORINFO.Create(); if (GetMonitorInfo(monitor, ref monitorInfo)) { RECT rcMonitorArea = monitorInfo.rcMonitor; var x = monitorInfo.rcWork.left; var y = monitorInfo.rcWork.top; var cx = Math.Abs(monitorInfo.rcWork.right - x); var cy = Math.Abs(monitorInfo.rcWork.bottom - y); SetWindowPos(_hwnd, WindowPosZOrder.HWND_NOTOPMOST, x, y, cx, cy, SetWindowPosFlags.SWP_SHOWWINDOW); } } } public void SetIcon(IWindowIconImpl icon) { var impl = (IconImpl)icon; var hIcon = impl.HIcon; UnmanagedMethods.PostMessage(_hwnd, (int)UnmanagedMethods.WindowsMessage.WM_SETICON, new IntPtr((int)UnmanagedMethods.Icons.ICON_BIG), hIcon); } private static int ToInt32(IntPtr ptr) { if (IntPtr.Size == 4) return ptr.ToInt32(); return (int)(ptr.ToInt64() & 0xffffffff); } public void ShowTaskbarIcon(bool value) { if (_taskbarIcon == value) { return; } _taskbarIcon = value; var style = (UnmanagedMethods.WindowStyles)UnmanagedMethods.GetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_EXSTYLE); style &= ~(UnmanagedMethods.WindowStyles.WS_VISIBLE); style |= UnmanagedMethods.WindowStyles.WS_EX_TOOLWINDOW; if (value) style |= UnmanagedMethods.WindowStyles.WS_EX_APPWINDOW; else style &= ~(UnmanagedMethods.WindowStyles.WS_EX_APPWINDOW); WINDOWPLACEMENT windowPlacement = UnmanagedMethods.WINDOWPLACEMENT.Default; if (UnmanagedMethods.GetWindowPlacement(_hwnd, ref windowPlacement)) { //Toggle to make the styles stick UnmanagedMethods.ShowWindow(_hwnd, ShowWindowCommand.Hide); UnmanagedMethods.SetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_EXSTYLE, (uint)style); UnmanagedMethods.ShowWindow(_hwnd, windowPlacement.ShowCmd); } } private void UpdateWMStyles(Action change) { var oldDecorated = _decorated; var oldThickness = BorderThickness; change(); var style = (WindowStyles)GetWindowLong(_hwnd, (int)WindowLongParam.GWL_STYLE); const WindowStyles controlledFlags = WindowStyles.WS_OVERLAPPEDWINDOW; style = style | controlledFlags ^ controlledFlags; style |= WindowStyles.WS_OVERLAPPEDWINDOW; if (!_decorated) { style ^= (WindowStyles.WS_CAPTION | WindowStyles.WS_SYSMENU); } if (!_resizable) { style ^= (WindowStyles.WS_SIZEFRAME); } GetClientRect(_hwnd, out var oldClientRect); var oldClientRectOrigin = new UnmanagedMethods.POINT(); ClientToScreen(_hwnd, ref oldClientRectOrigin); oldClientRect.Offset(oldClientRectOrigin); SetWindowLong(_hwnd, (int)WindowLongParam.GWL_STYLE, (uint)style); UnmanagedMethods.GetWindowRect(_hwnd, out var windowRect); bool frameUpdated = false; if (oldDecorated != _decorated) { var newRect = oldClientRect; if (_decorated) AdjustWindowRectEx(ref newRect, (uint)style, false, GetWindowLong(_hwnd, (int)WindowLongParam.GWL_EXSTYLE)); SetWindowPos(_hwnd, IntPtr.Zero, newRect.left, newRect.top, newRect.Width, newRect.Height, SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_FRAMECHANGED); frameUpdated = true; } if (!frameUpdated) SetWindowPos(_hwnd, IntPtr.Zero, 0, 0, 0, 0, SetWindowPosFlags.SWP_FRAMECHANGED | SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE); } public void CanResize(bool value) { if (value == _resizable) { return; } UpdateWMStyles(()=> _resizable = value); } public void SetTopmost(bool value) { if (value == _topmost) { return; } IntPtr hWndInsertAfter = value ? WindowPosZOrder.HWND_TOPMOST : WindowPosZOrder.HWND_NOTOPMOST; UnmanagedMethods.SetWindowPos(_hwnd, hWndInsertAfter, 0, 0, 0, 0, SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE); _topmost = value; } PixelSize EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo.Size { get { RECT rect; GetClientRect(_hwnd, out rect); return new PixelSize( Math.Max(1, rect.right - rect.left), Math.Max(1, rect.bottom - rect.top)); } } IntPtr EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo.Handle => Handle.Handle; } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.Control.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI { public partial class Control : System.ComponentModel.IComponent, IDisposable, IParserAccessor, IUrlResolutionService, IDataBindingsAccessor, IControlBuilderAccessor, IControlDesignerAccessor, IExpressionsAccessor { #region Methods and constructors protected internal virtual new void AddedControl(System.Web.UI.Control control, int index) { } protected virtual new void AddParsedSubObject(Object obj) { } public virtual new void ApplyStyleSheetSkin(Page page) { } protected void BuildProfileTree(string parentId, bool calcViewState) { } protected void ClearCachedClientID() { } protected void ClearChildControlState() { } protected void ClearChildState() { } protected void ClearChildViewState() { } protected void ClearEffectiveClientIDMode() { } public Control() { } protected internal virtual new void CreateChildControls() { } protected virtual new ControlCollection CreateControlCollection() { return default(ControlCollection); } protected virtual new void DataBind(bool raiseOnDataBinding) { } public virtual new void DataBind() { } protected virtual new void DataBindChildren() { } public virtual new void Dispose() { } protected virtual new void EnsureChildControls() { } protected void EnsureID() { } public virtual new System.Web.UI.Control FindControl(string id) { return default(System.Web.UI.Control); } protected virtual new System.Web.UI.Control FindControl(string id, int pathOffset) { return default(System.Web.UI.Control); } public virtual new void Focus() { } protected virtual new System.Collections.IDictionary GetDesignModeState() { return default(System.Collections.IDictionary); } public string GetRouteUrl(Object routeParameters) { return default(string); } public string GetRouteUrl(string routeName, System.Web.Routing.RouteValueDictionary routeParameters) { return default(string); } public string GetRouteUrl(System.Web.Routing.RouteValueDictionary routeParameters) { return default(string); } public string GetRouteUrl(string routeName, Object routeParameters) { return default(string); } public string GetUniqueIDRelativeTo(System.Web.UI.Control control) { return default(string); } public virtual new bool HasControls() { return default(bool); } protected bool HasEvents() { return default(bool); } protected bool IsLiteralContent() { return default(bool); } protected internal virtual new void LoadControlState(Object savedState) { } protected virtual new void LoadViewState(Object savedState) { } protected internal string MapPathSecure(string virtualPath) { return default(string); } protected virtual new bool OnBubbleEvent(Object source, EventArgs args) { return default(bool); } protected virtual new void OnDataBinding(EventArgs e) { } protected internal virtual new void OnInit(EventArgs e) { } protected internal virtual new void OnLoad(EventArgs e) { } protected internal virtual new void OnPreRender(EventArgs e) { } protected internal virtual new void OnUnload(EventArgs e) { } protected internal Stream OpenFile(string path) { return default(Stream); } protected void RaiseBubbleEvent(Object source, EventArgs args) { } protected internal virtual new void RemovedControl(System.Web.UI.Control control) { } protected internal virtual new void Render(HtmlTextWriter writer) { } protected internal virtual new void RenderChildren(HtmlTextWriter writer) { } public virtual new void RenderControl(HtmlTextWriter writer) { } protected void RenderControl(HtmlTextWriter writer, System.Web.UI.Adapters.ControlAdapter adapter) { } protected virtual new System.Web.UI.Adapters.ControlAdapter ResolveAdapter() { return default(System.Web.UI.Adapters.ControlAdapter); } public string ResolveClientUrl(string relativeUrl) { return default(string); } public string ResolveUrl(string relativeUrl) { return default(string); } protected internal virtual new Object SaveControlState() { return default(Object); } protected virtual new Object SaveViewState() { return default(Object); } protected virtual new void SetDesignModeState(System.Collections.IDictionary data) { } public void SetRenderMethodDelegate(RenderMethod renderMethod) { } System.Collections.IDictionary System.Web.UI.IControlDesignerAccessor.GetDesignModeState() { return default(System.Collections.IDictionary); } void System.Web.UI.IControlDesignerAccessor.SetDesignModeState(System.Collections.IDictionary data) { } void System.Web.UI.IControlDesignerAccessor.SetOwnerControl(System.Web.UI.Control owner) { } void System.Web.UI.IParserAccessor.AddParsedSubObject(Object obj) { } protected virtual new void TrackViewState() { } #endregion #region Properties and indexers protected System.Web.UI.Adapters.ControlAdapter Adapter { get { return default(System.Web.UI.Adapters.ControlAdapter); } } public string AppRelativeTemplateSourceDirectory { get { return default(string); } set { } } public System.Web.UI.Control BindingContainer { get { return default(System.Web.UI.Control); } } protected bool ChildControlsCreated { get { return default(bool); } set { } } public virtual new string ClientID { get { return default(string); } } public virtual new ClientIDMode ClientIDMode { get { return default(ClientIDMode); } set { } } protected char ClientIDSeparator { get { return default(char); } } internal protected virtual new System.Web.HttpContext Context { get { return default(System.Web.HttpContext); } } public virtual new ControlCollection Controls { get { return default(ControlCollection); } } public System.Web.UI.Control DataItemContainer { get { return default(System.Web.UI.Control); } } public System.Web.UI.Control DataKeysContainer { get { return default(System.Web.UI.Control); } } internal protected bool DesignMode { get { return default(bool); } } public virtual new bool EnableTheming { get { return default(bool); } set { } } public virtual new bool EnableViewState { get { return default(bool); } set { } } protected System.ComponentModel.EventHandlerList Events { get { return default(System.ComponentModel.EventHandlerList); } } protected bool HasChildViewState { get { return default(bool); } } public virtual new string ID { get { return default(string); } set { } } protected char IdSeparator { get { return default(char); } } internal protected bool IsChildControlStateCleared { get { return default(bool); } } protected bool IsTrackingViewState { get { return default(bool); } } internal protected bool IsViewStateEnabled { get { return default(bool); } } protected bool LoadViewStateByID { get { return default(bool); } } public virtual new System.Web.UI.Control NamingContainer { get { return default(System.Web.UI.Control); } } public virtual new Page Page { get { return default(Page); } set { } } public virtual new System.Web.UI.Control Parent { get { return default(System.Web.UI.Control); } } public virtual new Version RenderingCompatibility { get { return default(Version); } set { } } public System.ComponentModel.ISite Site { get { return default(System.ComponentModel.ISite); } set { } } public virtual new string SkinID { get { return default(string); } set { } } ControlBuilder System.Web.UI.IControlBuilderAccessor.ControlBuilder { get { return default(ControlBuilder); } } System.Collections.IDictionary System.Web.UI.IControlDesignerAccessor.UserData { get { return default(System.Collections.IDictionary); } } DataBindingCollection System.Web.UI.IDataBindingsAccessor.DataBindings { get { return default(DataBindingCollection); } } bool System.Web.UI.IDataBindingsAccessor.HasDataBindings { get { return default(bool); } } ExpressionBindingCollection System.Web.UI.IExpressionsAccessor.Expressions { get { return default(ExpressionBindingCollection); } } bool System.Web.UI.IExpressionsAccessor.HasExpressions { get { return default(bool); } } public TemplateControl TemplateControl { get { return default(TemplateControl); } set { } } public virtual new string TemplateSourceDirectory { get { return default(string); } } public virtual new string UniqueID { get { return default(string); } } protected virtual new StateBag ViewState { get { return default(StateBag); } } protected virtual new bool ViewStateIgnoresCase { get { return default(bool); } } public virtual new ViewStateMode ViewStateMode { get { return default(ViewStateMode); } set { } } public virtual new bool Visible { get { return default(bool); } set { } } #endregion #region Events public event EventHandler DataBinding { add { } remove { } } public event EventHandler Disposed { add { } remove { } } public event EventHandler Init { add { } remove { } } public event EventHandler Load { add { } remove { } } public event EventHandler PreRender { add { } remove { } } public event EventHandler Unload { add { } remove { } } #endregion } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Hydra.HydraServer.HydraServerPublic File: HydraServerTask.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Hydra.HydraServer { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Security; using Ecng.Collections; using Ecng.Common; using Ecng.ComponentModel; using StockSharp.Algo; using StockSharp.Algo.Candles; using StockSharp.Algo.History; using StockSharp.Algo.History.Hydra; using StockSharp.Algo.Storages; using StockSharp.Logging; using StockSharp.BusinessEntities; using StockSharp.Hydra.Core; using StockSharp.Messages; using StockSharp.Localization; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; [DisplayNameLoc(_sourceName)] [DescriptionLoc(LocalizedStrings.Str2281ParamsKey, _sourceName)] [Doc("http://stocksharp.com/doc/html/c84d96f5-d466-4dbd-b7d4-9f87cba8ea7f.htm")] [Icon("hydra_server_logo.png")] [TaskCategory(TaskCategories.History | TaskCategories.Ticks | TaskCategories.Stock | TaskCategories.Forex | TaskCategories.Free | TaskCategories.MarketDepth | TaskCategories.OrderLog | TaskCategories.Level1 | TaskCategories.Candles | TaskCategories.Transactions)] class HydraServerTask : BaseHydraTask, ISecurityDownloader { private const string _sourceName = "S#.Data Server"; [TaskSettingsDisplayName(_sourceName)] [CategoryOrder(_sourceName, 0)] private sealed class HydraServerSettings : HydraTaskSettings { public HydraServerSettings(HydraTaskSettings settings) : base(settings) { ExtensionInfo.TryAdd(nameof(IgnoreWeekends), true); CollectionHelper.TryAdd(ExtensionInfo, nameof(DayOffset), 1); } [CategoryLoc(_sourceName)] [DisplayNameLoc(LocalizedStrings.AddressKey)] [DescriptionLoc(LocalizedStrings.AddressKey, true)] [PropertyOrder(0)] public Uri Address { get { return ExtensionInfo[nameof(Address)].To<Uri>(); } set { ExtensionInfo[nameof(Address)] = value.ToString(); } } [CategoryLoc(_sourceName)] [DisplayNameLoc(LocalizedStrings.LoginKey)] [DescriptionLoc(LocalizedStrings.Str2302Key)] [PropertyOrder(1)] public string Login { get { return (string)ExtensionInfo[nameof(Login)]; } set { ExtensionInfo[nameof(Login)] = value; } } [CategoryLoc(_sourceName)] [DisplayNameLoc(LocalizedStrings.PasswordKey)] [DescriptionLoc(LocalizedStrings.Str2303Key)] [PropertyOrder(2)] public SecureString Password { get { return ExtensionInfo[nameof(Password)].To<SecureString>(); } set { ExtensionInfo[nameof(Password)] = value; } } [CategoryLoc(_sourceName)] [DisplayNameLoc(LocalizedStrings.Str2282Key)] [DescriptionLoc(LocalizedStrings.Str2304Key)] [PropertyOrder(3)] public DateTime StartFrom { get { return ExtensionInfo[nameof(StartFrom)].To<DateTime>(); } set { ExtensionInfo[nameof(StartFrom)] = value.Ticks; } } [CategoryLoc(_sourceName)] [DisplayNameLoc(LocalizedStrings.Str2284Key)] [DescriptionLoc(LocalizedStrings.Str2285Key)] [PropertyOrder(4)] public int DayOffset { get { return ExtensionInfo[nameof(DayOffset)].To<int>(); } set { ExtensionInfo[nameof(DayOffset)] = value; } } [CategoryLoc(_sourceName)] [DisplayNameLoc(LocalizedStrings.Str2286Key)] [DescriptionLoc(LocalizedStrings.Str2287Key)] [PropertyOrder(5)] public bool IgnoreWeekends { get { return (bool)ExtensionInfo[nameof(IgnoreWeekends)]; } set { ExtensionInfo[nameof(IgnoreWeekends)] = value; } } [Browsable(false)] public override IEnumerable<Level1Fields> SupportedLevel1Fields { get { return base.SupportedLevel1Fields; } set { base.SupportedLevel1Fields = value; } } } private HydraServerSettings _settings; public HydraServerTask() { SupportedDataTypes = new[] { TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15), TimeSpan.FromHours(1), TimeSpan.FromDays(1) } .Select(tf => DataType.Create(typeof(TimeFrameCandleMessage), tf)) .Concat(new[] { DataType.Create(typeof(ExecutionMessage), ExecutionTypes.Tick), DataType.Create(typeof(ExecutionMessage), ExecutionTypes.Transaction), DataType.Create(typeof(ExecutionMessage), ExecutionTypes.OrderLog), DataType.Create(typeof(QuoteChangeMessage), null), DataType.Create(typeof(Level1ChangeMessage), null), DataType.Create(typeof(NewsMessage), null), }) .ToArray(); } protected override void ApplySettings(HydraTaskSettings settings) { _settings = new HydraServerSettings(settings); if (settings.IsDefault) { _settings.DayOffset = 1; _settings.StartFrom = new DateTime(2000,1,1); _settings.Address = "net.tcp://localhost:8000".To<Uri>(); _settings.Login = string.Empty; _settings.Password = new SecureString(); _settings.Interval = TimeSpan.FromDays(1); _settings.IgnoreWeekends = true; } } public override HydraTaskSettings Settings => _settings; public override IEnumerable<DataType> SupportedDataTypes { get; } protected override TimeSpan OnProcess() { using (var client = CreateClient()) { var allSecurity = this.GetAllSecurity(); if (allSecurity != null) { this.AddInfoLog(LocalizedStrings.Str2305); client.Refresh(EntityRegistry.Securities, new Security(), SaveSecurity, () => !CanProcess(false)); } var supportedDataTypes = Enumerable.Empty<DataType>(); if (allSecurity != null) supportedDataTypes = SupportedDataTypes.Intersect(allSecurity.DataTypes).ToArray(); this.AddInfoLog(LocalizedStrings.Str2306Params.Put(_settings.StartFrom)); var hasSecurities = false; foreach (var security in GetWorkingSecurities()) { hasSecurities = true; if (!CanProcess()) break; this.AddInfoLog(LocalizedStrings.Str2307Params.Put(security.Security.Id)); //foreach (var dataType in security.GetSupportDataTypes(this)) foreach (var pair in (allSecurity == null ? security.DataTypes : supportedDataTypes)) { if (!CanProcess()) break; if (!DownloadData(security, pair.MessageType, pair.Arg, client)) break; } } if (!hasSecurities) { this.AddWarningLog(LocalizedStrings.Str2292); return TimeSpan.MaxValue; } if (CanProcess()) this.AddInfoLog(LocalizedStrings.Str2300); return base.OnProcess(); } } private bool DownloadData(HydraTaskSecurity security, Type dataType, object arg, RemoteStorageClient client) { var localStorage = StorageRegistry.GetStorage(security.Security, dataType, arg, _settings.Drive, _settings.StorageFormat); var remoteStorage = client.GetRemoteStorage(security.Security.ToSecurityId(), dataType, arg, _settings.StorageFormat); var endDate = DateTime.Today - TimeSpan.FromDays(_settings.DayOffset); var dates = remoteStorage.Dates.Where(date => date >= _settings.StartFrom && date <= endDate).Except(localStorage.Dates).ToArray(); if (dates.IsEmpty()) { if (!CanProcess()) return false; } else { this.AddInfoLog(LocalizedStrings.Str2308Params.Put(dataType.Name)); foreach (var date in dates) { if (!CanProcess()) return false; if (_settings.IgnoreWeekends && !security.IsTradeDate(date)) { this.AddDebugLog(LocalizedStrings.WeekEndDate, date); continue; } this.AddDebugLog(LocalizedStrings.StartDownloding, dataType, arg, date, security.Security.Id); using (var stream = remoteStorage.LoadStream(date)) { if (stream == Stream.Null) { this.AddDebugLog(LocalizedStrings.NoData); continue; } this.AddInfoLog(LocalizedStrings.Str2309Params.Put(date)); localStorage.Drive.SaveStream(date, stream); var info = localStorage.Serializer.CreateMetaInfo(date); stream.Position = 0; info.Read(stream); if (dataType == typeof(Trade)) { dataType = typeof(ExecutionMessage); arg = ExecutionTypes.Tick; } else if (dataType == typeof(OrderLogItem)) { dataType = typeof(ExecutionMessage); arg = ExecutionTypes.OrderLog; } else if (dataType.IsCandle()) { dataType = dataType.ToCandleMessageType(); } RaiseDataLoaded(security.Security, dataType, arg, date, info.Count); } } } return true; } void ISecurityDownloader.Refresh(ISecurityStorage storage, Security criteria, Action<Security> newSecurity, Func<bool> isCancelled) { using (var client = CreateClient()) client.Refresh(storage, criteria, newSecurity, isCancelled); } private RemoteStorageClient CreateClient() { return new RemoteStorageClient(_settings.Address) { Credentials = { Login = _settings.Login, Password = _settings.Password } }; } } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Linq; using FluentMigrator.Builders.Create.Table; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Model; using FluentMigrator.Runner.Extensions; using Moq; using NUnit.Framework; using NUnit.Should; using FluentMigrator.Builders; namespace FluentMigrator.Tests.Unit.Builders.Create { [TestFixture] public class CreateTableExpressionBuilderTests { [Test] public void CallingAsAnsiStringSetsColumnDbTypeToAnsiString() { VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString()); } [Test] public void CallingAsAnsiStringWithSizeSetsColumnDbTypeToAnsiString() { VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString(255)); } [Test] public void CallingAsAnsiStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsAnsiString(255)); } [Test] public void CallingAsBinarySetsColumnDbTypeToBinary() { VerifyColumnDbType(DbType.Binary, b => b.AsBinary(255)); } [Test] public void CallingAsBinarySetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsBinary(255)); } [Test] public void CallingAsBooleanSetsColumnDbTypeToBoolean() { VerifyColumnDbType(DbType.Boolean, b => b.AsBoolean()); } [Test] public void CallingAsByteSetsColumnDbTypeToByte() { VerifyColumnDbType(DbType.Byte, b => b.AsByte()); } [Test] public void CallingAsCurrencySetsColumnDbTypeToCurrency() { VerifyColumnDbType(DbType.Currency, b => b.AsCurrency()); } [Test] public void CallingAsDateSetsColumnDbTypeToDate() { VerifyColumnDbType(DbType.Date, b => b.AsDate()); } [Test] public void CallingAsDateTimeSetsColumnDbTypeToDateTime() { VerifyColumnDbType(DbType.DateTime, b => b.AsDateTime()); } [Test] public void CallingAsDateTimeOffsetSetsColumnDbTypeToDateTimeOffset() { VerifyColumnDbType(DbType.DateTimeOffset, b => b.AsDateTimeOffset()); } [Test] public void CallingAsDecimalSetsColumnDbTypeToDecimal() { VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal()); } [Test] public void CallingAsDecimalWithSizeSetsColumnDbTypeToDecimal() { VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal(1, 2)); } [Test] public void CallingAsDecimalStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(1, b => b.AsDecimal(1, 2)); } [Test] public void CallingAsDecimalStringSetsColumnPrecisionToSpecifiedValue() { VerifyColumnPrecision(2, b => b.AsDecimal(1, 2)); } [Test] public void CallingAsDoubleSetsColumnDbTypeToDouble() { VerifyColumnDbType(DbType.Double, b => b.AsDouble()); } [Test] public void CallingAsGuidSetsColumnDbTypeToGuid() { VerifyColumnDbType(DbType.Guid, b => b.AsGuid()); } [Test] public void CallingAsFixedLengthStringSetsColumnDbTypeToStringFixedLength() { VerifyColumnDbType(DbType.StringFixedLength, e => e.AsFixedLengthString(255)); } [Test] public void CallingAsFixedLengthStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsFixedLengthString(255)); } [Test] public void CallingAsFixedLengthAnsiStringSetsColumnDbTypeToAnsiStringFixedLength() { VerifyColumnDbType(DbType.AnsiStringFixedLength, b => b.AsFixedLengthAnsiString(255)); } [Test] public void CallingAsFixedLengthAnsiStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255)); } [Test] public void CallingAsFloatSetsColumnDbTypeToSingle() { VerifyColumnDbType(DbType.Single, b => b.AsFloat()); } [Test] public void CallingAsInt16SetsColumnDbTypeToInt16() { VerifyColumnDbType(DbType.Int16, b => b.AsInt16()); } [Test] public void CallingAsInt32SetsColumnDbTypeToInt32() { VerifyColumnDbType(DbType.Int32, b => b.AsInt32()); } [Test] public void CallingAsInt64SetsColumnDbTypeToInt64() { VerifyColumnDbType(DbType.Int64, b => b.AsInt64()); } [Test] public void CallingAsStringSetsColumnDbTypeToString() { VerifyColumnDbType(DbType.String, b => b.AsString()); } [Test] public void CallingAsStringWithSizeSetsColumnDbTypeToString() { VerifyColumnDbType(DbType.String, b => b.AsString(255)); } [Test] public void CallingAsStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255)); } [Test] public void CallingAsTimeSetsColumnDbTypeToTime() { VerifyColumnDbType(DbType.Time, b => b.AsTime()); } [Test] public void CallingAsXmlSetsColumnDbTypeToXml() { VerifyColumnDbType(DbType.Xml, b => b.AsXml()); } [Test] public void CallingAsXmlWithSizeSetsColumnDbTypeToXml() { VerifyColumnDbType(DbType.Xml, b => b.AsXml(255)); } [Test] public void CallingAsXmlSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsXml(255)); } [Test] public void CallingAsCustomSetsTypeToNullAndSetsCustomType() { VerifyColumnProperty(c => c.Type = null, b => b.AsCustom("Test")); VerifyColumnProperty(c => c.CustomType = "Test", b => b.AsCustom("Test")); } [Test] public void CallingWithDefaultValueSetsDefaultValue() { const int value = 42; var contextMock = new Mock<IMigrationContext>(); var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateTableExpression>(); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); builder.CurrentColumn = columnMock.Object; builder.WithDefaultValue(42); columnMock.VerifySet(c => c.DefaultValue = value); } [Test] public void CallingWithDefaultSetsDefaultValue() { var contextMock = new Mock<IMigrationContext>(); var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateTableExpression>(); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); builder.CurrentColumn = columnMock.Object; builder.WithDefault(SystemMethods.CurrentDateTime); columnMock.VerifySet(c => c.DefaultValue = SystemMethods.CurrentDateTime); } [Test] public void CallingForeignKeySetsIsForeignKeyToTrue() { VerifyColumnProperty(c => c.IsForeignKey = true, b => b.ForeignKey()); } [Test] public void CallingIdentitySetsIsIdentityToTrue() { VerifyColumnProperty(c => c.IsIdentity = true, b => b.Identity()); } [Test] public void CallingIdentityWithSeededIdentitySetsAdditionalProperties() { var contextMock = new Mock<IMigrationContext>(); var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateTableExpression>(); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); builder.CurrentColumn = columnMock.Object; builder.Identity(12, 44); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(SqlServerExtensions.IdentitySeed, 12)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(SqlServerExtensions.IdentityIncrement, 44)); } [Test] public void CallingIndexedCallsHelperWithNullIndexName() { VerifyColumnHelperCall(c => c.Indexed(), h => h.Indexed(null)); } [Test] public void CallingIndexedNamedCallsHelperWithName() { VerifyColumnHelperCall(c => c.Indexed("MyIndexName"), h => h.Indexed("MyIndexName")); } [Test] public void CallingPrimaryKeySetsIsPrimaryKeyToTrue() { VerifyColumnProperty(c => c.IsPrimaryKey = true, b => b.PrimaryKey()); } [Test] public void NullableUsesHelper() { VerifyColumnHelperCall(c => c.Nullable(), h => h.SetNullable(true)); } [Test] public void NotNullableUsesHelper() { VerifyColumnHelperCall(c => c.NotNullable(), h => h.SetNullable(false)); } [Test] public void UniqueUsesHelper() { VerifyColumnHelperCall(c => c.Unique(), h => h.Unique(null)); } [Test] public void NamedUniqueUsesHelper() { VerifyColumnHelperCall(c => c.Unique("asdf"), h => h.Unique("asdf")); } [Test] public void CallingReferencesAddsNewForeignKeyExpressionToContext() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateTableExpression>(); expressionMock.SetupGet(x => x.TableName).Returns("Bacon"); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object) { CurrentColumn = columnMock.Object }; builder.References("fk_foo", "FooTable", new[] { "BarColumn" }); collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>( fk => fk.ForeignKey.Name == "fk_foo" && fk.ForeignKey.ForeignTable == "FooTable" && fk.ForeignKey.ForeignColumns.Contains("BarColumn") && fk.ForeignKey.ForeignColumns.Count == 1 && fk.ForeignKey.PrimaryTable == "Bacon" && fk.ForeignKey.PrimaryColumns.Contains("BaconId") && fk.ForeignKey.PrimaryColumns.Count == 1 ))); contextMock.VerifyGet(x => x.Expressions); } [Test] public void CallingReferencedByAddsNewForeignKeyExpressionToContext() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateTableExpression>(); expressionMock.SetupGet(x => x.TableName).Returns("Bacon"); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object) { CurrentColumn = columnMock.Object }; builder.ReferencedBy("fk_foo", "FooTable", "BarColumn"); collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>( fk => fk.ForeignKey.Name == "fk_foo" && fk.ForeignKey.ForeignTable == "FooTable" && fk.ForeignKey.ForeignColumns.Contains("BarColumn") && fk.ForeignKey.ForeignColumns.Count == 1 && fk.ForeignKey.PrimaryTable == "Bacon" && fk.ForeignKey.PrimaryColumns.Contains("BaconId") && fk.ForeignKey.PrimaryColumns.Count == 1 ))); contextMock.VerifyGet(x => x.Expressions); } [Test] public void CallingForeignKeyAddsNewForeignKeyExpressionToContext() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateTableExpression>(); expressionMock.SetupGet(x => x.TableName).Returns("Bacon"); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object) { CurrentColumn = columnMock.Object }; builder.ForeignKey("fk_foo", "FooTable", "BarColumn"); collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>( fk => fk.ForeignKey.Name == "fk_foo" && fk.ForeignKey.PrimaryTable == "FooTable" && fk.ForeignKey.PrimaryColumns.Contains("BarColumn") && fk.ForeignKey.PrimaryColumns.Count == 1 && fk.ForeignKey.ForeignTable == "Bacon" && fk.ForeignKey.ForeignColumns.Contains("BaconId") && fk.ForeignKey.ForeignColumns.Count == 1 ))); contextMock.VerifyGet(x => x.Expressions); } [TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)] public void CallingOnUpdateSetsOnUpdateOnForeignKeyExpression(Rule rule) { var builder = new CreateTableExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() }; builder.OnUpdate(rule); Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule)); Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(Rule.None)); } [TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)] public void CallingOnDeleteSetsOnDeleteOnForeignKeyExpression(Rule rule) { var builder = new CreateTableExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() }; builder.OnDelete(rule); Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(Rule.None)); Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule)); } [TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)] public void CallingOnDeleteOrUpdateSetsOnUpdateAndOnDeleteOnForeignKeyExpression(Rule rule) { var builder = new CreateTableExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() }; builder.OnDeleteOrUpdate(rule); Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule)); Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule)); } [Test] public void CallingWithColumnAddsNewColumnToExpression() { const string name = "BaconId"; var collectionMock = new Mock<IList<ColumnDefinition>>(); var expressionMock = new Mock<CreateTableExpression>(); expressionMock.SetupGet(e => e.Columns).Returns(collectionMock.Object); var contextMock = new Mock<IMigrationContext>(); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); builder.WithColumn(name); collectionMock.Verify(x => x.Add(It.Is<ColumnDefinition>(c => c.Name.Equals(name)))); expressionMock.VerifyGet(e => e.Columns); } [Test] public void ColumnHelperSetOnCreation() { var expressionMock = new Mock<CreateTableExpression>(); var contextMock = new Mock<IMigrationContext>(); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); Assert.IsNotNull(builder.ColumnHelper); } [Test] public void IColumnExpressionBuilder_UsesExpressionSchemaAndTableName() { var expressionMock = new Mock<CreateTableExpression>(); var contextMock = new Mock<IMigrationContext>(); expressionMock.SetupGet(n => n.SchemaName).Returns("Fred"); expressionMock.SetupGet(n => n.TableName).Returns("Flinstone"); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); var builderAsInterface = (IColumnExpressionBuilder)builder; Assert.AreEqual("Fred", builderAsInterface.SchemaName); Assert.AreEqual("Flinstone", builderAsInterface.TableName); } [Test] public void IColumnExpressionBuilder_UsesCurrentColumn() { var expressionMock = new Mock<CreateTableExpression>(); var contextMock = new Mock<IMigrationContext>(); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); var curColumn = new Mock<ColumnDefinition>().Object; builder.CurrentColumn = curColumn; var builderAsInterface = (IColumnExpressionBuilder)builder; Assert.AreSame(curColumn, builderAsInterface.Column); } private void VerifyColumnHelperCall(Action<CreateTableExpressionBuilder> callToTest, System.Linq.Expressions.Expression<Action<ColumnExpressionBuilderHelper>> expectedHelperAction) { var expressionMock = new Mock<CreateTableExpression>(); var contextMock = new Mock<IMigrationContext>(); var helperMock = new Mock<ColumnExpressionBuilderHelper>(); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); builder.ColumnHelper = helperMock.Object; callToTest(builder); helperMock.Verify(expectedHelperAction); } private void VerifyColumnProperty(Action<ColumnDefinition> columnExpression, Action<CreateTableExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateTableExpression>(); var contextMock = new Mock<IMigrationContext>(); contextMock.SetupGet(mc => mc.Expressions).Returns(new Collection<IMigrationExpression>()); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); builder.CurrentColumn = columnMock.Object; callToTest(builder); columnMock.VerifySet(columnExpression); } private void VerifyColumnDbType(DbType expected, Action<CreateTableExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateTableExpression>(); var contextMock = new Mock<IMigrationContext>(); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); builder.CurrentColumn = columnMock.Object; callToTest(builder); columnMock.VerifySet(c => c.Type = expected); } private void VerifyColumnSize(int expected, Action<CreateTableExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateTableExpression>(); var contextMock = new Mock<IMigrationContext>(); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); builder.CurrentColumn = columnMock.Object; callToTest(builder); columnMock.VerifySet(c => c.Size = expected); } private void VerifyColumnPrecision(int expected, Action<CreateTableExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateTableExpression>(); var contextMock = new Mock<IMigrationContext>(); var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object); builder.CurrentColumn = columnMock.Object; callToTest(builder); columnMock.VerifySet(c => c.Precision = expected); } } }
using System; using System.Collections.Generic; using System.Diagnostics; #if WINRT && !UNITY_EDITOR using Windows.Networking; using Windows.Networking.Connectivity; #else using System.Net; using System.Net.Sockets; using System.Net.NetworkInformation; #endif namespace LiteNetLib { #if WINRT && !UNITY_EDITOR public enum ConsoleColor { Gray, Yellow, Cyan, DarkCyan, DarkGreen, Blue, DarkRed, Red, Green, DarkYellow } #endif [Flags] public enum LocalAddrType { IPv4 = 1, IPv6 = 2, All = 3 } public static class NetUtils { internal static int RelativeSequenceNumber(int number, int expected) { return (number - expected + NetConstants.MaxSequence + NetConstants.HalfMaxSequence) % NetConstants.MaxSequence - NetConstants.HalfMaxSequence; } internal static int GetDividedPacketsCount(int size, int mtu) { return (size / mtu) + (size % mtu == 0 ? 0 : 1); } public static void PrintInterfaceInfos() { #if !WINRT || UNITY_EDITOR DebugWriteForce(ConsoleColor.Green, "IPv6Support: {0}", Socket.OSSupportsIPv6); try { foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork || ip.Address.AddressFamily == AddressFamily.InterNetworkV6) { DebugWriteForce( ConsoleColor.Green, "Interface: {0}, Type: {1}, Ip: {2}, OpStatus: {3}", ni.Name, ni.NetworkInterfaceType.ToString(), ip.Address.ToString(), ni.OperationalStatus.ToString()); } } } } catch (Exception e) { DebugWriteForce(ConsoleColor.Red, "Error while getting interface infos: {0}", e.ToString()); } #endif } public static void GetLocalIpList(List<string> targetList, LocalAddrType addrType) { bool ipv4 = (addrType & LocalAddrType.IPv4) == LocalAddrType.IPv4; bool ipv6 = (addrType & LocalAddrType.IPv6) == LocalAddrType.IPv6; #if WINRT && !UNITY_EDITOR foreach (HostName localHostName in NetworkInformation.GetHostNames()) { if (localHostName.IPInformation != null && ((ipv4 && localHostName.Type == HostNameType.Ipv4) || (ipv6 && localHostName.Type == HostNameType.Ipv6))) { targetList.Add(localHostName.ToString()); } } #else try { foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { //Skip loopback if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue; var ipProps = ni.GetIPProperties(); //Skip address without gateway if (ipProps.GatewayAddresses.Count == 0) continue; foreach (UnicastIPAddressInformation ip in ipProps.UnicastAddresses) { var address = ip.Address; if ((ipv4 && address.AddressFamily == AddressFamily.InterNetwork) || (ipv6 && address.AddressFamily == AddressFamily.InterNetworkV6)) targetList.Add(address.ToString()); } } } catch { //ignored } //Fallback mode (unity android) if (targetList.Count == 0) { #if NETCORE var hostTask = Dns.GetHostEntryAsync(Dns.GetHostName()); hostTask.Wait(); var host = hostTask.Result; #else var host = Dns.GetHostEntry(Dns.GetHostName()); #endif foreach (IPAddress ip in host.AddressList) { if((ipv4 && ip.AddressFamily == AddressFamily.InterNetwork) || (ipv6 && ip.AddressFamily == AddressFamily.InterNetworkV6)) targetList.Add(ip.ToString()); } } #endif if (targetList.Count == 0) { if(ipv4) targetList.Add("127.0.0.1"); if(ipv6) targetList.Add("::1"); } } private static readonly List<string> IpList = new List<string>(); public static string GetLocalIp(LocalAddrType addrType) { lock (IpList) { IpList.Clear(); GetLocalIpList(IpList, addrType); return IpList.Count == 0 ? string.Empty : IpList[0]; } } private static readonly object DebugLogLock = new object(); private static void DebugWriteLogic(ConsoleColor color, string str, params object[] args) { lock (DebugLogLock) { if (NetDebug.Logger == null) { #if UNITY_5 UnityEngine.Debug.LogFormat(str, args); #elif WINRT Debug.WriteLine(str, args); #else Console.ForegroundColor = color; Console.WriteLine(str, args); Console.ForegroundColor = ConsoleColor.Gray; #endif } else { NetDebug.Logger.WriteNet(color, str, args); } } } [Conditional("DEBUG_MESSAGES")] internal static void DebugWrite(string str, params object[] args) { DebugWriteLogic(ConsoleColor.DarkGreen, str, args); } [Conditional("DEBUG_MESSAGES")] internal static void DebugWrite(ConsoleColor color, string str, params object[] args) { DebugWriteLogic(color, str, args); } [Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")] internal static void DebugWriteForce(ConsoleColor color, string str, params object[] args) { DebugWriteLogic(color, str, args); } [Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")] internal static void DebugWriteError(string str, params object[] args) { DebugWriteLogic(ConsoleColor.Red, str, args); } } }
/*************************************************************************** * Attributes.cs * ------------------- * begin : May 1, 2002 * copyright : (C) The RunUO Software Team * email : info@runuo.com * * $Id: Attributes.cs 274 2007-12-17 20:41:34Z mark $ * ***************************************************************************/ /*************************************************************************** * * 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. * ***************************************************************************/ using System; using System.Collections.Generic; using System.Reflection; namespace Server { [AttributeUsage( AttributeTargets.Property )] public class HueAttribute : Attribute { public HueAttribute() { } } [AttributeUsage( AttributeTargets.Property )] public class BodyAttribute : Attribute { public BodyAttribute() { } } [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct )] public class PropertyObjectAttribute : Attribute { public PropertyObjectAttribute() { } } [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct )] public class NoSortAttribute : Attribute { public NoSortAttribute() { } } [AttributeUsage( AttributeTargets.Method )] public class CallPriorityAttribute : Attribute { private int m_Priority; public int Priority { get{ return m_Priority; } set{ m_Priority = value; } } public CallPriorityAttribute( int priority ) { m_Priority = priority; } } public class CallPriorityComparer : IComparer<MethodInfo> { public int Compare( MethodInfo x, MethodInfo y ) { if ( x == null && y == null ) return 0; if ( x == null ) return 1; if ( y == null ) return -1; return GetPriority( x ) - GetPriority( y ); } private int GetPriority( MethodInfo mi ) { object[] objs = mi.GetCustomAttributes( typeof( CallPriorityAttribute ), true ); if ( objs == null ) return 0; if ( objs.Length == 0 ) return 0; CallPriorityAttribute attr = objs[0] as CallPriorityAttribute; if ( attr == null ) return 0; return attr.Priority; } } [AttributeUsage( AttributeTargets.Class )] public class TypeAliasAttribute : Attribute { private string[] m_Aliases; public string[] Aliases { get { return m_Aliases; } } public TypeAliasAttribute( params string[] aliases ) { m_Aliases = aliases; } } [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct )] public class ParsableAttribute : Attribute { public ParsableAttribute() { } } [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum )] public class CustomEnumAttribute : Attribute { private string[] m_Names; public string[] Names { get { return m_Names; } } public CustomEnumAttribute( string[] names ) { m_Names = names; } } [AttributeUsage( AttributeTargets.Constructor )] public class ConstructableAttribute : Attribute { private AccessLevel m_AccessLevel; public AccessLevel AccessLevel { get { return m_AccessLevel; } set { m_AccessLevel = value; } } public ConstructableAttribute() : this( AccessLevel.Player ) //Lowest accesslevel for current functionality (Level determined by access to [add) { } public ConstructableAttribute( AccessLevel accessLevel ) { m_AccessLevel = accessLevel; } } [AttributeUsage( AttributeTargets.Property )] public class CommandPropertyAttribute : Attribute { private AccessLevel m_ReadLevel, m_WriteLevel; private bool m_ReadOnly; public AccessLevel ReadLevel { get { return m_ReadLevel; } } public AccessLevel WriteLevel { get { return m_WriteLevel; } } public bool ReadOnly { get { return m_ReadOnly; } } public CommandPropertyAttribute( AccessLevel level, bool readOnly ) { m_ReadLevel = level; m_ReadOnly = readOnly; } public CommandPropertyAttribute( AccessLevel level ) : this( level, level ) { } public CommandPropertyAttribute( AccessLevel readLevel, AccessLevel writeLevel ) { m_ReadLevel = readLevel; m_WriteLevel = writeLevel; } } }
//#define DEBUGREADERS using System; using System.Data; using ExcelDataReader.Desktop.Portable; namespace Excel { public class ExcelOpenXmlReader : IExcelDataReader { private readonly ExcelDataReader.Portable.IExcelDataReader portable; private bool disposed; #region Members #endregion internal ExcelOpenXmlReader(ExcelDataReader.Portable.IExcelDataReader portable) { this.portable = portable; //_isValid = true; //_isFirstRead = true; //_defaultDateTimeStyles = new List<int>(new int[] //{ // 14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47 //}); } #region IExcelDataReader Members public void Initialize(System.IO.Stream fileStream) { portable.Initialize(fileStream); } public DataSet AsDataSet() { return AsDataSet(true); } //todo: this is identical in ExcelBinaryReader public DataSet AsDataSet(bool convertOADateTime) { var datasetHelper = new DatasetHelper(); portable.LoadDataSet(datasetHelper, convertOADateTime); return (DataSet)datasetHelper.Dataset; } public bool IsFirstRowAsColumnNames { get { return portable.IsFirstRowAsColumnNames; } set { portable.IsFirstRowAsColumnNames = value; } } public bool IsValid { get { return portable.IsValid; } } public string ExceptionMessage { get { return portable.ExceptionMessage; } } public string Name { get { return portable.Name; } } public string VisibleState { get { return portable.VisibleState; } } public void Close() { portable.Close(); } public int Depth { get { return portable.Depth; } } public int ResultsCount { get { return portable.ResultsCount; } } public bool IsClosed { get { return portable.IsClosed; } } public bool NextResult() { return portable.NextResult(); } public bool Read() { return portable.Read(); } public int FieldCount { get { return portable.FieldCount; } } public bool GetBoolean(int i) { return portable.GetBoolean(i); } public DateTime GetDateTime(int i) { return portable.GetDateTime(i); } public decimal GetDecimal(int i) { return portable.GetDecimal(i); } public double GetDouble(int i) { return portable.GetDouble(i); } public float GetFloat(int i) { return portable.GetFloat(i); } public short GetInt16(int i) { return portable.GetInt16(i); } public int GetInt32(int i) { return portable.GetInt32(i); } public long GetInt64(int i) { return portable.GetInt64(i); } public string GetString(int i) { return portable.GetString(i); } public object GetValue(int i) { return portable.GetValue(i); } public bool IsDBNull(int i) { return portable.IsDBNull(i); } public object this[int i] { get { return portable[i]; } } #endregion #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { if (disposing) { portable.Dispose(); } disposed = true; } } ~ExcelOpenXmlReader() { Dispose(false); } #endregion #region Not Supported IDataReader Members public DataTable GetSchemaTable() { throw new NotSupportedException(); } public int RecordsAffected { get { throw new NotSupportedException(); } } #endregion #region Not Supported IDataRecord Members public byte GetByte(int i) { throw new NotSupportedException(); } public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { throw new NotSupportedException(); } public char GetChar(int i) { throw new NotSupportedException(); } public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { throw new NotSupportedException(); } public IDataReader GetData(int i) { throw new NotSupportedException(); } public string GetDataTypeName(int i) { throw new NotSupportedException(); } public Type GetFieldType(int i) { throw new NotSupportedException(); } public Guid GetGuid(int i) { throw new NotSupportedException(); } public string GetName(int i) { throw new NotSupportedException(); } public int GetOrdinal(string name) { throw new NotSupportedException(); } public int GetValues(object[] values) { throw new NotSupportedException(); } public object this[string name] { get { throw new NotSupportedException(); } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSLInteger = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass { // LSL CONSTANTS public static readonly LSLInteger TRUE = new LSLInteger(1); public static readonly LSLInteger FALSE = new LSLInteger(0); public const int STATUS_PHYSICS = 1; public const int STATUS_ROTATE_X = 2; public const int STATUS_ROTATE_Y = 4; public const int STATUS_ROTATE_Z = 8; public const int STATUS_PHANTOM = 16; public const int STATUS_SANDBOX = 32; public const int STATUS_BLOCK_GRAB = 64; public const int STATUS_DIE_AT_EDGE = 128; public const int STATUS_RETURN_AT_EDGE = 256; public const int STATUS_CAST_SHADOWS = 512; public const int AGENT = 1; public const int AGENT_BY_LEGACY_NAME = 1; public const int AGENT_BY_USERNAME = 0x10; public const int NPC = 0x20; public const int ACTIVE = 2; public const int PASSIVE = 4; public const int SCRIPTED = 8; public const int OS_NPC = 0x01000000; public const int CONTROL_FWD = 1; public const int CONTROL_BACK = 2; public const int CONTROL_LEFT = 4; public const int CONTROL_RIGHT = 8; public const int CONTROL_UP = 16; public const int CONTROL_DOWN = 32; public const int CONTROL_ROT_LEFT = 256; public const int CONTROL_ROT_RIGHT = 512; public const int CONTROL_LBUTTON = 268435456; public const int CONTROL_ML_LBUTTON = 1073741824; //Permissions public const int PERMISSION_DEBIT = 2; public const int PERMISSION_TAKE_CONTROLS = 4; public const int PERMISSION_REMAP_CONTROLS = 8; public const int PERMISSION_TRIGGER_ANIMATION = 16; public const int PERMISSION_ATTACH = 32; public const int PERMISSION_RELEASE_OWNERSHIP = 64; public const int PERMISSION_CHANGE_LINKS = 128; public const int PERMISSION_CHANGE_JOINTS = 256; public const int PERMISSION_CHANGE_PERMISSIONS = 512; public const int PERMISSION_TRACK_CAMERA = 1024; public const int PERMISSION_CONTROL_CAMERA = 2048; public const int AGENT_FLYING = 1; public const int AGENT_ATTACHMENTS = 2; public const int AGENT_SCRIPTED = 4; public const int AGENT_MOUSELOOK = 8; public const int AGENT_SITTING = 16; public const int AGENT_ON_OBJECT = 32; public const int AGENT_AWAY = 64; public const int AGENT_WALKING = 128; public const int AGENT_IN_AIR = 256; public const int AGENT_TYPING = 512; public const int AGENT_CROUCHING = 1024; public const int AGENT_BUSY = 2048; public const int AGENT_ALWAYS_RUN = 4096; //Particle Systems public const int PSYS_PART_INTERP_COLOR_MASK = 1; public const int PSYS_PART_INTERP_SCALE_MASK = 2; public const int PSYS_PART_BOUNCE_MASK = 4; public const int PSYS_PART_WIND_MASK = 8; public const int PSYS_PART_FOLLOW_SRC_MASK = 16; public const int PSYS_PART_FOLLOW_VELOCITY_MASK = 32; public const int PSYS_PART_TARGET_POS_MASK = 64; public const int PSYS_PART_TARGET_LINEAR_MASK = 128; public const int PSYS_PART_EMISSIVE_MASK = 256; public const int PSYS_PART_FLAGS = 0; public const int PSYS_PART_START_COLOR = 1; public const int PSYS_PART_START_ALPHA = 2; public const int PSYS_PART_END_COLOR = 3; public const int PSYS_PART_END_ALPHA = 4; public const int PSYS_PART_START_SCALE = 5; public const int PSYS_PART_END_SCALE = 6; public const int PSYS_PART_MAX_AGE = 7; public const int PSYS_SRC_ACCEL = 8; public const int PSYS_SRC_PATTERN = 9; public const int PSYS_SRC_INNERANGLE = 10; public const int PSYS_SRC_OUTERANGLE = 11; public const int PSYS_SRC_TEXTURE = 12; public const int PSYS_SRC_BURST_RATE = 13; public const int PSYS_SRC_BURST_PART_COUNT = 15; public const int PSYS_SRC_BURST_RADIUS = 16; public const int PSYS_SRC_BURST_SPEED_MIN = 17; public const int PSYS_SRC_BURST_SPEED_MAX = 18; public const int PSYS_SRC_MAX_AGE = 19; public const int PSYS_SRC_TARGET_KEY = 20; public const int PSYS_SRC_OMEGA = 21; public const int PSYS_SRC_ANGLE_BEGIN = 22; public const int PSYS_SRC_ANGLE_END = 23; public const int PSYS_SRC_PATTERN_DROP = 1; public const int PSYS_SRC_PATTERN_EXPLODE = 2; public const int PSYS_SRC_PATTERN_ANGLE = 4; public const int PSYS_SRC_PATTERN_ANGLE_CONE = 8; public const int PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY = 16; public const int VEHICLE_TYPE_NONE = 0; public const int VEHICLE_TYPE_SLED = 1; public const int VEHICLE_TYPE_CAR = 2; public const int VEHICLE_TYPE_BOAT = 3; public const int VEHICLE_TYPE_AIRPLANE = 4; public const int VEHICLE_TYPE_BALLOON = 5; public const int VEHICLE_LINEAR_FRICTION_TIMESCALE = 16; public const int VEHICLE_ANGULAR_FRICTION_TIMESCALE = 17; public const int VEHICLE_LINEAR_MOTOR_DIRECTION = 18; public const int VEHICLE_LINEAR_MOTOR_OFFSET = 20; public const int VEHICLE_ANGULAR_MOTOR_DIRECTION = 19; public const int VEHICLE_HOVER_HEIGHT = 24; public const int VEHICLE_HOVER_EFFICIENCY = 25; public const int VEHICLE_HOVER_TIMESCALE = 26; public const int VEHICLE_BUOYANCY = 27; public const int VEHICLE_LINEAR_DEFLECTION_EFFICIENCY = 28; public const int VEHICLE_LINEAR_DEFLECTION_TIMESCALE = 29; public const int VEHICLE_LINEAR_MOTOR_TIMESCALE = 30; public const int VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE = 31; public const int VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY = 32; public const int VEHICLE_ANGULAR_DEFLECTION_TIMESCALE = 33; public const int VEHICLE_ANGULAR_MOTOR_TIMESCALE = 34; public const int VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE = 35; public const int VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY = 36; public const int VEHICLE_VERTICAL_ATTRACTION_TIMESCALE = 37; public const int VEHICLE_BANKING_EFFICIENCY = 38; public const int VEHICLE_BANKING_MIX = 39; public const int VEHICLE_BANKING_TIMESCALE = 40; public const int VEHICLE_REFERENCE_FRAME = 44; public const int VEHICLE_RANGE_BLOCK = 45; public const int VEHICLE_ROLL_FRAME = 46; public const int VEHICLE_FLAG_NO_DEFLECTION_UP = 1; public const int VEHICLE_FLAG_LIMIT_ROLL_ONLY = 2; public const int VEHICLE_FLAG_HOVER_WATER_ONLY = 4; public const int VEHICLE_FLAG_HOVER_TERRAIN_ONLY = 8; public const int VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT = 16; public const int VEHICLE_FLAG_HOVER_UP_ONLY = 32; public const int VEHICLE_FLAG_LIMIT_MOTOR_UP = 64; public const int VEHICLE_FLAG_MOUSELOOK_STEER = 128; public const int VEHICLE_FLAG_MOUSELOOK_BANK = 256; public const int VEHICLE_FLAG_CAMERA_DECOUPLED = 512; public const int VEHICLE_FLAG_NO_X = 1024; public const int VEHICLE_FLAG_NO_Y = 2048; public const int VEHICLE_FLAG_NO_Z = 4096; public const int VEHICLE_FLAG_LOCK_HOVER_HEIGHT = 8192; public const int VEHICLE_FLAG_NO_DEFLECTION = 16392; public const int VEHICLE_FLAG_LOCK_ROTATION = 32784; public const int INVENTORY_ALL = -1; public const int INVENTORY_NONE = -1; public const int INVENTORY_TEXTURE = 0; public const int INVENTORY_SOUND = 1; public const int INVENTORY_LANDMARK = 3; public const int INVENTORY_CLOTHING = 5; public const int INVENTORY_OBJECT = 6; public const int INVENTORY_NOTECARD = 7; public const int INVENTORY_SCRIPT = 10; public const int INVENTORY_BODYPART = 13; public const int INVENTORY_ANIMATION = 20; public const int INVENTORY_GESTURE = 21; public const int ATTACH_CHEST = 1; public const int ATTACH_HEAD = 2; public const int ATTACH_LSHOULDER = 3; public const int ATTACH_RSHOULDER = 4; public const int ATTACH_LHAND = 5; public const int ATTACH_RHAND = 6; public const int ATTACH_LFOOT = 7; public const int ATTACH_RFOOT = 8; public const int ATTACH_BACK = 9; public const int ATTACH_PELVIS = 10; public const int ATTACH_MOUTH = 11; public const int ATTACH_CHIN = 12; public const int ATTACH_LEAR = 13; public const int ATTACH_REAR = 14; public const int ATTACH_LEYE = 15; public const int ATTACH_REYE = 16; public const int ATTACH_NOSE = 17; public const int ATTACH_RUARM = 18; public const int ATTACH_RLARM = 19; public const int ATTACH_LUARM = 20; public const int ATTACH_LLARM = 21; public const int ATTACH_RHIP = 22; public const int ATTACH_RULEG = 23; public const int ATTACH_RLLEG = 24; public const int ATTACH_LHIP = 25; public const int ATTACH_LULEG = 26; public const int ATTACH_LLLEG = 27; public const int ATTACH_BELLY = 28; public const int ATTACH_RPEC = 29; public const int ATTACH_LPEC = 30; public const int ATTACH_LEFT_PEC = 29; // Same value as ATTACH_RPEC, see https://jira.secondlife.com/browse/SVC-580 public const int ATTACH_RIGHT_PEC = 30; // Same value as ATTACH_LPEC, see https://jira.secondlife.com/browse/SVC-580 public const int ATTACH_HUD_CENTER_2 = 31; public const int ATTACH_HUD_TOP_RIGHT = 32; public const int ATTACH_HUD_TOP_CENTER = 33; public const int ATTACH_HUD_TOP_LEFT = 34; public const int ATTACH_HUD_CENTER_1 = 35; public const int ATTACH_HUD_BOTTOM_LEFT = 36; public const int ATTACH_HUD_BOTTOM = 37; public const int ATTACH_HUD_BOTTOM_RIGHT = 38; #region osMessageAttachments constants /// <summary> /// Instructs osMessageAttachements to send the message to attachments /// on every point. /// </summary> /// <remarks> /// One might expect this to be named OS_ATTACH_ALL, but then one might /// also expect functions designed to attach or detach or get /// attachments to work with it too. Attaching a no-copy item to /// many attachments could be dangerous. /// when combined with OS_ATTACH_MSG_INVERT_POINTS, will prevent the /// message from being sent. /// if combined with OS_ATTACH_MSG_OBJECT_CREATOR or /// OS_ATTACH_MSG_SCRIPT_CREATOR, could result in no message being /// sent- this is expected behaviour. /// </remarks> public const int OS_ATTACH_MSG_ALL = -65535; /// <summary> /// Instructs osMessageAttachements to invert how the attachment points /// list should be treated (e.g. go from inclusive operation to /// exclusive operation). /// </summary> /// <remarks> /// This might be used if you want to deliver a message to one set of /// attachments and a different message to everything else. With /// this flag, you only need to build one explicit list for both calls. /// </remarks> public const int OS_ATTACH_MSG_INVERT_POINTS = 1; /// <summary> /// Instructs osMessageAttachments to only send the message to /// attachments with a CreatorID that matches the host object CreatorID /// </summary> /// <remarks> /// This would be used if distributed in an object vendor/updater server. /// </remarks> public const int OS_ATTACH_MSG_OBJECT_CREATOR = 2; /// <summary> /// Instructs osMessageAttachments to only send the message to /// attachments with a CreatorID that matches the sending script CreatorID /// </summary> /// <remarks> /// This might be used if the script is distributed independently of a /// containing object. /// </remarks> public const int OS_ATTACH_MSG_SCRIPT_CREATOR = 4; #endregion public const int LAND_LEVEL = 0; public const int LAND_RAISE = 1; public const int LAND_LOWER = 2; public const int LAND_SMOOTH = 3; public const int LAND_NOISE = 4; public const int LAND_REVERT = 5; public const int LAND_SMALL_BRUSH = 1; public const int LAND_MEDIUM_BRUSH = 2; public const int LAND_LARGE_BRUSH = 3; //Agent Dataserver public const int DATA_ONLINE = 1; public const int DATA_NAME = 2; public const int DATA_BORN = 3; public const int DATA_RATING = 4; public const int DATA_SIM_POS = 5; public const int DATA_SIM_STATUS = 6; public const int DATA_SIM_RATING = 7; public const int DATA_PAYINFO = 8; public const int DATA_SIM_RELEASE = 128; public const int ANIM_ON = 1; public const int LOOP = 2; public const int REVERSE = 4; public const int PING_PONG = 8; public const int SMOOTH = 16; public const int ROTATE = 32; public const int SCALE = 64; public const int ALL_SIDES = -1; public const int LINK_SET = -1; public const int LINK_ROOT = 1; public const int LINK_ALL_OTHERS = -2; public const int LINK_ALL_CHILDREN = -3; public const int LINK_THIS = -4; public const int CHANGED_INVENTORY = 1; public const int CHANGED_COLOR = 2; public const int CHANGED_SHAPE = 4; public const int CHANGED_SCALE = 8; public const int CHANGED_TEXTURE = 16; public const int CHANGED_LINK = 32; public const int CHANGED_ALLOWED_DROP = 64; public const int CHANGED_OWNER = 128; public const int CHANGED_REGION = 256; public const int CHANGED_TELEPORT = 512; public const int CHANGED_REGION_RESTART = 1024; public const int CHANGED_REGION_START = 1024; //LL Changed the constant from CHANGED_REGION_RESTART public const int CHANGED_MEDIA = 2048; public const int CHANGED_ANIMATION = 16384; public const int TYPE_INVALID = 0; public const int TYPE_INTEGER = 1; public const int TYPE_FLOAT = 2; public const int TYPE_STRING = 3; public const int TYPE_KEY = 4; public const int TYPE_VECTOR = 5; public const int TYPE_ROTATION = 6; //XML RPC Remote Data Channel public const int REMOTE_DATA_CHANNEL = 1; public const int REMOTE_DATA_REQUEST = 2; public const int REMOTE_DATA_REPLY = 3; //llHTTPRequest public const int HTTP_METHOD = 0; public const int HTTP_MIMETYPE = 1; public const int HTTP_BODY_MAXLENGTH = 2; public const int HTTP_VERIFY_CERT = 3; public const int PRIM_MATERIAL = 2; public const int PRIM_PHYSICS = 3; public const int PRIM_TEMP_ON_REZ = 4; public const int PRIM_PHANTOM = 5; public const int PRIM_POSITION = 6; public const int PRIM_SIZE = 7; public const int PRIM_ROTATION = 8; public const int PRIM_TYPE = 9; public const int PRIM_TEXTURE = 17; public const int PRIM_COLOR = 18; public const int PRIM_BUMP_SHINY = 19; public const int PRIM_FULLBRIGHT = 20; public const int PRIM_FLEXIBLE = 21; public const int PRIM_TEXGEN = 22; public const int PRIM_CAST_SHADOWS = 24; // Not implemented, here for completeness sake public const int PRIM_POINT_LIGHT = 23; // Huh? public const int PRIM_GLOW = 25; public const int PRIM_TEXT = 26; public const int PRIM_NAME = 27; public const int PRIM_DESC = 28; public const int PRIM_ROT_LOCAL = 29; public const int PRIM_OMEGA = 32; public const int PRIM_POS_LOCAL = 33; public const int PRIM_LINK_TARGET = 34; public const int PRIM_SLICE = 35; public const int PRIM_TEXGEN_DEFAULT = 0; public const int PRIM_TEXGEN_PLANAR = 1; public const int PRIM_TYPE_BOX = 0; public const int PRIM_TYPE_CYLINDER = 1; public const int PRIM_TYPE_PRISM = 2; public const int PRIM_TYPE_SPHERE = 3; public const int PRIM_TYPE_TORUS = 4; public const int PRIM_TYPE_TUBE = 5; public const int PRIM_TYPE_RING = 6; public const int PRIM_TYPE_SCULPT = 7; public const int PRIM_HOLE_DEFAULT = 0; public const int PRIM_HOLE_CIRCLE = 16; public const int PRIM_HOLE_SQUARE = 32; public const int PRIM_HOLE_TRIANGLE = 48; public const int PRIM_MATERIAL_STONE = 0; public const int PRIM_MATERIAL_METAL = 1; public const int PRIM_MATERIAL_GLASS = 2; public const int PRIM_MATERIAL_WOOD = 3; public const int PRIM_MATERIAL_FLESH = 4; public const int PRIM_MATERIAL_PLASTIC = 5; public const int PRIM_MATERIAL_RUBBER = 6; public const int PRIM_MATERIAL_LIGHT = 7; public const int PRIM_SHINY_NONE = 0; public const int PRIM_SHINY_LOW = 1; public const int PRIM_SHINY_MEDIUM = 2; public const int PRIM_SHINY_HIGH = 3; public const int PRIM_BUMP_NONE = 0; public const int PRIM_BUMP_BRIGHT = 1; public const int PRIM_BUMP_DARK = 2; public const int PRIM_BUMP_WOOD = 3; public const int PRIM_BUMP_BARK = 4; public const int PRIM_BUMP_BRICKS = 5; public const int PRIM_BUMP_CHECKER = 6; public const int PRIM_BUMP_CONCRETE = 7; public const int PRIM_BUMP_TILE = 8; public const int PRIM_BUMP_STONE = 9; public const int PRIM_BUMP_DISKS = 10; public const int PRIM_BUMP_GRAVEL = 11; public const int PRIM_BUMP_BLOBS = 12; public const int PRIM_BUMP_SIDING = 13; public const int PRIM_BUMP_LARGETILE = 14; public const int PRIM_BUMP_STUCCO = 15; public const int PRIM_BUMP_SUCTION = 16; public const int PRIM_BUMP_WEAVE = 17; public const int PRIM_SCULPT_TYPE_SPHERE = 1; public const int PRIM_SCULPT_TYPE_TORUS = 2; public const int PRIM_SCULPT_TYPE_PLANE = 3; public const int PRIM_SCULPT_TYPE_CYLINDER = 4; public const int PRIM_SCULPT_FLAG_INVERT = 64; public const int PRIM_SCULPT_FLAG_MIRROR = 128; public const int PROFILE_NONE = 0; public const int PROFILE_SCRIPT_MEMORY = 1; public const int MASK_BASE = 0; public const int MASK_OWNER = 1; public const int MASK_GROUP = 2; public const int MASK_EVERYONE = 3; public const int MASK_NEXT = 4; public const int PERM_TRANSFER = 8192; public const int PERM_MODIFY = 16384; public const int PERM_COPY = 32768; public const int PERM_MOVE = 524288; public const int PERM_ALL = 2147483647; public const int PARCEL_MEDIA_COMMAND_STOP = 0; public const int PARCEL_MEDIA_COMMAND_PAUSE = 1; public const int PARCEL_MEDIA_COMMAND_PLAY = 2; public const int PARCEL_MEDIA_COMMAND_LOOP = 3; public const int PARCEL_MEDIA_COMMAND_TEXTURE = 4; public const int PARCEL_MEDIA_COMMAND_URL = 5; public const int PARCEL_MEDIA_COMMAND_TIME = 6; public const int PARCEL_MEDIA_COMMAND_AGENT = 7; public const int PARCEL_MEDIA_COMMAND_UNLOAD = 8; public const int PARCEL_MEDIA_COMMAND_AUTO_ALIGN = 9; public const int PARCEL_MEDIA_COMMAND_TYPE = 10; public const int PARCEL_MEDIA_COMMAND_SIZE = 11; public const int PARCEL_MEDIA_COMMAND_DESC = 12; public const int PARCEL_FLAG_ALLOW_FLY = 0x1; // parcel allows flying public const int PARCEL_FLAG_ALLOW_SCRIPTS = 0x2; // parcel allows outside scripts public const int PARCEL_FLAG_ALLOW_LANDMARK = 0x8; // parcel allows landmarks to be created public const int PARCEL_FLAG_ALLOW_TERRAFORM = 0x10; // parcel allows anyone to terraform the land public const int PARCEL_FLAG_ALLOW_DAMAGE = 0x20; // parcel allows damage public const int PARCEL_FLAG_ALLOW_CREATE_OBJECTS = 0x40; // parcel allows anyone to create objects public const int PARCEL_FLAG_USE_ACCESS_GROUP = 0x100; // parcel limits access to a group public const int PARCEL_FLAG_USE_ACCESS_LIST = 0x200; // parcel limits access to a list of residents public const int PARCEL_FLAG_USE_BAN_LIST = 0x400; // parcel uses a ban list, including restricting access based on payment info public const int PARCEL_FLAG_USE_LAND_PASS_LIST = 0x800; // parcel allows passes to be purchased public const int PARCEL_FLAG_LOCAL_SOUND_ONLY = 0x8000; // parcel restricts spatialized sound to the parcel public const int PARCEL_FLAG_RESTRICT_PUSHOBJECT = 0x200000; // parcel restricts llPushObject public const int PARCEL_FLAG_ALLOW_GROUP_SCRIPTS = 0x2000000; // parcel allows scripts owned by group public const int PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS = 0x4000000; // parcel allows group object creation public const int PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY = 0x8000000; // parcel allows objects owned by any user to enter public const int PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY = 0x10000000; // parcel allows with the same group to enter public const int REGION_FLAG_ALLOW_DAMAGE = 0x1; // region is entirely damage enabled public const int REGION_FLAG_FIXED_SUN = 0x10; // region has a fixed sun position public const int REGION_FLAG_BLOCK_TERRAFORM = 0x40; // region terraforming disabled public const int REGION_FLAG_SANDBOX = 0x100; // region is a sandbox public const int REGION_FLAG_DISABLE_COLLISIONS = 0x1000; // region has disabled collisions public const int REGION_FLAG_DISABLE_PHYSICS = 0x4000; // region has disabled physics public const int REGION_FLAG_BLOCK_FLY = 0x80000; // region blocks flying public const int REGION_FLAG_ALLOW_DIRECT_TELEPORT = 0x100000; // region allows direct teleports public const int REGION_FLAG_RESTRICT_PUSHOBJECT = 0x400000; // region restricts llPushObject //llManageEstateAccess public const int ESTATE_ACCESS_ALLOWED_AGENT_ADD = 0; public const int ESTATE_ACCESS_ALLOWED_AGENT_REMOVE = 1; public const int ESTATE_ACCESS_ALLOWED_GROUP_ADD = 2; public const int ESTATE_ACCESS_ALLOWED_GROUP_REMOVE = 3; public const int ESTATE_ACCESS_BANNED_AGENT_ADD = 4; public const int ESTATE_ACCESS_BANNED_AGENT_REMOVE = 5; public static readonly LSLInteger PAY_HIDE = new LSLInteger(-1); public static readonly LSLInteger PAY_DEFAULT = new LSLInteger(-2); public const string NULL_KEY = "00000000-0000-0000-0000-000000000000"; public const string EOF = "\n\n\n"; public const double PI = 3.14159274f; public const double TWO_PI = 6.28318548f; public const double PI_BY_TWO = 1.57079637f; public const double DEG_TO_RAD = 0.01745329238f; public const double RAD_TO_DEG = 57.29578f; public const double SQRT2 = 1.414213538f; public const int STRING_TRIM_HEAD = 1; public const int STRING_TRIM_TAIL = 2; public const int STRING_TRIM = 3; public const int LIST_STAT_RANGE = 0; public const int LIST_STAT_MIN = 1; public const int LIST_STAT_MAX = 2; public const int LIST_STAT_MEAN = 3; public const int LIST_STAT_MEDIAN = 4; public const int LIST_STAT_STD_DEV = 5; public const int LIST_STAT_SUM = 6; public const int LIST_STAT_SUM_SQUARES = 7; public const int LIST_STAT_NUM_COUNT = 8; public const int LIST_STAT_GEOMETRIC_MEAN = 9; public const int LIST_STAT_HARMONIC_MEAN = 100; //ParcelPrim Categories public const int PARCEL_COUNT_TOTAL = 0; public const int PARCEL_COUNT_OWNER = 1; public const int PARCEL_COUNT_GROUP = 2; public const int PARCEL_COUNT_OTHER = 3; public const int PARCEL_COUNT_SELECTED = 4; public const int PARCEL_COUNT_TEMP = 5; public const int DEBUG_CHANNEL = 0x7FFFFFFF; public const int PUBLIC_CHANNEL = 0x00000000; // Constants for llGetObjectDetails public const int OBJECT_UNKNOWN_DETAIL = -1; public const int OBJECT_NAME = 1; public const int OBJECT_DESC = 2; public const int OBJECT_POS = 3; public const int OBJECT_ROT = 4; public const int OBJECT_VELOCITY = 5; public const int OBJECT_OWNER = 6; public const int OBJECT_GROUP = 7; public const int OBJECT_CREATOR = 8; public const int OBJECT_RUNNING_SCRIPT_COUNT = 9; public const int OBJECT_TOTAL_SCRIPT_COUNT = 10; public const int OBJECT_SCRIPT_MEMORY = 11; public const int OBJECT_SCRIPT_TIME = 12; public const int OBJECT_PRIM_EQUIVALENCE = 13; public const int OBJECT_SERVER_COST = 14; public const int OBJECT_STREAMING_COST = 15; public const int OBJECT_PHYSICS_COST = 16; public const int OBJECT_CHARACTER_TIME = 17; public const int OBJECT_ROOT = 18; public const int OBJECT_ATTACHED_POINT = 19; public const int OBJECT_PATHFINDING_TYPE = 20; public const int OBJECT_PHYSICS = 21; public const int OBJECT_PHANTOM = 22; public const int OBJECT_TEMP_ON_REZ = 23; // Pathfinding types public const int OPT_OTHER = -1; public const int OPT_LEGACY_LINKSET = 0; public const int OPT_AVATAR = 1; public const int OPT_CHARACTER = 2; public const int OPT_WALKABLE = 3; public const int OPT_STATIC_OBSTACLE = 4; public const int OPT_MATERIAL_VOLUME = 5; public const int OPT_EXCLUSION_VOLUME = 6; // for llGetAgentList public const int AGENT_LIST_PARCEL = 1; public const int AGENT_LIST_PARCEL_OWNER = 2; public const int AGENT_LIST_REGION = 4; // Can not be public const? public static readonly vector ZERO_VECTOR = new vector(0.0, 0.0, 0.0); public static readonly rotation ZERO_ROTATION = new rotation(0.0, 0.0, 0.0, 1.0); // constants for llSetCameraParams public const int CAMERA_PITCH = 0; public const int CAMERA_FOCUS_OFFSET = 1; public const int CAMERA_FOCUS_OFFSET_X = 2; public const int CAMERA_FOCUS_OFFSET_Y = 3; public const int CAMERA_FOCUS_OFFSET_Z = 4; public const int CAMERA_POSITION_LAG = 5; public const int CAMERA_FOCUS_LAG = 6; public const int CAMERA_DISTANCE = 7; public const int CAMERA_BEHINDNESS_ANGLE = 8; public const int CAMERA_BEHINDNESS_LAG = 9; public const int CAMERA_POSITION_THRESHOLD = 10; public const int CAMERA_FOCUS_THRESHOLD = 11; public const int CAMERA_ACTIVE = 12; public const int CAMERA_POSITION = 13; public const int CAMERA_POSITION_X = 14; public const int CAMERA_POSITION_Y = 15; public const int CAMERA_POSITION_Z = 16; public const int CAMERA_FOCUS = 17; public const int CAMERA_FOCUS_X = 18; public const int CAMERA_FOCUS_Y = 19; public const int CAMERA_FOCUS_Z = 20; public const int CAMERA_POSITION_LOCKED = 21; public const int CAMERA_FOCUS_LOCKED = 22; // constants for llGetParcelDetails public const int PARCEL_DETAILS_NAME = 0; public const int PARCEL_DETAILS_DESC = 1; public const int PARCEL_DETAILS_OWNER = 2; public const int PARCEL_DETAILS_GROUP = 3; public const int PARCEL_DETAILS_AREA = 4; public const int PARCEL_DETAILS_ID = 5; public const int PARCEL_DETAILS_SEE_AVATARS = 6; // not implemented //osSetParcelDetails public const int PARCEL_DETAILS_CLAIMDATE = 10; // constants for llSetClickAction public const int CLICK_ACTION_NONE = 0; public const int CLICK_ACTION_TOUCH = 0; public const int CLICK_ACTION_SIT = 1; public const int CLICK_ACTION_BUY = 2; public const int CLICK_ACTION_PAY = 3; public const int CLICK_ACTION_OPEN = 4; public const int CLICK_ACTION_PLAY = 5; public const int CLICK_ACTION_OPEN_MEDIA = 6; public const int CLICK_ACTION_ZOOM = 7; // constants for the llDetectedTouch* functions public const int TOUCH_INVALID_FACE = -1; public static readonly vector TOUCH_INVALID_TEXCOORD = new vector(-1.0, -1.0, 0.0); public static readonly vector TOUCH_INVALID_VECTOR = ZERO_VECTOR; // constants for llGetPrimMediaParams/llSetPrimMediaParams public const int PRIM_MEDIA_ALT_IMAGE_ENABLE = 0; public const int PRIM_MEDIA_CONTROLS = 1; public const int PRIM_MEDIA_CURRENT_URL = 2; public const int PRIM_MEDIA_HOME_URL = 3; public const int PRIM_MEDIA_AUTO_LOOP = 4; public const int PRIM_MEDIA_AUTO_PLAY = 5; public const int PRIM_MEDIA_AUTO_SCALE = 6; public const int PRIM_MEDIA_AUTO_ZOOM = 7; public const int PRIM_MEDIA_FIRST_CLICK_INTERACT = 8; public const int PRIM_MEDIA_WIDTH_PIXELS = 9; public const int PRIM_MEDIA_HEIGHT_PIXELS = 10; public const int PRIM_MEDIA_WHITELIST_ENABLE = 11; public const int PRIM_MEDIA_WHITELIST = 12; public const int PRIM_MEDIA_PERMS_INTERACT = 13; public const int PRIM_MEDIA_PERMS_CONTROL = 14; public const int PRIM_MEDIA_CONTROLS_STANDARD = 0; public const int PRIM_MEDIA_CONTROLS_MINI = 1; public const int PRIM_MEDIA_PERM_NONE = 0; public const int PRIM_MEDIA_PERM_OWNER = 1; public const int PRIM_MEDIA_PERM_GROUP = 2; public const int PRIM_MEDIA_PERM_ANYONE = 4; public const int PRIM_PHYSICS_SHAPE_TYPE = 30; public const int PRIM_PHYSICS_SHAPE_PRIM = 0; public const int PRIM_PHYSICS_SHAPE_CONVEX = 2; public const int PRIM_PHYSICS_SHAPE_NONE = 1; public const int PRIM_PHYSICS_MATERIAL = 31; public const int DENSITY = 1; public const int FRICTION = 2; public const int RESTITUTION = 4; public const int GRAVITY_MULTIPLIER = 8; // extra constants for llSetPrimMediaParams public static readonly LSLInteger LSL_STATUS_OK = new LSLInteger(0); public static readonly LSLInteger LSL_STATUS_MALFORMED_PARAMS = new LSLInteger(1000); public static readonly LSLInteger LSL_STATUS_TYPE_MISMATCH = new LSLInteger(1001); public static readonly LSLInteger LSL_STATUS_BOUNDS_ERROR = new LSLInteger(1002); public static readonly LSLInteger LSL_STATUS_NOT_FOUND = new LSLInteger(1003); public static readonly LSLInteger LSL_STATUS_NOT_SUPPORTED = new LSLInteger(1004); public static readonly LSLInteger LSL_STATUS_INTERNAL_ERROR = new LSLInteger(1999); public static readonly LSLInteger LSL_STATUS_WHITELIST_FAILED = new LSLInteger(2001); // Constants for default textures public const string TEXTURE_BLANK = "5748decc-f629-461c-9a36-a35a221fe21f"; public const string TEXTURE_DEFAULT = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_PLYWOOD = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_TRANSPARENT = "8dcd4a48-2d37-4909-9f78-f7a9eb4ef903"; public const string TEXTURE_MEDIA = "8b5fec65-8d8d-9dc5-cda8-8fdf2716e361"; // Constants for osGetRegionStats public const int STATS_TIME_DILATION = 0; public const int STATS_SIM_FPS = 1; public const int STATS_PHYSICS_FPS = 2; public const int STATS_AGENT_UPDATES = 3; public const int STATS_ROOT_AGENTS = 4; public const int STATS_CHILD_AGENTS = 5; public const int STATS_TOTAL_PRIMS = 6; public const int STATS_ACTIVE_PRIMS = 7; public const int STATS_FRAME_MS = 8; public const int STATS_NET_MS = 9; public const int STATS_PHYSICS_MS = 10; public const int STATS_IMAGE_MS = 11; public const int STATS_OTHER_MS = 12; public const int STATS_IN_PACKETS_PER_SECOND = 13; public const int STATS_OUT_PACKETS_PER_SECOND = 14; public const int STATS_UNACKED_BYTES = 15; public const int STATS_AGENT_MS = 16; public const int STATS_PENDING_DOWNLOADS = 17; public const int STATS_PENDING_UPLOADS = 18; public const int STATS_ACTIVE_SCRIPTS = 19; public const int STATS_SCRIPT_LPS = 20; // Constants for osNpc* functions public const int OS_NPC_FLY = 0; public const int OS_NPC_NO_FLY = 1; public const int OS_NPC_LAND_AT_TARGET = 2; public const int OS_NPC_RUNNING = 4; public const int OS_NPC_SIT_NOW = 0; public const int OS_NPC_CREATOR_OWNED = 0x1; public const int OS_NPC_NOT_OWNED = 0x2; public const int OS_NPC_SENSE_AS_AGENT = 0x4; public const string URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED"; public const string URL_REQUEST_DENIED = "URL_REQUEST_DENIED"; public static readonly LSLInteger RC_REJECT_TYPES = 0; public static readonly LSLInteger RC_DETECT_PHANTOM = 1; public static readonly LSLInteger RC_DATA_FLAGS = 2; public static readonly LSLInteger RC_MAX_HITS = 3; public static readonly LSLInteger RC_REJECT_AGENTS = 1; public static readonly LSLInteger RC_REJECT_PHYSICAL = 2; public static readonly LSLInteger RC_REJECT_NONPHYSICAL = 4; public static readonly LSLInteger RC_REJECT_LAND = 8; public static readonly LSLInteger RC_GET_NORMAL = 1; public static readonly LSLInteger RC_GET_ROOT_KEY = 2; public static readonly LSLInteger RC_GET_LINK_NUM = 4; public static readonly LSLInteger RCERR_UNKNOWN = -1; public static readonly LSLInteger RCERR_SIM_PERF_LOW = -2; public static readonly LSLInteger RCERR_CAST_TIME_EXCEEDED = 3; /// <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; } }
/* Copyright (C) 2014 Newcastle University * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ using System; using System.Collections.Generic; using System.Linq; using Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Widget; using Android.Media; using Bootleg.API; using Android.Graphics; using Android.Util; using System.Threading.Tasks; using Android.Views.Animations; using Android.Content.Res; using System.Timers; using System.IO; using Android.Support.V4.App; using Android.Support.V4.View; using ViewPagerIndicator; using System.Text.RegularExpressions; using Android.Content.PM; using RadialProgress; using System.Diagnostics; using Bootleg.Droid.UI; using static Bootleg.Droid.UI.PermissionsDialog; using Square.Picasso; using Bootleg.Droid.Fragments; using Newtonsoft.Json; using Android.Support.V4.Content; using Android.Hardware.Camera2; using Bootleg.Droid.Util; using Plugin.Permissions; using Android.Support.V7.Widget; using Bootleg.API.Model; using static Android.Views.View; using Android.Runtime; namespace Bootleg.Droid { [Activity(ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, ScreenOrientation = ScreenOrientation.UserLandscape, LaunchMode = LaunchMode.SingleTask, ResizeableActivity = false)] public class Video : FragmentActivity, IFragmentController, Android.Widget.ViewSwitcher.IViewFactory, IOnSystemUiVisibilityChangeListener { public override void OnWindowFocusChanged(bool hasFocus) { base.OnWindowFocusChanged(hasFocus); if (hasFocus) Window.DecorView.SystemUiVisibility = (StatusBarVisibility)flags; } public override void OnConfigurationChanged(Configuration newConfig) { base.OnConfigurationChanged(newConfig); } public override bool OnCreateOptionsMenu(IMenu menu) { return false; } public override bool OnPrepareOptionsMenu(IMenu menu) { return false; } MediaRecorder audioRecorder; bool recording; Java.IO.File path; Animation pulse; Timer shotlength; Stopwatch stopwatch; DateTime lastrecordtime = DateTime.Now; DateTime startedrecordingtime; string GetExternalPath() { var dirs = ContextCompat.GetExternalFilesDirs(this, null); if (dirs.Count() == 1) return Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMovies).Path; else if (dirs.Last() != null) return dirs.Last().AbsolutePath; else return Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMovies).Path; } bool CheckSpace(string dir) { //var dir = Android.OS.Environment.(Android.OS.Environment.sec).Path; //Directory.CreateDirectory(dir); StatFs stat = new StatFs(dir); long bytesAvailable = stat.BlockSizeLong * stat.AvailableBlocksLong; long megAvailable = bytesAvailable / (1024*1024); if (megAvailable < 300) { //throw error: Android.Support.V7.App.AlertDialog.Builder builder = new Android.Support.V7.App.AlertDialog.Builder(this, Resource.Style.MyAlertDialogStyle); builder.SetMessage(Resource.String.nospace); builder.SetNeutralButton(Android.Resource.String.Ok, (o, q) => { Bootlegger.BootleggerClient.UnSelectRole(!WhiteLabelConfig.REDUCE_BANDWIDTH, true); Finish(); //Intent i = new Intent(this.ApplicationContext, typeof(Login)); //StartActivity(i); }); builder.SetCancelable(false); try { builder.Show(); } catch { //cannot do anything about this... } return false; } else { return true; } } void StartRecording() { var testfile = new Java.IO.File(GetExternalPath()); if(CheckSpace(testfile.AbsolutePath)) { progress_view.ProgressColor = Color.Tomato; FindViewById<View>(Resource.Id.recordlight).StartAnimation(pulse); FindViewById<View>(Resource.Id.recordlight).Visibility = ViewStates.Visible; //System.Console.WriteLine("starting record"); stopwatch = new Stopwatch(); stopwatch.Start(); startedrecordingtime = DateTime.Now; recording = true; //recordlength = 0; FindViewById<ToggleButton>(Resource.Id.Play).Checked = true; //if (camera == null) // camera = Android.Hardware.Camera.Open(); if (Android.OS.Environment.ExternalStorageState != Android.OS.Environment.MediaMounted) { Toast.MakeText(this, Resource.String.nostorage, ToastLength.Short); } testfile = new Java.IO.File(testfile, "bootlegger"); if (!testfile.Exists()) { if (!testfile.Mkdirs()) { //major error!! Log.Error("BL", "Directory not created (might not be needed)"); } } //new filename: Java.IO.File file; //fix for if this phone has taken over someone else's account and thus does not have a client or server side shot allocation: Shot.ShotTypes shotype; try { shotype = (Bootlegger.BootleggerClient.CurrentClientShotType != null) ? Bootlegger.BootleggerClient.CurrentClientShotType.shot_type : Bootlegger.BootleggerClient.CurrentServerShotType.shot_type; } catch { shotype = Shot.ShotTypes.VIDEO; } switch (shotype) { case Shot.ShotTypes.PHOTO: file = new Java.IO.File(testfile, DateTime.Now.Ticks + ".jpg"); path = file; thumbnailfilename = file.ToString(); progress_view.Visibility = ViewStates.Gone; cameraDriver.TakePhoto(thumbnailfilename); break; case Shot.ShotTypes.AUDIO: file = new Java.IO.File(testfile, DateTime.Now.Ticks + ".aac"); path = file; file.CreateNewFile(); if (audioRecorder != null) { audioRecorder.Reset(); } else { audioRecorder = new MediaRecorder(); } //recorder.SetVideoSource(null); audioRecorder.Reset(); audioRecorder.SetAudioSource(AudioSource.Mic); audioRecorder.SetOutputFormat(OutputFormat.AacAdts); audioRecorder.SetOutputFile(file.AbsolutePath); audioRecorder.SetAudioEncoder(AudioEncoder.Aac); audioRecorder.SetMaxDuration(1000*60*5); audioRecorder.SetPreviewDisplay(null); StartLocationTrack(); try { audioRecorder.Prepare(); } catch (Exception) { } try { audioRecorder.Start(); pulse = AnimationUtils.LoadAnimation(this, Resource.Animation.pulse); FindViewById<View>(Resource.Id.recordlight).StartAnimation(pulse); FindViewById<View>(Resource.Id.recordlight).Visibility = ViewStates.Visible; if (!WhiteLabelConfig.REDUCE_BANDWIDTH) { Bootlegger.BootleggerClient.RecordingStarted(); } progress_view.Value = 0; FindViewById<TextView>(Resource.Id.timestamp).Text = "00:00"; } catch (Exception) { //recording failed: recording = false; FindViewById<ToggleButton>(Resource.Id.Play).Checked = false; } break; case Shot.ShotTypes.VIDEO: file = new Java.IO.File(testfile, DateTime.Now.Ticks + ".mp4"); file.CreateNewFile(); path = file; StartLocationTrack(); try { cameraDriver.StartRecord(path.AbsolutePath); Bootlegger.BootleggerClient.RecordingStarted(); progress_view.Value = 0; FindViewById<TextView>(Resource.Id.timestamp).Text = "00:00"; } catch (Exception) { //recording failed: recording = false; stopwatch.Stop(); FindViewById<ToggleButton>(Resource.Id.Play).Checked = false; } break; } //end switch }//end space check } private void StartLocationTrack() { if (!disablelocation) { if (WhiteLabelConfig.GPS_RECORD_INTERVAL_SECS > TimeSpan.Zero) { Plugin.Geolocator.CrossGeolocator.Current.StopListeningAsync(); Plugin.Geolocator.CrossGeolocator.Current.StartListeningAsync(WhiteLabelConfig.GPS_RECORD_INTERVAL_SECS, 10, true); } } } private void StopLocationTrack() { Plugin.Geolocator.CrossGeolocator.Current.StopListeningAsync(); //Plugin.Geolocator.CrossGeolocator.Current.StartListeningAsync(5000, 10); } async Task StopRecording() { Bitmap bitmap = null; Shot.ShotTypes shotype; try { shotype = (Bootlegger.BootleggerClient.CurrentClientShotType != null) ? Bootlegger.BootleggerClient.CurrentClientShotType.shot_type : Bootlegger.BootleggerClient.CurrentServerShotType.shot_type; } catch { shotype = Shot.ShotTypes.VIDEO; } //var shotype = ((Application as BootleggerApp).Comms.CurrentClientShotType != null) ? (Application as BootleggerApp).Comms.CurrentClientShotType.shot_type : (Application as BootleggerApp).Comms.CurrentServerShotType.shot_type; switch (shotype) { case Shot.ShotTypes.AUDIO: //stop audio recorder: try { //crash here... audioRecorder.Stop(); audioRecorder.Reset(); } catch (Exception) { } break; case Shot.ShotTypes.PHOTO: //do nothing... //bitmap = await BitmapFactory.DecodeFileAsync(thumbnailfilename); //resize bitmap: //create thumbnailed version of the jpg break; default: try { //crash here... cameraDriver.StopRecord(); } catch (Exception) { } //add thumb bitmap = await ThumbnailUtils.CreateVideoThumbnailAsync(path.AbsolutePath, Android.Provider.ThumbnailKind.MiniKind); break; } //display the shot selection screen if needed: FindViewById<ToggleButton>(Resource.Id.Play).Checked = false; recording = false; if (LIVEMODE) progress_view.ProgressColor = Color.DodgerBlue; FindViewById<TextView>(Resource.Id.timestamp).Text = "00:00"; progress_view.Visibility = ViewStates.Visible; stopwatch.Stop(); progress_view.Value = 0; StopLocationTrack(); if (!LIVEMODE) { if (!WhiteLabelConfig.SHOW_ALL_SHOTS) { //return to role selection: FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Gone; FindViewById(Resource.Id.roleselector).Visibility = ViewStates.Visible; //set role selection tab: } else { FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Visible; } } if (!WhiteLabelConfig.REDUCE_BANDWIDTH) { Bootlegger.BootleggerClient.RecordingStopped(); } if (shotype != Shot.ShotTypes.PHOTO) { pulse.AnimationEnd += pulse_AnimationEnd; pulse.Cancel(); FindViewById<View>(Resource.Id.recordlight).ClearAnimation(); FindViewById<View>(Resource.Id.recordlight).Post(new Action(() => { FindViewById<View>(Resource.Id.recordlight).Visibility = ViewStates.Invisible; })); } progress_view.Value = 0; FindViewById<TextView>(Resource.Id.timestamp).Text = "00:00"; //create new media item MediaItem newm = new MediaItem(); newm.Filename = path.AbsolutePath; if (Bootlegger.BootleggerClient.CurrentClientShotType != null) newm.ShortName = Bootlegger.BootleggerClient.CurrentClientShotType.name; else newm.ShortName = newm.Filename.Split('/').Last().Split('.').Reverse().Skip(1).First(); //add geo data var mygeo = new Dictionary<string, string>(); if (Plugin.Geolocator.CrossGeolocator.Current.IsGeolocationAvailable && Plugin.Geolocator.CrossGeolocator.Current.IsGeolocationEnabled && currentposition != null) { mygeo.Add("gps_lat", currentposition.Latitude.ToString()); mygeo.Add("gps_lng", currentposition.Longitude.ToString()); mygeo.Add("gps_head", currentposition.Heading.ToString()); mygeo.Add("gps_acc", currentposition.Accuracy.ToString()); mygeo.Add("gps_alt", currentposition.Altitude.ToString()); mygeo.Add("gps_spd", currentposition.Speed.ToString()); } mygeo.Add("clip_length", stopwatch.Elapsed.ToString()); mygeo.Add("camera", (CURRENTCAMERA == 0) ? "rear" : "front"); mygeo.Add("device_os", Build.VERSION.SdkInt.ToString()); mygeo.Add("device_hardware", Build.Manufacturer); mygeo.Add("device_hardware_ver", Build.Model); if (cameraDriver.ZoomLevels.Count < FindViewById<SeekBar>(Resource.Id.zoom).Progress) mygeo.Add("zoom", (cameraDriver.ZoomLevels[FindViewById<SeekBar>(Resource.Id.zoom).Progress].IntValue()/100.0).ToString()); mygeo.Add("captured_at", startedrecordingtime.ToString("dd/MM/yyyy H:mm:ss.ff tt zz")); string filename = path.AbsolutePath + ".jpg"; if (shotype == Shot.ShotTypes.PHOTO) { filename = thumbnailfilename; } FileStream outt; if (bitmap != null) { bool dothumb = false; try { outt = new FileStream(filename, FileMode.CreateNew); await bitmap.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, outt); outt.Close(); dothumb = true; } catch (Exception) { } if (!dothumb) filename = null; } var m = Bootlegger.BootleggerClient.CreateMediaMeta(newm, mygeo, null, filename); //HACK: does this stop the server getting the information it needs?? if (!LIVEMODE && !WhiteLabelConfig.REDUCE_BANDWIDTH) { try { await Bootlegger.BootleggerClient.UploadMedia(m); } catch { //if no internet etc, then cant do this right now... } } //update upload gui hasrecorded = true; recording = false; progress_view.Value = 0; } async Task record() { if (!recording && canrecord) { //cant record within 4 seconds of last record time... if ((DateTime.Now - lastrecordtime).TotalMilliseconds < 4000) { FindViewById<ToggleButton>(Resource.Id.Play).Checked = false; return; } else { lastrecordtime = DateTime.Now; StartRecording(); //DISABLE ROLE SELECTION //_adapter.myrolefrag.View.Enabled = false; } } else if (recording) { //disable the button: FindViewById<ToggleButton>(Resource.Id.Play).Enabled = false; //stop recording await StopRecording(); FindViewById<ToggleButton>(Resource.Id.Play).Enabled = true; } } //long recordlength; long waitinglength; bool hasrecorded = false; void shotlength_Elapsed(object sender, ElapsedEventArgs e) { //stop recording now max_length reached. if (!LIVEMODE && recording && (Bootlegger.BootleggerClient.CurrentClientShotType != null && Bootlegger.BootleggerClient.CurrentClientShotType.max_length != 0)) { if (stopwatch.Elapsed.TotalSeconds >= Bootlegger.BootleggerClient.CurrentClientShotType.max_length) { RunOnUiThread(() => { record(); }); } } //STOP RECORDING IF THE SERVER FOR SOME REASON HAS NOT STOPPED YOU ALREADY IN LIVE MODE AFTER 2 MINS5 if (recording && LIVEMODE && stopwatch.Elapsed.TotalSeconds > 60*2) { RunOnUiThread(() => { record(); }); } RunOnUiThread(() => { //if recording... if (recording) { waitinglength = 0; if (expectedrecordlength > 0) { progress_view.Visibility = ViewStates.Visible; progress_view.Value = (int)(((stopwatch.Elapsed.TotalSeconds) / (double)expectedrecordlength) * 100); } else { if (Bootlegger.BootleggerClient.CurrentClientShotType != null && Bootlegger.BootleggerClient.CurrentClientShotType.max_length != 0) { //if it has a max length progress_view.Visibility = ViewStates.Visible; progress_view.Value = (float)(((stopwatch.Elapsed.TotalSeconds) / (float)Bootlegger.BootleggerClient.CurrentClientShotType.max_length) * 100f) + 0.1f; } } //TODO: i18n timestamp FindViewById<TextView>(Resource.Id.timestamp).Text = stopwatch.Elapsed.Minutes.ToString().PadLeft(2, '0') + ":" + stopwatch.Elapsed.Seconds.ToString().PadLeft(2, '0'); //recordlength += 1000; } else { try { //if (Bootlegger.BootleggerClient.CurrentEvent!=null && Bootlegger.BootleggerClient.CurrentEvent.HasStarted && hasrecorded && !Bootlegger.BootleggerClient.CurrentEvent.offline && !LIVEMODE) //{ FindViewById<View>(Resource.Id.recordlight).Visibility = ViewStates.Invisible; //progress_view.Visibility = ViewStates.Visible; //progress_view.Value = (int)((((double)waitinglength) / ((double)Bootlegger.BootleggerClient.CurrentUser.CycleLength)) * 100); //waitinglength += 1; //} } catch { } finally { FindViewById<View>(Resource.Id.recordlight).Visibility = ViewStates.Invisible; } } }); } void pulse_AnimationEnd(object sender, Animation.AnimationEndEventArgs e) { FindViewById<View>(Resource.Id.recordlight).Post(new Action(() => { FindViewById<View>(Resource.Id.recordlight).Visibility = ViewStates.Invisible; })); } public static int getSoftButtonsBarSizePort(Activity activity) { // getRealMetrics is only available with API 17 and + if (Build.VERSION.SdkInt >= Build.VERSION_CODES.JellyBeanMr1) { DisplayMetrics metrics = new DisplayMetrics(); activity.WindowManager.DefaultDisplay.GetMetrics(metrics); int usableHeight = metrics.HeightPixels; activity.WindowManager.DefaultDisplay.GetRealMetrics(metrics); int realHeight = metrics.HeightPixels; if (realHeight > usableHeight) return realHeight - usableHeight; else return 0; } return 0; } //SurfaceView video; bool canrecord = false; void start() { var play = FindViewById<ToggleButton>(Resource.Id.Play); play.Click += delegate { record(); }; canrecord = true; progress_view.Value = 0; FindViewById<TextView>(Resource.Id.timestamp).Text = "00:00"; // setup timer for countdown display if (shotlength != null) shotlength.Stop(); shotlength = new Timer(500); shotlength.Elapsed += shotlength_Elapsed; shotlength.Start(); } //DrawerLayout tabHost; private TextSwitcher mSwitcher; ShotPageAdapter mAdapter; //ShotAdapter allshots; ViewPager _pager; bool firstrun; bool PermissionsGranted = false; protected async override void OnStart() { base.OnStart(); Bootlegger.BootleggerClient.OnRoleChanged += Comms_OnRoleChanged; Bootlegger.BootleggerClient.OnMessage += Comms_OnMessage; Bootlegger.BootleggerClient.OnPhaseChange += Comms_OnPhaseChange; Bootlegger.BootleggerClient.OnEventUpdated += Comms_OnEventUpdated; Bootlegger.BootleggerClient.OnImagesUpdated += Comms_OnImagesUpdated; Bootlegger.BootleggerClient.OnPermissionsChanged += Comms_OnPermissionsChanged; Bootlegger.BootleggerClient.OnLoginElsewhere += Comms_OnLoginElsewhere; //download image files for the event: if (!firstrun) { FindViewById<FrameLayout>(Resource.Id.initprogress).Visibility = ViewStates.Visible; if ((Application as BootleggerApp).IsReallyConnected) { try { //throw new Exception("test"); await Bootlegger.BootleggerClient.GetImages(); } catch (Exception e) { //cant do this -- so close application! Log.Error("Bootlegger", e.Message); if (e.InnerException != null) Log.Error("Bootlegger", e.InnerException.Message); RunOnUiThread(new Action(() => { Android.Support.V7.App.AlertDialog.Builder builder = new Android.Support.V7.App.AlertDialog.Builder(this, Resource.Style.MyAlertDialogStyle); builder.SetMessage(Resources.GetString(Resource.String.tryagain, e.Message)); builder.SetNeutralButton(Android.Resource.String.Ok, new EventHandler<DialogClickEventArgs>((o, q) => { //(Application as BootleggerApp).TOTALFAIL = true; Finish(); return; })); builder.SetCancelable(false); try { builder.Show(); } catch { //cannot do anything about this... } })); } finally { firstrun = true; } } } _pager = null; try { if (shotselector == null) { //add shot selector to panel: var role = Bootlegger.BootleggerClient.CurrentClientRole; shotselector = new ShotSelectAdapter(this); shotselector.OnShotSelected += SelectorClick; FindViewById<RecyclerView>(Resource.Id.shotselectorlist).SetLayoutManager(new GridLayoutManager(this, 3)); FindViewById<RecyclerView>(Resource.Id.shotselectorlist).SetAdapter(shotselector); shotselector.UpdateData(Bootlegger.BootleggerClient.CurrentClientRole.Shots); //add role fragment to shot panel: if (!WhiteLabelConfig.SHOW_ALL_SHOTS) { FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Gone; } else { FindViewById(Resource.Id.roleselector).Visibility = ViewStates.Gone; } } } catch { } //LIVE MODE if (LIVEMODE) { try { if (mAdapter == null) { //setup pager for demo images: mAdapter = new ShotPageAdapter(SupportFragmentManager, Bootlegger.BootleggerClient.CurrentClientRole.Shots); ViewPager mPager = FindViewById<ViewPager>(Resource.Id.pager); mPager.Adapter = mAdapter; var indicator = FindViewById<CirclePageIndicator>(Resource.Id.indicator); indicator.SetViewPager(mPager); indicator.SetSnap(true); } } catch { } } //hide progress FindViewById<FrameLayout>(Resource.Id.initprogress).Visibility = ViewStates.Invisible; Bootlegger.BootleggerClient.OnModeChange += Comms_OnModeChange; //fix for camera 1 api: try { FindViewById<View>(Resource.Id.camera_preview).Post(() => { FindViewById<View>(Resource.Id.camera_preview).RequestLayout(); }); } catch { //handle camera not created yet (permissions not met) } //if its in role select mode and coming from the roles selection screen, show the shots rather than the roles: if (from_roles ?? false && !WhiteLabelConfig.SHOW_ALL_SHOTS) { FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Visible; FindViewById(Resource.Id.roleselector).Visibility = ViewStates.Gone; } } private void _adapter_OnRoleChanged() { //can only do this if not recording: if (!recording) { shotselector.UpdateData(Bootlegger.BootleggerClient.CurrentClientRole.Shots); if (!LIVEMODE) FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Visible; } else { //Toast.MakeText(this,Resource.String.norolechange,ToastLength.Short).Show(); } } ShotSelectAdapter shotselector; //VideoPagerAdapter _adapter; CleanRadialProgressView progress_view; public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults) { Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); RequestedOrientation = ScreenOrientation.Landscape; Bootlegger.BootleggerClient.InBackground = false; SetTheme(Resource.Style.Theme_Normal); Window.DecorView.SystemUiVisibility = (StatusBarVisibility)flags; //Window.DecorView.SystemUiVisibility = (StatusBarVisibility)(SystemUiFlags.Fullscreen | SystemUiFlags.LayoutFullscreen | SystemUiFlags.LayoutStable | SystemUiFlags.HideNavigation | SystemUiFlags.LayoutHideNavigation | SystemUiFlags.ImmersiveSticky); //RequestWindowFeature(WindowFeatures.NoTitle); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); //Window.AddFlags(WindowManagerFlags.); //Window.AddFlags(WindowManagerFlags.LayoutNoLimits); //Window.AddFlags(WindowManagerFlags.TranslucentNavigation); SetContentView(Resource.Layout.Video_Main); progress_view = FindViewById<CleanRadialProgressView>(Resource.Id.progress); progress_view.ProgressColor = Color.Tomato; start(); //show progress Bootlegger.BootleggerClient.OnImagesDownloading += (o) => { RunOnUiThread(new Action(() => { FindViewById<ProgressBar>(Resource.Id.initprogressbar).Progress = o; })); ; }; FindViewById<ImageButton>(Resource.Id.goback).Click += Fin_Click; FindViewById<ImageButton>(Resource.Id.switchcam).Click += Cam_Switch; FindViewById<ImageView>(Resource.Id.overlayimg).SetAlpha(120); Bootlegger.BootleggerClient.OnNotification += Comms_OnNotification; if (ApplicationContext.PackageManager.HasSystemFeature(PackageManager.FeatureCameraFlash) && WhiteLabelConfig.USE_FLASH) { FindViewById<ToggleButton>(Resource.Id.flash).Click += FlashToggle_Click; } else { FindViewById<ToggleButton>(Resource.Id.flash).Visibility = ViewStates.Gone; } FindViewById<Button>(Resource.Id.openhelp).Click += HelpOpen_Click; if (!WhiteLabelConfig.EXTERNAL_LINKS) FindViewById(Resource.Id.openhelp).Visibility = ViewStates.Gone; FindViewById<ImageButton>(Resource.Id.Help).Click += Help_Click; FindViewById(Resource.Id.helpoverlay).Click += HelpOverlay_Click; FindViewById<ToggleButton>(Resource.Id.showoverlay).CheckedChange += Video_CheckedChange; if (!WhiteLabelConfig.SHOW_ALL_SHOTS) { FindViewById<ImageButton>(Resource.Id.switchrole).Visibility = ViewStates.Gone; } FindViewById<ImageButton>(Resource.Id.switchrole).Click += Video_Click; mSwitcher = FindViewById<TextSwitcher>(Resource.Id.message); // Set the factory used to create TextViews to switch between. mSwitcher.SetFactory(this); mSwitcher.SetInAnimation(this, Android.Resource.Animation.FadeIn); mSwitcher.SetOutAnimation(this, Android.Resource.Animation.FadeOut); FindViewById(Resource.Id.messageholder).Visibility = ViewStates.Invisible; var msg = FindViewById<TextSwitcher>(Resource.Id.message); FindViewById<SeekBar>(Resource.Id.zoom).ProgressChanged += Video_ProgressChanged; Bootlegger.BootleggerClient.CanUpload = false; Plugin.Geolocator.CrossGeolocator.Current.DesiredAccuracy = 10; Plugin.Geolocator.CrossGeolocator.Current.PositionChanged += geo_PositionChanged; ScreenOrientationEvent orientation = new ScreenOrientationEvent(this); orientation.ShowWarning += orientation_ShowWarning; orientation.Enable(); FindViewById<ImageButton>(Resource.Id.closeshots).Click += CloseShots_Click; //White Label Text Size if (WhiteLabelConfig.LARGE_SHOT_FONT) FindViewById<TextView>(Resource.Id.overlaytext).SetTextSize(ComplexUnitType.Sp, 40); if (savedInstanceState == null) { selectrolefrag = new SelectRoleFrag(Bootlegger.BootleggerClient.CurrentEvent, true); Android.Support.V4.App.FragmentTransaction ft = SupportFragmentManager.BeginTransaction(); ft.Add(Resource.Id.roleselector, selectrolefrag, "arolefragment").Commit(); } else { selectrolefrag = SupportFragmentManager.FindFragmentByTag("arolefragment") as SelectRoleFrag; } selectrolefrag.OnRoleChanged += () => { FindViewById(Resource.Id.roleselector).Visibility = ViewStates.Gone; _adapter_OnRoleChanged(); }; } private void Video_Click(object sender, EventArgs e) { //OPEN CHANGE ROLE PANEL: _pager.SetCurrentItem(0, false); } private void Comms_OnLoginElsewhere() { //logged in elsewhere... RunOnUiThread(new Action(() => { if (recording) { record(); } Android.Support.V7.App.AlertDialog.Builder builder = new Android.Support.V7.App.AlertDialog.Builder(this, Resource.Style.MyAlertDialogStyle); builder.SetMessage(Resource.String.loggedinelsewhere); builder.SetNeutralButton(Android.Resource.String.Ok, new EventHandler<DialogClickEventArgs>((o, q) => { Finish(); Bootlegger.BootleggerClient.CurrentClientRole = null; })); builder.SetCancelable(false); try { builder.Show(); } catch { //cannot do anything about this... } })); } private void Comms_OnPermissionsChanged() { RunOnUiThread(async () => { try { await AskPermissions(this, Bootlegger.BootleggerClient.CurrentEvent, true); } catch (NotGivenPermissionException) { //not accepted the permissions, so remove from the event: new Android.Support.V7.App.AlertDialog.Builder(this, Resource.Style.MyAlertDialogStyle).SetMessage(Resource.String.finishshooting) .SetCancelable(false) .SetTitle(Resource.String.permschanged) .SetMessage(Resource.String.notacceptperms) .SetPositiveButton(Resource.String.iunderstand, (o,e) => { ShowLeaveDialog(true); }) .Show(); } }); } private void Comms_OnImagesUpdated() { //do a notify RunOnUiThread(() => { shotselector?.UpdateData(Bootlegger.BootleggerClient.CurrentClientRole.Shots); }); } private void Video_Touch(object sender, View.TouchEventArgs e) { e.Handled = true; } private void Leave_Click(object sender, EventArgs e) { ShowLeaveDialog(false); } private void Settings_Click(object sender, EventArgs e) { //change page: _pager.CurrentItem = 2; } private void AllShots_Click(object sender, EventArgs e) { //change page: _pager.CurrentItem = 1; } private void ChangeRole_Click(object sender, EventArgs e) { //change page: _pager.CurrentItem = 0; } private void HelpOpen_Click(object sender, EventArgs e) { LoginFuncs.ShowHelp(this,"#video"); } private void CloseShots_Click(object sender, EventArgs e) { if (Bootlegger.BootleggerClient.CurrentClientShotType==null) Bootlegger.BootleggerClient.SetShot(Bootlegger.BootleggerClient.CurrentEvent.shottypes.First()); FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Gone; //CloseButtons(); } void Comms_OnEventUpdated() { //update adapters: try { FindViewById(Resource.Id.shotselector).Post(() => { //already disconnected if (Bootlegger.BootleggerClient.CurrentClientRole != null) shotselector.UpdateData(Bootlegger.BootleggerClient.CurrentClientRole.Shots); }); } catch (Exception) { } } void Comms_OnPhaseChange(MetaPhase obj) { //if there are no roles associated with this phase: if (obj.roles == null || obj.roles.Contains(Bootlegger.BootleggerClient.CurrentClientRole.id)) { Comms_OnMessage(Bootlegger.BootleggerNotificationType.PhaseChanged,obj.name, false, false, true); } else { Comms_OnMessage(Bootlegger.BootleggerNotificationType.RoleUpdated,obj.name,true,false,true); } } void Comms_OnNotification(Bootlegger.BootleggerNotificationType ntype,string arg1) { Intent resultIntent = new Intent(this, typeof(SplashActivity)); Android.Support.V4.App.TaskStackBuilder stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(this); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(Video))); stackBuilder.AddNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent); string title = ""; string content = ""; switch (ntype) { case Bootlegger.BootleggerNotificationType.CrewReminder: title = Resources.GetString(Resource.String.crewreminder_title); if (string.IsNullOrEmpty(arg1)) content = Resources.GetString(Resource.String.crewreminder_content); else content = arg1; break; case Bootlegger.BootleggerNotificationType.PhaseChanged: title = Resources.GetString(Resource.String.phasechange_title); content = Resources.GetString(Resource.String.phasechange,arg1); break; case Bootlegger.BootleggerNotificationType.RoleUpdated: case Bootlegger.BootleggerNotificationType.ShootUpdated: title = Resources.GetString(Resource.String.phasechange_title); content = Resources.GetString(Resource.String.phasechangerole,arg1); break; } NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .SetContentTitle(title) .SetStyle(new NotificationCompat.BigTextStyle().BigText(content)) .SetContentIntent(resultPendingIntent) .SetSmallIcon(Resource.Drawable.ic_notification); //.SetContentText(content); builder.SetAutoCancel(true); // Obtain a reference to the NotificationManager NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService); notificationManager.Notify(0, builder.Build()); } void SelectorClick(Shot item) { ShowShotRelease(item); Picasso.With(this).Load("file://" + item.image).Into(FindViewById<ImageView>(Resource.Id.overlayimg)); if (item.coverage_class!=null) { if (Bootlegger.BootleggerClient.CurrentEvent.coverage_classes.Count > item.coverage_class) { FindViewById<TextView>(Resource.Id.overlaytext).Text = Regex.Replace((!string.IsNullOrEmpty(item.description))?item.description : "", "%%(.*?)%%", Bootlegger.BootleggerClient.CurrentEvent.coverage_classes[int.Parse(item.coverage_class.ToString())].name); } } else { FindViewById<TextView>(Resource.Id.overlaytext).Text = Regex.Replace((!string.IsNullOrEmpty(item.description)) ? item.description : "", "%%(.*?)%%", Resources.GetString(Resource.String.them)); } FindViewById(Resource.Id.overlay).Visibility = ViewStates.Visible; FindViewById<ToggleButton>(Resource.Id.showoverlay).Checked = true; Bootlegger.BootleggerClient.AcceptShot(item); Bootlegger.BootleggerClient.SetShot(item); if (recording && stopwatch != null) Bootlegger.BootleggerClient.AddTimedMeta(stopwatch.Elapsed, "shot", item.id.ToString()); switch (item.shot_type) { case Shot.ShotTypes.PHOTO: FindViewById<ImageView>(Resource.Id.shottype).SetImageResource(Resource.Drawable.ic_photo_camera_white_24dp); FindViewById<ImageView>(Resource.Id.shottype).Visibility = ViewStates.Visible; break; case Shot.ShotTypes.AUDIO: FindViewById<ImageView>(Resource.Id.shottype).SetImageResource(Resource.Drawable.ic_mic_white_48dp); FindViewById<ImageView>(Resource.Id.shottype).Visibility = ViewStates.Visible; break; default: FindViewById<ImageView>(Resource.Id.shottype).Visibility = ViewStates.Gone; break; } FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Gone; } bool flashon = false; private void FlashToggle_Click(object sender, EventArgs e) { if (FindViewById(Resource.Id.helpoverlay).Visibility == ViewStates.Visible) return; if (cameraDriver.HasFlash) { if (!flashon) { cameraDriver.FlashOn(); flashon = true; if (recording) Bootlegger.BootleggerClient.AddTimedMeta(stopwatch.Elapsed, "flash", "on"); } else { cameraDriver.FlashOff(); flashon = false; if (recording) Bootlegger.BootleggerClient.AddTimedMeta(stopwatch.Elapsed, "flash", "off"); } } } void Fin_Click(object sender, EventArgs e) { //show uploads screen after the event has finished Bootlegger.BootleggerClient.UnSelectRole(!WhiteLabelConfig.REDUCE_BANDWIDTH, true); Finish(); return; } private void orientation_ShowWarning(bool obj) { if (obj) { if (stopwatch != null && recording && FindViewById<ImageView>(Resource.Id.rotatewarning).Visibility == ViewStates.Invisible) Bootlegger.BootleggerClient.AddTimedMeta(stopwatch.Elapsed, "rotwarn", "on"); FindViewById<ImageView>(Resource.Id.rotatewarning).Visibility = ViewStates.Visible; } else { if (stopwatch != null && recording && FindViewById<ImageView>(Resource.Id.rotatewarning).Visibility == ViewStates.Visible) Bootlegger.BootleggerClient.AddTimedMeta(stopwatch.Elapsed, "rotwarn", "off"); FindViewById<ImageView>(Resource.Id.rotatewarning).Visibility = ViewStates.Invisible; } } TimeSpan lastzoomreport = TimeSpan.Zero; void Video_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { //adjust camera zoom cameraDriver.Zoom(e.Progress); if (recording && lastzoomreport < stopwatch.Elapsed - TimeSpan.FromMilliseconds(200)) { lastzoomreport = stopwatch.Elapsed; Bootlegger.BootleggerClient.AddTimedMeta(stopwatch.Elapsed, "zoom", (cameraDriver.ZoomLevels[FindViewById<SeekBar>(Resource.Id.zoom).Progress].IntValue()/100.0).ToString()); } } void Comms_OnServerDied() { RunOnUiThread(new Action(() => { if (recording) record(); Android.Support.V7.App.AlertDialog.Builder builder = new Android.Support.V7.App.AlertDialog.Builder(this, Resource.Style.MyAlertDialogStyle); builder.SetNeutralButton(Android.Resource.String.Ok,new EventHandler<DialogClickEventArgs>((o,q) => { //(Application as BootleggerApp).TOTALFAIL = true; Bootlegger.BootleggerClient.UnSelectRole(!WhiteLabelConfig.REDUCE_BANDWIDTH, true); Finish(); //Intent i = new Intent(this.ApplicationContext, typeof(Login)); //StartActivity(i); })); builder.SetCancelable(false); try { builder.Show(); } catch { //cannot do anything about this... } })); } void HelpOverlay_Click(object sender, EventArgs e) { FindViewById(Resource.Id.helpoverlay).Visibility = ViewStates.Invisible; } void Help_Click(object sender, EventArgs e) { //show tooltips for help (or help overlay) FindViewById(Resource.Id.helpoverlay).Visibility = ViewStates.Visible; } void Start_Click(object sender, EventArgs e) { Bootlegger.BootleggerClient.EventStarted(); } void Hold_Click(object sender, EventArgs e) { Bootlegger.BootleggerClient.HoldShot(); } void Skip_Click(object sender, EventArgs e) { Bootlegger.BootleggerClient.SkipShot(); } Plugin.Geolocator.Abstractions.Position currentposition; void geo_PositionChanged(object sender, Plugin.Geolocator.Abstractions.PositionEventArgs e) { currentposition = e.Position; if (recording && WhiteLabelConfig.GPS_RECORD_INTERVAL_SECS > TimeSpan.Zero) { Bootlegger.BootleggerClient.AddTimedMeta(stopwatch.Elapsed, "geo", JsonConvert.SerializeObject(e.Position)); } } void Video_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) { FindViewById(Resource.Id.overlay).Visibility = ViewStates.Visible; } else { FindViewById(Resource.Id.overlay).Visibility = ViewStates.Invisible; } } Android.Support.V7.App.AlertDialog currentshotchoicedialog; void Comms_OnRoleChanged(Role obj) { //RunOnUiThread(new Action(() => //{ // Android.Support.V7.App.AlertDialog.Builder builder = new Android.Support.V7.App.AlertDialog.Builder(this, Resource.Style.MyAlertDialogStyle); // builder.SetMessage(Resources.GetString(Resource.String.wouldyoudorole,obj.name)).SetPositiveButton(Android.Resource.String.Yes, new EventHandler<DialogClickEventArgs>((o, e) => // { // Bootlegger.BootleggerClient.AcceptRole(obj); // })).SetNegativeButton(Android.Resource.String.No, new EventHandler<DialogClickEventArgs>((o, e) => // { // Bootlegger.BootleggerClient.RejectRole(obj); // })).SetCancelable(false).Show(); //})); } int expectedrecordlength = 0; Timer timer; int timercount = 0; void Comms_OnCountdown(int obj) { RunOnUiThread(new Action(() => { //close shot selection dialog to stop confusion if (currentshotchoicedialog != null && currentshotchoicedialog.IsShowing) { currentshotchoicedialog.Dismiss(); if (Bootlegger.BootleggerClient.CurrentServerShotType!=null) { Picasso.With(this).Load("file://" + Bootlegger.BootleggerClient.CurrentServerShotType.image).Into(FindViewById<ImageView>(Resource.Id.overlayimg)); if (Bootlegger.BootleggerClient.CurrentServerShotType.coverage_class != null) { if (Bootlegger.BootleggerClient.CurrentEvent.coverage_classes.Count > Bootlegger.BootleggerClient.CurrentServerShotType.coverage_class) { FindViewById<TextView>(Resource.Id.overlaytext).Text = Regex.Replace(Bootlegger.BootleggerClient.CurrentServerShotType.description, "%%(.*?)%%", Bootlegger.BootleggerClient.CurrentEvent.coverage_classes[int.Parse(Bootlegger.BootleggerClient.CurrentServerShotType.coverage_class.ToString())].name); } } else { FindViewById<TextView>(Resource.Id.overlaytext).Text = Regex.Replace(Bootlegger.BootleggerClient.CurrentServerShotType.description, "%%(.*?)%%", "them"); } //FindViewById<TextView>(Resource.Id.overlaytext).Text = Regex.Replace(item.description, "%%(.*?)%%", ""); FindViewById(Resource.Id.overlay).Visibility = ViewStates.Visible; FindViewById<ToggleButton>(Resource.Id.showoverlay).Checked = true; } //show the overlay for the current server based shot... Comms_OnMessage(Bootlegger.BootleggerNotificationType.GoingLive,"",false,false,false); } //FindViewById<LinearLayout>(Resource.Id.countdown).Visibility = ViewStates.Visible; timercount = obj; //FindViewById<TextView>(Resource.Id.livecount).Text = Java.Lang.String.Format("%d", obj); if (timer != null) timer.Stop(); timer = new Timer(1000); timer.Elapsed += (o, e) => { timercount--; if (timercount <= 0) { (o as Timer).Stop(); } else { RunOnUiThread(new Action(() => { //bounce animation: ScaleAnimation animation = new ScaleAnimation(1,1.5f,1,1.5f,Dimension.RelativeToSelf, 0.5f, Dimension.RelativeToSelf, 0.5f); animation.RepeatCount = 0; animation.RepeatMode = RepeatMode.Reverse; animation.Interpolator = new DecelerateInterpolator(); animation.Duration = 100; })); } }; timer.Start(); })); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } public override void OnBackPressed() { if (FindViewById(Resource.Id.helpoverlay).Visibility == ViewStates.Visible) { FindViewById(Resource.Id.helpoverlay).Visibility = ViewStates.Gone; } else { if (!WhiteLabelConfig.SHOW_ALL_SHOTS) { if (FindViewById(Resource.Id.shotselector).Visibility == ViewStates.Visible) { FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Gone; FindViewById(Resource.Id.roleselector).Visibility = ViewStates.Visible; } else { if (FindViewById(Resource.Id.shotselector).Visibility == ViewStates.Gone && !recording && FindViewById(Resource.Id.roleselector).Visibility == ViewStates.Gone) { FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Visible; } else if (FindViewById(Resource.Id.roleselector).Visibility == ViewStates.Visible) { ShowLeaveDialog(false); } } } else { if (FindViewById(Resource.Id.shotselector).Visibility == ViewStates.Visible || !LIVEMODE) { ShowLeaveDialog(false); } else { if (FindViewById(Resource.Id.shotselector).Visibility == ViewStates.Gone && !recording) { FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Visible; } } } //} } } async void ShowLeaveDialog(bool cancelable, bool perms = false) { if (recording) await StopRecording(); Bootlegger.BootleggerClient.UnSelectRole(!WhiteLabelConfig.REDUCE_BANDWIDTH, true); Intent intent = new Intent(); intent.PutExtra("videocap", true); if (perms) intent.PutExtra("needsperms", true); intent.PutExtra("eventid", Bootlegger.BootleggerClient.CurrentEvent.id); SetResult(Result.Ok, intent); Finish(); } private void ShowShotRelease(Shot item) { if (item.release && Bootlegger.BootleggerClient.CurrentEvent.shotrelease != null && Bootlegger.BootleggerClient.CurrentEvent.shotrelease != "") { //show release dialog: var dialog = new Android.Support.V7.App.AlertDialog.Builder(this,Resource.Style.MyAlertDialogStyle); View di = LayoutInflater.Inflate(Resource.Layout.shot_release_dialog, null); //if ((Application as BootleggerApp).Comms.CurrentEvent.shotrelease != null && (Application as BootleggerApp).Comms.CurrentEvent.shotrelease != "") di.FindViewById<TextView>(Resource.Id.text).TextFormatted = (Android.Text.Html.FromHtml(Bootlegger.BootleggerClient.CurrentEvent.shotrelease)); dialog.SetView(di); dialog.SetNegativeButton(Android.Resource.String.No, new EventHandler<DialogClickEventArgs>((oe, eo) => { //return to the shot selection screen FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Visible; })) .SetPositiveButton(Resource.String.agree, new EventHandler<DialogClickEventArgs>((oe, eo) => { //continue: })) .SetCancelable(false) .Show(); } } public void Video_ItemSelected(Shot item) { //Shot item; ShowShotRelease(item); //sets the overlay: Picasso.With(this).Load("file://" + item.image).Into(FindViewById<ImageView>(Resource.Id.overlayimg)); if (item.coverage_class != null) { if (Bootlegger.BootleggerClient.CurrentEvent.coverage_classes.Count > item.coverage_class) { FindViewById<TextView>(Resource.Id.overlaytext).Text = Regex.Replace(item.description, "%%(.*?)%%", Bootlegger.BootleggerClient.CurrentEvent.coverage_classes[int.Parse(item.coverage_class.ToString())].name); } } else { FindViewById<TextView>(Resource.Id.overlaytext).Text = Regex.Replace(item.description, "%%(.*?)%%", Resources.GetString(Resource.String.them)); } //FindViewById<TextView>(Resource.Id.overlaytext).Text = Regex.Replace(item.description, "%%(.*?)%%", ""); FindViewById(Resource.Id.overlay).Visibility = ViewStates.Visible; FindViewById<ToggleButton>(Resource.Id.showoverlay).Checked = true; if (!LIVEMODE) Bootlegger.BootleggerClient.AcceptShot(item); Bootlegger.BootleggerClient.SetShot(item); if (recording && stopwatch != null) Bootlegger.BootleggerClient.AddTimedMeta(stopwatch.Elapsed, "shot", item.id.ToString()); switch (item.shot_type) { case Shot.ShotTypes.PHOTO: FindViewById<ImageView>(Resource.Id.shottype).SetImageResource(Android.Resource.Drawable.IcMenuGallery); FindViewById<ImageView>(Resource.Id.shottype).Visibility = ViewStates.Visible; break; case Shot.ShotTypes.AUDIO: FindViewById<ImageView>(Resource.Id.shottype).SetImageResource(Android.Resource.Drawable.IcButtonSpeakNow); FindViewById<ImageView>(Resource.Id.shottype).Visibility = ViewStates.Visible; break; default: FindViewById<ImageView>(Resource.Id.shottype).Visibility = ViewStates.Gone; break; } FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Gone; } void Comms_OnMessage(Bootlegger.BootleggerNotificationType ntype, string obj,bool dialog,bool shots,bool vibrate) { string content = ""; switch (ntype) { case Bootlegger.BootleggerNotificationType.CrewReminder: if (string.IsNullOrEmpty(obj)) content = Resources.GetString(Resource.String.crewreminder_content); else content = obj; break; case Bootlegger.BootleggerNotificationType.PhaseChanged: content = Resources.GetString(Resource.String.phasechange, obj); break; case Bootlegger.BootleggerNotificationType.RoleUpdated: content = Resources.GetString(Resource.String.phasechangerole, obj); break; case Bootlegger.BootleggerNotificationType.ShootUpdated: content = Resources.GetString(Resource.String.shootupdatedlong, obj); break; } if (!dialog) { RunOnUiThread(new Action(() => { var msg = FindViewById<TextSwitcher>(Resource.Id.message); if (msg != null) { FindViewById(Resource.Id.messageholder).PostDelayed(() => { msg.SetText(""); FindViewById(Resource.Id.messageholder).Visibility = ViewStates.Invisible; }, 6000); FindViewById(Resource.Id.messageholder).Visibility = ViewStates.Visible; msg.SetText(content); } })); } else { //generic message with dialog RunOnUiThread(new Action(() => { Android.Support.V7.App.AlertDialog.Builder builder = new Android.Support.V7.App.AlertDialog.Builder(this,Resource.Style.MyAlertDialogStyle); builder .SetMessage(content) .SetPositiveButton(Android.Resource.String.Ok, new EventHandler<DialogClickEventArgs>((o, e) => { })) .SetCancelable(false).Show(); })); //} } if (vibrate) { Vibrator vi; vi = (Vibrator)GetSystemService(Context.VibratorService); if (vi.HasVibrator) { vi.Vibrate(100); } } } bool LIVEMODE; bool shownonce; //doing this on load... void Comms_OnModeChange(string obj) { switch (obj) { case "manual": RunOnUiThread(new Action(() => { //show play button FindViewById(Resource.Id.Play).Visibility = ViewStates.Visible; FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Gone; })); break; case "stopped": //event is closed: RunOnUiThread(new Action(() => { FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Gone; FindViewById(Resource.Id.Closed).Visibility = ViewStates.Visible; })); break; case "timed": //show hold / skip button RunOnUiThread(new Action(() => { FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Gone; FindViewById(Resource.Id.Play).Visibility = ViewStates.Gone; })); LIVEMODE = true; break; case "selection": default: RunOnUiThread(new Action(() => { if (!shownonce) { FindViewById(Resource.Id.Play).Visibility = ViewStates.Visible; FindViewById<ToggleButton>(Resource.Id.Play).TextOn = ""; FindViewById<ToggleButton>(Resource.Id.Play).TextOff = ""; if (WhiteLabelConfig.SHOW_ALL_SHOTS) { FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Visible; FindViewById(Resource.Id.roleselector).Visibility = ViewStates.Gone; } else { FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Gone; FindViewById(Resource.Id.roleselector).Visibility = ViewStates.Visible; } shownonce = true; } })); //})); LIVEMODE = false; break; } } public View MakeView() { // Create a new TextView TextView t = new TextView(this) { Gravity = GravityFlags.Top | GravityFlags.CenterHorizontal }; if (t.LayoutDirection == Android.Views.LayoutDirection.Ltr) { t.SetPadding(30, 5, 5, 15); t.SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.ic_headset_mic_white_48dp, 0, 0, 0); } else { t.SetPadding(5, 5, 30, 15); t.SetCompoundDrawablesWithIntrinsicBounds(0, 0, Resource.Drawable.ic_headset_mic_white_48dp, 0); } t.TextSize = 20; t.SetTextColor(Color.Black); return t; } //bool started = false; protected async override void OnPause() { base.OnPause(); //background beacon //Beacons.BeaconInstance.InBackground = true; (Application as BootleggerApp).ReturnState = new BootleggerApp.ApplicationReturnState() { ReturnsTo = BootleggerApp.ReturnType.OPEN_SHOOT }; //tell client that not in shooting mode if (!WhiteLabelConfig.REDUCE_BANDWIDTH) Bootlegger.BootleggerClient.NotReadyToShoot(); //pause any location services: await Plugin.Geolocator.CrossGeolocator.Current.StopListeningAsync(); //geo.StopListening(); //if (recorder != null) //{ if (recording) { await record(); } Bootlegger.BootleggerClient.InBackground = true; lock (cameraDriverLock) { if (cameraDriver != null) cameraDriver.CloseCamera(); } //kill camera?? } object cameraDriverLock = new object(); bool disablelocation = false; bool? from_roles; //bool waitingonperms = false; protected async override void OnResume() { base.OnResume(); NavBarFix(); //Analytics.TrackEvent("VideoScreen"); Bootleg.API.Bootlegger.BootleggerClient.LogUserAction("Video", new KeyValuePair<string, string>("eventid", Bootlegger.BootleggerClient.CurrentEvent.id)); //FindViewById<FrameLayout>(Resource.Id.rolesdemo).Visibility = ViewStates.Gone; //set var to remember if we came from the roles screen: if (!from_roles.HasValue) from_roles = Intent.GetBooleanExtra(Roles.FROM_ROLE, false); var permstatus = new List<Plugin.Permissions.Abstractions.PermissionStatus> { await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Camera), await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Microphone), await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Storage) }; if (!permstatus.All((p) => p == Plugin.Permissions.Abstractions.PermissionStatus.Granted)) { var permsToAskFor = new[] { Plugin.Permissions.Abstractions.Permission.Camera, Plugin.Permissions.Abstractions.Permission.Microphone, Plugin.Permissions.Abstractions.Permission.Storage }; if (WhiteLabelConfig.USE_GPS) { permsToAskFor.Append(Plugin.Permissions.Abstractions.Permission.Location); } var hasperms = await Plugin.Permissions.CrossPermissions.Current.RequestPermissionsAsync(permsToAskFor); if (hasperms.All((p) => (p.Key == Plugin.Permissions.Abstractions.Permission.Location)? true : p.Value == Plugin.Permissions.Abstractions.PermissionStatus.Granted)) PermissionsGranted = true; else { ShowLeaveDialog(false,true); } } else { PermissionsGranted = true; } if (!PermissionsGranted) { Finish(); return; } if (WhiteLabelConfig.ALLOW_BLE) { //start broadcasting beacon //await Beacons.BeaconInstance.StartBroadcastingBle(this, Bootlegger.BootleggerClient.CurrentEvent); //Beacons.BeaconInstance.InBackground = false; } //Insights.Track("VideoScreen"); Bootlegger.BootleggerClient.InBackground = false; FindViewById(Resource.Id.helpoverlay).Visibility = ViewStates.Invisible; if (Bootlegger.BootleggerClient.CurrentEvent == null) { Finish(); return; } Comms_OnModeChange(Bootlegger.BootleggerClient.CurrentEvent.CurrentMode); pulse = AnimationUtils.LoadAnimation(this, Resource.Animation.pulse); lock (cameraDriverLock) { try { ReStartCamera(null); } catch { } } //ask for location perms: if (WhiteLabelConfig.USE_GPS) { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Location); if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted) { if (!Plugin.Geolocator.CrossGeolocator.Current.IsListening) await Plugin.Geolocator.CrossGeolocator.Current.StartListeningAsync(WhiteLabelConfig.GPS_RECORD_INTERVAL_SECS, 10, true); } else { disablelocation = true; } //if (!disablelocation) //{ //} } if (from_roles.HasValue && from_roles==true && !WhiteLabelConfig.SHOW_ALL_SHOTS) { FindViewById(Resource.Id.shotselector).Visibility = ViewStates.Visible; FindViewById(Resource.Id.roleselector).Visibility = ViewStates.Gone; } } void NavBarFix() { // MOVING / HIDING THE BUTTONS DEPENDING ON SOFT KEYS AND LOCATIONS: if (!ViewConfiguration.Get(this).HasPermanentMenuKey && !KeyCharacterMap.DeviceHasKey(Keycode.Back)) { //TODO: show soft back button: FindViewById(Resource.Id.backbtn).Visibility = ViewStates.Visible; FindViewById(Resource.Id.backbtn).Click += Video_Click1; //var padding_right = 0; //Rect visibleFrame = new Rect(); //Window.DecorView.GetWindowVisibleDisplayFrame(visibleFrame); //DisplayMetrics dm = Resources.DisplayMetrics; //// check if the DecorView takes the whole screen vertically or horizontally //var isRightOfContent = dm.HeightPixels == visibleFrame.Bottom; //var isBelowContent = dm.WidthPixels == visibleFrame.Right; //var nav_horz = Resources.GetIdentifier("navigation_bar_height_landscape", "dimen", "android"); //var navbardim = Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); //var padding_right = Resources.GetDimensionPixelSize(navbardim); //var padding_top = Resources.GetDimensionPixelSize(nav_horz); //pad overlay text -- why?? //FindViewById<TextView>(Resource.Id.overlaytext).SetPadding(0, Utils.dp2px(this, 6), Utils.dp2px(this, 80), 0); //return; //if (padding_right < padding_top) //{ //if (navbardim > 0) //{ //var param = FindViewById(Resource.Id.allbuttons).LayoutParameters.DeepCopy(); // (FindViewById<LinearLayout>(Resource.Id.allbuttons).LayoutParameters as LinearLayout.MarginLayoutParams).RightMargin = padding_right; // (FindViewById<FrameLayout>(Resource.Id.recordbtnwrapper).LayoutParameters as LinearLayout.MarginLayoutParams).RightMargin = padding_right; // //} // //Window.AddFlags(WindowManagerFlags.TranslucentNavigation); //} //else //{ // //var padding_top = Resources.GetDimensionPixelSize(navbardim); // //Window.AddFlags(WindowManagerFlags.TranslucentNavigation); // //var barsize = getSoftButtonsBarSizePort(this); // FindViewById<TextView>(Resource.Id.overlaytext).SetPadding(0, Utils.dp2px(this, 6), Utils.dp2px(this, 80 + padding_top), 0); //} } else { FindViewById(Resource.Id.backbtn).Visibility = ViewStates.Gone; } } private void Video_Click1(object sender, EventArgs e) { //perform back action OnBackPressed(); } SelectRoleFrag selectrolefrag; protected override void OnStop() { base.OnStop(); //started = false; //stop ble beacon //Beacons.BeaconInstance.StopBroadcastingBle(); Bootlegger.BootleggerClient.OnCountdown -= Comms_OnCountdown; Bootlegger.BootleggerClient.OnRoleChanged -= Comms_OnRoleChanged; Bootlegger.BootleggerClient.OnServerDied -= Comms_OnServerDied; Bootlegger.BootleggerClient.OnMessage -= Comms_OnMessage; Bootlegger.BootleggerClient.OnPhaseChange -= Comms_OnPhaseChange; Bootlegger.BootleggerClient.OnEventUpdated -= Comms_OnEventUpdated; Bootlegger.BootleggerClient.OnImagesUpdated -= Comms_OnImagesUpdated; Bootlegger.BootleggerClient.OnPermissionsChanged -= Comms_OnPermissionsChanged; } string thumbnailfilename = ""; #region CAMERA public enum CAMERA_POSITION { REAR=0, FRONT=1}; CAMERA_POSITION CURRENTCAMERA; private void Cam_Switch(object sender, EventArgs e) { if (!recording) { if (CURRENTCAMERA == CAMERA_POSITION.REAR && cameraDriver.NumCameras > 1) { CURRENTCAMERA = CAMERA_POSITION.FRONT; ReStartCamera(null); } else if (CURRENTCAMERA != CAMERA_POSITION.REAR) { CURRENTCAMERA = CAMERA_POSITION.REAR; ReStartCamera(null); } else { ReStartCamera(null); } } } ICameraDriver cameraDriver; private void ReStartCamera(Bundle savedInstanceState) { //stop old camera if (PermissionsGranted) { try { if (cameraDriver != null) cameraDriver.CloseCamera(); } catch { } if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) { CameraManager manager = (CameraManager)GetSystemService(Context.CameraService); var cameraId = Camera2Fragment.GetCam(manager, CURRENTCAMERA); CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId); if ((int)characteristics.Get(CameraCharacteristics.InfoSupportedHardwareLevel) != (int)InfoSupportedHardwareLevel.Full) cameraDriver = Camera1Fragment.NewInstance((int)CURRENTCAMERA); else cameraDriver = Camera2Fragment.newInstance(CURRENTCAMERA); } else { cameraDriver = Camera1Fragment.NewInstance((int)CURRENTCAMERA); } SupportFragmentManager.BeginTransaction().Replace(Resource.Id.VideoPreview, cameraDriver as Android.Support.V4.App.Fragment).Commit(); cameraDriver.OnPictureTaken += CameraDriver_OnPictureTaken; cameraDriver.OnSetupComplete += CameraDriver_OnSetupComplete; cameraDriver.OnError += CameraDriver_OnError; } } private void CameraDriver_OnError(string obj) { //Toast.MakeText(Application.Context, new Exce, ToastLength.Short).Show(); LoginFuncs.ShowToast(this, new Exception("Camera Problem")); Bootlegger.BootleggerClient.UnSelectRole(!WhiteLabelConfig.REDUCE_BANDWIDTH, true); Finish(); return; } private void CameraDriver_OnSetupComplete() { if (!cameraDriver.HasZoom) FindViewById<SeekBar>(Resource.Id.zoom).Visibility = ViewStates.Gone; else { try { var levels = cameraDriver.ZoomLevels; var p = from n in levels where n.IntValue() >= 200 orderby n.IntValue() ascending select n; var max = levels.IndexOf(p.First()); FindViewById<SeekBar>(Resource.Id.zoom).Max = max; } catch { FindViewById<SeekBar>(Resource.Id.zoom).Visibility = ViewStates.Gone; } } try { FindViewById<View>(Resource.Id.camera_preview).Post(() => { FindViewById<View>(Resource.Id.camera_preview).RequestLayout(); }); } catch { //handle camera not created yet (permissions not met) } } private void CameraDriver_OnPictureTaken() { RunOnUiThread(async () => { if (recording) { await record(); } }); } public void OnSystemUiVisibilityChange([GeneratedEnum] StatusBarVisibility visibility) { if ((visibility & (StatusBarVisibility)SystemUiFlags.Fullscreen) == 0) { Window.DecorView.SystemUiVisibility = (StatusBarVisibility)flags; } } SystemUiFlags flags = SystemUiFlags.LayoutFullscreen | SystemUiFlags.LayoutHideNavigation | SystemUiFlags.LayoutFullscreen | SystemUiFlags.HideNavigation | SystemUiFlags.Fullscreen | SystemUiFlags.ImmersiveSticky; #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 Xunit; namespace System.PrivateUri.Tests { public static class UriTests { [InlineData(true)] [InlineData(false)] [Theory] public static void TestCtor_String_Boolean(bool dontEscape) { #pragma warning disable 0618 #pragma warning disable 0612 Uri uri = new Uri(@"http://foo/bar/baz#frag", dontEscape); #pragma warning restore 0612 #pragma warning restore 0618 int i; string s; bool b; UriHostNameType uriHostNameType; string[] ss; s = uri.ToString(); Assert.Equal(s, @"http://foo/bar/baz#frag"); s = uri.AbsolutePath; Assert.Equal<String>(s, @"/bar/baz"); s = uri.AbsoluteUri; Assert.Equal<String>(s, @"http://foo/bar/baz#frag"); s = uri.Authority; Assert.Equal<String>(s, @"foo"); s = uri.DnsSafeHost; Assert.Equal<String>(s, @"foo"); s = uri.Fragment; Assert.Equal<String>(s, @"#frag"); s = uri.Host; Assert.Equal<String>(s, @"foo"); uriHostNameType = uri.HostNameType; Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns); b = uri.IsAbsoluteUri; Assert.True(b); b = uri.IsDefaultPort; Assert.True(b); b = uri.IsFile; Assert.False(b); b = uri.IsLoopback; Assert.False(b); b = uri.IsUnc; Assert.False(b); s = uri.LocalPath; Assert.Equal<String>(s, @"/bar/baz"); s = uri.OriginalString; Assert.Equal<String>(s, @"http://foo/bar/baz#frag"); s = uri.PathAndQuery; Assert.Equal<String>(s, @"/bar/baz"); i = uri.Port; Assert.Equal<int>(i, 80); s = uri.Query; Assert.Equal<String>(s, @""); s = uri.Scheme; Assert.Equal<String>(s, @"http"); ss = uri.Segments; Assert.Equal<int>(ss.Length, 3); Assert.Equal<String>(ss[0], @"/"); Assert.Equal<String>(ss[1], @"bar/"); Assert.Equal<String>(ss[2], @"baz"); b = uri.UserEscaped; Assert.Equal(b, dontEscape); s = uri.UserInfo; Assert.Equal<String>(s, @""); } [InlineData(true)] [InlineData(false)] [Theory] public static void TestCtor_Uri_String_Boolean(bool dontEscape) { Uri uri; uri = new Uri(@"http://www.contoso.com/"); #pragma warning disable 0618 uri = new Uri(uri, "catalog/shownew.htm?date=today", dontEscape); #pragma warning restore 0618 int i; string s; bool b; UriHostNameType uriHostNameType; string[] ss; s = uri.ToString(); Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.AbsolutePath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.AbsoluteUri; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.Authority; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.DnsSafeHost; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.Fragment; Assert.Equal<String>(s, @""); s = uri.Host; Assert.Equal<String>(s, @"www.contoso.com"); uriHostNameType = uri.HostNameType; Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns); b = uri.IsAbsoluteUri; Assert.True(b); b = uri.IsDefaultPort; Assert.True(b); b = uri.IsFile; Assert.False(b); b = uri.IsLoopback; Assert.False(b); b = uri.IsUnc; Assert.False(b); s = uri.LocalPath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.OriginalString; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.PathAndQuery; Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today"); i = uri.Port; Assert.Equal<int>(i, 80); s = uri.Query; Assert.Equal<String>(s, @"?date=today"); s = uri.Scheme; Assert.Equal<String>(s, @"http"); ss = uri.Segments; Assert.Equal<int>(ss.Length, 3); Assert.Equal<String>(ss[0], @"/"); Assert.Equal<String>(ss[1], @"catalog/"); Assert.Equal<String>(ss[2], @"shownew.htm"); b = uri.UserEscaped; Assert.Equal(b, dontEscape); s = uri.UserInfo; Assert.Equal<String>(s, @""); } [Fact] public static void TestMakeRelative_Invalid() { var baseUri = new Uri("http://www.domain.com/"); var relativeUri = new Uri("/path/", UriKind.Relative); #pragma warning disable 0618 AssertExtensions.Throws<ArgumentNullException>("toUri", () => baseUri.MakeRelative(null)); // Uri is null Assert.Throws<InvalidOperationException>(() => relativeUri.MakeRelative(baseUri)); // Base uri is relative Assert.Throws<InvalidOperationException>(() => baseUri.MakeRelative(relativeUri)); // Uri is relative #pragma warning restore 0618 } [Fact] public static void TestMakeRelative() { // Create a base Uri. Uri address1 = new Uri("http://www.contoso.com/"); Uri address2 = new Uri("http://www.contoso.com:8000/"); Uri address3 = new Uri("http://username@www.contoso.com/"); // Create a new Uri from a string. Uri address4 = new Uri("http://www.contoso.com/index.htm?date=today"); #pragma warning disable 0618 // Determine the relative Uri. string uriStr1 = address1.MakeRelative(address4); string uriStr2 = address2.MakeRelative(address4); string uriStr3 = address3.MakeRelative(address4); #pragma warning restore 0618 Assert.Equal(uriStr1, @"index.htm"); Assert.Equal(uriStr2, @"http://www.contoso.com/index.htm?date=today"); Assert.Equal(uriStr3, @"index.htm"); } [Fact] public static void TestHexMethods() { char testChar = 'e'; Assert.True(Uri.IsHexDigit(testChar)); Assert.Equal(14, Uri.FromHex(testChar)); string hexString = Uri.HexEscape(testChar); Assert.Equal(hexString, "%65"); int index = 0; Assert.True(Uri.IsHexEncoding(hexString, index)); Assert.Equal(testChar, Uri.HexUnescape(hexString, ref index)); } [Fact] public static void TestHexMethods_Invalid() { AssertExtensions.Throws<ArgumentException>(null, () => Uri.FromHex('?')); Assert.Throws<ArgumentOutOfRangeException>(() => Uri.HexEscape('\x100')); int index = -1; Assert.Throws<ArgumentOutOfRangeException>(() => Uri.HexUnescape("%75", ref index)); index = 0; Uri.HexUnescape("%75", ref index); Assert.Throws<ArgumentOutOfRangeException>(() => Uri.HexUnescape("%75", ref index)); } } }
using System; using System.Windows.Input; using System.Diagnostics; using System.Linq.Expressions; using System.Threading.Tasks; namespace Xamvvm { /// <summary> /// xamvvm ICommand implementation. /// </summary> public class BaseCommand<T> : IBaseCommand { readonly Func<T, Task> _execute; readonly Func<T, bool> _canExecuteFunc; readonly WeakEventManager _weakEventManager = new WeakEventManager(); bool _canExecute = true; /// <summary> /// Initializes a new instance of the <see cref="Xamvvm.BaseCommand"/> class. /// </summary> /// <param name="execute">Execute.</param> #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public BaseCommand(Action<T> execute) : this(new Func<T, Task>(async (obj) => execute(obj)), null) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { if (execute == null) throw new ArgumentNullException(nameof(execute)); } /// <summary> /// Initializes a new instance of the <see cref="Xamvvm.BaseCommand"/> class. /// </summary> /// <param name="execute">Execute.</param> public BaseCommand(Func<T, Task> execute) : this(execute, null) { } /// <summary> /// Initializes a new instance of the <see cref="Xamvvm.BaseCommand"/> class. /// </summary> /// <param name="execute">Execute.</param> /// <param name="canExecute">Can execute.</param> public BaseCommand(Func<T, Task> execute, Func<T, bool> canExecute) { if (execute == null) throw new ArgumentNullException(nameof(execute)); _execute = execute; _canExecuteFunc = canExecute; } /// <summary> /// Occurs when can execute changed. /// </summary> public event EventHandler CanExecuteChanged { add { _weakEventManager.AddEventHandler(value); } remove { _weakEventManager.RemoveEventHandler(value); } } /// <summary> /// Raises the can execute changed. /// </summary> public void RaiseCanExecuteChanged() { _weakEventManager.HandleEvent(this, EventArgs.Empty, nameof(CanExecuteChanged)); } /// <summary> /// Determines whether this instance can execute the specified parameter. /// </summary> /// <returns><c>true</c> if this instance can execute the specified parameter; otherwise, <c>false</c>.</returns> /// <param name="parameter">Parameter.</param> [DebuggerStepThrough] public bool CanExecute(object parameter) { return _canExecute && (_canExecuteFunc == null || _canExecuteFunc((T)parameter)); } /// <summary> /// Execute the specified action. /// </summary> /// <param name="parameter">Parameter.</param> public async void Execute(object parameter) { try { _canExecute = false; RaiseCanExecuteChanged(); if (parameter == null) await _execute(default(T)); else await _execute((T)parameter); } finally { _canExecute = true; RaiseCanExecuteChanged(); } } } /// <summary> /// xamvvm ICommand implementation. /// </summary> public class BaseCommand : IBaseCommand { readonly Func<object, Task> _execute; readonly Func<bool> _canExecuteFunc; readonly WeakEventManager _weakEventManager = new WeakEventManager(); bool _canExecute = true; /// <summary> /// Initializes a new instance of the <see cref="Xamvvm.BaseCommand"/> class. /// </summary> /// <param name="execute">Execute.</param> #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public BaseCommand(Action<object> execute) : this(new Func<object, Task>(async (obj) => execute(obj)), null) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { if (execute == null) throw new ArgumentNullException(nameof(execute)); } /// <summary> /// Initializes a new instance of the <see cref="Xamvvm.BaseCommand"/> class. /// </summary> /// <param name="execute">Execute.</param> public BaseCommand(Func<object, Task> execute) : this(execute, null) { } /// <summary> /// Initializes a new instance of the <see cref="Xamvvm.BaseCommand"/> class. /// </summary> /// <param name="execute">Execute.</param> /// <param name="canExecute">Can execute.</param> public BaseCommand(Func<object, Task> execute, Func<bool> canExecute) { if (execute == null) { throw new ArgumentNullException(nameof(execute)); } _execute = execute; _canExecuteFunc = canExecute; } /// <summary> /// Occurs when can execute changed. /// </summary> public event EventHandler CanExecuteChanged { add { _weakEventManager.AddEventHandler(value); } remove { _weakEventManager.RemoveEventHandler(value); } } /// <summary> /// Raises the can execute changed. /// </summary> public void RaiseCanExecuteChanged() { _weakEventManager.HandleEvent(this, EventArgs.Empty, nameof(CanExecuteChanged)); } /// <summary> /// Determines whether this instance can execute the specified parameter. /// </summary> /// <returns><c>true</c> if this instance can execute the specified parameter; otherwise, <c>false</c>.</returns> /// <param name="parameter">Parameter.</param> [DebuggerStepThrough] public bool CanExecute(object parameter) { return _canExecute && (_canExecuteFunc == null || _canExecuteFunc()); } /// <summary> /// Execute the specified action. /// </summary> /// <param name="parameter">Parameter.</param> public async void Execute(object parameter) { try { _canExecute = false; RaiseCanExecuteChanged(); await _execute(parameter); } finally { _canExecute = true; RaiseCanExecuteChanged(); } } } class WeakEventManager { readonly Dictionary<string, List<Subscription>> _eventHandlers = new Dictionary<string, List<Subscription>>(); public void AddEventHandler<TEventArgs>(EventHandler<TEventArgs> handler, [CallerMemberName]string eventName = null) where TEventArgs : EventArgs { if (string.IsNullOrEmpty(eventName)) throw new ArgumentNullException(nameof(eventName)); if (handler == null) throw new ArgumentNullException(nameof(handler)); AddEventHandler(eventName, handler.Target, handler.GetMethodInfo()); } public void AddEventHandler(EventHandler handler, [CallerMemberName]string eventName = null) { if (string.IsNullOrEmpty(eventName)) throw new ArgumentNullException(nameof(eventName)); if (handler == null) throw new ArgumentNullException(nameof(handler)); AddEventHandler(eventName, handler.Target, handler.GetMethodInfo()); } public void HandleEvent(object sender, object args, string eventName) { var toRaise = new List<(object subscriber, MethodInfo handler)>(); var toRemove = new List<Subscription>(); if (_eventHandlers.TryGetValue(eventName, out List<Subscription> target)) { for (int i = 0; i < target.Count; i++) { Subscription subscription = target[i]; bool isStatic = subscription.Subscriber == null; if (isStatic) { // For a static method, we'll just pass null as the first parameter of MethodInfo.Invoke toRaise.Add((null, subscription.Handler)); continue; } object subscriber = subscription.Subscriber.Target; if (subscriber == null) // The subscriber was collected, so there's no need to keep this subscription around toRemove.Add(subscription); else toRaise.Add((subscriber, subscription.Handler)); } for (int i = 0; i < toRemove.Count; i++) { Subscription subscription = toRemove[i]; target.Remove(subscription); } } for (int i = 0; i < toRaise.Count; i++) { (var subscriber, var handler) = toRaise[i]; handler.Invoke(subscriber, new[] { sender, args }); } } public void RemoveEventHandler<TEventArgs>(EventHandler<TEventArgs> handler, [CallerMemberName]string eventName = null) where TEventArgs : EventArgs { if (string.IsNullOrEmpty(eventName)) throw new ArgumentNullException(nameof(eventName)); if (handler == null) throw new ArgumentNullException(nameof(handler)); RemoveEventHandler(eventName, handler.Target, handler.GetMethodInfo()); } public void RemoveEventHandler(EventHandler handler, [CallerMemberName]string eventName = null) { if (string.IsNullOrEmpty(eventName)) throw new ArgumentNullException(nameof(eventName)); if (handler == null) throw new ArgumentNullException(nameof(handler)); RemoveEventHandler(eventName, handler.Target, handler.GetMethodInfo()); } void AddEventHandler(string eventName, object handlerTarget, MethodInfo methodInfo) { if (!_eventHandlers.TryGetValue(eventName, out List<Subscription> targets)) { targets = new List<Subscription>(); _eventHandlers.Add(eventName, targets); } if (handlerTarget == null) { // This event handler is a static method targets.Add(new Subscription(null, methodInfo)); return; } targets.Add(new Subscription(new WeakReference(handlerTarget), methodInfo)); } void RemoveEventHandler(string eventName, object handlerTarget, MemberInfo methodInfo) { if (!_eventHandlers.TryGetValue(eventName, out List<Subscription> subscriptions)) return; for (int n = subscriptions.Count; n > 0; n--) { Subscription current = subscriptions[n - 1]; if (current.Subscriber?.Target != handlerTarget || current.Handler.Name != methodInfo.Name) continue; subscriptions.Remove(current); break; } } struct Subscription { public Subscription(WeakReference subscriber, MethodInfo handler) { Subscriber = subscriber; Handler = handler ?? throw new ArgumentNullException(nameof(handler)); } public readonly WeakReference Subscriber; public readonly MethodInfo Handler; } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Concurrency; namespace Orleans.Streams { [Serializable] [Immutable] internal class StreamImpl<T> : IStreamIdentity, IAsyncStream<T>, IStreamControl, ISerializable { private readonly StreamId streamId; private readonly bool isRewindable; [NonSerialized] private IInternalStreamProvider provider; [NonSerialized] private volatile IInternalAsyncBatchObserver<T> producerInterface; [NonSerialized] private IInternalAsyncObservable<T> consumerInterface; [NonSerialized] private readonly object initLock; // need the lock since the same code runs in the provider on the client and in the silo. internal StreamId StreamId { get { return streamId; } } public bool IsRewindable { get { return isRewindable; } } public Guid Guid { get { return streamId.Guid; } } public string Namespace { get { return streamId.Namespace; } } public string ProviderName { get { return streamId.ProviderName; } } // IMPORTANT: This constructor needs to be public for Json deserialization to work. public StreamImpl() { initLock = new object(); } internal StreamImpl(StreamId streamId, IInternalStreamProvider provider, bool isRewindable) { if (null == streamId) throw new ArgumentNullException("streamId"); if (null == provider) throw new ArgumentNullException("provider"); this.streamId = streamId; this.provider = provider; producerInterface = null; consumerInterface = null; initLock = new object(); this.isRewindable = isRewindable; } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer) { return GetConsumerInterface().SubscribeAsync(observer, null); } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer, StreamSequenceToken token, StreamFilterPredicate filterFunc = null, object filterData = null) { return GetConsumerInterface().SubscribeAsync(observer, token, filterFunc, filterData); } public async Task Cleanup(bool cleanupProducers, bool cleanupConsumers) { // Cleanup producers if (cleanupProducers && producerInterface != null) { await producerInterface.Cleanup(); producerInterface = null; } // Cleanup consumers if (cleanupConsumers && consumerInterface != null) { await consumerInterface.Cleanup(); consumerInterface = null; } } public Task OnNextAsync(T item, StreamSequenceToken token = null) { return GetProducerInterface().OnNextAsync(item, token); } public Task OnNextBatchAsync(IEnumerable<T> batch, StreamSequenceToken token = null) { return GetProducerInterface().OnNextBatchAsync(batch, token); } public Task OnCompletedAsync() { return GetProducerInterface().OnCompletedAsync(); } public Task OnErrorAsync(Exception ex) { return GetProducerInterface().OnErrorAsync(ex); } internal Task<StreamSubscriptionHandle<T>> ResumeAsync( StreamSubscriptionHandle<T> handle, IAsyncObserver<T> observer, StreamSequenceToken token) { return GetConsumerInterface().ResumeAsync(handle, observer, token); } public Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptionHandles() { return GetConsumerInterface().GetAllSubscriptions(); } internal Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle) { return GetConsumerInterface().UnsubscribeAsync(handle); } internal IAsyncBatchObserver<T> GetProducerInterface() { if (producerInterface != null) return producerInterface; lock (initLock) { if (producerInterface != null) return producerInterface; if (provider == null) provider = GetStreamProvider(); producerInterface = provider.GetProducerInterface<T>(this); } return producerInterface; } internal IInternalAsyncObservable<T> GetConsumerInterface() { if (consumerInterface == null) { lock (initLock) { if (consumerInterface == null) { if (provider == null) provider = GetStreamProvider(); consumerInterface = provider.GetConsumerInterface<T>(this); } } } return consumerInterface; } private IInternalStreamProvider GetStreamProvider() { return RuntimeClient.Current.CurrentStreamProviderManager.GetProvider(streamId.ProviderName) as IInternalStreamProvider; } #region IComparable<IAsyncStream<T>> Members public int CompareTo(IAsyncStream<T> other) { var o = other as StreamImpl<T>; return o == null ? 1 : streamId.CompareTo(o.streamId); } #endregion #region IEquatable<IAsyncStream<T>> Members public virtual bool Equals(IAsyncStream<T> other) { var o = other as StreamImpl<T>; return o != null && streamId.Equals(o.streamId); } #endregion public override bool Equals(object obj) { var o = obj as StreamImpl<T>; return o != null && streamId.Equals(o.streamId); } public override int GetHashCode() { return streamId.GetHashCode(); } public override string ToString() { return streamId.ToString(); } #region ISerializable Members public void GetObjectData(SerializationInfo info, StreamingContext context) { // Use the AddValue method to specify serialized values. info.AddValue("StreamId", streamId, typeof(StreamId)); info.AddValue("IsRewindable", isRewindable, typeof(bool)); } // The special constructor is used to deserialize values. protected StreamImpl(SerializationInfo info, StreamingContext context) { // Reset the property value using the GetValue method. streamId = (StreamId)info.GetValue("StreamId", typeof(StreamId)); isRewindable = info.GetBoolean("IsRewindable"); initLock = new object(); } #endregion } }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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 UnityEngine; using System.Collections.Generic; namespace Spine.Unity.Modules.AttachmentTools { public static class AttachmentRegionExtensions { #region GetRegion /// <summary> /// Tries to get the region (image) of a renderable attachment. If the attachment is not renderable, it returns null.</summary> public static AtlasRegion GetRegion (this Attachment attachment) { var regionAttachment = attachment as RegionAttachment; if (regionAttachment != null) return regionAttachment.RendererObject as AtlasRegion; var meshAttachment = attachment as MeshAttachment; if (meshAttachment != null) return meshAttachment.RendererObject as AtlasRegion; return null; } /// <summary>Gets the region (image) of a RegionAttachment</summary> public static AtlasRegion GetRegion (this RegionAttachment regionAttachment) { return regionAttachment.RendererObject as AtlasRegion; } /// <summary>Gets the region (image) of a MeshAttachment</summary> public static AtlasRegion GetRegion (this MeshAttachment meshAttachment) { return meshAttachment.RendererObject as AtlasRegion; } #endregion #region SetRegion /// <summary> /// Tries to set the region (image) of a renderable attachment. If the attachment is not renderable, nothing is applied.</summary> public static void SetRegion (this Attachment attachment, AtlasRegion region, bool updateOffset = true) { var regionAttachment = attachment as RegionAttachment; if (regionAttachment != null) regionAttachment.SetRegion(region, updateOffset); var meshAttachment = attachment as MeshAttachment; if (meshAttachment != null) meshAttachment.SetRegion(region, updateOffset); } /// <summary>Sets the region (image) of a RegionAttachment</summary> public static void SetRegion (this RegionAttachment attachment, AtlasRegion region, bool updateOffset = true) { if (region == null) throw new System.ArgumentNullException("region"); // (AtlasAttachmentLoader.cs) attachment.RendererObject = region; attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.rotate); attachment.regionOffsetX = region.offsetX; attachment.regionOffsetY = region.offsetY; attachment.regionWidth = region.width; attachment.regionHeight = region.height; attachment.regionOriginalWidth = region.originalWidth; attachment.regionOriginalHeight = region.originalHeight; if (updateOffset) attachment.UpdateOffset(); } /// <summary>Sets the region (image) of a MeshAttachment</summary> public static void SetRegion (this MeshAttachment attachment, AtlasRegion region, bool updateUVs = true) { if (region == null) throw new System.ArgumentNullException("region"); // (AtlasAttachmentLoader.cs) attachment.RendererObject = region; attachment.RegionU = region.u; attachment.RegionV = region.v; attachment.RegionU2 = region.u2; attachment.RegionV2 = region.v2; attachment.RegionRotate = region.rotate; attachment.regionOffsetX = region.offsetX; attachment.regionOffsetY = region.offsetY; attachment.regionWidth = region.width; attachment.regionHeight = region.height; attachment.regionOriginalWidth = region.originalWidth; attachment.regionOriginalHeight = region.originalHeight; if (updateUVs) attachment.UpdateUVs(); } #endregion #region Runtime RegionAttachments /// <summary> /// Creates a RegionAttachment based on a sprite. This method creates a real, usable AtlasRegion. That AtlasRegion uses a new AtlasPage with the Material provided./// </summary> public static RegionAttachment ToRegionAttachment (this Sprite sprite, Material material) { return sprite.ToRegionAttachment(material.ToSpineAtlasPage()); } /// <summary> /// Creates a RegionAttachment based on a sprite. This method creates a real, usable AtlasRegion. That AtlasRegion uses the AtlasPage provided./// </summary> public static RegionAttachment ToRegionAttachment (this Sprite sprite, AtlasPage page) { if (sprite == null) throw new System.ArgumentNullException("sprite"); if (page == null) throw new System.ArgumentNullException("page"); var region = sprite.ToAtlasRegion(page); var unitsPerPixel = 1f / sprite.pixelsPerUnit; return region.ToRegionAttachment(sprite.name, unitsPerPixel); } /// <summary> /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate texture of the Sprite's texture data. Returns a RegionAttachment that uses it. Use this if you plan to use a premultiply alpha shader such as "Spine/Skeleton"</summary> public static RegionAttachment ToRegionAttachmentPMAClone (this Sprite sprite, Shader shader, TextureFormat textureFormat = SpriteAtlasRegionExtensions.SpineTextureFormat, bool mipmaps = SpriteAtlasRegionExtensions.UseMipMaps, Material materialPropertySource = null) { if (sprite == null) throw new System.ArgumentNullException("sprite"); if (shader == null) throw new System.ArgumentNullException("shader"); var region = sprite.ToAtlasRegionPMAClone(shader, textureFormat, mipmaps, materialPropertySource); var unitsPerPixel = 1f / sprite.pixelsPerUnit; return region.ToRegionAttachment(sprite.name, unitsPerPixel); } public static RegionAttachment ToRegionAttachmentPMAClone (this Sprite sprite, Material materialPropertySource, TextureFormat textureFormat = SpriteAtlasRegionExtensions.SpineTextureFormat, bool mipmaps = SpriteAtlasRegionExtensions.UseMipMaps) { return sprite.ToRegionAttachmentPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource); } /// <summary> /// Creates a new RegionAttachment from a given AtlasRegion.</summary> public static RegionAttachment ToRegionAttachment (this AtlasRegion region, string attachmentName, float scale = 0.01f) { if (string.IsNullOrEmpty(attachmentName)) throw new System.ArgumentException("attachmentName can't be null or empty.", "attachmentName"); if (region == null) throw new System.ArgumentNullException("region"); // (AtlasAttachmentLoader.cs) var attachment = new RegionAttachment(attachmentName); attachment.RendererObject = region; attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.rotate); attachment.regionOffsetX = region.offsetX; attachment.regionOffsetY = region.offsetY; attachment.regionWidth = region.width; attachment.regionHeight = region.height; attachment.regionOriginalWidth = region.originalWidth; attachment.regionOriginalHeight = region.originalHeight; attachment.Path = region.name; attachment.scaleX = 1; attachment.scaleY = 1; attachment.rotation = 0; attachment.r = 1; attachment.g = 1; attachment.b = 1; attachment.a = 1; // pass OriginalWidth and OriginalHeight because UpdateOffset uses it in its calculation. attachment.width = attachment.regionOriginalWidth * scale; attachment.height = attachment.regionOriginalHeight * scale; attachment.SetColor(Color.white); attachment.UpdateOffset(); return attachment; } /// <summary> Sets the scale. Call regionAttachment.UpdateOffset to apply the change.</summary> public static void SetScale (this RegionAttachment regionAttachment, Vector2 scale) { regionAttachment.scaleX = scale.x; regionAttachment.scaleY = scale.y; } /// <summary> Sets the scale. Call regionAttachment.UpdateOffset to apply the change.</summary> public static void SetScale (this RegionAttachment regionAttachment, float x, float y) { regionAttachment.scaleX = x; regionAttachment.scaleY = y; } /// <summary> Sets the position offset. Call regionAttachment.UpdateOffset to apply the change.</summary> public static void SetPositionOffset (this RegionAttachment regionAttachment, Vector2 offset) { regionAttachment.x = offset.x; regionAttachment.y = offset.y; } /// <summary> Sets the position offset. Call regionAttachment.UpdateOffset to apply the change.</summary> public static void SetPositionOffset (this RegionAttachment regionAttachment, float x, float y) { regionAttachment.x = x; regionAttachment.y = y; } /// <summary> Sets the rotation. Call regionAttachment.UpdateOffset to apply the change.</summary> public static void SetRotation (this RegionAttachment regionAttachment, float rotation) { regionAttachment.rotation = rotation; } #endregion } public static class SpriteAtlasRegionExtensions { internal const TextureFormat SpineTextureFormat = TextureFormat.RGBA32; internal const bool UseMipMaps = false; internal const float DefaultScale = 0.01f; public static AtlasRegion ToAtlasRegion (this Texture2D t, Material materialPropertySource, float scale = DefaultScale) { return t.ToAtlasRegion(materialPropertySource.shader, scale, materialPropertySource); } public static AtlasRegion ToAtlasRegion (this Texture2D t, Shader shader, float scale = DefaultScale, Material materialPropertySource = null) { var material = new Material(shader); if (materialPropertySource != null) { material.CopyPropertiesFromMaterial(materialPropertySource); material.shaderKeywords = materialPropertySource.shaderKeywords; } material.mainTexture = t; var page = material.ToSpineAtlasPage(); float width = t.width; float height = t.height; var region = new AtlasRegion(); region.name = t.name; region.index = -1; region.rotate = false; // World space units Vector2 boundsMin = Vector2.zero, boundsMax = new Vector2(width, height) * scale; // Texture space/pixel units region.width = (int)width; region.originalWidth = (int)width; region.height = (int)height; region.originalHeight = (int)height; region.offsetX = width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0)); region.offsetY = height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0)); // Use the full area of the texture. region.u = 0; region.v = 1; region.u2 = 1; region.v2 = 0; region.x = 0; region.y = 0; region.page = page; return region; } /// <summary> /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary> public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { return t.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource); } /// <summary> /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary> public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) { var material = new Material(shader); if (materialPropertySource != null) { material.CopyPropertiesFromMaterial(materialPropertySource); material.shaderKeywords = materialPropertySource.shaderKeywords; } var newTexture = t.GetClone(false, textureFormat, mipmaps); newTexture.ApplyPMA(true); newTexture.name = t.name + "-pma-"; material.name = t.name + shader.name; material.mainTexture = newTexture; var page = material.ToSpineAtlasPage(); var region = newTexture.ToAtlasRegion(shader); region.page = page; return region; } /// <summary> /// Creates a new Spine.AtlasPage from a UnityEngine.Material. If the material has a preassigned texture, the page width and height will be set.</summary> public static AtlasPage ToSpineAtlasPage (this Material m) { var newPage = new AtlasPage { rendererObject = m, name = m.name }; var t = m.mainTexture; if (t != null) { newPage.width = t.width; newPage.height = t.height; } return newPage; } /// <summary> /// Creates a Spine.AtlasRegion from a UnityEngine.Sprite.</summary> public static AtlasRegion ToAtlasRegion (this Sprite s, AtlasPage page) { if (page == null) throw new System.ArgumentNullException("page", "page cannot be null. AtlasPage determines which texture region belongs and how it should be rendered. You can use material.ToSpineAtlasPage() to get a shareable AtlasPage from a Material, or use the sprite.ToAtlasRegion(material) overload."); var region = s.ToAtlasRegion(); region.page = page; return region; } /// <summary> /// Creates a Spine.AtlasRegion from a UnityEngine.Sprite. This creates a new AtlasPage object for every AtlasRegion you create. You can centralize Material control by creating a shared atlas page using Material.ToSpineAtlasPage and using the sprite.ToAtlasRegion(AtlasPage) overload.</summary> public static AtlasRegion ToAtlasRegion (this Sprite s, Material material) { var region = s.ToAtlasRegion(); region.page = material.ToSpineAtlasPage(); return region; } /// <summary> /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary> public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) { var material = new Material(shader); if (materialPropertySource != null) { material.CopyPropertiesFromMaterial(materialPropertySource); material.shaderKeywords = materialPropertySource.shaderKeywords; } var tex = s.ToTexture(false, textureFormat, mipmaps); tex.ApplyPMA(true); tex.name = s.name + "-pma-"; material.name = tex.name + shader.name; material.mainTexture = tex; var page = material.ToSpineAtlasPage(); var region = s.ToAtlasRegion(true); region.page = page; return region; } public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { return s.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource); } internal static AtlasRegion ToAtlasRegion (this Sprite s, bool isolatedTexture = false) { var region = new AtlasRegion(); region.name = s.name; region.index = -1; region.rotate = s.packed && s.packingRotation != SpritePackingRotation.None; // World space units Bounds bounds = s.bounds; Vector2 boundsMin = bounds.min, boundsMax = bounds.max; // Texture space/pixel units Rect spineRect = s.rect.SpineUnityFlipRect(s.texture.height); region.width = (int)spineRect.width; region.originalWidth = (int)spineRect.width; region.height = (int)spineRect.height; region.originalHeight = (int)spineRect.height; region.offsetX = spineRect.width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0)); region.offsetY = spineRect.height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0)); if (isolatedTexture) { region.u = 0; region.v = 1; region.u2 = 1; region.v2 = 0; region.x = 0; region.y = 0; } else { Texture2D tex = s.texture; Rect uvRect = TextureRectToUVRect(s.textureRect, tex.width, tex.height); region.u = uvRect.xMin; region.v = uvRect.yMax; region.u2 = uvRect.xMax; region.v2 = uvRect.yMin; region.x = (int)spineRect.x; region.y = (int)spineRect.y; } return region; } #region Runtime Repacking /// <summary> /// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas comprised of all the regions from the original skin.</summary> /// <remarks>No Spine.Atlas object is created so there is no way to find AtlasRegions except through the Attachments using them.</remarks> public static Skin GetRepackedSkin (this Skin o, string newName, Material materialPropertySource, out Material m, out Texture2D t, int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { return GetRepackedSkin(o, newName, materialPropertySource.shader, out m, out t, maxAtlasSize, padding, textureFormat, mipmaps, materialPropertySource); } /// <summary> /// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas comprised of all the regions from the original skin.</summary> /// <remarks>No Spine.Atlas object is created so there is no way to find AtlasRegions except through the Attachments using them.</remarks> public static Skin GetRepackedSkin (this Skin o, string newName, Shader shader, out Material m, out Texture2D t, int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) { var skinAttachments = o.Attachments; var newSkin = new Skin(newName); // Use these to detect and use shared regions. var existingRegions = new Dictionary<AtlasRegion, int>(); var regionIndexes = new List<int>(); // Collect all textures from the attachments of the original skin. var repackedAttachments = new List<Attachment>(); var texturesToPack = new List<Texture2D>(); var originalRegions = new List<AtlasRegion>(); int newRegionIndex = 0; foreach (var kvp in skinAttachments) { var newAttachment = kvp.Value.GetClone(true); if (IsRenderable(newAttachment)) { var region = newAttachment.GetAtlasRegion(); int existingIndex; if (existingRegions.TryGetValue(region, out existingIndex)) { regionIndexes.Add(existingIndex); // Store the region index for the eventual new attachment. } else { originalRegions.Add(region); texturesToPack.Add(region.ToTexture()); // Add the texture to the PackTextures argument existingRegions.Add(region, newRegionIndex); // Add the region to the dictionary of known regions regionIndexes.Add(newRegionIndex); // Store the region index for the eventual new attachment. newRegionIndex++; } repackedAttachments.Add(newAttachment); } var key = kvp.Key; newSkin.AddAttachment(key.slotIndex, key.name, newAttachment); } // Fill a new texture with the collected attachment textures. var newTexture = new Texture2D(maxAtlasSize, maxAtlasSize, textureFormat, mipmaps); newTexture.anisoLevel = texturesToPack[0].anisoLevel; newTexture.name = newName; var rects = newTexture.PackTextures(texturesToPack.ToArray(), padding, maxAtlasSize); // Rehydrate the repacked textures as a Material, Spine atlas and Spine.AtlasAttachments var newMaterial = new Material(shader); if (materialPropertySource != null) { newMaterial.CopyPropertiesFromMaterial(materialPropertySource); newMaterial.shaderKeywords = materialPropertySource.shaderKeywords; } newMaterial.name = newName; newMaterial.mainTexture = newTexture; var page = newMaterial.ToSpineAtlasPage(); page.name = newName; var repackedRegions = new List<AtlasRegion>(); for (int i = 0, n = originalRegions.Count; i < n; i++) { var oldRegion = originalRegions[i]; var newRegion = UVRectToAtlasRegion(rects[i], oldRegion.name, page, oldRegion.offsetX, oldRegion.offsetY, oldRegion.rotate); repackedRegions.Add(newRegion); } // Map the cloned attachments to the repacked atlas. for (int i = 0, n = repackedAttachments.Count; i < n; i++) { var a = repackedAttachments[i]; a.SetRegion(repackedRegions[regionIndexes[i]]); } // // Clean up // foreach (var ttp in texturesToPack) // UnityEngine.Object.Destroy(ttp); t = newTexture; m = newMaterial; return newSkin; } public static Sprite ToSprite (this AtlasRegion ar, float pixelsPerUnit = 100) { return Sprite.Create(ar.GetMainTexture(), ar.GetUnityRect(), new Vector2(0.5f, 0.5f), pixelsPerUnit); } static Dictionary<AtlasRegion, Texture2D> CachedRegionTextures = new Dictionary<AtlasRegion, Texture2D>(); static List<Texture2D> CachedRegionTexturesList = new List<Texture2D>(); public static void ClearCache () { foreach (var t in CachedRegionTexturesList) { UnityEngine.Object.Destroy(t); } CachedRegionTextures.Clear(); CachedRegionTexturesList.Clear(); } /// <summary>Creates a new Texture2D object based on an AtlasRegion. /// If applyImmediately is true, Texture2D.Apply is called immediately after the Texture2D is filled with data.</summary> public static Texture2D ToTexture (this AtlasRegion ar, bool applyImmediately = true, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { Texture2D output; CachedRegionTextures.TryGetValue(ar, out output); if (output == null) { Texture2D sourceTexture = ar.GetMainTexture(); Rect r = ar.GetUnityRect(sourceTexture.height); int width = (int)r.width; int height = (int)r.height; output = new Texture2D(width, height, textureFormat, mipmaps); output.name = ar.name; Color[] pixelBuffer = sourceTexture.GetPixels((int)r.x, (int)r.y, width, height); output.SetPixels(pixelBuffer); CachedRegionTextures.Add(ar, output); CachedRegionTexturesList.Add(output); if (applyImmediately) output.Apply(); } return output; } static Texture2D ToTexture (this Sprite s, bool applyImmediately = true, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { var spriteTexture = s.texture; var r = s.textureRect; var spritePixels = spriteTexture.GetPixels((int)r.x, (int)r.y, (int)r.width, (int)r.height); var newTexture = new Texture2D((int)r.width, (int)r.height, textureFormat, mipmaps); newTexture.SetPixels(spritePixels); if (applyImmediately) newTexture.Apply(); return newTexture; } static Texture2D GetClone (this Texture2D t, bool applyImmediately = true, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { var spritePixels = t.GetPixels(0, 0, (int)t.width, (int)t.height); var newTexture = new Texture2D((int)t.width, (int)t.height, textureFormat, mipmaps); newTexture.SetPixels(spritePixels); if (applyImmediately) newTexture.Apply(); return newTexture; } static bool IsRenderable (Attachment a) { return a is RegionAttachment || a is MeshAttachment; } /// <summary> /// Get a rect with flipped Y so that a Spine atlas rect gets converted to a Unity Sprite rect and vice versa.</summary> static Rect SpineUnityFlipRect (this Rect rect, int textureHeight) { rect.y = textureHeight - rect.y - rect.height; return rect; } /// <summary> /// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up). /// This overload relies on region.page.height being correctly set.</summary> static Rect GetUnityRect (this AtlasRegion region) { return region.GetSpineAtlasRect().SpineUnityFlipRect(region.page.height); } /// <summary> /// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up).</summary> static Rect GetUnityRect (this AtlasRegion region, int textureHeight) { return region.GetSpineAtlasRect().SpineUnityFlipRect(textureHeight); } /// <summary> /// Returns a Rect of the AtlasRegion according to Spine texture coordinates. (x-right, y-down)</summary> static Rect GetSpineAtlasRect (this AtlasRegion region, bool includeRotate = true) { if (includeRotate && region.rotate) return new Rect(region.x, region.y, region.height, region.width); else return new Rect(region.x, region.y, region.width, region.height); } /// <summary> /// Denormalize a uvRect into a texture-space Rect.</summary> static Rect UVRectToTextureRect (Rect uvRect, int texWidth, int texHeight) { uvRect.x *= texWidth; uvRect.width *= texWidth; uvRect.y *= texHeight; uvRect.height *= texHeight; return uvRect; } /// <summary> /// Normalize a texture Rect into UV coordinates.</summary> static Rect TextureRectToUVRect (Rect textureRect, int texWidth, int texHeight) { textureRect.x = Mathf.InverseLerp(0, texWidth, textureRect.x); textureRect.y = Mathf.InverseLerp(0, texHeight, textureRect.y); textureRect.width = Mathf.InverseLerp(0, texWidth, textureRect.width); textureRect.height = Mathf.InverseLerp(0, texHeight, textureRect.height); return textureRect; } /// <summary> /// Creates a new Spine AtlasRegion according to a Unity UV Rect (x-right, y-up, uv-normalized).</summary> static AtlasRegion UVRectToAtlasRegion (Rect uvRect, string name, AtlasPage page, float offsetX, float offsetY, bool rotate) { var tr = UVRectToTextureRect(uvRect, page.width, page.height); var rr = tr.SpineUnityFlipRect(page.height); int x = (int)rr.x, y = (int)rr.y; int w, h; if (rotate) { w = (int)rr.height; h = (int)rr.width; } else { w = (int)rr.width; h = (int)rr.height; } return new AtlasRegion { page = page, name = name, u = uvRect.xMin, u2 = uvRect.xMax, v = uvRect.yMax, v2 = uvRect.yMin, index = -1, width = w, originalWidth = w, height = h, originalHeight = h, offsetX = offsetX, offsetY = offsetY, x = x, y = y, rotate = rotate }; } /// <summary> /// Tries to get the backing AtlasRegion of an attachment if it is renderable. Returns null for non-renderable attachments.</summary> static AtlasRegion GetAtlasRegion (this Attachment a) { var regionAttachment = a as RegionAttachment; if (regionAttachment != null) return (regionAttachment.RendererObject) as AtlasRegion; var meshAttachment = a as MeshAttachment; if (meshAttachment != null) return (meshAttachment.RendererObject) as AtlasRegion; return null; } /// <summary> /// Convenience method for getting the main texture of the material of the page of the region.</summary> static Texture2D GetMainTexture (this AtlasRegion region) { var material = (region.page.rendererObject as Material); return material.mainTexture as Texture2D; } static void ApplyPMA (this Texture2D texture, bool applyImmediately = true) { var pixels = texture.GetPixels(); for (int i = 0, n = pixels.Length; i < n; i++) { Color p = pixels[i]; float a = p.a; p.r = p.r * a; p.g = p.g * a; p.b = p.b * a; pixels[i] = p; } texture.SetPixels(pixels); if (applyImmediately) texture.Apply(); } #endregion static float InverseLerp (float a, float b, float value) { return (value - a) / (b - a); } } public static class SkinExtensions { #region Skeleton Skin Extensions /// <summary> /// Convenience method for duplicating a skeleton's current active skin so changes to it will not affect other skeleton instances. .</summary> public static Skin UnshareSkin (this Skeleton skeleton, bool includeDefaultSkin, bool unshareAttachments, AnimationState state = null) { // 1. Copy the current skin and set the skeleton's skin to the new one. var newSkin = skeleton.GetClonedSkin("cloned skin", includeDefaultSkin, unshareAttachments, true); skeleton.SetSkin(newSkin); // 2. Apply correct attachments: skeleton.SetToSetupPose + animationState.Apply if (state != null) { skeleton.SetToSetupPose(); state.Apply(skeleton); } // 3. Return unshared skin. return newSkin; } public static Skin GetClonedSkin (this Skeleton skeleton, string newSkinName, bool includeDefaultSkin = false, bool cloneAttachments = false, bool cloneMeshesAsLinked = true) { var newSkin = new Skin(newSkinName); // may have null name. Harmless. var defaultSkin = skeleton.data.DefaultSkin; var activeSkin = skeleton.skin; if (includeDefaultSkin) defaultSkin.CopyTo(newSkin, true, cloneAttachments, cloneMeshesAsLinked); if (activeSkin != null) activeSkin.CopyTo(newSkin, true, cloneAttachments, cloneMeshesAsLinked); return newSkin; } #endregion /// <summary> /// Gets a shallow copy of the skin. The cloned skin's attachments are shared with the original skin.</summary> public static Skin GetClone (this Skin original) { var newSkin = new Skin(original.name + " clone"); var newSkinAttachments = newSkin.Attachments; foreach (var a in original.Attachments) newSkinAttachments[a.Key] = a.Value; return newSkin; } /// <summary>Adds an attachment to the skin for the specified slot index and name. If the name already exists for the slot, the previous value is replaced.</summary> public static void SetAttachment (this Skin skin, string slotName, string keyName, Attachment attachment, Skeleton skeleton) { int slotIndex = skeleton.FindSlotIndex(slotName); if (skeleton == null) throw new System.ArgumentNullException("skeleton", "skeleton cannot be null."); if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName"); skin.AddAttachment(slotIndex, keyName, attachment); } /// <summary>Gets an attachment from the skin for the specified slot index and name.</summary> public static Attachment GetAttachment (this Skin skin, string slotName, string keyName, Skeleton skeleton) { int slotIndex = skeleton.FindSlotIndex(slotName); if (skeleton == null) throw new System.ArgumentNullException("skeleton", "skeleton cannot be null."); if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName"); return skin.GetAttachment(slotIndex, keyName); } /// <summary>Adds an attachment to the skin for the specified slot index and name. If the name already exists for the slot, the previous value is replaced.</summary> public static void SetAttachment (this Skin skin, int slotIndex, string keyName, Attachment attachment) { skin.AddAttachment(slotIndex, keyName, attachment); } /// <summary>Removes the attachment. Returns true if the element is successfully found and removed; otherwise, false.</summary> public static bool RemoveAttachment (this Skin skin, string slotName, string keyName, Skeleton skeleton) { int slotIndex = skeleton.FindSlotIndex(slotName); if (skeleton == null) throw new System.ArgumentNullException("skeleton", "skeleton cannot be null."); if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName"); return skin.RemoveAttachment(slotIndex, keyName); } /// <summary>Removes the attachment. Returns true if the element is successfully found and removed; otherwise, false.</summary> public static bool RemoveAttachment (this Skin skin, int slotIndex, string keyName) { return skin.Attachments.Remove(new Skin.AttachmentKeyTuple(slotIndex, keyName)); } public static void Clear (this Skin skin) { skin.Attachments.Clear(); } public static void Append (this Skin destination, Skin source) { source.CopyTo(destination, true, false); } public static void CopyTo (this Skin source, Skin destination, bool overwrite, bool cloneAttachments, bool cloneMeshesAsLinked = true) { var sourceAttachments = source.Attachments; var destinationAttachments = destination.Attachments; if (cloneAttachments) { if (overwrite) { foreach (var e in sourceAttachments) destinationAttachments[e.Key] = e.Value.GetClone(cloneMeshesAsLinked); } else { foreach (var e in sourceAttachments) { if (destinationAttachments.ContainsKey(e.Key)) continue; destinationAttachments.Add(e.Key, e.Value.GetClone(cloneMeshesAsLinked)); } } } else { if (overwrite) { foreach (var e in sourceAttachments) destinationAttachments[e.Key] = e.Value; } else { foreach (var e in sourceAttachments) { if (destinationAttachments.ContainsKey(e.Key)) continue; destinationAttachments.Add(e.Key, e.Value); } } } } } public static class AttachmentCloneExtensions { /// <summary> /// Clones the attachment.</summary> public static Attachment GetClone (this Attachment o, bool cloneMeshesAsLinked) { var regionAttachment = o as RegionAttachment; if (regionAttachment != null) return regionAttachment.GetClone(); var meshAttachment = o as MeshAttachment; if (meshAttachment != null) return cloneMeshesAsLinked ? meshAttachment.GetLinkedClone() : meshAttachment.GetClone(); var boundingBoxAttachment = o as BoundingBoxAttachment; if (boundingBoxAttachment != null) return boundingBoxAttachment.GetClone(); var pathAttachment = o as PathAttachment; if (pathAttachment != null) return pathAttachment.GetClone(); var pointAttachment = o as PointAttachment; if (pointAttachment != null) return pointAttachment.GetClone(); var clippingAttachment = o as ClippingAttachment; if (clippingAttachment != null) return clippingAttachment.GetClone(); return null; } public static RegionAttachment GetClone (this RegionAttachment o) { return new RegionAttachment(o.Name + "clone") { x = o.x, y = o.y, rotation = o.rotation, scaleX = o.scaleX, scaleY = o.scaleY, width = o.width, height = o.height, r = o.r, g = o.g, b = o.b, a = o.a, Path = o.Path, RendererObject = o.RendererObject, regionOffsetX = o.regionOffsetX, regionOffsetY = o.regionOffsetY, regionWidth = o.regionWidth, regionHeight = o.regionHeight, regionOriginalWidth = o.regionOriginalWidth, regionOriginalHeight = o.regionOriginalHeight, uvs = o.uvs.Clone() as float[], offset = o.offset.Clone() as float[] }; } public static ClippingAttachment GetClone (this ClippingAttachment o) { var ca = new ClippingAttachment(o.Name) { endSlot = o.endSlot }; CloneVertexAttachment(o, ca); return ca; } public static PointAttachment GetClone (this PointAttachment o) { var pa = new PointAttachment(o.Name) { rotation = o.rotation, x = o.x, y = o.y }; return pa; } public static BoundingBoxAttachment GetClone (this BoundingBoxAttachment o) { var ba = new BoundingBoxAttachment(o.Name); CloneVertexAttachment(o, ba); return ba; } public static MeshAttachment GetLinkedClone (this MeshAttachment o, bool inheritDeform = true) { return o.GetLinkedMesh(o.Name, o.RendererObject as AtlasRegion, inheritDeform); } /// <summary> /// Returns a clone of the MeshAttachment. This will cause Deform animations to stop working unless you explicity set the .parentMesh to the original.</summary> public static MeshAttachment GetClone (this MeshAttachment o) { var ma = new MeshAttachment(o.Name) { r = o.r, g = o.g, b = o.b, a = o.a, inheritDeform = o.inheritDeform, Path = o.Path, RendererObject = o.RendererObject, regionOffsetX = o.regionOffsetX, regionOffsetY = o.regionOffsetY, regionWidth = o.regionWidth, regionHeight = o.regionHeight, regionOriginalWidth = o.regionOriginalWidth, regionOriginalHeight = o.regionOriginalHeight, RegionU = o.RegionU, RegionV = o.RegionV, RegionU2 = o.RegionU2, RegionV2 = o.RegionV2, RegionRotate = o.RegionRotate, uvs = o.uvs.Clone() as float[] }; // Linked mesh if (o.ParentMesh != null) { // bones, vertices, worldVerticesLength, regionUVs, triangles, HullLength, Edges, Width, Height ma.ParentMesh = o.ParentMesh; } else { CloneVertexAttachment(o, ma); // bones, vertices, worldVerticesLength ma.regionUVs = o.regionUVs.Clone() as float[]; ma.triangles = o.triangles.Clone() as int[]; ma.hulllength = o.hulllength; // Nonessential. ma.Edges = (o.Edges == null) ? null : o.Edges.Clone() as int[]; // Allow absence of Edges array when nonessential data is not exported. ma.Width = o.Width; ma.Height = o.Height; } return ma; } public static PathAttachment GetClone (this PathAttachment o) { var newPathAttachment = new PathAttachment(o.Name) { lengths = o.lengths.Clone() as float[], closed = o.closed, constantSpeed = o.constantSpeed }; CloneVertexAttachment(o, newPathAttachment); return newPathAttachment; } static void CloneVertexAttachment (VertexAttachment src, VertexAttachment dest) { dest.worldVerticesLength = src.worldVerticesLength; if (src.bones != null) dest.bones = src.bones.Clone() as int[]; if (src.vertices != null) dest.vertices = src.vertices.Clone() as float[]; } #region Runtime Linked MeshAttachments /// <summary> /// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to the AtlasRegion provided.</summary> public static MeshAttachment GetLinkedMesh (this MeshAttachment o, string newLinkedMeshName, AtlasRegion region, bool inheritDeform = true) { //if (string.IsNullOrEmpty(attachmentName)) throw new System.ArgumentException("attachmentName cannot be null or empty", "attachmentName"); if (region == null) throw new System.ArgumentNullException("region"); // If parentMesh is a linked mesh, create a link to its parent. Preserves Deform animations. if (o.ParentMesh != null) o = o.ParentMesh; // 1. NewMeshAttachment (AtlasAttachmentLoader.cs) var mesh = new MeshAttachment(newLinkedMeshName); mesh.SetRegion(region, false); // 2. (SkeletonJson.cs::ReadAttachment. case: LinkedMesh) mesh.Path = newLinkedMeshName; mesh.r = 1f; mesh.g = 1f; mesh.b = 1f; mesh.a = 1f; //mesh.ParentMesh property call below sets mesh.Width and mesh.Height // 3. Link mesh with parent. (SkeletonJson.cs) mesh.inheritDeform = inheritDeform; mesh.ParentMesh = o; mesh.UpdateUVs(); return mesh; } /// <summary> /// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to an AtlasRegion generated from a Sprite. The AtlasRegion will be mapped to a new Material based on the shader. /// For better caching and batching, use GetLinkedMesh(string, AtlasRegion, bool)</summary> public static MeshAttachment GetLinkedMesh (this MeshAttachment o, Sprite sprite, Shader shader, bool inheritDeform = true, Material materialPropertySource = null) { var m = new Material(shader); if (materialPropertySource != null) { m.CopyPropertiesFromMaterial(materialPropertySource); m.shaderKeywords = materialPropertySource.shaderKeywords; } return o.GetLinkedMesh(sprite.name, sprite.ToAtlasRegion(), inheritDeform); } /// <summary> /// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to an AtlasRegion generated from a Sprite. The AtlasRegion will be mapped to a new Material based on the shader. /// For better caching and batching, use GetLinkedMesh(string, AtlasRegion, bool)</summary> public static MeshAttachment GetLinkedMesh (this MeshAttachment o, Sprite sprite, Material materialPropertySource, bool inheritDeform = true) { return o.GetLinkedMesh(sprite, materialPropertySource.shader, inheritDeform, materialPropertySource); } #endregion #region RemappedClone Convenience Methods /// <summary> /// Gets a clone of the attachment remapped with a sprite image.</summary> /// <returns>The remapped clone.</returns> /// <param name="o">The original attachment.</param> /// <param name="sprite">The sprite whose texture to use.</param> /// <param name="sourceMaterial">The source material used to copy the shader and material properties from.</param> /// <param name="premultiplyAlpha">If <c>true</c>, a premultiply alpha clone of the original texture will be created.</param> /// <param name="cloneMeshAsLinked">If <c>true</c> MeshAttachments will be cloned as linked meshes and will inherit animation from the original attachment.</param> /// <param name="useOriginalRegionSize">If <c>true</c> the size of the original attachment will be followed, instead of using the Sprite size.</param> public static Attachment GetRemappedClone (this Attachment o, Sprite sprite, Material sourceMaterial, bool premultiplyAlpha = true, bool cloneMeshAsLinked = true, bool useOriginalRegionSize = false) { var atlasRegion = premultiplyAlpha ? sprite.ToAtlasRegionPMAClone(sourceMaterial) : sprite.ToAtlasRegion(false); return o.GetRemappedClone(atlasRegion, cloneMeshAsLinked, useOriginalRegionSize, 1f/sprite.pixelsPerUnit); } /// <summary> /// Gets a clone of the attachment remapped with an atlasRegion image.</summary> /// <returns>The remapped clone.</returns> /// <param name="o">The original attachment.</param> /// <param name="atlasRegion">Atlas region.</param> /// <param name="cloneMeshAsLinked">If <c>true</c> MeshAttachments will be cloned as linked meshes and will inherit animation from the original attachment.</param> /// <param name="useOriginalRegionSize">If <c>true</c> the size of the original attachment will be followed, instead of using the Sprite size.</param> /// <param name="scale">Unity units per pixel scale used to scale the atlas region size when not using the original region size.</param> public static Attachment GetRemappedClone (this Attachment o, AtlasRegion atlasRegion, bool cloneMeshAsLinked = true, bool useOriginalRegionSize = false, float scale = 0.01f) { var regionAttachment = o as RegionAttachment; if (regionAttachment != null) { RegionAttachment newAttachment = regionAttachment.GetClone(); newAttachment.SetRegion(atlasRegion, false); if (!useOriginalRegionSize) { newAttachment.width = atlasRegion.width * scale; newAttachment.height = atlasRegion.height * scale; } newAttachment.UpdateOffset(); return newAttachment; } else { var meshAttachment = o as MeshAttachment; if (meshAttachment != null) { MeshAttachment newAttachment = cloneMeshAsLinked ? meshAttachment.GetLinkedClone(cloneMeshAsLinked) : meshAttachment.GetClone(); newAttachment.SetRegion(atlasRegion); return newAttachment; } } return o.GetClone(true); // Non-renderable Attachments will return as normal cloned attachments. } #endregion } }
using System; using System.Collections.ObjectModel; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Content; using FlatRedBall.Math; using FlatRedBall.Graphics; using System.Diagnostics; using FlatRedBall.Math.Geometry; namespace FlatRedBall { public partial class Camera : PositionedObject { #region Fields /// <summary> /// A Vector3 representing the "Up" orientation. The camera will adjust its rotation so that this vector /// is up. This enables 3D games (such as first person shooters) to rotate the camera yet still have a natural-feeling /// up vector. /// </summary> public Vector3 UpVector = new Vector3(0, 1, 0); static int sCreatedCount = 0; float mFarClipPlane; float mNearClipPlane; Matrix mView; Matrix mViewRelative; Matrix mProjection; Matrix mViewProjection; float mMinimumX; float mMinimumY; float mMaximumX; float mMaximumY; float mBaseZ; float mBaseMinimumX; float mBaseMinimumY; float mBaseMaximumX; float mBaseMaximumY; bool mOrthogonal; float mOrthogonalWidth; float mOrthogonalHeight; #if SUPPORTS_POST_PROCESSING ShadowMap mShadow = null; internal PostProcessingEffectCollection mPostProcessing; #region XML Docs /// <summary> /// Defines the rendering order for this camera /// </summary> #endregion public List<RenderMode> RenderOrder; #region XML Docs /// <summary> /// List of rendered textures (during render pass) /// </summary> #endregion internal Dictionary<int, RenderTargetTexture> mRenderTargetTextures; #region XML Docs /// <summary> /// The final render for this camera (after post-processing) /// </summary> #endregion internal RenderTargetTexture mRenderTargetTexture; #region XML Docs /// <summary> /// Whether or not this camera should be drawn to the screen /// </summary> #endregion public bool DrawToScreen = true; bool mClearsTargetDefaultRenderMode = true; #endif BoundingFrustum mBoundingFrustum; CameraCullMode mCameraCullMode; CameraModelCullMode mCameraModelCullMode; #region Viewport settings //internal int mTargetWidth; //internal int mTargetHeight; public Color BackgroundColor = new Color(0,0,0,0); SplitScreenViewport splitScreenViewport; public SplitScreenViewport CurrentSplitScreenViewport => splitScreenViewport; bool mUsesSplitScreenViewport = false; #endregion List<Layer> mLayers = new List<Layer>(); ReadOnlyCollection<Layer> mLayersReadOnly; //internal SpriteList mSpritesToBillBoard = new SpriteList(); string mContentManager; #region XML Docs /// <summary> /// Whether or not lighting is enabled for this camera /// </summary> #endregion internal bool mLightingEnabled = false; #endregion #region Properties /// <summary> /// Sets whether the Camera will prevent viewports from being larger than the resolution. This value defaults to true. /// </summary> /// <remarks> /// The purpose of this value is to prevent cameras from attempting to draw outside of the window's client bounds. A camera /// which has a viewport larger than the window client bounds will throw an exception. However, cameras (and layers) which render /// to a render target which is larger than the current window should be able to render to the full render target even if it is larger /// than the current window. Therefore, this value should be set to false if rendering to large render targets. /// </remarks> public bool ShouldRestrictViewportToResolution { get; set; } public Matrix View { get { return mView; }// GetLookAtMatrix(false); } } public Matrix Projection { get { return mProjection; }// GetProjectionMatrix(); } } public BoundingFrustum BoundingFrustum { get { return mBoundingFrustum; } } public CameraCullMode CameraCullMode { get { return mCameraCullMode; } set { mCameraCullMode = value; } } public CameraModelCullMode CameraModelCullMode { get { return mCameraModelCullMode; } set { mCameraModelCullMode = value; } } /// <summary> /// The Y field of view of the camera in radians. Field of view represents the /// Y angle from the bottom of the screen to the top. /// </summary> /// <remarks> /// This modifies the xEdge and yEdge properties. Default value is (float)Math.PI / 4.0f; /// </remarks> public virtual float FieldOfView { get { return mFieldOfView; } set { #if DEBUG if (value >= (float)System.Math.PI) { throw new ArgumentException("FieldOfView must be smaller than PI."); } if (value <= 0) { throw new ArgumentException("FieldOfView must be greater than 0."); } #endif mFieldOfView = value; mYEdge = (float)(100 * System.Math.Tan(mFieldOfView / 2.0)); mXEdge = mYEdge * mAspectRatio; #if !SILVERLIGHT UpdateViewProjectionMatrix(); #endif } } #region XML Docs /// <summary> /// A Camera-specific layer. Objects on this layer will not appear /// in any other cameras. /// </summary> /// <remarks> /// This instance is automatically created when the Camera is instantiated. /// </remarks> #endregion public Layer Layer { get { return mLayers[0]; } } public ReadOnlyCollection<Layer> Layers { get { return mLayersReadOnly; } } /// <summary> /// The Minimum camera X (center). This is applied prior to rendering and will override attachment. /// </summary> public float MinimumX { get { return mMinimumX; } set { mMinimumX = value; } } /// <summary> /// The Minimum camera Y (center). This is applied prior to rendering and will override attachment. /// </summary> public float MinimumY { get { return mMinimumY; } set { mMinimumY = value; } } /// <summary> /// The maximum Camera X (center). This is applied prior to rendering and will override attachment. /// </summary> public float MaximumX { get { return mMaximumX; } set { mMaximumX = value; } } /// <summary> /// The maximum Camera Y (center). This is applied prior to rendering and will override attachment. /// </summary> public float MaximumY { get { return mMaximumY; } set { mMaximumY = value; } } public float NearClipPlane { get { return mNearClipPlane; } set { mNearClipPlane = value; } } public float FarClipPlane { get { return mFarClipPlane; } set { mFarClipPlane = value; } } public float XEdge { get { return mXEdge; } } public float YEdge { get { return mYEdge; } } public float TopDestinationVelocity { get { return mTopDestinationVelocity; } set { mTopDestinationVelocity = value; } } public float BottomDestinationVelocity { get { return mBottomDestinationVelocity; } set { mBottomDestinationVelocity = value; } } public float LeftDestinationVelocity { get { return mLeftDestinationVelocity; } set { mLeftDestinationVelocity = value; } } public float RightDestinationVelocity { get { return mRightDestinationVelocity; } set { mRightDestinationVelocity = value; } } /// <summary> /// The number of horizontal units shown by the camera when the camera has Orthogonal = true /// </summary> /// <remarks> /// Orthogonal values will not have any impact on rendering if Orthogonal is false. /// </remarks> public float OrthogonalWidth { get { return mOrthogonalWidth; } set { #if DEBUG if (value < 0) { throw new Exception("OrthogonalWidth must be positive"); } #endif mOrthogonalWidth = value; } } /// <summary> /// The number of vertical units shown by the camera when the camera has Orthogonal = true /// </summary> /// <remarks> /// Orthogonal values will not have any impact on rendering if Orthogonal is false. /// </remarks> public float OrthogonalHeight { get { return mOrthogonalHeight; } set { #if DEBUG if (value < 0) { throw new Exception("OrthogonalHeight must be positive"); } #endif mOrthogonalHeight = value; } } #endregion public bool ShiftsHalfUnitForRendering { get { // This causes all kinds of jitteryness when attached to an object, so we should make sure // the camera is not attached to anything: return Parent == null && mOrthogonal && (this.mOrthogonalWidth / (float)this.DestinationRectangle.Width == 1); } } #region Constructor /// <summary> /// Creates a new camera instance. This camera will not be drawn by the engine until it is added /// through the SpriteManager. /// </summary> public Camera () : this(null) { } public Camera(string contentManagerName) : this( contentManagerName, FlatRedBallServices.ClientWidth, FlatRedBallServices.ClientHeight) { SetSplitScreenViewport(SplitScreenViewport.FullScreen); ShouldRestrictViewportToResolution = true; } public Camera(string contentManagerName, int width, int height) : base() { ShouldRestrictViewportToResolution = true; ClearsDepthBuffer = true; mContentManager = contentManagerName; DrawsToScreen = true; ClearMinimumsAndMaximums(); // set the borders to float.NaN so they are not applied. ClearBorders(); mNearClipPlane = 1; mFarClipPlane = 1000; mOrthogonal = false; mOrthogonalWidth = width; mOrthogonalHeight = height; mAspectRatio = width / (float)height; // Be sure to instantiate the frustum before setting the FieldOfView // since setting the FieldOfView sets the frustum: mBoundingFrustum = new BoundingFrustum(Matrix.Identity); // use the Property rather than base value so that the mXEdge and mYEdge are set FieldOfView = (float)System.Math.PI / 4.0f; // Set up the default viewport DestinationRectangle = new Rectangle( 0, 0, width, height); mCameraCullMode = CameraCullMode.UnrotatedDownZ; Layer layer = new Layer(); layer.mCameraBelongingTo = this; layer.Name = "Camera Layer"; mLayers.Add(layer); mLayersReadOnly = new ReadOnlyCollection<Layer>(mLayers); Position.Z = -MathFunctions.ForwardVector3.Z * 40; #if SUPPORTS_POST_PROCESSING mPostProcessing = new PostProcessingEffectCollection(); if (Renderer.UseRenderTargets) { mPostProcessing.InitializeEffects(); } // Create the render order collection RenderOrder = new List<RenderMode>(); RenderOrder.Add(RenderMode.Default); RefreshTexture(); #endif } #endregion #region Public Methods public Layer AddLayer() { Layer layer = new Layer(); mLayers.Add(layer); layer.mCameraBelongingTo = this; return layer; } #region XML Docs /// <summary> /// Adds a layer to the Camera. This method does not remove layers that already /// exist in the SpriteManager. /// </summary> /// <param name="layerToAdd">The layer to add.</param> #endregion public void AddLayer(Layer layerToAdd) { if (layerToAdd.mCameraBelongingTo != null) { throw new System.InvalidOperationException("The argument layer already belongs to a Camera."); } else { // The layer doesn't belong to a camera so it can be added here. mLayers.Add(layerToAdd); layerToAdd.mCameraBelongingTo = this; } } public void MoveToBack(Layer layer) { mLayers.Remove(layer); mLayers.Insert(0, layer); } public void MoveToFront(Layer layer) { // Last layers appear on top (front) mLayers.Remove(layer); mLayers.Add(layer); } #region XmlDocs /// <summary> /// Supplied sprites are billboarded using the camera's RotationMatrix. /// Only the main Camera can billboard sprites. /// </summary> #endregion public void AddSpriteToBillboard(Sprite sprite) { // This only works on the main camera. Multi-camera games must implement their // own solutions: #if DEBUG if(this != Camera.Main) { throw new InvalidOperationException("Sprites can only be billboarded on the main camera"); } #endif //this.mSpritesToBillBoard.Add(sprite); sprite.IsBillboarded = true; } #region XML Docs /// <summary> /// Removes all visibility borders. /// <seealso cref="FlatRedBall.Camera.SetBordersAtZ"/> /// </summary> #endregion public void ClearBorders() { mBaseZ = float.NaN; mBaseMinimumX = float.NaN; mBaseMinimumY = float.NaN; mBaseMaximumX = float.NaN; mBaseMaximumY = float.NaN; } public void ClearMinimumsAndMaximums() { mMinimumX = float.NegativeInfinity; mMinimumY = float.NegativeInfinity; mMaximumX = float.PositiveInfinity; mMaximumY = float.PositiveInfinity; } public void FixDestinationRectangleHeightConstant() { mDestinationRectangle.Width = (int)(mAspectRatio * mDestinationRectangle.Height); } public void FixDestinationRectangleWidthConstant() { mDestinationRectangle.Height = (int)(mDestinationRectangle.Width / mAspectRatio); } public override void ForceUpdateDependencies() { base.ForceUpdateDependencies(); // This will be done both in TimedUpdate as well as here X = System.Math.Min(X, mMaximumX); X = System.Math.Max(X, mMinimumX); Y = System.Math.Min(Y, mMaximumY); Y = System.Math.Max(Y, mMinimumY); if (!double.IsNaN(this.mBaseMaximumX)) { CalculateMaxAndMins(); } // This should happen AFTER mins and maxes are set UpdateViewProjectionMatrix(true); } public Matrix GetLookAtMatrix() { return GetLookAtMatrix(false); } public Matrix GetLookAtMatrix(bool relativeToCamera) { Vector3 positionVector; if (relativeToCamera) { positionVector = new Vector3(0, 0, 0); return Matrix.CreateLookAt(Vector3.Zero, -Vector3.UnitZ, Vector3.UnitY); } else { positionVector = Position; Vector3 cameraTarget = positionVector + mRotationMatrix.Forward; // FRB has historically had a lot of // jagged edges and rendering issues which // I think are caused by floating point inaccuracies. // Unfortunately these tend to happen most when objects // are positioned at whole numbers, which is very common. // Going to shift the camera by .5 units if the Camera is viewing // in 2D mode to try to reduce this if (ShiftsHalfUnitForRendering) { // This doesn't seem to fix // problems when the camera can // smooth scroll. I'm going to move // the camera to multiples of 5. //positionVector.X += .5f; //positionVector.Y -= .5f; //cameraTarget.X += .5f; //cameraTarget.Y -= .5f; // This also causes rendering issues, I think I'm going to do it in update dependencies //positionVector.X = (int)positionVector.X + .5f; //positionVector.Y = (int)positionVector.Y - .5f; //cameraTarget.X = (int)cameraTarget.X + .5f; //cameraTarget.Y = (int)cameraTarget.Y - .5f; // Math this is complicated. Without this // stuff that is attached to the Camera tends // to not be rendered properly :( So putting it back in positionVector.X += .5f; positionVector.Y -= .5f; cameraTarget.X += .5f; cameraTarget.Y -= .5f; } Matrix returnMatrix; Matrix.CreateLookAt( ref positionVector, // Position of the camera eye ref cameraTarget, // Point that the eye is looking at ref UpVector, out returnMatrix); return returnMatrix; } } public Matrix GetProjectionMatrix() { if (mOrthogonal == false) { //return Matrix.CreatePerspectiveFieldOfView( // mFieldOfView * 1.066667f, // mAspectRatio, // mNearClipPlane, // mFarClipPlane); return Matrix.CreatePerspectiveFieldOfView( mFieldOfView, mAspectRatio, mNearClipPlane, mFarClipPlane); } else { return Matrix.CreateOrthographic( mOrthogonalWidth, mOrthogonalHeight, mNearClipPlane, mFarClipPlane); } } public float GetRequiredAspectRatio(float desiredYEdge, float zValue) { float modifiedDesiredYEdge = 100 * desiredYEdge / (Position.Z - zValue); return (float)System.Math.Atan(modifiedDesiredYEdge / 100) * 2; } public Viewport GetViewport() { // Viewport is a struct, so we can start with the current viewport Viewport viewport = Renderer.GraphicsDevice.Viewport; viewport.X = DestinationRectangle.X; viewport.Y = DestinationRectangle.Y; viewport.Width = DestinationRectangle.Width; viewport.Height = DestinationRectangle.Height; if (ShouldRestrictViewportToResolution) { RestrictViewportToResolution(ref viewport); } return viewport; } public static void RestrictViewportToResolution(ref Viewport viewport) { // Renders can happen before the graphics device is reset // If so, we want to make sure we aren't rendering outside of the bounds: int maxWidthAllowed = Renderer.GraphicsDevice.PresentationParameters.BackBufferWidth - viewport.X; int maxHeightAllowed = Renderer.GraphicsDevice.PresentationParameters.BackBufferHeight - viewport.Y; viewport.Width = System.Math.Min(viewport.Width, maxWidthAllowed); viewport.Height = System.Math.Min(viewport.Height, maxHeightAllowed); } public Viewport GetViewport(LayerCameraSettings lcs, RenderTarget2D renderTarget = null) { Viewport viewport = Renderer.GraphicsDevice.Viewport; bool explicitlySetsDestination = lcs != null && lcs.TopDestination >= 0 && lcs.BottomDestination >= 0 && lcs.LeftDestination >= 0 && lcs.RightDestination >= 0; if(explicitlySetsDestination) { viewport.X = (int)lcs.LeftDestination; viewport.Y = (int)lcs.TopDestination; viewport.Width = (int)(lcs.RightDestination - lcs.LeftDestination); viewport.Height = (int)(lcs.BottomDestination - lcs.TopDestination); } else { // borrow the size from whatever it's tied to, which could be a camera or a render target if(renderTarget != null) { viewport.X = 0; viewport.Y = 0; viewport.Width = renderTarget.Width; viewport.Height = renderTarget.Height; } else { viewport.X = DestinationRectangle.X; viewport.Y = DestinationRectangle.Y; viewport.Width = DestinationRectangle.Width; viewport.Height = DestinationRectangle.Height; } } // Debug should *NEVER* be more tolerant of bad settings: //#if DEBUG if (ShouldRestrictViewportToResolution) { int destinationWidth; int destinationHeight; if(renderTarget == null) { destinationWidth = FlatRedBallServices.GraphicsOptions.ResolutionWidth; destinationHeight = FlatRedBallServices.GraphicsOptions.ResolutionHeight; } else { destinationWidth = renderTarget.Width; destinationHeight = renderTarget.Height; } // September 24, 2012 // There is currently a // bug if the user starts // on a Screen with a 2D layer // in portrait mode. The game tells // Windows 8 that it wants to be in portrait // mode. When it does so, the game flips, but // it takes a second. FRB may still render during // that time and this code gets called. The resolutions // don't match up and we have issues. Not sure how to fix // this (yet). // Update August 25, 2013 // This code can throw an exception when resizing a window. // But the user didn't do anything wrong - the engine just hasn't // gotten a chance to reset the device yet. So we'll tolerate it: if (viewport.Y + viewport.Height > destinationHeight) { //throw new Exception("The pixel height resolution of the display is " + // FlatRedBallServices.GraphicsOptions.ResolutionHeight + // " but the LayerCameraSettings' BottomDestination is " + (viewport.Y + viewport.Height)); int amountToSubtract = (viewport.Y + viewport.Height) - destinationHeight; viewport.Height -= amountToSubtract; } if (viewport.X + viewport.Width > destinationWidth) { //throw new Exception("The pixel width resolution of the display is " + // FlatRedBallServices.GraphicsOptions.ResolutionWidth + // " but the LayerCameraSettings' RightDestination is " + (viewport.X + viewport.Width)); int amountToSubtract = (viewport.X + viewport.Width) - destinationWidth; viewport.Width -= amountToSubtract; } //#endif } return viewport; } #region Is object in view #endregion #region XML Docs /// <summary> /// Moves a Sprite so that it remains fully in the camera's view. /// </summary> /// <remarks> /// This method does not consider Sprite rotation, negative scale, or situations /// when the camera is not looking down the Z axis. /// </remarks> /// <param name="sprite">The Sprite to keep in view.</param> #endregion public void KeepSpriteInScreen(Sprite sprite) { // If the Sprite has a parent, then we need to force update so that its // position is what it will be when it's drawn. Be sure to do this before // storing off the oldPosition if (sprite.Parent != null) { sprite.ForceUpdateDependencies(); } Vector3 oldPosition = sprite.Position; float edgeCoef = (Z - sprite.Z) / 100.0f; if (sprite.X - sprite.ScaleX < X - edgeCoef * XEdge) sprite.X = X - edgeCoef * XEdge + sprite.ScaleX; if (sprite.X + sprite.ScaleX > X + edgeCoef * XEdge) sprite.X = X + edgeCoef * XEdge - sprite.ScaleX; if (sprite.Y - sprite.ScaleY < Y - edgeCoef * YEdge) sprite.Y = Y - edgeCoef * YEdge + sprite.ScaleY; if (sprite.Y + sprite.ScaleY > Y + edgeCoef * YEdge) sprite.Y = Y + edgeCoef * YEdge - sprite.ScaleY; if (sprite.Parent != null) { Vector3 shiftAmount = sprite.Position - oldPosition; sprite.TopParent.Position += shiftAmount; } } public override void Pause(FlatRedBall.Instructions.InstructionList instructions) { FlatRedBall.Instructions.Pause.CameraUnpauseInstruction instruction = new FlatRedBall.Instructions.Pause.CameraUnpauseInstruction(this); instruction.Stop(this); instructions.Add(instruction); // TODO: Need to pause the lights, but currently we don't know what type the lights are } public void PositionRandomlyInView(IPositionable positionable) { PositionRandomlyInView(positionable, Z, Z); } /// <summary> /// Positiones the argument positionable randomly in camera between the argument bounds. /// </summary> /// <remarks> /// Assumes the camera is viewing down the Z plane - it is unrotated. /// </remarks> /// <param name="positionable">The object to reposition.</param> /// <param name="minimumDistanceFromCamera">The closest possible distance from the camera.</param> /// <param name="maximumDistanceFromCamera">The furthest possible distance from the camera.</param> public void PositionRandomlyInView(IPositionable positionable, float minimumDistanceFromCamera, float maximumDistanceFromCamera) { // First get the distance from the camera. float distanceFromCamera = minimumDistanceFromCamera + (float)(FlatRedBallServices.Random.NextDouble() * (maximumDistanceFromCamera - minimumDistanceFromCamera)); positionable.Z = Z + (distanceFromCamera * FlatRedBall.Math.MathFunctions.ForwardVector3.Z); positionable.X = X - RelativeXEdgeAt(positionable.Z) + (float)( FlatRedBallServices.Random.NextDouble() * 2.0f * RelativeXEdgeAt(positionable.Z) ); positionable.Y = Y - RelativeYEdgeAt(positionable.Z) + (float)(FlatRedBallServices.Random.NextDouble() * 2.0f * RelativeYEdgeAt(positionable.Z)); } public void RefreshTexture() { #if SUPPORTS_POST_PROCESSING if (mRenderTargetTexture != null && mRenderTargetTexture.IsDisposed == false) { throw new InvalidOperationException("The old RenderTargetTexture must first be disposed"); } // Create the render textures collection mRenderTargetTextures = new Dictionary<int, RenderTargetTexture>(); mRenderTargetTexture = new RenderTargetTexture( SurfaceFormat.Color, DestinationRectangle.Width, DestinationRectangle.Height, true); FlatRedBallServices.AddDisposable("Render Target Texture" + sCreatedCount, mRenderTargetTexture, mContentManager); sCreatedCount++; #endif } public void SetRelativeYEdgeAt(float zDistance, float verticalDistance) { FieldOfView = (float)(2 * System.Math.Atan((double)((.5 * verticalDistance) / zDistance))); } public void ScaleDestinationRectangle(float scaleAmount) { float newWidth = DestinationRectangle.Width * scaleAmount; float newHeight = DestinationRectangle.Height * scaleAmount; float destinationCenterX = DestinationRectangle.Left + DestinationRectangle.Width / 2.0f; float destinationCenterY = DestinationRectangle.Top + DestinationRectangle.Height / 2.0f; DestinationRectangle = new Rectangle( (int)(destinationCenterX - newWidth / 2.0f), (int)(destinationCenterY - newHeight / 2.0f), (int)(newWidth), (int)(newHeight)); } #region XML Docs /// <summary> /// Removes the argument Layer from this Camera. Does not empty the layer or /// remove contained objects from their respective managers. /// </summary> /// <param name="layerToRemove">The layer to remove</param> #endregion public void RemoveLayer(Layer layerToRemove) { mLayers.Remove(layerToRemove); layerToRemove.mCameraBelongingTo = null; } #region XML Docs /// <summary> /// Sets the visible borders when the camera is looking down the Z axis. /// </summary> /// <remarks> /// This sets visibility ranges for the camera. That is, if the camera's maximumX is set to 100 at a zToSetAt of /// 0, the camera will never be able to see the point x = 101, z = 0. The camera imposes these limitations /// by calculating the actual minimum and maximum values according to the variables passed. Also, /// the camera keeps track of these visible limits and readjusts the mimimum and maximum values /// when the camera moves in the z direction. Therefore, it is only necessary to set these /// values once, and the camera will remeber that these are the visibility borders, regardless of /// its position. It is important to note that the visiblity borders can be violated if they are too /// close together - if a camera moves so far back that its viewable area at the set Z is greater than /// the set minimumX and maximumX range, the camera will show an area outside of this range. /// <seealso cref="FlatRedBall.Camera.ClearBorders"/> /// </remarks> /// <param name="minimumX">The minimum x value of the visiblity border.</param> /// <param name="minimumY">The minimum y value of the visiblity border.</param> /// <param name="maximumX">The maximum x value of the visiblity border.</param> /// <param name="maximumY">The maximum y value of the visiblity border.</param> /// <param name="zToSetAt">The z value of the plane to use for the visibility border.</param> #endregion public void SetBordersAtZ(float minimumX, float minimumY, float maximumX, float maximumY, float zToSetAt) { mBaseZ = zToSetAt; mBaseMinimumX = minimumX; mBaseMinimumY = minimumY; mBaseMaximumX = maximumX; mBaseMaximumY = maximumY; CalculateMaxAndMins(); X = System.Math.Min(X, mMaximumX); X = System.Math.Max(X, mMinimumX); Y = System.Math.Min(Y, mMaximumY); Y = System.Math.Max(Y, mMinimumY); } public void SetBordersAt(AxisAlignedRectangle visibleBounds) { SetBordersAtZ(visibleBounds.Left, visibleBounds.Bottom, visibleBounds.Right, visibleBounds.Top, visibleBounds.Z); } #region XML Docs /// <summary> /// Copies all fields from the argument to the camera instance. /// </summary> /// <remarks> /// This method will not copy the name, InstructionArray, or children PositionedObjects /// (objects attached to the cameraToSetTo). /// </remarks> /// <param name="cameraToSetTo">The camera to clone.</param> #endregion public void SetCameraTo(Camera cameraToSetTo) { this.mAspectRatio = cameraToSetTo.mAspectRatio; this.mBaseMaximumX = cameraToSetTo.mBaseMaximumX; this.mBaseMaximumY = cameraToSetTo.mBaseMaximumY; this.mBaseMinimumX = cameraToSetTo.mBaseMinimumX; this.mBaseMinimumY = cameraToSetTo.mBaseMinimumY; this.mBaseZ = cameraToSetTo.mBaseZ; // cannot set children, because any PO can only be attached to one other PO this.CameraCullMode = cameraToSetTo.CameraCullMode; this.mParent = cameraToSetTo.Parent; this.mDestinationRectangle = cameraToSetTo.mDestinationRectangle; this.mFieldOfView = cameraToSetTo.mFieldOfView; // not setting InstructionArray. May want to do this later this.MaximumX = cameraToSetTo.MaximumX; this.MaximumY = cameraToSetTo.MaximumY; this.MinimumX = cameraToSetTo.MinimumX; this.MinimumY = cameraToSetTo.MinimumY; // does not set name this.mOrthogonal = cameraToSetTo.mOrthogonal; this.mOrthogonalWidth = cameraToSetTo.mOrthogonalWidth; this.mOrthogonalHeight = cameraToSetTo.mOrthogonalHeight; this.RelativeX = cameraToSetTo.RelativeX; this.RelativeAcceleration = cameraToSetTo.RelativeAcceleration; this.RelativeXVelocity = cameraToSetTo.RelativeXVelocity; this.RelativeY = cameraToSetTo.RelativeY; this.RelativeYVelocity = cameraToSetTo.RelativeYVelocity; this.RelativeZ = cameraToSetTo.RelativeZ; this.RelativeZVelocity = cameraToSetTo.RelativeZVelocity; this.X = cameraToSetTo.X; this.XAcceleration = cameraToSetTo.XAcceleration; this.mXEdge = cameraToSetTo.mXEdge; this.XVelocity = cameraToSetTo.XVelocity; this.Y = cameraToSetTo.Y; this.YAcceleration = cameraToSetTo.YAcceleration; this.mYEdge = cameraToSetTo.mYEdge; this.YVelocity = cameraToSetTo.YVelocity; this.Z = cameraToSetTo.Z; this.ZAcceleration = cameraToSetTo.ZAcceleration; this.ZVelocity = cameraToSetTo.ZVelocity; this.mNearClipPlane = cameraToSetTo.mNearClipPlane; this.mFarClipPlane = cameraToSetTo.mFarClipPlane; } public void SetLookAtRotationMatrix(Vector3 LookAtPoint) { SetLookAtRotationMatrix(LookAtPoint, new Vector3(0, 1, 0)); } public void SetLookAtRotationMatrix(Vector3 LookAtPoint, Vector3 upDirection) { Matrix newMatrix = Matrix.Invert( Matrix.CreateLookAt( Position, LookAtPoint, upDirection)); // Kill the translation newMatrix.M41 = 0; newMatrix.M42 = 0; newMatrix.M43 = 0; // leave M44 to 1 RotationMatrix = newMatrix; } public void SetDeviceViewAndProjection(BasicEffect effect, bool relativeToCamera) { #if !SILVERLIGHT // Set up our view matrix. A view matrix can be defined given an eye point, // a point to lookat, and a direction for which way is up. effect.View = GetLookAtMatrix(relativeToCamera); effect.Projection = GetProjectionMatrix(); #endif } public void SetDeviceViewAndProjection(GenericEffect effect, bool relativeToCamera) { // Set up our view matrix. A view matrix can be defined given an eye point, // a point to lookat, and a direction for which way is up. effect.View = GetLookAtMatrix(relativeToCamera); effect.Projection = GetProjectionMatrix(); } public void SetDeviceViewAndProjection(Effect effect, bool relativeToCamera) { //TimeManager.SumTimeSection("Start of SetDeviceViewAndProjection"); #region Create the matrices // Get view, projection, and viewproj values Matrix view = (relativeToCamera)? mViewRelative : mView; Matrix viewProj; Matrix.Multiply(ref view, ref mProjection, out viewProj); #endregion if (effect is AlphaTestEffect) { AlphaTestEffect asAlphaTestEffect = effect as AlphaTestEffect; asAlphaTestEffect.View = view; asAlphaTestEffect.Projection = mProjection; } else { //TimeManager.SumTimeSection("Create the matrices"); //EffectParameterBlock block = new EffectParameterBlock(effect); #region Get all valid parameters EffectParameter paramNameViewProj = effect.Parameters["ViewProj"]; EffectParameter paramNameView = effect.Parameters["View"]; EffectParameter paramNameProjection = effect.Parameters["Projection"]; //EffectParameter paramSemViewProj = effect.Parameters.GetParameterBySemantic("VIEWPROJ"); //EffectParameter paramSemView = effect.Parameters.GetParameterBySemantic("VIEW"); //EffectParameter paramSemProjection = effect.Parameters.GetParameterBySemantic("PROJECTION"); #endregion //TimeManager.SumTimeSection("Get all valid parameters"); #region Set all available parameters //if (paramNameProjection != null || paramNameView != null || // paramNameViewProj != null || paramSemProjection != null || // paramSemView != null || paramSemViewProj != null) //{ //block.Begin(); if (paramNameView != null) paramNameView.SetValue(view); //if (paramSemView != null) paramSemView.SetValue(view); if (paramNameProjection != null) paramNameProjection.SetValue(mProjection); //if (paramSemProjection != null) paramSemProjection.SetValue(mProjection); if (paramNameViewProj != null) paramNameViewProj.SetValue(viewProj); //if (paramSemViewProj != null) paramSemViewProj.SetValue(viewProj); //block.End(); //block.Apply(); //} #endregion //TimeManager.SumTimeSection("Set available parameters"); } } public override void TimedActivity(float secondDifference, double secondDifferenceSquaredDividedByTwo, float secondsPassedLastFrame) { base.TimedActivity(secondDifference, secondDifferenceSquaredDividedByTwo, secondsPassedLastFrame); // This will be done both in UpdateDependencies as well as here X = System.Math.Min(X, mMaximumX); X = System.Math.Max(X, mMinimumX); Y = System.Math.Min(Y, mMaximumY); Y = System.Math.Max(Y, mMinimumY); if (!double.IsNaN(this.mBaseMaximumX)) { CalculateMaxAndMins(); } #region update the destination rectangle (for viewport) if (mTopDestinationVelocity != 0f || mBottomDestinationVelocity != 0f || mLeftDestinationVelocity != 0f || mRightDestinationVelocity != 0f) { mTopDestination += mTopDestinationVelocity * TimeManager.SecondDifference; mBottomDestination += mBottomDestinationVelocity * TimeManager.SecondDifference; mLeftDestination += mLeftDestinationVelocity * TimeManager.SecondDifference; mRightDestination += mRightDestinationVelocity * TimeManager.SecondDifference; UpdateDestinationRectangle(); FixAspectRatioYConstant(); } #endregion } public override void UpdateDependencies(double currentTime) { base.UpdateDependencies(currentTime); // This will be done both in TimedUpdate as well as here X = System.Math.Min(X, mMaximumX); X = System.Math.Max(X, mMinimumX); Y = System.Math.Min(Y, mMaximumY); Y = System.Math.Max(Y, mMinimumY); if (!double.IsNaN(this.mBaseMaximumX)) { CalculateMaxAndMins(); } // I'm not sure if this is the proper fix but on WP7 it prevents // tile maps from rendering improperly when scrolling. if (ShiftsHalfUnitForRendering && this.Parent != null) { Position.X = (int)Position.X + .25f; Position.Y = (int)Position.Y - .25f; } // This should happen AFTER mins and maxes are set UpdateViewProjectionMatrix(true); } public void UpdateViewProjectionMatrix() { UpdateViewProjectionMatrix(false); } public void UpdateViewProjectionMatrix(bool updateFrustum) { mView = GetLookAtMatrix(false); mViewRelative = GetLookAtMatrix(true); //NOTE: Certain objects need to be rendered "Pixel Perfect" on screen. // However, DX9 (and by extension XNA) has an "issue" moving from texel space to pixel space. // http://msdn.microsoft.com/en-us/library/bb219690(v=vs.85).aspx // if an object needs to be pixel perfect, it needs to have it's projection matrix shifted by -.5 x and -.5 y //EXAMPLE: // mProjection = Matrix.CreateTranslation(-0.5f, -0.5f, 0) * GetProjectionMatrix(); mProjection = GetProjectionMatrix(); if (updateFrustum) { Matrix.Multiply(ref mView, ref mProjection, out mViewProjection); mBoundingFrustum.Matrix = (mViewProjection); } } /// <summary> /// Sets the camera to be 2D (far-away things do not get smaller) by /// setting Orthogonal to true and adjusts the OrthogonalWidth and OrthogonalHeight /// to match the pixel resolution. In other words, this makes 1 unit in game match 1 pixel on screen. /// </summary> public void UsePixelCoordinates() { UsePixelCoordinates(false, mDestinationRectangle.Width, mDestinationRectangle.Height); } [Obsolete("Use parameterless method")] public void UsePixelCoordinates(bool moveCornerToOrigin) { UsePixelCoordinates(moveCornerToOrigin, mDestinationRectangle.Width, mDestinationRectangle.Height); } #region XML Docs /// Sets the viewport for this camera to a standard split-screen viewport /// </summary> /// <param name="viewport">The viewport to use for this camera. If null, the camera will not automatically /// adjust itself.</param> public void SetSplitScreenViewport(SplitScreenViewport? viewport) { if(viewport == null) { mUsesSplitScreenViewport = false; } else { mUsesSplitScreenViewport = true; splitScreenViewport = viewport.Value; // Set the left mLeftDestination = //FlatRedBallServices.GraphicsDevice.Viewport.X + (( (( viewport != SplitScreenViewport.RightHalf && viewport != SplitScreenViewport.TopRight && viewport != SplitScreenViewport.BottomRight) ? 0 : FlatRedBallServices.ClientWidth / 2); // Set the top mTopDestination = //FlatRedBallServices.GraphicsDevice.Viewport.Y + (( (( viewport != SplitScreenViewport.BottomHalf && viewport != SplitScreenViewport.BottomLeft && viewport != SplitScreenViewport.BottomRight) ? 0 : FlatRedBallServices.ClientHeight / 2); // Set the right (left + width) mRightDestination = mLeftDestination + (( viewport != SplitScreenViewport.FullScreen && viewport != SplitScreenViewport.BottomHalf && viewport != SplitScreenViewport.TopHalf) ? FlatRedBallServices.ClientWidth / 2 : FlatRedBallServices.ClientWidth); // Set the bottom (top + height) mBottomDestination = mTopDestination + (( viewport != SplitScreenViewport.FullScreen && viewport != SplitScreenViewport.LeftHalf && viewport != SplitScreenViewport.RightHalf) ? FlatRedBallServices.ClientHeight / 2 : FlatRedBallServices.ClientHeight); // Update the destination rectangle UpdateDestinationRectangle(); } } #endregion #region Internal Methods //internal void FlushLayers() //{ // int layerCount = mLayers.Count; // for (int i = 0; i < layerCount; i++) // { // mLayers[i].Flush(); // } //} internal int UpdateSpriteInCameraView(SpriteList spriteList) { return UpdateSpriteInCameraView(spriteList, false); } internal int UpdateSpriteInCameraView(SpriteList spriteList, bool relativeToCamera) { int numberVisible = 0; for (int i = 0; i < spriteList.Count; i++) { Sprite s = spriteList[i]; if (!s.AbsoluteVisible || // If using InterpolateColor, then alpha is used for interpolation of colors and // not transparency (s.ColorOperation != ColorOperation.InterpolateColor && s.Alpha < .0001f )) { s.mInCameraView = false; continue; } s.mInCameraView = IsSpriteInView(s, relativeToCamera); if (s.mInCameraView) { numberVisible++; } } return numberVisible; } internal void UpdateOnResize() { if (mUsesSplitScreenViewport) SetSplitScreenViewport(splitScreenViewport); } #endregion #region Private Methods #region XML Docs /// <summary> /// Calculates the minimum and maximum X values for the camera based off of its /// base values (such as mBaseMaximumX) and its current view /// </summary> #endregion public void CalculateMaxAndMins() { // Vic says: This method used to be private. But now we want it public so that // Entities that control the camera can force calculate it. if (mOrthogonal) { mMinimumX = mBaseMinimumX + mOrthogonalWidth / 2.0f; mMaximumX = mBaseMaximumX - mOrthogonalWidth / 2.0f; mMinimumY = mBaseMinimumY + mOrthogonalHeight / 2.0f; mMaximumY = mBaseMaximumY - mOrthogonalHeight / 2.0f; } else { mMinimumX = mBaseMinimumX + mXEdge * (mBaseZ - Z) / (100f * MathFunctions.ForwardVector3.Z); mMaximumX = mBaseMaximumX - mXEdge * (mBaseZ - Z) / (100f * MathFunctions.ForwardVector3.Z); mMinimumY = mBaseMinimumY + mYEdge * (mBaseZ - Z) / (100f * MathFunctions.ForwardVector3.Z); mMaximumY = mBaseMaximumY - mYEdge * (mBaseZ - Z) / (100f * MathFunctions.ForwardVector3.Z); } } #region XML Docs /// <summary> /// Updates the destination rectangle (for the viewport). Also fixes the aspect ratio. /// </summary> #endregion private void UpdateDestinationRectangle() { //usesSplitScreenViewport = false; //mDestinationRectangle = value; //mTopDestination = mDestinationRectangle.Top; //mBottomDestination = mDestinationRectangle.Bottom; //mLeftDestination = mDestinationRectangle.Left; //mRightDestination = mDestinationRectangle.Right; //FixAspectRatioYConstant(); mDestinationRectangle = new Rectangle( (int)mLeftDestination, (int)mTopDestination, (int)(mRightDestination - mLeftDestination), (int)(mBottomDestination - mTopDestination)); FixAspectRatioYConstant(); #if SUPPORTS_POST_PROCESSING // Update post-processing buffers if (Renderer.UseRenderTargets && PostProcessingManager.IsInitialized) { foreach (PostProcessingEffectBase effect in PostProcessing.EffectCombineOrder) { effect.UpdateToScreenSize(); } } #endif } #endregion #region Protected Methods #endregion #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using AutoMapper.Configuration; using AutoMapper.Configuration.Conventions; using AutoMapper.Mappers; namespace AutoMapper { #if NETSTANDARD1_1 struct IConvertible{} #endif [DebuggerDisplay("{Name}")] public class ProfileMap { private readonly TypeMapFactory _typeMapFactory = new TypeMapFactory(); private readonly IEnumerable<ITypeMapConfiguration> _typeMapConfigs; private readonly IEnumerable<ITypeMapConfiguration> _openTypeMapConfigs; private readonly LockingConcurrentDictionary<Type, TypeDetails> _typeDetails; public ProfileMap(IProfileConfiguration profile) : this(profile, null) { } public ProfileMap(IProfileConfiguration profile, IConfiguration configuration) { _typeDetails = new LockingConcurrentDictionary<Type, TypeDetails>(TypeDetailsFactory); Name = profile.ProfileName; AllowNullCollections = profile.AllowNullCollections ?? configuration?.AllowNullCollections ?? false; AllowNullDestinationValues = profile.AllowNullDestinationValues ?? configuration?.AllowNullDestinationValues ?? true; EnableNullPropagationForQueryMapping = profile.EnableNullPropagationForQueryMapping ?? configuration?.EnableNullPropagationForQueryMapping ?? false; ConstructorMappingEnabled = profile.ConstructorMappingEnabled ?? configuration?.ConstructorMappingEnabled ?? true; ShouldMapField = profile.ShouldMapField ?? configuration?.ShouldMapField ?? (p => p.IsPublic()); ShouldMapProperty = profile.ShouldMapProperty ?? configuration?.ShouldMapProperty ?? (p => p.IsPublic()); CreateMissingTypeMaps = profile.CreateMissingTypeMaps ?? configuration?.CreateMissingTypeMaps ?? true; ValidateInlineMaps = profile.ValidateInlineMaps ?? configuration?.ValidateInlineMaps ?? true; TypeConfigurations = profile.TypeConfigurations .Concat(configuration?.TypeConfigurations ?? Enumerable.Empty<IConditionalObjectMapper>()) .ToArray(); ValueTransformers = profile.ValueTransformers.Concat(configuration?.ValueTransformers ?? Enumerable.Empty<ValueTransformerConfiguration>()).ToArray(); MemberConfigurations = profile.MemberConfigurations.ToArray(); MemberConfigurations.FirstOrDefault()?.AddMember<NameSplitMember>(_ => _.SourceMemberNamingConvention = profile.SourceMemberNamingConvention); MemberConfigurations.FirstOrDefault()?.AddMember<NameSplitMember>(_ => _.DestinationMemberNamingConvention = profile.DestinationMemberNamingConvention); GlobalIgnores = profile.GlobalIgnores.Concat(configuration?.GlobalIgnores ?? Enumerable.Empty<string>()).ToArray(); SourceExtensionMethods = profile.SourceExtensionMethods.Concat(configuration?.SourceExtensionMethods ?? Enumerable.Empty<MethodInfo>()).ToArray(); AllPropertyMapActions = profile.AllPropertyMapActions.Concat(configuration?.AllPropertyMapActions ?? Enumerable.Empty<Action<PropertyMap, IMemberConfigurationExpression>>()).ToArray(); AllTypeMapActions = profile.AllTypeMapActions.Concat(configuration?.AllTypeMapActions ?? Enumerable.Empty<Action<TypeMap, IMappingExpression>>()).ToArray(); Prefixes = profile.MemberConfigurations .Select(m => m.NameMapper) .SelectMany(m => m.NamedMappers) .OfType<PrePostfixName>() .SelectMany(m => m.Prefixes) .ToArray(); Postfixes = profile.MemberConfigurations .Select(m => m.NameMapper) .SelectMany(m => m.NamedMappers) .OfType<PrePostfixName>() .SelectMany(m => m.Postfixes) .ToArray(); _typeMapConfigs = profile.TypeMapConfigs.ToArray(); _openTypeMapConfigs = profile.OpenTypeMapConfigs.ToArray(); } public bool AllowNullCollections { get; } public bool AllowNullDestinationValues { get; } public bool ConstructorMappingEnabled { get; } public bool CreateMissingTypeMaps { get; } public bool ValidateInlineMaps { get; } public bool EnableNullPropagationForQueryMapping { get; } public string Name { get; } public Func<FieldInfo, bool> ShouldMapField { get; } public Func<PropertyInfo, bool> ShouldMapProperty { get; } public IEnumerable<Action<PropertyMap, IMemberConfigurationExpression>> AllPropertyMapActions { get; } public IEnumerable<Action<TypeMap, IMappingExpression>> AllTypeMapActions { get; } public IEnumerable<string> GlobalIgnores { get; } public IEnumerable<IMemberConfiguration> MemberConfigurations { get; } public IEnumerable<MethodInfo> SourceExtensionMethods { get; } public IEnumerable<IConditionalObjectMapper> TypeConfigurations { get; } public IEnumerable<string> Prefixes { get; } public IEnumerable<string> Postfixes { get; } public IEnumerable<ValueTransformerConfiguration> ValueTransformers { get; } public TypeDetails CreateTypeDetails(Type type) => _typeDetails.GetOrAdd(type); private TypeDetails TypeDetailsFactory(Type type) => new TypeDetails(type, this); public void Register(TypeMapRegistry typeMapRegistry) { foreach (var config in _typeMapConfigs.Where(c => !c.IsOpenGeneric)) { BuildTypeMap(typeMapRegistry, config); if (config.ReverseTypeMap != null) { BuildTypeMap(typeMapRegistry, config.ReverseTypeMap); } } } public void Configure(TypeMapRegistry typeMapRegistry) { foreach (var typeMapConfiguration in _typeMapConfigs.Where(c => !c.IsOpenGeneric)) { Configure(typeMapRegistry, typeMapConfiguration); if (typeMapConfiguration.ReverseTypeMap != null) { Configure(typeMapRegistry, typeMapConfiguration.ReverseTypeMap); } } } private void BuildTypeMap(TypeMapRegistry typeMapRegistry, ITypeMapConfiguration config) { var typeMap = _typeMapFactory.CreateTypeMap(config.SourceType, config.DestinationType, this); config.Configure(typeMap); typeMapRegistry.RegisterTypeMap(typeMap); } private void Configure(TypeMapRegistry typeMapRegistry, ITypeMapConfiguration typeMapConfiguration) { var typeMap = typeMapRegistry.GetTypeMap(typeMapConfiguration.Types); Configure(typeMapRegistry, typeMap); } private void Configure(TypeMapRegistry typeMapRegistry, TypeMap typeMap) { foreach (var action in AllTypeMapActions) { var expression = new MappingExpression(typeMap.Types, typeMap.ConfiguredMemberList); action(typeMap, expression); expression.Configure(typeMap); } foreach (var action in AllPropertyMapActions) { foreach (var propertyMap in typeMap.GetPropertyMaps()) { var memberExpression = new MappingExpression.MemberConfigurationExpression(propertyMap.DestinationProperty, typeMap.SourceType); action(propertyMap, memberExpression); memberExpression.Configure(typeMap); } } ApplyBaseMaps(typeMapRegistry, typeMap, typeMap); ApplyDerivedMaps(typeMapRegistry, typeMap, typeMap); } public bool IsConventionMap(TypePair types) { return TypeConfigurations.Any(c => c.IsMatch(types)); } public TypeMap CreateConventionTypeMap(TypeMapRegistry typeMapRegistry, TypePair types) { var typeMap = _typeMapFactory.CreateTypeMap(types.SourceType, types.DestinationType, this); typeMap.IsConventionMap = true; var config = new MappingExpression(typeMap.Types, typeMap.ConfiguredMemberList); config.Configure(typeMap); Configure(typeMapRegistry, typeMap); return typeMap; } public TypeMap CreateInlineMap(TypeMapRegistry typeMapRegistry, TypePair types) { var typeMap = _typeMapFactory.CreateTypeMap(types.SourceType, types.DestinationType, this); typeMap.IsConventionMap = true; Configure(typeMapRegistry, typeMap); return typeMap; } public TypeMap CreateClosedGenericTypeMap(ITypeMapConfiguration openMapConfig, TypeMapRegistry typeMapRegistry, TypePair closedTypes) { var closedMap = _typeMapFactory.CreateTypeMap(closedTypes.SourceType, closedTypes.DestinationType, this); openMapConfig.Configure(closedMap); Configure(typeMapRegistry, closedMap); if(closedMap.TypeConverterType != null) { var typeParams = (openMapConfig.SourceType.IsGenericTypeDefinition() ? closedTypes.SourceType.GetGenericArguments() : new Type[0]) .Concat (openMapConfig.DestinationType.IsGenericTypeDefinition() ? closedTypes.DestinationType.GetGenericArguments() : new Type[0]); var neededParameters = closedMap.TypeConverterType.GetGenericParameters().Length; closedMap.TypeConverterType = closedMap.TypeConverterType.MakeGenericType(typeParams.Take(neededParameters).ToArray()); } if(closedMap.DestinationTypeOverride?.IsGenericTypeDefinition() == true) { var neededParameters = closedMap.DestinationTypeOverride.GetGenericParameters().Length; closedMap.DestinationTypeOverride = closedMap.DestinationTypeOverride.MakeGenericType(closedTypes.DestinationType.GetGenericArguments().Take(neededParameters).ToArray()); } return closedMap; } public ITypeMapConfiguration GetGenericMap(TypePair closedTypes) { return _openTypeMapConfigs .SelectMany(tm => tm.ReverseTypeMap == null ? new[] { tm } : new[] { tm, tm.ReverseTypeMap }) .Where(tm => tm.Types.SourceType.GetGenericTypeDefinitionIfGeneric() == closedTypes.SourceType.GetGenericTypeDefinitionIfGeneric() && tm.Types.DestinationType.GetGenericTypeDefinitionIfGeneric() == closedTypes.DestinationType.GetGenericTypeDefinitionIfGeneric()) .OrderByDescending(tm => tm.DestinationType == closedTypes.DestinationType) // Favor more specific destination matches, .ThenByDescending(tm => tm.SourceType == closedTypes.SourceType) // then more specific source matches .FirstOrDefault(); } private static void ApplyBaseMaps(TypeMapRegistry typeMapRegistry, TypeMap derivedMap, TypeMap currentMap) { foreach (var baseMap in currentMap.IncludedBaseTypes.Select(typeMapRegistry.GetTypeMap).Where(baseMap => baseMap != null)) { baseMap.IncludeDerivedTypes(currentMap.SourceType, currentMap.DestinationType); derivedMap.AddInheritedMap(baseMap); ApplyBaseMaps(typeMapRegistry, derivedMap, baseMap); } } private void ApplyDerivedMaps(TypeMapRegistry typeMapRegistry, TypeMap baseMap, TypeMap typeMap) { foreach (var inheritedTypeMap in typeMap.IncludedDerivedTypes.Select(typeMapRegistry.GetTypeMap).Where(map => map != null)) { inheritedTypeMap.IncludeBaseTypes(typeMap.SourceType, typeMap.DestinationType); inheritedTypeMap.AddInheritedMap(baseMap); ApplyDerivedMaps(typeMapRegistry, baseMap, inheritedTypeMap); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.SS.UserModel { using System; using NUnit.Framework; using NPOI.SS; using NPOI.SS.Util; using NPOI.SS.UserModel; using System.Collections; /** * Common superclass for Testing {@link NPOI.xssf.UserModel.XSSFCell} and * {@link NPOI.HSSF.UserModel.HSSFCell} */ [TestFixture] public class BaseTestSheet { private ITestDataProvider _testDataProvider; public BaseTestSheet() : this(TestCases.HSSF.HSSFITestDataProvider.Instance) { } protected BaseTestSheet(ITestDataProvider TestDataProvider) { _testDataProvider = TestDataProvider; } [Test] public void TestCreateRow() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); Assert.AreEqual(0, sheet.PhysicalNumberOfRows); //Test that we Get null for undefined rownumber Assert.IsNull(sheet.GetRow(1)); // Test row creation with consecutive indexes IRow row1 = sheet.CreateRow(0); IRow row2 = sheet.CreateRow(1); Assert.AreEqual(0, row1.RowNum); Assert.AreEqual(1, row2.RowNum); IEnumerator it = sheet.GetRowEnumerator(); Assert.IsTrue(it.MoveNext()); Assert.AreSame(row1, it.Current); Assert.IsTrue(it.MoveNext()); Assert.AreSame(row2, it.Current); Assert.AreEqual(1, sheet.LastRowNum); // Test row creation with non consecutive index IRow row101 = sheet.CreateRow(100); Assert.IsNotNull(row101); Assert.AreEqual(100, sheet.LastRowNum); Assert.AreEqual(3, sheet.PhysicalNumberOfRows); // Test overwriting an existing row IRow row2_ovrewritten = sheet.CreateRow(1); ICell cell = row2_ovrewritten.CreateCell(0); cell.SetCellValue(100); IEnumerator it2 = sheet.GetRowEnumerator(); Assert.IsTrue(it2.MoveNext()); Assert.AreSame(row1, it2.Current); Assert.IsTrue(it2.MoveNext()); IRow row2_ovrewritten_ref = (IRow)it2.Current; Assert.AreSame(row2_ovrewritten, row2_ovrewritten_ref); Assert.AreEqual(100.0, row2_ovrewritten_ref.GetCell(0).NumericCellValue, 0.0); } [Test] public void TestRemoveRow() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet1 = workbook.CreateSheet(); Assert.AreEqual(0, sheet1.PhysicalNumberOfRows); Assert.AreEqual(0, sheet1.FirstRowNum); Assert.AreEqual(0, sheet1.LastRowNum); IRow row0 = sheet1.CreateRow(0); Assert.AreEqual(1, sheet1.PhysicalNumberOfRows); Assert.AreEqual(0, sheet1.FirstRowNum); Assert.AreEqual(0, sheet1.LastRowNum); sheet1.RemoveRow(row0); Assert.AreEqual(0, sheet1.PhysicalNumberOfRows); Assert.AreEqual(0, sheet1.FirstRowNum); Assert.AreEqual(0, sheet1.LastRowNum); sheet1.CreateRow(1); IRow row2 = sheet1.CreateRow(2); Assert.AreEqual(2, sheet1.PhysicalNumberOfRows); Assert.AreEqual(1, sheet1.FirstRowNum); Assert.AreEqual(2, sheet1.LastRowNum); Assert.IsNotNull(sheet1.GetRow(1)); Assert.IsNotNull(sheet1.GetRow(2)); sheet1.RemoveRow(row2); Assert.IsNotNull(sheet1.GetRow(1)); Assert.IsNull(sheet1.GetRow(2)); Assert.AreEqual(1, sheet1.PhysicalNumberOfRows); Assert.AreEqual(1, sheet1.FirstRowNum); Assert.AreEqual(1, sheet1.LastRowNum); IRow row3 = sheet1.CreateRow(3); ISheet sheet2 = workbook.CreateSheet(); try { sheet2.RemoveRow(row3); Assert.Fail("Expected exception"); } catch (ArgumentException e) { Assert.AreEqual("Specified row does not belong to this sheet", e.Message); } } [Test] public void TestCloneSheet() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ICreationHelper factory = workbook.GetCreationHelper(); ISheet sheet = workbook.CreateSheet("Test Clone"); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); ICell cell2 = row.CreateCell(1); cell.SetCellValue(factory.CreateRichTextString("Clone_test")); cell2.CellFormula = (/*setter*/"SIN(1)"); ISheet clonedSheet = workbook.CloneSheet(0); IRow clonedRow = clonedSheet.GetRow(0); //Check for a good clone Assert.AreEqual(clonedRow.GetCell(0).RichStringCellValue.String, "Clone_test"); //Check that the cells are not somehow linked cell.SetCellValue(factory.CreateRichTextString("Difference Check")); cell2.CellFormula = (/*setter*/"cos(2)"); if ("Difference Check".Equals(clonedRow.GetCell(0).RichStringCellValue.String)) { Assert.Fail("string cell not properly Cloned"); } if ("COS(2)".Equals(clonedRow.GetCell(1).CellFormula)) { Assert.Fail("formula cell not properly Cloned"); } Assert.AreEqual(clonedRow.GetCell(0).RichStringCellValue.String, "Clone_test"); Assert.AreEqual(clonedRow.GetCell(1).CellFormula, "SIN(1)"); } /** Tests that the sheet name for multiple Clones of the same sheet is unique * BUG 37416 */ [Test] public void TestCloneSheetMultipleTimes() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ICreationHelper factory = workbook.GetCreationHelper(); ISheet sheet = workbook.CreateSheet("Test Clone"); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); cell.SetCellValue(factory.CreateRichTextString("Clone_test")); //Clone the sheet multiple times workbook.CloneSheet(0); workbook.CloneSheet(0); Assert.IsNotNull(workbook.GetSheet("Test Clone")); Assert.IsNotNull(workbook.GetSheet("Test Clone (2)")); Assert.AreEqual("Test Clone (3)", workbook.GetSheetName(2)); Assert.IsNotNull(workbook.GetSheet("Test Clone (3)")); workbook.RemoveSheetAt(0); workbook.RemoveSheetAt(0); workbook.RemoveSheetAt(0); workbook.CreateSheet("abc ( 123)"); workbook.CloneSheet(0); Assert.AreEqual("abc (124)", workbook.GetSheetName(1)); } /** * Setting landscape and portrait stuff on new sheets */ [Test] public void TestPrintSetupLandscapeNew() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheetL = workbook.CreateSheet("LandscapeS"); ISheet sheetP = workbook.CreateSheet("LandscapeP"); // Check two aspects of the print Setup Assert.IsFalse(sheetL.PrintSetup.Landscape); Assert.IsFalse(sheetP.PrintSetup.Landscape); Assert.AreEqual(1, sheetL.PrintSetup.Copies); Assert.AreEqual(1, sheetP.PrintSetup.Copies); // Change one on each sheetL.PrintSetup.Landscape = (/*setter*/true); sheetP.PrintSetup.Copies = (/*setter*/(short)3); // Check taken Assert.IsTrue(sheetL.PrintSetup.Landscape); Assert.IsFalse(sheetP.PrintSetup.Landscape); Assert.AreEqual(1, sheetL.PrintSetup.Copies); Assert.AreEqual(3, sheetP.PrintSetup.Copies); // Save and re-load, and check still there workbook = _testDataProvider.WriteOutAndReadBack(workbook); sheetL = workbook.GetSheet("LandscapeS"); sheetP = workbook.GetSheet("LandscapeP"); Assert.IsTrue(sheetL.PrintSetup.Landscape); Assert.IsFalse(sheetP.PrintSetup.Landscape); Assert.AreEqual(1, sheetL.PrintSetup.Copies); Assert.AreEqual(3, sheetP.PrintSetup.Copies); } /** * Test Adding merged regions. If the region's bounds are outside of the allowed range * then an ArgumentException should be thrown * */ [Test] public void TestAddMerged() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); Assert.AreEqual(0, sheet.NumMergedRegions); SpreadsheetVersion ssVersion = _testDataProvider.GetSpreadsheetVersion(); CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); sheet.AddMergedRegion(region); Assert.AreEqual(1, sheet.NumMergedRegions); try { region = new CellRangeAddress(-1, -1, -1, -1); sheet.AddMergedRegion(region); Assert.Fail("Expected exception"); } catch (ArgumentException) { // TODO Assert.AreEqual("Minimum row number is 0.", e.Message); } try { region = new CellRangeAddress(0, 0, 0, ssVersion.LastColumnIndex + 1); sheet.AddMergedRegion(region); Assert.Fail("Expected exception"); } catch (ArgumentException e) { Assert.AreEqual("Maximum column number is " + ssVersion.LastColumnIndex, e.Message); } try { region = new CellRangeAddress(0, ssVersion.LastRowIndex + 1, 0, 1); sheet.AddMergedRegion(region); Assert.Fail("Expected exception"); } catch (ArgumentException e) { Assert.AreEqual("Maximum row number is " + ssVersion.LastRowIndex, e.Message); } Assert.AreEqual(1, sheet.NumMergedRegions); } /** * When removing one merged region, it would break * */ [Test] public void TestRemoveMerged() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); sheet.AddMergedRegion(region); region = new CellRangeAddress(1, 2, 0, 1); sheet.AddMergedRegion(region); sheet.RemoveMergedRegion(0); region = sheet.GetMergedRegion(0); Assert.AreEqual(1, region.FirstRow, "Left over region should be starting at row 1"); sheet.RemoveMergedRegion(0); Assert.AreEqual(0, sheet.NumMergedRegions, "there should be no merged regions left!"); //an, Add, Remove, Get(0) would null pointer sheet.AddMergedRegion(region); Assert.AreEqual(1, sheet.NumMergedRegions, "there should now be one merged region!"); sheet.RemoveMergedRegion(0); Assert.AreEqual(0, sheet.NumMergedRegions, "there should now be zero merged regions!"); //add it again! region.LastRow = (/*setter*/4); sheet.AddMergedRegion(region); Assert.AreEqual(1, sheet.NumMergedRegions, "there should now be one merged region!"); //should exist now! Assert.IsTrue(1 <= sheet.NumMergedRegions, "there isn't more than one merged region in there"); region = sheet.GetMergedRegion(0); Assert.AreEqual(4, region.LastRow, "the merged row to doesnt match the one we Put in "); } [Test] public void TestShiftMerged() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ICreationHelper factory = wb.GetCreationHelper(); ISheet sheet = wb.CreateSheet(); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); cell.SetCellValue(factory.CreateRichTextString("first row, first cell")); row = sheet.CreateRow(1); cell = row.CreateCell(1); cell.SetCellValue(factory.CreateRichTextString("second row, second cell")); CellRangeAddress region = new CellRangeAddress(1, 1, 0, 1); sheet.AddMergedRegion(region); sheet.ShiftRows(1, 1, 1); region = sheet.GetMergedRegion(0); Assert.AreEqual(2, region.FirstRow, "Merged region not Moved over to row 2"); } /** * Tests the display of gridlines, formulas, and rowcolheadings. * @author Shawn Laubach (slaubach at apache dot org) */ [Test] public void TestDisplayOptions() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); Assert.AreEqual(sheet.DisplayGridlines, true); Assert.AreEqual(sheet.DisplayRowColHeadings, true); Assert.AreEqual(sheet.DisplayFormulas, false); Assert.AreEqual(sheet.DisplayZeros, true); sheet.DisplayGridlines = (/*setter*/false); sheet.DisplayRowColHeadings = (/*setter*/false); sheet.DisplayFormulas = (/*setter*/true); sheet.DisplayZeros = (/*setter*/false); wb = _testDataProvider.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); Assert.AreEqual(sheet.DisplayGridlines, false); Assert.AreEqual(sheet.DisplayRowColHeadings, false); Assert.AreEqual(sheet.DisplayFormulas, true); Assert.AreEqual(sheet.DisplayZeros, false); } [Test] public void TestColumnWidth() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); //default column width measured in characters sheet.DefaultColumnWidth = (/*setter*/10); Assert.AreEqual(10, sheet.DefaultColumnWidth); //columns A-C have default width Assert.AreEqual(256 * 10, sheet.GetColumnWidth(0)); Assert.AreEqual(256 * 10, sheet.GetColumnWidth(1)); Assert.AreEqual(256 * 10, sheet.GetColumnWidth(2)); //set custom width for D-F for (char i = 'D'; i <= 'F'; i++) { //Sheet#setColumnWidth accepts the width in units of 1/256th of a character width int w = 256 * 12; sheet.SetColumnWidth(/*setter*/i, w); Assert.AreEqual(w, sheet.GetColumnWidth(i)); } //reset the default column width, columns A-C Change, D-F still have custom width sheet.DefaultColumnWidth = (/*setter*/20); Assert.AreEqual(20, sheet.DefaultColumnWidth); Assert.AreEqual(256 * 20, sheet.GetColumnWidth(0)); Assert.AreEqual(256 * 20, sheet.GetColumnWidth(1)); Assert.AreEqual(256 * 20, sheet.GetColumnWidth(2)); for (char i = 'D'; i <= 'F'; i++) { int w = 256 * 12; Assert.AreEqual(w, sheet.GetColumnWidth(i)); } // check for 16-bit signed/unsigned error: sheet.SetColumnWidth(/*setter*/10, 40000); Assert.AreEqual(40000, sheet.GetColumnWidth(10)); //The maximum column width for an individual cell is 255 characters try { sheet.SetColumnWidth(/*setter*/9, 256 * 256); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.AreEqual("The maximum column width for an individual cell is 255 characters.", e.Message); } //serialize and read again wb = _testDataProvider.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); Assert.AreEqual(20, sheet.DefaultColumnWidth); //columns A-C have default width Assert.AreEqual(256 * 20, sheet.GetColumnWidth(0)); Assert.AreEqual(256 * 20, sheet.GetColumnWidth(1)); Assert.AreEqual(256 * 20, sheet.GetColumnWidth(2)); //columns D-F have custom width for (char i = 'D'; i <= 'F'; i++) { short w = (256 * 12); Assert.AreEqual(w, sheet.GetColumnWidth(i)); } Assert.AreEqual(40000, sheet.GetColumnWidth(10)); } [Test] public void TestDefaultRowHeight() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); sheet.DefaultRowHeightInPoints = (/*setter*/15); Assert.AreEqual((short)300, sheet.DefaultRowHeight); Assert.AreEqual(15.0F, sheet.DefaultRowHeightInPoints, 0.01F); IRow row = sheet.CreateRow(1); // new row inherits default height from the sheet Assert.AreEqual(sheet.DefaultRowHeight, row.Height); // Set a new default row height in twips and Test Getting the value in points sheet.DefaultRowHeight = (/*setter*/(short)360); Assert.AreEqual(18.0f, sheet.DefaultRowHeightInPoints, 0.01F); Assert.AreEqual((short)360, sheet.DefaultRowHeight); // Test that defaultRowHeight is a tRuncated short: E.G. 360inPoints -> 18; 361inPoints -> 18 sheet.DefaultRowHeight = (/*setter*/(short)361); Assert.AreEqual((float)361 / 20, sheet.DefaultRowHeightInPoints, 0.01F); Assert.AreEqual((short)361, sheet.DefaultRowHeight); // Set a new default row height in points and Test Getting the value in twips sheet.DefaultRowHeightInPoints = (/*setter*/17.5f); Assert.AreEqual(17.5f, sheet.DefaultRowHeightInPoints, 0.01F); Assert.AreEqual((short)(17.5f * 20), sheet.DefaultRowHeight); } /** cell with formula becomes null on cloning a sheet*/ [Test] public void Test35084() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet s = wb.CreateSheet("Sheet1"); IRow r = s.CreateRow(0); r.CreateCell(0).SetCellValue(1); r.CreateCell(1).CellFormula = (/*setter*/"A1*2"); ISheet s1 = wb.CloneSheet(0); r = s1.GetRow(0); Assert.AreEqual(r.GetCell(0).NumericCellValue, 1, 0, "double"); // sanity check Assert.IsNotNull(r.GetCell(1)); Assert.AreEqual(r.GetCell(1).CellFormula, "A1*2", "formula"); } /** Test that new default column styles Get applied */ [Test] public virtual void TestDefaultColumnStyle() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ICellStyle style = wb.CreateCellStyle(); ISheet sheet = wb.CreateSheet(); sheet.SetDefaultColumnStyle(/*setter*/0, style); Assert.IsNotNull(sheet.GetColumnStyle(0)); Assert.AreEqual(style.Index, sheet.GetColumnStyle(0).Index); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); ICellStyle style2 = cell.CellStyle; Assert.IsNotNull(style2); Assert.AreEqual(style.Index, style2.Index, "style should match"); } [Test] public void TestOutlineProperties() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); //TODO defaults are different in HSSF and XSSF //Assert.IsTrue(sheet.RowSumsBelow); //Assert.IsTrue(sheet.RowSumsRight); sheet.RowSumsBelow = (/*setter*/false); sheet.RowSumsRight = (/*setter*/false); Assert.IsFalse(sheet.RowSumsBelow); Assert.IsFalse(sheet.RowSumsRight); sheet.RowSumsBelow = (/*setter*/true); sheet.RowSumsRight = (/*setter*/true); Assert.IsTrue(sheet.RowSumsBelow); Assert.IsTrue(sheet.RowSumsRight); wb = _testDataProvider.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); Assert.IsTrue(sheet.RowSumsBelow); Assert.IsTrue(sheet.RowSumsRight); } /** * Test basic display properties */ [Test] public void TestSheetProperties() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); Assert.IsFalse(sheet.HorizontallyCenter); sheet.HorizontallyCenter = (/*setter*/true); Assert.IsTrue(sheet.HorizontallyCenter); sheet.HorizontallyCenter = (/*setter*/false); Assert.IsFalse(sheet.HorizontallyCenter); Assert.IsFalse(sheet.VerticallyCenter); sheet.VerticallyCenter = (/*setter*/true); Assert.IsTrue(sheet.VerticallyCenter); sheet.VerticallyCenter = (/*setter*/false); Assert.IsFalse(sheet.VerticallyCenter); Assert.IsFalse(sheet.IsPrintGridlines); sheet.IsPrintGridlines = (/*setter*/true); Assert.IsTrue(sheet.IsPrintGridlines); Assert.IsFalse(sheet.DisplayFormulas); sheet.DisplayFormulas = (/*setter*/true); Assert.IsTrue(sheet.DisplayFormulas); Assert.IsTrue(sheet.DisplayGridlines); sheet.DisplayGridlines = (/*setter*/false); Assert.IsFalse(sheet.DisplayGridlines); //TODO: default "guts" is different in HSSF and XSSF //Assert.IsTrue(sheet.DisplayGuts); sheet.DisplayGuts = (/*setter*/false); Assert.IsFalse(sheet.DisplayGuts); Assert.IsTrue(sheet.DisplayRowColHeadings); sheet.DisplayRowColHeadings = (/*setter*/false); Assert.IsFalse(sheet.DisplayRowColHeadings); //TODO: default "autobreaks" is different in HSSF and XSSF //Assert.IsTrue(sheet.Autobreaks); sheet.Autobreaks = (/*setter*/false); Assert.IsFalse(sheet.Autobreaks); Assert.IsFalse(sheet.ScenarioProtect); //TODO: default "fit-to-page" is different in HSSF and XSSF //Assert.IsFalse(sheet.FitToPage); sheet.FitToPage = (/*setter*/true); Assert.IsTrue(sheet.FitToPage); sheet.FitToPage = (/*setter*/false); Assert.IsFalse(sheet.FitToPage); } public void BaseTestGetSetMargin(double[] defaultMargins) { double marginLeft = defaultMargins[0]; double marginRight = defaultMargins[1]; double marginTop = defaultMargins[2]; double marginBottom = defaultMargins[3]; double marginHeader = defaultMargins[4]; double marginFooter = defaultMargins[5]; IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet 1"); Assert.AreEqual(marginLeft, sheet.GetMargin(MarginType.LeftMargin), 0.0); sheet.SetMargin(MarginType.LeftMargin, 10.0); //left margin is custom, all others are default Assert.AreEqual(10.0, sheet.GetMargin(MarginType.LeftMargin), 0.0); Assert.AreEqual(marginRight, sheet.GetMargin(MarginType.RightMargin), 0.0); Assert.AreEqual(marginTop, sheet.GetMargin(MarginType.TopMargin), 0.0); Assert.AreEqual(marginBottom, sheet.GetMargin(MarginType.BottomMargin), 0.0); sheet.SetMargin(/*setter*/MarginType.RightMargin, 11.0); Assert.AreEqual(11.0, sheet.GetMargin(MarginType.RightMargin), 0.0); sheet.SetMargin(/*setter*/MarginType.TopMargin, 12.0); Assert.AreEqual(12.0, sheet.GetMargin(MarginType.TopMargin), 0.0); sheet.SetMargin(/*setter*/MarginType.BottomMargin, 13.0); Assert.AreEqual(13.0, sheet.GetMargin(MarginType.BottomMargin), 0.0); sheet.SetMargin(MarginType.FooterMargin, 5.6); Assert.AreEqual(5.6, sheet.GetMargin(MarginType.FooterMargin), 0.0); sheet.SetMargin(MarginType.HeaderMargin, 11.5); Assert.AreEqual(11.5, sheet.GetMargin(MarginType.HeaderMargin), 0.0); // incorrect margin constant try { sheet.SetMargin((MarginType)65, 15); Assert.Fail("Expected exception"); } catch (InvalidOperationException e) { Assert.AreEqual("Unknown margin constant: 65", e.Message); } } [Test] public void TestRowBreaks() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); //Sheet#getRowBreaks() returns an empty array if no row breaks are defined Assert.IsNotNull(sheet.RowBreaks); Assert.AreEqual(0, sheet.RowBreaks.Length); sheet.SetRowBreak(1); Assert.AreEqual(1, sheet.RowBreaks.Length); sheet.SetRowBreak(15); Assert.AreEqual(2, sheet.RowBreaks.Length); Assert.AreEqual(1, sheet.RowBreaks[0]); Assert.AreEqual(15, sheet.RowBreaks[1]); sheet.SetRowBreak(1); Assert.AreEqual(2, sheet.RowBreaks.Length); Assert.IsTrue(sheet.IsRowBroken(1)); Assert.IsTrue(sheet.IsRowBroken(15)); //now remove the Created breaks sheet.RemoveRowBreak(1); Assert.AreEqual(1, sheet.RowBreaks.Length); sheet.RemoveRowBreak(15); Assert.AreEqual(0, sheet.RowBreaks.Length); Assert.IsFalse(sheet.IsRowBroken(1)); Assert.IsFalse(sheet.IsRowBroken(15)); } [Test] public void TestColumnBreaks() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); Assert.IsNotNull(sheet.ColumnBreaks); Assert.AreEqual(0, sheet.ColumnBreaks.Length); Assert.IsFalse(sheet.IsColumnBroken(0)); sheet.SetColumnBreak(11); Assert.IsNotNull(sheet.ColumnBreaks); Assert.AreEqual(11, sheet.ColumnBreaks[0]); sheet.SetColumnBreak(12); Assert.AreEqual(2, sheet.ColumnBreaks.Length); Assert.IsTrue(sheet.IsColumnBroken(11)); Assert.IsTrue(sheet.IsColumnBroken(12)); sheet.RemoveColumnBreak((short)11); Assert.AreEqual(1, sheet.ColumnBreaks.Length); sheet.RemoveColumnBreak((short)15); //remove non-existing Assert.AreEqual(1, sheet.ColumnBreaks.Length); sheet.RemoveColumnBreak((short)12); Assert.AreEqual(0, sheet.ColumnBreaks.Length); Assert.IsFalse(sheet.IsColumnBroken(11)); Assert.IsFalse(sheet.IsColumnBroken(12)); } [Test] public void TestGetFirstLastRowNum() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet 1"); sheet.CreateRow(9); sheet.CreateRow(0); sheet.CreateRow(1); Assert.AreEqual(0, sheet.FirstRowNum); Assert.AreEqual(9, sheet.LastRowNum); } [Test] public void TestGetFooter() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet 1"); Assert.IsNotNull(sheet.Footer); sheet.Footer.Center = (/*setter*/"test center footer"); Assert.AreEqual("test center footer", sheet.Footer.Center); } [Test] public void TestGetSetColumnHidden() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet 1"); sheet.SetColumnHidden(2, true); Assert.IsTrue(sheet.IsColumnHidden(2)); } [Test] public void TestProtectSheet() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); Assert.IsFalse(sheet.Protect); sheet.ProtectSheet("Test"); Assert.IsTrue(sheet.Protect); sheet.ProtectSheet(null); Assert.IsFalse(sheet.Protect); } [Test] public void TestCreateFreezePane() { IWorkbook wb = _testDataProvider.CreateWorkbook(); // create a workbook ISheet sheet = wb.CreateSheet(); Assert.IsNull(sheet.PaneInformation); sheet.CreateFreezePane(0, 0); // still null Assert.IsNull(sheet.PaneInformation); sheet.CreateFreezePane(2, 3); PaneInformation info = sheet.PaneInformation; Assert.AreEqual(PaneInformation.PANE_LOWER_RIGHT, info.ActivePane); Assert.AreEqual(3, info.HorizontalSplitPosition); Assert.AreEqual(3, info.HorizontalSplitTopRow); Assert.AreEqual(2, info.VerticalSplitLeftColumn); Assert.AreEqual(2, info.VerticalSplitPosition); sheet.CreateFreezePane(0, 0); // If both colSplit and rowSplit are zero then the existing freeze pane is Removed Assert.IsNull(sheet.PaneInformation); sheet.CreateFreezePane(0, 3); info = sheet.PaneInformation; Assert.AreEqual(PaneInformation.PANE_LOWER_LEFT, info.ActivePane); Assert.AreEqual(3, info.HorizontalSplitPosition); Assert.AreEqual(3, info.HorizontalSplitTopRow); Assert.AreEqual(0, info.VerticalSplitLeftColumn); Assert.AreEqual(0, info.VerticalSplitPosition); sheet.CreateFreezePane(3, 0); info = sheet.PaneInformation; Assert.AreEqual(PaneInformation.PANE_UPPER_RIGHT, info.ActivePane); Assert.AreEqual(0, info.HorizontalSplitPosition); Assert.AreEqual(0, info.HorizontalSplitTopRow); Assert.AreEqual(3, info.VerticalSplitLeftColumn); Assert.AreEqual(3, info.VerticalSplitPosition); sheet.CreateFreezePane(0, 0); // If both colSplit and rowSplit are zero then the existing freeze pane is Removed Assert.IsNull(sheet.PaneInformation); } [Test] public void TestGetRepeatingRowsAndColumns() { IWorkbook wb = _testDataProvider.OpenSampleWorkbook( "RepeatingRowsCols." + _testDataProvider.StandardFileNameExtension); CheckRepeatingRowsAndColumns(wb.GetSheetAt(0), null, null); CheckRepeatingRowsAndColumns(wb.GetSheetAt(1), "1:1", null); CheckRepeatingRowsAndColumns(wb.GetSheetAt(2), null, "A:A"); CheckRepeatingRowsAndColumns(wb.GetSheetAt(3), "2:3", "A:B"); } [Test] public void TestSetRepeatingRowsAndColumnsBug47294() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet1 = wb.CreateSheet(); sheet1.RepeatingRows = (CellRangeAddress.ValueOf("1:4")); Assert.AreEqual("1:4", sheet1.RepeatingRows.FormatAsString()); //must handle sheets with quotas, see Bugzilla #47294 ISheet sheet2 = wb.CreateSheet("My' Sheet"); sheet2.RepeatingRows = (CellRangeAddress.ValueOf("1:4")); Assert.AreEqual("1:4", sheet2.RepeatingRows.FormatAsString()); } [Test] public void TestSetRepeatingRowsAndColumns() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet1 = wb.CreateSheet("Sheet1"); ISheet sheet2 = wb.CreateSheet("Sheet2"); ISheet sheet3 = wb.CreateSheet("Sheet3"); CheckRepeatingRowsAndColumns(sheet1, null, null); sheet1.RepeatingRows = (CellRangeAddress.ValueOf("4:5")); sheet2.RepeatingColumns = (CellRangeAddress.ValueOf("A:C")); sheet3.RepeatingRows = (CellRangeAddress.ValueOf("1:4")); sheet3.RepeatingColumns = (CellRangeAddress.ValueOf("A:A")); CheckRepeatingRowsAndColumns(sheet1, "4:5", null); CheckRepeatingRowsAndColumns(sheet2, null, "A:C"); CheckRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); // write out, read back, and test refrain... wb = _testDataProvider.WriteOutAndReadBack(wb); sheet1 = wb.GetSheetAt(0); sheet2 = wb.GetSheetAt(1); sheet3 = wb.GetSheetAt(2); CheckRepeatingRowsAndColumns(sheet1, "4:5", null); CheckRepeatingRowsAndColumns(sheet2, null, "A:C"); CheckRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); // check removing repeating rows and columns sheet3.RepeatingRows = (null); CheckRepeatingRowsAndColumns(sheet3, null, "A:A"); sheet3.RepeatingColumns = (null); CheckRepeatingRowsAndColumns(sheet3, null, null); } private void CheckRepeatingRowsAndColumns( ISheet s, String expectedRows, String expectedCols) { if (expectedRows == null) { Assert.IsNull(s.RepeatingRows); } else { Assert.AreEqual(expectedRows, s.RepeatingRows.FormatAsString()); } if (expectedCols == null) { Assert.IsNull(s.RepeatingColumns); } else { Assert.AreEqual(expectedCols, s.RepeatingColumns.FormatAsString()); } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Base class for content in text based FrameworkElement. // // History: // 07/2003 : [....] - Created // 02/18/2004: [....] - new TOM method implementation for TextContainer rewrite. // 10/28/2004 : [....] - ContentElements refactoring. // //--------------------------------------------------------------------------- // Enable presharp pragma warning suppress directives. #pragma warning disable 1634, 1691 using System.Collections; using System.ComponentModel; using System.Windows.Controls; using System.Windows.Markup; using System.Windows.Media; using MS.Internal; using MS.Internal.PresentationFramework; using MS.Internal.PtsHost.UnsafeNativeMethods; // PTS restrictions using MS.Internal.Text; namespace System.Windows.Documents { /// <summary> /// TextElement is an base class for content in text based FrameworkElement /// controls such as Text, FlowDocument, or RichTextBox. TextElements span /// other content, applying property values or providing structural information. /// </summary> /// <remarks> /// </remarks> public abstract class TextElement : FrameworkContentElement, IAddChild { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors static TextElement() { // For attached properties metadata specific to the type needs to be set using OverrideMetadata // instead of passing it during property registration. Otherwise all types will get it. PropertyChangedCallback typographyChanged = new PropertyChangedCallback(OnTypographyChanged); // Registering typography properties metadata DependencyProperty[] typographyProperties = Typography.TypographyPropertiesList; for (int i = 0; i < typographyProperties.Length; i++) { typographyProperties[i].OverrideMetadata(typeof(TextElement), new FrameworkPropertyMetadata(typographyChanged)); } } /// <summary> /// Internal constructor to prevent publicly derived classes. /// </summary> internal TextElement() : base() { } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Extracts this TextElement from its current position, if any, and /// inserts it at a specified location. /// </summary> /// <param name="start"> /// New start position. /// </param> /// <param name="end"> /// New end position. /// </param> /// <exception cref="System.ArgumentException"> /// Throws an ArgumentException if start and end are not /// positioned within the same document, or if start is positioned /// after end, or if start == null but end != null. /// </exception> /// <remarks> /// This method extracts the TextElement from its current position, /// leaving behind any contained content, before inserting the TextElement /// at a new location. /// /// If start is null, end must also be null, and the TextElement will /// not be inserted into a new document. /// </remarks> internal void Reposition(TextPointer start, TextPointer end) { TextContainer tree; if (start != null) { ValidationHelper.VerifyPositionPair(start, end); } else if (end != null) { throw new ArgumentException(SR.Get(SRID.TextElement_UnmatchedEndPointer)); } if (start != null) { // start/end must be equally scoped. But we want to discount // this TextElement when considering scoping -- it will be // extracted before the final insert. SplayTreeNode startNode = start.GetScopingNode(); // Suppress presharp 6506: Parameter 'end' to this public method must be validated. // We already validated it indirectly above, when calling ValidationHelper.VerifyPositionPair. #pragma warning suppress 6506 SplayTreeNode endNode = end.GetScopingNode(); if (startNode == _textElementNode) { startNode = _textElementNode.GetContainingNode(); } if (endNode == _textElementNode) { endNode = _textElementNode.GetContainingNode(); } if (startNode != endNode) { throw new ArgumentException(SR.Get(SRID.InDifferentScope, "start", "end")); } } if (this.IsInTree) { tree = EnsureTextContainer(); if (start == null) { // // Case 0: Extract this element from its tree. // tree.BeginChange(); try { tree.ExtractElementInternal(this); } finally { tree.EndChange(); } } else { // Presharp doesn't understand that by design TextPointer.TextContainer can never be null. #pragma warning suppress 6506 if (tree == start.TextContainer) { // // Case 1: extract and insert this TextElement within the same tree. // tree.BeginChange(); try { tree.ExtractElementInternal(this); tree.InsertElementInternal(start, end, this); } finally { tree.EndChange(); } } else { // // Case 2: extract and insert this TextElement from one tree to another tree. // tree.BeginChange(); try { tree.ExtractElementInternal(this); } finally { tree.EndChange(); } // Presharp doesn't understand that by design TextPointer.TextContainer can never be null. #pragma warning suppress 56506 start.TextContainer.BeginChange(); try { start.TextContainer.InsertElementInternal(start, end, this); } finally { start.TextContainer.EndChange(); } } } } else if (start != null) { // // Case 3: insert this TextElement to a new tree (this is no current tree). // start.TextContainer.BeginChange(); try { start.TextContainer.InsertElementInternal(start, end, this); } finally { start.TextContainer.EndChange(); } } } /// <summary> /// Extracts this TextElement and its content from its current /// position, if any, and inserts it at a specified location. /// </summary> /// <param name="textPosition"> /// New position. /// </param> /// <remarks> /// This method extracts the TextElement from its current position, /// including any contained content, before inserting the TextElement /// at a new location. /// /// If textPosition is null, the TextElement will not be inserted into /// a new document. /// </remarks> internal void RepositionWithContent(TextPointer textPosition) { TextContainer tree; if (textPosition == null) { if (this.IsInTree) { tree = EnsureTextContainer(); // Presharp doesn't understand that by design EnsureTextContainer can never return null. #pragma warning suppress 6506 tree.BeginChange(); try { tree.DeleteContentInternal(this.ElementStart, this.ElementEnd); } finally { tree.EndChange(); } } } else { tree = textPosition.TextContainer; // Presharp doesn't understand that by design TextPointer.TextContainer can never be null. #pragma warning suppress 56506 tree.BeginChange(); try { tree.InsertElementInternal(textPosition, textPosition, this); } finally { tree.EndChange(); } } } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties internal static readonly UncommonField<TextElement> ContainerTextElementField = new UncommonField<TextElement>(); /// <summary> /// A TextRange spanning the content of this element. /// </summary> internal TextRange TextRange { get { VerifyAccess(); TextContainer tree = EnsureTextContainer(); TextPointer contentStart = new TextPointer(tree, _textElementNode, ElementEdge.AfterStart, LogicalDirection.Backward); contentStart.Freeze(); TextPointer contentEnd = new TextPointer(tree, _textElementNode, ElementEdge.BeforeEnd, LogicalDirection.Forward); contentEnd.Freeze(); return new TextRange(contentStart, contentEnd); } } /// <summary> /// A TextPointer located just before the start edge of this TextElement. /// </summary> /// <Remarks> /// The TextPointer returned always has its IsFrozen property set true /// and LogicalDirection set Forward. /// </Remarks> public TextPointer ElementStart { get { TextContainer tree; TextPointer elementStart; tree = EnsureTextContainer(); elementStart = new TextPointer(tree, _textElementNode, ElementEdge.BeforeStart, LogicalDirection.Forward); elementStart.Freeze(); return elementStart; } } internal StaticTextPointer StaticElementStart { get { TextContainer tree = EnsureTextContainer(); return new StaticTextPointer(tree, _textElementNode, 0); } } /// <summary> /// A TextPointer located just past the start edge of this TextElement. /// </summary> /// <Remarks> /// The TextPointer returned always has its IsFrozen property set true /// and LogicalDirection set Backward. /// </Remarks> public TextPointer ContentStart { get { TextContainer tree; TextPointer contentStart; tree = EnsureTextContainer(); contentStart = new TextPointer(tree, _textElementNode, ElementEdge.AfterStart, LogicalDirection.Backward); contentStart.Freeze(); return contentStart; } } internal StaticTextPointer StaticContentStart { get { TextContainer tree = EnsureTextContainer(); return new StaticTextPointer(tree, _textElementNode, 1); } } /// <summary> /// A TextPointer located just before the end edge of this TextElement. /// </summary> /// <Remarks> /// The TextPointer returned always has its IsFrozen property set true /// and LogicalDirection set Forward. /// </Remarks> public TextPointer ContentEnd { get { TextContainer tree; TextPointer contentEnd; tree = EnsureTextContainer(); contentEnd = new TextPointer(tree, _textElementNode, ElementEdge.BeforeEnd, LogicalDirection.Forward); contentEnd.Freeze(); return contentEnd; } } internal StaticTextPointer StaticContentEnd { get { TextContainer tree = EnsureTextContainer(); return new StaticTextPointer(tree, _textElementNode, _textElementNode.SymbolCount - 1); } } // Returns true if a position belongs to inner part of this TextElement (ContentStart and ContentEnd including). internal bool Contains(TextPointer position) { TextContainer tree = EnsureTextContainer(); ValidationHelper.VerifyPosition(tree, position); return this.ContentStart.CompareTo(position) <= 0 && this.ContentEnd.CompareTo(position) >= 0; } /// <summary> /// A TextPointer located just after the end edge of this TextElement. /// </summary> /// <Remarks> /// The TextPointer returned always has its IsFrozen property set true /// and LogicalDirection set Backward. /// </Remarks> public TextPointer ElementEnd { get { TextContainer tree; TextPointer elementEnd; tree = EnsureTextContainer(); elementEnd = new TextPointer(tree, _textElementNode, ElementEdge.AfterEnd, LogicalDirection.Backward); elementEnd.Freeze(); return elementEnd; } } internal StaticTextPointer StaticElementEnd { get { TextContainer tree = EnsureTextContainer(); return new StaticTextPointer(tree, _textElementNode, _textElementNode.SymbolCount); } } #region DependencyProperties /// <summary> /// DependencyProperty for <see cref="FontFamily" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty FontFamilyProperty = DependencyProperty.RegisterAttached( "FontFamily", typeof(FontFamily), typeof(TextElement), new FrameworkPropertyMetadata( SystemFonts.MessageFontFamily, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits), new ValidateValueCallback(IsValidFontFamily)); /// <summary> /// The FontFamily property specifies the name of font family. /// </summary> [Localizability( LocalizationCategory.Font, Modifiability = Modifiability.Unmodifiable )] public FontFamily FontFamily { get { return (FontFamily) GetValue(FontFamilyProperty); } set { SetValue(FontFamilyProperty, value); } } /// <summary> /// DependencyProperty setter for <see cref="FontFamily" /> property. /// </summary> /// <param name="element">The element to which to write the attached property.</param> /// <param name="value">The property value to set</param> public static void SetFontFamily(DependencyObject element, FontFamily value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(FontFamilyProperty, value); } /// <summary> /// DependencyProperty getter for <see cref="FontFamily" /> property. /// </summary> /// <param name="element">The element from which to read the attached property.</param> public static FontFamily GetFontFamily(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return (FontFamily)element.GetValue(FontFamilyProperty); } /// <summary> /// DependencyProperty for <see cref="FontStyle" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty FontStyleProperty = DependencyProperty.RegisterAttached( "FontStyle", typeof(FontStyle), typeof(TextElement), new FrameworkPropertyMetadata( SystemFonts.MessageFontStyle, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits)); /// <summary> /// The FontStyle property requests normal, italic, and oblique faces within a font family. /// </summary> public FontStyle FontStyle { get { return (FontStyle) GetValue(FontStyleProperty); } set { SetValue(FontStyleProperty, value); } } /// <summary> /// DependencyProperty setter for <see cref="FontStyle" /> property. /// </summary> /// <param name="element">The element to which to write the attached property.</param> /// <param name="value">The property value to set</param> public static void SetFontStyle(DependencyObject element, FontStyle value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(FontStyleProperty, value); } /// <summary> /// DependencyProperty getter for <see cref="FontStyle" /> property. /// </summary> /// <param name="element">The element from which to read the attached property.</param> public static FontStyle GetFontStyle(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return (FontStyle)element.GetValue(FontStyleProperty); } /// <summary> /// DependencyProperty for <see cref="FontWeight" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty FontWeightProperty = DependencyProperty.RegisterAttached( "FontWeight", typeof(FontWeight), typeof(TextElement), new FrameworkPropertyMetadata( SystemFonts.MessageFontWeight, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits)); /// <summary> /// The FontWeight property specifies the weight of the font. /// </summary> public FontWeight FontWeight { get { return (FontWeight) GetValue(FontWeightProperty); } set { SetValue(FontWeightProperty, value); } } /// <summary> /// DependencyProperty setter for <see cref="FontWeight" /> property. /// </summary> /// <param name="element">The element to which to write the attached property.</param> /// <param name="value">The property value to set</param> public static void SetFontWeight(DependencyObject element, FontWeight value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(FontWeightProperty, value); } /// <summary> /// DependencyProperty getter for <see cref="FontWeight" /> property. /// </summary> /// <param name="element">The element from which to read the attached property.</param> public static FontWeight GetFontWeight(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return (FontWeight)element.GetValue(FontWeightProperty); } /// <summary> /// DependencyProperty for <see cref="FontStretch" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty FontStretchProperty = DependencyProperty.RegisterAttached( "FontStretch", typeof(FontStretch), typeof(TextElement), new FrameworkPropertyMetadata( FontStretches.Normal, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits)); /// <summary> /// The FontStretch property selects a normal, condensed, or extended face from a font family. /// </summary> public FontStretch FontStretch { get { return (FontStretch) GetValue(FontStretchProperty); } set { SetValue(FontStretchProperty, value); } } /// <summary> /// DependencyProperty setter for <see cref="FontStretch" /> property. /// </summary> /// <param name="element">The element to which to write the attached property.</param> /// <param name="value">The property value to set</param> public static void SetFontStretch(DependencyObject element, FontStretch value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(FontStretchProperty, value); } /// <summary> /// DependencyProperty getter for <see cref="FontStretch" /> property. /// </summary> /// <param name="element">The element from which to read the attached property.</param> public static FontStretch GetFontStretch(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return (FontStretch)element.GetValue(FontStretchProperty); } /// <summary> /// DependencyProperty for <see cref="FontSize" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty FontSizeProperty = DependencyProperty.RegisterAttached( "FontSize", typeof(double), typeof(TextElement), new FrameworkPropertyMetadata( SystemFonts.MessageFontSize, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits), new ValidateValueCallback(IsValidFontSize)); /// <summary> /// The FontSize property specifies the size of the font. /// </summary> [TypeConverter(typeof(FontSizeConverter))] [Localizability(LocalizationCategory.None)] public double FontSize { get { return (double) GetValue(FontSizeProperty); } set { SetValue(FontSizeProperty, value); } } /// <summary> /// DependencyProperty setter for <see cref="FontSize" /> property. /// </summary> /// <param name="element">The element to which to write the attached property.</param> /// <param name="value">The property value to set</param> public static void SetFontSize(DependencyObject element, double value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(FontSizeProperty, value); } /// <summary> /// DependencyProperty getter for <see cref="FontSize" /> property. /// </summary> /// <param name="element">The element from which to read the attached property.</param> [TypeConverter(typeof(FontSizeConverter))] public static double GetFontSize(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return (double)element.GetValue(FontSizeProperty); } /// <summary> /// DependencyProperty for <see cref="Foreground" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty ForegroundProperty = DependencyProperty.RegisterAttached( "Foreground", typeof(Brush), typeof(TextElement), new FrameworkPropertyMetadata( Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender | FrameworkPropertyMetadataOptions.Inherits)); /// <summary> /// The Foreground property specifies the foreground brush of an element's text content. /// </summary> public Brush Foreground { get { return (Brush) GetValue(ForegroundProperty); } set { SetValue(ForegroundProperty, value); } } /// <summary> /// DependencyProperty setter for <see cref="Foreground" /> property. /// </summary> /// <param name="element">The element to which to write the attached property.</param> /// <param name="value">The property value to set</param> public static void SetForeground(DependencyObject element, Brush value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(ForegroundProperty, value); } /// <summary> /// DependencyProperty getter for <see cref="Foreground" /> property. /// </summary> /// <param name="element">The element from which to read the attached property.</param> public static Brush GetForeground(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return (Brush)element.GetValue(ForegroundProperty); } /// <summary> /// DependencyProperty for <see cref="Background" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty BackgroundProperty = DependencyProperty.Register("Background", typeof(Brush), typeof(TextElement), new FrameworkPropertyMetadata((Brush)null, FrameworkPropertyMetadataOptions.AffectsRender)); /// <summary> /// The Background property defines the brush used to fill the content area. /// </summary> public Brush Background { get { return (Brush) GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } /// <summary> /// DependencyProperty for <see cref="TextEffectCollection" /> property. /// It doesn't affect layout /// </summary> public static readonly DependencyProperty TextEffectsProperty = DependencyProperty.Register( "TextEffects", typeof(TextEffectCollection), typeof(TextElement), new FrameworkPropertyMetadata( new FreezableDefaultValueFactory(TextEffectCollection.Empty), FrameworkPropertyMetadataOptions.AffectsRender)); /// <summary> /// The TextEffects property specifies effects that are added to the text of an element. /// </summary> public TextEffectCollection TextEffects { get { return (TextEffectCollection) GetValue(TextEffectsProperty); } set { SetValue(TextEffectsProperty, value); } } /// <summary> /// Class providing access to all text typography properties /// </summary> public Typography Typography { get { return new Typography(this); } } #endregion DependencyProperties #region IAddChild ///<summary> /// Called to add the object as a child. ///</summary> ///<param name="value"> /// A Block to add as a child. ///</param> /// <exception cref="System.ArgumentException"> /// o must derive from either UIElement or TextElement, or an /// ArgumentException will be thrown by this method. /// </exception> void IAddChild.AddChild(object value) { Type valueType = value.GetType(); TextElement te = value as TextElement; if (te != null) { TextSchema.ValidateChild(/*parent:*/this, /*child:*/te, true /* throwIfIllegalChild */, true /* throwIfIllegalHyperlinkDescendent */); Append(te); } else { UIElement uie = value as UIElement; if (uie != null) { InlineUIContainer inlineContainer = this as InlineUIContainer; if (inlineContainer != null) { if (inlineContainer.Child != null) { throw new ArgumentException(SR.Get(SRID.TextSchema_ThisInlineUIContainerHasAChildUIElementAlready, this.GetType().Name, ((InlineUIContainer)this).Child.GetType().Name, value.GetType().Name)); } inlineContainer.Child = uie; } else { BlockUIContainer blockContainer = this as BlockUIContainer; if (blockContainer != null) { if (blockContainer.Child != null) { throw new ArgumentException(SR.Get(SRID.TextSchema_ThisBlockUIContainerHasAChildUIElementAlready, this.GetType().Name, ((BlockUIContainer)this).Child.GetType().Name, value.GetType().Name)); } blockContainer.Child = uie; } else { if (TextSchema.IsValidChild(/*parent:*/this, /*childType:*/typeof(InlineUIContainer))) { // Create implicit InlineUIContainer wrapper for this UIElement InlineUIContainer implicitInlineUIContainer = Inline.CreateImplicitInlineUIContainer(this); Append(implicitInlineUIContainer); implicitInlineUIContainer.Child = uie; } else { throw new ArgumentException(SR.Get(SRID.TextSchema_ChildTypeIsInvalid, this.GetType().Name, value.GetType().Name)); } } } } else { throw new ArgumentException(SR.Get(SRID.TextSchema_ChildTypeIsInvalid, this.GetType().Name, value.GetType().Name)); } } } ///<summary> /// Called when text appears under the tag in markup ///</summary> ///<param name="text"> /// Text to Add to this TextElement ///</param> /// <ExternalAPI/> void IAddChild.AddText(string text) { if (text == null) { throw new ArgumentNullException("text"); } // Check if text run is allowed in this element, // and create implicit Run if possible. if (TextSchema.IsValidChild(/*parent:*/this, /*childType:*/typeof(string))) { Append(text); } else { // Implicit Run creation if (TextSchema.IsValidChild(/*parent:*/this, /*childType:*/typeof(Run))) { // NOTE: Do not use new Run(text) constructor to avoid TextContainer creation // which would hit parser perf Run implicitRun = Inline.CreateImplicitRun(this); Append(implicitRun); implicitRun.Text = text; } else { // Otherwise text is not allowed. Throw if it is not a whitespace if (text.Trim().Length > 0) { throw new InvalidOperationException(SR.Get(SRID.TextSchema_TextIsNotAllowed, this.GetType().Name)); } // As to whitespace - it can be simply ignored } } } #endregion IAddChild #region LogicalTree /// <summary> /// Returns enumerator to logical children. /// </summary> protected internal override IEnumerator LogicalChildren { get { return this.IsEmpty ? new RangeContentEnumerator(null, null) : new RangeContentEnumerator(this.ContentStart, this.ContentEnd); } } #endregion LogicalTree #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Notification that a specified property has been invalidated /// </summary> /// <param name="e">EventArgs that contains the property, metadata, old value, and new value for this change</param> protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { // Always call base.OnPropertyChanged, otherwise Property Engine will not work. base.OnPropertyChanged(e); // Note whether or not this change due to a SetValue/ClearValue call. bool localValueChanged = e.NewValueSource == BaseValueSourceInternal.Local || e.OldValueSource == BaseValueSourceInternal.Local; if (localValueChanged || e.IsAValueChange || e.IsASubPropertyChange) { if (this.IsInTree) // No work to do if no one's listening. { // If the modified property affects layout we have some additional // bookkeeping to take care of. FrameworkPropertyMetadata fmetadata = e.Metadata as FrameworkPropertyMetadata; if (fmetadata != null) { bool affectsMeasureOrArrange = fmetadata.AffectsMeasure || fmetadata.AffectsArrange || fmetadata.AffectsParentMeasure || fmetadata.AffectsParentArrange; bool affectsRender = (fmetadata.AffectsRender && (e.IsAValueChange || !fmetadata.SubPropertiesDoNotAffectRender)); if (affectsMeasureOrArrange || affectsRender) { TextContainer textContainer = EnsureTextContainer(); textContainer.BeginChange(); try { if (localValueChanged) { TextTreeUndo.CreatePropertyUndoUnit(this, e); } if (e.IsAValueChange || e.IsASubPropertyChange) { NotifyTypographicPropertyChanged(affectsMeasureOrArrange, localValueChanged, e.Property); } } finally { textContainer.EndChange(); } } } } } } // Notify our TextContainer that a typographic property has changed // value on this TextElement. // This has the side effect of invalidating layout. internal void NotifyTypographicPropertyChanged(bool affectsMeasureOrArrange, bool localValueChanged, DependencyProperty property) { if (!this.IsInTree) // No work to do if no one's listening. { return; } TextContainer tree; TextPointer beforeStart; tree = EnsureTextContainer(); // Take note that something layout related has changed. tree.NextLayoutGeneration(); // Notify any external listeners. if (tree.HasListeners) { // Get the position before the start of this element. beforeStart = new TextPointer(tree, _textElementNode, ElementEdge.BeforeStart, LogicalDirection.Forward); beforeStart.Freeze(); // Raise ContentAffected event that spans entire TextElement (from BeforeStart to AfterEnd). tree.BeginChange(); try { tree.BeforeAddChange(); if (localValueChanged) { tree.AddLocalValueChange(); } tree.AddChange(beforeStart, _textElementNode.SymbolCount, _textElementNode.IMECharCount, PrecursorTextChangeType.PropertyModified, property, !affectsMeasureOrArrange); } finally { tree.EndChange(); } } } #endregion Protected Events //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal static TypographyProperties GetTypographyProperties(DependencyObject element) { TypographyProperties group = new TypographyProperties(); group.SetStandardLigatures((bool) element.GetValue(Typography.StandardLigaturesProperty)); group.SetContextualLigatures((bool) element.GetValue(Typography.ContextualLigaturesProperty)); group.SetDiscretionaryLigatures((bool) element.GetValue(Typography.DiscretionaryLigaturesProperty)); group.SetHistoricalLigatures((bool) element.GetValue(Typography.HistoricalLigaturesProperty)); group.SetAnnotationAlternates((int) element.GetValue(Typography.AnnotationAlternatesProperty)); group.SetContextualAlternates((bool) element.GetValue(Typography.ContextualAlternatesProperty)); group.SetHistoricalForms((bool) element.GetValue(Typography.HistoricalFormsProperty)); group.SetKerning((bool) element.GetValue(Typography.KerningProperty)); group.SetCapitalSpacing((bool) element.GetValue(Typography.CapitalSpacingProperty)); group.SetCaseSensitiveForms((bool) element.GetValue(Typography.CaseSensitiveFormsProperty)); group.SetStylisticSet1((bool) element.GetValue(Typography.StylisticSet1Property)); group.SetStylisticSet2((bool) element.GetValue(Typography.StylisticSet2Property)); group.SetStylisticSet3((bool) element.GetValue(Typography.StylisticSet3Property)); group.SetStylisticSet4((bool) element.GetValue(Typography.StylisticSet4Property)); group.SetStylisticSet5((bool) element.GetValue(Typography.StylisticSet5Property)); group.SetStylisticSet6((bool) element.GetValue(Typography.StylisticSet6Property)); group.SetStylisticSet7((bool) element.GetValue(Typography.StylisticSet7Property)); group.SetStylisticSet8((bool) element.GetValue(Typography.StylisticSet8Property)); group.SetStylisticSet9((bool) element.GetValue(Typography.StylisticSet9Property)); group.SetStylisticSet10((bool) element.GetValue(Typography.StylisticSet10Property)); group.SetStylisticSet11((bool) element.GetValue(Typography.StylisticSet11Property)); group.SetStylisticSet12((bool) element.GetValue(Typography.StylisticSet12Property)); group.SetStylisticSet13((bool) element.GetValue(Typography.StylisticSet13Property)); group.SetStylisticSet14((bool) element.GetValue(Typography.StylisticSet14Property)); group.SetStylisticSet15((bool) element.GetValue(Typography.StylisticSet15Property)); group.SetStylisticSet16((bool) element.GetValue(Typography.StylisticSet16Property)); group.SetStylisticSet17((bool) element.GetValue(Typography.StylisticSet17Property)); group.SetStylisticSet18((bool) element.GetValue(Typography.StylisticSet18Property)); group.SetStylisticSet19((bool) element.GetValue(Typography.StylisticSet19Property)); group.SetStylisticSet20((bool) element.GetValue(Typography.StylisticSet20Property)); group.SetFraction((FontFraction) element.GetValue(Typography.FractionProperty)); group.SetSlashedZero((bool) element.GetValue(Typography.SlashedZeroProperty)); group.SetMathematicalGreek((bool) element.GetValue(Typography.MathematicalGreekProperty)); group.SetEastAsianExpertForms((bool) element.GetValue(Typography.EastAsianExpertFormsProperty)); group.SetVariants((FontVariants) element.GetValue(Typography.VariantsProperty)); group.SetCapitals((FontCapitals) element.GetValue(Typography.CapitalsProperty)); group.SetNumeralStyle((FontNumeralStyle) element.GetValue(Typography.NumeralStyleProperty)); group.SetNumeralAlignment((FontNumeralAlignment) element.GetValue(Typography.NumeralAlignmentProperty)); group.SetEastAsianWidths((FontEastAsianWidths) element.GetValue(Typography.EastAsianWidthsProperty)); group.SetEastAsianLanguage((FontEastAsianLanguage) element.GetValue(Typography.EastAsianLanguageProperty)); group.SetStandardSwashes((int) element.GetValue(Typography.StandardSwashesProperty)); group.SetContextualSwashes((int) element.GetValue(Typography.ContextualSwashesProperty)); group.SetStylisticAlternates((int) element.GetValue(Typography.StylisticAlternatesProperty)); return group; } // ........................................................................ // // Helpers for Text Flow Initialization // // ........................................................................ // Recursively calls EndInit for this element and for all its descendants internal void DeepEndInit() { if (!this.IsInitialized) { if (!this.IsEmpty) { IEnumerator children = this.LogicalChildren; while (children.MoveNext()) { // child.Current could be FrameworkElement, FrameworkContentElement, // or anything else. Only recursively call self for FE & FCE. TextElement child = children.Current as TextElement; if (child != null) { child.DeepEndInit(); } } } // Mark the end of the initialization phase this.EndInit(); Invariant.Assert(this.IsInitialized); } } // Returns the common TextElement ancestor of two TextElements. internal static TextElement GetCommonAncestor(TextElement element1, TextElement element2) { if (element1 != element2) { int depth1 = 0; int depth2 = 0; TextElement element; // Calculate the depths of each TextElement within the tree. for (element = element1; element.Parent is TextElement; element = (TextElement)element.Parent) { depth1++; } for (element = element2; element.Parent is TextElement; element = (TextElement)element.Parent) { depth2++; } // Then walk up until we reach an equal depth. while (depth1 > depth2 && element1 != element2) { element1 = (TextElement)element1.Parent; depth1--; } while (depth2 > depth1 && element1 != element2) { element2 = (TextElement)element2.Parent; depth2--; } // Then, if necessary, keep going up to the root looking for a match. while (element1 != element2) { element1 = element1.Parent as TextElement; element2 = element2.Parent as TextElement; } } Invariant.Assert(element1 == element2); return element1; } /// <summary> /// Derived classes override this method to get notified when a TextContainer /// change affects the text parented by this element. /// </summary> /// <remarks> /// If this TextElement is a Run, this function will be called whenever the text content /// under this Run changes. If this TextElement is not a Run, this function will be called /// most of the time its content changes, but not necessarily always. /// </remarks> internal virtual void OnTextUpdated() { } /// <summary> /// Derived classes override this method to get notified before TextContainer /// causes a logical tree change that affects this element. /// </summary> internal virtual void BeforeLogicalTreeChange() { } /// <summary> /// Derived classes override this method to get notified after TextContainer /// causes a logical tree change that affects this element. /// </summary> internal virtual void AfterLogicalTreeChange() { } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties //------------------------------------------------------ // The TextContainer containing this TextElement. //------------------------------------------------------ internal TextContainer TextContainer { get { return EnsureTextContainer(); } } //------------------------------------------------------ // Emptiness of an element //------------------------------------------------------ internal bool IsEmpty { get { if (_textElementNode == null) return true; return (_textElementNode.ContainedNode == null); } } //------------------------------------------------------ // True if this TextElement is contained within a TextContainer. //------------------------------------------------------ internal bool IsInTree { get { return _textElementNode != null; } } //------------------------------------------------------ // Symbol offset of this.ElementStart. //------------------------------------------------------ internal int ElementStartOffset { get { Invariant.Assert(this.IsInTree, "TextElement is not in any TextContainer, caller should ensure this."); return _textElementNode.GetSymbolOffset(EnsureTextContainer().Generation) - 1; } } //------------------------------------------------------ // Symbol offset of this.ContentStart. //------------------------------------------------------ internal int ContentStartOffset { get { Invariant.Assert(this.IsInTree, "TextElement is not in any TextContainer, caller should ensure this."); return _textElementNode.GetSymbolOffset(EnsureTextContainer().Generation); } } //------------------------------------------------------ // Symbol offset of this.ContentEnd. //------------------------------------------------------ internal int ContentEndOffset { get { Invariant.Assert(this.IsInTree, "TextElement is not in any TextContainer, caller should ensure this."); return _textElementNode.GetSymbolOffset(EnsureTextContainer().Generation) + _textElementNode.SymbolCount - 2; } } //------------------------------------------------------ // Symbol offset of this.ElementEnd. //------------------------------------------------------ internal int ElementEndOffset { get { Invariant.Assert(this.IsInTree, "TextElement is not in any TextContainer, caller should ensure this."); return _textElementNode.GetSymbolOffset(EnsureTextContainer().Generation) + _textElementNode.SymbolCount - 1; } } //------------------------------------------------------ // Symbol count of this TextElement, including start/end // edges. //------------------------------------------------------ internal int SymbolCount { get { return this.IsInTree ? _textElementNode.SymbolCount : 2; } } //------------------------------------------------------ // The node in a TextContainer representing this TextElement. //------------------------------------------------------ internal TextTreeTextElementNode TextElementNode { get { return _textElementNode; } set { _textElementNode = value; } } //------------------------------------------------------------------- // Typography properties group //------------------------------------------------------------------- internal TypographyProperties TypographyPropertiesGroup { get { if (_typographyPropertiesGroup == null) { _typographyPropertiesGroup = GetTypographyProperties(this); } return _typographyPropertiesGroup; } } private static void OnTypographyChanged(DependencyObject element, DependencyPropertyChangedEventArgs e) { ((TextElement) element)._typographyPropertiesGroup = null; } //------------------------------------------------------ // Derived classes override this method if they want // their left edges to be visible to IMEs. This is the // case for structural elements like Paragraph but not // for formatting elements like Inline. //------------------------------------------------------ internal virtual bool IsIMEStructuralElement { get { return false; } } //------------------------------------------------------ // Plain text character count of this element's edges. // Used by the IME to convert Paragraph, TableCell, etc. // into unicode placeholders. //------------------------------------------------------ internal int IMELeftEdgeCharCount { get { int leftEdgeCharCount = 0; if (this.IsIMEStructuralElement) { if (!this.IsInTree) { // IMELeftEdgeCharCount depends on context, has no meaning outside a tree. leftEdgeCharCount = -1; } else { // The first sibling is always invisible to the IME. // This ensures we don't get into trouble creating implicit // content on IME SetText calls. leftEdgeCharCount = this.TextElementNode.IsFirstSibling ? 0 : 1; } } return leftEdgeCharCount; } } //------------------------------------------------------ // Returns true if this node is the leftmost sibling of its parent // and visible to the IMEs (ie, is a Block). // // This is interesting because when we do want to expose // element edges to the IMEs (Blocks, TableCell, etc.) we // have one exception: the first sibling. Edges of first // siblings must be hidden because the TextEditor will // implicitly create first siblings when the IMEs, for example, // insert raw text into a TableCell that lacks a Paragraph. // The IMEs can't handle the implicit edge creation, so we // hide those edges. //------------------------------------------------------ internal virtual bool IsFirstIMEVisibleSibling { get { bool isFirstIMEVisibleSibling = false; if (this.IsIMEStructuralElement) { isFirstIMEVisibleSibling = (this.TextElementNode == null) ? true : this.TextElementNode.IsFirstSibling; } return isFirstIMEVisibleSibling; } } //------------------------------------------------------ // Returns a TextElement immediately following this one // on the same level of siblings. //------------------------------------------------------ internal TextElement NextElement { get { if (!this.IsInTree) { return null; } TextTreeTextElementNode node = _textElementNode.GetNextNode() as TextTreeTextElementNode; return (node != null) ? node.TextElement : null; } } //------------------------------------------------------ // Returns a TextElement immediately preceding this one // on the same level of siblings. //------------------------------------------------------ internal TextElement PreviousElement { get { if (!this.IsInTree) { return null; } TextTreeTextElementNode node = _textElementNode.GetPreviousNode() as TextTreeTextElementNode; return (node != null) ? node.TextElement : null; } } //------------------------------------------------------ // Returns the first TextElement contained by this // TextElement. //------------------------------------------------------ internal TextElement FirstChildElement { get { if (!this.IsInTree) { return null; } TextTreeTextElementNode node = _textElementNode.GetFirstContainedNode() as TextTreeTextElementNode; return (node != null) ? node.TextElement : null; } } //------------------------------------------------------ // Returns the last TextElement contained by this // TextElement. //------------------------------------------------------ internal TextElement LastChildElement { get { if (!this.IsInTree) { return null; } TextTreeTextElementNode node = _textElementNode.GetLastContainedNode() as TextTreeTextElementNode; return (node != null) ? node.TextElement : null; } } #endregion Internal Properties //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods /// <summary> /// Inserts a string at the end of the content spanned by this TextElement. /// </summary> /// <param name="textData"> /// string to insert. /// </param> private void Append(string textData) { TextContainer tree; if (textData == null) { throw new ArgumentNullException("textData"); } tree = EnsureTextContainer(); tree.BeginChange(); try { // tree.InsertTextInternal(new TextPointer(tree, _textElementNode, ElementEdge.BeforeEnd), textData); } finally { tree.EndChange(); } } /// <summary> /// Inserts a TextElement at the end of the content spanned by this /// TextElement. /// </summary> /// <param name="element"> /// TextElement to insert. /// </param> /// <Remarks> /// This method will remove element from TextContainer it was previously /// positioned within. Any content spanned by element will also /// be moved. /// </Remarks> private void Append(TextElement element) { TextContainer tree; TextPointer position; if (element == null) { throw new ArgumentNullException("element"); } tree = EnsureTextContainer(); tree.BeginChange(); try { // position = new TextPointer(tree, _textElementNode, ElementEdge.BeforeEnd); tree.InsertElementInternal(position, position, element); } finally { tree.EndChange(); } } // Demand creates a TextContainer if no tree is associated with this instance. // Otherwise returns the exisiting tree, and clears the tree's DeadPositionList. private TextContainer EnsureTextContainer() { TextContainer tree; TextPointer start; if (this.IsInTree) { tree = _textElementNode.GetTextTree(); tree.EmptyDeadPositionList(); } else { tree = new TextContainer(null, false /* plainTextOnly */); start = tree.Start; tree.BeginChange(); try { tree.InsertElementInternal(start, start, this); } finally { // No event will be raised, since we know there are no listeners yet! tree.EndChange(); } Invariant.Assert(this.IsInTree); } return tree; } private static bool IsValidFontFamily(object o) { FontFamily value = o as FontFamily; return (value != null); } /// <summary> /// <see cref="DependencyProperty.ValidateValueCallback"/> /// </summary> private static bool IsValidFontSize(object value) { double fontSize = (double) value; double minFontSize = TextDpi.MinWidth; double maxFontSize = Math.Min(1000000, PTS.MaxFontSize); if (Double.IsNaN(fontSize)) { return false; } if (fontSize < minFontSize) { return false; } if (fontSize > maxFontSize) { return false; } return true; } #endregion Private methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields // The node in a TextContainer representing this TextElement. private TextTreeTextElementNode _textElementNode; //------------------------------------------------------------------- // Typography Group Property //------------------------------------------------------------------- private TypographyProperties _typographyPropertiesGroup = Typography.Default; #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; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Threading.Tasks; using Windows.Foundation; using Windows.Storage; using Windows.Storage.Search; using Windows.Storage.FileProperties; using Windows.UI.Core; using WinRTFileAttributes = Windows.Storage.FileAttributes; namespace System.IO { internal sealed partial class WinRTFileSystem : FileSystem { public override int MaxPath { get { return Interop.mincore.MAX_PATH; } } public override int MaxDirectoryPath { get { return Interop.mincore.MAX_DIRECTORY_PATH; } } private static System.IO.FileAttributes ConvertFileAttributes(WinRTFileAttributes fileAttributes) { //namespace Windows.Storage //{ // [Flags] // public enum FileAttributes // { // Normal = 0, // ReadOnly = 1, // Directory = 16, // Archive = 32, // Temporary = 256, // LocallyIncomplete = 512, // } //} //namespace System.IO //{ // [Flags] // public enum FileAttributes // { // ReadOnly = 1, // Hidden = 2, // System = 4, // Directory = 16, // Archive = 32, // Device = 64, // Normal = 128, // Temporary = 256, // SparseFile = 512, // ReparsePoint = 1024, // Compressed = 2048, // Offline = 4096, // NotContentIndexed = 8192, // Encrypted = 16384, // } //} // Normal is a special case and happens to have different values in WinRT and Win32. // It's meant to indicate the absence of other flags. On WinRT this logically is 0, // however on Win32 it is represented with a discrete value of 128. return (fileAttributes == WinRTFileAttributes.Normal) ? FileAttributes.Normal : (FileAttributes)fileAttributes; } private static WinRTFileAttributes ConvertFileAttributes(FileAttributes fileAttributes) { // see comment above // Here we make sure to remove the "normal" value since it is redundant // We do not mask unsupported values return (fileAttributes == FileAttributes.Normal) ? WinRTFileAttributes.Normal : (WinRTFileAttributes)(fileAttributes & ~FileAttributes.Normal); } public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { EnsureBackgroundThread(); SynchronousResultOf(CopyFileAsync(sourceFullPath, destFullPath, overwrite)); } private async Task CopyFileAsync(string sourceFullPath, string destFullPath, bool overwrite) { StorageFile file = await StorageFile.GetFileFromPathAsync(sourceFullPath).TranslateWinRTTask(sourceFullPath); string destDirectory, destFileName; PathHelpers.SplitDirectoryFile(destFullPath, out destDirectory, out destFileName); StorageFolder destFolder = await StorageFolder.GetFolderFromPathAsync(destDirectory).TranslateWinRTTask(destDirectory, isDirectory: true); await file.CopyAsync(destFolder, destFileName, overwrite ? NameCollisionOption.ReplaceExisting : NameCollisionOption.FailIfExists).TranslateWinRTTask(sourceFullPath); } public override void CreateDirectory(string fullPath) { EnsureBackgroundThread(); SynchronousResultOf(CreateDirectoryAsync(fullPath, failIfExists: false)); } private async Task<StorageFolder> CreateDirectoryAsync(string fullPath, bool failIfExists) { if (fullPath.Length >= Interop.mincore.MAX_DIRECTORY_PATH) throw new PathTooLongException(SR.IO_PathTooLong); Stack<string> stackDir = new Stack<string>(); StorageFolder workingFolder = null; string workingPath = fullPath; // walk up the path until we can get a directory while (workingFolder == null) { try { workingFolder = await StorageFolder.GetFolderFromPathAsync(workingPath).TranslateWinRTTask(workingPath, isDirectory: true); } catch (IOException) { } catch (UnauthorizedAccessException) { } if (workingFolder == null) { // we couldn't get the directory, we'll need to create it string folderName = null; PathHelpers.SplitDirectoryFile(workingPath, out workingPath, out folderName); if (String.IsNullOrEmpty(folderName)) { // we reached the root and it did not exist. we can't create roots. throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND, workingPath); } stackDir.Push(folderName); Debug.Assert(!String.IsNullOrEmpty(workingPath)); } } Debug.Assert(workingFolder != null); if (failIfExists && (stackDir.Count == 0)) throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_ALREADY_EXISTS, fullPath); // we have work to do. if stackDir is empty it means we were passed a path to an existing directory. while (stackDir.Count > 0) { // use CreationCollisionOption.OpenIfExists to address a race conditions when creating directories workingFolder = await workingFolder.CreateFolderAsync(stackDir.Pop(), CreationCollisionOption.OpenIfExists).TranslateWinRTTask(fullPath, isDirectory: true); } return workingFolder; } public override void DeleteFile(string fullPath) { EnsureBackgroundThread(); SynchronousResultOf(DeleteFileAsync(fullPath)); } private async Task DeleteFileAsync(string fullPath) { try { // Note the absence of TranslateWinRTTask, we translate below in the catch block. StorageFile file = await StorageFile.GetFileFromPathAsync(fullPath).AsTask().ConfigureAwait(false); await file.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().ConfigureAwait(false); } catch (Exception exception) { // For consistency with Win32 we ignore missing files if (exception.HResult != HResults.ERROR_FILE_NOT_FOUND) throw exception.TranslateWinRTException(fullPath); } } public override bool DirectoryExists(string fullPath) { EnsureBackgroundThread(); return SynchronousResultOf(DirectoryExistsAsync(fullPath)); } private async Task<bool> DirectoryExistsAsync(string fullPath) { string directoryPath = null, fileName = null; PathHelpers.SplitDirectoryFile(fullPath, out directoryPath, out fileName); // Rather than call await StorageFolder.GetFolderFromPathAsync(fullPath); and catch FileNotFoundException // we try to avoid the exception by calling TryGetItemAsync. // We can still hit an exception if the parent directory doesn't exist but it does provide better performance // for the existing parent/non-existing directory case and avoids a first chance exception which is a developer // pain point. StorageFolder parent = null; try { parent = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath, isDirectory: true); } catch (IOException) { } catch (UnauthorizedAccessException) { } if (String.IsNullOrEmpty(fileName)) { // we were given a root return parent != null; } if (parent != null) { StorageFolder folder = await parent.TryGetItemAsync(fileName).TranslateWinRTTask(fullPath, isDirectory: true) as StorageFolder; return folder != null; } else { // it's possible we don't have access to the parent but do have access to this folder try { StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(fullPath).TranslateWinRTTask(fullPath, isDirectory: true); return folder != null; } catch (IOException) { } catch (UnauthorizedAccessException) { } } return false; } public override IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { IReadOnlyList<IStorageItem> storageFiles = SynchronousResultOf(EnumerateFileQuery(fullPath, searchPattern, searchOption, searchTarget)); return IteratePathsFromStorageItems(storageFiles); } public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { IReadOnlyList<IStorageItem> storageFiles = SynchronousResultOf(EnumerateFileQuery(fullPath, searchPattern, searchOption, searchTarget)); return IterateFileSystemInfosFromStorageItems(storageFiles); } /// <summary> /// Translates IStorageItems into FileSystemInfos and yields the results. /// </summary> private static IEnumerable<FileSystemInfo> IterateFileSystemInfosFromStorageItems(IReadOnlyList<IStorageItem> storageFiles) { int count = storageFiles.Count; for (int i = 0; i < count; i++) { if (storageFiles[i].IsOfType(StorageItemTypes.Folder)) { yield return new DirectoryInfo(storageFiles[i].Path); } else // If it is neither a File nor folder then we treat it as a File. { yield return new FileInfo(storageFiles[i].Path); } } } /// <summary> /// Translates IStorageItems into string paths and yields the results. /// </summary> private static IEnumerable<string> IteratePathsFromStorageItems(IReadOnlyList<IStorageItem> storageFiles) { int count = storageFiles.Count; for (int i = 0; i < count; i++) { yield return storageFiles[i].Path; } } private async static Task<IReadOnlyList<IStorageItem>> EnumerateFileQuery(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { // Get a StorageFolder for "path" string fullPath = Path.GetFullPath(path); StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(fullPath).TranslateWinRTTask(fullPath, isDirectory: true); // Construct a query for the search. QueryOptions query = new QueryOptions(); // Translate SearchOption into FolderDepth query.FolderDepth = searchOption == SearchOption.AllDirectories ? FolderDepth.Deep : FolderDepth.Shallow; // Construct an AQS filter string normalizedSearchPattern = PathHelpers.NormalizeSearchPattern(searchPattern); if (normalizedSearchPattern.Length == 0) { // An empty searchPattern will return no results and requires no AQS parsing. return new IStorageItem[0]; } else { // Parse the query as an ItemPathDisplay filter. string searchPath = PathHelpers.GetFullSearchString(fullPath, normalizedSearchPattern); string aqs = "System.ItemPathDisplay:~\"" + searchPath + "\""; query.ApplicationSearchFilter = aqs; // If the filtered path is deeper than the given user path, we need to get a new folder for it. // This occurs when someone does something like Enumerate("C:\first\second\", "C:\first\second\third\*"). // When AllDirectories is set this isn't an issue, but for TopDirectoryOnly we have to do some special work // to make sure something is actually returned when the searchPattern is a subdirectory of the path. // To do this, we attempt to get a new StorageFolder for the subdirectory and return an empty enumerable // if we can't. string searchPatternDirName = Path.GetDirectoryName(normalizedSearchPattern); string userPath = string.IsNullOrEmpty(searchPatternDirName) ? fullPath : Path.Combine(fullPath, searchPatternDirName); if (userPath != folder.Path) { folder = await StorageFolder.GetFolderFromPathAsync(userPath).TranslateWinRTTask(userPath, isDirectory: true); } } // Execute our built query if (searchTarget == SearchTarget.Files) { StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(query); return await queryResult.GetFilesAsync().TranslateWinRTTask(folder.Path, isDirectory: true); } else if (searchTarget == SearchTarget.Directories) { StorageFolderQueryResult queryResult = folder.CreateFolderQueryWithOptions(query); return await queryResult.GetFoldersAsync().TranslateWinRTTask(folder.Path, isDirectory: true); } else { StorageItemQueryResult queryResult = folder.CreateItemQueryWithOptions(query); return await queryResult.GetItemsAsync().TranslateWinRTTask(folder.Path, isDirectory: true); } } public override bool FileExists(string fullPath) { EnsureBackgroundThread(); return SynchronousResultOf(FileExistsAsync(fullPath)); } private async Task<bool> FileExistsAsync(string fullPath) { string directoryPath = null, fileName = null; PathHelpers.SplitDirectoryFile(fullPath, out directoryPath, out fileName); if (String.IsNullOrEmpty(fileName)) { // No filename was provided return false; } // Rather than call await StorageFile.GetFileFromPathAsync(fullPath); and catch FileNotFoundException // we try to avoid the exception by calling TryGetItemAsync. // We can still hit an exception if the directory doesn't exist but it does provide better performance // for the existing folder/non-existing file case and avoids a first chance exception which is a developer // pain point. StorageFolder parent = null; try { parent = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath); } catch (IOException) { } catch (UnauthorizedAccessException) { } StorageFile file = null; if (parent != null) { // The expectation is that this API will never throw, thus it is missing TranslateWinRTTask file = await parent.TryGetItemAsync(fileName).TranslateWinRTTask(fullPath) as StorageFile; } else { // it's possible we don't have access to the parent but do have access to this file try { file = await StorageFile.GetFileFromPathAsync(fullPath).TranslateWinRTTask(fullPath); } catch (IOException) { } catch (UnauthorizedAccessException) { } } return (file != null) ? file.IsAvailable : false; } public override FileAttributes GetAttributes(string fullPath) { EnsureBackgroundThread(); return SynchronousResultOf(GetAttributesAsync(fullPath)); } private async Task<FileAttributes> GetAttributesAsync(string fullPath) { IStorageItem item = await GetStorageItemAsync(fullPath).ConfigureAwait(false); return ConvertFileAttributes(item.Attributes); } public override DateTimeOffset GetCreationTime(string fullPath) { EnsureBackgroundThread(); return SynchronousResultOf(GetCreationTimeAsync(fullPath)); } private async Task<DateTimeOffset> GetCreationTimeAsync(string fullPath) { IStorageItem item = await GetStorageItemAsync(fullPath).ConfigureAwait(false); return item.DateCreated; } public override string GetCurrentDirectory() { throw new PlatformNotSupportedException(); } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return new WinRTFileSystemObject(fullPath, asDirectory); } public override DateTimeOffset GetLastAccessTime(string fullPath) { EnsureBackgroundThread(); return SynchronousResultOf(GetLastAccessTimeAsync(fullPath)); } private async Task<DateTimeOffset> GetLastAccessTimeAsync(string fullPath) { IStorageItem item = await GetStorageItemAsync(fullPath).ConfigureAwait(false); return await GetLastAccessTimeAsync(item).ConfigureAwait(false); } // declare a static to avoid unnecessary heap allocations private static readonly string[] s_dateAccessedKey = { "System.DateAccessed" }; private static async Task<DateTimeOffset> GetLastAccessTimeAsync(IStorageItem item) { BasicProperties properties = await item.GetBasicPropertiesAsync().TranslateWinRTTask(item.Path); var propertyMap = await properties.RetrievePropertiesAsync(s_dateAccessedKey).TranslateWinRTTask(item.Path); // shell doesn't expose this metadata on all item types if (propertyMap.ContainsKey(s_dateAccessedKey[0])) { return (DateTimeOffset)propertyMap[s_dateAccessedKey[0]]; } // fallback to modified date return properties.DateModified; } public override DateTimeOffset GetLastWriteTime(string fullPath) { EnsureBackgroundThread(); return SynchronousResultOf(GetLastWriteTimeAsync(fullPath)); } private async Task<DateTimeOffset> GetLastWriteTimeAsync(string fullPath) { IStorageItem item = await GetStorageItemAsync(fullPath).ConfigureAwait(false); return await GetLastWriteTimeAsync(item).ConfigureAwait(false); } private static async Task<DateTimeOffset> GetLastWriteTimeAsync(IStorageItem item) { BasicProperties properties = await item.GetBasicPropertiesAsync().TranslateWinRTTask(item.Path); return properties.DateModified; } private static async Task<IStorageItem> GetStorageItemAsync(string fullPath) { string directoryPath, itemName; PathHelpers.SplitDirectoryFile(fullPath, out directoryPath, out itemName); StorageFolder parent = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath, isDirectory: true); if (String.IsNullOrEmpty(itemName)) return parent; return await parent.GetItemAsync(itemName).TranslateWinRTTask(fullPath); } public override void MoveDirectory(string sourceFullPath, string destFullPath) { EnsureBackgroundThread(); SynchronousResultOf(MoveDirectoryAsync(sourceFullPath, destFullPath)); } private async Task MoveDirectoryAsync(string sourceFullPath, string destFullPath) { StorageFolder sourceFolder = await StorageFolder.GetFolderFromPathAsync(sourceFullPath).TranslateWinRTTask(sourceFullPath, isDirectory: true); // WinRT doesn't support move, only rename // If parents are the same, just rename. string sourceParent, sourceFolderName, destParent, destFolderName; PathHelpers.SplitDirectoryFile(sourceFullPath, out sourceParent, out sourceFolderName); PathHelpers.SplitDirectoryFile(destFullPath, out destParent, out destFolderName); // same parent folder if (String.Equals(sourceParent, destParent, StringComparison.OrdinalIgnoreCase)) { // not the same subfolder if (!String.Equals(sourceFolderName, destFolderName, StringComparison.OrdinalIgnoreCase)) { await sourceFolder.RenameAsync(destFolderName).TranslateWinRTTask(destFullPath, isDirectory: true); } // else : nothing to do } else { // Otherwise, create the destination and move each item recursively. // We could do a copy, which would be safer in case of a failure // We do a move because it has the perf characteristics that match the win32 move StorageFolder destFolder = await CreateDirectoryAsync(destFullPath, failIfExists: true).ConfigureAwait(false); await MoveDirectoryAsync(sourceFolder, destFolder).ConfigureAwait(false); } } private async Task MoveDirectoryAsync(StorageFolder sourceFolder, StorageFolder destFolder) { foreach (var sourceFile in await sourceFolder.GetFilesAsync().TranslateWinRTTask(sourceFolder.Path, isDirectory: true)) { await sourceFile.MoveAsync(destFolder).TranslateWinRTTask(sourceFile.Path); } foreach (var sourceSubFolder in await sourceFolder.GetFoldersAsync().TranslateWinRTTask(sourceFolder.Path, isDirectory: true)) { StorageFolder destSubFolder = await destFolder.CreateFolderAsync(sourceSubFolder.Name).TranslateWinRTTask(destFolder.Path, isDirectory: true); // Recursively move sub-directory await MoveDirectoryAsync(sourceSubFolder, destSubFolder).ConfigureAwait(false); } // sourceFolder should now be empty await sourceFolder.DeleteAsync(StorageDeleteOption.PermanentDelete).TranslateWinRTTask(sourceFolder.Path, isDirectory: true); } public override void MoveFile(string sourceFullPath, string destFullPath) { EnsureBackgroundThread(); SynchronousResultOf(MoveFileAsync(sourceFullPath, destFullPath)); } private async Task MoveFileAsync(string sourceFullPath, string destFullPath) { StorageFile file = await StorageFile.GetFileFromPathAsync(sourceFullPath).TranslateWinRTTask(sourceFullPath); string destDirectory, destFileName; PathHelpers.SplitDirectoryFile(destFullPath, out destDirectory, out destFileName); // Win32 MoveFileEx will return success if source and destination are the same. // Comparison is safe here as the caller has normalized both paths. if (!sourceFullPath.Equals(destFullPath, StringComparison.OrdinalIgnoreCase)) { StorageFolder destFolder = await StorageFolder.GetFolderFromPathAsync(destDirectory).TranslateWinRTTask(destDirectory, isDirectory: true); await file.MoveAsync(destFolder, destFileName, NameCollisionOption.FailIfExists).TranslateWinRTTask(sourceFullPath); } } public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) { EnsureBackgroundThread(); return SynchronousResultOf(OpenAsync(fullPath, mode, access, share, bufferSize, options, parent)); } private async Task<FileStreamBase> OpenAsync(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) { // When trying to open the root directory, we need to throw an Access Denied if (PathInternal.GetRootLength(fullPath) == fullPath.Length) throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_ACCESS_DENIED, fullPath); // Win32 CreateFile returns ERROR_PATH_NOT_FOUND when given a path that ends with '\' if (PathHelpers.EndsInDirectorySeparator(fullPath)) throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND, fullPath); StorageFile file = null; // FileMode if (mode == FileMode.Open || mode == FileMode.Truncate) { file = await StorageFile.GetFileFromPathAsync(fullPath).TranslateWinRTTask(fullPath); } else { CreationCollisionOption collisionOptions; switch (mode) { case FileMode.Create: collisionOptions = CreationCollisionOption.ReplaceExisting; break; case FileMode.CreateNew: collisionOptions = CreationCollisionOption.FailIfExists; break; case FileMode.Append: case FileMode.OpenOrCreate: default: collisionOptions = CreationCollisionOption.OpenIfExists; break; } string directoryPath, fileName; PathHelpers.SplitDirectoryFile(fullPath, out directoryPath, out fileName); StorageFolder directory = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath, isDirectory: true); file = await directory.CreateFileAsync(fileName, collisionOptions).TranslateWinRTTask(fullPath); } // FileAccess: WinRT doesn't support FileAccessMode.Write so we upgrade to ReadWrite FileAccessMode accessMode = ((access & FileAccess.Write) != 0) ? FileAccessMode.ReadWrite : FileAccessMode.Read; // FileShare: cannot translate StorageFile uses a different sharing model (oplocks) that is controlled via FileAccessMode // FileOptions: ignore most values of FileOptions as they are hints and are not supported by WinRT. // FileOptions.Encrypted is not a hint, and not supported by WinRT, but there is precedent for ignoring this (FAT). // FileOptions.DeleteOnClose should result in an UnauthorizedAccessException when // opening a file that can only be read, but we cannot safely reproduce that behavior // in WinRT without actually deleting the file. // Instead the failure will occur in the finalizer for WinRTFileStream and be ignored. // open our stream Stream stream = (await file.OpenAsync(accessMode).TranslateWinRTTask(fullPath)).AsStream(bufferSize); if (mode == FileMode.Append) { // seek to end. stream.Seek(0, SeekOrigin.End); } else if (mode == FileMode.Truncate) { // truncate stream to 0 stream.SetLength(0); } return new WinRTFileStream(stream, file, access, options, parent); } public override void RemoveDirectory(string fullPath, bool recursive) { EnsureBackgroundThread(); SynchronousResultOf(RemoveDirectoryAsync(fullPath, recursive)); } private async Task RemoveDirectoryAsync(string fullPath, bool recursive) { StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(fullPath).TranslateWinRTTask(fullPath, isDirectory: true); // StorageFolder.DeleteAsync will always be recursive. Detect a non-empty folder up front and throw. if (!recursive && (await folder.GetItemsAsync()).Count != 0) throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_DIR_NOT_EMPTY, fullPath); // StorageFolder.Delete ignores readonly attribute. Detect and throw. if ((folder.Attributes & WinRTFileAttributes.ReadOnly) == WinRTFileAttributes.ReadOnly) throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); StorageFolder parentFolder = await folder.GetParentAsync().TranslateWinRTTask(fullPath, isDirectory: true); // StorageFolder.Delete throws on hidden directories but we cannot prevent it. await folder.DeleteAsync(StorageDeleteOption.PermanentDelete).TranslateWinRTTask(fullPath, isDirectory: true); // WinRT will ignore failures to delete in cases where files are in use. // Throw if the folder still remains after successful DeleteAsync if (null != await (parentFolder.TryGetItemAsync(folder.Name))) throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_DIR_NOT_EMPTY, fullPath); } public override void SetAttributes(string fullPath, FileAttributes attributes) { EnsureBackgroundThread(); SynchronousResultOf(SetAttributesAsync(fullPath, attributes)); } private async Task SetAttributesAsync(string fullPath, FileAttributes attributes) { IStorageItem item = await GetStorageItemAsync(fullPath).ConfigureAwait(false); await SetAttributesAsync(item, attributes).ConfigureAwait(false); } private static async Task SetAttributesAsync(IStorageItem item, FileAttributes attributes) { BasicProperties basicProperties = await item.GetBasicPropertiesAsync().TranslateWinRTTask(item.Path); // This works for only a subset of attributes, unsupported attributes are ignored. // We don't mask the attributes since WinRT just ignores the unsupported ones and flowing // them enables possible lightup in the future. var property = new KeyValuePair<string, object>("System.FileAttributes", (UInt32)ConvertFileAttributes(attributes)); try { await basicProperties.SavePropertiesAsync(new[] { property }).AsTask().ConfigureAwait(false); } catch (Exception exception) { if (exception.HResult != HResults.ERROR_INVALID_PARAMETER) throw new ArgumentException(SR.Arg_InvalidFileAttrs); throw exception.TranslateWinRTException(item.Path); } } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { // intentionally noop : not supported // "System.DateCreated" property is readonly } public override void SetCurrentDirectory(string fullPath) { throw new PlatformNotSupportedException(); } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { // intentionally noop // "System.DateAccessed" property is readonly } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { // intentionally noop : not supported // "System.DateModified" property is readonly } #region Task Utility private static void EnsureBackgroundThread() { // WinRT async operations on brokered files require posting a message back to the UI thread. // If we were to run a sync method on the UI thread we'd deadlock. Throw instead. if (IsUIThread()) throw new InvalidOperationException(SR.IO_SyncOpOnUIThread); } private static bool IsUIThread() { CoreWindow window = CoreWindow.GetForCurrentThread(); return window != null && window.Dispatcher != null && window.Dispatcher.HasThreadAccess; } private static void SynchronousResultOf(Task task) { WaitForTask(task); } private static TResult SynchronousResultOf<TResult>(Task<TResult> task) { WaitForTask(task); return task.Result; } // this needs to be separate from SynchronousResultOf so that SynchronousResultOf<T> can call it. private static void WaitForTask(Task task) { // This should never be called from the UI thread since it can deadlock // Throwing here, however, is too late since work has already been started // Instead we assert here so that our tests can catch cases where we forgot to // call EnsureBackgroundThread before starting the task. Debug.Assert(!IsUIThread()); task.GetAwaiter().GetResult(); } #endregion Task Utility } }
/* * Utils.cs * SnowplowTracker * * Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. * * Authors: Joshua Beemster, Paul Boocock * Copyright: Copyright (c) 2015-2019 Snowplow Analytics Ltd * License: Apache License Version 2.0 */ using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using System.Web; using Newtonsoft.Json; namespace SnowplowTracker { public class Utils { /// <summary> /// Returns the current time since the UNIX Epoch /// </summary> /// <returns>the time since UNIX Epoch in milliseconds</returns> public static long GetTimestamp() { return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds; } /// <summary> /// Returns a newly generated GUID string /// </summary> /// <returns>a new GUID</returns> public static string GetGUID() { return Guid.NewGuid().ToString(); } /// <summary> /// Returns a dictionary converted to a JSON String /// </summary> /// <returns>the dictionary as a JSON String</returns> public static string DictToJSONString(IDictionary dict) { string result = JsonConvert.SerializeObject(dict); if (result == null) { Log.Error("Utils: Error serializing dictionary to JSON string."); } return result; } /// <summary> /// Returns a dictionary converted from a JSON String /// </summary> /// <returns>the dictionary from the JSON String</returns> public static Dictionary<string, object> JSONStringToDict(string jsonString) { var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString); if (result == null) { Log.Error("Utils: Error deserializing JSON string to dictionary."); } return result; } /// <summary> /// Gets the length of the UTF8 String. /// </summary> /// <returns>The UTF8 length</returns> /// <param name="str">String to get the length of</param> public static long GetUTF8Length(string str) { return System.Text.Encoding.UTF8.GetByteCount(str); } /// <summary> /// Base64 encodes a string /// </summary> /// <returns>the encoded string</returns> public static string Base64EncodeString(string stringToEncode) { byte[] plainTextBytes = StringToBytes(stringToEncode); return System.Convert.ToBase64String(plainTextBytes); } /// <summary> /// Converts an event from a dictionary to a querystring /// </summary> /// <param name="payload">The event to convert</param> /// <returns>Querystring of the form "?e=pv&tna=cf&..."</returns> public static string ToQueryString(Dictionary<string, object> payload) { List<string> encodedKvPairs = new List<string>(); foreach (KeyValuePair<string, object> kvPair in payload) { encodedKvPairs.Add(string.Format("{0}={1}", HttpUtility.UrlEncode(kvPair.Key), HttpUtility.UrlEncode((string)kvPair.Value))); } return String.Format("?{0}", String.Join("&", encodedKvPairs.ToArray())); } /// <summary> /// Strings to bytes. /// </summary> /// <returns>Converts strings to bytes and returns the byte array</returns> /// <param name="str">The string to convert</param> public static byte[] StringToBytes(string str) { return System.Text.Encoding.UTF8.GetBytes(str); } /// <summary> /// Serialize the specified dictionary. /// </summary> /// <param name="dict">The dictionary to serialize</param> public static byte[] SerializeDictionary(Dictionary<string, object> dict) { try { BinaryFormatter binFormatter = new BinaryFormatter(); MemoryStream mStream = new MemoryStream(); binFormatter.Serialize(mStream, dict); return mStream.ToArray(); } catch (Exception e) { Log.Error("EventStore: Error serializing Dictionary: " + e.Message); return null; } } /// <summary> /// Deserialize the specified bytes. /// </summary> /// <param name="bytes">The byte array to deserialize</param> public static Dictionary<string, object> DeserializeDictionary(byte[] bytes) { try { BinaryFormatter binFormatter = new BinaryFormatter(); MemoryStream mStream = new MemoryStream(bytes); return (Dictionary<string, object>)binFormatter.Deserialize(mStream); } catch (Exception e) { Log.Error("EventStore: Error de-serializing byte array: " + e.Message); return null; } } /// <summary> /// Checks the argument providied and will throw an exception if it fails. /// </summary> /// <param name="argument">If set to <c>true</c> argument.</param> /// <param name="message">Message to print in failure case.</param> public static void CheckArgument(bool argument, string message) { if (!argument) { throw new ArgumentException(message); } } /// <summary> /// Writes the dictionary to file. /// </summary> /// <returns><c>true</c>, if dictionary to file was written, <c>false</c> otherwise.</returns> /// <param name="path">Path.</param> /// <param name="dictionary">Dictionary.</param> public static bool WriteDictionaryToFile(string path, Dictionary<string, object> dictionary) { try { File.WriteAllBytes(path, SerializeDictionary(dictionary)); return true; } catch (Exception e) { Log.Error("Utils: Error writing dictionary to file: " + e.StackTrace); return false; } } /// <summary> /// Reads the dictionary from file. /// </summary> /// <returns>The dictionary from file.</returns> /// <param name="path">Path.</param> public static Dictionary<string, object> ReadDictionaryFromFile(string path) { try { byte[] bytes = File.ReadAllBytes(path); return DeserializeDictionary(bytes); } catch (Exception e) { Log.Error("Utils: Error reading dictionary from file: " + e.StackTrace); return null; } } /// <summary> /// Determines if is time in range the specified startTime checkTime range. /// </summary> /// <returns><c>true</c> if is time in range the specified startTime checkTime range; otherwise, <c>false</c>.</returns> /// <param name="startTime">Start time.</param> /// <param name="checkTime">Check time.</param> /// <param name="range">Range.</param> public static bool IsTimeInRange(long startTime, long checkTime, long range) { return (startTime > (checkTime - range)); } } }
using System; using System.Diagnostics; using System.Text; using u8 = System.Byte; namespace Community.CsharpSqlite { using sqlite3_int64 = System.Int64; using sqlite3_stmt = Sqlite3.Vdbe; public partial class Sqlite3 { /* ** 2005 July 8 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code associated with the ANALYZE command. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ #if !SQLITE_OMIT_ANALYZE //#include "sqliteInt.h" /* ** This routine generates code that opens the sqlite_stat1 table for ** writing with cursor iStatCur. If the library was built with the ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is ** opened for writing using cursor (iStatCur+1) ** ** If the sqlite_stat1 tables does not previously exist, it is created. ** Similarly, if the sqlite_stat2 table does not exist and the library ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. ** ** Argument zWhere may be a pointer to a buffer containing a table name, ** or it may be a NULL pointer. If it is not NULL, then all entries in ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated ** with the named table are deleted. If zWhere==0, then code is generated ** to delete all stat table entries. */ public struct _aTable { public string zName; public string zCols; public _aTable( string zName, string zCols ) { this.zName = zName; this.zCols = zCols; } }; static _aTable[] aTable = new _aTable[]{ new _aTable( "sqlite_stat1", "tbl,idx,stat" ), #if SQLITE_ENABLE_STAT2 new _aTable( "sqlite_stat2", "tbl,idx,sampleno,sample" ), #endif }; static void openStatTable( Parse pParse, /* Parsing context */ int iDb, /* The database we are looking in */ int iStatCur, /* Open the sqlite_stat1 table on this cursor */ string zWhere, /* Delete entries for this table or index */ string zWhereType /* Either "tbl" or "idx" */ ) { int[] aRoot = new int[] { 0, 0 }; u8[] aCreateTbl = new u8[] { 0, 0 }; int i; sqlite3 db = pParse.db; Db pDb; Vdbe v = sqlite3GetVdbe( pParse ); if ( v == null ) return; Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); Debug.Assert( sqlite3VdbeDb( v ) == db ); pDb = db.aDb[iDb]; for ( i = 0; i < ArraySize( aTable ); i++ ) { string zTab = aTable[i].zName; Table pStat; if ( ( pStat = sqlite3FindTable( db, zTab, pDb.zName ) ) == null ) { /* The sqlite_stat[12] table does not exist. Create it. Note that a ** side-effect of the CREATE TABLE statement is to leave the rootpage ** of the new table in register pParse.regRoot. This is important ** because the OpenWrite opcode below will be needing it. */ sqlite3NestedParse( pParse, "CREATE TABLE %Q.%s(%s)", pDb.zName, zTab, aTable[i].zCols ); aRoot[i] = pParse.regRoot; aCreateTbl[i] = 1; } else { /* The table already exists. If zWhere is not NULL, delete all entries ** associated with the table zWhere. If zWhere is NULL, delete the ** entire contents of the table. */ aRoot[i] = pStat.tnum; sqlite3TableLock( pParse, iDb, aRoot[i], 1, zTab ); if ( !String.IsNullOrEmpty( zWhere ) ) { sqlite3NestedParse( pParse, "DELETE FROM %Q.%s WHERE %s=%Q", pDb.zName, zTab, zWhereType, zWhere ); } else { /* The sqlite_stat[12] table already exists. Delete all rows. */ sqlite3VdbeAddOp2( v, OP_Clear, aRoot[i], iDb ); } } } /* Open the sqlite_stat[12] tables for writing. */ for ( i = 0; i < ArraySize( aTable ); i++ ) { sqlite3VdbeAddOp3( v, OP_OpenWrite, iStatCur + i, aRoot[i], iDb ); sqlite3VdbeChangeP4( v, -1, 3, P4_INT32 ); sqlite3VdbeChangeP5( v, aCreateTbl[i] ); } } /* ** Generate code to do an analysis of all indices associated with ** a single table. */ static void analyzeOneTable( Parse pParse, /* Parser context */ Table pTab, /* Table whose indices are to be analyzed */ Index pOnlyIdx, /* If not NULL, only analyze this one index */ int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */ int iMem /* Available memory locations begin here */ ) { sqlite3 db = pParse.db; /* Database handle */ Index pIdx; /* An index to being analyzed */ int iIdxCur; /* Cursor open on index being analyzed */ Vdbe v; /* The virtual machine being built up */ int i; /* Loop counter */ int topOfLoop; /* The top of the loop */ int endOfLoop; /* The end of the loop */ int jZeroRows = -1; /* Jump from here if number of rows is zero */ int iDb; /* Index of database containing pTab */ int regTabname = iMem++; /* Register containing table name */ int regIdxname = iMem++; /* Register containing index name */ int regSampleno = iMem++; /* Register containing next sample number */ int regCol = iMem++; /* Content of a column analyzed table */ int regRec = iMem++; /* Register holding completed record */ int regTemp = iMem++; /* Temporary use register */ int regRowid = iMem++; /* Rowid for the inserted record */ #if SQLITE_ENABLE_STAT2 int addr = 0; /* Instruction address */ int regTemp2 = iMem++; /* Temporary use register */ int regSamplerecno = iMem++; /* Index of next sample to record */ int regRecno = iMem++; /* Current sample index */ int regLast = iMem++; /* Index of last sample to record */ int regFirst = iMem++; /* Index of first sample to record */ #endif v = sqlite3GetVdbe( pParse ); if ( v == null || NEVER( pTab == null ) ) { return; } if ( pTab.tnum == 0 ) { /* Do not gather statistics on views or virtual tables */ return; } if ( pTab.zName.StartsWith( "sqlite_", StringComparison.OrdinalIgnoreCase ) ) { /* Do not gather statistics on system tables */ return; } Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); Debug.Assert( iDb >= 0 ); Debug.Assert( sqlite3SchemaMutexHeld(db, iDb, null) ); #if !SQLITE_OMIT_AUTHORIZATION if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab.zName, 0, db.aDb[iDb].zName ) ){ return; } #endif /* Establish a read-lock on the table at the shared-cache level. */ sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName ); iIdxCur = pParse.nTab++; sqlite3VdbeAddOp4( v, OP_String8, 0, regTabname, 0, pTab.zName, 0 ); for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext ) { int nCol; KeyInfo pKey; if ( pOnlyIdx != null && pOnlyIdx != pIdx ) continue; nCol = pIdx.nColumn; pKey = sqlite3IndexKeyinfo( pParse, pIdx ); if ( iMem + 1 + ( nCol * 2 ) > pParse.nMem ) { pParse.nMem = iMem + 1 + ( nCol * 2 ); } /* Open a cursor to the index to be analyzed. */ Debug.Assert( iDb == sqlite3SchemaToIndex( db, pIdx.pSchema ) ); sqlite3VdbeAddOp4( v, OP_OpenRead, iIdxCur, pIdx.tnum, iDb, pKey, P4_KEYINFO_HANDOFF ); VdbeComment( v, "%s", pIdx.zName ); /* Populate the registers containing the index names. */ sqlite3VdbeAddOp4( v, OP_String8, 0, regIdxname, 0, pIdx.zName, 0 ); #if SQLITE_ENABLE_STAT2 /* If this iteration of the loop is generating code to analyze the ** first index in the pTab.pIndex list, then register regLast has ** not been populated. In this case populate it now. */ if ( pTab.pIndex == pIdx ) { sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno ); sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES * 2 - 1, regTemp ); sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES * 2, regTemp2 ); sqlite3VdbeAddOp2( v, OP_Count, iIdxCur, regLast ); sqlite3VdbeAddOp2( v, OP_Null, 0, regFirst ); addr = sqlite3VdbeAddOp3( v, OP_Lt, regSamplerecno, 0, regLast ); sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regLast, regFirst ); sqlite3VdbeAddOp3( v, OP_Multiply, regLast, regTemp, regLast ); sqlite3VdbeAddOp2( v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES * 2 - 2 ); sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regLast, regLast ); sqlite3VdbeJumpHere( v, addr ); } /* Zero the regSampleno and regRecno registers. */ sqlite3VdbeAddOp2( v, OP_Integer, 0, regSampleno ); sqlite3VdbeAddOp2( v, OP_Integer, 0, regRecno ); sqlite3VdbeAddOp2( v, OP_Copy, regFirst, regSamplerecno ); #endif /* The block of memory cells initialized here is used as follows. ** ** iMem: ** The total number of rows in the table. ** ** iMem+1 .. iMem+nCol: ** Number of distinct entries in index considering the ** left-most N columns only, where N is between 1 and nCol, ** inclusive. ** ** iMem+nCol+1 .. Mem+2*nCol: ** Previous value of indexed columns, from left to right. ** ** Cells iMem through iMem+nCol are initialized to 0. The others are ** initialized to contain an SQL NULL. */ for ( i = 0; i <= nCol; i++ ) { sqlite3VdbeAddOp2( v, OP_Integer, 0, iMem + i ); } for ( i = 0; i < nCol; i++ ) { sqlite3VdbeAddOp2( v, OP_Null, 0, iMem + nCol + i + 1 ); } /* Start the analysis loop. This loop runs through all the entries in ** the index b-tree. */ endOfLoop = sqlite3VdbeMakeLabel( v ); sqlite3VdbeAddOp2( v, OP_Rewind, iIdxCur, endOfLoop ); topOfLoop = sqlite3VdbeCurrentAddr( v ); sqlite3VdbeAddOp2( v, OP_AddImm, iMem, 1 ); for ( i = 0; i < nCol; i++ ) { sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, regCol ); CollSeq pColl; if ( i == 0 ) { #if SQLITE_ENABLE_STAT2 /* Check if the record that cursor iIdxCur points to contains a ** value that should be stored in the sqlite_stat2 table. If so, ** store it. */ int ne = sqlite3VdbeAddOp3( v, OP_Ne, regRecno, 0, regSamplerecno ); Debug.Assert( regTabname + 1 == regIdxname && regTabname + 2 == regSampleno && regTabname + 3 == regCol ); sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL ); sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0 ); sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur + 1, regRowid ); sqlite3VdbeAddOp3( v, OP_Insert, iStatCur + 1, regRec, regRowid ); /* Calculate new values for regSamplerecno and regSampleno. ** ** sampleno = sampleno + 1 ** samplerecno = samplerecno+(remaining records)/(remaining samples) */ sqlite3VdbeAddOp2( v, OP_AddImm, regSampleno, 1 ); sqlite3VdbeAddOp3( v, OP_Subtract, regRecno, regLast, regTemp ); sqlite3VdbeAddOp2( v, OP_AddImm, regTemp, -1 ); sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2 ); sqlite3VdbeAddOp3( v, OP_Subtract, regSampleno, regTemp2, regTemp2 ); sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regTemp, regTemp ); sqlite3VdbeAddOp3( v, OP_Add, regSamplerecno, regTemp, regSamplerecno ); sqlite3VdbeJumpHere( v, ne ); sqlite3VdbeAddOp2( v, OP_AddImm, regRecno, 1 ); #endif /* Always record the very first row */ sqlite3VdbeAddOp1( v, OP_IfNot, iMem + 1 ); } Debug.Assert( pIdx.azColl != null ); Debug.Assert( pIdx.azColl[i] != null ); pColl = sqlite3LocateCollSeq( pParse, pIdx.azColl[i] ); sqlite3VdbeAddOp4( v, OP_Ne, regCol, 0, iMem + nCol + i + 1, pColl, P4_COLLSEQ ); sqlite3VdbeChangeP5( v, SQLITE_NULLEQ ); } //if( db.mallocFailed ){ // /* If a malloc failure has occurred, then the result of the expression // ** passed as the second argument to the call to sqlite3VdbeJumpHere() // ** below may be negative. Which causes an Debug.Assert() to fail (or an // ** out-of-bounds write if SQLITE_DEBUG is not defined). */ // return; //} sqlite3VdbeAddOp2( v, OP_Goto, 0, endOfLoop ); for ( i = 0; i < nCol; i++ ) { int addr2 = sqlite3VdbeCurrentAddr( v ) - ( nCol * 2 ); if ( i == 0 ) { sqlite3VdbeJumpHere( v, addr2 - 1 ); /* Set jump dest for the OP_IfNot */ } sqlite3VdbeJumpHere( v, addr2 ); /* Set jump dest for the OP_Ne */ sqlite3VdbeAddOp2( v, OP_AddImm, iMem + i + 1, 1 ); sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, iMem + nCol + i + 1 ); } /* End of the analysis loop. */ sqlite3VdbeResolveLabel( v, endOfLoop ); sqlite3VdbeAddOp2( v, OP_Next, iIdxCur, topOfLoop ); sqlite3VdbeAddOp1( v, OP_Close, iIdxCur ); /* Store the results in sqlite_stat1. ** ** The result is a single row of the sqlite_stat1 table. The first ** two columns are the names of the table and index. The third column ** is a string composed of a list of integer statistics about the ** index. The first integer in the list is the total number of entries ** in the index. There is one additional integer in the list for each ** column of the table. This additional integer is a guess of how many ** rows of the table the index will select. If D is the count of distinct ** values and K is the total number of rows, then the integer is computed ** as: ** ** I = (K+D-1)/D ** ** If K==0 then no entry is made into the sqlite_stat1 table. ** If K>0 then it is always the case the D>0 so division by zero ** is never possible. */ sqlite3VdbeAddOp2( v, OP_SCopy, iMem, regSampleno ); if ( jZeroRows < 0 ) { jZeroRows = sqlite3VdbeAddOp1( v, OP_IfNot, iMem ); } for ( i = 0; i < nCol; i++ ) { sqlite3VdbeAddOp4( v, OP_String8, 0, regTemp, 0, " ", 0 ); sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regSampleno, regSampleno ); sqlite3VdbeAddOp3( v, OP_Add, iMem, iMem + i + 1, regTemp ); sqlite3VdbeAddOp2( v, OP_AddImm, regTemp, -1 ); sqlite3VdbeAddOp3( v, OP_Divide, iMem + i + 1, regTemp, regTemp ); sqlite3VdbeAddOp1( v, OP_ToInt, regTemp ); sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regSampleno, regSampleno ); } sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0 ); sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid ); sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid ); sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); } /* If the table has no indices, create a single sqlite_stat1 entry ** containing NULL as the index name and the row count as the content. */ if ( pTab.pIndex == null ) { sqlite3VdbeAddOp3( v, OP_OpenRead, iIdxCur, pTab.tnum, iDb ); VdbeComment( v, "%s", pTab.zName ); sqlite3VdbeAddOp2( v, OP_Count, iIdxCur, regSampleno ); sqlite3VdbeAddOp1( v, OP_Close, iIdxCur ); jZeroRows = sqlite3VdbeAddOp1( v, OP_IfNot, regSampleno ); } else { sqlite3VdbeJumpHere( v, jZeroRows ); jZeroRows = sqlite3VdbeAddOp0( v, OP_Goto ); } sqlite3VdbeAddOp2( v, OP_Null, 0, regIdxname ); sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0 ); sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid ); sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid ); sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); if ( pParse.nMem < regRec ) pParse.nMem = regRec; sqlite3VdbeJumpHere( v, jZeroRows ); } /* ** Generate code that will cause the most recent index analysis to ** be loaded into internal hash tables where is can be used. */ static void loadAnalysis( Parse pParse, int iDb ) { Vdbe v = sqlite3GetVdbe( pParse ); if ( v != null ) { sqlite3VdbeAddOp1( v, OP_LoadAnalysis, iDb ); } } /* ** Generate code that will do an analysis of an entire database */ static void analyzeDatabase( Parse pParse, int iDb ) { sqlite3 db = pParse.db; Schema pSchema = db.aDb[iDb].pSchema; /* Schema of database iDb */ HashElem k; int iStatCur; int iMem; sqlite3BeginWriteOperation( pParse, 0, iDb ); iStatCur = pParse.nTab; pParse.nTab += 2; openStatTable( pParse, iDb, iStatCur, null, null ); iMem = pParse.nMem + 1; Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); //for(k=sqliteHashFirst(pSchema.tblHash); k; k=sqliteHashNext(k)){ for ( k = pSchema.tblHash.first; k != null; k = k.next ) { Table pTab = (Table)k.data;// sqliteHashData( k ); analyzeOneTable( pParse, pTab, null, iStatCur, iMem ); } loadAnalysis( pParse, iDb ); } /* ** Generate code that will do an analysis of a single table in ** a database. If pOnlyIdx is not NULL then it is a single index ** in pTab that should be analyzed. */ static void analyzeTable( Parse pParse, Table pTab, Index pOnlyIdx) { int iDb; int iStatCur; Debug.Assert( pTab != null ); Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); sqlite3BeginWriteOperation( pParse, 0, iDb ); iStatCur = pParse.nTab; pParse.nTab += 2; if ( pOnlyIdx != null ) { openStatTable( pParse, iDb, iStatCur, pOnlyIdx.zName, "idx" ); } else { openStatTable( pParse, iDb, iStatCur, pTab.zName, "tbl" ); } analyzeOneTable( pParse, pTab, pOnlyIdx, iStatCur, pParse.nMem + 1 ); loadAnalysis( pParse, iDb ); } /* ** Generate code for the ANALYZE command. The parser calls this routine ** when it recognizes an ANALYZE command. ** ** ANALYZE -- 1 ** ANALYZE <database> -- 2 ** ANALYZE ?<database>.?<tablename> -- 3 ** ** Form 1 causes all indices in all attached databases to be analyzed. ** Form 2 analyzes all indices the single database named. ** Form 3 analyzes all indices associated with the named table. */ // OVERLOADS, so I don't need to rewrite parse.c static void sqlite3Analyze( Parse pParse, int null_2, int null_3 ) { sqlite3Analyze( pParse, null, null ); } static void sqlite3Analyze( Parse pParse, Token pName1, Token pName2 ) { sqlite3 db = pParse.db; int iDb; int i; string z, zDb; Table pTab; Index pIdx; Token pTableName = null; /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) { return; } Debug.Assert( pName2 != null || pName1 == null ); if ( pName1 == null ) { /* Form 1: Analyze everything */ for ( i = 0; i < db.nDb; i++ ) { if ( i == 1 ) continue; /* Do not analyze the TEMP database */ analyzeDatabase( pParse, i ); } } else if ( pName2.n == 0 ) { /* Form 2: Analyze the database or table named */ iDb = sqlite3FindDb( db, pName1 ); if ( iDb >= 0 ) { analyzeDatabase( pParse, iDb ); } else { z = sqlite3NameFromToken( db, pName1 ); if ( z != null ) { if ( ( pIdx = sqlite3FindIndex( db, z, null ) ) != null ) { analyzeTable( pParse, pIdx.pTable, pIdx ); } else if ( ( pTab = sqlite3LocateTable( pParse, 0, z, null ) ) != null ) { analyzeTable( pParse, pTab, null ); } z = null;//sqlite3DbFree( db, z ); } } } else { /* Form 3: Analyze the fully qualified table name */ iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pTableName ); if ( iDb >= 0 ) { zDb = db.aDb[iDb].zName; z = sqlite3NameFromToken( db, pTableName ); if ( z != null ) { if ( ( pIdx = sqlite3FindIndex( db, z, zDb ) ) != null ) { analyzeTable( pParse, pIdx.pTable, pIdx ); } else if ( ( pTab = sqlite3LocateTable( pParse, 0, z, zDb ) ) != null ) { analyzeTable( pParse, pTab, null ); } z = null; //sqlite3DbFree( db, z ); } } } } /* ** Used to pass information from the analyzer reader through to the ** callback routine. */ //typedef struct analysisInfo analysisInfo; public struct analysisInfo { public sqlite3 db; public string zDatabase; }; /* ** This callback is invoked once for each index when reading the ** sqlite_stat1 table. ** ** argv[0] = name of the table ** argv[1] = name of the index (might be NULL) ** argv[2] = results of analysis - on integer for each column ** ** Entries for which argv[1]==NULL simply record the number of rows in ** the table. */ static int analysisLoader( object pData, sqlite3_int64 argc, object Oargv, object NotUsed ) { string[] argv = (string[])Oargv; analysisInfo pInfo = (analysisInfo)pData; Index pIndex; Table pTable; int i, c, n; int v; string z; Debug.Assert( argc == 3 ); UNUSED_PARAMETER2( NotUsed, argc ); if ( argv == null || argv[0] == null || argv[2] == null ) { return 0; } pTable = sqlite3FindTable( pInfo.db, argv[0], pInfo.zDatabase ); if ( pTable == null ) { return 0; } if ( !String.IsNullOrEmpty( argv[1] ) ) { pIndex = sqlite3FindIndex( pInfo.db, argv[1], pInfo.zDatabase ); } else { pIndex = null; } n = pIndex != null ? pIndex.nColumn : 0; z = argv[2]; int zIndex = 0; for ( i = 0; z != null && i <= n; i++ ) { v = 0; while ( zIndex < z.Length && ( c = z[zIndex] ) >= '0' && c <= '9' ) { v = v * 10 + c - '0'; zIndex++; } if ( i == 0 ) pTable.nRowEst = (uint)v; if ( pIndex == null ) break; pIndex.aiRowEst[i] = v; if ( zIndex < z.Length && z[zIndex] == ' ' ) zIndex++; if ( string.Equals(z.Substring(zIndex), "unordered", StringComparison.Ordinal) )//memcmp( z, "unordered", 10 ) == 0 ) { pIndex.bUnordered = 1; break; } } return 0; } /* ** If the Index.aSample variable is not NULL, delete the aSample[] array ** and its contents. */ static void sqlite3DeleteIndexSamples( sqlite3 db, Index pIdx ) { #if SQLITE_ENABLE_STAT2 if ( pIdx.aSample != null ) { int j; for ( j = 0; j < SQLITE_INDEX_SAMPLES; j++ ) { IndexSample p = pIdx.aSample[j]; if ( p.eType == SQLITE_TEXT || p.eType == SQLITE_BLOB ) { p.u.z = null;//sqlite3DbFree(db, p.u.z); p.u.zBLOB = null; } } sqlite3DbFree( db, ref pIdx.aSample ); } #else UNUSED_PARAMETER(db); UNUSED_PARAMETER( pIdx ); #endif } /* ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[] ** arrays. The contents of sqlite_stat2 are used to populate the ** Index.aSample[] arrays. ** ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined ** during compilation and the sqlite_stat2 table is present, no data is ** read from it. ** ** If SQLITE_ENABLE_STAT2 was defined during compilation and the ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is ** returned. However, in this case, data is read from the sqlite_stat1 ** table (if it is present) before returning. ** ** If an OOM error occurs, this function always sets db.mallocFailed. ** This means if the caller does not care about other errors, the return ** code may be ignored. */ static int sqlite3AnalysisLoad( sqlite3 db, int iDb ) { analysisInfo sInfo; HashElem i; string zSql; int rc; Debug.Assert( iDb >= 0 && iDb < db.nDb ); Debug.Assert( db.aDb[iDb].pBt != null ); /* Clear any prior statistics */ Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); //for(i=sqliteHashFirst(&db.aDb[iDb].pSchema.idxHash);i;i=sqliteHashNext(i)){ for ( i = db.aDb[iDb].pSchema.idxHash.first; i != null; i = i.next ) { Index pIdx = (Index)i.data;// sqliteHashData( i ); sqlite3DefaultRowEst( pIdx ); sqlite3DeleteIndexSamples( db, pIdx ); pIdx.aSample = null; } /* Check to make sure the sqlite_stat1 table exists */ sInfo.db = db; sInfo.zDatabase = db.aDb[iDb].zName; if ( sqlite3FindTable( db, "sqlite_stat1", sInfo.zDatabase ) == null ) { return SQLITE_ERROR; } /* Load new statistics out of the sqlite_stat1 table */ zSql = sqlite3MPrintf( db, "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase ); //if ( zSql == null ) //{ // rc = SQLITE_NOMEM; //} //else { rc = sqlite3_exec( db, zSql, (dxCallback)analysisLoader, sInfo, 0 ); sqlite3DbFree( db, ref zSql ); } /* Load the statistics from the sqlite_stat2 table. */ #if SQLITE_ENABLE_STAT2 if ( rc == SQLITE_OK && null == sqlite3FindTable( db, "sqlite_stat2", sInfo.zDatabase ) ) { rc = SQLITE_ERROR; } if ( rc == SQLITE_OK ) { sqlite3_stmt pStmt = null; zSql = sqlite3MPrintf( db, "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase ); //if( null==zSql ){ //rc = SQLITE_NOMEM; //}else{ rc = sqlite3_prepare( db, zSql, -1, ref pStmt, 0 ); sqlite3DbFree( db, ref zSql ); //} if ( rc == SQLITE_OK ) { while ( sqlite3_step( pStmt ) == SQLITE_ROW ) { string zIndex; /* Index name */ Index pIdx; /* Pointer to the index object */ zIndex = sqlite3_column_text( pStmt, 0 ); pIdx = !String.IsNullOrEmpty( zIndex ) ? sqlite3FindIndex( db, zIndex, sInfo.zDatabase ) : null; if ( pIdx != null ) { int iSample = sqlite3_column_int( pStmt, 1 ); if ( iSample < SQLITE_INDEX_SAMPLES && iSample >= 0 ) { int eType = sqlite3_column_type( pStmt, 2 ); if ( pIdx.aSample == null ) { //static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES; //pIdx->aSample = (IndexSample )sqlite3DbMallocRaw(0, sz); //if( pIdx.aSample==0 ){ //db.mallocFailed = 1; //break; //} pIdx.aSample = new IndexSample[SQLITE_INDEX_SAMPLES];//memset(pIdx->aSample, 0, sz); } //Debug.Assert( pIdx.aSample != null ); if ( pIdx.aSample[iSample] == null ) pIdx.aSample[iSample] = new IndexSample(); IndexSample pSample = pIdx.aSample[iSample]; { pSample.eType = (u8)eType; if ( eType == SQLITE_INTEGER || eType == SQLITE_FLOAT ) { pSample.u.r = sqlite3_column_double( pStmt, 2 ); } else if ( eType == SQLITE_TEXT || eType == SQLITE_BLOB ) { string z = null; byte[] zBLOB = null; //string z = (string )( //(eType==SQLITE_BLOB) ? //sqlite3_column_blob(pStmt, 2): //sqlite3_column_text(pStmt, 2) //); if ( eType == SQLITE_BLOB ) zBLOB = sqlite3_column_blob( pStmt, 2 ); else z = sqlite3_column_text( pStmt, 2 ); int n = sqlite3_column_bytes( pStmt, 2 ); if ( n > 24 ) { n = 24; } pSample.nByte = (u8)n; if ( n < 1 ) { pSample.u.z = null; pSample.u.zBLOB = null; } else { pSample.u.z = z; pSample.u.zBLOB = zBLOB; //pSample->u.z = sqlite3DbMallocRaw(dbMem, n); //if( pSample->u.z ){ // memcpy(pSample->u.z, z, n); //}else{ // db->mallocFailed = 1; // break; //} } } } } } } rc = sqlite3_finalize( pStmt ); } } #endif //if( rc==SQLITE_NOMEM ){ // db.mallocFailed = 1; //} return rc; } #endif // * SQLITE_OMIT_ANALYZE */ } }
using System; using System.Diagnostics; using System.IO; using System.Collections; using OTFontFile.Rasterizer; using OTFontFile; namespace OTFontFileVal { public class OTFontVal : OTFont { /*************** * constructors */ public OTFontVal(OTFile f) : base (f) { } public OTFontVal(OTFile f, uint FontFileNumber, OffsetTable ot, OutlineType outlineType) : base (f, FontFileNumber, ot, outlineType) { } /************************ * public static methods */ public static new OTFontVal ReadFont(OTFile file, uint FontFileNumber, uint filepos) { OTFontVal f = null; OffsetTable ot = ReadOffsetTable(file, filepos); if (ot != null) { if (ot.numTables == ot.DirectoryEntries.Count) { OutlineType olt = OutlineType.OUTLINE_INVALID; for (int i = 0; i<ot.DirectoryEntries.Count; i++) { DirectoryEntry temp = (DirectoryEntry)ot.DirectoryEntries[i]; string sTable = (string)temp.tag; if (sTable == "CFF ") { olt = OutlineType.OUTLINE_POSTSCRIPT; break; } else if (sTable == "glyf") { olt = OutlineType.OUTLINE_TRUETYPE; break; } } f = new OTFontVal(file, FontFileNumber, ot, olt); } } return f; } /***************** * public methods */ public bool Validate() { bool bRet = true; int canrast; Validator v = GetFile().GetValidator(); if (v.PerformTest(T._OFFSET_sfntVersion)) { uint sfnt = m_OffsetTable.sfntVersion.GetUint(); if (!OTFile.IsValidSfntVersion(sfnt)) { v.Error(T._OFFSET_sfntVersion, E._OFFSET_E_InvalidSFNT, null, "0x"+sfnt.ToString("x8")); bRet = false; } } if (v.PerformTest(T._OFFSET_numTables)) { if (m_OffsetTable.numTables == 0) { v.Error(T._OFFSET_numTables, E._OFFSET_E_numTables, null); bRet = false; } else { v.Pass(T._OFFSET_numTables, P._OFFSET_P_numTables, null, m_OffsetTable.numTables.ToString()); } } if (v.PerformTest(T._OFFSET_BinarySearchFields)) { ushort numTables = m_OffsetTable.numTables; ushort CalculatedSearchRange = (ushort)(util.MaxPower2LE(numTables) * 16); ushort CalculatedEntrySelector = util.Log2(util.MaxPower2LE(numTables)); ushort CalculatedRangeShift = (ushort)(numTables*16 - CalculatedSearchRange); bool bBinaryFieldsOk = true; if (m_OffsetTable.searchRange != CalculatedSearchRange) { v.Error(T._OFFSET_BinarySearchFields, E._OFFSET_E_searchRange, null, m_OffsetTable.searchRange.ToString()); bBinaryFieldsOk = false; bRet = false; } if (m_OffsetTable.entrySelector != CalculatedEntrySelector) { v.Error(T._OFFSET_BinarySearchFields, E._OFFSET_E_entrySelector, null, m_OffsetTable.entrySelector.ToString()); bBinaryFieldsOk = false; bRet = false; } if (m_OffsetTable.rangeShift != CalculatedRangeShift) { v.Error(T._OFFSET_BinarySearchFields, E._OFFSET_E_rangeShift, null, m_OffsetTable.rangeShift.ToString()); bBinaryFieldsOk = false; bRet = false; } if (bBinaryFieldsOk) { v.Pass(T._OFFSET_BinarySearchFields, P._OFFSET_P_BinarySearchTables, null); } } bRet &= CheckDirectoryEntriesNonZero(v); bRet &= CheckTablesInFileAndNotOverlapping(v); bRet &= CheckNoDuplicateTags(v); if (v.PerformTest(T._DE_TagsAscendingOrder)) { bRet &= CheckTagsAscending(v); } if (v.PerformTest(T._DE_TagNames)) { bRet &= CheckTagNames(v); } if (v.PerformTest(T._DE_TableAlignment)) { bRet &= CheckTableAlignment(v); } if (v.PerformTest(T._FONT_RequiredTables)) { bRet &= CheckForRequiredTables(v); } if (v.PerformTest(T._FONT_RecommendedTables)) { bRet &= CheckForRecommendedTables(v); } if (v.PerformTest(T._FONT_UnnecessaryTables)) { bRet &= CheckForNoUnnecessaryTables(v); } if (v.PerformTest(T._FONT_OptimalTableOrder)) { bRet &= CheckForOptimalTableOrder(v); } // Validate each table if (m_OffsetTable != null) { for (int i = 0; i<m_OffsetTable.DirectoryEntries.Count; i++) { // check to see if user canceled validation if (v.CancelFlag) { break; } // get the table DirectoryEntry de = (DirectoryEntry)m_OffsetTable.DirectoryEntries[i]; OTTable table = GetFile().GetTableManager().GetTable(this, de); // Will it really happen? if (GetFile().GetTableManager().GetUnaliasedTableName(de.tag) == "DSIG" && GetFile().IsCollection()) continue; // Call the function that validates a single table bRet &= this.GetFile().ValidateTable(table, v, de, this); } } canrast = TestFontRasterization(); ushort numGlyphs = GetMaxpNumGlyphs(); // rasterization test - BW v.OnRastTestValidationEvent_BW(true); if (v.PeformRastTest_BW()) { if (canrast > 0) { try { // fetch the rasterizer object and initialize it with this font RasterInterf ri = GetFile().GetRasterizer(); ri.RasterNewSfnt(GetFile().GetFileStream(), GetFontIndexInFile()); // call the rasterizer RasterInterf.UpdateProgressDelegate upg = new RasterInterf.UpdateProgressDelegate(v.OnTableProgress); RasterInterf.RastTestErrorDelegate rted = new RasterInterf.RastTestErrorDelegate(v.OnRastTestError); int x = v.GetRastTestXRes(); int y = v.GetRastTestYRes(); int [] pointsizes = v.GetRastTestPointSizes(); RastTestTransform rtt = v.GetRastTestTransform(); bRet &= ri.RastTest( x, y, pointsizes, rtt.stretchX, rtt.stretchY, rtt.rotation, rtt.skew, rtt.matrix, true, false, false, 0, rted, upg, numGlyphs); if (ri.GetRastErrorCount() == 0) { v.Pass(T.T_NULL, P._rast_P_rasterization, null); } } catch (Exception e) { v.ApplicationError(T.T_NULL, E._rast_A_ExceptionUnhandled, null, e.StackTrace); } } else if (canrast == 0) { v.Info(T.T_NULL, I._rast_I_rasterization, null, GetDevMetricsDataError()); } else { v.Error(T.T_NULL, E._rast_E_rasterization, null, GetDevMetricsDataError()); bRet = false; } } else { v.Info(I._TEST_I_RastTestNotSelected, null); } v.OnRastTestValidationEvent_BW(false); // rasterization test - Grayscale v.OnRastTestValidationEvent_Grayscale(true); if (v.PeformRastTest_Grayscale()) { if (canrast > 0) { try { // fetch the rasterizer object and initialize it with this font RasterInterf ri = GetFile().GetRasterizer(); ri.RasterNewSfnt(GetFile().GetFileStream(), GetFontIndexInFile()); // call the rasterizer RasterInterf.UpdateProgressDelegate upg = new RasterInterf.UpdateProgressDelegate(v.OnTableProgress); RasterInterf.RastTestErrorDelegate rted = new RasterInterf.RastTestErrorDelegate(v.OnRastTestError); int x = v.GetRastTestXRes(); int y = v.GetRastTestYRes(); int [] pointsizes = v.GetRastTestPointSizes(); RastTestTransform rtt = v.GetRastTestTransform(); bRet &= ri.RastTest( x, y, pointsizes, rtt.stretchX, rtt.stretchY, rtt.rotation, rtt.skew, rtt.matrix, false, true, false, 0, rted, upg, numGlyphs); if (ri.GetRastErrorCount() == 0) { v.Pass(T.T_NULL, P._rast_P_rasterization, null); } } catch (Exception e) { v.ApplicationError(T.T_NULL, E._rast_A_ExceptionUnhandled, null, e.StackTrace); } } else if (canrast == 0) { v.Info(T.T_NULL, I._rast_I_rasterization, null, GetDevMetricsDataError()); } else { v.Error(T.T_NULL, E._rast_E_rasterization, null, GetDevMetricsDataError()); bRet = false; } } else { v.Info(I._TEST_I_RastTestNotSelected, null); } v.OnRastTestValidationEvent_Grayscale(false); // rasterization test - Cleartype v.OnRastTestValidationEvent_Cleartype(true); if (v.PeformRastTest_Cleartype()) { if (canrast > 0) { try { uint CTFlags = v.GetCleartypeFlags(); // fetch the rasterizer object and initialize it with this font RasterInterf ri = GetFile().GetRasterizer(); ri.RasterNewSfnt(GetFile().GetFileStream(), GetFontIndexInFile()); // call the rasterizer RasterInterf.UpdateProgressDelegate upg = new RasterInterf.UpdateProgressDelegate(v.OnTableProgress); RasterInterf.RastTestErrorDelegate rted = new RasterInterf.RastTestErrorDelegate(v.OnRastTestError); int x = v.GetRastTestXRes(); int y = v.GetRastTestYRes(); int [] pointsizes = v.GetRastTestPointSizes(); RastTestTransform rtt = v.GetRastTestTransform(); bRet &= ri.RastTest( x, y, pointsizes, rtt.stretchX, rtt.stretchY, rtt.rotation, rtt.skew, rtt.matrix, false, false, true, CTFlags, rted, upg, numGlyphs); if (ri.GetRastErrorCount() == 0) { v.Pass(T.T_NULL, P._rast_P_rasterization, null); } } catch (Exception e) { v.ApplicationError(T.T_NULL, E._rast_A_ExceptionUnhandled, null, e.StackTrace); } } else if (canrast == 0) { v.Info(T.T_NULL, I._rast_I_rasterization, null, GetDevMetricsDataError()); } else { v.Error(T.T_NULL, E._rast_E_rasterization, null, GetDevMetricsDataError()); bRet = false; } } else { v.Info(I._TEST_I_RastTestNotSelected, null); } v.OnRastTestValidationEvent_Cleartype(false); return bRet; } public new OTTable GetTable(OTTag tag) { OTTable table = null; // find the directory entry in this font that matches the tag DirectoryEntry de = GetDirectoryEntry(tag); if (de != null) { // get the table from the table manager table = GetFile().GetTableManager().GetTable(this, de); } return table; } public new OTFileVal GetFile() { return (OTFileVal)m_File; } public RasterInterf.DevMetricsData GetCalculatedDevMetrics() { if (m_DevMetricsData != null) { return m_DevMetricsData; } // get numGlyphs ushort numGlyphs = GetMaxpNumGlyphs(); // hdmx byte [] hdmxPointSizes = null; ushort maxHdmxPointSize = 0; Table_hdmx hdmxTable = (Table_hdmx)GetTable("hdmx"); int bCalc_hdmx = 0; if (hdmxTable != null && GetFile().GetValidator().TestTable("hdmx")) { bCalc_hdmx = 1; // the hdmxPointSizes array stores a 1 for each pixel size represented in the hdmx table //hdmxPointSizes = new byte[numGlyphs]; hdmxPointSizes = new byte[256]; for (uint i=0; i<hdmxTable.NumberDeviceRecords; i++) { Table_hdmx.DeviceRecord dr = hdmxTable.GetDeviceRecord(i, numGlyphs); hdmxPointSizes[dr.PixelSize] = 1; if (maxHdmxPointSize < dr.PixelSize) { maxHdmxPointSize = dr.PixelSize; } } } // LTSH Table_LTSH LTSHTable = (Table_LTSH)GetTable("LTSH"); int bCalc_LTSH = 0; if (LTSHTable != null && GetFile().GetValidator().TestTable("LTSH")) { bCalc_LTSH = 1; } // VDMX byte uchPixelHeightRangeStart = 8;//#define DEFAULT_PixelHeightRangeStart 8 byte uchPixelHeightRangeEnd = 255;//#define DEFAULT_PixelHeightRangeEnd 255 ushort [] VDMXxResolution = new ushort[1]; ushort [] VDMXyResolution = new ushort[1]; VDMXxResolution[0] = 72; // always calculate at least a 1:1 ratio (used for calculating hdmx and LTSH) VDMXyResolution[0] = 72; // cacheTT code used 72:72, I think using 1:1 here will make the cacheTT code fail ushort cVDMXResolutions = 1; Table_VDMX VDMXTable = (Table_VDMX)GetTable("VDMX"); int bCalc_VDMX = 0; if (VDMXTable != null && GetFile().GetValidator().TestTable("VDMX")) { bCalc_VDMX = 1; Table_VDMX.Vdmx VdmxGroup = VDMXTable.GetVdmxGroup(0); uchPixelHeightRangeStart = VdmxGroup.startsz; uchPixelHeightRangeEnd = VdmxGroup.endsz; VDMXxResolution = new ushort[VDMXTable.numRatios]; VDMXyResolution = new ushort[VDMXTable.numRatios]; for (uint i=0; i<VDMXTable.numRatios; i++) { Table_VDMX.Ratios ratio = VDMXTable.GetRatioRange(i); VDMXxResolution[i] = ratio.xRatio; VDMXyResolution[i] = ratio.yStartRatio; // cacheTT code seems to expect unreduced ratios if (VDMXxResolution[i] < 72 && VDMXyResolution[i] < 72) { VDMXxResolution[i] *= 72; VDMXyResolution[i] *= 72; } } cVDMXResolutions = VDMXTable.numRatios; } // make sure that we are going to have a known problem with the // rasterizer due to missing tables or bad offsets if (TestFontRasterization() > 0) { // fetch the rasterizer object and initialize it with this font RasterInterf ri = GetFile().GetRasterizer(); ri.RasterNewSfnt(GetFile().GetFileStream(), GetFontIndexInFile()); // calculate the cached data try { Validator v = GetFile().GetValidator(); RasterInterf.UpdateProgressDelegate upg = new RasterInterf.UpdateProgressDelegate(v.OnTableProgress); m_DevMetricsData = ri.CalcDevMetrics(bCalc_hdmx, bCalc_LTSH, bCalc_VDMX, numGlyphs, hdmxPointSizes, maxHdmxPointSize, uchPixelHeightRangeStart, uchPixelHeightRangeEnd, VDMXxResolution, VDMXyResolution, cVDMXResolutions, upg); } catch (Exception e) { m_sDevMetricsDataError = e.Message; } } return m_DevMetricsData; } public String GetDevMetricsDataError() { return m_sDevMetricsDataError; } /****************** * protected methods */ protected static OffsetTable ReadOffsetTable(OTFileVal file, uint filepos) { // read the Offset Table from the file Validator v = file.GetValidator(); const int SIZEOF_OFFSETTABLE = 12; OffsetTable ot = null; // read the offset table MBOBuffer buf = file.ReadPaddedBuffer(filepos, SIZEOF_OFFSETTABLE); if (buf != null) { if (OTFile.IsValidSfntVersion(buf.GetUint(0))) { ot = new OffsetTable(buf); } else { v.Error(T.T_NULL, E._OFFSET_E_InvalidSFNT, null, "0x"+buf.GetUint(0).ToString("x8")); } } // now read the directory entries if (ot != null) { const int SIZEOF_DIRECTORYENTRY = 16; for (int i=0; i<ot.numTables; i++) { uint dirFilePos = (uint)(filepos+SIZEOF_OFFSETTABLE+i*SIZEOF_DIRECTORYENTRY); MBOBuffer DirEntBuf = file.ReadPaddedBuffer(dirFilePos, SIZEOF_DIRECTORYENTRY); if (DirEntBuf != null) { DirectoryEntry de = new DirectoryEntry(); de.tag = new OTTag(DirEntBuf.GetBuffer()); de.checkSum = DirEntBuf.GetUint(4); de.offset = DirEntBuf.GetUint(8); de.length = DirEntBuf.GetUint(12); ot.DirectoryEntries.Add(de); if (de.offset > file.GetFileLength()) { v.Error(T.T_NULL, E._DE_E_OffsetPastEOF, de.tag, "0x"+de.offset.ToString("x8")); } } else { break; } } } return ot; } protected bool CheckDirectoryEntriesNonZero(Validator v) { Debug.Assert(m_OffsetTable != null); bool bRet = false; if (m_OffsetTable != null) { bRet = true; for (int i = 0; i<m_OffsetTable.DirectoryEntries.Count; i++) { DirectoryEntry de = (DirectoryEntry)m_OffsetTable.DirectoryEntries[i]; if (de.tag == 0) { v.Error(E._DE_E_TagZero, null); bRet = false; } if (de.length == 0) { v.Error(T.T_NULL, E._DE_E_LengthZero, null, de.tag); bRet = false; } if (de.offset == 0) { v.Error(T.T_NULL, E._DE_E_OffsetZero, null, de.tag); bRet = false; } } } return bRet; } protected bool CheckNoDuplicateTags(Validator v) { Debug.Assert(m_OffsetTable != null); bool bRet = false; if (m_OffsetTable != null) { bRet = true; for (int i = 0; i<m_OffsetTable.DirectoryEntries.Count; i++) { DirectoryEntry de1 = (DirectoryEntry)m_OffsetTable.DirectoryEntries[i]; // compare this directory entry with every one that follows it for (int j=i+1; j<m_OffsetTable.DirectoryEntries.Count; j++) { DirectoryEntry de2 = (DirectoryEntry)m_OffsetTable.DirectoryEntries[j]; if (de1.tag == de2.tag) { v.Error(T.T_NULL, E._DE_E_DuplicateTag, null, de1.tag); } } } } return bRet; } protected bool CheckTablesInFileAndNotOverlapping(Validator v) { Debug.Assert(m_OffsetTable != null); bool bRet = false; if (m_OffsetTable != null) { bRet = true; for (int i = 0; i<m_OffsetTable.DirectoryEntries.Count; i++) { DirectoryEntry de = (DirectoryEntry)m_OffsetTable.DirectoryEntries[i]; // make sure the offset plus length is within the file if (de.offset + de.length > GetFile().GetFileLength()) { v.Error(T.T_NULL, E._DE_E_TableEndPastEOF, de.tag, de.tag); bRet = false; } // make sure the table doesn't overlap any other tables for (int j=0; j<m_OffsetTable.DirectoryEntries.Count; j++) { if (i!=j) // don't compare the table to itself! { DirectoryEntry de2 = (DirectoryEntry)m_OffsetTable.DirectoryEntries[j]; if ( // make sure the table doesn't start inside a second table (de.offset > de2.offset && de.offset < de2.offset+de2.length) || // make sure the table doesn't end inside a second table (de.offset+de.length > de2.offset && de.offset+de.length < de2.offset+de2.length) ) { string sDetails = de.tag + " overlaps " + de2.tag; v.Error(T.T_NULL, E._DE_E_OverlappingTable, de.tag, sDetails); } } } } } return bRet; } protected bool CheckTagsAscending(Validator v) { Debug.Assert(m_OffsetTable != null); bool bRet = false; if (m_OffsetTable != null) { bRet = true; for (int i = 0; i<m_OffsetTable.DirectoryEntries.Count; i++) { DirectoryEntry de1 = (DirectoryEntry)m_OffsetTable.DirectoryEntries[i]; // compare this directory entry with every one that follows it for (int j=i+1; j<m_OffsetTable.DirectoryEntries.Count; j++) { DirectoryEntry de2 = (DirectoryEntry)m_OffsetTable.DirectoryEntries[j]; if ((uint)de1.tag > (uint)de2.tag) { v.Error(E._DE_E_TagsAscending, null); bRet = false; break; } } if (bRet == false) { break; } } if (bRet == true) { v.Pass(P._DE_P_TagsAscending, null); } } return bRet; } protected bool CheckTagNames(Validator v) { Debug.Assert(m_OffsetTable != null); bool bRet = false; if (m_OffsetTable != null) { bRet = true; for (int i = 0; i<m_OffsetTable.DirectoryEntries.Count; i++) { DirectoryEntry de = (DirectoryEntry)m_OffsetTable.DirectoryEntries[i]; if (!de.tag.IsValid()) { v.Error(T.T_NULL, E._DE_E_TagName, null, (string)de.tag); bRet = false; } } if (bRet == true) { v.Pass(P._DE_P_TagName, null); } } return bRet; } protected bool CheckTableAlignment(Validator v) { Debug.Assert(m_OffsetTable != null); bool bRet = false; if (m_OffsetTable != null) { bRet = true; for (int i = 0; i<m_OffsetTable.DirectoryEntries.Count; i++) { DirectoryEntry de = (DirectoryEntry)m_OffsetTable.DirectoryEntries[i]; if ((de.offset & 0x03) != 0) { v.Warning(T.T_NULL, W._DE_W_TableAlignment, null, (string)de.tag); //bRet = false; } } if (bRet == true) { v.Pass(P._DE_P_TableAlignment, null); } } return bRet; } protected bool CheckForRequiredTables(Validator v) { bool bRet = true; string [] RequiredTables = {"cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post"}; for (int i=0; i<RequiredTables.Length; i++) { if (GetDirectoryEntry(RequiredTables[i]) == null) { v.Error(T.T_NULL, E._FONT_E_MissingRequiredTable, null, RequiredTables[i]); bRet = false; } } if (GetDirectoryEntry("glyf") == null && GetDirectoryEntry("CFF ") == null && GetDirectoryEntry("EBDT") == null) { v.Error(T.T_NULL, E._FONT_E_MissingRequiredTable, null, "Font must contain either a 'glyf', 'CFF ', or 'EBDT' table"); bRet = false; } if (GetDirectoryEntry("glyf") != null) { string [] RequiredGlyphTables = {"loca"}; for (int i=0; i<RequiredGlyphTables.Length; i++) { if (GetDirectoryEntry(RequiredGlyphTables[i]) == null) { v.Error(T.T_NULL, E._FONT_E_MissingRequiredTable, null, RequiredGlyphTables[i] + " is required since the font contains a glyf table"); bRet = false; } } } if (GetDirectoryEntry("EBDT") != null) { if (GetDirectoryEntry("EBLC") == null) { v.Error(T.T_NULL, E._FONT_E_MissingRequiredTable, null, "EBLC is required since the font contains an EBDT table"); bRet = false; } } if (GetDirectoryEntry("EBLC") != null) { if (GetDirectoryEntry("EBDT") == null) { v.Error(T.T_NULL, E._FONT_E_MissingRequiredTable, null, "EBDT is required since the font contains an EBLC table"); bRet = false; } } if (GetDirectoryEntry("EBSC") != null) { if (GetDirectoryEntry("EBDT") == null) { v.Error(T.T_NULL, E._FONT_E_MissingRequiredTable, null, "EBDT is required since the font contains an EBSC table"); bRet = false; } if (GetDirectoryEntry("EBLC") == null) { v.Error(T.T_NULL, E._FONT_E_MissingRequiredTable, null, "EBLC is required since the font contains an EBSC table"); bRet = false; } } if (bRet) { v.Pass(P._FONT_P_MissingRequiredTable, null); } return bRet; } protected bool CheckForRecommendedTables(Validator v) { bool bRet = true; bool bMissing = false; if (!IsPostScript()) { if (GetDirectoryEntry("gasp") == null) { v.Warning(T.T_NULL, W._FONT_W_MissingRecommendedTable, null, "gasp"); bMissing = true; } Table_hmtx hmtxTable = (Table_hmtx)GetTable("hmtx"); if (hmtxTable != null) { if (!hmtxTable.IsMonospace(this) && !ContainsSymbolsOnly()) { if (GetDirectoryEntry("kern") == null) { v.Warning(T.T_NULL, W._FONT_W_MissingRecommendedTable, null, "kern"); bMissing = true; } if (GetDirectoryEntry("hdmx") == null) { v.Warning(T.T_NULL, W._FONT_W_MissingRecommendedTable, null, "hdmx"); bMissing = true; } } } if (GetDirectoryEntry("VDMX") == null) { v.Warning(T.T_NULL, W._FONT_W_MissingRecommendedTable, null, "VDMX"); bMissing = true; } } if (GetDirectoryEntry("DSIG") == null) { v.Warning(T.T_NULL, W._FONT_W_MissingRecommendedTable, null, "DSIG"); bMissing = true; } if (!bMissing) { v.Pass(P._FONT_P_MissingRecommendedTable, null); } return bRet; } protected bool CheckForNoUnnecessaryTables(Validator v) { bool bRet = true; bool bFoundUnnecessary = false; Table_hmtx hmtxTable = (Table_hmtx)GetTable("hmtx"); if (hmtxTable != null) { if (hmtxTable.IsMonospace(this)) { if (GetDirectoryEntry("hdmx") != null) { v.Warning(T.T_NULL, W._FONT_W_UnnecessaryTable, null, "hdmx table not needed for monospaced font"); bFoundUnnecessary = true; } if (GetDirectoryEntry("LTSH") != null) { v.Warning(T.T_NULL, W._FONT_W_UnnecessaryTable, null, "LTSH table not needed for monospaced font"); bFoundUnnecessary = true; } if (GetDirectoryEntry("kern") != null) { v.Warning(T.T_NULL, W._FONT_W_UnnecessaryTable, null, "kern table not needed for monospaced font"); bFoundUnnecessary = true; } } if (GetDirectoryEntry("CFF ") == null && GetDirectoryEntry("VORG") != null) { v.Warning(T.T_NULL, W._FONT_W_UnnecessaryTable, null, "VORG table not needed, it may optionally be present for fonts with Postscript outlines"); bFoundUnnecessary = true; } if (GetDirectoryEntry("PCLT") != null) { v.Warning(T.T_NULL, W._FONT_W_UnnecessaryTable, null, "PCLT table not needed, Microsoft no longer recommends including this table"); bFoundUnnecessary = true; } } if (GetDirectoryEntry("CFF ") != null) { string [] UnnecessaryTables = {"glyf", "fpgm", "cvt ", "loca", "prep"}; for (int i=0; i<UnnecessaryTables.Length; i++) { if (GetDirectoryEntry(UnnecessaryTables[i]) != null) { v.Warning(T.T_NULL, W._FONT_W_UnnecessaryTable, null, UnnecessaryTables[i] + " not needed since the font contains a 'CFF ' table"); bFoundUnnecessary = true; } } } if (GetDirectoryEntry("glyf") != null) { if (GetDirectoryEntry("CFF ") != null) { v.Warning(T.T_NULL, W._FONT_W_UnnecessaryTable, null, "CFF not needed since the font contains a 'CFF ' table"); bFoundUnnecessary = true; } } if (ContainsLatinOnly()) { if (GetDirectoryEntry("vhea") != null) { v.Warning(T.T_NULL, W._FONT_W_UnnecessaryTable, null, "vhea not needed since the font only contains Latin characters"); bFoundUnnecessary = true; } if (GetDirectoryEntry("vmtx") != null) { v.Warning(T.T_NULL, W._FONT_W_UnnecessaryTable, null, "vmtx not needed since the font only contains Latin characters"); bFoundUnnecessary = true; } } if (!bFoundUnnecessary) { v.Pass(P._FONT_P_UnnecessaryTable, null); } return bRet; } protected bool CheckForOptimalTableOrder(Validator v) { bool bRet = true; if (!GetFile().IsCollection()) // don't perform this test on .ttc files { string [] OrderedTables = null; string [] TTOrderedTables = { "head", "hhea", "maxp", "OS/2", "hmtx", "LTSH", "VDMX", "hdmx", "cmap", "fpgm", "prep", "cvt ", "loca", "glyf", "kern", "name", "post", "gasp", "PCLT" /*"DSIG"*/ }; string [] PSOrderedTables = { "head", "hhea", "maxp", "OS/2", "name", "cmap", "post", "CFF " }; if (ContainsTrueTypeOutlines()) { OrderedTables = TTOrderedTables; } else if (ContainsPostScriptOutlines()) { OrderedTables = PSOrderedTables; } if (OrderedTables != null) { Debug.Assert(m_OffsetTable != null); bool bOrderOk = true; if (m_OffsetTable != null) { for (int i=0; i<OrderedTables.Length-1; i++) { for (int j=i+1; j<OrderedTables.Length; j++) { DirectoryEntry deBefore = GetDirectoryEntry(OrderedTables[i]); DirectoryEntry deAfter = GetDirectoryEntry(OrderedTables[j]); if (deBefore != null && deAfter != null) { if (deBefore.offset > deAfter.offset) { string sDetails = "table '" + deAfter.tag + "' precedes table '" + deBefore.tag + "'"; v.Warning(T.T_NULL, W._FONT_W_OptimalOrder, null, sDetails); bOrderOk = false; break; } } } if (!bOrderOk) { break; } } } if (bOrderOk) { v.Pass(P._FONT_P_OptimalOrder, null); } } } return bRet; } //Checks the presence of the CFF table to decide whether the font file has or not PostScript outlines protected bool IsPostScript() { DirectoryEntry de_cff = GetDirectoryEntry("CFF "); Table_CFF cffTable = (Table_CFF)GetTable("CFF "); if (de_cff != null && cffTable != null) { return true; } return false; } //If it is OK, return > 0 //If it is faulty, return < 0 //If it has postscript outlines (can't rasterize for now, but it is ok) , return 0 protected int TestFontRasterization() { //Any font with postscript outlines instead of truetype outlines has a CFF, table //So, if the file has a CFF table, we return 0 promptly if (IsPostScript()) { m_sDevMetricsDataError = "Font has PostScript outlines, rasterization not yet implemented"; return 0; } // We do a sanity check here to make sure font meets minimal requirements before we will do // rasterization testing string s = "Unable to get data from rasterizer. "; DirectoryEntry de_head = GetDirectoryEntry("head"); Table_head headTable = (Table_head)GetTable("head"); if ( (de_head != null && headTable == null) || headTable == null) { m_sDevMetricsDataError = s + "'head' table is not present."; return -1; } if (headTable.GetLength() != 54) { m_sDevMetricsDataError = s + "'head' table length is invalid."; return -1; } if (headTable.magicNumber != 0x5f0f3cf5) { m_sDevMetricsDataError = s + "'head' table magic number is not correct."; return -1; } Table_maxp maxpTable = (Table_maxp)GetTable("maxp"); if (maxpTable == null) { m_sDevMetricsDataError = s + "'maxp' table is not present."; return -1; } uint val = maxpTable.TableVersionNumber.GetUint(); if ( (val == 0x00005000 && maxpTable.GetLength() != 6) || (val == 0x00010000 && maxpTable.GetLength() != 32)) { m_sDevMetricsDataError = s + "'maxp' table length is invalid."; return -1; } DirectoryEntry de_cvt = GetDirectoryEntry("cvt "); Table_cvt cvtTable = (Table_cvt)GetTable("cvt "); if (de_cvt != null && cvtTable == null) { m_sDevMetricsDataError = s + "'cvt ' table is not valid."; return -1; } DirectoryEntry de_glyf = GetDirectoryEntry("glyf"); Table_glyf glyfTable = (Table_glyf)GetTable("glyf"); if ( (de_glyf != null && glyfTable == null) || glyfTable == null) { m_sDevMetricsDataError = s + "'glyf' table is not valid."; return -1; } Table_hhea hheaTable = (Table_hhea)GetTable("hhea"); if (hheaTable == null) { m_sDevMetricsDataError = s + "'hhea' table is not present."; return -1; } return 1; } /************** * member data */ RasterInterf.DevMetricsData m_DevMetricsData; String m_sDevMetricsDataError; } }
// 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; using Microsoft.Build.Framework; using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.BackEnd; using Microsoft.Build.Logging; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Exceptions; using Microsoft.Build.Shared; using Microsoft.Build.UnitTests.BackEnd; using System.IO; using System.Threading; using System.Reflection; using System.Collections.Generic; using System.Linq; using Shouldly; using Xunit; namespace Microsoft.Build.UnitTests.Logging { /// <summary> /// Test the logging service component /// </summary> public class LoggingService_Tests { #region Data /// <summary> /// An already instantiated and initialized service. /// This is used so the host object does not need to be /// used in every test method. /// </summary> private LoggingService _initializedService; #endregion #region Setup /// <summary> /// This method is run before each test case is run. /// We instantiate and initialize a new logging service each time /// </summary> public LoggingService_Tests() { InitializeLoggingService(); } #endregion #region Test BuildComponent Methods /// <summary> /// Verify the CreateLogger method create a LoggingService in both Synchronous mode /// and Asynchronous mode. /// </summary> [Fact] public void CreateLogger() { // Generic host which has some default properties set inside of it IBuildComponent logServiceComponent = (IBuildComponent)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); // Create a synchronous logging service and do some quick checks Assert.NotNull(logServiceComponent); LoggingService logService = (LoggingService)logServiceComponent; Assert.Equal(LoggerMode.Synchronous, logService.LoggingMode); Assert.Equal(LoggingServiceState.Instantiated, logService.ServiceState); // Create an asynchronous logging service logServiceComponent = (IBuildComponent)LoggingService.CreateLoggingService(LoggerMode.Asynchronous, 1); Assert.NotNull(logServiceComponent); logService = (LoggingService)logServiceComponent; Assert.Equal(LoggerMode.Asynchronous, logService.LoggingMode); Assert.Equal(LoggingServiceState.Instantiated, logService.ServiceState); // Shutdown logging thread logServiceComponent.InitializeComponent(new MockHost()); logServiceComponent.ShutdownComponent(); Assert.Equal(LoggingServiceState.Shutdown, logService.ServiceState); } /// <summary> /// Test the IBuildComponent method InitializeComponent, make sure the component gets the parameters it expects /// </summary> [Fact] public void InitializeComponent() { IBuildComponent logServiceComponent = (IBuildComponent)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); BuildParameters parameters = new BuildParameters(); parameters.MaxNodeCount = 4; parameters.OnlyLogCriticalEvents = true; IBuildComponentHost loggingHost = new MockHost(parameters); // Make sure we are in the Instantiated state before initializing Assert.Equal(LoggingServiceState.Instantiated, ((LoggingService)logServiceComponent).ServiceState); logServiceComponent.InitializeComponent(loggingHost); // Make sure that the parameters in the host are set in the logging service LoggingService service = (LoggingService)logServiceComponent; Assert.Equal(LoggingServiceState.Initialized, service.ServiceState); Assert.Equal(4, service.MaxCPUCount); Assert.True(service.OnlyLogCriticalEvents); } /// <summary> /// Verify the correct exception is thrown when a null Component host is passed in /// </summary> [Fact] public void InitializeComponentNullHost() { Assert.Throws<InternalErrorException>(() => { IBuildComponent logServiceComponent = (IBuildComponent)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); logServiceComponent.InitializeComponent(null); } ); } /// <summary> /// Verify an exception is thrown if in initialized is called after the service has been shutdown /// </summary> [Fact] public void InitializeComponentAfterShutdown() { Assert.Throws<InternalErrorException>(() => { _initializedService.ShutdownComponent(); _initializedService.InitializeComponent(new MockHost()); } ); } /// <summary> /// Verify the correct exceptions are thrown if the loggers crash /// when they are shutdown /// </summary> [Fact] public void ShutDownComponentExceptionsInForwardingLogger() { // Cause a logger exception in the shutdown of the logger string className = "Microsoft.Build.UnitTests.Logging.LoggingService_Tests+ShutdownLoggerExceptionFL"; Type exceptionType = typeof(LoggerException); VerifyShutdownExceptions(null, className, exceptionType); Assert.Equal(LoggingServiceState.Shutdown, _initializedService.ServiceState); // Cause a general exception which should result in an InternalLoggerException className = "Microsoft.Build.UnitTests.Logging.LoggingService_Tests+ShutdownGeneralExceptionFL"; exceptionType = typeof(InternalLoggerException); VerifyShutdownExceptions(null, className, exceptionType); Assert.Equal(LoggingServiceState.Shutdown, _initializedService.ServiceState); #if FEATURE_VARIOUS_EXCEPTIONS // Cause a StackOverflow exception in the shutdown of the logger // this kind of exception should not be caught className = "Microsoft.Build.UnitTests.Logging.LoggingService_Tests+ShutdownStackoverflowExceptionFL"; exceptionType = typeof(StackOverflowException); VerifyShutdownExceptions(null, className, exceptionType); #endif Assert.Equal(LoggingServiceState.Shutdown, _initializedService.ServiceState); } /// <summary> /// Verify the correct exceptions are thrown when ILoggers /// throw exceptions during shutdown /// </summary> [Fact] public void ShutDownComponentExceptionsInLogger() { LoggerThrowException logger = new LoggerThrowException(true, false, new LoggerException("Hello")); VerifyShutdownExceptions(logger, null, typeof(LoggerException)); logger = new LoggerThrowException(true, false, new Exception("boo")); VerifyShutdownExceptions(logger, null, typeof(InternalLoggerException)); #if FEATURE_VARIOUS_EXCEPTIONS logger = new LoggerThrowException(true, false, new StackOverflowException()); VerifyShutdownExceptions(logger, null, typeof(StackOverflowException)); #endif Assert.Equal(LoggingServiceState.Shutdown, _initializedService.ServiceState); } /// <summary> /// Make sure an exception is thrown if shutdown is called /// more than once /// </summary> [Fact] public void DoubleShutdown() { Assert.Throws<InternalErrorException>(() => { _initializedService.ShutdownComponent(); _initializedService.ShutdownComponent(); } ); } #endregion #region RegisterLogger /// <summary> /// Verify we get an exception when a null logger is passed in /// </summary> [Fact] public void NullLogger() { Assert.Throws<InternalErrorException>(() => { _initializedService.RegisterLogger(null); } ); } /// <summary> /// Verify we get an exception when we try and register a logger /// and the system has already shutdown /// </summary> [Fact] public void RegisterLoggerServiceShutdown() { Assert.Throws<InternalErrorException>(() => { _initializedService.ShutdownComponent(); RegularILogger regularILogger = new RegularILogger(); _initializedService.RegisterLogger(regularILogger); } ); } /// <summary> /// Verify a logger exception when initializing a logger is rethrown /// as a logger exception /// </summary> [Fact] public void LoggerExceptionInInitialize() { Assert.Throws<LoggerException>(() => { LoggerThrowException exceptionLogger = new LoggerThrowException(false, true, new LoggerException()); _initializedService.RegisterLogger(exceptionLogger); } ); } /// <summary> /// Verify a general exception when initializing a logger is wrapped /// as a InternalLogger exception /// </summary> [Fact] public void GeneralExceptionInInitialize() { Assert.Throws<InternalLoggerException>(() => { LoggerThrowException exceptionLogger = new LoggerThrowException(false, true, new Exception()); _initializedService.RegisterLogger(exceptionLogger); } ); } #if FEATURE_VARIOUS_EXCEPTIONS /// <summary> /// Verify a critical exception is not wrapped /// </summary> [Fact] public void ILoggerExceptionInInitialize() { Assert.Throws<StackOverflowException>(() => { LoggerThrowException exceptionLogger = new LoggerThrowException(false, true, new StackOverflowException()); _initializedService.RegisterLogger(exceptionLogger); } ); } #endif /// <summary> /// Register an good Logger and verify it was registered. /// </summary> [Fact] public void RegisterILoggerAndINodeLoggerGood() { ConsoleLogger consoleLogger = new ConsoleLogger(); RegularILogger regularILogger = new RegularILogger(); Assert.True(_initializedService.RegisterLogger(consoleLogger)); Assert.True(_initializedService.RegisterLogger(regularILogger)); Assert.NotNull(_initializedService.RegisteredLoggerTypeNames); // Should have 2 central loggers and 1 forwarding logger Assert.Equal(3, _initializedService.RegisteredLoggerTypeNames.Count); Assert.Contains("Microsoft.Build.BackEnd.Logging.CentralForwardingLogger", _initializedService.RegisteredLoggerTypeNames); Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames); Assert.Contains("Microsoft.Build.Logging.ConsoleLogger", _initializedService.RegisteredLoggerTypeNames); // Should have 1 event sink Assert.NotNull(_initializedService.RegisteredSinkNames); Assert.Single(_initializedService.RegisteredSinkNames); } /// <summary> /// Try and register the same logger multiple times /// </summary> [Fact] public void RegisterDuplicateLogger() { ConsoleLogger consoleLogger = new ConsoleLogger(); RegularILogger regularILogger = new RegularILogger(); Assert.True(_initializedService.RegisterLogger(consoleLogger)); Assert.False(_initializedService.RegisterLogger(consoleLogger)); Assert.True(_initializedService.RegisterLogger(regularILogger)); Assert.False(_initializedService.RegisterLogger(regularILogger)); Assert.NotNull(_initializedService.RegisteredLoggerTypeNames); Assert.Equal(3, _initializedService.RegisteredLoggerTypeNames.Count); Assert.Contains("Microsoft.Build.BackEnd.Logging.CentralForwardingLogger", _initializedService.RegisteredLoggerTypeNames); Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames); Assert.Contains("Microsoft.Build.Logging.ConsoleLogger", _initializedService.RegisteredLoggerTypeNames); // Should have 1 event sink Assert.NotNull(_initializedService.RegisteredSinkNames); Assert.Single(_initializedService.RegisteredSinkNames); } #endregion #region RegisterDistributedLogger /// <summary> /// Verify we get an exception when a null logger forwarding logger is passed in /// </summary> [Fact] public void NullForwardingLogger() { Assert.Throws<InternalErrorException>(() => { _initializedService.RegisterDistributedLogger(null, null); } ); } /// <summary> /// Verify we get an exception when we try and register a distributed logger /// and the system has already shutdown /// </summary> [Fact] public void RegisterDistributedLoggerServiceShutdown() { Assert.Throws<InternalErrorException>(() => { _initializedService.ShutdownComponent(); string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; #if FEATURE_ASSEMBLY_LOCATION LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); #endif _initializedService.RegisterDistributedLogger(null, description); } ); } /// <summary> /// Register both a good central logger and a good forwarding logger /// </summary> [Fact] public void RegisterGoodDistributedAndCentralLogger() { string configurableClassName = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; string distributedClassName = "Microsoft.Build.Logging.DistributedFileLogger"; #if FEATURE_ASSEMBLY_LOCATION LoggerDescription configurableDescription = CreateLoggerDescription(configurableClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); LoggerDescription distributedDescription = CreateLoggerDescription(distributedClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else LoggerDescription configurableDescription = CreateLoggerDescription(configurableClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); LoggerDescription distributedDescription = CreateLoggerDescription(distributedClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); #endif DistributedFileLogger fileLogger = new DistributedFileLogger(); RegularILogger regularILogger = new RegularILogger(); Assert.True(_initializedService.RegisterDistributedLogger(regularILogger, configurableDescription)); Assert.True(_initializedService.RegisterDistributedLogger(null, distributedDescription)); Assert.NotNull(_initializedService.RegisteredLoggerTypeNames); // Should have 2 central loggers and 2 forwarding logger Assert.Equal(4, _initializedService.RegisteredLoggerTypeNames.Count); Assert.Contains("Microsoft.Build.Logging.ConfigurableForwardingLogger", _initializedService.RegisteredLoggerTypeNames); Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames); Assert.Contains("Microsoft.Build.Logging.DistributedFileLogger", _initializedService.RegisteredLoggerTypeNames); Assert.Contains("Microsoft.Build.BackEnd.Logging.NullCentralLogger", _initializedService.RegisteredLoggerTypeNames); // Should have 2 event sink Assert.NotNull(_initializedService.RegisteredSinkNames); Assert.Equal(2, _initializedService.RegisteredSinkNames.Count); Assert.Equal(2, _initializedService.LoggerDescriptions.Count); } /// <summary> /// Have a one forwarding logger which forwards build started and finished and have one which does not and a regular logger. Expect the central loggers to all get /// one build started and one build finished event only. /// </summary> [Fact] public void RegisterGoodDistributedAndCentralLoggerTestBuildStartedFinished() { string configurableClassNameA = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; string configurableClassNameB = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; #if FEATURE_ASSEMBLY_LOCATION LoggerDescription configurableDescriptionA = CreateLoggerDescription(configurableClassNameA, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); LoggerDescription configurableDescriptionB = CreateLoggerDescription(configurableClassNameB, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else LoggerDescription configurableDescriptionA = CreateLoggerDescription(configurableClassNameA, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); LoggerDescription configurableDescriptionB = CreateLoggerDescription(configurableClassNameB, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); #endif RegularILogger regularILoggerA = new RegularILogger(); RegularILogger regularILoggerB = new RegularILogger(); RegularILogger regularILoggerC = new RegularILogger(); Assert.True(_initializedService.RegisterDistributedLogger(regularILoggerA, configurableDescriptionA)); Assert.True(_initializedService.RegisterDistributedLogger(regularILoggerB, configurableDescriptionB)); Assert.True(_initializedService.RegisterLogger(regularILoggerC)); Assert.NotNull(_initializedService.RegisteredLoggerTypeNames); _initializedService.LogBuildStarted(); Assert.Equal(1, regularILoggerA.BuildStartedCount); Assert.Equal(1, regularILoggerB.BuildStartedCount); Assert.Equal(1, regularILoggerC.BuildStartedCount); _initializedService.LogBuildFinished(true); Assert.Equal(1, regularILoggerA.BuildFinishedCount); Assert.Equal(1, regularILoggerB.BuildFinishedCount); Assert.Equal(1, regularILoggerC.BuildFinishedCount); // Make sure if we call build started again we only get one other build started event. _initializedService.LogBuildStarted(); Assert.Equal(2, regularILoggerA.BuildStartedCount); Assert.Equal(2, regularILoggerB.BuildStartedCount); Assert.Equal(2, regularILoggerC.BuildStartedCount); // Make sure if we call build started again we only get one other build started event. _initializedService.LogBuildFinished(true); Assert.Equal(2, regularILoggerA.BuildFinishedCount); Assert.Equal(2, regularILoggerB.BuildFinishedCount); Assert.Equal(2, regularILoggerC.BuildFinishedCount); } /// <summary> /// Try and register a duplicate central logger /// </summary> [Fact] public void RegisterDuplicateCentralLogger() { string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; #if FEATURE_ASSEMBLY_LOCATION LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); #endif RegularILogger regularILogger = new RegularILogger(); Assert.True(_initializedService.RegisterDistributedLogger(regularILogger, description)); Assert.False(_initializedService.RegisterDistributedLogger(regularILogger, description)); // Should have 2 central loggers and 1 forwarding logger Assert.Equal(2, _initializedService.RegisteredLoggerTypeNames.Count); Assert.Contains("Microsoft.Build.Logging.ConfigurableForwardingLogger", _initializedService.RegisteredLoggerTypeNames); Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames); // Should have 1 sink Assert.NotNull(_initializedService.RegisteredSinkNames); Assert.Single(_initializedService.RegisteredSinkNames); Assert.Single(_initializedService.LoggerDescriptions); } /// <summary> /// Try and register a duplicate Forwarding logger /// </summary> [Fact] public void RegisterDuplicateForwardingLoggerLogger() { string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; #if FEATURE_ASSEMBLY_LOCATION LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); #endif RegularILogger regularILogger = new RegularILogger(); Assert.True(_initializedService.RegisterDistributedLogger(regularILogger, description)); Assert.True(_initializedService.RegisterDistributedLogger(null, description)); Assert.Equal(4, _initializedService.RegisteredLoggerTypeNames.Count); // Verify there are two versions in the type names, one for each description int countForwardingLogger = 0; foreach (string loggerName in _initializedService.RegisteredLoggerTypeNames) { if (String.Compare("Microsoft.Build.Logging.ConfigurableForwardingLogger", loggerName, StringComparison.OrdinalIgnoreCase) == 0) { countForwardingLogger++; } } Assert.Equal(2, countForwardingLogger); Assert.Contains("Microsoft.Build.BackEnd.Logging.NullCentralLogger", _initializedService.RegisteredLoggerTypeNames); Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames); // Should have 2 sink Assert.NotNull(_initializedService.RegisteredSinkNames); Assert.Equal(2, _initializedService.RegisteredSinkNames.Count); Assert.Equal(2, _initializedService.LoggerDescriptions.Count); } #endregion #region RegisterLoggerDescriptions /// <summary> /// Verify we get an exception when a null description collection is passed in /// </summary> [Fact] public void NullDescriptionCollection() { Assert.Throws<InternalErrorException>(() => { _initializedService.InitializeNodeLoggers(null, new EventSourceSink(), 3); } ); } /// <summary> /// Verify we get an exception when an empty description collection is passed in /// </summary> [Fact] public void EmptyDescriptionCollection() { Assert.Throws<InternalErrorException>(() => { _initializedService.InitializeNodeLoggers(new List<LoggerDescription>(), new EventSourceSink(), 3); } ); } /// <summary> /// Verify we get an exception when we try and register a description and the component has already shutdown /// </summary> [Fact] public void NullForwardingLoggerSink() { Assert.Throws<InternalErrorException>(() => { string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; #if FEATURE_ASSEMBLY_LOCATION LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); #endif _initializedService.ShutdownComponent(); List<LoggerDescription> tempList = new List<LoggerDescription>(); tempList.Add(description); _initializedService.InitializeNodeLoggers(tempList, new EventSourceSink(), 2); } ); } /// <summary> /// Register both a good central logger and a good forwarding logger /// </summary> [Fact] public void RegisterGoodDiscriptions() { string configurableClassName = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; string distributedClassName = "Microsoft.Build.BackEnd.Logging.CentralForwardingLogger"; EventSourceSink sink = new EventSourceSink(); EventSourceSink sink2 = new EventSourceSink(); List<LoggerDescription> loggerDescriptions = new List<LoggerDescription>(); #if FEATURE_ASSEMBLY_LOCATION loggerDescriptions.Add(CreateLoggerDescription(configurableClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true)); loggerDescriptions.Add(CreateLoggerDescription(distributedClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true)); #else loggerDescriptions.Add(CreateLoggerDescription(configurableClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true)); loggerDescriptions.Add(CreateLoggerDescription(distributedClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true)); #endif // Register some descriptions with a sink _initializedService.InitializeNodeLoggers(loggerDescriptions, sink, 1); // Register the same descriptions with another sink (so we can see that another sink was added) _initializedService.InitializeNodeLoggers(loggerDescriptions, sink2, 1); // Register the descriptions again with the same sink so we can verify that another sink was not created _initializedService.InitializeNodeLoggers(loggerDescriptions, sink, 1); Assert.NotNull(_initializedService.RegisteredLoggerTypeNames); // Should have 6 forwarding logger. three of each type Assert.Equal(6, _initializedService.RegisteredLoggerTypeNames.Count); Assert.Contains("Microsoft.Build.Logging.ConfigurableForwardingLogger", _initializedService.RegisteredLoggerTypeNames); Assert.Contains("Microsoft.Build.BackEnd.Logging.CentralForwardingLogger", _initializedService.RegisteredLoggerTypeNames); int countForwardingLogger = 0; foreach (string loggerName in _initializedService.RegisteredLoggerTypeNames) { if (String.Compare("Microsoft.Build.Logging.ConfigurableForwardingLogger", loggerName, StringComparison.OrdinalIgnoreCase) == 0) { countForwardingLogger++; } } // Should be 3, one for each call to RegisterLoggerDescriptions Assert.Equal(3, countForwardingLogger); countForwardingLogger = 0; foreach (string loggerName in _initializedService.RegisteredLoggerTypeNames) { if (String.Compare("Microsoft.Build.BackEnd.Logging.CentralForwardingLogger", loggerName, StringComparison.OrdinalIgnoreCase) == 0) { countForwardingLogger++; } } // Should be 3, one for each call to RegisterLoggerDescriptions Assert.Equal(3, countForwardingLogger); // Should have 2 event sink Assert.NotNull(_initializedService.RegisteredSinkNames); Assert.Equal(2, _initializedService.RegisteredSinkNames.Count); // There should not be any (this method is to be called on a child node) Assert.Empty(_initializedService.LoggerDescriptions); } /// <summary> /// Try and register a duplicate central logger /// </summary> [Fact] public void RegisterDuplicateDistributedCentralLogger() { string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; #if FEATURE_ASSEMBLY_LOCATION LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); #endif RegularILogger regularILogger = new RegularILogger(); Assert.True(_initializedService.RegisterDistributedLogger(regularILogger, description)); Assert.False(_initializedService.RegisterDistributedLogger(regularILogger, description)); // Should have 2 central loggers and 1 forwarding logger Assert.Equal(2, _initializedService.RegisteredLoggerTypeNames.Count); Assert.Contains("Microsoft.Build.Logging.ConfigurableForwardingLogger", _initializedService.RegisteredLoggerTypeNames); Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames); // Should have 1 sink Assert.NotNull(_initializedService.RegisteredSinkNames); Assert.Single(_initializedService.RegisteredSinkNames); Assert.Single(_initializedService.LoggerDescriptions); } #endregion #region Test Properties /// <summary> /// Verify the getters and setters for the properties work. /// </summary> [Fact] public void Properties() { // Test OnlyLogCriticalEvents LoggingService loggingService = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); Assert.False(loggingService.OnlyLogCriticalEvents); // "Expected only log critical events to be false" loggingService.OnlyLogCriticalEvents = true; Assert.True(loggingService.OnlyLogCriticalEvents); // "Expected only log critical events to be true" // Test LoggingMode Assert.Equal(LoggerMode.Synchronous, loggingService.LoggingMode); // "Expected Logging mode to be Synchronous" // Test LoggerDescriptions Assert.Empty(loggingService.LoggerDescriptions); // "Expected LoggerDescriptions to be empty" // Test Number of InitialNodes Assert.Equal(1, loggingService.MaxCPUCount); loggingService.MaxCPUCount = 5; Assert.Equal(5, loggingService.MaxCPUCount); } #endregion #region PacketHandling Tests /// <summary> /// Verify how a null packet is handled. There should be an InternalErrorException thrown /// </summary> [Fact] public void NullPacketReceived() { Assert.Throws<InternalErrorException>(() => { LoggingService loggingService = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); loggingService.PacketReceived(1, null); } ); } /// <summary> /// Verify when a non logging packet is received. /// An invalid operation should be thrown /// </summary> [Fact] public void NonLoggingPacketPacketReceived() { Assert.Throws<InternalErrorException>(() => { LoggingService loggingService = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); NonLoggingPacket packet = new NonLoggingPacket(); loggingService.PacketReceived(1, packet); } ); } /// <summary> /// Verify when a logging packet is received the build event is /// properly passed to ProcessLoggingEvent /// An invalid operation should be thrown /// </summary> [Fact] public void LoggingPacketReceived() { LoggingServicesLogMethod_Tests.ProcessBuildEventHelper loggingService = (LoggingServicesLogMethod_Tests.ProcessBuildEventHelper)LoggingServicesLogMethod_Tests.ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); BuildMessageEventArgs messageEvent = new BuildMessageEventArgs("MyMessage", "HelpKeyword", "Sender", MessageImportance.High); LogMessagePacket packet = new LogMessagePacket(new KeyValuePair<int, BuildEventArgs>(1, messageEvent)); loggingService.PacketReceived(1, packet); BuildMessageEventArgs messageEventFromPacket = loggingService.ProcessedBuildEvent as BuildMessageEventArgs; Assert.NotNull(messageEventFromPacket); Assert.Equal(messageEventFromPacket, messageEvent); // "Expected messages to match" } #endregion private static readonly BuildWarningEventArgs BuildWarningEventForTreatAsErrorOrMessageTests = new BuildWarningEventArgs("subcategory", "C94A41A90FFB4EF592BF98BA59BEE8AF", "file", 1, 2, 3, 4, "message", "helpKeyword", "senderName"); /// <summary> /// Verifies that a warning is logged as an error when it's warning code specified. /// </summary> [Theory] [InlineData(0, 1)] [InlineData(0, 2)] [InlineData(1, 1)] [InlineData(1, 2)] public void TreatWarningsAsErrorWhenSpecified(int loggerMode, int nodeId) { HashSet<string> warningsAsErrors = new HashSet<string> { "123", BuildWarningEventForTreatAsErrorOrMessageTests.Code, "ABC", }; MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsErrors); BuildErrorEventArgs actualBuildEvent = logger.Errors.ShouldHaveSingleItem(); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Code, actualBuildEvent.Code); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.File, actualBuildEvent.File); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ProjectFile, actualBuildEvent.ProjectFile); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Subcategory, actualBuildEvent.Subcategory); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.HelpKeyword, actualBuildEvent.HelpKeyword); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Message, actualBuildEvent.Message); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.SenderName, actualBuildEvent.SenderName); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ColumnNumber, actualBuildEvent.ColumnNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndColumnNumber, actualBuildEvent.EndColumnNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndLineNumber, actualBuildEvent.EndLineNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.LineNumber, actualBuildEvent.LineNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.BuildEventContext, actualBuildEvent.BuildEventContext); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Timestamp, actualBuildEvent.Timestamp); } /// <summary> /// Verifies that a warning is not treated as an error when other warning codes are specified. /// </summary> [Fact] public void NotTreatWarningsAsErrorWhenNotSpecified() { HashSet<string> warningsAsErrors = new HashSet<string> { "123", "ABC", }; MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, warningsAsErrors: warningsAsErrors); var actualEvent = logger.Warnings.ShouldHaveSingleItem(); actualEvent.ShouldBe(BuildWarningEventForTreatAsErrorOrMessageTests); } /// <summary> /// Verifies that a warning is not treated as an error when other warning codes are specified. /// </summary> [Theory] [InlineData(0, 1)] [InlineData(0, 2)] [InlineData(1, 1)] [InlineData(1, 2)] public void TreatWarningsAsErrorWhenAllSpecified(int loggerMode, int nodeId) { HashSet<string> warningsAsErrors = new HashSet<string>(); MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsErrors); logger.Errors.ShouldHaveSingleItem(); } /// <summary> /// Verifies that a warning is logged as a low importance message when it's warning code is specified. /// </summary> [Theory] [InlineData(0, 1)] [InlineData(0, 2)] [InlineData(1, 1)] [InlineData(1, 2)] public void TreatWarningsAsMessagesWhenSpecified(int loggerMode, int nodeId) { HashSet<string> warningsAsMessages = new HashSet<string> { "FOO", BuildWarningEventForTreatAsErrorOrMessageTests.Code, "BAR", }; MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsMessages: warningsAsMessages); BuildMessageEventArgs actualBuildEvent = logger.BuildMessageEvents.ShouldHaveSingleItem(); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.BuildEventContext, actualBuildEvent.BuildEventContext); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Code, actualBuildEvent.Code); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ColumnNumber, actualBuildEvent.ColumnNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndColumnNumber, actualBuildEvent.EndColumnNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndLineNumber, actualBuildEvent.EndLineNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.File, actualBuildEvent.File); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.HelpKeyword, actualBuildEvent.HelpKeyword); Assert.Equal(MessageImportance.Low, actualBuildEvent.Importance); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.LineNumber, actualBuildEvent.LineNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Message, actualBuildEvent.Message); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ProjectFile, actualBuildEvent.ProjectFile); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.SenderName, actualBuildEvent.SenderName); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Subcategory, actualBuildEvent.Subcategory); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Timestamp, actualBuildEvent.Timestamp); } /// <summary> /// Verifies that a warning is not treated as a low importance message when other warning codes are specified. /// </summary> [Fact] public void NotTreatWarningsAsMessagesWhenNotSpecified() { HashSet<string> warningsAsMessages = new HashSet<string> { "FOO", "BAR", }; MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, warningsAsMessages: warningsAsMessages); logger.Warnings.ShouldHaveSingleItem(); } /// <summary> /// Verifies that warnings are treated as an error for a particular project when codes are specified. /// </summary> [Theory] [InlineData(0, 1)] [InlineData(0, 2)] [InlineData(1, 1)] [InlineData(1, 2)] public void TreatWarningsAsErrorByProjectWhenSpecified(int loggerMode, int nodeId) { HashSet<string> warningsAsErrorsForProject = new HashSet<string> { "123", BuildWarningEventForTreatAsErrorOrMessageTests.Code, "ABC" }; MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsErrorsForProject: warningsAsErrorsForProject); BuildErrorEventArgs actualBuildEvent = logger.Errors.ShouldHaveSingleItem(); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Code, actualBuildEvent.Code); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.File, actualBuildEvent.File); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ProjectFile, actualBuildEvent.ProjectFile); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Subcategory, actualBuildEvent.Subcategory); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.HelpKeyword, actualBuildEvent.HelpKeyword); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Message, actualBuildEvent.Message); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.SenderName, actualBuildEvent.SenderName); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ColumnNumber, actualBuildEvent.ColumnNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndColumnNumber, actualBuildEvent.EndColumnNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndLineNumber, actualBuildEvent.EndLineNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.LineNumber, actualBuildEvent.LineNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.BuildEventContext, actualBuildEvent.BuildEventContext); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Timestamp, actualBuildEvent.Timestamp); } /// <summary> /// Verifies that all warnings are treated as errors for a particular project. /// </summary> [Theory] [InlineData(0, 1)] [InlineData(0, 2)] [InlineData(1, 1)] [InlineData(1, 2)] public void TreatWarningsAsErrorByProjectWhenAllSpecified(int loggerMode, int nodeId) { HashSet<string> warningsAsErrorsForProject = new HashSet<string>(); MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsErrorsForProject: warningsAsErrorsForProject); logger.Errors.ShouldHaveSingleItem(); } /// <summary> /// Verifies that warnings are treated as messages for a particular project. /// </summary> [Theory] [InlineData(0, 1)] [InlineData(0, 2)] [InlineData(1, 1)] [InlineData(1, 2)] public void TreatWarningsAsMessagesByProjectWhenSpecified(int loggerMode, int nodeId) { HashSet<string> warningsAsMessagesForProject = new HashSet<string> { "123", BuildWarningEventForTreatAsErrorOrMessageTests.Code, "ABC" }; MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsMessagesForProject: warningsAsMessagesForProject); BuildMessageEventArgs actualBuildEvent = logger.BuildMessageEvents.ShouldHaveSingleItem(); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.BuildEventContext, actualBuildEvent.BuildEventContext); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Code, actualBuildEvent.Code); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ColumnNumber, actualBuildEvent.ColumnNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndColumnNumber, actualBuildEvent.EndColumnNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndLineNumber, actualBuildEvent.EndLineNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.File, actualBuildEvent.File); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.HelpKeyword, actualBuildEvent.HelpKeyword); Assert.Equal(MessageImportance.Low, actualBuildEvent.Importance); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.LineNumber, actualBuildEvent.LineNumber); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Message, actualBuildEvent.Message); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ProjectFile, actualBuildEvent.ProjectFile); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.SenderName, actualBuildEvent.SenderName); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Subcategory, actualBuildEvent.Subcategory); Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Timestamp, actualBuildEvent.Timestamp); } private MockLogger GetLoggedEventsWithWarningsAsErrorsOrMessages( BuildEventArgs buildEvent, LoggerMode loggerMode = LoggerMode.Synchronous, int nodeId = 1, ISet<string> warningsAsErrors = null, ISet<string> warningsAsMessages = null, ISet<string> warningsAsErrorsForProject = null, ISet<string> warningsAsMessagesForProject = null) { IBuildComponentHost host = new MockHost(); BuildEventContext buildEventContext = new BuildEventContext( submissionId: 0, nodeId: 1, projectInstanceId: 2, projectContextId: -1, targetId: -1, taskId: -1); BuildRequestData buildRequestData = new BuildRequestData("projectFile", new Dictionary<string, string>(), "Current", new[] { "Build" }, null); ConfigCache configCache = host.GetComponent(BuildComponentType.ConfigCache) as ConfigCache; configCache.AddConfiguration(new BuildRequestConfiguration(buildEventContext.ProjectInstanceId, buildRequestData, buildRequestData.ExplicitlySpecifiedToolsVersion)); MockLogger logger = new MockLogger(); ILoggingService loggingService = LoggingService.CreateLoggingService(loggerMode, nodeId); ((IBuildComponent)loggingService).InitializeComponent(host); loggingService.RegisterLogger(logger); BuildEventContext projectStarted = loggingService.LogProjectStarted(buildEventContext, 0, buildEventContext.ProjectInstanceId, BuildEventContext.Invalid, "projectFile", "Build", Enumerable.Empty<DictionaryEntry>(), Enumerable.Empty<DictionaryEntry>()); if (warningsAsErrorsForProject != null) { loggingService.AddWarningsAsErrors(projectStarted, warningsAsErrorsForProject); } if (warningsAsMessagesForProject != null) { loggingService.AddWarningsAsMessages(projectStarted, warningsAsMessagesForProject); } loggingService.WarningsAsErrors = warningsAsErrors; loggingService.WarningsAsMessages = warningsAsMessages; buildEvent.BuildEventContext = projectStarted; loggingService.LogBuildEvent(buildEvent); loggingService.LogProjectFinished(projectStarted, "projectFile", true); while (logger.ProjectFinishedEvents.Count == 0) { Thread.Sleep(100); } ((IBuildComponent)loggingService).ShutdownComponent(); return logger; } #region PrivateMethods /// <summary> /// Instantiate and Initialize a new loggingService. /// This is used by the test setup method to create /// a new logging service before each test. /// </summary> private void InitializeLoggingService() { BuildParameters parameters = new BuildParameters(); parameters.MaxNodeCount = 2; MockHost mockHost = new MockHost(parameters); IBuildComponent logServiceComponent = (IBuildComponent)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); logServiceComponent.InitializeComponent(mockHost); _initializedService = logServiceComponent as LoggingService; } /// <summary> /// Register the correct logger and then call the shutdownComponent method. /// This will call shutdown on the loggers, we should expect to see certain exceptions. /// </summary> /// <param name="logger">Logger to register, this will only be used if className is null</param> /// <param name="className">ClassName to instantiate a new distributed logger</param> /// <param name="expectedExceptionType">Exception type which is expected to be thrown</param> private void VerifyShutdownExceptions(ILogger logger, string className, Type expectedExceptionType) { InitializeLoggingService(); if (className != null) { #if FEATURE_ASSEMBLY_LOCATION Assembly thisAssembly = Assembly.GetAssembly(typeof(LoggingService_Tests)); #else Assembly thisAssembly = typeof(LoggingService_Tests).GetTypeInfo().Assembly; #endif string loggerAssemblyName = thisAssembly.FullName; LoggerDescription centralLoggerDescrption = CreateLoggerDescription(className, loggerAssemblyName, true); _initializedService.RegisterDistributedLogger(null, centralLoggerDescrption); } else { _initializedService.RegisterLogger(logger); } try { _initializedService.ShutdownComponent(); Assert.True(false, "No Exceptions Generated"); } catch (Exception e) { if (e.GetType() != expectedExceptionType) { Assert.True(false, "Expected a " + expectedExceptionType + " but got a " + e.GetType() + " Stack:" + e.ToString()); } } } /// <summary> /// Create a logger description from the class name and logger assembly /// This is used in any test which needs to register a distributed logger. /// </summary> /// <param name="loggerClassName">Fully qualified class name (don't for get ParentClass+Nestedclass, if nested)</param> /// <param name="loggerAssemblyName">Assembly name which contains class</param> /// <returns>A logger description which can be registered</returns> private LoggerDescription CreateLoggerDescription(string loggerClassName, string loggerAssemblyName, bool forwardAllEvents) { string eventsToForward = "CustomEvent"; if (forwardAllEvents == true) { eventsToForward = "BuildStartedEvent;BuildFinishedEvent;ProjectStartedEvent;ProjectFinishedEvent;TargetStartedEvent;TargetFinishedEvent;TaskStartedEvent;TaskFinishedEvent;ErrorEvent;WarningEvent;HighMessageEvent;NormalMessageEvent;LowMessageEvent;CustomEvent;CommandLine"; } LoggerDescription centralLoggerDescrption = new LoggerDescription ( loggerClassName, loggerAssemblyName, null /*Not needed as we are loading from current assembly*/, eventsToForward, LoggerVerbosity.Diagnostic /*Not used, but the spirit of the logger is to forward everything so this is the most appropriate verbosity */ ); return centralLoggerDescrption; } #endregion #region HelperClasses /// <summary> /// A forwarding logger which will throw an exception /// </summary> public class BaseFLThrowException : LoggerThrowException, IForwardingLogger { #region Constructor /// <summary> /// Create a forwarding logger which will throw an exception on initialize or shutdown /// </summary> /// <param name="throwOnShutdown">Throw exception on shutdown</param> /// <param name="throwOnInitialize">Throw exception on initialize</param> /// <param name="exception">Exception to throw</param> internal BaseFLThrowException(bool throwOnShutdown, bool throwOnInitialize, Exception exception) : base(throwOnShutdown, throwOnInitialize, exception) { } #endregion #region IForwardingLogger Members /// <summary> /// Not used, implemented due to interface /// </summary> /// <value>Notused</value> public IEventRedirector BuildEventRedirector { get; set; } /// <summary> /// Not used, implemented due to interface /// </summary> /// <value>Not used</value> public int NodeId { get; set; } #endregion } /// <summary> /// Forwarding logger which throws a logger exception in the shutdown method. /// This is to test the logging service exception handling. /// </summary> public class ShutdownLoggerExceptionFL : BaseFLThrowException { /// <summary> /// Create a logger which will throw a logger exception /// in the shutdown method /// </summary> public ShutdownLoggerExceptionFL() : base(true, false, new LoggerException("Hello")) { } } /// <summary> /// Forwarding logger which will throw a general exception in the shutdown method /// This is used to test the logging service shutdown handling method. /// </summary> public class ShutdownGeneralExceptionFL : BaseFLThrowException { /// <summary> /// Create a logger which logs a general exception in the shutdown method /// </summary> public ShutdownGeneralExceptionFL() : base(true, false, new Exception("Hello")) { } } #if FEATURE_VARIOUS_EXCEPTIONS /// <summary> /// Forwarding logger which will throw a StackOverflowException /// in the shutdown method. This is to test the shutdown exception handling /// </summary> public class ShutdownStackoverflowExceptionFL : BaseFLThrowException { /// <summary> /// Create a logger which will throw a StackOverflow exception /// in the shutdown method. /// </summary> public ShutdownStackoverflowExceptionFL() : base(true, false, new StackOverflowException()) { } } #endif /// <summary> /// Logger which can throw a defined exception in the initialize or shutdown methods /// </summary> public class LoggerThrowException : INodeLogger { #region Constructor /// <summary> /// Constructor to tell the logger when to throw an exception and what exception /// to throw /// </summary> /// <param name="throwOnShutdown">True, throw the exception when shutdown is called</param> /// <param name="throwOnInitialize">True, throw the exception when Initialize is called</param> /// <param name="exception">The exception to throw</param> internal LoggerThrowException(bool throwOnShutdown, bool throwOnInitialize, Exception exception) { ExceptionToThrow = exception; ThrowExceptionOnShutdown = throwOnShutdown; ThrowExceptionOnInitialize = throwOnInitialize; } #endregion #region Properties /// <summary> /// Not used, implemented due to ILoggerInterface /// </summary> /// <value>Not used</value> public LoggerVerbosity Verbosity { get; set; } /// <summary> /// Not used, implemented due to ILoggerInterface /// </summary> /// <value>Not used</value> public string Parameters { get; set; } /// <summary> /// Should the exception be thrown on the call to shutdown /// </summary> /// <value>Not used</value> protected bool ThrowExceptionOnShutdown { get; set; } /// <summary> /// Should the exception be thrown on the call to initialize /// </summary> /// <value>Not used</value> protected bool ThrowExceptionOnInitialize { get; set; } /// <summary> /// The exception which will be thrown in shutdown or initialize /// </summary> /// <value>Not used</value> protected Exception ExceptionToThrow { get; set; } #endregion #region ILogger Members /// <summary> /// Initialize the logger, throw an exception /// if ThrowExceptionOnInitialize is set /// </summary> /// <param name="eventSource">Not used</param> public void Initialize(IEventSource eventSource) { if (ThrowExceptionOnInitialize && ExceptionToThrow != null) { throw ExceptionToThrow; } } /// <summary> /// Shutdown the logger, throw an exception if /// ThrowExceptionOnShutdown is set /// </summary> public void Shutdown() { if (ThrowExceptionOnShutdown && ExceptionToThrow != null) { throw ExceptionToThrow; } } /// <summary> /// Initialize using the INodeLogger Interface /// </summary> /// <param name="eventSource">Not used</param> /// <param name="nodeCount">Not used</param> public void Initialize(IEventSource eventSource, int nodeCount) { Initialize(eventSource); } #endregion } /// <summary> /// Create a regular ILogger to test Registering ILoggers. /// </summary> public class RegularILogger : ILogger { #region Properties /// <summary> /// ParametersForTheLogger /// </summary> public string Parameters { get; set; } /// <summary> /// Verbosity /// </summary> public LoggerVerbosity Verbosity { get; set; } /// <summary> /// Number of times build started was logged /// </summary> internal int BuildStartedCount { get; set; } /// <summary> /// Number of times build finished was logged /// </summary> internal int BuildFinishedCount { get; set; } /// <summary> /// Initialize /// </summary> public void Initialize(IEventSource eventSource) { eventSource.AnyEventRaised += new AnyEventHandler(LoggerEventHandler); } /// <summary> /// DoNothing /// </summary> public void Shutdown() { // do nothing } /// <summary> /// Log the event /// </summary> internal void LoggerEventHandler(object sender, BuildEventArgs eventArgs) { if (eventArgs is BuildStartedEventArgs) { ++BuildStartedCount; } if (eventArgs is BuildFinishedEventArgs) { ++BuildFinishedCount; } } } /// <summary> /// Create a regular ILogger which keeps track of how many of each event were logged /// </summary> public class TestLogger : ILogger { /// <summary> /// Not Used /// </summary> /// <value>Not used</value> public LoggerVerbosity Verbosity { get; set; } /// <summary> /// Do Nothing /// </summary> /// <value>Not Used</value> public string Parameters { get; set; } /// <summary> /// Do Nothing /// </summary> /// <param name="eventSource">Not Used</param> public void Initialize(IEventSource eventSource) { } /// <summary> /// Do Nothing /// </summary> public void Shutdown() { } #endregion } /// <summary> /// Create a non logging packet to test the packet handling code /// </summary> internal class NonLoggingPacket : INodePacket { #region Members /// <summary> /// Inform users of the class, this class is a BuildRequest packet /// </summary> public NodePacketType Type { get { return NodePacketType.BuildRequest; } } /// <summary> /// Serialize the packet /// </summary> public void Translate(ITranslator translator) { throw new NotImplementedException(); } #endregion } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Apache.NMS.Util; using System; using System.IO; namespace Apache.NMS.Stomp.Commands { public class BytesMessage : Message, IBytesMessage { private EndianBinaryReader dataIn; private EndianBinaryWriter dataOut; private MemoryStream outputBuffer; private int length; public override byte GetDataStructureType() { return DataStructureTypes.BytesMessageType; } public override Object Clone() { StoreContent(); return base.Clone(); } public override void OnSend() { base.OnSend(); StoreContent(); } public override void ClearBody() { base.ClearBody(); this.outputBuffer = null; this.dataIn = null; this.dataOut = null; this.length = 0; } public long BodyLength { get { InitializeReading(); return this.length; } } public byte ReadByte() { InitializeReading(); try { return dataIn.ReadByte(); } catch(EndOfStreamException e) { throw NMSExceptionSupport.CreateMessageEOFException(e); } catch(IOException e) { throw NMSExceptionSupport.CreateMessageFormatException(e); } } public void WriteByte( byte value ) { InitializeWriting(); try { dataOut.Write( value ); } catch(Exception e) { throw NMSExceptionSupport.Create(e); } } public bool ReadBoolean() { InitializeReading(); try { return dataIn.ReadBoolean(); } catch(EndOfStreamException e) { throw NMSExceptionSupport.CreateMessageEOFException(e); } catch(IOException e) { throw NMSExceptionSupport.CreateMessageFormatException(e); } } public void WriteBoolean( bool value ) { InitializeWriting(); try { dataOut.Write( value ); } catch(Exception e) { throw NMSExceptionSupport.Create(e); } } public char ReadChar() { InitializeReading(); try { return dataIn.ReadChar(); } catch(EndOfStreamException e) { throw NMSExceptionSupport.CreateMessageEOFException(e); } catch(IOException e) { throw NMSExceptionSupport.CreateMessageFormatException(e); } } public void WriteChar( char value ) { InitializeWriting(); try { dataOut.Write( value ); } catch(Exception e) { throw NMSExceptionSupport.Create(e); } } public short ReadInt16() { InitializeReading(); try { return dataIn.ReadInt16(); } catch(EndOfStreamException e) { throw NMSExceptionSupport.CreateMessageEOFException(e); } catch(IOException e) { throw NMSExceptionSupport.CreateMessageFormatException(e); } } public void WriteInt16( short value ) { InitializeWriting(); try { dataOut.Write( value ); } catch(Exception e) { throw NMSExceptionSupport.Create(e); } } public int ReadInt32() { InitializeReading(); try { return dataIn.ReadInt32(); } catch(EndOfStreamException e) { throw NMSExceptionSupport.CreateMessageEOFException(e); } catch(IOException e) { throw NMSExceptionSupport.CreateMessageFormatException(e); } } public void WriteInt32( int value ) { InitializeWriting(); try { dataOut.Write( value ); } catch(Exception e) { throw NMSExceptionSupport.Create(e); } } public long ReadInt64() { InitializeReading(); try { return dataIn.ReadInt64(); } catch(EndOfStreamException e) { throw NMSExceptionSupport.CreateMessageEOFException(e); } catch(IOException e) { throw NMSExceptionSupport.CreateMessageFormatException(e); } } public void WriteInt64( long value ) { InitializeWriting(); try { dataOut.Write( value ); } catch(Exception e) { throw NMSExceptionSupport.Create(e); } } public float ReadSingle() { InitializeReading(); try { return dataIn.ReadSingle(); } catch(EndOfStreamException e) { throw NMSExceptionSupport.CreateMessageEOFException(e); } catch(IOException e) { throw NMSExceptionSupport.CreateMessageFormatException(e); } } public void WriteSingle( float value ) { InitializeWriting(); try { dataOut.Write( value ); } catch(Exception e) { throw NMSExceptionSupport.Create(e); } } public double ReadDouble() { InitializeReading(); try { return dataIn.ReadDouble(); } catch(EndOfStreamException e) { throw NMSExceptionSupport.CreateMessageEOFException(e); } catch(IOException e) { throw NMSExceptionSupport.CreateMessageFormatException(e); } } public void WriteDouble( double value ) { InitializeWriting(); try { dataOut.Write( value ); } catch(Exception e) { throw NMSExceptionSupport.Create(e); } } public int ReadBytes( byte[] value ) { InitializeReading(); try { return dataIn.Read( value, 0, value.Length ); } catch(EndOfStreamException e) { throw NMSExceptionSupport.CreateMessageEOFException(e); } catch(IOException e) { throw NMSExceptionSupport.CreateMessageFormatException(e); } } public int ReadBytes( byte[] value, int length ) { InitializeReading(); try { return dataIn.Read( value, 0, length ); } catch(EndOfStreamException e) { throw NMSExceptionSupport.CreateMessageEOFException(e); } catch(IOException e) { throw NMSExceptionSupport.CreateMessageFormatException(e); } } public void WriteBytes( byte[] value ) { InitializeWriting(); try { dataOut.Write( value, 0, value.Length ); } catch(Exception e) { throw NMSExceptionSupport.Create(e); } } public void WriteBytes( byte[] value, int offset, int length ) { InitializeWriting(); try { dataOut.Write( value, offset, length ); } catch(Exception e) { throw NMSExceptionSupport.Create(e); } } public string ReadString() { InitializeReading(); try { // JMS, CMS and NMS all encode the String using a 16 bit size header. return dataIn.ReadString16(); } catch(EndOfStreamException e) { throw NMSExceptionSupport.CreateMessageEOFException(e); } catch(IOException e) { throw NMSExceptionSupport.CreateMessageFormatException(e); } } public void WriteString( string value ) { InitializeWriting(); try { // JMS, CMS and NMS all encode the String using a 16 bit size header. dataOut.WriteString16(value); } catch(Exception e) { throw NMSExceptionSupport.Create(e); } } public void WriteObject( System.Object value ) { InitializeWriting(); if( value is System.Byte ) { this.dataOut.Write( (byte) value ); } else if( value is Char ) { this.dataOut.Write( (char) value ); } else if( value is Boolean ) { this.dataOut.Write( (bool) value ); } else if( value is Int16 ) { this.dataOut.Write( (short) value ); } else if( value is Int32 ) { this.dataOut.Write( (int) value ); } else if( value is Int64 ) { this.dataOut.Write( (long) value ); } else if( value is Single ) { this.dataOut.Write( (float) value ); } else if( value is Double ) { this.dataOut.Write( (double) value ); } else if( value is byte[] ) { this.dataOut.Write( (byte[]) value ); } else if( value is String ) { this.dataOut.WriteString16( (string) value ); } else { throw new MessageFormatException("Cannot write non-primitive type:" + value.GetType()); } } public new byte[] Content { get { byte[] buffer = null; InitializeReading(); if(this.length != 0) { buffer = new byte[this.length]; this.dataIn.Read(buffer, 0, buffer.Length); } return buffer; } set { InitializeWriting(); this.dataOut.Write(value, 0, value.Length); } } public void Reset() { StoreContent(); this.dataIn = null; this.dataOut = null; this.outputBuffer = null; this.ReadOnlyBody = true; } private void InitializeReading() { FailIfWriteOnlyBody(); if(this.dataIn == null) { byte[] data = base.Content; if(base.Content == null) { data = new byte[0]; } Stream target = new MemoryStream(data, false); this.length = data.Length; this.dataIn = new EndianBinaryReader(target); } } private void InitializeWriting() { FailIfReadOnlyBody(); if(this.dataOut == null) { this.outputBuffer = new MemoryStream(); this.dataOut = new EndianBinaryWriter(this.outputBuffer); } } private void StoreContent() { if(this.dataOut != null) { this.dataOut.Close(); base.Content = outputBuffer.ToArray(); this.dataOut = null; this.outputBuffer = null; } } } }
using System; using Raksha.Crypto.Modes; using Raksha.Crypto.Paddings; namespace Raksha.Crypto.Macs { /** * CMAC - as specified at www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html * <p> * CMAC is analogous to OMAC1 - see also en.wikipedia.org/wiki/CMAC * </p><p> * CMAC is a NIST recomendation - see * csrc.nist.gov/CryptoToolkit/modes/800-38_Series_Publications/SP800-38B.pdf * </p><p> * CMAC/OMAC1 is a blockcipher-based message authentication code designed and * analyzed by Tetsu Iwata and Kaoru Kurosawa. * </p><p> * CMAC/OMAC1 is a simple variant of the CBC MAC (Cipher Block Chaining Message * Authentication Code). OMAC stands for One-Key CBC MAC. * </p><p> * It supports 128- or 64-bits block ciphers, with any key size, and returns * a MAC with dimension less or equal to the block size of the underlying * cipher. * </p> */ public class CMac : IMac { private const byte CONSTANT_128 = (byte)0x87; private const byte CONSTANT_64 = (byte)0x1b; private byte[] ZEROES; private byte[] mac; private byte[] buf; private int bufOff; private IBlockCipher cipher; private int macSize; private byte[] L, Lu, Lu2; /** * create a standard MAC based on a CBC block cipher (64 or 128 bit block). * This will produce an authentication code the length of the block size * of the cipher. * * @param cipher the cipher to be used as the basis of the MAC generation. */ public CMac( IBlockCipher cipher) : this(cipher, cipher.GetBlockSize() * 8) { } /** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. * <p/> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * * @param cipher the cipher to be used as the basis of the MAC generation. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8 and @lt;= 128. */ public CMac( IBlockCipher cipher, int macSizeInBits) { if ((macSizeInBits % 8) != 0) throw new ArgumentException("MAC size must be multiple of 8"); if (macSizeInBits > (cipher.GetBlockSize() * 8)) { throw new ArgumentException( "MAC size must be less or equal to " + (cipher.GetBlockSize() * 8)); } if (cipher.GetBlockSize() != 8 && cipher.GetBlockSize() != 16) { throw new ArgumentException( "Block size must be either 64 or 128 bits"); } this.cipher = new CbcBlockCipher(cipher); this.macSize = macSizeInBits / 8; mac = new byte[cipher.GetBlockSize()]; buf = new byte[cipher.GetBlockSize()]; ZEROES = new byte[cipher.GetBlockSize()]; bufOff = 0; } public string AlgorithmName { get { return cipher.AlgorithmName; } } private byte[] doubleLu( byte[] inBytes) { int FirstBit = (inBytes[0] & 0xFF) >> 7; byte[] ret = new byte[inBytes.Length]; for (int i = 0; i < inBytes.Length - 1; i++) { ret[i] = (byte)((inBytes[i] << 1) + ((inBytes[i + 1] & 0xFF) >> 7)); } ret[inBytes.Length - 1] = (byte)(inBytes[inBytes.Length - 1] << 1); if (FirstBit == 1) { ret[inBytes.Length - 1] ^= inBytes.Length == 16 ? CONSTANT_128 : CONSTANT_64; } return ret; } public void Init( ICipherParameters parameters) { Reset(); cipher.Init(true, parameters); //initializes the L, Lu, Lu2 numbers L = new byte[ZEROES.Length]; cipher.ProcessBlock(ZEROES, 0, L, 0); Lu = doubleLu(L); Lu2 = doubleLu(Lu); cipher.Init(true, parameters); } public int GetMacSize() { return macSize; } public void Update( byte input) { if (bufOff == buf.Length) { cipher.ProcessBlock(buf, 0, mac, 0); bufOff = 0; } buf[bufOff++] = input; } public void BlockUpdate( byte[] inBytes, int inOff, int len) { if (len < 0) throw new ArgumentException("Can't have a negative input length!"); int blockSize = cipher.GetBlockSize(); int gapLen = blockSize - bufOff; if (len > gapLen) { Array.Copy(inBytes, inOff, buf, bufOff, gapLen); cipher.ProcessBlock(buf, 0, mac, 0); bufOff = 0; len -= gapLen; inOff += gapLen; while (len > blockSize) { cipher.ProcessBlock(inBytes, inOff, mac, 0); len -= blockSize; inOff += blockSize; } } Array.Copy(inBytes, inOff, buf, bufOff, len); bufOff += len; } public int DoFinal( byte[] outBytes, int outOff) { int blockSize = cipher.GetBlockSize(); byte[] lu; if (bufOff == blockSize) { lu = Lu; } else { new ISO7816d4Padding().AddPadding(buf, bufOff); lu = Lu2; } for (int i = 0; i < mac.Length; i++) { buf[i] ^= lu[i]; } cipher.ProcessBlock(buf, 0, mac, 0); Array.Copy(mac, 0, outBytes, outOff, macSize); Reset(); return macSize; } /** * Reset the mac generator. */ public void Reset() { /* * clean the buffer. */ Array.Clear(buf, 0, buf.Length); bufOff = 0; /* * Reset the underlying cipher. */ cipher.Reset(); } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace FickleFrostbite.FIT { /// <summary> /// Implements the BikeProfile profile message. /// </summary> public class BikeProfileMesg : Mesg { #region Fields #endregion #region Constructors public BikeProfileMesg() : base(Profile.mesgs[Profile.BikeProfileIndex]) { } public BikeProfileMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the MessageIndex field</summary> /// <returns>Returns nullable ushort representing the MessageIndex field</returns> public ushort? GetMessageIndex() { return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set MessageIndex field</summary> /// <param name="messageIndex_">Nullable field value to be set</param> public void SetMessageIndex(ushort? messageIndex_) { SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Name field</summary> /// <returns>Returns byte[] representing the Name field</returns> public byte[] GetName() { return (byte[])GetFieldValue(0, 0, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Name field</summary> /// <returns>Returns String representing the Name field</returns> public String GetNameAsString() { return Encoding.UTF8.GetString((byte[])GetFieldValue(0, 0, Fit.SubfieldIndexMainField)); } ///<summary> /// Set Name field</summary> /// <returns>Returns String representing the Name field</returns> public void SetName(String name_) { SetFieldValue(0, 0, System.Text.Encoding.UTF8.GetBytes(name_), Fit.SubfieldIndexMainField); } /// <summary> /// Set Name field</summary> /// <param name="name_">field value to be set</param> public void SetName(byte[] name_) { SetFieldValue(0, 0, name_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Sport field</summary> /// <returns>Returns nullable Sport enum representing the Sport field</returns> public Sport? GetSport() { object obj = GetFieldValue(1, 0, Fit.SubfieldIndexMainField); Sport? value = obj == null ? (Sport?)null : (Sport)obj; return value; } /// <summary> /// Set Sport field</summary> /// <param name="sport_">Nullable field value to be set</param> public void SetSport(Sport? sport_) { SetFieldValue(1, 0, sport_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SubSport field</summary> /// <returns>Returns nullable SubSport enum representing the SubSport field</returns> public SubSport? GetSubSport() { object obj = GetFieldValue(2, 0, Fit.SubfieldIndexMainField); SubSport? value = obj == null ? (SubSport?)null : (SubSport)obj; return value; } /// <summary> /// Set SubSport field</summary> /// <param name="subSport_">Nullable field value to be set</param> public void SetSubSport(SubSport? subSport_) { SetFieldValue(2, 0, subSport_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Odometer field /// Units: m</summary> /// <returns>Returns nullable float representing the Odometer field</returns> public float? GetOdometer() { return (float?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Odometer field /// Units: m</summary> /// <param name="odometer_">Nullable field value to be set</param> public void SetOdometer(float? odometer_) { SetFieldValue(3, 0, odometer_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BikeSpdAntId field</summary> /// <returns>Returns nullable ushort representing the BikeSpdAntId field</returns> public ushort? GetBikeSpdAntId() { return (ushort?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BikeSpdAntId field</summary> /// <param name="bikeSpdAntId_">Nullable field value to be set</param> public void SetBikeSpdAntId(ushort? bikeSpdAntId_) { SetFieldValue(4, 0, bikeSpdAntId_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BikeCadAntId field</summary> /// <returns>Returns nullable ushort representing the BikeCadAntId field</returns> public ushort? GetBikeCadAntId() { return (ushort?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BikeCadAntId field</summary> /// <param name="bikeCadAntId_">Nullable field value to be set</param> public void SetBikeCadAntId(ushort? bikeCadAntId_) { SetFieldValue(5, 0, bikeCadAntId_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BikeSpdcadAntId field</summary> /// <returns>Returns nullable ushort representing the BikeSpdcadAntId field</returns> public ushort? GetBikeSpdcadAntId() { return (ushort?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BikeSpdcadAntId field</summary> /// <param name="bikeSpdcadAntId_">Nullable field value to be set</param> public void SetBikeSpdcadAntId(ushort? bikeSpdcadAntId_) { SetFieldValue(6, 0, bikeSpdcadAntId_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BikePowerAntId field</summary> /// <returns>Returns nullable ushort representing the BikePowerAntId field</returns> public ushort? GetBikePowerAntId() { return (ushort?)GetFieldValue(7, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BikePowerAntId field</summary> /// <param name="bikePowerAntId_">Nullable field value to be set</param> public void SetBikePowerAntId(ushort? bikePowerAntId_) { SetFieldValue(7, 0, bikePowerAntId_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CustomWheelsize field /// Units: m</summary> /// <returns>Returns nullable float representing the CustomWheelsize field</returns> public float? GetCustomWheelsize() { return (float?)GetFieldValue(8, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set CustomWheelsize field /// Units: m</summary> /// <param name="customWheelsize_">Nullable field value to be set</param> public void SetCustomWheelsize(float? customWheelsize_) { SetFieldValue(8, 0, customWheelsize_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the AutoWheelsize field /// Units: m</summary> /// <returns>Returns nullable float representing the AutoWheelsize field</returns> public float? GetAutoWheelsize() { return (float?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set AutoWheelsize field /// Units: m</summary> /// <param name="autoWheelsize_">Nullable field value to be set</param> public void SetAutoWheelsize(float? autoWheelsize_) { SetFieldValue(9, 0, autoWheelsize_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BikeWeight field /// Units: kg</summary> /// <returns>Returns nullable float representing the BikeWeight field</returns> public float? GetBikeWeight() { return (float?)GetFieldValue(10, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BikeWeight field /// Units: kg</summary> /// <param name="bikeWeight_">Nullable field value to be set</param> public void SetBikeWeight(float? bikeWeight_) { SetFieldValue(10, 0, bikeWeight_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the PowerCalFactor field /// Units: %</summary> /// <returns>Returns nullable float representing the PowerCalFactor field</returns> public float? GetPowerCalFactor() { return (float?)GetFieldValue(11, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set PowerCalFactor field /// Units: %</summary> /// <param name="powerCalFactor_">Nullable field value to be set</param> public void SetPowerCalFactor(float? powerCalFactor_) { SetFieldValue(11, 0, powerCalFactor_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the AutoWheelCal field</summary> /// <returns>Returns nullable Bool enum representing the AutoWheelCal field</returns> public Bool? GetAutoWheelCal() { object obj = GetFieldValue(12, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set AutoWheelCal field</summary> /// <param name="autoWheelCal_">Nullable field value to be set</param> public void SetAutoWheelCal(Bool? autoWheelCal_) { SetFieldValue(12, 0, autoWheelCal_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the AutoPowerZero field</summary> /// <returns>Returns nullable Bool enum representing the AutoPowerZero field</returns> public Bool? GetAutoPowerZero() { object obj = GetFieldValue(13, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set AutoPowerZero field</summary> /// <param name="autoPowerZero_">Nullable field value to be set</param> public void SetAutoPowerZero(Bool? autoPowerZero_) { SetFieldValue(13, 0, autoPowerZero_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Id field</summary> /// <returns>Returns nullable byte representing the Id field</returns> public byte? GetId() { return (byte?)GetFieldValue(14, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Id field</summary> /// <param name="id_">Nullable field value to be set</param> public void SetId(byte? id_) { SetFieldValue(14, 0, id_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SpdEnabled field</summary> /// <returns>Returns nullable Bool enum representing the SpdEnabled field</returns> public Bool? GetSpdEnabled() { object obj = GetFieldValue(15, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set SpdEnabled field</summary> /// <param name="spdEnabled_">Nullable field value to be set</param> public void SetSpdEnabled(Bool? spdEnabled_) { SetFieldValue(15, 0, spdEnabled_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CadEnabled field</summary> /// <returns>Returns nullable Bool enum representing the CadEnabled field</returns> public Bool? GetCadEnabled() { object obj = GetFieldValue(16, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set CadEnabled field</summary> /// <param name="cadEnabled_">Nullable field value to be set</param> public void SetCadEnabled(Bool? cadEnabled_) { SetFieldValue(16, 0, cadEnabled_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SpdcadEnabled field</summary> /// <returns>Returns nullable Bool enum representing the SpdcadEnabled field</returns> public Bool? GetSpdcadEnabled() { object obj = GetFieldValue(17, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set SpdcadEnabled field</summary> /// <param name="spdcadEnabled_">Nullable field value to be set</param> public void SetSpdcadEnabled(Bool? spdcadEnabled_) { SetFieldValue(17, 0, spdcadEnabled_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the PowerEnabled field</summary> /// <returns>Returns nullable Bool enum representing the PowerEnabled field</returns> public Bool? GetPowerEnabled() { object obj = GetFieldValue(18, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set PowerEnabled field</summary> /// <param name="powerEnabled_">Nullable field value to be set</param> public void SetPowerEnabled(Bool? powerEnabled_) { SetFieldValue(18, 0, powerEnabled_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CrankLength field /// Units: mm</summary> /// <returns>Returns nullable float representing the CrankLength field</returns> public float? GetCrankLength() { return (float?)GetFieldValue(19, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set CrankLength field /// Units: mm</summary> /// <param name="crankLength_">Nullable field value to be set</param> public void SetCrankLength(float? crankLength_) { SetFieldValue(19, 0, crankLength_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Enabled field</summary> /// <returns>Returns nullable Bool enum representing the Enabled field</returns> public Bool? GetEnabled() { object obj = GetFieldValue(20, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set Enabled field</summary> /// <param name="enabled_">Nullable field value to be set</param> public void SetEnabled(Bool? enabled_) { SetFieldValue(20, 0, enabled_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BikeSpdAntIdTransType field</summary> /// <returns>Returns nullable byte representing the BikeSpdAntIdTransType field</returns> public byte? GetBikeSpdAntIdTransType() { return (byte?)GetFieldValue(21, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BikeSpdAntIdTransType field</summary> /// <param name="bikeSpdAntIdTransType_">Nullable field value to be set</param> public void SetBikeSpdAntIdTransType(byte? bikeSpdAntIdTransType_) { SetFieldValue(21, 0, bikeSpdAntIdTransType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BikeCadAntIdTransType field</summary> /// <returns>Returns nullable byte representing the BikeCadAntIdTransType field</returns> public byte? GetBikeCadAntIdTransType() { return (byte?)GetFieldValue(22, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BikeCadAntIdTransType field</summary> /// <param name="bikeCadAntIdTransType_">Nullable field value to be set</param> public void SetBikeCadAntIdTransType(byte? bikeCadAntIdTransType_) { SetFieldValue(22, 0, bikeCadAntIdTransType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BikeSpdcadAntIdTransType field</summary> /// <returns>Returns nullable byte representing the BikeSpdcadAntIdTransType field</returns> public byte? GetBikeSpdcadAntIdTransType() { return (byte?)GetFieldValue(23, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BikeSpdcadAntIdTransType field</summary> /// <param name="bikeSpdcadAntIdTransType_">Nullable field value to be set</param> public void SetBikeSpdcadAntIdTransType(byte? bikeSpdcadAntIdTransType_) { SetFieldValue(23, 0, bikeSpdcadAntIdTransType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BikePowerAntIdTransType field</summary> /// <returns>Returns nullable byte representing the BikePowerAntIdTransType field</returns> public byte? GetBikePowerAntIdTransType() { return (byte?)GetFieldValue(24, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BikePowerAntIdTransType field</summary> /// <param name="bikePowerAntIdTransType_">Nullable field value to be set</param> public void SetBikePowerAntIdTransType(byte? bikePowerAntIdTransType_) { SetFieldValue(24, 0, bikePowerAntIdTransType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the OdometerRollover field /// Comment: Rollover counter that can be used to extend the odometer</summary> /// <returns>Returns nullable byte representing the OdometerRollover field</returns> public byte? GetOdometerRollover() { return (byte?)GetFieldValue(37, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set OdometerRollover field /// Comment: Rollover counter that can be used to extend the odometer</summary> /// <param name="odometerRollover_">Nullable field value to be set</param> public void SetOdometerRollover(byte? odometerRollover_) { SetFieldValue(37, 0, odometerRollover_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the FrontGearNum field /// Comment: Number of front gears</summary> /// <returns>Returns nullable byte representing the FrontGearNum field</returns> public byte? GetFrontGearNum() { return (byte?)GetFieldValue(38, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set FrontGearNum field /// Comment: Number of front gears</summary> /// <param name="frontGearNum_">Nullable field value to be set</param> public void SetFrontGearNum(byte? frontGearNum_) { SetFieldValue(38, 0, frontGearNum_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field FrontGear</returns> public int GetNumFrontGear() { return GetNumFieldValues(39, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the FrontGear field /// Comment: Number of teeth on each gear 0 is innermost</summary> /// <param name="index">0 based index of FrontGear element to retrieve</param> /// <returns>Returns nullable byte representing the FrontGear field</returns> public byte? GetFrontGear(int index) { return (byte?)GetFieldValue(39, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set FrontGear field /// Comment: Number of teeth on each gear 0 is innermost</summary> /// <param name="index">0 based index of front_gear</param> /// <param name="frontGear_">Nullable field value to be set</param> public void SetFrontGear(int index, byte? frontGear_) { SetFieldValue(39, index, frontGear_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the RearGearNum field /// Comment: Number of rear gears</summary> /// <returns>Returns nullable byte representing the RearGearNum field</returns> public byte? GetRearGearNum() { return (byte?)GetFieldValue(40, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set RearGearNum field /// Comment: Number of rear gears</summary> /// <param name="rearGearNum_">Nullable field value to be set</param> public void SetRearGearNum(byte? rearGearNum_) { SetFieldValue(40, 0, rearGearNum_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field RearGear</returns> public int GetNumRearGear() { return GetNumFieldValues(41, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the RearGear field /// Comment: Number of teeth on each gear 0 is innermost</summary> /// <param name="index">0 based index of RearGear element to retrieve</param> /// <returns>Returns nullable byte representing the RearGear field</returns> public byte? GetRearGear(int index) { return (byte?)GetFieldValue(41, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set RearGear field /// Comment: Number of teeth on each gear 0 is innermost</summary> /// <param name="index">0 based index of rear_gear</param> /// <param name="rearGear_">Nullable field value to be set</param> public void SetRearGear(int index, byte? rearGear_) { SetFieldValue(41, index, rearGear_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the ShimanoDi2Enabled field</summary> /// <returns>Returns nullable Bool enum representing the ShimanoDi2Enabled field</returns> public Bool? GetShimanoDi2Enabled() { object obj = GetFieldValue(44, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set ShimanoDi2Enabled field</summary> /// <param name="shimanoDi2Enabled_">Nullable field value to be set</param> public void SetShimanoDi2Enabled(Bool? shimanoDi2Enabled_) { SetFieldValue(44, 0, shimanoDi2Enabled_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
using System; using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; public class RelativisticParent : MonoBehaviour { //Keep track of our own Mesh Filter private MeshFilter meshFilter; //Store this object's velocity here. public Vector3 viw; private GameState state; //When was this object created? use for moving objects private float startTime = 0; //When should we die? again, for moving objects private float deathTime = 0; // Get the start time of our object, so that we know where not to draw it public void SetStartTime() { startTime = (float) GameObject.FindGameObjectWithTag("Player").GetComponent<GameState>().TotalTimeWorld; } //Set the death time, so that we know at what point to destroy the object in the player's view point. public void SetDeathTime() { deathTime = (float)state.TotalTimeWorld; } //This is a function that just ensures we're slower than our maximum speed. The VIW that Unity sets SHOULD (it's creator-chosen) be smaller than the maximum speed. private void checkSpeed() { if (viw.magnitude > state.MaxSpeed-.01) { viw = viw.normalized * (float)(state.MaxSpeed-.01f); } } // Use this for initialization void Start() { if (GetComponent<ObjectMeshDensity>()) { GetComponent<ObjectMeshDensity>().enabled = false; } int vertCount = 0, triangleCount = 0; checkSpeed (); Matrix4x4 worldLocalMatrix = transform.worldToLocalMatrix; //This code combines the meshes of children of parent objects //This increases our FPS by a ton //Get an array of the meshfilters MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>(); //Count submeshes int[] subMeshCount = new int[meshFilters.Length]; //Get all the meshrenderers MeshRenderer[] meshRenderers = GetComponentsInChildren<MeshRenderer>(); //Length of our original array int meshFilterLength = meshFilters.Length; //And a counter int subMeshCounts = 0; //For every meshfilter, for (int y = 0; y < meshFilterLength; y++) { //If it's null, ignore it. if (meshFilters[y] == null) continue; if (meshFilters[y].sharedMesh == null) continue; //else add its vertices to the vertcount vertCount += meshFilters[y].sharedMesh.vertices.Length; //Add its triangles to the count triangleCount += meshFilters[y].sharedMesh.triangles.Length; //Add the number of submeshes to its spot in the array subMeshCount[y] = meshFilters[y].mesh.subMeshCount; //And add up the total number of submeshes subMeshCounts += meshFilters[y].mesh.subMeshCount; } // Get a temporary array of EVERY vertex Vector3[] tempVerts = new Vector3[vertCount]; //And make a triangle array for every submesh int[][] tempTriangles = new int[subMeshCounts][]; for (int u = 0; u < subMeshCounts; u++) { //Make every array the correct length of triangles tempTriangles[u] = new int[triangleCount]; } //Also grab our UV texture coordinates Vector2[] tempUVs = new Vector2[vertCount]; //And store a number of materials equal to the number of submeshes. Material[] tempMaterials = new Material[subMeshCounts]; int vertIndex = 0; Mesh MFs; int subMeshIndex = 0; //For all meshfilters for (int i = 0; i < meshFilterLength; i++) { //just doublecheck that the mesh isn't null MFs = meshFilters[i].sharedMesh; if (MFs == null) continue; //Otherwise, for all submeshes in the current mesh for (int q = 0; q < subMeshCount[i]; q++) { //grab its material tempMaterials[subMeshIndex] = meshRenderers[i].materials[q]; //Grab its triangles int[] tempSubTriangles = MFs.GetTriangles(q); //And put them into the submesh's triangle array for (int k = 0; k < tempSubTriangles.Length; k++) { tempTriangles[subMeshIndex][k] = tempSubTriangles[k] + vertIndex; } //Increment the submesh index subMeshIndex++; } Matrix4x4 cTrans = worldLocalMatrix * meshFilters[i].transform.localToWorldMatrix; //For all the vertices in the mesh for (int v = 0; v < MFs.vertices.Length; v++) { //Get the vertex and the UV coordinate tempVerts[vertIndex] = cTrans.MultiplyPoint3x4(MFs.vertices[v]); tempUVs[vertIndex] = MFs.uv[v]; vertIndex++; } //And delete that gameobject. meshFilters[i].gameObject.SetActive(false); } //Put it all together now. Mesh myMesh = new Mesh(); //Make the mesh have as many submeshes as you need myMesh.subMeshCount = subMeshCounts; //Set its vertices to tempverts myMesh.vertices = tempVerts; //start at the first submesh subMeshIndex = 0; //For every submesh in each meshfilter for (int l = 0; l < meshFilterLength; l++) { for (int g = 0; g < subMeshCount[l]; g++) { //Set a new submesh, using the triangle array and its submesh index (built in unity function) myMesh.SetTriangles(tempTriangles[subMeshIndex], subMeshIndex); //increment the submesh index subMeshIndex++; } } //Just shunt in the UV coordinates, we don't need to change them myMesh.uv = tempUVs; //THEN totally replace our object's mesh with this new, combined mesh GetComponent<MeshFilter>().mesh = myMesh; GetComponent<MeshRenderer>().enabled = true; GetComponent<MeshFilter>().mesh.RecalculateNormals(); GetComponent<MeshFilter>().GetComponent<Renderer>().materials = tempMaterials; transform.gameObject.SetActive(true); //End section of combining meshes state = GameObject.FindGameObjectWithTag("Player").GetComponent<GameState>(); meshFilter = GetComponent<MeshFilter>(); MeshRenderer tempRenderer = GetComponent<MeshRenderer>(); //Then the standard RelativisticObject startup if (tempRenderer.materials[0].mainTexture != null) { //So that we can set unique values to every moving object, we have to instantiate a material //It's the same as our old one, but now it's not connected to every other object with the same material Material quickSwapMaterial = Instantiate((tempRenderer as Renderer).materials[0]) as Material; //Then, set the value that we want quickSwapMaterial.SetFloat("_viw", 0); //And stick it back into our renderer. We'll do the SetVector thing every frame. tempRenderer.materials[0] = quickSwapMaterial; //set our start time and start position in the shader. tempRenderer.materials[0].SetFloat("_strtTime", (float)startTime); tempRenderer.materials[0].SetVector("_strtPos", new Vector4(transform.position.x, transform.position.y, transform.position.z, 0)); } //This code is a hack to ensure that frustrum culling does not take place //It changes the render bounds so that everything is contained within them Transform camTransform = Camera.main.transform; float distToCenter = (Camera.main.farClipPlane - Camera.main.nearClipPlane) / 2.0f; Vector3 center = camTransform.position + camTransform.forward * distToCenter; float extremeBound = 500000.0f; meshFilter.sharedMesh.bounds = new Bounds(center, Vector3.one * extremeBound); if (GetComponent<ObjectMeshDensity>()) { GetComponent<ObjectMeshDensity>().enabled = true; } } // Update is called once per frame void Update() { //Grab our renderer. MeshRenderer tempRenderer = GetComponent<MeshRenderer>(); if (meshFilter != null && !state.MovementFrozen) { //Send our object's v/c (Velocity over the Speed of Light) to the shader if (tempRenderer != null) { Vector3 tempViw = viw / (float)state.SpeedOfLight; tempRenderer.materials[0].SetVector("_viw", new Vector4(tempViw.x, tempViw.y, tempViw.z, 0)); } //As long as our object is actually alive, perform these calculations if (transform!=null && deathTime != 0) { //Here I take the angle that the player's velocity vector makes with the z axis float rotationAroundZ = 57.2957795f * Mathf.Acos(Vector3.Dot(state.PlayerVelocityVector, Vector3.forward) / state.PlayerVelocityVector.magnitude); if (state.PlayerVelocityVector.sqrMagnitude == 0) { rotationAroundZ = 0; } //Now we turn that rotation into a quaternion Quaternion rotateZ = Quaternion.AngleAxis(-rotationAroundZ, Vector3.Cross(state.PlayerVelocityVector,Vector3.forward)); //****************************************************************** //Place the vertex to be changed in a new Vector3 Vector3 riw = new Vector3(transform.position.x, transform.position.y, transform.position.z); riw -= state.playerTransform.position; //And we rotate our point that much to make it as if our magnitude of velocity is in the Z direction riw = rotateZ * riw; //Here begins the original code, made by the guys behind the Relativity game /**************************** * Start Part 6 Bullet 1 */ //Rotate that velocity! Vector3 storedViw = rotateZ * viw; float c = -Vector3.Dot(riw, riw); //first get position squared (position doted with position) float b = -(2 * Vector3.Dot(riw, storedViw)); //next get position doted with velocity, should be only in the Z direction float a = (float)state.SpeedOfLightSqrd - Vector3.Dot(storedViw, storedViw); /**************************** * Start Part 6 Bullet 2 * **************************/ float tisw = (float)(((-b - (Math.Sqrt((b * b) - 4f * a * c))) / (2f * a))); //If we're past our death time (in the player's view, as seen by tisw) if (state.TotalTimeWorld + tisw > deathTime) { Destroy(this.gameObject); } } //make our rigidbody's velocity viw if (GetComponent<Rigidbody>()!=null) { if (!double.IsNaN((double)state.SqrtOneMinusVSquaredCWDividedByCSquared) && (float)state.SqrtOneMinusVSquaredCWDividedByCSquared != 0) { Vector3 tempViw = viw; //ASK RYAN WHY THESE WERE DIVIDED BY THIS tempViw.x /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared; tempViw.y /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared; tempViw.z /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared; GetComponent<Rigidbody>().velocity = tempViw; } } } } }
// 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 BuildIt.CognitiveServices { /// <summary> /// The Search API provides a similar (but not exact) experience to /// Bing.com/Search by returning search results that Bing determines are /// relevant to the specified query. The results also identify the order /// that you must display the content in (see Using Ranking to Display /// Results). The response may also include related search links and /// suggest a query string that may more accurately represent the user's /// intent. Typically, you will call this API instead of calling the /// other APIs in the Bing API family, such as the Image API or News API. /// </summary> public partial class WebSearchAPIV5 : Microsoft.Rest.ServiceClient<WebSearchAPIV5>, IWebSearchAPIV5 { /// <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> /// Initializes a new instance of the WebSearchAPIV5 class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public WebSearchAPIV5(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the WebSearchAPIV5 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> public WebSearchAPIV5(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the WebSearchAPIV5 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> public WebSearchAPIV5(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 WebSearchAPIV5 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> public WebSearchAPIV5(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> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new System.Uri("https://api.cognitive.microsoft.com/bing/v5.0"); 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() } }; 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(); } /// <summary> /// Get web, image, news, &amp; videos results for a given query. /// </summary> /// <param name='count'> /// The number of search results to return in the response. The actual number /// delivered may be less than requested. /// </param> /// <param name='offset'> /// The zero-based offset that indicates the number of search results to skip /// before returning results. /// </param> /// <param name='mkt'> /// The market where the results come from. Typically, this is the country /// where the user is making the request from; however, it could be a /// different country if the user is not located in a country where Bing /// delivers results. The market must be in the form {language code}-{country /// code}. For example, en-US. /// /// &lt;br&gt; /// &lt;br&gt; /// Full list of supported markets: /// &lt;br&gt; /// es-AR,en-AU,de-AT,nl-BE,fr-BE,pt-BR,en-CA,fr-CA,es-CL,da-DK,fi-FI,fr-FR,de-DE,zh-HK,en-IN,en-ID,en-IE,it-IT,ja-JP,ko-KR,en-MY,es-MX,nl-NL,en-NZ,no-NO,zh-CN,pl-PL,pt-PT,en-PH,ru-RU,ar-SA,en-ZA,es-ES,sv-SE,fr-CH,de-CH,zh-TW,tr-TR,en-GB,en-US,es-US. /// Possible values include: 'en-us' /// </param> /// <param name='safesearch'> /// A filter used to filter results for adult content. Possible values /// include: 'Off', 'Moderate', 'Strict' /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> SearchWithHttpMessagesAsync(string query, double? count = 10, double? offset = 0, string mkt = "en-us", string safesearch = "Moderate", string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { string q = query; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("q", q); tracingParameters.Add("count", count); tracingParameters.Add("offset", offset); tracingParameters.Add("mkt", mkt); tracingParameters.Add("safesearch", safesearch); tracingParameters.Add("subscriptionKey", subscriptionKey); tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Search", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "search").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (q != null) { _queryParameters.Add(string.Format("q={0}", System.Uri.EscapeDataString(q))); } if (count != null) { _queryParameters.Add(string.Format("count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, this.SerializationSettings).Trim('"')))); } if (offset != null) { _queryParameters.Add(string.Format("offset={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(offset, this.SerializationSettings).Trim('"')))); } if (mkt != null) { _queryParameters.Add(string.Format("mkt={0}", System.Uri.EscapeDataString(mkt))); } if (safesearch != null) { _queryParameters.Add(string.Format("safesearch={0}", System.Uri.EscapeDataString(safesearch))); } if (subscriptionKey != null) { _queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (ocpApimSubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 429) { var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System.Collections.Generic; using System.Threading.Tasks; using DigitalOcean.API.Extensions; using DigitalOcean.API.Http; using DigitalOcean.API.Models.Responses; using RestSharp; namespace DigitalOcean.API.Clients { public class DropletActionsClient : IDropletActionsClient { private readonly IConnection _connection; public DropletActionsClient(IConnection connection) { _connection = connection; } #region IDropletActions Members /// <summary> /// Reboot a droplet /// </summary> public Task<Action> Reboot(long dropletId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "reboot" }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Power cycle a droplet /// </summary> public Task<Action> PowerCycle(long dropletId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "power_cycle" }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Shutdown a droplet /// </summary> public Task<Action> Shutdown(long dropletId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "shutdown" }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Turn off a droplet /// </summary> public Task<Action> PowerOff(long dropletId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "power_off" }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Turn on a droplet /// </summary> public Task<Action> PowerOn(long dropletId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "power_on" }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Reset the root password of the droplet /// </summary> public Task<Action> ResetPassword(long dropletId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "password_reset" }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Resize a droplet /// </summary> public Task<Action> Resize(long dropletId, string sizeSlug, bool resizeDisk) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "resize", Size = sizeSlug, Disk = resizeDisk }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Restore a droplet using an image /// A Droplet restoration will rebuild an image using a backup image. The image ID that is passed in must be a backup of /// the current Droplet instance. The operation will leave any embedded SSH keys intact. /// </summary> public Task<Action> Restore(long dropletId, object imageIdOrSlug) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "restore", Image = imageIdOrSlug }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Rebuild a droplet /// </summary> public Task<Action> Rebuild(long dropletId, object imageIdOrSlug) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "rebuild", Image = imageIdOrSlug }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Rename a droplets hostname /// </summary> public Task<Action> Rename(long dropletId, string name) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "rename", Name = name }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Chane the kernel of a droplet /// </summary> public Task<Action> ChangeKernel(long dropletId, long kernelId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "change_kernel", KernelId = kernelId }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Enable IPv6 networking on a droplet /// </summary> public Task<Action> EnableIpv6(long dropletId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "enable_ipv6" }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Enable backups on a droplet /// </summary> public Task<Action> EnableBackups(long dropletId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "enable_backups" }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Disable backups on a droplet /// </summary> public Task<Action> DisableBackups(long dropletId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "disable_backups" }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Enable private networking on a droplet /// </summary> public Task<Action> EnablePrivateNetworking(long dropletId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "enable_private_networking" }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Create a snapshot of a droplet /// </summary> public Task<Action> Snapshot(long dropletId, string name) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment) }; var body = new Models.Requests.DropletAction { Type = "snapshot", Name = name }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions", parameters, body, "action", Method.POST); } /// <summary> /// Retrieve an action for a droplet /// </summary> public Task<Action> GetDropletAction(long dropletId, long actionId) { var parameters = new List<Parameter> { new Parameter("dropletId", dropletId, ParameterType.UrlSegment), new Parameter("actionId", actionId, ParameterType.UrlSegment) }; return _connection.ExecuteRequest<Action>("droplets/{dropletId}/actions/{actionId}", parameters, null, "action"); } /// <summary> /// Some actions can be performed in bulk on tagged Droplets. /// The list of supported action types are: /// * power_cycle /// * power_on /// * power_off /// * shutdown /// * enable_private_networking /// * enable_ipv6 /// * enable_backups /// * disable_backups /// * snapshot /// </summary> public Task<IReadOnlyList<Action>> ActionOnTag(string tag, string actionType) { var parameters = new List<Parameter> { new Parameter("tag_name", tag, ParameterType.QueryString) }; var body = new Models.Requests.DropletAction { Type = actionType }; return _connection.ExecuteRequest<List<Action>>("droplets/actions", parameters, body, "actions", Method.POST) .ToReadOnlyListAsync(); } #endregion } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Cms.Core.Media; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Infrastructure.Serialization; using Umbraco.Extensions; namespace Umbraco.Cms.Core.PropertyEditors.ValueConverters { /// <summary> /// Represents a value of the image cropper value editor. /// </summary> [JsonConverter(typeof(NoTypeConverterJsonConverter<ImageCropperValue>))] [TypeConverter(typeof(ImageCropperValueTypeConverter))] [DataContract(Name = "imageCropDataSet")] public class ImageCropperValue : IHtmlEncodedString, IEquatable<ImageCropperValue> { /// <summary> /// Gets or sets the value source image. /// </summary> [DataMember(Name = "src")] public string Src { get; set; } /// <summary> /// Gets or sets the value focal point. /// </summary> [DataMember(Name = "focalPoint")] public ImageCropperFocalPoint FocalPoint { get; set; } /// <summary> /// Gets or sets the value crops. /// </summary> [DataMember(Name = "crops")] public IEnumerable<ImageCropperCrop> Crops { get; set; } /// <inheritdoc /> public override string ToString() => HasCrops() || HasFocalPoint() ? JsonConvert.SerializeObject(this, Formatting.None) : Src; /// <inheritdoc /> public string ToHtmlString() => Src; /// <summary> /// Gets a crop. /// </summary> public ImageCropperCrop GetCrop(string alias) { if (Crops == null) return null; return string.IsNullOrWhiteSpace(alias) ? Crops.FirstOrDefault() : Crops.FirstOrDefault(x => x.Alias.InvariantEquals(alias)); } public ImageUrlGenerationOptions GetCropBaseOptions(string url, ImageCropperCrop crop, bool preferFocalPoint) { if ((preferFocalPoint && HasFocalPoint()) || (crop != null && crop.Coordinates == null && HasFocalPoint())) { return new ImageUrlGenerationOptions(url) { FocalPoint = new ImageUrlGenerationOptions.FocalPointPosition(FocalPoint.Left, FocalPoint.Top) }; } else if (crop != null && crop.Coordinates != null && preferFocalPoint == false) { return new ImageUrlGenerationOptions(url) { Crop = new ImageUrlGenerationOptions.CropCoordinates(crop.Coordinates.X1, crop.Coordinates.Y1, crop.Coordinates.X2, crop.Coordinates.Y2) }; } else { return new ImageUrlGenerationOptions(url); } } /// <summary> /// Gets the value image URL for a specified crop. /// </summary> public string GetCropUrl(string alias, IImageUrlGenerator imageUrlGenerator, bool useCropDimensions = true, bool useFocalPoint = false, string cacheBusterValue = null) { var crop = GetCrop(alias); // could not find a crop with the specified, non-empty, alias if (crop == null && !string.IsNullOrWhiteSpace(alias)) return null; var options = GetCropBaseOptions(null, crop, useFocalPoint || string.IsNullOrWhiteSpace(alias)); if (crop != null && useCropDimensions) { options.Width = crop.Width; options.Height = crop.Height; } options.CacheBusterValue = cacheBusterValue; return imageUrlGenerator.GetImageUrl(options); } /// <summary> /// Gets the value image URL for a specific width and height. /// </summary> public string GetCropUrl(int width, int height, IImageUrlGenerator imageUrlGenerator, string cacheBusterValue = null) { var options = GetCropBaseOptions(null, null, false); options.Width = width; options.Height = height; options.CacheBusterValue = cacheBusterValue; return imageUrlGenerator.GetImageUrl(options); } /// <summary> /// Determines whether the value has a focal point. /// </summary> /// <returns></returns> public bool HasFocalPoint() => FocalPoint is ImageCropperFocalPoint focalPoint && (focalPoint.Left != 0.5m || focalPoint.Top != 0.5m); /// <summary> /// Determines whether the value has crops. /// </summary> public bool HasCrops() => Crops is IEnumerable<ImageCropperCrop> crops && crops.Any(); /// <summary> /// Determines whether the value has a specified crop. /// </summary> public bool HasCrop(string alias) => Crops is IEnumerable<ImageCropperCrop> crops && crops.Any(x => x.Alias == alias); /// <summary> /// Determines whether the value has a source image. /// </summary> public bool HasImage() => !string.IsNullOrWhiteSpace(Src); public ImageCropperValue Merge(ImageCropperValue imageCropperValue) { var crops = Crops?.ToList() ?? new List<ImageCropperCrop>(); var incomingCrops = imageCropperValue?.Crops; if (incomingCrops != null) { foreach (var incomingCrop in incomingCrops) { var crop = crops.FirstOrDefault(x => x.Alias == incomingCrop.Alias); if (crop == null) { // Add incoming crop crops.Add(incomingCrop); } else if (crop.Coordinates == null) { // Use incoming crop coordinates crop.Coordinates = incomingCrop.Coordinates; } } } return new ImageCropperValue() { Src = !string.IsNullOrWhiteSpace(Src) ? Src : imageCropperValue?.Src, Crops = crops, FocalPoint = FocalPoint ?? imageCropperValue?.FocalPoint }; } /// <summary> /// Removes redundant crop data/default focal point. /// </summary> /// <param name="value">The image cropper value.</param> public static void Prune(JObject value) { if (value is null) throw new ArgumentNullException(nameof(value)); if (value.TryGetValue("crops", out var crops)) { if (crops.HasValues) { foreach (var crop in crops.Values<JObject>().ToList()) { if (crop.TryGetValue("coordinates", out var coordinates) == false || coordinates.HasValues == false) { // Remove crop without coordinates crop.Remove(); continue; } // Width/height are already stored in the crop configuration crop.Remove("width"); crop.Remove("height"); } } if (crops.HasValues == false) { // Remove empty crops value.Remove("crops"); } } if (value.TryGetValue("focalPoint", out var focalPoint) && (focalPoint.HasValues == false || (focalPoint.Value<decimal>("top") == 0.5m && focalPoint.Value<decimal>("left") == 0.5m))) { // Remove empty/default focal point value.Remove("focalPoint"); } } #region IEquatable /// <inheritdoc /> public bool Equals(ImageCropperValue other) => ReferenceEquals(this, other) || Equals(this, other); /// <inheritdoc /> public override bool Equals(object obj) => ReferenceEquals(this, obj) || obj is ImageCropperValue other && Equals(this, other); private static bool Equals(ImageCropperValue left, ImageCropperValue right) => ReferenceEquals(left, right) // deals with both being null, too || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && string.Equals(left.Src, right.Src) && Equals(left.FocalPoint, right.FocalPoint) && left.ComparableCrops.SequenceEqual(right.ComparableCrops); private IEnumerable<ImageCropperCrop> ComparableCrops => Crops?.OrderBy(x => x.Alias) ?? Enumerable.Empty<ImageCropperCrop>(); public static bool operator ==(ImageCropperValue left, ImageCropperValue right) => Equals(left, right); public static bool operator !=(ImageCropperValue left, ImageCropperValue right) => !Equals(left, right); public override int GetHashCode() { unchecked { // properties are, practically, readonly // ReSharper disable NonReadonlyMemberInGetHashCode var hashCode = Src?.GetHashCode() ?? 0; hashCode = (hashCode * 397) ^ (FocalPoint?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Crops?.GetHashCode() ?? 0); return hashCode; // ReSharper restore NonReadonlyMemberInGetHashCode } } #endregion [DataContract(Name = "imageCropFocalPoint")] public class ImageCropperFocalPoint : IEquatable<ImageCropperFocalPoint> { [DataMember(Name = "left")] public decimal Left { get; set; } [DataMember(Name = "top")] public decimal Top { get; set; } #region IEquatable /// <inheritdoc /> public bool Equals(ImageCropperFocalPoint other) => ReferenceEquals(this, other) || Equals(this, other); /// <inheritdoc /> public override bool Equals(object obj) => ReferenceEquals(this, obj) || obj is ImageCropperFocalPoint other && Equals(this, other); private static bool Equals(ImageCropperFocalPoint left, ImageCropperFocalPoint right) => ReferenceEquals(left, right) // deals with both being null, too || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Left == right.Left && left.Top == right.Top; public static bool operator ==(ImageCropperFocalPoint left, ImageCropperFocalPoint right) => Equals(left, right); public static bool operator !=(ImageCropperFocalPoint left, ImageCropperFocalPoint right) => !Equals(left, right); public override int GetHashCode() { unchecked { // properties are, practically, readonly // ReSharper disable NonReadonlyMemberInGetHashCode return (Left.GetHashCode() * 397) ^ Top.GetHashCode(); // ReSharper restore NonReadonlyMemberInGetHashCode } } #endregion } [DataContract(Name = "imageCropData")] public class ImageCropperCrop : IEquatable<ImageCropperCrop> { [DataMember(Name = "alias")] public string Alias { get; set; } [DataMember(Name = "width")] public int Width { get; set; } [DataMember(Name = "height")] public int Height { get; set; } [DataMember(Name = "coordinates")] public ImageCropperCropCoordinates Coordinates { get; set; } #region IEquatable /// <inheritdoc /> public bool Equals(ImageCropperCrop other) => ReferenceEquals(this, other) || Equals(this, other); /// <inheritdoc /> public override bool Equals(object obj) => ReferenceEquals(this, obj) || obj is ImageCropperCrop other && Equals(this, other); private static bool Equals(ImageCropperCrop left, ImageCropperCrop right) => ReferenceEquals(left, right) // deals with both being null, too || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && string.Equals(left.Alias, right.Alias) && left.Width == right.Width && left.Height == right.Height && Equals(left.Coordinates, right.Coordinates); public static bool operator ==(ImageCropperCrop left, ImageCropperCrop right) => Equals(left, right); public static bool operator !=(ImageCropperCrop left, ImageCropperCrop right) => !Equals(left, right); public override int GetHashCode() { unchecked { // properties are, practically, readonly // ReSharper disable NonReadonlyMemberInGetHashCode var hashCode = Alias?.GetHashCode() ?? 0; hashCode = (hashCode * 397) ^ Width; hashCode = (hashCode * 397) ^ Height; hashCode = (hashCode * 397) ^ (Coordinates?.GetHashCode() ?? 0); return hashCode; // ReSharper restore NonReadonlyMemberInGetHashCode } } #endregion } [DataContract(Name = "imageCropCoordinates")] public class ImageCropperCropCoordinates : IEquatable<ImageCropperCropCoordinates> { [DataMember(Name = "x1")] public decimal X1 { get; set; } [DataMember(Name = "y1")] public decimal Y1 { get; set; } [DataMember(Name = "x2")] public decimal X2 { get; set; } [DataMember(Name = "y2")] public decimal Y2 { get; set; } #region IEquatable /// <inheritdoc /> public bool Equals(ImageCropperCropCoordinates other) => ReferenceEquals(this, other) || Equals(this, other); /// <inheritdoc /> public override bool Equals(object obj) => ReferenceEquals(this, obj) || obj is ImageCropperCropCoordinates other && Equals(this, other); private static bool Equals(ImageCropperCropCoordinates left, ImageCropperCropCoordinates right) => ReferenceEquals(left, right) // deals with both being null, too || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.X1 == right.X1 && left.X2 == right.X2 && left.Y1 == right.Y1 && left.Y2 == right.Y2; public static bool operator ==(ImageCropperCropCoordinates left, ImageCropperCropCoordinates right) => Equals(left, right); public static bool operator !=(ImageCropperCropCoordinates left, ImageCropperCropCoordinates right) => !Equals(left, right); public override int GetHashCode() { unchecked { // properties are, practically, readonly // ReSharper disable NonReadonlyMemberInGetHashCode var hashCode = X1.GetHashCode(); hashCode = (hashCode * 397) ^ Y1.GetHashCode(); hashCode = (hashCode * 397) ^ X2.GetHashCode(); hashCode = (hashCode * 397) ^ Y2.GetHashCode(); return hashCode; // ReSharper restore NonReadonlyMemberInGetHashCode } } #endregion } } }
using System.Collections.Generic; using BitbucketSharp.Models; using BitbucketSharp.MonoTouch.Controllers; namespace BitbucketSharp.Controllers { /// <summary> /// Provides access to repositories owned by a user /// </summary> public class UserRepositoriesController : Controller { /// <summary> /// Gets the owner of the repositories /// </summary> public UserController Owner { get; private set; } /// <summary> /// Constructor /// </summary> /// <param name="client">A handle to the client</param> /// <param name="owner">The owner of the repositories</param> public UserRepositoriesController(Client client, UserController owner) : base(client) { Owner = owner; } /// <summary> /// Access a specific repository via the slug /// </summary> /// <param name="slug">The repository slug</param> /// <returns></returns> public RepositoryController this[string slug] { get { return new RepositoryController(Client, Owner, slug); } } /// <summary> /// The URI of this controller /// </summary> public override string Uri { get { return "repositories"; } } } /// <summary> /// Provides access to 'global' repositories via a search method /// </summary> public class RepositoriesController : Controller { /// <summary> /// Constructor /// </summary> /// <param name="client">A handle to the client</param> public RepositoriesController(Client client) : base(client) { } /// <summary> /// Search for a specific repository via the name /// </summary> /// <param name="name">The partial or full name to search for</param> /// <returns>A list of RepositorySimpleModel</returns> public RepositorySearchModel Search(string name) { return Client.Request<RepositorySearchModel>(Uri + "/?name=" + name); } /// <summary> /// The URI of this controller /// </summary> public override string Uri { get { return "repositories"; } } } /// <summary> /// Provides access to a repository /// </summary> public class RepositoryController : Controller { /// <summary> /// Gets a handle to the issue controller /// </summary> public IssuesController Issues { get { return new IssuesController(Client, this); } } /// <summary> /// Gets the owner of the repository /// </summary> public UserController Owner { get; private set; } /// <summary> /// Gets the slug of the repository /// </summary> public string Slug { get; private set; } /// <summary> /// Gets the wikis of this repository /// </summary> public WikisController Wikis { get { return new WikisController(Client, this); } } /// <summary> /// Gets the invitations to this repository /// </summary> public InvitationController Invitations { get { return new InvitationController(Client, this); } } /// <summary> /// Gets the changesets. /// </summary> public ChangesetsController Changesets { get { return new ChangesetsController(Client, this); } } /// <summary> /// Gets the branches /// </summary> public BranchesController Branches { get { return new BranchesController(Client, this); } } /// <summary> /// Gets the privileges for this repository /// </summary> public RepositoryPrivilegeController Privileges { get { return new RepositoryPrivilegeController(Client, new UserPrivilegesController(Client, Owner), Slug); } } /// <summary> /// Gets the group privileges for this repository /// </summary> public RepositoryGroupPrivilegeController GroupPrivileges { get { return new RepositoryGroupPrivilegeController(Client, this); } } /// <summary> /// Gets the pull requests. /// </summary> public PullRequestsController PullRequests { get { return new PullRequestsController(Client, this); } } /// <summary> /// Constructor /// </summary> /// <param name="owner">The owner of this repository</param> /// <param name="slug">The slug of this repository</param> /// <param name="client">A handle to the client</param> public RepositoryController(Client client, UserController owner, string slug) : base(client) { Owner = owner; Slug = slug.Replace(' ', '-').ToLower(); } /// <summary> /// Requests the information on a specific repository /// </summary> /// <returns>A RepositoryDetailedModel</returns> public RepositoryDetailedModel GetInfo(bool forceCacheInvalidation = false) { return Client.Get<RepositoryDetailedModel>(Uri, forceCacheInvalidation); } /// <summary> /// Requests the followers of a specific repository /// </summary> /// <returns>A FollowersModel</returns> public FollowersModel GetFollowers(bool forceCacheInvalidation = false) { return Client.Get<FollowersModel>(Uri + "/followers", forceCacheInvalidation); } /// <summary> /// Gets the tags. /// </summary> public Dictionary<string, TagModel> GetTags(bool forceCacheInvalidation = false) { return Client.Get<Dictionary<string, TagModel>>(Uri + "/tags", forceCacheInvalidation); } /// <summary> /// Requests the events of a repository /// </summary> /// <param name="start">The start index of returned items (default: 0)</param> /// <param name="limit">The limit of returned items (default: 25)</param> /// <param name="type">The type of event to return. If null, all event types are returned</param> /// <returns>A EventsModel</returns> public EventsModel GetEvents(int start = 0, int limit = 25, string type = null) { return Client.Request<EventsModel>(Uri + "/events/?start=" + start + "&limit=" + limit + (type == null ? "" : "&type=" + type)); } /// <summary> /// Forks the repository. /// </summary> /// <returns>The repository model of the forked repository.</returns> /// <param name="name">The name of the new forked repository.</param> /// <param name="description">the description of the forked repository.</param> /// <param name="language">The language of the forked repository.</param> /// <param name="isPrivate">Whether or not the forked repository is private.</param> public RepositoryDetailedModel ForkRepository(string name, string description = null, string language = null, bool? isPrivate = null) { var data = new Dictionary<string, string>(); data.Add("name", name); if (description != null) data.Add("description", description); if (language != null) data.Add("language", language); if (isPrivate != null) data.Add("is_private", isPrivate.Value.ToString()); return Client.Post<RepositoryDetailedModel>(Uri + "/fork", data); } /// <summary> /// Toggle's the following for this repository. Don't use this... /// </summary> /// <returns><c>true</c>, if follow was toggled, <c>false</c> otherwise.</returns> public RepositoryFollowModel ToggleFollow() { return Client.Post<RepositoryFollowModel>(Owner + "/" + Slug + "/follow", null, "https://bitbucket.org/"); } /// <summary> /// Gets the primary branch /// </summary> /// <returns>The primary branch.</returns> /// <param name="forceCacheInvalidation">If set to <c>true</c> force cache invalidation.</param> public PrimaryBranchModel GetPrimaryBranch(bool forceCacheInvalidation = false) { return Client.Get<PrimaryBranchModel>(Uri + "/main-branch", forceCacheInvalidation); } /// <summary> /// The URI of this controller /// </summary> public override string Uri { get { return "repositories/" + Owner.Username + "/" + Slug; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace BullsAndCows.RestApi.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. // See the LICENSE file in the project root for more information. using System.Diagnostics.Tracing; using System.Globalization; namespace System.Net { // TODO: Issue #5144: This class should not change or it can introduce incompatibility issues. [EventSource(Name = "Microsoft-System-Net", Guid = "501a994a-eb63-5415-9af1-1b031260f16c")] internal sealed class NetEventSource : EventSource { private const int FunctionStartId = 1; private const int FunctionStopId = 2; private const int CriticalExceptionId = 3; private const int CriticalErrorId = 4; private readonly static NetEventSource s_log = new NetEventSource(); private NetEventSource() { } public static NetEventSource Log { get { return s_log; } } [NonEvent] internal static void Enter(ComponentType componentType, object obj, string method, object paramObject) { if (!s_log.IsEnabled()) { return; } string callerName; int callerHash; string parametersName = ""; int parametersHash = 0; if (obj is string) { callerName = obj as string; callerHash = 0; } else { callerName = LoggingHash.GetObjectName(obj); callerHash = LoggingHash.HashInt(obj); } if (paramObject is string) { parametersName = paramObject as string; parametersHash = 0; } else if (paramObject != null) { parametersName = LoggingHash.GetObjectName(paramObject); parametersHash = LoggingHash.HashInt(paramObject); } s_log.FunctionStart( callerName, callerHash, LoggingHash.GetObjectName(method), parametersName, parametersHash, componentType); } [Event(FunctionStartId, Keywords = Keywords.FunctionEntryExit, Level = EventLevel.Verbose, Message = "[{5}] {0}#{1}::{2}({3}#{4})")] internal unsafe void FunctionStart( string callerName, int callerHash, string method, string parametersName, int parametersHash, ComponentType componentType) { const int SizeData = 6; fixed (char* arg1Ptr = callerName, arg2Ptr = method, arg3Ptr = parametersName) { EventData* dataDesc = stackalloc EventSource.EventData[SizeData]; dataDesc[0].DataPointer = (IntPtr)arg1Ptr; dataDesc[0].Size = (callerName.Length + 1) * sizeof(char); // Size in bytes, including a null terminator. dataDesc[1].DataPointer = (IntPtr)(&callerHash); dataDesc[1].Size = sizeof(int); dataDesc[2].DataPointer = (IntPtr)(arg2Ptr); dataDesc[2].Size = (method.Length + 1) * sizeof(char); dataDesc[3].DataPointer = (IntPtr)(arg3Ptr); dataDesc[3].Size = (parametersName.Length + 1) * sizeof(char); dataDesc[4].DataPointer = (IntPtr)(&parametersHash); dataDesc[4].Size = sizeof(int); dataDesc[5].DataPointer = (IntPtr)(&componentType); dataDesc[5].Size = sizeof(int); WriteEventCore(FunctionStartId, SizeData, dataDesc); } } [NonEvent] internal static void Exit(ComponentType componentType, object obj, string method, object retObject) { if (!s_log.IsEnabled()) { return; } string callerName; int callerHash; string parametersName = ""; int parametersHash = 0; if (obj is string) { callerName = obj as string; callerHash = 0; } else { callerName = LoggingHash.GetObjectName(obj); callerHash = LoggingHash.HashInt(obj); } if (retObject is string) { parametersName = retObject as string; parametersHash = 0; } else if (retObject != null) { parametersName = LoggingHash.GetObjectName(retObject); parametersHash = LoggingHash.HashInt(retObject); } s_log.FunctionStop(callerName, callerHash, LoggingHash.GetObjectName(method), parametersName, parametersHash, componentType); } [Event(FunctionStopId, Keywords = Keywords.FunctionEntryExit, Level = EventLevel.Verbose, Message = "[{5}] {0}#{1}::{2}({3}#{4})")] internal unsafe void FunctionStop( string callerName, int callerHash, string method, string parametersName, int parametersHash, ComponentType componentType) { const int SizeData = 6; fixed (char* arg1Ptr = callerName, arg2Ptr = method, arg3Ptr = parametersName) { EventData* dataDesc = stackalloc EventSource.EventData[SizeData]; dataDesc[0].DataPointer = (IntPtr)arg1Ptr; dataDesc[0].Size = (callerName.Length + 1) * sizeof(char); // Size in bytes, including a null terminator. dataDesc[1].DataPointer = (IntPtr)(&callerHash); dataDesc[1].Size = sizeof(int); dataDesc[2].DataPointer = (IntPtr)(arg2Ptr); dataDesc[2].Size = (method.Length + 1) * sizeof(char); dataDesc[3].DataPointer = (IntPtr)(arg3Ptr); dataDesc[3].Size = (parametersName.Length + 1) * sizeof(char); dataDesc[4].DataPointer = (IntPtr)(&parametersHash); dataDesc[4].Size = sizeof(int); dataDesc[5].DataPointer = (IntPtr)(&componentType); dataDesc[5].Size = sizeof(int); WriteEventCore(FunctionStopId, SizeData, dataDesc); } } [NonEvent] internal static void Exception(ComponentType componentType, object obj, string method, Exception e) { s_log.CriticalException( LoggingHash.GetObjectName(obj), LoggingHash.GetObjectName(method), LoggingHash.GetObjectName(e.Message), LoggingHash.HashInt(obj), LoggingHash.GetObjectName(e.StackTrace), componentType); } [Event(CriticalExceptionId, Keywords = Keywords.Default, Level = EventLevel.Critical)] internal unsafe void CriticalException(string objName, string method, string message, int objHash, string stackTrace, ComponentType componentType) { const int SizeData = 6; fixed (char* arg1Ptr = objName, arg2Ptr = method, arg3Ptr = message, arg4Ptr = stackTrace) { EventData* dataDesc = stackalloc EventSource.EventData[SizeData]; dataDesc[0].DataPointer = (IntPtr)arg1Ptr; dataDesc[0].Size = (objName.Length + 1) * sizeof(char); // Size in bytes, including a null terminator. dataDesc[1].DataPointer = (IntPtr)(arg2Ptr); dataDesc[1].Size = (method.Length + 1) * sizeof(char); dataDesc[2].DataPointer = (IntPtr)(arg3Ptr); dataDesc[2].Size = (message.Length + 1) * sizeof(char); dataDesc[3].DataPointer = (IntPtr)(&objHash); dataDesc[3].Size = sizeof(int); dataDesc[4].DataPointer = (IntPtr)(arg4Ptr); dataDesc[4].Size = (stackTrace.Length + 1) * sizeof(char); dataDesc[5].DataPointer = (IntPtr)(&componentType); dataDesc[5].Size = sizeof(int); WriteEventCore(CriticalExceptionId, SizeData, dataDesc); } } [NonEvent] internal static void PrintError(ComponentType componentType, string msg) { if (msg == null) { return; } s_log.CriticalError(LoggingHash.GetObjectName(msg), "", "", 0, componentType); } [NonEvent] internal static void PrintError(ComponentType componentType, object obj, string method, string msg) { s_log.CriticalError( LoggingHash.GetObjectName(msg), LoggingHash.GetObjectName(method), LoggingHash.GetObjectName(obj), LoggingHash.HashInt(obj), componentType); } [Event(CriticalErrorId, Keywords = Keywords.Default, Level = EventLevel.Critical)] internal unsafe void CriticalError(string message, string method, string objName, int objHash, ComponentType componentType) { const int SizeData = 5; fixed (char* arg1Ptr = message, arg2Ptr = method, arg3Ptr = objName) { EventData* dataDesc = stackalloc EventSource.EventData[SizeData]; dataDesc[0].DataPointer = (IntPtr)arg1Ptr; dataDesc[0].Size = (message.Length + 1) * sizeof(char); // Size in bytes, including a null terminator. dataDesc[1].DataPointer = (IntPtr)(arg2Ptr); dataDesc[1].Size = (method.Length + 1) * sizeof(char); dataDesc[2].DataPointer = (IntPtr)(arg3Ptr); dataDesc[2].Size = (objName.Length + 1) * sizeof(char); dataDesc[3].DataPointer = (IntPtr)(&objHash); dataDesc[3].Size = sizeof(int); dataDesc[4].DataPointer = (IntPtr)(&componentType); dataDesc[4].Size = sizeof(int); WriteEventCore(CriticalErrorId, SizeData, dataDesc); } } public class Keywords { public const EventKeywords Default = (EventKeywords)0x0001; public const EventKeywords Debug = (EventKeywords)0x0002; public const EventKeywords FunctionEntryExit = (EventKeywords)0x0004; } public enum ComponentType { Socket, Http, WebSocket, Security, NetworkInformation, Requests } } }
/* * 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 OpenMetaverse; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; namespace OpenSim.Framework.Serialization.External { /// <summary> /// Serialize and deserialize user inventory items as an external format. /// </summary> public class UserInventoryItemSerializer { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static Dictionary<string, Action<InventoryItemBase, XmlReader>> m_InventoryItemXmlProcessors = new Dictionary<string, Action<InventoryItemBase, XmlReader>>(); #region InventoryItemBase Processor initialization static UserInventoryItemSerializer() { m_InventoryItemXmlProcessors.Add("Name", ProcessName); m_InventoryItemXmlProcessors.Add("ID", ProcessID); m_InventoryItemXmlProcessors.Add("InvType", ProcessInvType); m_InventoryItemXmlProcessors.Add("CreatorUUID", ProcessCreatorUUID); m_InventoryItemXmlProcessors.Add("CreatorID", ProcessCreatorID); m_InventoryItemXmlProcessors.Add("CreatorData", ProcessCreatorData); m_InventoryItemXmlProcessors.Add("CreationDate", ProcessCreationDate); m_InventoryItemXmlProcessors.Add("Owner", ProcessOwner); m_InventoryItemXmlProcessors.Add("Description", ProcessDescription); m_InventoryItemXmlProcessors.Add("AssetType", ProcessAssetType); m_InventoryItemXmlProcessors.Add("AssetID", ProcessAssetID); m_InventoryItemXmlProcessors.Add("SaleType", ProcessSaleType); m_InventoryItemXmlProcessors.Add("SalePrice", ProcessSalePrice); m_InventoryItemXmlProcessors.Add("BasePermissions", ProcessBasePermissions); m_InventoryItemXmlProcessors.Add("CurrentPermissions", ProcessCurrentPermissions); m_InventoryItemXmlProcessors.Add("EveryOnePermissions", ProcessEveryOnePermissions); m_InventoryItemXmlProcessors.Add("NextPermissions", ProcessNextPermissions); m_InventoryItemXmlProcessors.Add("Flags", ProcessFlags); m_InventoryItemXmlProcessors.Add("GroupID", ProcessGroupID); m_InventoryItemXmlProcessors.Add("GroupOwned", ProcessGroupOwned); } #endregion #region InventoryItemBase Processors private static void ProcessName(InventoryItemBase item, XmlReader reader) { item.Name = reader.ReadElementContentAsString("Name", String.Empty); } private static void ProcessID(InventoryItemBase item, XmlReader reader) { item.ID = Util.ReadUUID(reader, "ID"); } private static void ProcessInvType(InventoryItemBase item, XmlReader reader) { item.InvType = reader.ReadElementContentAsInt("InvType", String.Empty); } private static void ProcessCreatorUUID(InventoryItemBase item, XmlReader reader) { item.CreatorId = reader.ReadElementContentAsString("CreatorUUID", String.Empty); } private static void ProcessCreatorID(InventoryItemBase item, XmlReader reader) { // when it exists, this overrides the previous item.CreatorId = reader.ReadElementContentAsString("CreatorID", String.Empty); } private static void ProcessCreationDate(InventoryItemBase item, XmlReader reader) { item.CreationDate = reader.ReadElementContentAsInt("CreationDate", String.Empty); } private static void ProcessOwner(InventoryItemBase item, XmlReader reader) { item.Owner = Util.ReadUUID(reader, "Owner"); } private static void ProcessDescription(InventoryItemBase item, XmlReader reader) { item.Description = reader.ReadElementContentAsString("Description", String.Empty); } private static void ProcessAssetType(InventoryItemBase item, XmlReader reader) { item.AssetType = reader.ReadElementContentAsInt("AssetType", String.Empty); } private static void ProcessAssetID(InventoryItemBase item, XmlReader reader) { item.AssetID = Util.ReadUUID(reader, "AssetID"); } private static void ProcessSaleType(InventoryItemBase item, XmlReader reader) { item.SaleType = (byte)reader.ReadElementContentAsInt("SaleType", String.Empty); } private static void ProcessSalePrice(InventoryItemBase item, XmlReader reader) { item.SalePrice = reader.ReadElementContentAsInt("SalePrice", String.Empty); } private static void ProcessBasePermissions(InventoryItemBase item, XmlReader reader) { item.BasePermissions = (uint)reader.ReadElementContentAsInt("BasePermissions", String.Empty); } private static void ProcessCurrentPermissions(InventoryItemBase item, XmlReader reader) { item.CurrentPermissions = (uint)reader.ReadElementContentAsInt("CurrentPermissions", String.Empty); } private static void ProcessEveryOnePermissions(InventoryItemBase item, XmlReader reader) { item.EveryOnePermissions = (uint)reader.ReadElementContentAsInt("EveryOnePermissions", String.Empty); } private static void ProcessNextPermissions(InventoryItemBase item, XmlReader reader) { item.NextPermissions = (uint)reader.ReadElementContentAsInt("NextPermissions", String.Empty); } private static void ProcessFlags(InventoryItemBase item, XmlReader reader) { item.Flags = (uint)reader.ReadElementContentAsInt("Flags", String.Empty); } private static void ProcessGroupID(InventoryItemBase item, XmlReader reader) { item.GroupID = Util.ReadUUID(reader, "GroupID"); } private static void ProcessGroupOwned(InventoryItemBase item, XmlReader reader) { item.GroupOwned = Util.ReadBoolean(reader); } private static void ProcessCreatorData(InventoryItemBase item, XmlReader reader) { item.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty); } #endregion /// <summary> /// Deserialize item /// </summary> /// <param name="serializedSettings"></param> /// <returns></returns> /// <exception cref="System.Xml.XmlException"></exception> public static InventoryItemBase Deserialize(byte[] serialization) { return Deserialize(Encoding.ASCII.GetString(serialization, 0, serialization.Length)); } /// <summary> /// Deserialize settings /// </summary> /// <param name="serializedSettings"></param> /// <returns></returns> /// <exception cref="System.Xml.XmlException"></exception> public static InventoryItemBase Deserialize(string serialization) { InventoryItemBase item = new InventoryItemBase(); using (XmlTextReader reader = new XmlTextReader(new StringReader(serialization))) { reader.ReadStartElement("InventoryItem"); ExternalRepresentationUtils.ExecuteReadProcessors<InventoryItemBase>( item, m_InventoryItemXmlProcessors, reader); reader.ReadEndElement(); // InventoryItem } //m_log.DebugFormat("[XXX]: parsed InventoryItemBase {0} - {1}", obj.Name, obj.UUID); return item; } public static string Serialize(InventoryItemBase inventoryItem, Dictionary<string, object> options, IUserAccountService userAccountService) { StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("InventoryItem"); writer.WriteStartElement("Name"); writer.WriteString(inventoryItem.Name); writer.WriteEndElement(); writer.WriteStartElement("ID"); writer.WriteString(inventoryItem.ID.ToString()); writer.WriteEndElement(); writer.WriteStartElement("InvType"); writer.WriteString(inventoryItem.InvType.ToString()); writer.WriteEndElement(); writer.WriteStartElement("CreatorUUID"); if (options.ContainsKey("creators")) { writer.WriteString(inventoryItem.CreatorIdAsUuid.ToString()); } else { writer.WriteString(OspResolver.MakeOspa(inventoryItem.CreatorIdAsUuid, userAccountService)); } writer.WriteEndElement(); writer.WriteStartElement("CreationDate"); writer.WriteString(inventoryItem.CreationDate.ToString()); writer.WriteEndElement(); writer.WriteStartElement("Owner"); writer.WriteString(inventoryItem.Owner.ToString()); writer.WriteEndElement(); writer.WriteStartElement("Description"); writer.WriteString(inventoryItem.Description); writer.WriteEndElement(); writer.WriteStartElement("AssetType"); writer.WriteString(inventoryItem.AssetType.ToString()); writer.WriteEndElement(); writer.WriteStartElement("AssetID"); writer.WriteString(inventoryItem.AssetID.ToString()); writer.WriteEndElement(); writer.WriteStartElement("SaleType"); writer.WriteString(inventoryItem.SaleType.ToString()); writer.WriteEndElement(); writer.WriteStartElement("SalePrice"); writer.WriteString(inventoryItem.SalePrice.ToString()); writer.WriteEndElement(); writer.WriteStartElement("BasePermissions"); writer.WriteString(inventoryItem.BasePermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("CurrentPermissions"); writer.WriteString(inventoryItem.CurrentPermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("EveryOnePermissions"); writer.WriteString(inventoryItem.EveryOnePermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("NextPermissions"); writer.WriteString(inventoryItem.NextPermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("Flags"); writer.WriteString(inventoryItem.Flags.ToString()); writer.WriteEndElement(); writer.WriteStartElement("GroupID"); writer.WriteString(inventoryItem.GroupID.ToString()); writer.WriteEndElement(); writer.WriteStartElement("GroupOwned"); writer.WriteString(inventoryItem.GroupOwned.ToString()); writer.WriteEndElement(); if (options.ContainsKey("creators") && !string.IsNullOrEmpty(inventoryItem.CreatorData)) writer.WriteElementString("CreatorData", inventoryItem.CreatorData); else if (options.ContainsKey("home")) { if (userAccountService != null) { UserAccount account = userAccountService.GetUserAccount(UUID.Zero, inventoryItem.CreatorIdAsUuid); if (account != null) { string creatorData = ExternalRepresentationUtils.CalcCreatorData((string)options["home"], inventoryItem.CreatorIdAsUuid, account.FirstName + " " + account.LastName); writer.WriteElementString("CreatorData", creatorData); } writer.WriteElementString("CreatorID", inventoryItem.CreatorId); } } writer.WriteEndElement(); writer.Close(); sw.Close(); return sw.ToString(); } } }
using System; using System.Collections.Generic; using QuickGraph.Collections; using QuickGraph.Algorithms.Observers; using QuickGraph.Algorithms.Services; using System.Diagnostics.Contracts; namespace QuickGraph.Algorithms.Search { /// <summary> /// A breath first search algorithm for undirected graphs /// </summary> /// <reference-ref /// idref="gross98graphtheory" /// chapter="4.2" /// /> #if !SILVERLIGHT [Serializable] #endif public sealed class UndirectedBreadthFirstSearchAlgorithm<TVertex, TEdge> : RootedAlgorithmBase<TVertex, IUndirectedGraph<TVertex, TEdge>> , IUndirectedVertexPredecessorRecorderAlgorithm<TVertex, TEdge> , IDistanceRecorderAlgorithm<TVertex, TEdge> , IVertexColorizerAlgorithm<TVertex, TEdge> , IUndirectedTreeBuilderAlgorithm<TVertex, TEdge> where TEdge : IEdge<TVertex> { private IDictionary<TVertex, GraphColor> vertexColors; private IQueue<TVertex> vertexQueue; public UndirectedBreadthFirstSearchAlgorithm(IUndirectedGraph<TVertex, TEdge> g) : this(g, new QuickGraph.Collections.Queue<TVertex>(), new Dictionary<TVertex, GraphColor>()) { } public UndirectedBreadthFirstSearchAlgorithm( IUndirectedGraph<TVertex, TEdge> visitedGraph, IQueue<TVertex> vertexQueue, IDictionary<TVertex, GraphColor> vertexColors ) : this(null, visitedGraph, vertexQueue, vertexColors) { } public UndirectedBreadthFirstSearchAlgorithm( IAlgorithmComponent host, IUndirectedGraph<TVertex, TEdge> visitedGraph, IQueue<TVertex> vertexQueue, IDictionary<TVertex, GraphColor> vertexColors ) : base(host, visitedGraph) { Contract.Requires(vertexQueue != null); Contract.Requires(vertexColors != null); this.vertexColors = vertexColors; this.vertexQueue = vertexQueue; } public IDictionary<TVertex, GraphColor> VertexColors { get { return vertexColors; } } public GraphColor GetVertexColor(TVertex vertex) { return this.vertexColors[vertex]; } public event VertexAction<TVertex> InitializeVertex; private void OnInitializeVertex(TVertex v) { var eh = this.InitializeVertex; if (eh != null) eh(v); } public event VertexAction<TVertex> StartVertex; private void OnStartVertex(TVertex v) { var eh = this.StartVertex; if (eh != null) eh(v); } public event VertexAction<TVertex> ExamineVertex; private void OnExamineVertex(TVertex v) { var eh = this.ExamineVertex; if (eh != null) eh(v); } public event VertexAction<TVertex> DiscoverVertex; private void OnDiscoverVertex(TVertex v) { var eh = this.DiscoverVertex; if (eh != null) eh(v); } public event EdgeAction<TVertex, TEdge> ExamineEdge; private void OnExamineEdge(TEdge e) { var eh = this.ExamineEdge; if (eh != null) eh(e); } public event UndirectedEdgeAction<TVertex, TEdge> TreeEdge; private void OnTreeEdge(TEdge e, bool reversed) { var eh = this.TreeEdge; if (eh != null) eh(this, new UndirectedEdgeEventArgs<TVertex, TEdge>(e, reversed)); } public event UndirectedEdgeAction<TVertex, TEdge> NonTreeEdge; private void OnNonTreeEdge(TEdge e, bool reversed) { var eh = this.NonTreeEdge; if (eh != null) eh(this, new UndirectedEdgeEventArgs<TVertex, TEdge>(e, reversed)); } public event UndirectedEdgeAction<TVertex, TEdge> GrayTarget; private void OnGrayTarget(TEdge e, bool reversed) { var eh = this.GrayTarget; if (eh != null) eh(this, new UndirectedEdgeEventArgs<TVertex, TEdge>(e, reversed)); } public event UndirectedEdgeAction<TVertex, TEdge> BlackTarget; private void OnBlackTarget(TEdge e, bool reversed) { var eh = this.BlackTarget; if (eh != null) eh(this, new UndirectedEdgeEventArgs<TVertex, TEdge>(e, reversed)); } public event VertexAction<TVertex> FinishVertex; private void OnFinishVertex(TVertex v) { var eh = this.FinishVertex; if (eh != null) eh(v); } protected override void Initialize() { base.Initialize(); // initialize vertex u var cancelManager = this.Services.CancelManager; if (cancelManager.IsCancelling) return; foreach (var v in VisitedGraph.Vertices) { this.VertexColors[v] = GraphColor.White; this.OnInitializeVertex(v); } } protected override void InternalCompute() { TVertex rootVertex; if (!this.TryGetRootVertex(out rootVertex)) throw new InvalidOperationException("missing root vertex"); this.EnqueueRoot(rootVertex); this.FlushVisitQueue(); } public void Visit(TVertex s) { this.EnqueueRoot(s); this.FlushVisitQueue(); } private void EnqueueRoot(TVertex s) { this.OnStartVertex(s); this.VertexColors[s] = GraphColor.Gray; this.OnDiscoverVertex(s); this.vertexQueue.Enqueue(s); } private void FlushVisitQueue() { var cancelManager = this.Services.CancelManager; while (this.vertexQueue.Count > 0) { if (cancelManager.IsCancelling) return; var u = this.vertexQueue.Dequeue(); this.OnExamineVertex(u); foreach (var e in VisitedGraph.AdjacentEdges(u)) { var reversed = e.Target.Equals(u); TVertex v = reversed ? e.Source : e.Target; this.OnExamineEdge(e); var vColor = this.VertexColors[v]; if (vColor == GraphColor.White) { this.OnTreeEdge(e, reversed); this.VertexColors[v] = GraphColor.Gray; this.OnDiscoverVertex(v); this.vertexQueue.Enqueue(v); } else { this.OnNonTreeEdge(e, reversed); if (vColor == GraphColor.Gray) this.OnGrayTarget(e, reversed); else this.OnBlackTarget(e, reversed); } } this.VertexColors[u] = GraphColor.Black; this.OnFinishVertex(u); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Reflection; using ParquetSharp.Column; using ParquetSharp.External; using ParquetSharp.Format; using ParquetSharp.Hadoop.Api; using ParquetSharp.Hadoop.Codec; using ParquetSharp.Hadoop.Metadata; using ParquetSharp.Hadoop.Util; using static ParquetSharp.Log; using static ParquetSharp.Preconditions; namespace ParquetSharp.Hadoop { /** * OutputFormat to write to a Parquet file * * It requires a {@link WriteSupport} to convert the actual records to the underlying format. * It requires the schema of the incoming records. (provided by the write support) * It allows storing extra metadata in the footer (for example: for schema compatibility purpose when converting from a different schema language). * * The format configuration settings in the job configuration: * <pre> * # The block size is the size of a row group being buffered in memory * # this limits the memory usage when writing * # Larger values will improve the IO when reading but consume more memory when writing * parquet.block.size=134217728 # in bytes, default = 128 * 1024 * 1024 * * # The page size is for compression. When reading, each page can be decompressed independently. * # A block is composed of pages. The page is the smallest unit that must be read fully to access a single record. * # If this value is too small, the compression will deteriorate * parquet.page.size=1048576 # in bytes, default = 1 * 1024 * 1024 * * # There is one dictionary page per column per row group when dictionary encoding is used. * # The dictionary page size works like the page size but for dictionary * parquet.dictionary.page.size=1048576 # in bytes, default = 1 * 1024 * 1024 * * # The compression algorithm used to compress pages * parquet.compression=UNCOMPRESSED # one of: UNCOMPRESSED, SNAPPY, GZIP, LZO. Default: UNCOMPRESSED. Supersedes mapred.output.compress* * * # The write support class to convert the records written to the OutputFormat into the events accepted by the record consumer * # Usually provided by a specific ParquetOutputFormat subclass * parquet.write.typeof(support)= # fully qualified name * * # To enable/disable dictionary encoding * parquet.enable.dictionary=true # false to disable dictionary encoding * * # To enable/disable summary metadata aggregation at the end of a MR job * # The default is true (enabled) * parquet.enable.summary-metadata=true # false to disable summary aggregation * * # Maximum size (in bytes) allowed as padding to align row groups * # This is also the minimum size of a row group. Default: 0 * parquet.writer.max-padding=2097152 # 2 MB * </pre> * * If parquet.compression is not set, the following properties are checked (FileOutputFormat behavior). * Note that we explicitely disallow custom Codecs * <pre> * mapred.output.compress=true * mapred.output.compression.codec=org.apache.hadoop.io.compress.SomeCodec # the codec must be one of Snappy, GZip or LZO * </pre> * * if none of those is set the data is uncompressed. * * @author Julien Le Dem * * @param <T> the type of the materialized records */ public class ParquetOutputFormat<T> : FileOutputFormat<object, T> { private static readonly Log LOG = Log.getLog(typeof(ParquetOutputFormat<T>)); public enum JobSummaryLevel { /** * Write no summary files */ NONE, /** * Write both summary file with row group info and summary file without * (both _metadata and _common_metadata) */ ALL, /** * Write only the summary file without the row group info * (_common_metadata only) */ COMMON_ONLY } /** * An alias for JOB_SUMMARY_LEVEL, where true means ALL and false means NONE */ [Obsolete] public const string ENABLE_JOB_SUMMARY = "parquet.enable.summary-metadata"; /** * Must be one of the values in {@link JobSummaryLevel} (case insensitive) */ public const string JOB_SUMMARY_LEVEL = "parquet.summary.metadata.level"; public const string BLOCK_SIZE = "parquet.block.size"; public const string PAGE_SIZE = "parquet.page.size"; public const string COMPRESSION = "parquet.compression"; public const string WRITE_SUPPORT_CLASS = "parquet.write.typeof(support)"; public const string DICTIONARY_PAGE_SIZE = "parquet.dictionary.page.size"; public const string ENABLE_DICTIONARY = "parquet.enable.dictionary"; public const string VALIDATION = "parquet.validation"; public const string WRITER_VERSION = "parquet.writer.version"; public const string MEMORY_POOL_RATIO = "parquet.memory.pool.ratio"; public const string MIN_MEMORY_ALLOCATION = "parquet.memory.min.chunk.size"; public const string MAX_PADDING_BYTES = "parquet.writer.max-padding"; public const string MIN_ROW_COUNT_FOR_PAGE_SIZE_CHECK = "parquet.page.size.row.check.min"; public const string MAX_ROW_COUNT_FOR_PAGE_SIZE_CHECK = "parquet.page.size.row.check.max"; public const string ESTIMATE_PAGE_SIZE_CHECK = "parquet.page.size.check.estimate"; // default to no padding for now private const int DEFAULT_MAX_PADDING_SIZE = 0; public static JobSummaryLevel getJobSummaryLevel(Configuration conf) { string level = conf.get(JOB_SUMMARY_LEVEL); string deprecatedFlag = conf.get(ENABLE_JOB_SUMMARY); if (deprecatedFlag != null) { LOG.warn("Setting " + ENABLE_JOB_SUMMARY + " is deprecated, please use " + JOB_SUMMARY_LEVEL); } if (level != null && deprecatedFlag != null) { LOG.warn("Both " + JOB_SUMMARY_LEVEL + " and " + ENABLE_JOB_SUMMARY + " are set! " + ENABLE_JOB_SUMMARY + " will be ignored."); } if (level != null) { return JobSummaryLevel.valueOf(level.toUpperCase()); } if (deprecatedFlag != null) { return Boolean.valueOf(deprecatedFlag) ? JobSummaryLevel.ALL : JobSummaryLevel.NONE; } return JobSummaryLevel.ALL; } public static void setWriteSupportClass(Job job, System.Type writeSupportClass) { getConfiguration(job).set(WRITE_SUPPORT_CLASS, writeSupportClass.FullName); } public static void setWriteSupportClass(JobConf job, System.Type writeSupportClass) { job.set(WRITE_SUPPORT_CLASS, writeSupportClass.FullName); } public static System.Type getWriteSupportClass(Configuration configuration) { string className = configuration.get(WRITE_SUPPORT_CLASS); if (className == null) { return null; } System.Type writeSupportClass = ConfigurationUtil.getClassFromConfig(configuration, WRITE_SUPPORT_CLASS, typeof(Api.WriteSupport)); return writeSupportClass; } public static void setBlockSize(Job job, int blockSize) { getConfiguration(job).setInt(BLOCK_SIZE, blockSize); } public static void setPageSize(Job job, int pageSize) { getConfiguration(job).setInt(PAGE_SIZE, pageSize); } public static void setDictionaryPageSize(Job job, int pageSize) { getConfiguration(job).setInt(DICTIONARY_PAGE_SIZE, pageSize); } public static void setCompression(Job job, CompressionCodec compression) { getConfiguration(job).set(COMPRESSION, compression.name()); } public static void setEnableDictionary(Job job, bool enableDictionary) { getConfiguration(job).setBoolean(ENABLE_DICTIONARY, enableDictionary); } public static bool getEnableDictionary(JobContext jobContext) { return getEnableDictionary(getConfiguration(jobContext)); } public static int getBlockSize(JobContext jobContext) { return getBlockSize(getConfiguration(jobContext)); } public static int getPageSize(JobContext jobContext) { return getPageSize(getConfiguration(jobContext)); } public static int getDictionaryPageSize(JobContext jobContext) { return getDictionaryPageSize(getConfiguration(jobContext)); } public static CompressionCodecName getCompression(JobContext jobContext) { return getCompression(getConfiguration(jobContext)); } public static bool isCompressionSet(JobContext jobContext) { return isCompressionSet(getConfiguration(jobContext)); } public static void setValidation(JobContext jobContext, bool validating) { setValidation(getConfiguration(jobContext), validating); } public static bool getValidation(JobContext jobContext) { return getValidation(getConfiguration(jobContext)); } public static bool getEnableDictionary(Configuration configuration) { return configuration.getBoolean( ENABLE_DICTIONARY, ParquetProperties.DEFAULT_IS_DICTIONARY_ENABLED); } public static int getMinRowCountForPageSizeCheck(Configuration configuration) { return configuration.getInt(MIN_ROW_COUNT_FOR_PAGE_SIZE_CHECK, ParquetProperties.DEFAULT_MINIMUM_RECORD_COUNT_FOR_CHECK); } public static int getMaxRowCountForPageSizeCheck(Configuration configuration) { return configuration.getInt(MAX_ROW_COUNT_FOR_PAGE_SIZE_CHECK, ParquetProperties.DEFAULT_MINIMUM_RECORD_COUNT_FOR_CHECK); } public static bool getEstimatePageSizeCheck(Configuration configuration) { return configuration.getBoolean(ESTIMATE_PAGE_SIZE_CHECK, ParquetProperties.DEFAULT_ESTIMATE_ROW_COUNT_FOR_PAGE_SIZE_CHECK); } [Obsolete] public static int getBlockSize(Configuration configuration) { return configuration.getInt(BLOCK_SIZE, DEFAULT_BLOCK_SIZE); } public static long getLongBlockSize(Configuration configuration) { return configuration.getLong(BLOCK_SIZE, DEFAULT_BLOCK_SIZE); } public static int getPageSize(Configuration configuration) { return configuration.getInt(PAGE_SIZE, ParquetProperties.DEFAULT_PAGE_SIZE); } public static int getDictionaryPageSize(Configuration configuration) { return configuration.getInt( DICTIONARY_PAGE_SIZE, ParquetProperties.DEFAULT_DICTIONARY_PAGE_SIZE); } public static ParquetProperties.WriterVersion getWriterVersion(Configuration configuration) { String writerVersion = configuration.get( WRITER_VERSION, ParquetProperties.DEFAULT_WRITER_VERSION.ToString()); return ParquetProperties.WriterVersion.fromString(writerVersion); } public static CompressionCodecName getCompression(Configuration configuration) { return CodecConfig.getParquetCompressionCodec(configuration); } public static bool isCompressionSet(Configuration configuration) { return CodecConfig.isParquetCompressionSet(configuration); } public static void setValidation(Configuration configuration, bool validating) { configuration.setBoolean(VALIDATION, validating); } public static bool getValidation(Configuration configuration) { return configuration.getBoolean(VALIDATION, false); } private CompressionCodecName getCodec(TaskAttemptContext taskAttemptContext) { return CodecConfig.from(taskAttemptContext).getCodec(); } public static void setMaxPaddingSize(JobContext jobContext, int maxPaddingSize) { setMaxPaddingSize(getConfiguration(jobContext), maxPaddingSize); } public static void setMaxPaddingSize(Configuration conf, int maxPaddingSize) { conf.setInt(MAX_PADDING_BYTES, maxPaddingSize); } private static int getMaxPaddingSize(Configuration conf) { // default to no padding, 0% of the row group size return conf.getInt(MAX_PADDING_BYTES, DEFAULT_MAX_PADDING_SIZE); } private WriteSupport<T> writeSupport; private ParquetOutputCommitter committer; /** * constructor used when this OutputFormat in wrapped in another one (In Pig for example) * @param writeSupportClass the class used to convert the incoming records * @param schema the schema of the records * @param extraMetaData extra meta data to be stored in the footer of the file */ public ParquetOutputFormat(WriteSupport<T> writeSupport) { this.writeSupport = writeSupport; } /** * used when directly using the output format and configuring the write support implementation * using parquet.write.typeof(support) */ public ParquetOutputFormat() { } /** * {@inheritDoc} */ public RecordWriter<object, T> getRecordWriter(TaskAttemptContext taskAttemptContext) { Configuration conf = getConfiguration(taskAttemptContext); CompressionCodecName codec = getCodec(taskAttemptContext); String extension = Codec.getExtension() + ".parquet"; Path file = getDefaultWorkFile(taskAttemptContext, extension); return getRecordWriter(conf, file, codec); } public RecordWriter<object, T> getRecordWriter(TaskAttemptContext taskAttemptContext, Path file) { return getRecordWriter(getConfiguration(taskAttemptContext), file, getCodec(taskAttemptContext)); } public RecordWriter<object, T> getRecordWriter(Configuration conf, Path file, CompressionCodecName codec) { WriteSupport<T> writeSupport = getWriteSupport(conf); ParquetProperties props = ParquetProperties.builder() .withPageSize(getPageSize(conf)) .withDictionaryPageSize(getDictionaryPageSize(conf)) .withDictionaryEncoding(getEnableDictionary(conf)) .withWriterVersion(getWriterVersion(conf)) .estimateRowCountForPageSizeCheck(getEstimatePageSizeCheck(conf)) .withMinRowCountForPageSizeCheck(getMinRowCountForPageSizeCheck(conf)) .withMaxRowCountForPageSizeCheck(getMaxRowCountForPageSizeCheck(conf)) .build(); long blockSize = getLongBlockSize(conf); int maxPaddingSize = getMaxPaddingSize(conf); bool validating = getValidation(conf); if (INFO) LOG.info("Parquet block size to " + blockSize); if (INFO) LOG.info("Parquet page size to " + props.getPageSizeThreshold()); if (INFO) LOG.info("Parquet dictionary page size to " + props.getDictionaryPageSizeThreshold()); if (INFO) LOG.info("Dictionary is " + (props.isEnableDictionary() ? "on" : "off")); if (INFO) LOG.info("Validation is " + (validating ? "on" : "off")); if (INFO) LOG.info("Writer version is: " + props.getWriterVersion()); if (INFO) LOG.info("Maximum row group padding size is " + maxPaddingSize + " bytes"); if (INFO) LOG.info("Page size checking is: " + (props.estimateNextSizeCheck() ? "estimated" : "constant")); if (INFO) LOG.info("Min row count for page size check is: " + props.getMinRowCountForPageSizeCheck()); if (INFO) LOG.info("Min row count for page size check is: " + props.getMaxRowCountForPageSizeCheck()); CodecFactory codecFactory = new CodecFactory(conf, props.getPageSizeThreshold()); WriteSupport<T>.WriteContext init = writeSupport.init(conf); ParquetFileWriter w = new ParquetFileWriter( conf, init.getSchema(), file, Mode.CREATE, blockSize, maxPaddingSize); w.start(); float maxLoad = conf.getFloat(MEMORY_POOL_RATIO, MemoryManager.DEFAULT_MEMORY_POOL_RATIO); long minAllocation = conf.getLong(MIN_MEMORY_ALLOCATION, MemoryManager.DEFAULT_MIN_MEMORY_ALLOCATION); if (memoryManager == null) { memoryManager = new MemoryManager(maxLoad, minAllocation); } else if (memoryManager.getMemoryPoolRatio() != maxLoad) { LOG.warn("The configuration " + MEMORY_POOL_RATIO + " has been set. It should not " + "be reset by the new value: " + maxLoad); } return new ParquetRecordWriter<T>( w, writeSupport, init.getSchema(), init.getExtraMetaData(), blockSize, codecFactory.getCompressor(codec), validating, props, memoryManager); } /** * @param configuration to find the configuration for the write support class * @return the configured write support */ public WriteSupport<T> getWriteSupport(Configuration configuration) { if (writeSupport != null) return writeSupport; System.Type writeSupportClass = getWriteSupportClass(configuration); try { return (WriteSupport<T>)Activator.CreateInstance(checkNotNull(writeSupportClass, "writeSupportClass")); } catch (TargetInvocationException e) { throw new BadConfigurationException("could not instantiate write support class: " + writeSupportClass, e); } catch (MemberAccessException e) { throw new BadConfigurationException("could not instantiate write support class: " + writeSupportClass, e); } } public OutputCommitter getOutputCommitter(TaskAttemptContext context) { if (committer == null) { Path output = getOutputPath(context); committer = new ParquetOutputCommitter(output, context); } return committer; } /** * This memory manager is for all the real writers (InternalParquetRecordWriter) in one task. */ private static MemoryManager memoryManager; public static MemoryManager getMemoryManager() { return memoryManager; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type GraphServiceInvitationsCollectionRequest. /// </summary> public partial class GraphServiceInvitationsCollectionRequest : BaseRequest, IGraphServiceInvitationsCollectionRequest { /// <summary> /// Constructs a new GraphServiceInvitationsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public GraphServiceInvitationsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Invitation to the collection via POST. /// </summary> /// <param name="invitation">The Invitation to add.</param> /// <returns>The created Invitation.</returns> public System.Threading.Tasks.Task<Invitation> AddAsync(Invitation invitation) { return this.AddAsync(invitation, CancellationToken.None); } /// <summary> /// Adds the specified Invitation to the collection via POST. /// </summary> /// <param name="invitation">The Invitation to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Invitation.</returns> public System.Threading.Tasks.Task<Invitation> AddAsync(Invitation invitation, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Invitation>(invitation, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IGraphServiceInvitationsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IGraphServiceInvitationsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<GraphServiceInvitationsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IGraphServiceInvitationsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IGraphServiceInvitationsCollectionRequest Expand(Expression<Func<Invitation, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IGraphServiceInvitationsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IGraphServiceInvitationsCollectionRequest Select(Expression<Func<Invitation, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IGraphServiceInvitationsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IGraphServiceInvitationsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IGraphServiceInvitationsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IGraphServiceInvitationsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// 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.DataLake.Analytics { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for AccountOperations. /// </summary> public static partial class AccountOperationsExtensions { /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within a /// specific resource group. This includes a link to the next page, if any. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just those /// requested, e.g. Categories?$select=CategoryName,Description. Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the matching /// resources included with the resources in the response, e.g. /// Categories?$count=true. Optional. /// </param> public static IPage<DataLakeAnalyticsAccount> ListByResourceGroup(this IAccountOperations operations, string resourceGroupName, ODataQuery<DataLakeAnalyticsAccount> odataQuery = default(ODataQuery<DataLakeAnalyticsAccount>), string select = default(string), bool? count = default(bool?)) { return Task.Factory.StartNew(s => ((IAccountOperations)s).ListByResourceGroupAsync(resourceGroupName, odataQuery, select, count), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within a /// specific resource group. This includes a link to the next page, if any. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just those /// requested, e.g. Categories?$select=CategoryName,Description. Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the matching /// resources included with the resources in the response, e.g. /// Categories?$count=true. Optional. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<DataLakeAnalyticsAccount>> ListByResourceGroupAsync(this IAccountOperations operations, string resourceGroupName, ODataQuery<DataLakeAnalyticsAccount> odataQuery = default(ODataQuery<DataLakeAnalyticsAccount>), string select = default(string), bool? count = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, odataQuery, select, count, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within the /// current subscription. This includes a link to the next page, if any. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just those /// requested, e.g. Categories?$select=CategoryName,Description. Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the matching /// resources included with the resources in the response, e.g. /// Categories?$count=true. Optional. /// </param> public static IPage<DataLakeAnalyticsAccount> List(this IAccountOperations operations, ODataQuery<DataLakeAnalyticsAccount> odataQuery = default(ODataQuery<DataLakeAnalyticsAccount>), string select = default(string), bool? count = default(bool?)) { return Task.Factory.StartNew(s => ((IAccountOperations)s).ListAsync(odataQuery, select, count), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within the /// current subscription. This includes a link to the next page, if any. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just those /// requested, e.g. Categories?$select=CategoryName,Description. Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the matching /// resources included with the resources in the response, e.g. /// Categories?$count=true. Optional. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<DataLakeAnalyticsAccount>> ListAsync(this IAccountOperations operations, ODataQuery<DataLakeAnalyticsAccount> odataQuery = default(ODataQuery<DataLakeAnalyticsAccount>), string select = default(string), bool? count = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, select, count, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets details of the specified Data Lake Analytics account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to retrieve. /// </param> public static DataLakeAnalyticsAccount Get(this IAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew(s => ((IAccountOperations)s).GetAsync(resourceGroupName, accountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets details of the specified Data Lake Analytics account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to retrieve. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DataLakeAnalyticsAccount> GetAsync(this IAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Begins the delete delete process for the Data Lake Analytics account /// object specified by the account name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to delete /// </param> public static void Delete(this IAccountOperations operations, string resourceGroupName, string accountName) { Task.Factory.StartNew(s => ((IAccountOperations)s).DeleteAsync(resourceGroupName, accountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins the delete delete process for the Data Lake Analytics account /// object specified by the account name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to delete /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Begins the delete delete process for the Data Lake Analytics account /// object specified by the account name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to delete /// </param> public static void BeginDelete(this IAccountOperations operations, string resourceGroupName, string accountName) { Task.Factory.StartNew(s => ((IAccountOperations)s).BeginDeleteAsync(resourceGroupName, accountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins the delete delete process for the Data Lake Analytics account /// object specified by the account name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to delete /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates the specified Data Lake Analytics account. This supplies the user /// with computation services for Data Lake Analytics workloads /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account.the account will be associated with. /// </param> /// <param name='name'> /// The name of the Data Lake Analytics account to create. /// </param> /// <param name='parameters'> /// Parameters supplied to the create Data Lake Analytics account operation. /// </param> public static DataLakeAnalyticsAccount Create(this IAccountOperations operations, string resourceGroupName, string name, DataLakeAnalyticsAccount parameters) { return Task.Factory.StartNew(s => ((IAccountOperations)s).CreateAsync(resourceGroupName, name, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates the specified Data Lake Analytics account. This supplies the user /// with computation services for Data Lake Analytics workloads /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account.the account will be associated with. /// </param> /// <param name='name'> /// The name of the Data Lake Analytics account to create. /// </param> /// <param name='parameters'> /// Parameters supplied to the create Data Lake Analytics account operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DataLakeAnalyticsAccount> CreateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeAnalyticsAccount parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates the specified Data Lake Analytics account. This supplies the user /// with computation services for Data Lake Analytics workloads /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account.the account will be associated with. /// </param> /// <param name='name'> /// The name of the Data Lake Analytics account to create. /// </param> /// <param name='parameters'> /// Parameters supplied to the create Data Lake Analytics account operation. /// </param> public static DataLakeAnalyticsAccount BeginCreate(this IAccountOperations operations, string resourceGroupName, string name, DataLakeAnalyticsAccount parameters) { return Task.Factory.StartNew(s => ((IAccountOperations)s).BeginCreateAsync(resourceGroupName, name, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates the specified Data Lake Analytics account. This supplies the user /// with computation services for Data Lake Analytics workloads /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account.the account will be associated with. /// </param> /// <param name='name'> /// The name of the Data Lake Analytics account to create. /// </param> /// <param name='parameters'> /// Parameters supplied to the create Data Lake Analytics account operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DataLakeAnalyticsAccount> BeginCreateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeAnalyticsAccount parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the Data Lake Analytics account object specified by the /// accountName with the contents of the account object. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='name'> /// The name of the Data Lake Analytics account to update. /// </param> /// <param name='parameters'> /// Parameters supplied to the update Data Lake Analytics account operation. /// </param> public static DataLakeAnalyticsAccount Update(this IAccountOperations operations, string resourceGroupName, string name, DataLakeAnalyticsAccountUpdateParameters parameters = default(DataLakeAnalyticsAccountUpdateParameters)) { return Task.Factory.StartNew(s => ((IAccountOperations)s).UpdateAsync(resourceGroupName, name, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the Data Lake Analytics account object specified by the /// accountName with the contents of the account object. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='name'> /// The name of the Data Lake Analytics account to update. /// </param> /// <param name='parameters'> /// Parameters supplied to the update Data Lake Analytics account operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DataLakeAnalyticsAccount> UpdateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeAnalyticsAccountUpdateParameters parameters = default(DataLakeAnalyticsAccountUpdateParameters), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the Data Lake Analytics account object specified by the /// accountName with the contents of the account object. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='name'> /// The name of the Data Lake Analytics account to update. /// </param> /// <param name='parameters'> /// Parameters supplied to the update Data Lake Analytics account operation. /// </param> public static DataLakeAnalyticsAccount BeginUpdate(this IAccountOperations operations, string resourceGroupName, string name, DataLakeAnalyticsAccountUpdateParameters parameters = default(DataLakeAnalyticsAccountUpdateParameters)) { return Task.Factory.StartNew(s => ((IAccountOperations)s).BeginUpdateAsync(resourceGroupName, name, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the Data Lake Analytics account object specified by the /// accountName with the contents of the account object. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='name'> /// The name of the Data Lake Analytics account to update. /// </param> /// <param name='parameters'> /// Parameters supplied to the update Data Lake Analytics account operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DataLakeAnalyticsAccount> BeginUpdateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeAnalyticsAccountUpdateParameters parameters = default(DataLakeAnalyticsAccountUpdateParameters), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within a /// specific resource group. This includes a link to the next page, if any. /// </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<DataLakeAnalyticsAccount> ListByResourceGroupNext(this IAccountOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IAccountOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within a /// specific resource group. This includes a link to the next page, if any. /// </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<DataLakeAnalyticsAccount>> ListByResourceGroupNextAsync(this IAccountOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within the /// current subscription. This includes a link to the next page, if any. /// </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<DataLakeAnalyticsAccount> ListNext(this IAccountOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IAccountOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the first page of Data Lake Analytics accounts, if any, within the /// current subscription. This includes a link to the next page, if any. /// </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<DataLakeAnalyticsAccount>> ListNextAsync(this IAccountOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using Android.OS; using Android.App; using Android.Views; using Android.Widget; using System.Net.Http; using System.Threading.Tasks; using Microsoft.WindowsAzure.MobileServices; namespace androidsample { [Activity (MainLauncher = true, Icon="@drawable/ic_launcher", Label="@string/app_name", Theme="@style/AppTheme")] public class ToDoActivity : Activity { //Mobile Service Client reference private MobileServiceClient client; //Mobile Service Table used to access data private IMobileServiceTable<ToDoItem> toDoTable; //Adapter to sync the items list with the view private ToDoItemAdapter adapter; //EditText containing the "New ToDo" text private EditText textNewToDo; //Progress spinner to use for table operations private ProgressBar progressBar; const string applicationURL = @"MOBILE SERVICE URL"; protected override async void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Activity_To_Do); progressBar = FindViewById<ProgressBar> (Resource.Id.loadingProgressBar); // Initialize the progress bar progressBar.Visibility = ViewStates.Gone; // Create ProgressFilter to handle busy state var progressHandler = new ProgressHandler (); progressHandler.BusyStateChange += (busy) => { if (progressBar != null) progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone; }; try { CurrentPlatform.Init (); // Create the Mobile Service Client instance, using the provided // Mobile Service URL client = new MobileServiceClient ( applicationURL, progressHandler); // Get the Mobile Service Table instance to use toDoTable = client.GetTable <ToDoItem> (); textNewToDo = FindViewById<EditText> (Resource.Id.textNewToDo); // Create an adapter to bind the items with the view adapter = new ToDoItemAdapter (this, Resource.Layout.Row_List_To_Do); var listViewToDo = FindViewById<ListView> (Resource.Id.listViewToDo); listViewToDo.Adapter = adapter; // Load the items from the Mobile Service await RefreshItemsFromTableAsync (); } catch (Java.Net.MalformedURLException) { CreateAndShowDialog (new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error"); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } //Initializes the activity menu public override bool OnCreateOptionsMenu (IMenu menu) { MenuInflater.Inflate (Resource.Menu.activity_main, menu); return true; } //Select an option from the menu public override bool OnOptionsItemSelected (IMenuItem item) { if (item.ItemId == Resource.Id.menu_refresh) { OnRefreshItemsSelected (); } return true; } // Called when the refresh menu opion is selected async void OnRefreshItemsSelected () { await RefreshItemsFromTableAsync (); } //Refresh the list with the items in the Mobile Service Table async Task RefreshItemsFromTableAsync () { try { // Get the items that weren't marked as completed and add them in the // adapter var list = await toDoTable.Where (item => item.Complete == false).ToListAsync (); adapter.Clear (); foreach (ToDoItem current in list) adapter.Add (current); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } public async Task CheckItem (ToDoItem item) { if (client == null) { return; } // Set the item as completed and update it in the table item.Complete = true; try { await toDoTable.UpdateAsync (item); if (item.Complete) adapter.Remove (item); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } [Java.Interop.Export()] public async void AddItem (View view) { if (client == null || string.IsNullOrWhiteSpace (textNewToDo.Text)) { return; } // Create a new item var item = new ToDoItem { Text = textNewToDo.Text, Complete = false }; try { // Insert the new item await toDoTable.InsertAsync (item); if (!item.Complete) { adapter.Add (item); } } catch (Exception e) { CreateAndShowDialog (e, "Error"); } textNewToDo.Text = ""; } void CreateAndShowDialog (Exception exception, String title) { CreateAndShowDialog (exception.Message, title); } void CreateAndShowDialog (string message, string title) { AlertDialog.Builder builder = new AlertDialog.Builder (this); builder.SetMessage (message); builder.SetTitle (title); builder.Create ().Show (); } class ProgressHandler : DelegatingHandler { int busyCount = 0; public event Action<bool> BusyStateChange; #region implemented abstract members of HttpMessageHandler protected override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { //assumes always executes on UI thread if (busyCount++ == 0 && BusyStateChange != null) BusyStateChange (true); var response = await base.SendAsync (request, cancellationToken); // assumes always executes on UI thread if (--busyCount == 0 && BusyStateChange != null) BusyStateChange (false); return response; } #endregion } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; namespace System.Net.Sockets { public partial class SocketAsyncEventArgs : EventArgs, IDisposable { private IntPtr _acceptedFileDescriptor; private int _socketAddressSize; private SocketFlags _receivedFlags; private Action<int, byte[], int, SocketFlags, SocketError> _transferCompletionCallback; private void InitializeInternals() { // No-op for *nix. } private void FreeInternals() { // No-op for *nix. } private void SetupSingleBuffer() { // No-op for *nix. } private void SetupMultipleBuffers() { // No-op for *nix. } private void CompleteCore() { } private void FinishOperationSync(SocketError socketError, int bytesTransferred, SocketFlags flags) { Debug.Assert(socketError != SocketError.IOPending); if (socketError == SocketError.Success) { FinishOperationSyncSuccess(bytesTransferred, flags); } else { FinishOperationSyncFailure(socketError, bytesTransferred, flags); } } private void AcceptCompletionCallback(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError) { CompleteAcceptOperation(acceptedFileDescriptor, socketAddress, socketAddressSize, socketError); CompletionCallback(0, SocketFlags.None, socketError); } private void CompleteAcceptOperation(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError) { _acceptedFileDescriptor = acceptedFileDescriptor; Debug.Assert(socketAddress == null || socketAddress == _acceptBuffer, $"Unexpected socketAddress: {socketAddress}"); _acceptAddressBufferCount = socketAddressSize; } internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle) { if (!_buffer.Equals(default)) { throw new PlatformNotSupportedException(SR.net_sockets_accept_receive_notsupported); } _acceptedFileDescriptor = (IntPtr)(-1); Debug.Assert(acceptHandle == null, $"Unexpected acceptHandle: {acceptHandle}"); IntPtr acceptedFd; int socketAddressLen = _acceptAddressBufferCount / 2; SocketError socketError = handle.AsyncContext.AcceptAsync(_acceptBuffer, ref socketAddressLen, out acceptedFd, AcceptCompletionCallback); if (socketError != SocketError.IOPending) { CompleteAcceptOperation(acceptedFd, _acceptBuffer, socketAddressLen, socketError); FinishOperationSync(socketError, 0, SocketFlags.None); } return socketError; } private void ConnectCompletionCallback(SocketError socketError) { CompletionCallback(0, SocketFlags.None, socketError); } internal unsafe SocketError DoOperationConnect(Socket socket, SafeSocketHandle handle) { SocketError socketError = handle.AsyncContext.ConnectAsync(_socketAddress.Buffer, _socketAddress.Size, ConnectCompletionCallback); if (socketError != SocketError.IOPending) { FinishOperationSync(socketError, 0, SocketFlags.None); } return socketError; } internal SocketError DoOperationDisconnect(Socket socket, SafeSocketHandle handle) { SocketError socketError = SocketPal.Disconnect(socket, handle, _disconnectReuseSocket); FinishOperationSync(socketError, 0, SocketFlags.None); return socketError; } private Action<int, byte[], int, SocketFlags, SocketError> TransferCompletionCallback => _transferCompletionCallback ?? (_transferCompletionCallback = TransferCompletionCallbackCore); private void TransferCompletionCallbackCore(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError) { CompleteTransferOperation(bytesTransferred, socketAddress, socketAddressSize, receivedFlags, socketError); CompletionCallback(bytesTransferred, receivedFlags, socketError); } private void CompleteTransferOperation(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError) { Debug.Assert(socketAddress == null || socketAddress == _socketAddress.Buffer, $"Unexpected socketAddress: {socketAddress}"); _socketAddressSize = socketAddressSize; _receivedFlags = receivedFlags; } internal unsafe SocketError DoOperationReceive(SafeSocketHandle handle) { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; SocketFlags flags; int bytesReceived; SocketError errorCode; if (_bufferList == null) { errorCode = handle.AsyncContext.ReceiveAsync(_buffer.Slice(_offset, _count), _socketFlags, out bytesReceived, out flags, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.ReceiveAsync(_bufferListInternal, _socketFlags, out bytesReceived, out flags, TransferCompletionCallback); } if (errorCode != SocketError.IOPending) { CompleteTransferOperation(bytesReceived, null, 0, flags, errorCode); FinishOperationSync(errorCode, bytesReceived, flags); } return errorCode; } internal unsafe SocketError DoOperationReceiveFrom(SafeSocketHandle handle) { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; SocketFlags flags; SocketError errorCode; int bytesReceived = 0; int socketAddressLen = _socketAddress.Size; if (_bufferList == null) { errorCode = handle.AsyncContext.ReceiveFromAsync(_buffer.Slice(_offset, _count), _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesReceived, out flags, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.ReceiveFromAsync(_bufferListInternal, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesReceived, out flags, TransferCompletionCallback); } if (errorCode != SocketError.IOPending) { CompleteTransferOperation(bytesReceived, _socketAddress.Buffer, socketAddressLen, flags, errorCode); FinishOperationSync(errorCode, bytesReceived, flags); } return errorCode; } private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode) { CompleteReceiveMessageFromOperation(bytesTransferred, socketAddress, socketAddressSize, receivedFlags, ipPacketInformation, errorCode); CompletionCallback(bytesTransferred, receivedFlags, errorCode); } private void CompleteReceiveMessageFromOperation(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode) { Debug.Assert(_socketAddress != null, "Expected non-null _socketAddress"); Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress, $"Unexpected socketAddress: {socketAddress}"); _socketAddressSize = socketAddressSize; _receivedFlags = receivedFlags; _receiveMessageFromPacketInfo = ipPacketInformation; } internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeSocketHandle handle) { _receiveMessageFromPacketInfo = default(IPPacketInformation); _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; bool isIPv4, isIPv6; Socket.GetIPProtocolInformation(socket.AddressFamily, _socketAddress, out isIPv4, out isIPv6); int socketAddressSize = _socketAddress.Size; int bytesReceived; SocketFlags receivedFlags; IPPacketInformation ipPacketInformation; SocketError socketError = handle.AsyncContext.ReceiveMessageFromAsync(_buffer.Slice(_offset, _count), _bufferListInternal, _socketFlags, _socketAddress.Buffer, ref socketAddressSize, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, ReceiveMessageFromCompletionCallback); if (socketError != SocketError.IOPending) { CompleteReceiveMessageFromOperation(bytesReceived, _socketAddress.Buffer, socketAddressSize, receivedFlags, ipPacketInformation, socketError); FinishOperationSync(socketError, bytesReceived, receivedFlags); } return socketError; } internal unsafe SocketError DoOperationSend(SafeSocketHandle handle) { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; int bytesSent; SocketError errorCode; if (_bufferList == null) { errorCode = handle.AsyncContext.SendAsync(_buffer, _offset, _count, _socketFlags, out bytesSent, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.SendAsync(_bufferListInternal, _socketFlags, out bytesSent, TransferCompletionCallback); } if (errorCode != SocketError.IOPending) { CompleteTransferOperation(bytesSent, null, 0, SocketFlags.None, errorCode); FinishOperationSync(errorCode, bytesSent, SocketFlags.None); } return errorCode; } internal SocketError DoOperationSendPackets(Socket socket, SafeSocketHandle handle) { Debug.Assert(_sendPacketsElements != null); SendPacketsElement[] elements = (SendPacketsElement[])_sendPacketsElements.Clone(); FileStream[] files = new FileStream[elements.Length]; // Open all files synchronously ahead of time so that any exceptions are propagated // to the caller, to match Windows behavior. try { for (int i = 0; i < elements.Length; i++) { string path = elements[i]?.FilePath; if (path != null) { files[i] = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, useAsync: true); } } } catch (Exception exc) { // Clean up any files that were already opened. foreach (FileStream s in files) { s?.Dispose(); } // Windows differentiates the directory not being found from the file not being found. // Approximate this by checking to see if the directory exists; this is only best-effort, // as there are various things that could affect this, e.g. directory creation racing with // this check, but it's good enough for most situations. if (exc is FileNotFoundException fnfe) { string dirname = Path.GetDirectoryName(fnfe.FileName); if (!string.IsNullOrEmpty(dirname) && !Directory.Exists(dirname)) { throw new DirectoryNotFoundException(fnfe.Message); } } // Otherwise propagate the original error. throw; } SocketPal.SendPacketsAsync(socket, SendPacketsFlags, elements, files, (bytesTransferred, error) => { if (error == SocketError.Success) { FinishOperationAsyncSuccess((int)bytesTransferred, SocketFlags.None); } else { FinishOperationAsyncFailure(error, (int)bytesTransferred, SocketFlags.None); } }); return SocketError.IOPending; } internal SocketError DoOperationSendTo(SafeSocketHandle handle) { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; int bytesSent; int socketAddressLen = _socketAddress.Size; SocketError errorCode; if (_bufferList == null) { errorCode = handle.AsyncContext.SendToAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesSent, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.SendToAsync(_bufferListInternal, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesSent, TransferCompletionCallback); } if (errorCode != SocketError.IOPending) { CompleteTransferOperation(bytesSent, _socketAddress.Buffer, socketAddressLen, SocketFlags.None, errorCode); FinishOperationSync(errorCode, bytesSent, SocketFlags.None); } return errorCode; } internal void LogBuffer(int size) { // This should only be called if tracing is enabled. However, there is the potential for a race // condition where tracing is disabled between a calling check and here, in which case the assert // may fire erroneously. Debug.Assert(NetEventSource.IsEnabled); if (_bufferList == null) { NetEventSource.DumpBuffer(this, _buffer, _offset, size); } else if (_acceptBuffer != null) { NetEventSource.DumpBuffer(this, _acceptBuffer, 0, size); } } internal void LogSendPacketsBuffers(int size) { foreach (SendPacketsElement spe in _sendPacketsElements) { if (spe != null) { if (spe.Buffer != null && spe.Count > 0) { NetEventSource.DumpBuffer(this, spe.Buffer, spe.Offset, Math.Min(spe.Count, size)); } else if (spe.FilePath != null) { NetEventSource.NotLoggedFile(spe.FilePath, _currentSocket, _completedOperation); } else if (spe.FileStream != null) { NetEventSource.NotLoggedFile(spe.FileStream.Name, _currentSocket, _completedOperation); } } } } private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress) { System.Buffer.BlockCopy(_acceptBuffer, 0, remoteSocketAddress.Buffer, 0, _acceptAddressBufferCount); _acceptSocket = _currentSocket.CreateAcceptSocket( SafeSocketHandle.CreateSocket(_acceptedFileDescriptor), _currentSocket._rightEndPoint.Create(remoteSocketAddress)); return SocketError.Success; } private SocketError FinishOperationConnect() { // No-op for *nix. return SocketError.Success; } private unsafe int GetSocketAddressSize() { return _socketAddressSize; } private unsafe void FinishOperationReceiveMessageFrom() { // No-op for *nix. } private void FinishOperationSendPackets() { // No-op for *nix. } private void CompletionCallback(int bytesTransferred, SocketFlags flags, SocketError socketError) { if (socketError == SocketError.Success) { FinishOperationAsyncSuccess(bytesTransferred, flags); } else { if (_currentSocket.CleanedUp) { socketError = SocketError.OperationAborted; } FinishOperationAsyncFailure(socketError, bytesTransferred, flags); } } } }
// // RescanPipeline.cs // // Authors: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Data; using Mono.Unix; using Hyena; using Hyena.Jobs; using Hyena.Collections; using Hyena.Data.Sqlite; using Banshee.Base; using Banshee.Sources; using Banshee.Collection.Database; using Banshee.Library; using Banshee.ServiceStack; namespace Banshee.Collection { // Goals: // 1. Add new files that are on disk but not in the library // 2. Find the updated location of files that were moved // 3. Update metadata for files that were changed since we last scanned/imported // 4. Remove tracks that aren't on disk and weren't found to have moved // // Approach: // 1. For each file in the source's directory, find orphaned db track if any, or add if new // and update if modified; update the LastScannedAt stamp // 2. Remove all db tracks from the database that weren't scanned (LastScannedAt < scan_started) public class RescanPipeline : QueuePipeline<string> { private DateTime scan_started; private PrimarySource psource; private BatchUserJob job; private TrackSyncPipelineElement track_sync; public RescanPipeline (LibrarySource psource) : base () { this.psource = psource; scan_started = DateTime.Now; AddElement (new Banshee.IO.DirectoryScannerPipelineElement ()); AddElement (track_sync = new TrackSyncPipelineElement (psource, scan_started)); Finished += OnFinished; BuildJob (); Enqueue (psource.BaseDirectory); } private void BuildJob () { job = new BatchUserJob (Catalog.GetString ("Rescanning {0} of {1}"), "system-search", "gtk-find"); job.SetResources (Resource.Cpu, Resource.Disk, Resource.Database); job.PriorityHints = PriorityHints.SpeedSensitive; job.CanCancel = true; job.CancelRequested += delegate { cancelled = true; Cancel (); }; track_sync.ProcessedItem += delegate { job.Total = track_sync.TotalCount; job.Completed = track_sync.ProcessedCount; job.Status = track_sync.Status; }; job.Register (); } private bool cancelled = false; private void OnFinished (object o, EventArgs args) { job.Finish (); if (cancelled) { return; } //Hyena.Log.DebugFormat ("Have {0} items before delete", ServiceManager.DbConnection.Query<int>("select count(*) from coretracks where primarysourceid=?", psource.DbId)); // Delete tracks that are under the BaseDirectory and that weren't rescanned just now string condition = @"WHERE PrimarySourceID = ? AND Uri LIKE ? ESCAPE '\' AND LastSyncedStamp IS NOT NULL AND LastSyncedStamp < ?"; string uri = Hyena.StringUtil.EscapeLike (new SafeUri (psource.BaseDirectoryWithSeparator).AbsoluteUri) + "%"; ServiceManager.DbConnection.Execute (String.Format (@"BEGIN; DELETE FROM CorePlaylistEntries WHERE TrackID IN (SELECT TrackID FROM CoreTracks {0}); DELETE FROM CoreSmartPlaylistEntries WHERE TrackID IN (SELECT TrackID FROM CoreTracks {0}); DELETE FROM CoreTracks {0}; COMMIT", condition), psource.DbId, uri, scan_started, psource.DbId, uri, scan_started, psource.DbId, uri, scan_started ); // TODO prune artists/albums psource.Reload (); psource.NotifyTracksChanged (); //Hyena.Log.DebugFormat ("Have {0} items after delete", ServiceManager.DbConnection.Query<int>("select count(*) from coretracks where primarysourceid=?", psource.DbId)); } } public class TrackSyncPipelineElement : QueuePipelineElement<string> { private PrimarySource psource; private DateTime scan_started; private HyenaSqliteCommand fetch_command, fetch_similar_command; private string status; public string Status { get { return status; } } public TrackSyncPipelineElement (PrimarySource psource, DateTime scan_started) : base () { this.psource = psource; this.scan_started = scan_started; fetch_command = DatabaseTrackInfo.Provider.CreateFetchCommand ( "CoreTracks.PrimarySourceID = ? AND CoreTracks.Uri = ? LIMIT 1"); fetch_similar_command = DatabaseTrackInfo.Provider.CreateFetchCommand ( "CoreTracks.PrimarySourceID = ? AND CoreTracks.LastSyncedStamp < ? AND CoreTracks.MetadataHash = ?"); } protected override string ProcessItem (string file_path) { if (!DatabaseImportManager.IsWhiteListedFile (file_path)) { return null; } // Hack to ignore Podcast files if (file_path.Contains ("Podcasts")) { return null; } //Hyena.Log.DebugFormat ("Rescanning item {0}", file_path); try { SafeUri uri = new SafeUri (file_path); using (var reader = ServiceManager.DbConnection.Query (fetch_command, psource.DbId, uri.AbsoluteUri)) { if (reader.Read () ) { //Hyena.Log.DebugFormat ("Found it in the db!"); DatabaseTrackInfo track = DatabaseTrackInfo.Provider.Load (reader); MergeIfModified (track); // Either way, update the LastSyncStamp track.LastSyncedStamp = DateTime.Now; track.Save (false); status = String.Format ("{0} - {1}", track.DisplayArtistName, track.DisplayTrackTitle); } else { // This URI is not in the database - try to find it based on MetadataHash in case it was simply moved DatabaseTrackInfo track = new DatabaseTrackInfo (); Banshee.Streaming.StreamTagger.TrackInfoMerge (track, uri); using (var similar_reader = ServiceManager.DbConnection.Query ( fetch_similar_command, psource.DbId, scan_started, track.MetadataHash)) { DatabaseTrackInfo similar_track = null; while (similar_reader.Read ()) { similar_track = DatabaseTrackInfo.Provider.Load (similar_reader); if (!Banshee.IO.File.Exists (similar_track.Uri)) { //Hyena.Log.DebugFormat ("Apparently {0} was moved to {1}", similar_track.Uri, file_path); similar_track.Uri = uri; MergeIfModified (similar_track); similar_track.LastSyncedStamp = DateTime.Now; similar_track.Save (false); status = String.Format ("{0} - {1}", similar_track.DisplayArtistName, similar_track.DisplayTrackTitle); break; } similar_track = null; } // If we still couldn't find it, try to import it if (similar_track == null) { //Hyena.Log.DebugFormat ("Couldn't find it, so queueing to import it"); status = System.IO.Path.GetFileNameWithoutExtension (file_path); ServiceManager.Get<Banshee.Library.LibraryImportManager> ().ImportTrack (file_path); } } } } } catch (Exception e) { Hyena.Log.Exception (e); } return null; } private void MergeIfModified (TrackInfo track) { long mtime = Banshee.IO.File.GetModifiedTime (track.Uri); // If the file was modified since we last scanned, parse the file's metadata if (mtime > track.FileModifiedStamp) { using (var file = Banshee.Streaming.StreamTagger.ProcessUri (track.Uri)) { Banshee.Streaming.StreamTagger.TrackInfoMerge (track, file, false); } } } } }
using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Support; using NUnit.Framework; namespace Lucene.Net.Search.Spans { using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; [TestFixture] public class TestNearSpansOrdered : LuceneTestCase { protected internal IndexSearcher Searcher; protected internal Directory Directory; protected internal IndexReader Reader; public const string FIELD = "field"; [TearDown] public override void TearDown() { Reader.Dispose(); Directory.Dispose(); base.TearDown(); } [SetUp] public override void SetUp() { base.SetUp(); Directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy())); for (int i = 0; i < DocFields.Length; i++) { Document doc = new Document(); doc.Add(NewTextField(FIELD, DocFields[i], Field.Store.NO)); writer.AddDocument(doc); } Reader = writer.Reader; writer.Dispose(); Searcher = NewSearcher(Reader); } protected internal string[] DocFields = new string[] { "w1 w2 w3 w4 w5", "w1 w3 w2 w3 zz", "w1 xx w2 yy w3", "w1 w3 xx w2 yy w3 zz" }; protected internal virtual SpanNearQuery MakeQuery(string s1, string s2, string s3, int slop, bool inOrder) { return new SpanNearQuery(new SpanQuery[] { new SpanTermQuery(new Term(FIELD, s1)), new SpanTermQuery(new Term(FIELD, s2)), new SpanTermQuery(new Term(FIELD, s3)) }, slop, inOrder); } protected internal virtual SpanNearQuery MakeQuery() { return MakeQuery("w1", "w2", "w3", 1, true); } [Test] public virtual void TestSpanNearQuery() { SpanNearQuery q = MakeQuery(); CheckHits.DoCheckHits(Random(), q, FIELD, Searcher, new int[] { 0, 1 }, Similarity); } public virtual string s(Spans span) { return s(span.Doc, span.Start, span.End); } public virtual string s(int doc, int start, int end) { return "s(" + doc + "," + start + "," + end + ")"; } [Test] public virtual void TestNearSpansNext() { SpanNearQuery q = MakeQuery(); Spans span = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, q); Assert.AreEqual(true, span.Next()); Assert.AreEqual(s(0, 0, 3), s(span)); Assert.AreEqual(true, span.Next()); Assert.AreEqual(s(1, 0, 4), s(span)); Assert.AreEqual(false, span.Next()); } /// <summary> /// test does not imply that skipTo(doc+1) should work exactly the /// same as next -- it's only applicable in this case since we know doc /// does not contain more than one span /// </summary> [Test] public virtual void TestNearSpansSkipToLikeNext() { SpanNearQuery q = MakeQuery(); Spans span = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, q); Assert.AreEqual(true, span.SkipTo(0)); Assert.AreEqual(s(0, 0, 3), s(span)); Assert.AreEqual(true, span.SkipTo(1)); Assert.AreEqual(s(1, 0, 4), s(span)); Assert.AreEqual(false, span.SkipTo(2)); } [Test] public virtual void TestNearSpansNextThenSkipTo() { SpanNearQuery q = MakeQuery(); Spans span = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, q); Assert.AreEqual(true, span.Next()); Assert.AreEqual(s(0, 0, 3), s(span)); Assert.AreEqual(true, span.SkipTo(1)); Assert.AreEqual(s(1, 0, 4), s(span)); Assert.AreEqual(false, span.Next()); } [Test] public virtual void TestNearSpansNextThenSkipPast() { SpanNearQuery q = MakeQuery(); Spans span = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, q); Assert.AreEqual(true, span.Next()); Assert.AreEqual(s(0, 0, 3), s(span)); Assert.AreEqual(false, span.SkipTo(2)); } [Test] public virtual void TestNearSpansSkipPast() { SpanNearQuery q = MakeQuery(); Spans span = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, q); Assert.AreEqual(false, span.SkipTo(2)); } [Test] public virtual void TestNearSpansSkipTo0() { SpanNearQuery q = MakeQuery(); Spans span = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, q); Assert.AreEqual(true, span.SkipTo(0)); Assert.AreEqual(s(0, 0, 3), s(span)); } [Test] public virtual void TestNearSpansSkipTo1() { SpanNearQuery q = MakeQuery(); Spans span = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, q); Assert.AreEqual(true, span.SkipTo(1)); Assert.AreEqual(s(1, 0, 4), s(span)); } /// <summary> /// not a direct test of NearSpans, but a demonstration of how/when /// this causes problems /// </summary> [Test] public virtual void TestSpanNearScorerSkipTo1() { SpanNearQuery q = MakeQuery(); Weight w = Searcher.CreateNormalizedWeight(q); IndexReaderContext topReaderContext = Searcher.TopReaderContext; AtomicReaderContext leave = topReaderContext.Leaves[0]; Scorer s = w.GetScorer(leave, ((AtomicReader)leave.Reader).LiveDocs); Assert.AreEqual(1, s.Advance(1)); } /// <summary> /// not a direct test of NearSpans, but a demonstration of how/when /// this causes problems /// </summary> [Test] public virtual void TestSpanNearScorerExplain() { SpanNearQuery q = MakeQuery(); Explanation e = Searcher.Explain(q, 1); Assert.IsTrue(0.0f < e.Value, "Scorer explanation value for doc#1 isn't positive: " + e.ToString()); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.OpsWorks.Model { /// <summary> /// Container for the parameters to the CreateInstance operation. /// Creates an instance in a specified stack. For more information, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-add.html">Adding /// an Instance to a Layer</a>. /// /// /// <para> /// <b>Required Permissions</b>: To use this action, an IAM user must have a Manage permissions /// level for the stack, or an attached policy that explicitly grants permissions. For /// more information on user permissions, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html">Managing /// User Permissions</a>. /// </para> /// </summary> public partial class CreateInstanceRequest : AmazonOpsWorksRequest { private string _agentVersion; private string _amiId; private Architecture _architecture; private AutoScalingType _autoScalingType; private string _availabilityZone; private List<BlockDeviceMapping> _blockDeviceMappings = new List<BlockDeviceMapping>(); private bool? _ebsOptimized; private string _hostname; private bool? _installUpdatesOnBoot; private string _instanceType; private List<string> _layerIds = new List<string>(); private string _os; private RootDeviceType _rootDeviceType; private string _sshKeyName; private string _stackId; private string _subnetId; private VirtualizationType _virtualizationType; /// <summary> /// Gets and sets the property AgentVersion. /// <para> /// The default AWS OpsWorks agent version. You have the following options: /// </para> /// <ul> <li> <code>INHERIT</code> - Use the stack's default agent version setting.</li> /// <li> <i>version_number</i> - Use the specified agent version. This value overrides /// the stack's default setting. To update the agent version, edit the instance configuration /// and specify a new version. AWS OpsWorks then automatically installs that version on /// the instance.</li> </ul> /// <para> /// The default setting is <code>INHERIT</code>. To specify an agent version, you must /// use the complete version number, not the abbreviated number shown on the console. /// For a list of available agent version numbers, call <a>DescribeAgentVersions</a>. /// </para> /// </summary> public string AgentVersion { get { return this._agentVersion; } set { this._agentVersion = value; } } // Check to see if AgentVersion property is set internal bool IsSetAgentVersion() { return this._agentVersion != null; } /// <summary> /// Gets and sets the property AmiId. /// <para> /// A custom AMI ID to be used to create the instance. The AMI should be based on one /// of the supported operating systems. For more information, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-custom-ami.html">Using /// Custom AMIs</a>. /// </para> /// <note>If you specify a custom AMI, you must set <code>Os</code> to <code>Custom</code>.</note> /// </summary> public string AmiId { get { return this._amiId; } set { this._amiId = value; } } // Check to see if AmiId property is set internal bool IsSetAmiId() { return this._amiId != null; } /// <summary> /// Gets and sets the property Architecture. /// <para> /// The instance architecture. The default option is <code>x86_64</code>. Instance types /// do not necessarily support both architectures. For a list of the architectures that /// are supported by the different instance types, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html">Instance /// Families and Types</a>. /// </para> /// </summary> public Architecture Architecture { get { return this._architecture; } set { this._architecture = value; } } // Check to see if Architecture property is set internal bool IsSetArchitecture() { return this._architecture != null; } /// <summary> /// Gets and sets the property AutoScalingType. /// <para> /// For load-based or time-based instances, the type. Windows stacks can use only time-based /// instances. /// </para> /// </summary> public AutoScalingType AutoScalingType { get { return this._autoScalingType; } set { this._autoScalingType = value; } } // Check to see if AutoScalingType property is set internal bool IsSetAutoScalingType() { return this._autoScalingType != null; } /// <summary> /// Gets and sets the property AvailabilityZone. /// <para> /// The instance Availability Zone. For more information, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions /// and Endpoints</a>. /// </para> /// </summary> public string AvailabilityZone { get { return this._availabilityZone; } set { this._availabilityZone = value; } } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this._availabilityZone != null; } /// <summary> /// Gets and sets the property BlockDeviceMappings. /// <para> /// An array of <code>BlockDeviceMapping</code> objects that specify the instance's block /// devices. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html">Block /// Device Mapping</a>. /// </para> /// </summary> public List<BlockDeviceMapping> BlockDeviceMappings { get { return this._blockDeviceMappings; } set { this._blockDeviceMappings = value; } } // Check to see if BlockDeviceMappings property is set internal bool IsSetBlockDeviceMappings() { return this._blockDeviceMappings != null && this._blockDeviceMappings.Count > 0; } /// <summary> /// Gets and sets the property EbsOptimized. /// <para> /// Whether to create an Amazon EBS-optimized instance. /// </para> /// </summary> public bool EbsOptimized { get { return this._ebsOptimized.GetValueOrDefault(); } set { this._ebsOptimized = value; } } // Check to see if EbsOptimized property is set internal bool IsSetEbsOptimized() { return this._ebsOptimized.HasValue; } /// <summary> /// Gets and sets the property Hostname. /// <para> /// The instance host name. /// </para> /// </summary> public string Hostname { get { return this._hostname; } set { this._hostname = value; } } // Check to see if Hostname property is set internal bool IsSetHostname() { return this._hostname != null; } /// <summary> /// Gets and sets the property InstallUpdatesOnBoot. /// <para> /// Whether to install operating system and package updates when the instance boots. The /// default value is <code>true</code>. To control when updates are installed, set this /// value to <code>false</code>. You must then update your instances manually by using /// <a>CreateDeployment</a> to run the <code>update_dependencies</code> stack command /// or by manually running <code>yum</code> (Amazon Linux) or <code>apt-get</code> (Ubuntu) /// on the instances. /// </para> /// <note> /// <para> /// We strongly recommend using the default value of <code>true</code> to ensure that /// your instances have the latest security updates. /// </para> /// </note> /// </summary> public bool InstallUpdatesOnBoot { get { return this._installUpdatesOnBoot.GetValueOrDefault(); } set { this._installUpdatesOnBoot = value; } } // Check to see if InstallUpdatesOnBoot property is set internal bool IsSetInstallUpdatesOnBoot() { return this._installUpdatesOnBoot.HasValue; } /// <summary> /// Gets and sets the property InstanceType. /// <para> /// The instance type, such as <code>t2.micro</code>. For a list of supported instance /// types, open the stack in the console, choose <b>Instances</b>, and choose <b>+ Instance</b>. /// The <b>Size</b> list contains the currently supported types. For more information, /// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html">Instance /// Families and Types</a>. The parameter values that you use to specify the various types /// are in the <b>API Name</b> column of the <b>Available Instance Types</b> table. /// </para> /// </summary> public string InstanceType { get { return this._instanceType; } set { this._instanceType = value; } } // Check to see if InstanceType property is set internal bool IsSetInstanceType() { return this._instanceType != null; } /// <summary> /// Gets and sets the property LayerIds. /// <para> /// An array that contains the instance's layer IDs. /// </para> /// </summary> public List<string> LayerIds { get { return this._layerIds; } set { this._layerIds = value; } } // Check to see if LayerIds property is set internal bool IsSetLayerIds() { return this._layerIds != null && this._layerIds.Count > 0; } /// <summary> /// Gets and sets the property Os. /// <para> /// The instance's operating system, which must be set to one of the following. /// </para> /// <ul> <li>A supported Linux operating system: An Amazon Linux version, such as <code>Amazon /// Linux 2015.03</code>, <code>Red Hat Enterprise Linux 7</code>, <code>Ubuntu 12.04 /// LTS</code>, or <code>Ubuntu 14.04 LTS</code>.</li> <li> <code>Microsoft Windows Server /// 2012 R2 Base</code>.</li> <li>A custom AMI: <code>Custom</code>.</li> </ul> /// <para> /// For more information on the supported operating systems, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html">AWS /// OpsWorks Operating Systems</a>. /// </para> /// /// <para> /// The default option is the current Amazon Linux version. If you set this parameter /// to <code>Custom</code>, you must use the <a>CreateInstance</a> action's AmiId parameter /// to specify the custom AMI that you want to use. For more information on the supported /// operating systems, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html">Operating /// Systems</a>For more information on how to use custom AMIs with AWS OpsWorks, see <a /// href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-custom-ami.html">Using /// Custom AMIs</a>. /// </para> /// </summary> public string Os { get { return this._os; } set { this._os = value; } } // Check to see if Os property is set internal bool IsSetOs() { return this._os != null; } /// <summary> /// Gets and sets the property RootDeviceType. /// <para> /// The instance root device type. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device">Storage /// for the Root Device</a>. /// </para> /// </summary> public RootDeviceType RootDeviceType { get { return this._rootDeviceType; } set { this._rootDeviceType = value; } } // Check to see if RootDeviceType property is set internal bool IsSetRootDeviceType() { return this._rootDeviceType != null; } /// <summary> /// Gets and sets the property SshKeyName. /// <para> /// The instance's Amazon EC2 key-pair name. /// </para> /// </summary> public string SshKeyName { get { return this._sshKeyName; } set { this._sshKeyName = value; } } // Check to see if SshKeyName property is set internal bool IsSetSshKeyName() { return this._sshKeyName != null; } /// <summary> /// Gets and sets the property StackId. /// <para> /// The stack ID. /// </para> /// </summary> public string StackId { get { return this._stackId; } set { this._stackId = value; } } // Check to see if StackId property is set internal bool IsSetStackId() { return this._stackId != null; } /// <summary> /// Gets and sets the property SubnetId. /// <para> /// The ID of the instance's subnet. If the stack is running in a VPC, you can use this /// parameter to override the stack's default subnet ID value and direct AWS OpsWorks /// to launch the instance in a different subnet. /// </para> /// </summary> public string SubnetId { get { return this._subnetId; } set { this._subnetId = value; } } // Check to see if SubnetId property is set internal bool IsSetSubnetId() { return this._subnetId != null; } /// <summary> /// Gets and sets the property VirtualizationType. /// <para> /// The instance's virtualization type, <code>paravirtual</code> or <code>hvm</code>. /// </para> /// </summary> public VirtualizationType VirtualizationType { get { return this._virtualizationType; } set { this._virtualizationType = value; } } // Check to see if VirtualizationType property is set internal bool IsSetVirtualizationType() { return this._virtualizationType != null; } } }
//------------------------------------------------------------------------------ // <copyright file="InterchangeableLists.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ #if UNUSED_CODE namespace System.Web.UI.Design.MobileControls.Util { using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Diagnostics; using System.Web.UI.Design.MobileControls; using System.Windows.Forms; [ ToolboxItem(false), System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] internal sealed class InterchangeableLists : System.Windows.Forms.Panel { private System.Windows.Forms.Button _removeButton; private System.Windows.Forms.Button _addButton; private System.Windows.Forms.Button _upButton; private System.Windows.Forms.TreeView _availableList; private System.Windows.Forms.Label _availableFieldLabel; private System.Windows.Forms.TreeView _selectedList; private System.Windows.Forms.Button _downButton; private System.Windows.Forms.Label _selectedFieldLabel; private Hashtable _eventTable; /// <summary> /// Required designer variable. /// </summary> private static readonly Object _componentChangedEvent = new Object(); internal InterchangeableLists() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // _downButton.Image = GenericUI.SortDownIcon; _upButton.Image = GenericUI.SortUpIcon; UpdateButtonEnabling(); this._eventTable = new Hashtable(); } internal void SetTitles( String availableListTitle, String selectedListTitle) { this._selectedFieldLabel.Text = selectedListTitle; this._availableFieldLabel.Text = availableListTitle; } internal void AddToAvailableList(Object obj) { AddItem(_availableList, new TreeNode(obj.ToString())); } internal void AddToSelectedList(Object obj) { AddItem(_selectedList, new TreeNode(obj.ToString())); } internal void Initialize() { if (_availableList.Nodes.Count > 0) { _availableList.SelectedNode = _availableList.Nodes[0]; } if (_selectedList.Nodes.Count > 0) { _selectedList.SelectedNode = _selectedList.Nodes[0]; } } internal EventHandler OnComponentChanged { get { return (EventHandler)_eventTable[_componentChangedEvent]; } set { _eventTable[_componentChangedEvent] = value; } } private void NotifyChangeEvent() { EventHandler handler = (EventHandler)_eventTable[_componentChangedEvent]; if (handler != null) { handler(this, EventArgs.Empty); } } internal void Clear() { _availableList.Nodes.Clear(); _selectedList.Nodes.Clear(); } internal ICollection GetSelectedItems() { ArrayList list = new ArrayList(); foreach (TreeNode node in _selectedList.Nodes) { list.Add(node.Text); } return list; } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this._removeButton = new System.Windows.Forms.Button(); this._selectedFieldLabel = new System.Windows.Forms.Label(); this._addButton = new System.Windows.Forms.Button(); this._selectedList = new System.Windows.Forms.TreeView(); this._availableList = new System.Windows.Forms.TreeView(); this._availableFieldLabel = new System.Windows.Forms.Label(); this._upButton = new System.Windows.Forms.Button(); this._downButton = new System.Windows.Forms.Button(); this._removeButton.Location = new System.Drawing.Point(166, 69); this._removeButton.Size = new System.Drawing.Size(32, 25); this._removeButton.TabIndex = 4; this._removeButton.Text = "<"; this._removeButton.Click += new System.EventHandler(this.RemoveNode); this._removeButton.AccessibleName = SR.GetString(SR.EditableTreeList_DeleteName); this._removeButton.AccessibleDescription = SR.GetString(SR.EditableTreeList_DeleteDescription); this._removeButton.Name = SR.GetString(SR.EditableTreeList_DeleteName); this._selectedFieldLabel.Location = new System.Drawing.Point(202, 8); this._selectedFieldLabel.Size = new System.Drawing.Size(164, 16); this._selectedFieldLabel.TabIndex = 5; this._addButton.AccessibleName = SR.GetString(SR.EditableTreeList_AddName); this._addButton.AccessibleDescription = SR.GetString(SR.EditableTreeList_AddDescription); this._addButton.Name = SR.GetString(SR.EditableTreeList_AddName); this._addButton.Location = new System.Drawing.Point(166, 40); this._addButton.Size = new System.Drawing.Size(32, 25); this._addButton.TabIndex = 3; this._addButton.Text = ">"; this._addButton.Click += new System.EventHandler(this.AddNode); this._selectedList.HideSelection = false; this._selectedList.Indent = 15; this._selectedList.Location = new System.Drawing.Point(202, 24); this._selectedList.ShowLines = false; this._selectedList.ShowPlusMinus = false; this._selectedList.ShowRootLines = false; this._selectedList.Size = new System.Drawing.Size(154, 89); this._selectedList.TabIndex = 6; this._selectedList.DoubleClick += new System.EventHandler(this.RemoveNode); this._selectedList.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.SelectedList_AfterSelect); this._availableList.HideSelection = false; this._availableList.Indent = 15; this._availableList.Location = new System.Drawing.Point(8, 24); this._availableList.ShowLines = false; this._availableList.ShowPlusMinus = false; this._availableList.ShowRootLines = false; this._availableList.Size = new System.Drawing.Size(154, 89); this._availableList.TabIndex = 2; this._availableList.DoubleClick += new System.EventHandler(this.AddNode); this._availableList.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.AvailableList_AfterSelect); this._availableFieldLabel.Location = new System.Drawing.Point(8, 8); this._availableFieldLabel.Size = new System.Drawing.Size(164, 16); this._availableFieldLabel.TabIndex = 1; this._upButton.AccessibleName = SR.GetString(SR.EditableTreeList_MoveUpName); this._upButton.AccessibleDescription = SR.GetString(SR.EditableTreeList_MoveUpDescription); this._upButton.Name = SR.GetString(SR.EditableTreeList_MoveUpName); this._upButton.Location = new System.Drawing.Point(360, 24); this._upButton.Size = new System.Drawing.Size(28, 27); this._upButton.TabIndex = 7; this._upButton.Click += new System.EventHandler(this.Up_Click); this._downButton.AccessibleName = SR.GetString(SR.EditableTreeList_MoveDownName); this._downButton.AccessibleDescription = SR.GetString(SR.EditableTreeList_MoveDownDescription); this._downButton.Name = SR.GetString(SR.EditableTreeList_MoveDownName); this._downButton.Location = new System.Drawing.Point(360, 55); this._downButton.Size = new System.Drawing.Size(28, 27); this._downButton.TabIndex = 8; this._downButton.Click += new System.EventHandler(this.Down_Click); this.Controls.AddRange(new System.Windows.Forms.Control[] {this._availableFieldLabel, this._selectedFieldLabel, this._upButton, this._downButton, this._removeButton, this._selectedList, this._addButton, this._availableList}); this.Size = new System.Drawing.Size(396, 119); } private void UpdateButtonEnabling() { bool anAvailableItemIsSelected = (_availableList.SelectedNode != null); bool anSelectedItemIsSelected = (_selectedList.SelectedNode != null); _addButton.Enabled = anAvailableItemIsSelected; _removeButton.Enabled = anSelectedItemIsSelected; if (anSelectedItemIsSelected) { int selectedIndex = _selectedList.SelectedNode.Index; _upButton.Enabled = (selectedIndex > 0); _downButton.Enabled = (selectedIndex < _selectedList.Nodes.Count - 1); } else { _downButton.Enabled = false; _upButton.Enabled = false; } } private void AddNode(object sender, System.EventArgs e) { TreeNode selectedNode = _availableList.SelectedNode; if (selectedNode != null) { RemoveItem(_availableList, selectedNode); AddItem(_selectedList, selectedNode); UpdateButtonEnabling(); NotifyChangeEvent(); } } private void RemoveItem(TreeView list, TreeNode node) { Debug.Assert (list.Nodes.Contains(node)); int itemCount = list.Nodes.Count; int selectedIndex = list.SelectedNode.Index; list.Nodes.Remove(node); if (selectedIndex < itemCount - 1) { list.SelectedNode = list.Nodes[selectedIndex]; } else if (selectedIndex >= 1) { list.SelectedNode = list.Nodes[selectedIndex-1]; } else { Debug.Assert(itemCount == 1); list.SelectedNode = null; } } private void AddItem(TreeView list, TreeNode node) { Debug.Assert(node != null); list.Nodes.Add(node); list.SelectedNode = node; //_selectedList.Select(); } private void RemoveNode(object sender, System.EventArgs e) { TreeNode selectedNode = _selectedList.SelectedNode; if (selectedNode != null) { RemoveItem(_selectedList, selectedNode); AddItem(_availableList, selectedNode); UpdateButtonEnabling(); } //_availableList.Select(); NotifyChangeEvent(); } private void MoveItem( int direction /* 1 is up, -1 is down */) { Debug.Assert(direction == -1 || direction == 1); int selectedIndex = _selectedList.SelectedNode.Index; int newIndex = selectedIndex + direction; TreeNode node = _selectedList.SelectedNode; _selectedList.Nodes.RemoveAt(selectedIndex); _selectedList.Nodes.Insert(newIndex, node); _selectedList.SelectedNode = node; } private void Up_Click(object sender, System.EventArgs e) { MoveItem(-1); UpdateButtonEnabling(); //_selectedList.Select(); NotifyChangeEvent(); } private void Down_Click(object sender, System.EventArgs e) { MoveItem(+1); UpdateButtonEnabling(); //_selectedList.Select(); NotifyChangeEvent(); } private void AvailableList_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { UpdateButtonEnabling(); } private void SelectedList_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { UpdateButtonEnabling(); } } } #endif
//#define TRACEDEBUG //#define TRACEDEBUGTICKS #define TRACELOG using System; using System.Net; using System.Collections.Generic; using System.ComponentModel; using System.Security.Permissions; using Microsoft.Ccr.Core; using Microsoft.Dss.Core; using Microsoft.Dss.Core.Attributes; using Microsoft.Dss.ServiceModel.Dssp; using Microsoft.Dss.Core.DsspHttp; using Microsoft.Dss.ServiceModel.DsspServiceBase; using W3C.Soap; using TrackRoamer.Robotics.Utility.LibSystem; using submgr = Microsoft.Dss.Services.SubscriptionManager; using pxencoder = Microsoft.Robotics.Services.Encoder.Proxy; using powerbrick = TrackRoamer.Robotics.Services.TrackRoamerBrickPower.Proxy; namespace TrackRoamer.Robotics.Services.TrackRoamerServices.Encoder { [Contract(Contract.Identifier)] [AlternateContract(pxencoder.Contract.Identifier)] [DisplayName("(User) TrackRoamer Encoder")] [Description("Provides access to the TrackRoamer encoder.\n(Uses the Generic Encoder contract.)")] public class EncoderService : DsspServiceBase { [EmbeddedResource("TrackRoamer.Robotics.Services.TrackRoamerServices.TrackRoamerEncoder.xslt")] string _transform = null; [InitialStatePartner(Optional=true)] private pxencoder.EncoderState _state = new pxencoder.EncoderState(); private double? m_lastResetTicks; private object m_lastResetTicksLock = new object(); private bool _subscribed = false; [ServicePort("/TrackRoamerEncoder", AllowMultipleInstances = true)] private pxencoder.EncoderOperations _mainPort = new pxencoder.EncoderOperations(); [Partner("TrackRoamerPowerBrick", Contract = powerbrick.Contract.Identifier, CreationPolicy = PartnerCreationPolicy.UseExistingOrCreate, Optional = false)] private powerbrick.TrackRoamerBrickPowerOperations _trackroamerbotPort = new powerbrick.TrackRoamerBrickPowerOperations(); // Create a notification port; we will get only UpdateMotorEncoder on it: private Port<powerbrick.UpdateMotorEncoder> notificationPortEncoder = new Port<powerbrick.UpdateMotorEncoder>(); [SubscriptionManagerPartner] private submgr.SubscriptionManagerPort _subMgrPort = new submgr.SubscriptionManagerPort(); public EncoderService(DsspServiceCreationPort creationPort) : base(creationPort) { } protected override void Start() { // Configure default state. It will be replaced by the drive during configuration. if (_state == null) { _state = new pxencoder.EncoderState(); _state.HardwareIdentifier = -1; // 1=Left 2=Right _state.TicksPerRevolution = 100; SaveState(_state); } base.Start(); MainPortInterleave.CombineWith(new Interleave( new ExclusiveReceiverGroup( // prepare listening for Power Brick's encoder change notifications Arbiter.Receive<powerbrick.UpdateMotorEncoder>(true, notificationPortEncoder, MotorEncoderNotificationHandler) ), new ConcurrentReceiverGroup() )); // display HTTP service Uri LogInfo("Service uri: " + ServiceInfo.HttpUri()); // Subscribe to the Hardware Controller for encoder notifications if (ValidState(_state)) { SubscribeToPowerBrick(); } } private static bool ValidState(pxencoder.EncoderState state) { if (state != null) { if (state.HardwareIdentifier >= 1 && state.HardwareIdentifier <= 2) { return true; } } return false; } public string Name { get { string ret = "(INVALID STATE)"; if (ValidState(_state)) { ret = (_state.HardwareIdentifier == 1 ? "Left" : "Right"); } return ret + " Encoder"; } } private void SubscribeToPowerBrick() { Type[] notifyMeOf = new Type[] { typeof(powerbrick.UpdateMotorEncoder) }; Tracer.Trace("TrackRoamerEncoder: calling Subscribe() for UpdateMotorEncoder"); // Subscribe to the Power Brick and wait for a response Activate( Arbiter.Choice(_trackroamerbotPort.Subscribe(notificationPortEncoder, notifyMeOf), delegate(SubscribeResponseType Rsp) { // Subscription was successful, update our state with subscription status: _subscribed = true; LogInfo("EncoderService: " + Name + " Subscription to Power Brick Service succeeded"); }, delegate(Fault F) { LogError("EncoderService: " + Name + " Subscription to Power Brick Service failed"); } ) ); } /// <summary> /// we are getting encoder ticks for both sides from Power Brick here /// </summary> /// <param name="update"></param> private void MotorEncoderNotificationHandler(powerbrick.UpdateMotorEncoder update) { if (_state.HardwareIdentifier != update.Body.HardwareIdentifier) { #if TRACEDEBUGTICKS //LogInfo("TrackRoamerEncoder:MotorEncoderNotificationHandler() " + Name + " ignored other side -- update: left=" + update.Body.LeftDistance + " right=" + update.Body.RightDistance); #endif // TRACEDEBUGTICKS // addressed to the other side encoder, ignore it return; } #if TRACEDEBUGTICKS LogInfo("TrackRoamerEncoder:MotorEncoderNotificationHandler() " + Name + " got update: left=" + update.Body.LeftDistance + " right=" + update.Body.RightDistance); #endif // TRACEDEBUGTICKS bool changed = false; int val = 0; double dval = 0.0d; double dabs = 0.0d; if (_state.HardwareIdentifier == 1 && update.Body.LeftDistance != null) { lock (m_lastResetTicksLock) { // Generic Drive operates on positive tick counter values dabs = (double)update.Body.LeftDistance; if (m_lastResetTicks == null) { m_lastResetTicks = dabs; } else { dval = Math.Abs(dabs - (double)m_lastResetTicks); val = (int)dval; } changed = _state.TicksSinceReset != val; #if TRACEDEBUGTICKS //LogInfo("TrackRoamerEncoder:MotorEncoderNotificationHandler() -- left: " + _state.TicksSinceReset + " --> " + val + " (" + update.Body.LeftDistance + ")"); #endif // TRACEDEBUGTICKS } } if (_state.HardwareIdentifier == 2 && update.Body.RightDistance != null) { lock (m_lastResetTicksLock) { // Generic Drive operates on positive tick counter values dabs = (double)update.Body.RightDistance; if (m_lastResetTicks == null) { m_lastResetTicks = dabs; } else { dval = Math.Abs(dabs - (double)m_lastResetTicks); val = (int)dval; } changed = _state.TicksSinceReset != val; #if TRACEDEBUGTICKS //LogInfo("TrackRoamerEncoder:MotorEncoderNotificationHandler() -- right: " + _state.TicksSinceReset + " --> " + val + " (" + update.Body.RightDistance + ")"); #endif // TRACEDEBUGTICKS } } if (changed) { //LogInfo("TrackRoamerEncoder:MotorEncoderNotificationHandler() -- " // + (_state.HardwareIdentifier == 1 ? " left: " : "right: ") // + _state.TicksSinceReset + " --> " + val + " (" + dabs + ")"); _state.TicksSinceReset = val; _state.CurrentReading = val; _state.CurrentAngle = val * 2.0d * Math.PI / _state.TicksPerRevolution; //update time _state.TimeStamp = DateTime.Now; this.SendNotification<pxencoder.UpdateTickCount>(_subMgrPort, new pxencoder.UpdateTickCountRequest(_state.TimeStamp, _state.TicksSinceReset)); } //update.ResponsePort.Post(DefaultUpdateResponseType.Instance); } /// <summary> /// Get Handler /// </summary> /// <param name="get"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Concurrent)] public IEnumerator<ITask> GetHandler(pxencoder.Get get) { get.ResponsePort.Post(_state); yield break; } /// <summary> /// HttpGet Handler /// </summary> /// <param name="httpGet"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Concurrent)] public IEnumerator<ITask> HttpGetHandler(HttpGet httpGet) { httpGet.ResponsePort.Post(new HttpResponseType( HttpStatusCode.OK, _state, _transform) ); yield break; } /// <summary> /// Reset Handler /// </summary> /// <param name="reset"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public IEnumerator<ITask> ResetHandler(pxencoder.Reset update) { LogInfo("TrackRoamerEncoder : ResetHandler() m_lastResetTicks=" + m_lastResetTicks); // reset physical counter in the bot AX2850 controller: //trackroamerbot.ResetMotorEncoder resetMotorEncoder = new trackroamerbot.ResetMotorEncoder(); //resetMotorEncoder.Body.HardwareIdentifier = _state.HardwareIdentifier; //_trackroamerbotPort.Post(resetMotorEncoder); // initialize our local logical counter: lock (m_lastResetTicksLock) { _state.TicksSinceReset = 0; _state.CurrentReading = 0; _state.CurrentAngle = 0.0d; m_lastResetTicks = null; } update.ResponsePort.Post(DefaultUpdateResponseType.Instance); yield break; } /// <summary> /// Replace Handler /// </summary> /// <param name="replace"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public IEnumerator<ITask> ReplaceHandler(pxencoder.Replace replace) { //LogInfo("TrackRoamerEncoder : ReplaceHandler()"); if (_subscribed) { LogError("TrackRoamerEncoder : ReplaceHandler(): Already subscribed"); } else if (ValidState(replace.Body)) { //_state = (TREncoderState)replace.Body; _state = replace.Body; SaveState(_state); replace.ResponsePort.Post(DefaultReplaceResponseType.Instance); SubscribeToPowerBrick(); } else { LogError("TrackRoamerEncoder : ReplaceHandler(): Invalid State for replacement"); } yield break; } [ServiceHandler(ServiceHandlerBehavior.Teardown)] public virtual IEnumerator<ITask> DropHandler(DsspDefaultDrop drop) { LogInfo("TrackRoamerEncoder:DropHandler()"); base.DefaultDropHandler(drop); yield break; } #region Subscriptions /// <summary> /// Subcribe Handler /// </summary> /// <param name="subscribe"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public IEnumerator<ITask> SubscribeHandler(pxencoder.Subscribe subscribe) { LogInfo("TrackRoamerEncoder " + _state.HardwareIdentifier + " received Subscription request from Subscriber=" + subscribe.Body.Subscriber); yield return Arbiter.Choice( SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort), delegate(SuccessResult success) { LogInfo("TrackRoamerEncoder : Subscription granted (succeeded) subscriber: " + subscribe.Body.Subscriber); //_subMgrPort.Post(new submgr.Submit(subscribe.Body.Subscriber, DsspActions.ReplaceRequest, _state, null)); }, delegate(Exception fault) { LogError(fault); } ); } /// <summary> /// Reliable Subscribe Handler /// </summary> /// <param name="subscribe"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public IEnumerator<ITask> ReliableSubscribeHandler(pxencoder.ReliableSubscribe subscribe) { LogInfo("TrackRoamerEncoder " + _state.HardwareIdentifier + " received Reliable Subscription request from Subscriber=" + subscribe.Body.Subscriber); yield return Arbiter.Choice( SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort), delegate(SuccessResult success) { LogInfo("TrackRoamerEncoder : Reliable Subscription granted (succeeded) subscriber: " + subscribe.Body.Subscriber); //_subMgrPort.Post(new submgr.Submit(subscribe.Body.Subscriber, DsspActions.ReplaceRequest, _state, null)); }, delegate(Exception fault) { LogError(fault); } ); } #endregion #if TRACEDEBUG protected new void LogInfo(string str) { Tracer.Trace(str); } protected new void LogError(string str) { Tracer.Error(str); } #endif // TRACEDEBUG } }
// 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; /// <summary> /// DeploymentOperations operations. /// </summary> internal partial class DeploymentOperations : Microsoft.Rest.IServiceOperations<ResourceManagementClient>, IDeploymentOperations { /// <summary> /// Initializes a new instance of the DeploymentOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DeploymentOperations(ResourceManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the ResourceManagementClient /// </summary> public ResourceManagementClient Client { get; private set; } /// <summary> /// Gets a deployments operation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='operationId'> /// The ID of the operation to get. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentOperation>> GetWithHttpMessagesAsync(string resourceGroupName, string deploymentName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (deploymentName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "deploymentName"); } if (deploymentName != null) { if (deploymentName.Length > 64) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "deploymentName", 64); } if (deploymentName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "deploymentName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(deploymentName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "deploymentName", "^[-\\w\\._\\(\\)]+$"); } } if (operationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "operationId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations/{operationId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", System.Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<DeploymentOperation>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DeploymentOperation>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all deployments operations for a deployment. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment with the operation to get. /// </param> /// <param name='top'> /// The number of results to return. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentOperation>>> ListWithHttpMessagesAsync(string resourceGroupName, string deploymentName, int? top = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (deploymentName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "deploymentName"); } if (deploymentName != null) { if (deploymentName.Length > 64) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "deploymentName", 64); } if (deploymentName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "deploymentName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(deploymentName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "deploymentName", "^[-\\w\\._\\(\\)]+$"); } } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("top", top); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", System.Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (top != null) { _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, this.Client.SerializationSettings).Trim('"')))); } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentOperation>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<DeploymentOperation>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all deployments operations for a deployment. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentOperation>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentOperation>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<DeploymentOperation>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//------------------------------------------------------------------------------ // <copyright file="DynamicScriptObject.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: // Enables scripting support against the HTML DOM for XBAPs using the DLR // dynamic feature, as available through the dynamic keyword in C# 4.0 and // also supported in Visual Basic. // // History // 04/29/09 [....] Created // 06/30/09 [....] Changed to use IDispatchEx where possible //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Dynamic; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Windows; using MS.Internal.Interop; using MS.Win32; namespace System.Windows.Interop { /// <summary> /// Enables scripting support against the HTML DOM for XBAPs using the DLR. /// </summary> /// <SecurityNote> /// Instances of this type are directly exposed to partial-trust code through BrowserInteropHelper's /// HostScript property as an entry-point, and subsequently as a result of making dynamic calls on it /// causing wrapping in new instances of this type. All public methods on this type are used by the /// DLR to dispatch dynamic calls. The extent of the security measure taken here is to ensure that /// objects that get wrapped in DynamicScriptObject are safe for scripting, so all operations on them /// are deemed safe as well. /// This class needs to be public in order to make DLR accept it in partial trust. Making it internal /// causes failure followed by fallback to the default binders. Security-wise this should be fine as /// the wrapped script object is protected as SecurityCritical and only settable via the constructor, /// and therefore attempts to call any of the Try* methods with custom binder objects are fine as no /// calls can be made on an untrusted object. /// </SecurityNote> public sealed class DynamicScriptObject : DynamicObject { //---------------------------------------------- // // Constructors // //---------------------------------------------- #region Constructor /// <summary> /// Wraps the given object in a script object for "dynamic" access. /// </summary> /// <param name="scriptObject">Object to be wrapped.</param> /// <SecurityNote> /// Critical - Sets the critical _scriptObject field. It's the responsibility of the caller /// to ensure the object passed in is safe for scripting. We assume a closed world /// OM where everything returned from an object that's safe for scripting is still /// safe for scripting. This knowledge is used in wrapping returned objects in a /// DynamicScriptObject upon return of a dynamic IDispatch-based call. /// </SecurityNote> [SecurityCritical] internal DynamicScriptObject(UnsafeNativeMethods.IDispatch scriptObject) { if (scriptObject == null) { throw new ArgumentNullException("scriptObject"); } _scriptObject = scriptObject; // In the case of IE, we use IDispatchEx for enhanced security (see InvokeOnScriptObject). _scriptObjectEx = _scriptObject as UnsafeNativeMethods.IDispatchEx; } #endregion Constructor //---------------------------------------------- // // Public Methods // //---------------------------------------------- #region Public Methods /// <summary> /// Calls a script method. Corresponds to methods calls in the front-end language. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="args">The arguments to be used for the invocation.</param> /// <param name="result">The result of the invocation.</param> /// <returns>true - We never defer behavior to the call site, and throw if invalid access is attempted.</returns> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (binder == null) { throw new ArgumentNullException("binder"); } result = InvokeAndReturn(binder.Name, NativeMethods.DISPATCH_METHOD, args); return true; } /// <summary> /// Gets a member from script. Corresponds to property getter syntax in the front-end language. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="result">The result of the invocation.</param> /// <returns>true - We never defer behavior to the call site, and throw if invalid access is attempted.</returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { if (binder == null) { throw new ArgumentNullException("binder"); } result = InvokeAndReturn(binder.Name, NativeMethods.DISPATCH_PROPERTYGET, null); return true; } /// <summary> /// Sets a member in script. Corresponds to property setter syntax in the front-end language. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="value">The value to set.</param> /// <returns>true - We never defer behavior to the call site, and throw if invalid access is attempted.</returns> public override bool TrySetMember(SetMemberBinder binder, object value) { if (binder == null) { throw new ArgumentNullException("binder"); } int flags = GetPropertyPutMethod(value); object result = InvokeAndReturn(binder.Name, flags, new object[] { value }); return true; } /// <summary> /// Gets an indexed value from script. Corresponds to indexer getter syntax in the front-end language. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="indexes">The indexes to be used.</param> /// <param name="result">The result of the invocation.</param> /// <returns>true - We never defer behavior to the call site, and throw if invalid access is attempted.</returns> public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { if (binder == null) { throw new ArgumentNullException("binder"); } if (indexes == null) { throw new ArgumentNullException("indexes"); } // IE supports a default member for indexers. Try that first. This accommodates for indexing // in collection types, using a default method called "item". if (BrowserInteropHelper.IsHostedInIEorWebOC) { if (TryFindMemberAndInvoke(null, NativeMethods.DISPATCH_METHOD, false /* no DISPID caching */, indexes, out result)) { return true; } } // We fall back to property lookup given the first argument of the indices. This accommodates // for arrays (e.g. d.x[0]) and square-bracket-style property lookup (e.g. d.document["title"]). if (indexes.Length != 1) { throw new ArgumentException("indexes", HRESULT.DISP_E_BADPARAMCOUNT.GetException()); } object index = indexes[0]; if (index == null) { throw new ArgumentOutOfRangeException("indexes"); } result = InvokeAndReturn(index.ToString(), NativeMethods.DISPATCH_PROPERTYGET, false /* no DISPID caching */, null); return true; } /// <summary> /// Sets a member in script, through an indexer. Corresponds to indexer setter syntax in the front-end language. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="indexes">The indexes to be used.</param> /// <param name="value">The value to set.</param> /// <returns>true - We never defer behavior to the call site, and throw if invalid access is attempted.</returns> public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) { if (binder == null) { throw new ArgumentNullException("binder"); } if (indexes == null) { throw new ArgumentNullException("indexes"); } if (indexes.Length != 1) { throw new ArgumentException("indexes", HRESULT.DISP_E_BADPARAMCOUNT.GetException()); } object index = indexes[0]; if (index == null) { throw new ArgumentOutOfRangeException("indexes"); } // We don't cache resolved DISPIDs for indexers as they have the potential to be used for dynamic resolution // of a bunch of members, e.g. when indexing into arrays. This would flood the cache, likely for just a one- // time access. So we just don't cache in this case. object result = InvokeAndReturn(index.ToString(), NativeMethods.DISPATCH_PROPERTYPUT, false /* no DISPID caching */, new object[] { value }); return true; } /// <summary> /// Calls the default script method. Corresponds to delegate calling syntax in the front-end language. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="args">The arguments to be used for the invocation.</param> /// <param name="result">The result of the invocation.</param> /// <returns>true - We never defer behavior to the call site, and throw if invalid access is attempted.</returns> public override bool TryInvoke(InvokeBinder binder, object[] args, out object result) { if (binder == null) { throw new ArgumentNullException("binder"); } result = InvokeAndReturn(null, NativeMethods.DISPATCH_METHOD, args); return true; } /// <summary> /// Provides a string representation of the wrapped script object. /// </summary> /// <returns>String representation of the wrapped script object, using the toString method or default member on the script object.</returns> public override string ToString() { // Note we shouldn't throw in this method (rule CA1065), so we try with best attempt. HRESULT hr; Guid guid = Guid.Empty; object result = null; var dp = new NativeMethods.DISPPARAMS(); // Try to find a toString method. int dispid; if (TryGetDispIdForMember("toString", true /* DISPID caching */, out dispid)) { hr = InvokeOnScriptObject(dispid, NativeMethods.DISPATCH_METHOD, dp, null /* EXCEPINFO */, out result); } else { // If no toString method is found, we try the default member first as a property, then as a method. dispid = NativeMethods.DISPID_VALUE; hr = InvokeOnScriptObject(dispid, NativeMethods.DISPATCH_PROPERTYGET, dp, null /* EXCEPINFO */, out result); if (hr.Failed) { hr = InvokeOnScriptObject(dispid, NativeMethods.DISPATCH_METHOD, dp, null /* EXCEPINFO */, out result); } } if (hr.Succeeded && result != null) { return result.ToString(); } return base.ToString(); } #endregion Public Methods //---------------------------------------------- // // Internal Properties // //---------------------------------------------- #region Internal Properties /// <summary> /// Gets the IDispatch script object wrapped by the DynamicScriptObject. /// </summary> /// <SecurityNote> /// Critical - Accesses the critical _scriptObject field. /// TreatAsSafe - Though the IDispatch object per se is not necessarily safe for scripting, it has /// necessary protections built-in on the browser side. The more relevant reason for /// marking this as TAS is that invocations of members on the IDispatch interface /// required unmanaged code permissions anyway. /// </SecurityNote> internal UnsafeNativeMethods.IDispatch ScriptObject { [SecurityCritical, SecurityTreatAsSafe] get { return _scriptObject; } } #endregion Internal Properties //---------------------------------------------- // // Internal Methods // //---------------------------------------------- #region Internal Methods /// <summary> /// Helper method to attempt invoking a script member with the given name, flags and arguments. /// </summary> /// <param name="memberName">The name of the member to invoke.</param> /// <param name="flags">One of the DISPATCH_ flags for IDispatch calls.</param> /// <param name="cacheDispId">true to enable caching of DISPIDs; false otherwise.</param> /// <param name="args">Arguments passed to the call.</param> /// <param name="result">The raw (not wrapped in DynamicScriptObject) result of the invocation.</param> /// <returns>true if the member was found; false otherwise.</returns> /// <SecurityNote> /// Critical - Unpacks the critical _scriptObject field on DynamicScriptObject arguments. /// TreatAsSafe - Objects returned from script are considered safe for scripting. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal unsafe bool TryFindMemberAndInvokeNonWrapped(string memberName, int flags, bool cacheDispId, object[] args, out object result) { result = null; // In true DLR style we'd return false here, deferring further attempts for resolution to the // call site. For better debuggability though, and as we're talking to a specialized object // model, we rather throw instead. This Try-method allows internal lookups without directly // throwing on non-fatal "member not found" situations, as we might want to have more complex // fallback logic (as in ToString). int dispid; if (!TryGetDispIdForMember(memberName, cacheDispId, out dispid)) { return false; } NativeMethods.DISPPARAMS dp = new NativeMethods.DISPPARAMS(); // Required additional DISPPARAMS arguments for PROPERTYPUT cases. See IDispatch::Invoke // documentation for more info. int propertyPutDispId = NativeMethods.DISPID_PROPERTYPUT; if (flags == NativeMethods.DISPATCH_PROPERTYPUT || flags == NativeMethods.DISPATCH_PROPERTYPUTREF) { dp.cNamedArgs = 1; // Stack allocated variables are fixed (unmoveable), so no need to use a fixed // statement. The local variable should not get repurposed by the compiler in an // unsafe block as we're handing out a pointer to it. For comparison, see the DLR // code, CorRuntimeHelpers.cs, where the ConvertInt32ByrefToPtr function relies // on the same behavior as they take an IntPtr to a stack-allocated variable that // gets used by a DISPPARAMS in a similar way. They have a separate method likely // because expression trees can't deal with unsafe code, and they need to fix as // they use a by-ref argument which is considered movable (see C# spec, 18.3): // // public static unsafe IntPtr ConvertInt32ByrefToPtr(ref Int32 value) { // fixed (Int32 *x = &value) { // AssertByrefPointsToStack(new IntPtr(x)); // return new IntPtr(x); // } // } dp.rgdispidNamedArgs = new IntPtr(&propertyPutDispId); } try { if (args != null) { // Callers of this method might want to implement fallbacks that require the original // arguments in the original order, maybe to feed it in to this method again. If we // wouldn't clone the arguments array into a local copy, we'd be reversing again. args = (object[])args.Clone(); // Reverse the argument order so that parameters read naturally after IDispatch. // This code was initially ported from [....], see [....] bug 187662. Array.Reverse(args); // Unwrap arguments that were already promoted to DynamicScriptObject. This can happen // if the output of a script accessing method is fed in to the input of another one. for (int i = 0; i < args.Length; i++) { var wrappedArg = args[i] as DynamicScriptObject; if (wrappedArg != null) { args[i] = wrappedArg._scriptObject; } if (args[i] != null) { // Arrays of COM visible objects (in our definition of the word, see further) are // not considered COM visible by themselves, so we take care of this case as well. // Jagged arrays are not supported somehow, causing a SafeArrayTypeMismatchException // in the call to GetNativeVariantForObject on ArrayToVARIANTVector called below. // Multi-dimensional arrays turn out to work fine, so we don't opt out from those. Type argType = args[i].GetType(); if (argType.IsArray) { argType = argType.GetElementType(); } // Caveat: IsTypeVisibleFromCom evaluates false for COM object wrappers provided // by the CLR. Therefore we also check for the IsCOMObject property. It also seems // COM interop special-cases DateTime as it's not revealed to be visible by any // of the first two checks below. if (!Marshal.IsTypeVisibleFromCom(argType) && !argType.IsCOMObject && argType != typeof(DateTime)) { throw new ArgumentException(SR.Get(SRID.NeedToBeComVisible)); } } } dp.rgvarg = UnsafeNativeMethods.ArrayToVARIANTHelper.ArrayToVARIANTVector(args); dp.cArgs = (uint)args.Length; } NativeMethods.EXCEPINFO exInfo = new NativeMethods.EXCEPINFO(); HRESULT hr = InvokeOnScriptObject(dispid, flags, dp, exInfo, out result); if (hr.Failed) { if (hr == HRESULT.DISP_E_MEMBERNOTFOUND) { return false; } // See KB article 247784, INFO: '80020101' Returned From Some ActiveX Scripting Methods. // Internet Explorer returns this error when it has already reported a script error to the user // through a dialog or by putting a message in the status bar (Page contains script error). We // want consistency between browsers, so route this through the DISP_E_EXCEPTION case. if (hr == HRESULT.SCRIPT_E_REPORTED) { exInfo.scode = hr.Code; hr = HRESULT.DISP_E_EXCEPTION; } // We prefix exception messagages with "[memberName]" so that the target of the invocation can // be found easily. This is useful beyond just seeing the call site in the debugger as dynamic // calls lead to complicated call stacks with the DLR sliced in between the source and target. // Also, for good or for bad, dynamic has the potential to encourage endless "dotting into", so // it's preferrable to have our runtime resolution failure eloquating the target of the dynamic // call. Unfortunately stock CLR exception types often don't offer a convenient spot to put // this info in, so we resort to the Message property. Anyway, those exceptions are primarily // meant to provide debugging convenience and should not be reported to the end-user in a well- // tested application. Essentially all of this is to be conceived as "deferred compilation". string member = "[" + (memberName ?? "(default)") + "]"; Exception comException = hr.GetException(); if (hr == HRESULT.DISP_E_EXCEPTION) { // We wrap script execution failures in TargetInvocationException to keep the API surface // free of COMExceptions that reflect a mere implementation detail. int errorCode = exInfo.scode != 0 ? exInfo.scode : exInfo.wCode; hr = HRESULT.Make(true /* severity */, Facility.Dispatch, errorCode); string message = member + " " + (exInfo.bstrDescription ?? string.Empty); throw new TargetInvocationException(message, comException) { HelpLink = exInfo.bstrHelpFile, Source = exInfo.bstrSource }; } else if (hr == HRESULT.DISP_E_BADPARAMCOUNT || hr == HRESULT.DISP_E_PARAMNOTOPTIONAL) { throw new TargetParameterCountException(member, comException); } else if (hr == HRESULT.DISP_E_OVERFLOW || hr == HRESULT.DISP_E_TYPEMISMATCH) { throw new ArgumentException(member, new InvalidCastException(comException.Message, hr.Code)); } else { // Something really bad has happened; keeping the exception as-is. throw comException; } } } finally { if (dp.rgvarg != IntPtr.Zero) { UnsafeNativeMethods.ArrayToVARIANTHelper.FreeVARIANTVector(dp.rgvarg, args.Length); } } return true; } #endregion Internal Methods //---------------------------------------------- // // Private Methods // //---------------------------------------------- #region Private Methods /// <summary> /// Helper method to invoke a script member with the given name, flags and arguments. /// This overload always caches resolved DISPIDs. /// </summary> /// <param name="memberName">The name of the member to invoke.</param> /// <param name="flags">One of the DISPATCH_ flags for IDispatch calls.</param> /// <param name="args">Arguments passed to the call.</param> /// <returns>The result of the invocation.</returns> private object InvokeAndReturn(string memberName, int flags, object[] args) { return InvokeAndReturn(memberName, flags, true /* DISPID caching */, args); } /// <summary> /// Helper method to invoke a script member with the given name, flags and arguments. /// This overload allows control over the resolved DISPIDs caching behavior. /// </summary> /// <param name="memberName">The name of the member to invoke.</param> /// <param name="flags">One of the DISPATCH_ flags for IDispatch calls.</param> /// <param name="cacheDispId">true to enable caching of DISPIDs; false otherwise.</param> /// <param name="args">Arguments passed to the call.</param> /// <returns>The result of the invocation.</returns> private object InvokeAndReturn(string memberName, int flags, bool cacheDispId, object[] args) { object result; if (!TryFindMemberAndInvoke(memberName, flags, cacheDispId, args, out result)) { if (flags == NativeMethods.DISPATCH_METHOD) throw new MissingMethodException(this.ToString(), memberName); else throw new MissingMemberException(this.ToString(), memberName); } return result; } /// <summary> /// Helper method to attempt invoking a script member with the given name, flags and arguments. /// Wraps the result value in a DynamicScriptObject if required. /// </summary> /// <param name="memberName">The name of the member to invoke.</param> /// <param name="flags">One of the DISPATCH_ flags for IDispatch calls.</param> /// <param name="cacheDispId">true to enable caching of DISPIDs; false otherwise.</param> /// <param name="args">Arguments passed to the call.</param> /// <param name="result">The result of the invocation, wrapped in DynamicScriptObject if required.</param> /// <returns>true if the member was found; false otherwise.</returns> /// <SecurityNote> /// Critical - Calls the DynamicScriptObject constructor. /// TreatAsSafe - Objects promoted into DynamicScriptObject are considered safe for scripting. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private bool TryFindMemberAndInvoke(string memberName, int flags, bool cacheDispId, object[] args, out object result) { if (!TryFindMemberAndInvokeNonWrapped(memberName, flags, cacheDispId, args, out result)) { return false; } // Only wrap returned COM objects; if the object returns as a CLR object, we just return it. if (result != null && Marshal.IsComObject(result)) { // Script objects implement IDispatch. result = new DynamicScriptObject((UnsafeNativeMethods.IDispatch)result); } return true; } /// <summary> /// Helper method to map a script member with the given name onto a DISPID. /// </summary> /// <param name="memberName">The name of the member to look up.</param> /// <param name="cacheDispId">true to enable caching of DISPIDs; false otherwise.</param> /// <param name="dispid">If the member was found, its DISPID; otherwise, default DISPID_VALUE.</param> /// <returns>true if the member was found; false if it wasn't (DISP_E_UNKNOWNNAME).</returns> /// <SecurityNote> /// Critical - Invokes code on the critical _scriptObject field. /// TreatAsSafe - Objects promoted into DynamicScriptObject are considered safe for scripting. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private bool TryGetDispIdForMember(string memberName, bool cacheDispId, out int dispid) { dispid = NativeMethods.DISPID_VALUE; if (!string.IsNullOrEmpty(memberName)) { if ( !cacheDispId /* short-circuit lookup; will never get cached */ || !_dispIdCache.TryGetValue(memberName, out dispid)) { Guid guid = Guid.Empty; string[] names = new string[] { memberName }; int[] dispids = new int[] { NativeMethods.DISPID_UNKNOWN }; // Only the "member not found" case deserves special treatment. We leave it up to the // caller to decide on the right treatment. HRESULT hr = _scriptObject.GetIDsOfNames(ref guid, names, dispids.Length, Thread.CurrentThread.CurrentCulture.LCID, dispids); if (hr == HRESULT.DISP_E_UNKNOWNNAME) { return false; } // Fatal unexpected exception here; it's fine to leak a COMException to the surface. hr.ThrowIfFailed(); dispid = dispids[0]; if (cacheDispId) { _dispIdCache[memberName] = dispid; } } } return true; } /// <SecurityNote> /// Critical - Invokes code on the critical _scriptObject field. /// TreatAsSafe - Objects promoted into DynamicScriptObject are considered safe for scripting. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private HRESULT InvokeOnScriptObject(int dispid, int flags, NativeMethods.DISPPARAMS dp, NativeMethods.EXCEPINFO exInfo, out object result) { // If we use reflection to call script code, we need to Assert for the UnmanagedCode permission. // But it will be a security issue when the WPF app makes a framework object available to the // hosted script via ObjectForScripting or as parameter of InvokeScript, and calls the framework // API that demands the UnmanagedCode permission. We do not want the demand to succeed. However, // the stack walk will ignore the native frames and keeps going until it reaches the Assert. // // As an example, if a call to a script object causes an immediate callback before the initial // call returns, reentrancy occurs via COM's blocking message loop on outgoing calls: // // [managed ComVisible object] // [CLR COM interop] // [COM runtime] // ole32.dll!CCliModalLoop::BlockFn() // ole32.dll!ModalLoop() // [COM runtime] // PresentationFramework!DynamicScriptObject::InvokeScript(...) // // That is why we switch to invoking the script via IDispatch with SUCS on the methods. if (_scriptObjectEx != null) { // This case takes care of IE hosting where the use of IDispatchEx is recommended by IE people // since the service provider object we can pass here is used by the browser to enforce cross- // zone scripting mitigations. See Dev10 work item 710325 for more information. return _scriptObjectEx.InvokeEx(dispid, Thread.CurrentThread.CurrentCulture.LCID, flags, dp, out result, exInfo, BrowserInteropHelper.HostHtmlDocumentServiceProvider); } else { Guid guid = Guid.Empty; return _scriptObject.Invoke(dispid, ref guid, Thread.CurrentThread.CurrentCulture.LCID, flags, dp, out result, exInfo, null); } } /// <summary> /// Helper function to get the IDispatch::Invoke invocation method for setting a property. /// </summary> /// <param name="value">Object to be assigned to the property.</param> /// <returns>DISPATCH_PROPERTYPUTREF or DISPATCH_PROPERTYPUT</returns> private static int GetPropertyPutMethod(object value) { // TFS DD Dev10 787708 - On the top-level script scope, setting a variable of a reference // type without using the DISPATCH_PROPERTYPUTREF flag doesn't work since it causes the // default member to be invoked as part of the conversion of the reference to a "value". // It seems this didn't affect DOM property setters where the IDispatch implementation is // more relaxed about the use of PUTREF versus PUT. This code is pretty much analog to // the DLR's COM binder's; see ndp\fx\src\Dynamic\System\Dynamic\ComBinderHelpers.cs for // further information. if (value == null) { return NativeMethods.DISPATCH_PROPERTYPUTREF; } Type type = value.GetType(); if ( type.IsValueType || type.IsArray || type == typeof(string) || type == typeof(CurrencyWrapper) || type == typeof(DBNull) || type == typeof(Missing)) { return NativeMethods.DISPATCH_PROPERTYPUT; } else { return NativeMethods.DISPATCH_PROPERTYPUTREF; } } #endregion Private Methods //---------------------------------------------- // // Private Fields // //---------------------------------------------- #region Private Fields /// <summary> /// Script object to invoke operations on through the "dynamic" feature. /// </summary> /// <SecurityNote> /// Critical - Can be used to script against untrusted objects that are not safe for scripting. /// If setting this field to an arbitrary value were possible, dynamic calls against /// the DynamicScriptObject instance would dispatch against objects that could be /// unsafe for scripting. /// </SecurityNote> [SecurityCritical] private UnsafeNativeMethods.IDispatch _scriptObject; /// <summary> /// Script object to invoke operations on through the "dynamic" feature. /// Used in the case of IE, where IDispatchEx is used to tighten security (see InvokeOnScriptObject). /// </summary> /// <SecurityNote> /// Same as for _scriptObject field. /// </SecurityNote> [SecurityCritical] private UnsafeNativeMethods.IDispatchEx _scriptObjectEx; /// <summary> /// Cache of DISPID values for members. Allows to speed up repeated calls. /// </summary> private Dictionary<string, int> _dispIdCache = new Dictionary<string, int>(); #endregion Private Fields } }
// 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.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { /// <summary> /// Async thin tagger implementation. /// /// Actual tag information is stored in TagSource and shared between multiple taggers created for same views or buffers. /// /// It's responsibility is on interfaction between host and tagger. TagSource has responsibility on how to provide information for this tagger. /// </summary> internal sealed partial class AsynchronousTagger<TTag> : ITagger<TTag>, IDisposable where TTag : ITag { private const int MaxNumberOfRequestedSpans = 100; #region Fields that can be accessed from either thread private readonly ITextBuffer _subjectBuffer; private readonly TagSource<TTag> _tagSource; private readonly int _uiUpdateDelayInMS; #endregion #region Fields that can only be accessed from the foreground thread /// <summary> /// The batch change notifier that we use to throttle update to the UI. /// </summary> private readonly BatchChangeNotifier _batchChangeNotifier; #endregion public event EventHandler<SnapshotSpanEventArgs> TagsChanged; public AsynchronousTagger( IAsynchronousOperationListener listener, IForegroundNotificationService notificationService, TagSource<TTag> tagSource, ITextBuffer subjectBuffer, TimeSpan uiUpdateDelay) { Contract.ThrowIfNull(subjectBuffer); _subjectBuffer = subjectBuffer; _uiUpdateDelayInMS = (int)uiUpdateDelay.TotalMilliseconds; _batchChangeNotifier = new BatchChangeNotifier(subjectBuffer, listener, notificationService, ReportChangedSpan); _tagSource = tagSource; _tagSource.OnTaggerAdded(this); _tagSource.TagsChangedForBuffer += OnTagsChangedForBuffer; _tagSource.Paused += OnPaused; _tagSource.Resumed += OnResumed; } public void Dispose() { _tagSource.Resumed -= OnResumed; _tagSource.Paused -= OnPaused; _tagSource.TagsChangedForBuffer -= OnTagsChangedForBuffer; _tagSource.OnTaggerDisposed(this); } private void ReportChangedSpan(SnapshotSpan changeSpan) { var tagsChanged = TagsChanged; if (tagsChanged != null) { tagsChanged(this, new SnapshotSpanEventArgs(changeSpan)); } } private void OnPaused(object sender, EventArgs e) { _batchChangeNotifier.Pause(); } private void OnResumed(object sender, EventArgs e) { _batchChangeNotifier.Resume(); } private void OnTagsChangedForBuffer(object sender, TagsChangedForBufferEventArgs args) { if (args.Buffer != _subjectBuffer) { return; } // Note: This operation is uncancellable. Once we've been notified here, our cached tags // in the tag source are new. If we don't update the UI of the editor then we will end // up in an inconsistent state between us and the editor where we have new tags but the // editor will never know. var spansChanged = args.Spans; _tagSource.RegisterNotification(() => { _tagSource.WorkQueue.AssertIsForeground(); // Now report them back to the UI on the main thread. _batchChangeNotifier.EnqueueChanges(spansChanged.First().Snapshot, spansChanged); }, _uiUpdateDelayInMS, CancellationToken.None); } public IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection requestedSpans) { if (requestedSpans.Count == 0) { return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } var buffer = requestedSpans.First().Snapshot.TextBuffer; var tags = _tagSource.GetTagIntervalTreeForBuffer(buffer); if (tags == null) { return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } var result = GetTags(requestedSpans, tags); DebugVerifyTags(requestedSpans, result); return result; } private static IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection requestedSpans, ITagSpanIntervalTree<TTag> tags) { // Special case the case where there is only one requested span. In that case, we don't // need to allocate any intermediate collections return requestedSpans.Count == 1 ? tags.GetIntersectingSpans(requestedSpans[0]) : requestedSpans.Count < MaxNumberOfRequestedSpans ? GetTagsForSmallNumberOfSpans(requestedSpans, tags) : GetTagsForLargeNumberOfSpans(requestedSpans, tags); } private static IEnumerable<ITagSpan<TTag>> GetTagsForSmallNumberOfSpans( NormalizedSnapshotSpanCollection requestedSpans, ITagSpanIntervalTree<TTag> tags) { var result = new List<ITagSpan<TTag>>(); foreach (var s in requestedSpans) { result.AddRange(tags.GetIntersectingSpans(s)); } return result; } private static IEnumerable<ITagSpan<TTag>> GetTagsForLargeNumberOfSpans( NormalizedSnapshotSpanCollection requestedSpans, ITagSpanIntervalTree<TTag> tags) { // we are asked with bunch of spans. rather than asking same question again and again, ask once with big span // which will return superset of what we want. and then filter them out in O(m+n) cost. // m == number of requested spans, n = number of returned spans var mergedSpan = new SnapshotSpan(requestedSpans[0].Start, requestedSpans[requestedSpans.Count - 1].End); var result = tags.GetIntersectingSpans(mergedSpan); int requestIndex = 0; var enumerator = result.GetEnumerator(); try { if (!enumerator.MoveNext()) { return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } var hashSet = new HashSet<ITagSpan<TTag>>(); while (true) { var currentTag = enumerator.Current; var currentRequestSpan = requestedSpans[requestIndex]; var currentTagSpan = currentTag.Span; if (currentRequestSpan.Start > currentTagSpan.End) { if (!enumerator.MoveNext()) { break; } } else if (currentTagSpan.Start > currentRequestSpan.End) { requestIndex++; if (requestIndex >= requestedSpans.Count) { break; } } else { if (currentTagSpan.Length > 0) { hashSet.Add(currentTag); } if (!enumerator.MoveNext()) { break; } } } return hashSet; } finally { enumerator.Dispose(); } } [Conditional("DEBUG")] private static void DebugVerifyTags(NormalizedSnapshotSpanCollection requestedSpans, IEnumerable<ITagSpan<TTag>> tags) { if (tags == null) { return; } foreach (var tag in tags) { var span = tag.Span; if (!requestedSpans.Any(s => s.IntersectsWith(span))) { Contract.Fail(tag + " doesn't intersects with any requested span"); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using System; using System.Collections.Generic; using System.Reflection; using System.Xml; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.Framework.Scenes { public partial class SceneObjectGroup : EntityBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Force all task inventories of prims in the scene object to persist /// </summary> public void ForceInventoryPersistence() { SceneObjectPart[] parts = m_parts.GetArray(); for (int i = 0; i < parts.Length; i++) parts[i].Inventory.ForceInventoryPersistence(); } /// <summary> /// Start the scripts contained in all the prims in this group. /// </summary> /// <param name="startParam"></param> /// <param name="postOnRez"></param> /// <param name="engine"></param> /// <param name="stateSource"></param> /// <returns> /// Number of scripts that were valid for starting. This does not guarantee that all these scripts /// were actually started, but just that the start could be attempt (e.g. the asset data for the script could be found) /// </returns> public int CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource) { int scriptsStarted = 0; if (m_scene == null) { m_log.DebugFormat("[PRIM INVENTORY]: m_scene is null. Unable to create script instances"); return 0; } // Don't start scripts if they're turned off in the region! if (!m_scene.RegionInfo.RegionSettings.DisableScripts) { SceneObjectPart[] parts = m_parts.GetArray(); for (int i = 0; i < parts.Length; i++) scriptsStarted += parts[i].Inventory.CreateScriptInstances(startParam, postOnRez, engine, stateSource); } return scriptsStarted; } /// <summary> /// Stop and remove the scripts contained in all the prims in this group /// </summary> /// <param name="sceneObjectBeingDeleted"> /// Should be true if these scripts are being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstances(bool sceneObjectBeingDeleted) { SceneObjectPart[] parts = m_parts.GetArray(); for (int i = 0; i < parts.Length; i++) parts[i].Inventory.RemoveScriptInstances(sceneObjectBeingDeleted); } /// <summary> /// Stop the scripts contained in all the prims in this group /// </summary> public void StopScriptInstances() { Array.ForEach<SceneObjectPart>(m_parts.GetArray(), p => p.Inventory.StopScriptInstances()); } /// <summary> /// Add an inventory item from a user's inventory to a prim in this scene object. /// </summary> /// <param name="agentID">The agent adding the item.</param> /// <param name="localID">The local ID of the part receiving the add.</param> /// <param name="item">The user inventory item being added.</param> /// <param name="copyItemID">The item UUID that should be used by the new item.</param> /// <returns></returns> public bool AddInventoryItem(UUID agentID, uint localID, InventoryItemBase item, UUID copyItemID) { // m_log.DebugFormat( // "[PRIM INVENTORY]: Adding inventory item {0} from {1} to part with local ID {2}", // item.Name, remoteClient.Name, localID); UUID newItemId = (copyItemID != UUID.Zero) ? copyItemID : item.ID; SceneObjectPart part = GetPart(localID); if (part != null) { TaskInventoryItem taskItem = new TaskInventoryItem(); taskItem.ItemID = newItemId; taskItem.AssetID = item.AssetID; taskItem.Name = item.Name; taskItem.Description = item.Description; taskItem.OwnerID = part.OwnerID; // Transfer ownership taskItem.CreatorID = item.CreatorIdAsUuid; taskItem.Type = item.AssetType; taskItem.InvType = item.InvType; if (agentID != part.OwnerID && m_scene.Permissions.PropagatePermissions()) { taskItem.BasePermissions = item.BasePermissions & item.NextPermissions; taskItem.CurrentPermissions = item.CurrentPermissions & item.NextPermissions; taskItem.EveryonePermissions = item.EveryOnePermissions & item.NextPermissions; taskItem.GroupPermissions = item.GroupPermissions & item.NextPermissions; taskItem.NextPermissions = item.NextPermissions; // We're adding this to a prim we don't own. Force // owner change taskItem.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm; } else { taskItem.BasePermissions = item.BasePermissions; taskItem.CurrentPermissions = item.CurrentPermissions; taskItem.EveryonePermissions = item.EveryOnePermissions; taskItem.GroupPermissions = item.GroupPermissions; taskItem.NextPermissions = item.NextPermissions; } taskItem.Flags = item.Flags; // m_log.DebugFormat( // "[PRIM INVENTORY]: Flags are 0x{0:X} for item {1} added to part {2} by {3}", // taskItem.Flags, taskItem.Name, localID, remoteClient.Name); // TODO: These are pending addition of those fields to TaskInventoryItem // taskItem.SalePrice = item.SalePrice; // taskItem.SaleType = item.SaleType; taskItem.CreationDate = (uint)item.CreationDate; bool addFromAllowedDrop = agentID != part.OwnerID; part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop); return true; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't find prim local ID {0} in group {1}, {2} to add inventory item ID {3}", localID, Name, UUID, newItemId); } return false; } /// <summary> /// Returns an existing inventory item. Returns the original, so any changes will be live. /// </summary> /// <param name="primID"></param> /// <param name="itemID"></param> /// <returns>null if the item does not exist</returns> public TaskInventoryItem GetInventoryItem(uint primID, UUID itemID) { SceneObjectPart part = GetPart(primID); if (part != null) { return part.Inventory.GetInventoryItem(itemID); } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't find prim local ID {0} in prim {1}, {2} to get inventory item ID {3}", primID, part.Name, part.UUID, itemID); } return null; } /// <summary> /// Update an existing inventory item. /// </summary> /// <param name="item">The updated item. An item with the same id must already exist /// in this prim's inventory</param> /// <returns>false if the item did not exist, true if the update occurred succesfully</returns> public bool UpdateInventoryItem(TaskInventoryItem item) { SceneObjectPart part = GetPart(item.ParentPartID); if (part != null) { part.Inventory.UpdateInventoryItem(item); return true; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't find prim ID {0} to update item {1}, {2}", item.ParentPartID, item.Name, item.ItemID); } return false; } public int RemoveInventoryItem(uint localID, UUID itemID) { SceneObjectPart part = GetPart(localID); if (part != null) { int type = part.Inventory.RemoveInventoryItem(itemID); return type; } return -1; } public uint GetEffectivePermissions() { uint perms=(uint)(PermissionMask.Modify | PermissionMask.Copy | PermissionMask.Move | PermissionMask.Transfer) | 7; uint ownerMask = 0x7fffffff; SceneObjectPart[] parts = m_parts.GetArray(); for (int i = 0; i < parts.Length; i++) { SceneObjectPart part = parts[i]; ownerMask &= part.OwnerMask; perms &= part.Inventory.MaskEffectivePermissions(); } if ((ownerMask & (uint)PermissionMask.Modify) == 0) perms &= ~(uint)PermissionMask.Modify; if ((ownerMask & (uint)PermissionMask.Copy) == 0) perms &= ~(uint)PermissionMask.Copy; if ((ownerMask & (uint)PermissionMask.Transfer) == 0) perms &= ~(uint)PermissionMask.Transfer; // If root prim permissions are applied here, this would screw // with in-inventory manipulation of the next owner perms // in a major way. So, let's move this to the give itself. // Yes. I know. Evil. // if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Modify) == 0) // perms &= ~((uint)PermissionMask.Modify >> 13); // if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Copy) == 0) // perms &= ~((uint)PermissionMask.Copy >> 13); // if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Transfer) == 0) // perms &= ~((uint)PermissionMask.Transfer >> 13); return perms; } public void ApplyNextOwnerPermissions() { // m_log.DebugFormat("[PRIM INVENTORY]: Applying next owner permissions to {0} {1}", Name, UUID); SceneObjectPart[] parts = m_parts.GetArray(); for (int i = 0; i < parts.Length; i++) parts[i].ApplyNextOwnerPermissions(); } public string GetStateSnapshot() { Dictionary<UUID, string> states = new Dictionary<UUID, string>(); SceneObjectPart[] parts = m_parts.GetArray(); for (int i = 0; i < parts.Length; i++) { SceneObjectPart part = parts[i]; foreach (KeyValuePair<UUID, string> s in part.Inventory.GetScriptStates()) states[s.Key] = s.Value; } if (states.Count < 1) return String.Empty; XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, String.Empty, String.Empty); xmldoc.AppendChild(xmlnode); XmlElement rootElement = xmldoc.CreateElement("", "ScriptData", String.Empty); xmldoc.AppendChild(rootElement); XmlElement wrapper = xmldoc.CreateElement("", "ScriptStates", String.Empty); rootElement.AppendChild(wrapper); foreach (KeyValuePair<UUID, string> state in states) { XmlDocument sdoc = new XmlDocument(); sdoc.LoadXml(state.Value); XmlNodeList rootL = sdoc.GetElementsByTagName("State"); XmlNode rootNode = rootL[0]; XmlNode newNode = xmldoc.ImportNode(rootNode, true); wrapper.AppendChild(newNode); } return xmldoc.InnerXml; } public void SetState(string objXMLData, IScene ins) { if (!(ins is Scene)) return; Scene s = (Scene)ins; if (objXMLData == String.Empty) return; IScriptModule scriptModule = null; foreach (IScriptModule sm in s.RequestModuleInterfaces<IScriptModule>()) { if (sm.ScriptEngineName == s.DefaultScriptEngine) scriptModule = sm; else if (scriptModule == null) scriptModule = sm; } if (scriptModule == null) return; XmlDocument doc = new XmlDocument(); try { doc.LoadXml(objXMLData); } catch (Exception) // (System.Xml.XmlException) { // We will get here if the XML is invalid or in unit // tests. Really should determine which it is and either // fail silently or log it // Fail silently, for now. // TODO: Fix this // return; } XmlNodeList rootL = doc.GetElementsByTagName("ScriptData"); if (rootL.Count != 1) return; XmlElement rootE = (XmlElement)rootL[0]; XmlNodeList dataL = rootE.GetElementsByTagName("ScriptStates"); if (dataL.Count != 1) return; XmlElement dataE = (XmlElement)dataL[0]; foreach (XmlNode n in dataE.ChildNodes) { XmlElement stateE = (XmlElement)n; UUID itemID = new UUID(stateE.GetAttribute("UUID")); scriptModule.SetXMLState(itemID, n.OuterXml); } } public void ResumeScripts() { SceneObjectPart[] parts = m_parts.GetArray(); for (int i = 0; i < parts.Length; i++) parts[i].Inventory.ResumeScripts(); } /// <summary> /// Returns true if any part in the scene object contains scripts, false otherwise. /// </summary> /// <returns></returns> public bool ContainsScripts() { foreach (SceneObjectPart part in Parts) if (part.Inventory.ContainsScripts()) return true; return false; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using Stratus.Dependencies.Ludiq.Reflection; using UnityEngine.Events; namespace Stratus { /// <summary> /// Mantains state information of this object at runtime, saving and loading them at will /// </summary> public class StratusStatefulObject : StratusBehaviour { //------------------------------------------------------------------------/ // Declarations: Types //------------------------------------------------------------------------/ public class SerializedStateRecorder { public List<StratusMemberReference> memberReferences; public List<UnityMember> memberFields; } public class SerializedState { public string label { get; private set; } public int index { get; private set; } public object[] values { get; private set; } public SerializedState(string label, int index, object[] values) { this.label = label; this.index = index; this.values = values; } } //------------------------------------------------------------------------/ // Declarations: Events //------------------------------------------------------------------------/ public enum EventType { Save, Load, SaveInitial, LoadInitial, LoadLast } public enum InitialStateConfiguration { Immediate, OnEvent, [Tooltip("Invoked after the provided methods to invoke have been invoked")] OnCallbackFinished, OnDelay, } public class StateEvent : Stratus.StratusEvent { public StateEvent(EventType type, string label) { this.type = type; this.label = label; } public EventType type { get; private set; } public string label { get; private set; } public bool usesLabel => type == StratusStatefulObject.EventType.Save || type == StratusStatefulObject.EventType.Load; } //------------------------------------------------------------------------/ // Fields //------------------------------------------------------------------------/ public bool debug = false; public StratusEvent.Scope scope = StratusEvent.Scope.Scene; public InitialStateConfiguration initialStateConfiguration = InitialStateConfiguration.Immediate; public UnityEvent onInitialState = new UnityEvent(); public float delay = 0.0f; [Header("State")] //[DrawIf(nameof(initialStateConfiguration), InitialStateConfiguration.AfterEvent, ComparisonType.Equals)] public bool recordTransformState = true; [Filter(Methods = false, Properties = true, NonPublic = true, ReadOnly = true, Static = true, Inherited = true, Fields = true, Extension = false)] public List<UnityMember> memberFields = new List<UnityMember>(); private Dictionary<string, SerializedState> stateMap = new Dictionary<string, SerializedState>(); private List<SerializedState> stateList = new List<SerializedState>(); private List<StratusMemberReference> memberReferences = new List<StratusMemberReference>(); //------------------------------------------------------------------------/ // Properties //------------------------------------------------------------------------/ /// <summary> /// The initial state of this object /// </summary> public SerializedState initialState { get; private set; } /// <summary> /// The last state of this object /// </summary> public SerializedState lastState { get; private set; } /// <summary> /// The number of states this object has recorded /// </summary> public int numberOfStates { get; private set; } = 0; /// <summary> /// The number of members this object is recording /// </summary> public int memberCount { get; private set; } private static Dictionary<string, bool> availableStates { get; set; } = new Dictionary<string, bool>(); //------------------------------------------------------------------------/ // Messages //------------------------------------------------------------------------/ private void Awake() { // Optionally, subscribe to scene-wide events if (scope == StratusEvent.Scope.Scene) StratusScene.Connect<StateEvent>(this.OnStateEvent); // Always subscribe to specific requests gameObject.Connect<StateEvent>(this.OnStateEvent); AddCommonRecorders(); } private void Start() { switch (initialStateConfiguration) { case InitialStateConfiguration.Immediate: SaveInitialState(); break; case InitialStateConfiguration.OnEvent: gameObject.Dispatch<StateEvent>(new StateEvent(EventType.SaveInitial, null)); break; case InitialStateConfiguration.OnCallbackFinished: onInitialState.Invoke(); SaveInitialState(); break; case InitialStateConfiguration.OnDelay: Invoke(nameof(SaveInitialState), delay); break; } } private void OnValidate() { foreach (var member in memberFields) { if (member == null) continue; if (member.target != this.gameObject) member.target = this.gameObject; } } void OnStateEvent(StateEvent e) { switch (e.type) { case EventType.Save: SaveState(e.label); break; case EventType.Load: LoadState(e.label); break; case EventType.SaveInitial: SaveInitialState(); break; case EventType.LoadInitial: LoadInitialState(); break; case EventType.LoadLast: LoadLastState(); break; default: break; } } //------------------------------------------------------------------------/ // Methods: Public //------------------------------------------------------------------------/ public void LoadState(string label) { if (!stateMap.ContainsKey(label)) StratusDebug.LogError($"The state {label} was not found!", this); SerializedState state = stateMap[label]; LoadState(state); } public SerializedState SaveState(string label) { SerializedState state = MakeState(label); // Overwrite if found if (stateMap.ContainsKey(label)) { stateMap[label] = state; stateList.RemoveAt(stateMap[label].index); stateList.Add(state); if (debug) StratusDebug.Log($"The state {label} has been overwritten!", this); } // Else make a new one else { stateMap.Add(label, state); stateList.Add(state); } return state; } /// <summary> /// Loads the initial state of this object /// </summary> public void LoadInitialState() { LoadState(initialState); } /// <summary> /// Loads the last state of this object /// </summary> public void LoadLastState() { LoadState(lastState); } private void SaveInitialState() { initialState = MakeState("Initial"); } //------------------------------------------------------------------------/ // Methods: State //------------------------------------------------------------------------/ private void LoadState(SerializedState state) { // The starting index of objet values int index = 0; // Set through member reference foreach (var member in memberReferences) member.Set(state.values[index++]); // Set through member field foreach (var member in memberFields) { if (member.isAssigned) member.Set(state.values[index++]); } if (debug) StratusDebug.Log($"Loaded the state {state.label} with {memberCount} members!", this); } private SerializedState MakeState(string label) { List<object> values = new List<object>(); // Record from MemberReference foreach (var member in memberReferences) { values.Add(member.Get()); } // Record from MemebrField foreach (var member in memberFields) { if (member.isAssigned) values.Add(member.Get()); } SerializedState state = new SerializedState(label, numberOfStates, values.ToArray()); numberOfStates++; if (debug) StratusDebug.Log($"Recorded the state {state.label} with {memberCount} members!", this); lastState = state; return state; } //------------------------------------------------------------------------/ // Methods: Recorders //------------------------------------------------------------------------/ private void AddCommonRecorders() { if (recordTransformState) AddTransformRecorder(); memberCount = memberReferences.Count + memberFields.Count; } private void AddTransformRecorder() { memberReferences.Add(StratusMemberReference.Construct(() => transform.position)); memberReferences.Add(StratusMemberReference.Construct(() => transform.rotation)); memberReferences.Add(StratusMemberReference.Construct(() => transform.localScale)); memberReferences.Add(StratusMemberReference.Construct(() => transform.parent)); } } }
#region Using directives using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Diagnostics; #endregion namespace Microsoft.Msagl.Core.Geometry { /// <summary> /// Represents a node containing a box and some user data. /// Is used in curve intersections routines. /// </summary> public class RectangleNode<TData> { #if TEST_MSAGL /// <summary> /// /// </summary> /// <returns></returns> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return IsLeaf ? (Count + " " + UserData) : Count.ToString(); } #endif /// <summary> /// /// </summary> public int Count { get; set; } RectangleNode<TData> left; RectangleNode<TData> right; /// <summary> /// creates an empty node /// </summary> public RectangleNode() { } /// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="rect"></param> public RectangleNode(TData data, Rectangle rect) { UserData = data; Rectangle = rect; Count = 1; } RectangleNode(int count) { Count=count; } /// <summary> /// This field provides direct internal access to the value type Rectangle, which RTree and other callers /// modify directly with .Add(); the auto-property returns a temporary value-by-copy that is immediately discarded. /// </summary> // ReSharper disable InconsistentNaming internal Rectangle rectangle; // ReSharper restore InconsistentNaming /// <summary> /// gets or sets the rectangle of the node /// </summary> public Rectangle Rectangle { get { return rectangle; } set { rectangle = value; } } /// <summary> /// false if it is an internal node and true if it is a leaf /// </summary> internal bool IsLeaf { get { return left==null /*&& right==null*/; } //if left is a null then right is also a null } /// <summary> /// /// </summary> public RectangleNode<TData> Left { get { return left; } internal set { if (left != null && left.Parent==this) left.Parent = null; left = value; if (left != null) left.Parent = this; } } /// <summary> /// /// </summary> public RectangleNode<TData> Right { get { return right; } internal set { if (right != null&& right.Parent==this) right.Parent = null; right = value; if (right != null) right.Parent = this; } } /// <summary> /// The actual data if a leaf node, else null or a value-type default. /// </summary> public TData UserData { get; set; } /// <summary> /// Parent of this node. /// </summary> public RectangleNode<TData> Parent { get; private set; } internal bool IsLeftChild { get { Debug.Assert(Parent!=null); return Equals(Parent.Left); } } /// <summary> /// brings the first leaf which rectangle was hit and the delegate is happy with the object /// </summary> /// <param name="point"></param> /// <param name="hitTestForPointDelegate"></param> /// <returns></returns> public RectangleNode<TData> FirstHitNode(Point point, Func<Point, TData, HitTestBehavior> hitTestForPointDelegate) { if (rectangle.Contains(point)) { if (IsLeaf) { if (hitTestForPointDelegate != null) { return hitTestForPointDelegate(point, UserData) == HitTestBehavior.Stop ? this : null; } return this; } return Left.FirstHitNode(point, hitTestForPointDelegate) ?? Right.FirstHitNode(point, hitTestForPointDelegate); } return null; } /// <summary> /// brings the first leaf which rectangle was intersected /// </summary> /// <returns></returns> public RectangleNode<TData> FirstIntersectedNode(Rectangle r) { if (r.Intersects(rectangle)) { if (IsLeaf) return this; return Left.FirstIntersectedNode(r) ?? Right.FirstIntersectedNode(r); } return null; } /// <summary> /// brings the first leaf which rectangle was hit and the delegate is happy with the object /// </summary> /// <param name="point"></param> /// <returns></returns> public RectangleNode<TData> FirstHitNode(Point point) { if (rectangle.Contains(point)) { if (IsLeaf) return this; return Left.FirstHitNode(point) ?? Right.FirstHitNode(point); } return null; } /// <summary> /// returns all leaf nodes for which the rectangle was hit and the delegate is happy with the object /// </summary> /// <param name="rectanglePar"></param> /// <param name="hitTestAccept"></param> /// <returns></returns> public IEnumerable<TData> AllHitItems(Rectangle rectanglePar, Func<TData, bool> hitTestAccept) { var stack = new Stack<RectangleNode<TData>>(); stack.Push(this); while (stack.Count > 0) { RectangleNode<TData> node = stack.Pop(); if (node.Rectangle.Intersects(rectanglePar)) { if (node.IsLeaf) { if ((null == hitTestAccept) || hitTestAccept(node.UserData)) { yield return node.UserData; } } else { stack.Push(node.left); stack.Push(node.right); } } } } /// <summary> /// returns all items for which the rectangle contains the point /// </summary> /// <returns></returns> public IEnumerable<TData> AllHitItems(Point point) { var stack = new Stack<RectangleNode<TData>>(); stack.Push(this); while (stack.Count > 0) { var node = stack.Pop(); if (node.Rectangle.Contains(point)) { if (node.IsLeaf) yield return node.UserData; else { stack.Push(node.left); stack.Push(node.right); } } } } /// <summary> /// Returns all leaves whose rectangles intersect hitRectangle (or all leaves before hitTest returns false). /// </summary> /// <param name="hitTest"></param> /// <param name="hitRectangle"></param> /// <returns></returns> internal void VisitTree(Func<TData, HitTestBehavior> hitTest, Rectangle hitRectangle) { VisitTreeStatic(this, hitTest, hitRectangle); } static HitTestBehavior VisitTreeStatic(RectangleNode<TData> rectangleNode, Func<TData, HitTestBehavior> hitTest, Rectangle hitRectangle) { if (rectangleNode.Rectangle.Intersects(hitRectangle)) { if (hitTest(rectangleNode.UserData) == HitTestBehavior.Continue) { if (rectangleNode.Left != null) { // If rectangleNode.Left is not null, rectangleNode.Right won't be either. if (VisitTreeStatic(rectangleNode.Left, hitTest, hitRectangle) == HitTestBehavior.Continue && VisitTreeStatic(rectangleNode.Right, hitTest, hitRectangle) == HitTestBehavior.Continue) { return HitTestBehavior.Continue; } return HitTestBehavior.Stop; } return HitTestBehavior.Continue; } return HitTestBehavior.Stop; } return HitTestBehavior.Continue; } /// <summary> /// /// </summary> /// <returns></returns> public RectangleNode<TData> Clone() { var ret = new RectangleNode<TData>(Count) {UserData = UserData, Rectangle = Rectangle}; if (Left != null) ret.Left = Left.Clone(); if (Right != null) ret.Right = Right.Clone(); return ret; } /// <summary> /// yields all leaves which rectangles intersect the given one. We suppose that leaves are all nodes having UserData not a null. /// </summary> /// <param name="rectanglePar"></param> /// <returns></returns> public IEnumerable<TData> GetNodeItemsIntersectingRectangle(Rectangle rectanglePar) { return GetLeafRectangleNodesIntersectingRectangle(rectanglePar).Select(node => node.UserData); } /// <summary> /// yields all leaves whose rectangles intersect the given one. We suppose that leaves are all nodes having UserData not a null. /// </summary> /// <param name="rectanglePar"></param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public IEnumerable<RectangleNode<TData>> GetLeafRectangleNodesIntersectingRectangle(Rectangle rectanglePar) { var stack = new Stack<RectangleNode<TData>>(); stack.Push(this); while (stack.Count > 0) { RectangleNode<TData> node = stack.Pop(); if (node.Rectangle.Intersects(rectanglePar)) { if (node.IsLeaf) { yield return node; } else { stack.Push(node.left); stack.Push(node.right); } } } } /// <summary> /// Walk the tree and return the data from all leaves /// </summary> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public IEnumerable<TData> GetAllLeaves() { return GetAllLeafNodes().Select(n => n.UserData); } internal IEnumerable<RectangleNode<TData>> GetAllLeafNodes() { return EnumRectangleNodes(true /*leafOnly*/); } IEnumerable<RectangleNode<TData>> EnumRectangleNodes(bool leafOnly) { var stack = new Stack<RectangleNode<TData>>(); stack.Push(this); while (stack.Count > 0) { var node = stack.Pop(); if (node.IsLeaf || !leafOnly) { yield return node; } if (!node.IsLeaf) { stack.Push(node.left); stack.Push(node.right); } } } const int GroupSplitThreshold = 2; /// <summary> /// calculates a tree based on the given nodes /// </summary> /// <param name="nodes"></param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes"), SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static RectangleNode<TData> CreateRectangleNodeOnEnumeration(IEnumerable<RectangleNode<TData>> nodes) { if(nodes==null) return null; var nodeList = new List<RectangleNode<TData>>(nodes); return CreateRectangleNodeOnListOfNodes(nodeList); } ///<summary> ///calculates a tree based on the given nodes ///</summary> ///<param name="dataEnumeration"></param> ///<param name="rectangleDelegate"></param> ///<returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static RectangleNode<TData> CreateRectangleNodeOnData(IEnumerable<TData> dataEnumeration, Func<TData, Rectangle> rectangleDelegate) { if (dataEnumeration == null || rectangleDelegate == null) return null; var nodeList = new List<RectangleNode<TData>>(dataEnumeration.Select(d=>new RectangleNode<TData>(d, rectangleDelegate(d)))); return CreateRectangleNodeOnListOfNodes(nodeList); } /// <summary> /// /// </summary> /// <param name="nodes"></param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes"), SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] static public RectangleNode<TData> CreateRectangleNodeOnListOfNodes(IList<RectangleNode<TData>> nodes) { ValidateArg.IsNotNull(nodes, "nodes"); if (nodes.Count == 0) return null; if (nodes.Count == 1)return nodes[0]; //Finding the seeds var b0 = nodes[0].Rectangle; //the first seed int seed0 = 1; int seed1 = ChooseSeeds(nodes, ref b0, ref seed0); //We have two seeds at hand. Build two groups. var gr0 = new List<RectangleNode<TData>>(); var gr1 = new List<RectangleNode<TData>>(); gr0.Add(nodes[seed0]); gr1.Add(nodes[seed1]); var box0 = nodes[seed0].Rectangle; var box1 = nodes[seed1].Rectangle; //divide nodes on two groups DivideNodes(nodes, seed0, seed1, gr0, gr1, ref box0, ref box1, GroupSplitThreshold); var ret = new RectangleNode<TData>(nodes.Count) { Rectangle = new Rectangle(box0, box1), Left = CreateRectangleNodeOnListOfNodes(gr0), Right = CreateRectangleNodeOnListOfNodes(gr1) }; return ret; } static int ChooseSeeds(IList<RectangleNode<TData>> nodes, ref Rectangle b0, ref int seed0) { double area = new Rectangle(b0, nodes[seed0].Rectangle).Area; for (int i = 2; i < nodes.Count; i++) { double area0 = new Rectangle(b0, nodes[i].Rectangle).Area; if (area0 > area) { seed0 = i; area = area0; } } //Got the first seed seed0 //Now looking for a seed for the second group int seed1 = 0; //the compiler forces me to init it //init seed1 for (int i = 0; i < nodes.Count; i++) { if (i != seed0) { seed1 = i; break; } } area = new Rectangle(nodes[seed0].Rectangle, nodes[seed1].Rectangle).Area; //Now try to improve the second seed for (int i = 0; i < nodes.Count; i++) { if (i == seed0) continue; double area1 = new Rectangle(nodes[seed0].Rectangle, nodes[i].Rectangle).Area; if (area1 > area) { seed1 = i; area = area1; } } return seed1; } static void DivideNodes(IList<RectangleNode<TData>> nodes, int seed0, int seed1, List<RectangleNode<TData>> gr0, List<RectangleNode<TData>> gr1, ref Rectangle box0, ref Rectangle box1, int groupSplitThreshold) { for (int i = 0; i < nodes.Count; i++) { if (i == seed0 || i == seed1) continue; // ReSharper disable InconsistentNaming var box0_ = new Rectangle(box0, nodes[i].Rectangle); double delta0 = box0_.Area - box0.Area; var box1_ = new Rectangle(box1, nodes[i].Rectangle); double delta1 = box1_.Area - box1.Area; // ReSharper restore InconsistentNaming //keep the tree roughly balanced if (gr0.Count * groupSplitThreshold < gr1.Count) { gr0.Add(nodes[i]); box0 = box0_; } else if (gr1.Count * groupSplitThreshold < gr0.Count) { gr1.Add(nodes[i]); box1 = box1_; } else if (delta0 < delta1) { gr0.Add(nodes[i]); box0 = box0_; } else if (delta1 < delta0) { gr1.Add(nodes[i]); box1 = box1_; } else if (box0.Area < box1.Area) { gr0.Add(nodes[i]); box0 = box0_; } else { gr1.Add(nodes[i]); box1 = box1_; } } } /// <summary> /// Walk the tree from node down and apply visitor to all nodes /// </summary> /// <param name="node"></param> /// <param name="visitor"></param> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes"), SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] static public void TraverseHierarchy(RectangleNode<TData> node, Action<RectangleNode<TData>> visitor) { ValidateArg.IsNotNull(node, "node"); ValidateArg.IsNotNull(visitor, "visitor"); visitor(node); if (node.Left != null) TraverseHierarchy(node.Left, visitor); if (node.Right != null) TraverseHierarchy(node.Right, visitor); } } }
// *********************************************************************** // Copyright (c) 2006 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; using System.Collections; using System.ComponentModel; using NUnit.Framework.Constraints; namespace NUnit.Framework { /// <summary> /// A set of Assert methods operating on one or more collections /// </summary> public class CollectionAssert { #region Equals and ReferenceEquals /// <summary> /// The Equals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// </summary> /// <param name="a"></param> /// <param name="b"></param> [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { throw new InvalidOperationException("CollectionAssert.Equals should not be used for Assertions"); } /// <summary> /// override the default ReferenceEquals to throw an InvalidOperationException. This /// implementation makes sure there is no mistake in calling this function /// as part of Assert. /// </summary> /// <param name="a"></param> /// <param name="b"></param> public static new void ReferenceEquals(object a, object b) { throw new InvalidOperationException("CollectionAssert.ReferenceEquals should not be used for Assertions"); } #endregion #region AllItemsAreInstancesOfType /// <summary> /// Asserts that all items contained in collection are of the type specified by expectedType. /// </summary> /// <param name="collection">IEnumerable containing objects to be considered</param> /// <param name="expectedType">System.Type that all objects in collection must be instances of</param> public static void AllItemsAreInstancesOfType (IEnumerable collection, Type expectedType) { AllItemsAreInstancesOfType(collection, expectedType, string.Empty, null); } /// <summary> /// Asserts that all items contained in collection are of the type specified by expectedType. /// </summary> /// <param name="collection">IEnumerable containing objects to be considered</param> /// <param name="expectedType">System.Type that all objects in collection must be instances of</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AllItemsAreInstancesOfType (IEnumerable collection, Type expectedType, string message, params object[] args) { Assert.That(collection, Is.All.InstanceOf(expectedType), message, args); } #endregion #region AllItemsAreNotNull /// <summary> /// Asserts that all items contained in collection are not equal to null. /// </summary> /// <param name="collection">IEnumerable containing objects to be considered</param> public static void AllItemsAreNotNull (IEnumerable collection) { AllItemsAreNotNull(collection, string.Empty, null); } /// <summary> /// Asserts that all items contained in collection are not equal to null. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AllItemsAreNotNull (IEnumerable collection, string message, params object[] args) { Assert.That(collection, Is.All.Not.Null, message, args); } #endregion #region AllItemsAreUnique /// <summary> /// Ensures that every object contained in collection exists within the collection /// once and only once. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> public static void AllItemsAreUnique (IEnumerable collection) { AllItemsAreUnique(collection, string.Empty, null); } /// <summary> /// Ensures that every object contained in collection exists within the collection /// once and only once. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AllItemsAreUnique (IEnumerable collection, string message, params object[] args) { Assert.That(collection, Is.Unique, message, args); } #endregion #region AreEqual /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreEqual (IEnumerable expected, IEnumerable actual) { AreEqual(expected, actual, string.Empty, null); } /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer comparer) { AreEqual(expected, actual, comparer, string.Empty, null); } /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreEqual (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, Is.EqualTo(expected), message, args); } /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer comparer, string message, params object[] args) { Assert.That(actual, Is.EqualTo(expected).Using(comparer), message, args); } #endregion #region AreEquivalent /// <summary> /// Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreEquivalent (IEnumerable expected, IEnumerable actual) { AreEquivalent(expected, actual, string.Empty, null); } /// <summary> /// Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreEquivalent (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, Is.EquivalentTo(expected), message, args); } #endregion #region AreNotEqual /// <summary> /// Asserts that expected and actual are not exactly equal. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual) { AreNotEqual(expected, actual, string.Empty, null); } /// <summary> /// Asserts that expected and actual are not exactly equal. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual, IComparer comparer) { AreNotEqual(expected, actual, comparer, string.Empty, null); } /// <summary> /// Asserts that expected and actual are not exactly equal. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, Is.Not.EqualTo(expected), message, args); } /// <summary> /// Asserts that expected and actual are not exactly equal. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual, IComparer comparer, string message, params object[] args) { Assert.That(actual, Is.Not.EqualTo(expected).Using(comparer), message, args); } #endregion #region AreNotEquivalent /// <summary> /// Asserts that expected and actual are not equivalent. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreNotEquivalent (IEnumerable expected, IEnumerable actual) { AreNotEquivalent(expected, actual, string.Empty, null); } /// <summary> /// Asserts that expected and actual are not equivalent. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreNotEquivalent (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, Is.Not.EquivalentTo(expected), message, args); } #endregion #region Contains /// <summary> /// Asserts that collection contains actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object to be found within collection</param> public static void Contains (IEnumerable collection, Object actual) { Contains(collection, actual, string.Empty, null); } /// <summary> /// Asserts that collection contains actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object to be found within collection</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void Contains (IEnumerable collection, Object actual, string message, params object[] args) { Assert.That(collection, Has.Member(actual), message, args); } #endregion #region DoesNotContain /// <summary> /// Asserts that collection does not contain actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object that cannot exist within collection</param> public static void DoesNotContain (IEnumerable collection, Object actual) { DoesNotContain(collection, actual, string.Empty, null); } /// <summary> /// Asserts that collection does not contain actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object that cannot exist within collection</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void DoesNotContain (IEnumerable collection, Object actual, string message, params object[] args) { Assert.That(collection, Has.No.Member(actual), message, args); } #endregion #region IsNotSubsetOf /// <summary> /// Asserts that the superset does not contain the subset /// </summary> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="superset">The IEnumerable superset to be considered</param> public static void IsNotSubsetOf (IEnumerable subset, IEnumerable superset) { IsNotSubsetOf(subset, superset, string.Empty, null); } /// <summary> /// Asserts that the superset does not contain the subset /// </summary> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsNotSubsetOf (IEnumerable subset, IEnumerable superset, string message, params object[] args) { Assert.That(subset, Is.Not.SubsetOf(superset), message, args); } #endregion #region IsSubsetOf /// <summary> /// Asserts that the superset contains the subset. /// </summary> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="superset">The IEnumerable superset to be considered</param> public static void IsSubsetOf (IEnumerable subset, IEnumerable superset) { IsSubsetOf(subset, superset, string.Empty, null); } /// <summary> /// Asserts that the superset contains the subset. /// </summary> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsSubsetOf (IEnumerable subset, IEnumerable superset, string message, params object[] args) { Assert.That(subset, Is.SubsetOf(superset), message, args); } #endregion #region IsNotSupersetOf /// <summary> /// Asserts that the subset does not contain the superset /// </summary> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="subset">The IEnumerable subset to be considered</param> public static void IsNotSupersetOf(IEnumerable superset, IEnumerable subset) { IsNotSupersetOf(superset, subset, string.Empty, null); } /// <summary> /// Asserts that the subset does not contain the superset /// </summary> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsNotSupersetOf(IEnumerable superset, IEnumerable subset, string message, params object[] args) { Assert.That(superset, Is.Not.SupersetOf(subset), message, args); } #endregion #region IsSupersetOf /// <summary> /// Asserts that the subset contains the superset. /// </summary> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="subset">The IEnumerable subset to be considered</param> public static void IsSupersetOf(IEnumerable superset, IEnumerable subset) { IsSupersetOf(superset, subset, string.Empty, null); } /// <summary> /// Asserts that the subset contains the superset. /// </summary> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsSupersetOf(IEnumerable superset, IEnumerable subset, string message, params object[] args) { Assert.That(superset, Is.SupersetOf(subset), message, args); } #endregion #region IsEmpty /// <summary> /// Assert that an array, list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsEmpty(IEnumerable collection, string message, params object[] args) { Assert.That(collection, new EmptyCollectionConstraint(), message, args); } /// <summary> /// Assert that an array,list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> public static void IsEmpty(IEnumerable collection) { IsEmpty(collection, string.Empty, null); } #endregion #region IsNotEmpty /// <summary> /// Assert that an array, list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsNotEmpty(IEnumerable collection, string message, params object[] args) { Assert.That(collection, new NotConstraint(new EmptyCollectionConstraint()), message, args); } /// <summary> /// Assert that an array,list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> public static void IsNotEmpty(IEnumerable collection) { IsNotEmpty(collection, string.Empty, null); } #endregion #region IsOrdered /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsOrdered(IEnumerable collection, string message, params object[] args) { Assert.That(collection, Is.Ordered, message, args); } /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> public static void IsOrdered(IEnumerable collection) { IsOrdered(collection, string.Empty, null); } /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="comparer">A custom comparer to perform the comparisons</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsOrdered(IEnumerable collection, IComparer comparer, string message, params object[] args) { Assert.That(collection, Is.Ordered.Using(comparer), message, args); } /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="comparer">A custom comparer to perform the comparisons</param> public static void IsOrdered(IEnumerable collection, IComparer comparer) { IsOrdered(collection, comparer, string.Empty, null); } #endregion } }
using System.Drawing; using System.Windows.Forms; namespace ToolStripCustomizer.ColorTables { sealed class VS2010ColorTable : PresetColorTable { public VS2010ColorTable() : base("Visual Studio 2010") { } public override Color ButtonSelectedBorder { get { return Color.FromArgb(255, 229, 195, 101); } } public override Color ButtonCheckedGradientBegin { get { return Color.FromArgb(255, 255, 232, 166); } } public override Color ButtonCheckedGradientMiddle { get { return Color.FromArgb(255, 255, 232, 166); } } public override Color ButtonCheckedGradientEnd { get { return Color.FromArgb(255, 255, 252, 242); } } public override Color ButtonSelectedGradientBegin { get { return Color.FromArgb(255, 255, 252, 242); } } public override Color ButtonSelectedGradientMiddle { get { return Color.FromArgb(255, 255, 245, 217); } } public override Color ButtonSelectedGradientEnd { get { return Color.FromArgb(255, 255, 236, 181); } } public override Color ButtonPressedGradientBegin { get { return Color.FromArgb(255, 255, 232, 166); } } public override Color ButtonPressedGradientMiddle { get { return Color.FromArgb(255, 255, 232, 166); } } public override Color ButtonPressedGradientEnd { get { return Color.FromArgb(255, 255, 232, 166); } } public override Color CheckBackground { get { return Color.FromArgb(255, 255, 230, 162); } } public override Color CheckSelectedBackground { get { return Color.FromArgb(255, 255, 230, 162); } } public override Color CheckPressedBackground { get { return Color.FromArgb(255, 253, 170, 96); } } public override Color GripDark { get { return Color.FromArgb(255, 126, 138, 154); } } public override Color GripLight { get { return Color.FromArgb(255, 227, 230, 232); } } public override Color ImageMarginGradientBegin { get { return Color.FromArgb(255, 223, 236, 239); } } public override Color ImageMarginGradientMiddle { get { return Color.FromArgb(255, 223, 236, 239); } } public override Color ImageMarginGradientEnd { get { return Color.FromArgb(255, 223, 236, 239); } } public override Color ImageMarginRevealedGradientBegin { get { return Color.FromArgb(255, 233, 238, 238); } } public override Color ImageMarginRevealedGradientMiddle { get { return Color.FromArgb(255, 233, 238, 238); } } public override Color ImageMarginRevealedGradientEnd { get { return Color.FromArgb(255, 233, 238, 238); } } public override Color MenuStripGradientBegin { get { return Color.FromArgb(255, 162, 176, 202); } } public override Color MenuStripGradientEnd { get { return Color.FromArgb(255, 168, 182, 206); } } public override Color MenuItemSelected { get { return Color.FromArgb(255, 255, 236, 181); } } public override Color MenuItemBorder { get { return Color.FromArgb(255, 229, 195, 101); } } public override Color MenuBorder { get { return Color.FromArgb(255, 105, 119, 135); } } public override Color MenuItemSelectedGradientBegin { get { return Color.FromArgb(255, 252, 242, 255); } } public override Color MenuItemSelectedGradientEnd { get { return Color.FromArgb(255, 254, 227, 148); } } public override Color MenuItemPressedGradientBegin { get { return Color.FromArgb(255, 207, 211, 218); } } public override Color MenuItemPressedGradientMiddle { get { return Color.FromArgb(255, 218, 223, 231); } } public override Color MenuItemPressedGradientEnd { get { return Color.FromArgb(255, 218, 223, 231); } } public override Color RaftingContainerGradientBegin { get { return Color.FromArgb(255, 186, 192, 201); } } public override Color RaftingContainerGradientEnd { get { return Color.FromArgb(255, 186, 192, 201); } } public override Color SeparatorDark { get { return Color.FromArgb(255, 171, 180, 190); } } public override Color SeparatorLight { get { return Color.FromArgb(255, 117, 128, 145); } } public override Color StatusStripGradientBegin { get { return Color.FromArgb(255, 128, 140, 162); } } public override Color StatusStripGradientEnd { get { return Color.FromArgb(255, 111, 125, 149); } } public override Color ToolStripBorder { get { return Color.FromArgb(255, 99, 109, 126); } } public override Color ToolStripDropDownBackground { get { return Color.FromArgb(255, 218, 223, 231); } } public override Color ToolStripGradientBegin { get { return Color.FromArgb(255, 221, 226, 236); } } public override Color ToolStripGradientMiddle { get { return Color.FromArgb(255, 203, 210, 226); } } public override Color ToolStripGradientEnd { get { return Color.FromArgb(255, 203, 210, 226); } } public override Color ToolStripContentPanelGradientBegin { get { return Color.FromArgb(255, 137, 148, 163); } } public override Color ToolStripContentPanelGradientEnd { get { return Color.FromArgb(255, 137, 148, 163); } } public override Color ToolStripPanelGradientBegin { get { return Color.FromArgb(255, 156, 170, 193); } } public override Color ToolStripPanelGradientEnd { get { return Color.FromArgb(255, 156, 170, 193); } } public override Color OverflowButtonGradientBegin { get { return Color.FromArgb(255, 233, 235, 237); } } public override Color OverflowButtonGradientMiddle { get { return Color.FromArgb(255, 233, 235, 237); } } public override Color OverflowButtonGradientEnd { get { return Color.FromArgb(255, 208, 213, 217); } } } }
#region File Description //----------------------------------------------------------------------------- // Hud.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using RolePlayingGameData; #endregion namespace RolePlaying { /// <summary> /// Displays each player's basic statistics and the combat action menu. /// </summary> class Hud { private ScreenManager screenManager; public const int HudHeight = 183; #region Graphics Data private Texture2D backgroundHudTexture; private Texture2D topHudTexture; private Texture2D combatPopupTexture; private Texture2D activeCharInfoTexture; private Texture2D inActiveCharInfoTexture; private Texture2D cantUseCharInfoTexture; private Texture2D selectionBracketTexture; private Texture2D menuTexture; private Texture2D statsTexture; private Texture2D deadPortraitTexture; private Texture2D charSelFadeLeftTexture; private Texture2D charSelFadeRightTexture; private Texture2D charSelArrowLeftTexture; private Texture2D charSelArrowRightTexture; private Texture2D actionTexture; private Texture2D yButtonTexture; private Texture2D startButtonTexture; private Vector2 topHudPosition = new Vector2(353f, 30f); private Vector2 charSelLeftPosition = new Vector2(70f, 600f); private Vector2 charSelRightPosition = new Vector2(1170f, 600f); private Vector2 yButtonPosition = new Vector2(0f, 560f + 20f); private Vector2 startButtonPosition = new Vector2(0f, 560f + 35f); private Vector2 yTextPosition = new Vector2(0f, 560f + 70f); private Vector2 startTextPosition = new Vector2(0f, 560f + 70f); private Vector2 actionTextPosition = new Vector2(640f, 55f); private Vector2 backgroundHudPosition = new Vector2(0f, 525f); private Vector2 portraitPosition = new Vector2(640f, 55f); private Vector2 startingInfoPosition = new Vector2(0f, 550f); private Vector2 namePosition; private Vector2 levelPosition; private Vector2 detailPosition; private readonly Color activeNameColor = new Color(200, 200, 200); private readonly Color inActiveNameColor = new Color(100, 100, 100); private readonly Color nonSelColor = new Color(86, 26, 5); private readonly Color selColor = new Color(229, 206, 144); #endregion #region Action Text /// <summary> /// The text that is shown in the action bar at the top of the combat screen. /// </summary> private string actionText = String.Empty; /// <summary> /// The text that is shown in the action bar at the top of the combat screen. /// </summary> public string ActionText { get { return actionText; } set { actionText = value; } } #endregion #region Initialization /// <summary> /// Creates a new Hud object using the given ScreenManager. /// </summary> public Hud(ScreenManager screenManager) { // check the parameter if (screenManager == null) { throw new ArgumentNullException("screenManager"); } this.screenManager = screenManager; } /// <summary> /// Load the graphics content from the content manager. /// </summary> public void LoadContent() { ContentManager content = screenManager.Game.Content; backgroundHudTexture = content.Load<Texture2D>(@"Textures\HUD\HudBkgd"); topHudTexture = content.Load<Texture2D>(@"Textures\HUD\CombatStateInfoStrip"); activeCharInfoTexture = content.Load<Texture2D>(@"Textures\HUD\PlankActive"); inActiveCharInfoTexture = content.Load<Texture2D>(@"Textures\HUD\PlankInActive"); cantUseCharInfoTexture = content.Load<Texture2D>(@"Textures\HUD\PlankCantUse"); selectionBracketTexture = content.Load<Texture2D>(@"Textures\HUD\SelectionBrackets"); deadPortraitTexture = content.Load<Texture2D>(@"Textures\Characters\Portraits\Tombstone"); combatPopupTexture = content.Load<Texture2D>(@"Textures\HUD\CombatPopup"); charSelFadeLeftTexture = content.Load<Texture2D>(@"Textures\Buttons\CharSelectFadeLeft"); charSelFadeRightTexture = content.Load<Texture2D>(@"Textures\Buttons\CharSelectFadeRight"); charSelArrowLeftTexture = content.Load<Texture2D>(@"Textures\Buttons\CharSelectHlLeft"); charSelArrowRightTexture = content.Load<Texture2D>(@"Textures\Buttons\CharSelectHlRight"); actionTexture = content.Load<Texture2D>(@"Textures\HUD\HudSelectButton"); yButtonTexture = content.Load<Texture2D>(@"Textures\Buttons\YButton"); startButtonTexture = content.Load<Texture2D>(@"Textures\Buttons\StartButton"); menuTexture = content.Load<Texture2D>(@"Textures\HUD\Menu"); statsTexture = content.Load<Texture2D>(@"Textures\HUD\Stats"); } #endregion #region Drawing /// <summary> /// Draw the screen. /// </summary> public void Draw() { SpriteBatch spriteBatch = screenManager.SpriteBatch; spriteBatch.Begin(); startingInfoPosition.X = 640f; startingInfoPosition.X -= Session.Party.Players.Count / 2 * 200f; if (Session.Party.Players.Count % 2 != 0) { startingInfoPosition.X -= 100f; } spriteBatch.Draw(backgroundHudTexture, backgroundHudPosition, Color.White); if (CombatEngine.IsActive) { DrawForCombat(); } else { DrawForNonCombat(); } spriteBatch.End(); } /// <summary> /// Draws HUD for Combat Mode /// </summary> private void DrawForCombat() { SpriteBatch spriteBatch = screenManager.SpriteBatch; Vector2 position = startingInfoPosition; foreach (CombatantPlayer combatantPlayer in CombatEngine.Players) { DrawCombatPlayerDetails(combatantPlayer, position); position.X += activeCharInfoTexture.Width - 6f; } charSelLeftPosition.X = startingInfoPosition.X - 5f - charSelArrowLeftTexture.Width; charSelRightPosition.X = position.X + 5f; // Draw character Selection Arrows if (CombatEngine.IsPlayersTurn) { spriteBatch.Draw(charSelArrowLeftTexture, charSelLeftPosition, Color.White); spriteBatch.Draw(charSelArrowRightTexture, charSelRightPosition, Color.White); } else { spriteBatch.Draw(charSelFadeLeftTexture, charSelLeftPosition, Color.White); spriteBatch.Draw(charSelFadeRightTexture, charSelRightPosition, Color.White); } if (actionText.Length > 0) { spriteBatch.Draw(topHudTexture, topHudPosition, Color.White); // Draw Action Text Fonts.DrawCenteredText(spriteBatch, Fonts.PlayerStatisticsFont, actionText, actionTextPosition, Color.Black); } } /// <summary> /// Draws HUD for non Combat Mode /// </summary> private void DrawForNonCombat() { SpriteBatch spriteBatch = screenManager.SpriteBatch; Vector2 position = startingInfoPosition; foreach (Player player in Session.Party.Players) { DrawNonCombatPlayerDetails(player, position); position.X += inActiveCharInfoTexture.Width - 6f; } yTextPosition.X = position.X + 5f; yButtonPosition.X = position.X + 9f; // Draw Select Button spriteBatch.Draw(statsTexture, yTextPosition, Color.White); spriteBatch.Draw(yButtonTexture, yButtonPosition, Color.White); startTextPosition.X = startingInfoPosition.X - startButtonTexture.Width - 25f; startButtonPosition.X = startingInfoPosition.X - startButtonTexture.Width - 10f; // Draw Back Button spriteBatch.Draw(menuTexture, startTextPosition, Color.White); spriteBatch.Draw(startButtonTexture, startButtonPosition, Color.White); } enum PlankState { Active, InActive, CantUse, } /// <summary> /// Draws Player Details /// </summary> /// <param name="playerIndex">Index of player details to draw</param> /// <param name="position">Position where to draw</param> private void DrawCombatPlayerDetails(CombatantPlayer player, Vector2 position) { SpriteBatch spriteBatch = screenManager.SpriteBatch; PlankState plankState; bool isPortraitActive = false; bool isCharDead = false; Color color; portraitPosition.X = position.X + 7f; portraitPosition.Y = position.Y + 7f; namePosition.X = position.X + 84f; namePosition.Y = position.Y + 12f; levelPosition.X = position.X + 84f; levelPosition.Y = position.Y + 39f; detailPosition.X = position.X + 25f; detailPosition.Y = position.Y + 66f; position.X -= 2; position.Y -= 4; if (player.IsTurnTaken) { plankState = PlankState.CantUse; isPortraitActive = false; } else { plankState = PlankState.InActive; isPortraitActive = true; } if (((CombatEngine.HighlightedCombatant == player) && !player.IsTurnTaken) || (CombatEngine.PrimaryTargetedCombatant == player) || (CombatEngine.SecondaryTargetedCombatants.Contains(player))) { plankState = PlankState.Active; } if (player.IsDeadOrDying) { isCharDead = true; isPortraitActive = false; plankState = PlankState.CantUse; } // Draw Info Slab if (plankState == PlankState.Active) { color = activeNameColor; spriteBatch.Draw(activeCharInfoTexture, position, Color.White); // Draw Brackets if ((CombatEngine.HighlightedCombatant == player) && !player.IsTurnTaken) { spriteBatch.Draw(selectionBracketTexture, position, Color.White); } if (isPortraitActive && (CombatEngine.HighlightedCombatant == player) && (CombatEngine.HighlightedCombatant.CombatAction == null) && !CombatEngine.IsDelaying) { position.X += activeCharInfoTexture.Width / 2; position.X -= combatPopupTexture.Width / 2; position.Y -= combatPopupTexture.Height; // Draw Action DrawActionsMenu(position); } } else if (plankState == PlankState.InActive) { color = inActiveNameColor; spriteBatch.Draw(inActiveCharInfoTexture, position, Color.White); } else { color = Color.Black; spriteBatch.Draw(cantUseCharInfoTexture, position, Color.White); } if (isCharDead) { spriteBatch.Draw(deadPortraitTexture, portraitPosition, Color.White); } else { // Draw Player Portrait DrawPortrait(player.Player, portraitPosition, plankState); } // Draw Player Name spriteBatch.DrawString(Fonts.PlayerStatisticsFont, player.Player.Name, namePosition, color); color = Color.Black; // Draw Player Details spriteBatch.DrawString(Fonts.HudDetailFont, "Lvl: " + player.Player.CharacterLevel, levelPosition, color); spriteBatch.DrawString(Fonts.HudDetailFont, "HP: " + player.Statistics.HealthPoints + "/" + player.Player.CharacterStatistics.HealthPoints, detailPosition, color); detailPosition.Y += 30f; spriteBatch.DrawString(Fonts.HudDetailFont, "MP: " + player.Statistics.MagicPoints + "/" + player.Player.CharacterStatistics.MagicPoints, detailPosition, color); } /// <summary> /// Draws Player Details /// </summary> /// <param name="playerIndex">Index of player details to draw</param> /// <param name="position">Position where to draw</param> private void DrawNonCombatPlayerDetails(Player player, Vector2 position) { SpriteBatch spriteBatch = screenManager.SpriteBatch; PlankState plankState; bool isCharDead = false; Color color; portraitPosition.X = position.X + 7f; portraitPosition.Y = position.Y + 7f; namePosition.X = position.X + 84f; namePosition.Y = position.Y + 12f; levelPosition.X = position.X + 84f; levelPosition.Y = position.Y + 39f; detailPosition.X = position.X + 25f; detailPosition.Y = position.Y + 66f; position.X -= 2; position.Y -= 4; plankState = PlankState.Active; // Draw Info Slab if (plankState == PlankState.Active) { color = activeNameColor; spriteBatch.Draw(activeCharInfoTexture, position, Color.White); } else if (plankState == PlankState.InActive) { color = inActiveNameColor; spriteBatch.Draw(inActiveCharInfoTexture, position, Color.White); } else { color = Color.Black; spriteBatch.Draw(cantUseCharInfoTexture, position, Color.White); } if (isCharDead) { spriteBatch.Draw(deadPortraitTexture, portraitPosition, Color.White); } else { // Draw Player Portrait DrawPortrait(player, portraitPosition, plankState); } // Draw Player Name spriteBatch.DrawString(Fonts.PlayerStatisticsFont, player.Name, namePosition, color); color = Color.Black; // Draw Player Details spriteBatch.DrawString(Fonts.HudDetailFont, "Lvl: " + player.CharacterLevel, levelPosition, color); spriteBatch.DrawString(Fonts.HudDetailFont, "HP: " + player.CurrentStatistics.HealthPoints + "/" + player.CharacterStatistics.HealthPoints, detailPosition, color); detailPosition.Y += 30f; spriteBatch.DrawString(Fonts.HudDetailFont, "MP: " + player.CurrentStatistics.MagicPoints + "/" + player.CharacterStatistics.MagicPoints, detailPosition, color); } /// <summary> /// Draw the portrait of the given player at the given position. /// </summary> private void DrawPortrait(Player player, Vector2 position, PlankState plankState) { switch (plankState) { case PlankState.Active: screenManager.SpriteBatch.Draw(player.ActivePortraitTexture, position, Color.White); break; case PlankState.InActive: screenManager.SpriteBatch.Draw(player.InactivePortraitTexture, position, Color.White); break; case PlankState.CantUse: screenManager.SpriteBatch.Draw(player.UnselectablePortraitTexture, position, Color.White); break; } } #endregion #region Combat Action Menu /// <summary> /// The list of entries in the combat action menu. /// </summary> private string[] actionList = new string[5] { "Attack", "Spell", "Item", "Defend", "Flee", }; /// <summary> /// The currently highlighted item. /// </summary> private int highlightedAction = 0; /// <summary> /// Handle user input to the actions menu. /// </summary> public void UpdateActionsMenu() { // cursor up if (InputManager.IsActionTriggered(InputManager.Action.CursorUp)) { if (highlightedAction > 0) { highlightedAction--; } return; } // cursor down if (InputManager.IsActionTriggered(InputManager.Action.CursorDown)) { if (highlightedAction < actionList.Length - 1) { highlightedAction++; } return; } // select an action if (InputManager.IsActionTriggered(InputManager.Action.Ok)) { switch (actionList[highlightedAction]) { case "Attack": { ActionText = "Performing a Melee Attack"; CombatEngine.HighlightedCombatant.CombatAction = new MeleeCombatAction(CombatEngine.HighlightedCombatant); CombatEngine.HighlightedCombatant.CombatAction.Target = CombatEngine.FirstEnemyTarget; } break; case "Spell": { SpellbookScreen spellbookScreen = new SpellbookScreen( CombatEngine.HighlightedCombatant.Character, CombatEngine.HighlightedCombatant.Statistics); spellbookScreen.SpellSelected += new SpellbookScreen.SpellSelectedHandler( spellbookScreen_SpellSelected); Session.ScreenManager.AddScreen(spellbookScreen); } break; case "Item": { InventoryScreen inventoryScreen = new InventoryScreen(true); inventoryScreen.GearSelected += new InventoryScreen.GearSelectedHandler( inventoryScreen_GearSelected); Session.ScreenManager.AddScreen(inventoryScreen); } break; case "Defend": { ActionText = "Defending"; CombatEngine.HighlightedCombatant.CombatAction = new DefendCombatAction( CombatEngine.HighlightedCombatant); CombatEngine.HighlightedCombatant.CombatAction.Start(); } break; case "Flee": CombatEngine.AttemptFlee(); break; } return; } } /// <summary> /// Recieves the spell from the Spellbook screen and casts it. /// </summary> void spellbookScreen_SpellSelected(Spell spell) { if (spell != null) { ActionText = "Casting " + spell.Name; CombatEngine.HighlightedCombatant.CombatAction = new SpellCombatAction(CombatEngine.HighlightedCombatant, spell); if (spell.IsOffensive) { CombatEngine.HighlightedCombatant.CombatAction.Target = CombatEngine.FirstEnemyTarget; } else { CombatEngine.HighlightedCombatant.CombatAction.Target = CombatEngine.HighlightedCombatant; } } } /// <summary> /// Receives the item back from the Inventory screen and uses it. /// </summary> void inventoryScreen_GearSelected(Gear gear) { Item item = gear as Item; if (item != null) { ActionText = "Using " + item.Name; CombatEngine.HighlightedCombatant.CombatAction = new ItemCombatAction(CombatEngine.HighlightedCombatant, item); if (item.IsOffensive) { CombatEngine.HighlightedCombatant.CombatAction.Target = CombatEngine.FirstEnemyTarget; } else { CombatEngine.HighlightedCombatant.CombatAction.Target = CombatEngine.HighlightedCombatant; } } } /// <summary> /// Draws the combat action menu. /// </summary> /// <param name="position">The position of the menu.</param> private void DrawActionsMenu(Vector2 position) { ActionText = "Choose an Action"; SpriteBatch spriteBatch = screenManager.SpriteBatch; Vector2 arrowPosition; float height = 25f; spriteBatch.Draw(combatPopupTexture, position, Color.White); position.Y += 21f; arrowPosition = position; arrowPosition.X += 10f; arrowPosition.Y += 2f; arrowPosition.Y += height * (int)highlightedAction; spriteBatch.Draw(actionTexture, arrowPosition, Color.White); position.Y += 4f; position.X += 50f; // Draw Action Text for (int i = 0; i < actionList.Length; i++) { spriteBatch.DrawString(Fonts.GearInfoFont, actionList[i], position, i == highlightedAction ? selColor : nonSelColor); position.Y += height; } } #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. namespace System.Runtime.Serialization.Json { using System.Runtime.Serialization; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Text; using System.Xml; using System.Collections; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Globalization; using System.Reflection; using System.Security; public sealed class DataContractJsonSerializer : XmlObjectSerializer { private const char BACK_SLASH = '\\'; private const char FORWARD_SLASH = '/'; private const char HIGH_SURROGATE_START = (char)0xd800; private const char LOW_SURROGATE_END = (char)0xdfff; private const char MAX_CHAR = (char)0xfffe; private const char WHITESPACE = ' '; internal IList<Type> knownTypeList; internal DataContractDictionary knownDataContracts; private readonly EmitTypeInformation _emitTypeInformation; private ReadOnlyCollection<Type> _knownTypeCollection; private readonly int _maxItemsInObjectGraph; private readonly bool _serializeReadOnlyTypes; private readonly DateTimeFormat _dateTimeFormat; private readonly bool _useSimpleDictionaryFormat; private readonly DataContractJsonSerializerImpl _serializer; private readonly bool _ignoreExtensionDataObject; public DataContractJsonSerializer(Type type) { _serializer = new DataContractJsonSerializerImpl(type); } public DataContractJsonSerializer(Type type, string rootName) : this(type, rootName, null) { } public DataContractJsonSerializer(Type type, XmlDictionaryString rootName) : this(type, rootName, null) { } public DataContractJsonSerializer(Type type, IEnumerable<Type> knownTypes) { _serializer = new DataContractJsonSerializerImpl(type, knownTypes); } public DataContractJsonSerializer(Type type, string rootName, IEnumerable<Type> knownTypes) : this(type, new DataContractJsonSerializerSettings() { RootName = rootName, KnownTypes = knownTypes }) { } public DataContractJsonSerializer(Type type, XmlDictionaryString rootName, IEnumerable<Type> knownTypes) { _serializer = new DataContractJsonSerializerImpl(type, rootName, knownTypes); } public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings settings) { _serializer = new DataContractJsonSerializerImpl(type, settings); } public bool IgnoreExtensionDataObject { get { return _ignoreExtensionDataObject; } } public ReadOnlyCollection<Type> KnownTypes { get { if (_knownTypeCollection == null) { if (knownTypeList != null) { _knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList); } else { _knownTypeCollection = new ReadOnlyCollection<Type>(Array.Empty<Type>()); } } return _knownTypeCollection; } } internal override DataContractDictionary KnownDataContracts { get { if (this.knownDataContracts == null && this.knownTypeList != null) { // This assignment may be performed concurrently and thus is a race condition. // It's safe, however, because at worse a new (and identical) dictionary of // data contracts will be created and re-assigned to this field. Introduction // of a lock here could lead to deadlocks. this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList); } return this.knownDataContracts; } } public int MaxItemsInObjectGraph { get { return _maxItemsInObjectGraph; } } public DateTimeFormat DateTimeFormat { get { return _dateTimeFormat; } } public EmitTypeInformation EmitTypeInformation { get { return _emitTypeInformation; } } public bool SerializeReadOnlyTypes { get { return _serializeReadOnlyTypes; } } public bool UseSimpleDictionaryFormat { get { return _useSimpleDictionaryFormat; } } internal static void CheckIfTypeIsReference(DataContract dataContract) { if (dataContract.IsReference) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError( XmlObjectSerializer.CreateSerializationException(SR.Format( SR.JsonUnsupportedForIsReference, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.IsReference))); } } internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType) { DataContract contract = DataContractSerializer.GetDataContract(declaredTypeContract, declaredType, objectType); CheckIfTypeIsReference(contract); return contract; } public override void WriteObject(Stream stream, object graph) { _serializer.WriteObject(stream, graph); } public override void WriteObject(XmlWriter writer, object graph) { _serializer.WriteObject(writer, graph); } public override void WriteObject(XmlDictionaryWriter writer, object graph) { _serializer.WriteObject(writer, graph); } public override object ReadObject(Stream stream) { return _serializer.ReadObject(stream); } public override object ReadObject(XmlReader reader) { return _serializer.ReadObject(reader); } public override object ReadObject(XmlReader reader, bool verifyObjectName) { return _serializer.ReadObject(reader, verifyObjectName); } public override object ReadObject(XmlDictionaryReader reader) { return _serializer.ReadObject(reader); } private List<Type> GetKnownTypesFromContext(XmlObjectSerializerContext context, IList<Type> serializerKnownTypeList) { List<Type> knownTypesList = new List<Type>(); if (context != null) { List<XmlQualifiedName> stableNames = new List<XmlQualifiedName>(); Dictionary<XmlQualifiedName, DataContract>[] entries = context.scopedKnownTypes.dataContractDictionaries; if (entries != null) { for (int i = 0; i < entries.Length; i++) { Dictionary<XmlQualifiedName, DataContract> entry = entries[i]; if (entry != null) { foreach (KeyValuePair<XmlQualifiedName, DataContract> pair in entry) { if (!stableNames.Contains(pair.Key)) { stableNames.Add(pair.Key); knownTypesList.Add(pair.Value.UnderlyingType); } } } } } if (serializerKnownTypeList != null) { knownTypesList.AddRange(serializerKnownTypeList); } } return knownTypesList; } internal static void InvokeOnSerializing(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context) { if (contract is ClassDataContract) { ClassDataContract classContract = contract as ClassDataContract; if (classContract.BaseContract != null) InvokeOnSerializing(value, classContract.BaseContract, context); if (classContract.OnSerializing != null) { bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null); try { classContract.OnSerializing.Invoke(value, new object[] { context.GetStreamingContext() }); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } catch (TargetInvocationException targetInvocationException) { if (targetInvocationException.InnerException == null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers throw targetInvocationException.InnerException; } } } } internal static void InvokeOnSerialized(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context) { if (contract is ClassDataContract) { ClassDataContract classContract = contract as ClassDataContract; if (classContract.BaseContract != null) InvokeOnSerialized(value, classContract.BaseContract, context); if (classContract.OnSerialized != null) { bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null); try { classContract.OnSerialized.Invoke(value, new object[] { context.GetStreamingContext() }); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } catch (TargetInvocationException targetInvocationException) { if (targetInvocationException.InnerException == null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers throw targetInvocationException.InnerException; } } } } internal static void InvokeOnDeserializing(object value, DataContract contract, XmlObjectSerializerReadContextComplexJson context) { if (contract is ClassDataContract) { ClassDataContract classContract = contract as ClassDataContract; if (classContract.BaseContract != null) InvokeOnDeserializing(value, classContract.BaseContract, context); if (classContract.OnDeserializing != null) { bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try { classContract.OnDeserializing.Invoke(value, new object[] { context.GetStreamingContext() }); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForRead(securityException); } else { throw; } } catch (TargetInvocationException targetInvocationException) { if (targetInvocationException.InnerException == null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers throw targetInvocationException.InnerException; } } } } internal static void InvokeOnDeserialized(object value, DataContract contract, XmlObjectSerializerReadContextComplexJson context) { if (contract is ClassDataContract) { ClassDataContract classContract = contract as ClassDataContract; if (classContract.BaseContract != null) InvokeOnDeserialized(value, classContract.BaseContract, context); if (classContract.OnDeserialized != null) { bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try { classContract.OnDeserialized.Invoke(value, new object[] { context.GetStreamingContext() }); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForRead(securityException); } else { throw; } } catch (TargetInvocationException targetInvocationException) { if (targetInvocationException.InnerException == null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers throw targetInvocationException.InnerException; } } } } internal static bool CharacterNeedsEscaping(char ch) { return (ch == FORWARD_SLASH || ch == JsonGlobals.QuoteChar || ch < WHITESPACE || ch == BACK_SLASH || (ch >= HIGH_SURROGATE_START && (ch <= LOW_SURROGATE_END || ch >= MAX_CHAR))); } internal static bool CheckIfJsonNameRequiresMapping(string jsonName) { if (jsonName != null) { if (!DataContract.IsValidNCName(jsonName)) { return true; } for (int i = 0; i < jsonName.Length; i++) { if (CharacterNeedsEscaping(jsonName[i])) { return true; } } } return false; } internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString jsonName) { return (jsonName == null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value); } internal static string ConvertXmlNameToJsonName(string xmlName) { return XmlConvert.DecodeName(xmlName); } internal static XmlDictionaryString ConvertXmlNameToJsonName(XmlDictionaryString xmlName) { return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value)); } internal static object ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context) { return JsonDataContract.GetJsonDataContract(contract).ReadJsonValue(reader, context); } internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { contract.WriteJsonValue(writer, graph, context, declaredTypeHandle); } public override void WriteStartObject(XmlWriter writer, object graph) { _serializer.WriteStartObject(writer, graph); } public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { _serializer.WriteStartObject(writer, graph); } public override void WriteObjectContent(XmlWriter writer, object graph) { _serializer.WriteObjectContent(writer, graph); } public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { _serializer.WriteObjectContent(writer, graph); } public override void WriteEndObject(XmlWriter writer) { _serializer.WriteEndObject(writer); } public override void WriteEndObject(XmlDictionaryWriter writer) { _serializer.WriteEndObject(writer); } public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return _serializer.ReadObject(reader, verifyObjectName); } public override bool IsStartObject(XmlReader reader) { return _serializer.IsStartObject(reader); } public override bool IsStartObject(XmlDictionaryReader reader) { return _serializer.IsStartObject(reader); } } internal sealed class DataContractJsonSerializerImpl : XmlObjectSerializer { internal IList<Type> knownTypeList; internal DataContractDictionary knownDataContracts; private EmitTypeInformation _emitTypeInformation; private bool _ignoreExtensionDataObject; private ReadOnlyCollection<Type> _knownTypeCollection; private int _maxItemsInObjectGraph; private DataContract _rootContract; // post-surrogate private XmlDictionaryString _rootName; private bool _rootNameRequiresMapping; private Type _rootType; private bool _serializeReadOnlyTypes; private DateTimeFormat _dateTimeFormat; private bool _useSimpleDictionaryFormat; public DataContractJsonSerializerImpl(Type type) : this(type, (IEnumerable<Type>)null) { } public DataContractJsonSerializerImpl(Type type, IEnumerable<Type> knownTypes) : this(type, null, knownTypes, int.MaxValue, false, false) { } public DataContractJsonSerializerImpl(Type type, XmlDictionaryString rootName, IEnumerable<Type> knownTypes) : this(type, rootName, knownTypes, int.MaxValue, false, false) { } internal DataContractJsonSerializerImpl(Type type, XmlDictionaryString rootName, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool alwaysEmitTypeInformation) { EmitTypeInformation emitTypeInformation = alwaysEmitTypeInformation ? EmitTypeInformation.Always : EmitTypeInformation.AsNeeded; Initialize(type, rootName, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, emitTypeInformation, false, null, false); } public DataContractJsonSerializerImpl(Type type, DataContractJsonSerializerSettings settings) { if (settings == null) { settings = new DataContractJsonSerializerSettings(); } XmlDictionaryString rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName); Initialize(type, rootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject, settings.EmitTypeInformation, settings.SerializeReadOnlyTypes, settings.DateTimeFormat, settings.UseSimpleDictionaryFormat); } public ReadOnlyCollection<Type> KnownTypes { get { if (_knownTypeCollection == null) { if (knownTypeList != null) { _knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList); } else { _knownTypeCollection = new ReadOnlyCollection<Type>(Array.Empty<Type>()); } } return _knownTypeCollection; } } internal override DataContractDictionary KnownDataContracts { get { if (this.knownDataContracts == null && this.knownTypeList != null) { // This assignment may be performed concurrently and thus is a race condition. // It's safe, however, because at worse a new (and identical) dictionary of // data contracts will be created and re-assigned to this field. Introduction // of a lock here could lead to deadlocks. this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList); } return this.knownDataContracts; } } internal int MaxItemsInObjectGraph { get { return _maxItemsInObjectGraph; } } internal bool AlwaysEmitTypeInformation { get { return _emitTypeInformation == EmitTypeInformation.Always; } } public EmitTypeInformation EmitTypeInformation { get { return _emitTypeInformation; } } public bool SerializeReadOnlyTypes { get { return _serializeReadOnlyTypes; } } public DateTimeFormat DateTimeFormat { get { return _dateTimeFormat; } } public bool UseSimpleDictionaryFormat { get { return _useSimpleDictionaryFormat; } } private DataContract RootContract { get { if (_rootContract == null) { _rootContract = DataContract.GetDataContract(_rootType); CheckIfTypeIsReference(_rootContract); } return _rootContract; } } private XmlDictionaryString RootName { get { return _rootName ?? JsonGlobals.rootDictionaryString; } } public override bool IsStartObject(XmlReader reader) { // No need to pass in DateTimeFormat to JsonReaderDelegator: no DateTimes will be read in IsStartObject return IsStartObjectHandleExceptions(new JsonReaderDelegator(reader)); } public override bool IsStartObject(XmlDictionaryReader reader) { // No need to pass in DateTimeFormat to JsonReaderDelegator: no DateTimes will be read in IsStartObject return IsStartObjectHandleExceptions(new JsonReaderDelegator(reader)); } public override object ReadObject(Stream stream) { CheckNull(stream, nameof(stream)); return ReadObject(JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max)); } public override object ReadObject(XmlReader reader) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), true); } public override object ReadObject(XmlReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), verifyObjectName); } public override object ReadObject(XmlDictionaryReader reader) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), true); // verifyObjectName } public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), verifyObjectName); } public override void WriteEndObject(XmlWriter writer) { // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in end object WriteEndObjectHandleExceptions(new JsonWriterDelegator(writer)); } public override void WriteEndObject(XmlDictionaryWriter writer) { // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in end object WriteEndObjectHandleExceptions(new JsonWriterDelegator(writer)); } public override void WriteObject(Stream stream, object graph) { CheckNull(stream, nameof(stream)); XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, false); // ownsStream WriteObject(jsonWriter, graph); jsonWriter.Flush(); } public override void WriteObject(XmlWriter writer, object graph) { WriteObjectHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } public override void WriteObject(XmlDictionaryWriter writer, object graph) { WriteObjectHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } public override void WriteObjectContent(XmlWriter writer, object graph) { WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } public override void WriteStartObject(XmlWriter writer, object graph) { // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in start object WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph); } public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in start object WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph); } internal static bool CheckIfJsonNameRequiresMapping(string jsonName) { if (jsonName != null) { if (!DataContract.IsValidNCName(jsonName)) { return true; } for (int i = 0; i < jsonName.Length; i++) { if (XmlJsonWriter.CharacterNeedsEscaping(jsonName[i])) { return true; } } } return false; } internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString jsonName) { return (jsonName == null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value); } internal static bool CheckIfXmlNameRequiresMapping(string xmlName) { return (xmlName == null) ? false : CheckIfJsonNameRequiresMapping(ConvertXmlNameToJsonName(xmlName)); } internal static bool CheckIfXmlNameRequiresMapping(XmlDictionaryString xmlName) { return (xmlName == null) ? false : CheckIfXmlNameRequiresMapping(xmlName.Value); } internal static string ConvertXmlNameToJsonName(string xmlName) { return XmlConvert.DecodeName(xmlName); } internal static XmlDictionaryString ConvertXmlNameToJsonName(XmlDictionaryString xmlName) { return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value)); } internal static bool IsJsonLocalName(XmlReaderDelegator reader, string elementName) { string name; if (XmlObjectSerializerReadContextComplexJson.TryGetJsonLocalName(reader, out name)) { return (elementName == name); } return false; } internal static object ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context) { return JsonDataContract.GetJsonDataContract(contract).ReadJsonValue(reader, context); } internal static void WriteJsonNull(XmlWriterDelegator writer) { writer.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.nullString); // prefix // namespace } internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { contract.WriteJsonValue(writer, graph, context, declaredTypeHandle); } internal override Type GetDeserializeType() { return _rootType; } internal override Type GetSerializeType(object graph) { return (graph == null) ? _rootType : graph.GetType(); } internal override bool InternalIsStartObject(XmlReaderDelegator reader) { if (IsRootElement(reader, RootContract, RootName, XmlDictionaryString.Empty)) { return true; } return IsJsonLocalName(reader, RootName.Value); } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) { if (MaxItemsInObjectGraph == 0) { throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)); } if (verifyObjectName) { if (!InternalIsStartObject(xmlReader)) { throw XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElement, XmlDictionaryString.Empty, RootName), xmlReader); } } else if (!IsStartElement(xmlReader)) { throw XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElementAtDeserialize, XmlNodeType.Element), xmlReader); } DataContract contract = RootContract; if (contract.IsPrimitive && object.ReferenceEquals(contract.UnderlyingType, _rootType))// handle Nullable<T> differently { return DataContractJsonSerializerImpl.ReadJsonValue(contract, xmlReader, null); } XmlObjectSerializerReadContextComplexJson context = XmlObjectSerializerReadContextComplexJson.CreateContext(this, contract); return context.InternalDeserialize(xmlReader, _rootType, contract, null, null); } internal override void InternalWriteEndObject(XmlWriterDelegator writer) { writer.WriteEndElement(); } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph) { InternalWriteStartObject(writer, graph); InternalWriteObjectContent(writer, graph); InternalWriteEndObject(writer); } internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) { if (MaxItemsInObjectGraph == 0) { throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)); } DataContract contract = RootContract; Type declaredType = contract.UnderlyingType; Type graphType = (graph == null) ? declaredType : graph.GetType(); //if (dataContractSurrogate != null) //{ // graph = DataContractSerializer.SurrogateToDataContractType(dataContractSurrogate, graph, declaredType, ref graphType); //} if (graph == null) { WriteJsonNull(writer); } else { if (declaredType == graphType) { if (contract.CanContainReferences) { XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, contract); context.OnHandleReference(writer, graph, true); // canContainReferences context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle); } else { DataContractJsonSerializerImpl.WriteJsonValue(JsonDataContract.GetJsonDataContract(contract), writer, graph, null, declaredType.TypeHandle); // XmlObjectSerializerWriteContextComplexJson } } else { XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, RootContract); contract = DataContractJsonSerializerImpl.GetDataContract(contract, declaredType, graphType); if (contract.CanContainReferences) { context.OnHandleReference(writer, graph, true); // canContainCyclicReference context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType); } else { context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle); } } } } internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph) { if (_rootNameRequiresMapping) { writer.WriteStartElement("a", JsonGlobals.itemString, JsonGlobals.itemString); writer.WriteAttributeString(null, JsonGlobals.itemString, null, RootName.Value); } else { writer.WriteStartElement(RootName, XmlDictionaryString.Empty); } } private void AddCollectionItemTypeToKnownTypes(Type knownType) { Type itemType; Type typeToCheck = knownType; while (CollectionDataContract.IsCollection(typeToCheck, out itemType)) { if (itemType.IsGenericType && (itemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue)) { itemType = Globals.TypeOfKeyValuePair.MakeGenericType(itemType.GenericTypeArguments); } this.knownTypeList.Add(itemType); typeToCheck = itemType; } } private void Initialize(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, EmitTypeInformation emitTypeInformation, bool serializeReadOnlyTypes, DateTimeFormat dateTimeFormat, bool useSimpleDictionaryFormat) { CheckNull(type, nameof(type)); _rootType = type; if (knownTypes != null) { this.knownTypeList = new List<Type>(); foreach (Type knownType in knownTypes) { this.knownTypeList.Add(knownType); if (knownType != null) { AddCollectionItemTypeToKnownTypes(knownType); } } } if (maxItemsInObjectGraph < 0) { throw new ArgumentOutOfRangeException(nameof(maxItemsInObjectGraph), SR.ValueMustBeNonNegative); } _maxItemsInObjectGraph = maxItemsInObjectGraph; _ignoreExtensionDataObject = ignoreExtensionDataObject; _emitTypeInformation = emitTypeInformation; _serializeReadOnlyTypes = serializeReadOnlyTypes; _dateTimeFormat = dateTimeFormat; _useSimpleDictionaryFormat = useSimpleDictionaryFormat; } private void Initialize(Type type, XmlDictionaryString rootName, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, EmitTypeInformation emitTypeInformation, bool serializeReadOnlyTypes, DateTimeFormat dateTimeFormat, bool useSimpleDictionaryFormat) { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, emitTypeInformation, serializeReadOnlyTypes, dateTimeFormat, useSimpleDictionaryFormat); _rootName = ConvertXmlNameToJsonName(rootName); _rootNameRequiresMapping = CheckIfJsonNameRequiresMapping(_rootName); } internal static void CheckIfTypeIsReference(DataContract dataContract) { if (dataContract.IsReference) { throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonUnsupportedForIsReference, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.IsReference)); } } internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType) { DataContract contract = DataContractSerializer.GetDataContract(declaredTypeContract, declaredType, objectType); CheckIfTypeIsReference(contract); return contract; } } }
/* The MIT License (MIT) Copyright (c) 2007 - 2020 Microting A/S 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.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microting.eForm.Infrastructure.Constants; using Microting.eForm.Infrastructure.Data.Entities; using NUnit.Framework; namespace eFormSDK.InSight.Tests { [TestFixture] public class OptionTranslationUTest : DbTestFixture { [Test] public async Task OptionTranslation_Create_DoesCreate_W_MicrotingUid() { //Arrange Random rnd = new Random(); bool randomBool = rnd.Next(0, 2) > 0; QuestionSet questionSet = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, PossiblyDeployed = randomBool }; await questionSet.Create(DbContext).ConfigureAwait(false); Question question = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, QuestionSetId = questionSet.Id }; await question.Create(DbContext).ConfigureAwait(false); Option option = new Option { Weight = rnd.Next(1, 255), OptionIndex = rnd.Next(1, 255), WeightValue = rnd.Next(1, 255), QuestionId = question.Id }; await option.Create(DbContext).ConfigureAwait(false); Language language = new Language { LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString() }; await language.Create(DbContext).ConfigureAwait(false); OptionTranslation optionTranslation = new OptionTranslation { LanguageId = language.Id, OptionId = option.Id, Name = Guid.NewGuid().ToString(), MicrotingUid = rnd.Next(1, 255) }; // Act await optionTranslation.Create(DbContext).ConfigureAwait(false); List<OptionTranslation> optionTranslations = DbContext.OptionTranslations.AsNoTracking().ToList(); List<OptionTranslationVersion> optionTranslationVersions = DbContext.OptionTranslationVersions.AsNoTracking().ToList(); // Assert Assert.NotNull(optionTranslations); Assert.NotNull(optionTranslationVersions); Assert.AreEqual(1, optionTranslations.Count); Assert.AreEqual(1, optionTranslationVersions.Count); Assert.AreEqual(optionTranslation.Name, optionTranslations[0].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslations[0].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslations[0].LanguageId); Assert.AreEqual(optionTranslation.MicrotingUid, optionTranslations[0].MicrotingUid); Assert.AreEqual(optionTranslation.Name, optionTranslationVersions[0].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslationVersions[0].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslationVersions[0].LanguageId); Assert.AreEqual(optionTranslation.MicrotingUid, optionTranslationVersions[0].MicrotingUid); } [Test] public async Task OptionTranslation_Create_DoesCreate_WO_MicrotingUid() { //Arrange Random rnd = new Random(); bool randomBool = rnd.Next(0, 2) > 0; QuestionSet questionSet = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, PossiblyDeployed = randomBool }; await questionSet.Create(DbContext).ConfigureAwait(false); Question question = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, QuestionSetId = questionSet.Id }; await question.Create(DbContext).ConfigureAwait(false); Option option = new Option { Weight = rnd.Next(1, 255), OptionIndex = rnd.Next(1, 255), WeightValue = rnd.Next(1, 255), QuestionId = question.Id }; await option.Create(DbContext).ConfigureAwait(false); Language language = new Language { LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString() }; await language.Create(DbContext).ConfigureAwait(false); OptionTranslation optionTranslation = new OptionTranslation { LanguageId = language.Id, OptionId = option.Id, Name = Guid.NewGuid().ToString(), }; // Act await optionTranslation.Create(DbContext).ConfigureAwait(false); List<OptionTranslation> optionTranslations = DbContext.OptionTranslations.AsNoTracking().ToList(); List<OptionTranslationVersion> optionTranslationVersions = DbContext.OptionTranslationVersions.AsNoTracking().ToList(); // Assert Assert.NotNull(optionTranslations); Assert.NotNull(optionTranslationVersions); Assert.AreEqual(1, optionTranslations.Count); Assert.AreEqual(1, optionTranslationVersions.Count); Assert.AreEqual(optionTranslation.Name, optionTranslations[0].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslations[0].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslations[0].LanguageId); Assert.AreEqual(null, optionTranslations[0].MicrotingUid); Assert.AreEqual(optionTranslation.Name, optionTranslationVersions[0].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslationVersions[0].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslationVersions[0].LanguageId); Assert.AreEqual(null, optionTranslationVersions[0].MicrotingUid); } [Test] public async Task OptionTranslation_Update_DoesUpdate_W_MicrotingUid() { //Arrange Random rnd = new Random(); bool randomBool = rnd.Next(0, 2) > 0; QuestionSet questionSet = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, PossiblyDeployed = randomBool }; await questionSet.Create(DbContext).ConfigureAwait(false); QuestionSet questionSet2 = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, PossiblyDeployed = randomBool }; await questionSet2.Create(DbContext).ConfigureAwait(false); Question question = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, QuestionSetId = questionSet.Id }; await question.Create(DbContext).ConfigureAwait(false); Question question2 = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, QuestionSetId = questionSet.Id }; await question2.Create(DbContext).ConfigureAwait(false); Option option = new Option { Weight = rnd.Next(1, 255), OptionIndex = rnd.Next(1, 255), WeightValue = rnd.Next(1, 255), QuestionId = question.Id }; await option.Create(DbContext).ConfigureAwait(false); Option option2 = new Option { Weight = rnd.Next(1, 255), OptionIndex = rnd.Next(1, 255), WeightValue = rnd.Next(1, 255), QuestionId = question.Id }; await option2.Create(DbContext).ConfigureAwait(false); Language language = new Language { LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString() }; await language.Create(DbContext).ConfigureAwait(false); Language language2 = new Language { LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString() }; await language2.Create(DbContext).ConfigureAwait(false); OptionTranslation optionTranslation = new OptionTranslation { LanguageId = language.Id, OptionId = option.Id, Name = Guid.NewGuid().ToString(), MicrotingUid = rnd.Next(1, 255) }; await optionTranslation.Create(DbContext).ConfigureAwait(false); var oldLanguageId = optionTranslation.LanguageId; var oldOptionId = optionTranslation.OptionId; var oldName = optionTranslation.Name; var oldMicrotingUid = optionTranslation.MicrotingUid; optionTranslation.Name = Guid.NewGuid().ToString(); optionTranslation.LanguageId = language2.Id; optionTranslation.MicrotingUid = rnd.Next(1, 255); optionTranslation.OptionId = option2.Id; // Act await optionTranslation.Update(DbContext).ConfigureAwait(false); List<OptionTranslation> optionTranslations = DbContext.OptionTranslations.AsNoTracking().ToList(); List<OptionTranslationVersion> optionTranslationVersions = DbContext.OptionTranslationVersions.AsNoTracking().ToList(); // Assert Assert.NotNull(optionTranslations); Assert.NotNull(optionTranslationVersions); Assert.AreEqual(1, optionTranslations.Count); Assert.AreEqual(2, optionTranslationVersions.Count); Assert.AreEqual(optionTranslation.Name, optionTranslations[0].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslations[0].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslations[0].LanguageId); Assert.AreEqual(optionTranslation.MicrotingUid, optionTranslations[0].MicrotingUid); Assert.AreEqual(oldName, optionTranslationVersions[0].Name); Assert.AreEqual(oldOptionId, optionTranslationVersions[0].OptionId); Assert.AreEqual(oldLanguageId, optionTranslationVersions[0].LanguageId); Assert.AreEqual(oldMicrotingUid, optionTranslationVersions[0].MicrotingUid); Assert.AreEqual(optionTranslation.Name, optionTranslationVersions[1].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslationVersions[1].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslationVersions[1].LanguageId); Assert.AreEqual(optionTranslation.MicrotingUid, optionTranslationVersions[1].MicrotingUid); } [Test] public async Task OptionTranslation_Update_DoesUpdate_WO_MicrotingUid() { //Arrange Random rnd = new Random(); bool randomBool = rnd.Next(0, 2) > 0; QuestionSet questionSet = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, PossiblyDeployed = randomBool }; await questionSet.Create(DbContext).ConfigureAwait(false); QuestionSet questionSet2 = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, PossiblyDeployed = randomBool }; await questionSet2.Create(DbContext).ConfigureAwait(false); Question question = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, QuestionSetId = questionSet.Id }; await question.Create(DbContext).ConfigureAwait(false); Question question2 = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, QuestionSetId = questionSet.Id }; await question2.Create(DbContext).ConfigureAwait(false); Option option = new Option { Weight = rnd.Next(1, 255), OptionIndex = rnd.Next(1, 255), WeightValue = rnd.Next(1, 255), QuestionId = question.Id }; await option.Create(DbContext).ConfigureAwait(false); Option option2 = new Option { Weight = rnd.Next(1, 255), OptionIndex = rnd.Next(1, 255), WeightValue = rnd.Next(1, 255), QuestionId = question.Id }; await option2.Create(DbContext).ConfigureAwait(false); Language language = new Language { LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString() }; await language.Create(DbContext).ConfigureAwait(false); Language language2 = new Language { LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString() }; await language2.Create(DbContext).ConfigureAwait(false); OptionTranslation optionTranslation = new OptionTranslation { LanguageId = language.Id, OptionId = option.Id, Name = Guid.NewGuid().ToString() }; await optionTranslation.Create(DbContext).ConfigureAwait(false); var oldLanguageId = optionTranslation.LanguageId; var oldOptionId = optionTranslation.OptionId; var oldName = optionTranslation.Name; optionTranslation.Name = Guid.NewGuid().ToString(); optionTranslation.LanguageId = language2.Id; optionTranslation.OptionId = option2.Id; // Act await optionTranslation.Update(DbContext).ConfigureAwait(false); List<OptionTranslation> optionTranslations = DbContext.OptionTranslations.AsNoTracking().ToList(); List<OptionTranslationVersion> optionTranslationVersions = DbContext.OptionTranslationVersions.AsNoTracking().ToList(); // Assert Assert.NotNull(optionTranslations); Assert.NotNull(optionTranslationVersions); Assert.AreEqual(1, optionTranslations.Count); Assert.AreEqual(2, optionTranslationVersions.Count); Assert.AreEqual(optionTranslation.Name, optionTranslations[0].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslations[0].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslations[0].LanguageId); Assert.AreEqual(optionTranslation.MicrotingUid, optionTranslations[0].MicrotingUid); Assert.AreEqual(oldName, optionTranslationVersions[0].Name); Assert.AreEqual(oldOptionId, optionTranslationVersions[0].OptionId); Assert.AreEqual(oldLanguageId, optionTranslationVersions[0].LanguageId); Assert.AreEqual(null, optionTranslationVersions[0].MicrotingUid); Assert.AreEqual(optionTranslation.Name, optionTranslationVersions[1].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslationVersions[1].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslationVersions[1].LanguageId); Assert.AreEqual(null, optionTranslationVersions[1].MicrotingUid); } [Test] public async Task OptionTranslation_Update_DoesUpdate_W_MicrotingUid_RemovesUid() { //Arrange Random rnd = new Random(); bool randomBool = rnd.Next(0, 2) > 0; QuestionSet questionSet = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, PossiblyDeployed = randomBool }; await questionSet.Create(DbContext).ConfigureAwait(false); QuestionSet questionSet2 = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, PossiblyDeployed = randomBool }; await questionSet2.Create(DbContext).ConfigureAwait(false); Question question = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, QuestionSetId = questionSet.Id }; await question.Create(DbContext).ConfigureAwait(false); Question question2 = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, QuestionSetId = questionSet.Id }; await question2.Create(DbContext).ConfigureAwait(false); Option option = new Option { Weight = rnd.Next(1, 255), OptionIndex = rnd.Next(1, 255), WeightValue = rnd.Next(1, 255), QuestionId = question.Id }; await option.Create(DbContext).ConfigureAwait(false); Option option2 = new Option { Weight = rnd.Next(1, 255), OptionIndex = rnd.Next(1, 255), WeightValue = rnd.Next(1, 255), QuestionId = question.Id }; await option2.Create(DbContext).ConfigureAwait(false); Language language = new Language { LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString() }; await language.Create(DbContext).ConfigureAwait(false); Language language2 = new Language { LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString() }; await language2.Create(DbContext).ConfigureAwait(false); OptionTranslation optionTranslation = new OptionTranslation { LanguageId = language.Id, OptionId = option.Id, Name = Guid.NewGuid().ToString(), MicrotingUid = rnd.Next(1, 255) }; await optionTranslation.Create(DbContext).ConfigureAwait(false); var oldLanguageId = optionTranslation.LanguageId; var oldOptionId = optionTranslation.OptionId; var oldName = optionTranslation.Name; var oldMicrotingUid = optionTranslation.MicrotingUid; optionTranslation.Name = Guid.NewGuid().ToString(); optionTranslation.LanguageId = language2.Id; optionTranslation.MicrotingUid = null; optionTranslation.OptionId = option2.Id; // Act await optionTranslation.Update(DbContext).ConfigureAwait(false); List<OptionTranslation> optionTranslations = DbContext.OptionTranslations.AsNoTracking().ToList(); List<OptionTranslationVersion> optionTranslationVersions = DbContext.OptionTranslationVersions.AsNoTracking().ToList(); // Assert Assert.NotNull(optionTranslations); Assert.NotNull(optionTranslationVersions); Assert.AreEqual(1, optionTranslations.Count); Assert.AreEqual(2, optionTranslationVersions.Count); Assert.AreEqual(optionTranslation.Name, optionTranslations[0].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslations[0].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslations[0].LanguageId); Assert.AreEqual(null, optionTranslations[0].MicrotingUid); Assert.AreEqual(oldName, optionTranslationVersions[0].Name); Assert.AreEqual(oldOptionId, optionTranslationVersions[0].OptionId); Assert.AreEqual(oldLanguageId, optionTranslationVersions[0].LanguageId); Assert.AreEqual(oldMicrotingUid, optionTranslationVersions[0].MicrotingUid); Assert.AreEqual(optionTranslation.Name, optionTranslationVersions[1].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslationVersions[1].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslationVersions[1].LanguageId); Assert.AreEqual(null, optionTranslationVersions[1].MicrotingUid); } [Test] public async Task OptionTranslation_Update_DoesUpdate_WO_MicrotingUid_AddsUid() { //Arrange Random rnd = new Random(); bool randomBool = rnd.Next(0, 2) > 0; QuestionSet questionSet = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, PossiblyDeployed = randomBool }; await questionSet.Create(DbContext).ConfigureAwait(false); QuestionSet questionSet2 = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, PossiblyDeployed = randomBool }; await questionSet2.Create(DbContext).ConfigureAwait(false); Question question = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, QuestionSetId = questionSet.Id }; await question.Create(DbContext).ConfigureAwait(false); Question question2 = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, QuestionSetId = questionSet.Id }; await question2.Create(DbContext).ConfigureAwait(false); Option option = new Option { Weight = rnd.Next(1, 255), OptionIndex = rnd.Next(1, 255), WeightValue = rnd.Next(1, 255), QuestionId = question.Id }; await option.Create(DbContext).ConfigureAwait(false); Option option2 = new Option { Weight = rnd.Next(1, 255), OptionIndex = rnd.Next(1, 255), WeightValue = rnd.Next(1, 255), QuestionId = question.Id }; await option2.Create(DbContext).ConfigureAwait(false); Language language = new Language { LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString() }; await language.Create(DbContext).ConfigureAwait(false); Language language2 = new Language { LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString() }; await language2.Create(DbContext).ConfigureAwait(false); OptionTranslation optionTranslation = new OptionTranslation { LanguageId = language.Id, OptionId = option.Id, Name = Guid.NewGuid().ToString() }; await optionTranslation.Create(DbContext).ConfigureAwait(false); var oldLanguageId = optionTranslation.LanguageId; var oldOptionId = optionTranslation.OptionId; var oldName = optionTranslation.Name; optionTranslation.Name = Guid.NewGuid().ToString(); optionTranslation.LanguageId = language2.Id; optionTranslation.OptionId = option2.Id; optionTranslation.MicrotingUid = rnd.Next(1, 255); // Act await optionTranslation.Update(DbContext).ConfigureAwait(false); List<OptionTranslation> optionTranslations = DbContext.OptionTranslations.AsNoTracking().ToList(); List<OptionTranslationVersion> optionTranslationVersions = DbContext.OptionTranslationVersions.AsNoTracking().ToList(); // Assert Assert.NotNull(optionTranslations); Assert.NotNull(optionTranslationVersions); Assert.AreEqual(1, optionTranslations.Count); Assert.AreEqual(2, optionTranslationVersions.Count); Assert.AreEqual(optionTranslation.Name, optionTranslations[0].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslations[0].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslations[0].LanguageId); Assert.AreEqual(optionTranslation.MicrotingUid, optionTranslations[0].MicrotingUid); Assert.AreEqual(oldName, optionTranslationVersions[0].Name); Assert.AreEqual(oldOptionId, optionTranslationVersions[0].OptionId); Assert.AreEqual(oldLanguageId, optionTranslationVersions[0].LanguageId); Assert.AreEqual(null, optionTranslationVersions[0].MicrotingUid); Assert.AreEqual(optionTranslation.Name, optionTranslationVersions[1].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslationVersions[1].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslationVersions[1].LanguageId); Assert.AreEqual(optionTranslation.MicrotingUid, optionTranslationVersions[1].MicrotingUid); } [Test] public async Task OptionTranslation_Delete_DoesDelete() { //Arrange Random rnd = new Random(); bool randomBool = rnd.Next(0, 2) > 0; QuestionSet questionSet = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, PossiblyDeployed = randomBool }; await questionSet.Create(DbContext).ConfigureAwait(false); Question question = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, QuestionSetId = questionSet.Id }; await question.Create(DbContext).ConfigureAwait(false); Option option = new Option { Weight = rnd.Next(1, 255), OptionIndex = rnd.Next(1, 255), WeightValue = rnd.Next(1, 255), QuestionId = question.Id }; await option.Create(DbContext).ConfigureAwait(false); Language language = new Language { LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString() }; await language.Create(DbContext).ConfigureAwait(false); OptionTranslation optionTranslation = new OptionTranslation { LanguageId = language.Id, OptionId = option.Id, Name = Guid.NewGuid().ToString(), MicrotingUid = rnd.Next(1, 255) }; await optionTranslation.Create(DbContext).ConfigureAwait(false); var oldLanguageId = optionTranslation.LanguageId; var oldOptionId = optionTranslation.OptionId; var oldName = optionTranslation.Name; var oldMicrotingUid = optionTranslation.MicrotingUid; // Act await optionTranslation.Delete(DbContext); List<OptionTranslation> optionTranslations = DbContext.OptionTranslations.AsNoTracking().ToList(); List<OptionTranslationVersion> optionTranslationVersions = DbContext.OptionTranslationVersions.AsNoTracking().ToList(); // Assert Assert.NotNull(optionTranslations); Assert.NotNull(optionTranslationVersions); Assert.AreEqual(1, optionTranslations.Count); Assert.AreEqual(2, optionTranslationVersions.Count); Assert.AreEqual(optionTranslation.Name, optionTranslations[0].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslations[0].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslations[0].LanguageId); Assert.AreEqual(optionTranslation.MicrotingUid, optionTranslations[0].MicrotingUid); Assert.AreEqual(Constants.WorkflowStates.Removed, optionTranslations[0].WorkflowState); Assert.AreEqual(oldName, optionTranslationVersions[0].Name); Assert.AreEqual(oldOptionId, optionTranslationVersions[0].OptionId); Assert.AreEqual(oldLanguageId, optionTranslationVersions[0].LanguageId); Assert.AreEqual(oldMicrotingUid, optionTranslationVersions[0].MicrotingUid); Assert.AreEqual(Constants.WorkflowStates.Created, optionTranslationVersions[0].WorkflowState); Assert.AreEqual(optionTranslation.Name, optionTranslationVersions[1].Name); Assert.AreEqual(optionTranslation.OptionId, optionTranslationVersions[1].OptionId); Assert.AreEqual(optionTranslation.LanguageId, optionTranslationVersions[1].LanguageId); Assert.AreEqual(optionTranslation.MicrotingUid, optionTranslationVersions[1].MicrotingUid); Assert.AreEqual(Constants.WorkflowStates.Removed, optionTranslationVersions[1].WorkflowState); } } }
//------------------------------------------------------------------------------ // <copyright file="CommandBuilder.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.Common { using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Globalization; using System.Text; using System.Text.RegularExpressions; public abstract class DbCommandBuilder : Component { // V1.2.3300 private class ParameterNames { private const string DefaultOriginalPrefix = "Original_"; private const string DefaultIsNullPrefix = "IsNull_"; // we use alternative prefix if the default prefix fails parametername validation private const string AlternativeOriginalPrefix = "original"; private const string AlternativeIsNullPrefix = "isnull"; private const string AlternativeOriginalPrefix2 = "ORIGINAL"; private const string AlternativeIsNullPrefix2 = "ISNULL"; private string _originalPrefix; private string _isNullPrefix; private Regex _parameterNameParser; private DbCommandBuilder _dbCommandBuilder; private string[] _baseParameterNames; private string[] _originalParameterNames; private string[] _nullParameterNames; private bool[] _isMutatedName; private int _count; private int _genericParameterCount; private int _adjustedParameterNameMaxLength; internal ParameterNames(DbCommandBuilder dbCommandBuilder, DbSchemaRow[] schemaRows) { _dbCommandBuilder = dbCommandBuilder; _baseParameterNames = new string[schemaRows.Length]; _originalParameterNames = new string[schemaRows.Length]; _nullParameterNames = new string[schemaRows.Length]; _isMutatedName = new bool[schemaRows.Length]; _count = schemaRows.Length; _parameterNameParser = new Regex(_dbCommandBuilder.ParameterNamePattern, RegexOptions.ExplicitCapture | RegexOptions.Singleline); SetAndValidateNamePrefixes(); _adjustedParameterNameMaxLength = GetAdjustedParameterNameMaxLength(); // Generate the baseparameter names and remove conflicting names // No names will be generated for any name that is rejected due to invalid prefix, regex violation or // name conflict after mutation. // All null values will be replaced with generic parameter names // for (int i = 0; i < schemaRows.Length; i++) { if (null == schemaRows[i]) { continue; } bool isMutatedName = false; string columnName = schemaRows[i].ColumnName; // all names that start with original- or isNullPrefix are invalid if (null != _originalPrefix) { if (columnName.StartsWith(_originalPrefix, StringComparison.OrdinalIgnoreCase)) { continue; } } if (null != _isNullPrefix) { if (columnName.StartsWith(_isNullPrefix, StringComparison.OrdinalIgnoreCase)) { continue; } } // Mutate name if it contains space(s) if (columnName.IndexOf(' ') >= 0) { columnName = columnName.Replace(' ', '_'); isMutatedName = true; } // Validate name against regular expression if (!_parameterNameParser.IsMatch(columnName)) { continue; } // Validate name against adjusted max parametername length if (columnName.Length > _adjustedParameterNameMaxLength) { continue; } _baseParameterNames[i] = columnName; _isMutatedName[i] = isMutatedName; } EliminateConflictingNames(); // Generate names for original- and isNullparameters // no names will be generated if the prefix failed parametername validation for (int i = 0; i < schemaRows.Length; i++) { if (null != _baseParameterNames[i]) { if (null != _originalPrefix) { _originalParameterNames[i] = _originalPrefix + _baseParameterNames[i]; } if (null != _isNullPrefix) { // don't bother generating an 'IsNull' name if it's not used if (schemaRows[i].AllowDBNull) { _nullParameterNames[i] = _isNullPrefix + _baseParameterNames[i]; } } } } ApplyProviderSpecificFormat(); GenerateMissingNames(schemaRows); } private void SetAndValidateNamePrefixes() { if (_parameterNameParser.IsMatch(DefaultIsNullPrefix)) { _isNullPrefix = DefaultIsNullPrefix; } else if (_parameterNameParser.IsMatch(AlternativeIsNullPrefix)) { _isNullPrefix = AlternativeIsNullPrefix; } else if (_parameterNameParser.IsMatch(AlternativeIsNullPrefix2)) { _isNullPrefix = AlternativeIsNullPrefix2; } else { _isNullPrefix = null; } if (_parameterNameParser.IsMatch(DefaultOriginalPrefix)) { _originalPrefix = DefaultOriginalPrefix; } else if (_parameterNameParser.IsMatch(AlternativeOriginalPrefix)) { _originalPrefix = AlternativeOriginalPrefix; } else if (_parameterNameParser.IsMatch(AlternativeOriginalPrefix2)) { _originalPrefix = AlternativeOriginalPrefix2; } else { _originalPrefix = null; } } private void ApplyProviderSpecificFormat() { for (int i = 0; i < _baseParameterNames.Length; i++) { if (null != _baseParameterNames[i]) { _baseParameterNames[i] = _dbCommandBuilder.GetParameterName(_baseParameterNames[i]); } if (null != _originalParameterNames[i]) { _originalParameterNames[i] = _dbCommandBuilder.GetParameterName(_originalParameterNames[i]); } if (null != _nullParameterNames[i]) { _nullParameterNames[i] = _dbCommandBuilder.GetParameterName(_nullParameterNames[i]); } } } private void EliminateConflictingNames() { // for (int i = 0; i < _count - 1; i++) { string name = _baseParameterNames[i]; if (null != name) { for (int j = i + 1; j < _count; j++) { if (ADP.CompareInsensitiveInvariant(name, _baseParameterNames[j])) { // found duplicate name // the name unchanged name wins int iMutatedName = _isMutatedName[j] ? j : i; Debug.Assert(_isMutatedName[iMutatedName], String.Format(CultureInfo.InvariantCulture, "{0} expected to be a mutated name", _baseParameterNames[iMutatedName])); _baseParameterNames[iMutatedName] = null; // null out the culprit } } } } } // Generates parameternames that couldn't be generated from columnname internal void GenerateMissingNames(DbSchemaRow[] schemaRows) { // foreach name in base names // if base name is null // for base, original and nullnames (null names only if nullable) // do // generate name based on current index // increment index // search name in base names // loop while name occures in base names // end for // end foreach string name; for (int i = 0; i < _baseParameterNames.Length; i++) { name = _baseParameterNames[i]; if (null == name) { _baseParameterNames[i] = GetNextGenericParameterName(); _originalParameterNames[i] = GetNextGenericParameterName(); // don't bother generating an 'IsNull' name if it's not used if ((null != schemaRows[i]) && schemaRows[i].AllowDBNull) { _nullParameterNames[i] = GetNextGenericParameterName(); } } } } private int GetAdjustedParameterNameMaxLength() { int maxPrefixLength = Math.Max( (null != _isNullPrefix ? _isNullPrefix.Length : 0), (null != _originalPrefix ? _originalPrefix.Length : 0) ) + _dbCommandBuilder.GetParameterName("").Length; return _dbCommandBuilder.ParameterNameMaxLength - maxPrefixLength; } private string GetNextGenericParameterName() { string name; bool nameExist; do { nameExist = false; _genericParameterCount++; name = _dbCommandBuilder.GetParameterName(_genericParameterCount); for (int i = 0; i < _baseParameterNames.Length; i++) { if (ADP.CompareInsensitiveInvariant(_baseParameterNames[i], name)) { nameExist = true; break; } } } while (nameExist); return name; } internal string GetBaseParameterName(int index) { return (_baseParameterNames[index]); } internal string GetOriginalParameterName(int index) { return (_originalParameterNames[index]); } internal string GetNullParameterName(int index) { return (_nullParameterNames[index]); } } private const string DeleteFrom = "DELETE FROM "; private const string InsertInto = "INSERT INTO "; private const string DefaultValues = " DEFAULT VALUES"; private const string Values = " VALUES "; private const string Update = "UPDATE "; private const string Set = " SET "; private const string Where = " WHERE "; private const string SpaceLeftParenthesis = " ("; private const string Comma = ", "; private const string Equal = " = "; private const string LeftParenthesis = "("; private const string RightParenthesis = ")"; private const string NameSeparator = "."; private const string IsNull = " IS NULL"; private const string EqualOne = " = 1"; private const string And = " AND "; private const string Or = " OR "; private DbDataAdapter _dataAdapter; private DbCommand _insertCommand; private DbCommand _updateCommand; private DbCommand _deleteCommand; private MissingMappingAction _missingMappingAction; private ConflictOption _conflictDetection = ConflictOption.CompareAllSearchableValues; private bool _setAllValues = false; private bool _hasPartialPrimaryKey = false; private DataTable _dbSchemaTable; private DbSchemaRow[] _dbSchemaRows; private string[] _sourceColumnNames; private ParameterNames _parameterNames = null; private string _quotedBaseTableName; // quote strings to use around SQL object names private CatalogLocation _catalogLocation = CatalogLocation.Start; private string _catalogSeparator = NameSeparator; private string _schemaSeparator = NameSeparator; private string _quotePrefix = ""; private string _quoteSuffix = ""; private string _parameterNamePattern = null; private string _parameterMarkerFormat = null; private int _parameterNameMaxLength = 0; protected DbCommandBuilder() : base() { // V1.2.3300 } [ DefaultValueAttribute(ConflictOption.CompareAllSearchableValues), ResCategoryAttribute(Res.DataCategory_Update), ResDescriptionAttribute(Res.DbCommandBuilder_ConflictOption), ] virtual public ConflictOption ConflictOption { // V1.2.3300 get { return _conflictDetection; } set { switch(value) { case ConflictOption.CompareAllSearchableValues: case ConflictOption.CompareRowVersion: case ConflictOption.OverwriteChanges: _conflictDetection = value; break; default: throw ADP.InvalidConflictOptions(value); } } } [ DefaultValueAttribute(CatalogLocation.Start), ResCategoryAttribute(Res.DataCategory_Schema), ResDescriptionAttribute(Res.DbCommandBuilder_CatalogLocation), ] virtual public CatalogLocation CatalogLocation { // V1.2.3300, MDAC 79449 get { return _catalogLocation; } set { if (null != _dbSchemaTable) { throw ADP.NoQuoteChange(); } switch(value) { case CatalogLocation.Start: case CatalogLocation.End: _catalogLocation = value; break; default: throw ADP.InvalidCatalogLocation(value); } } } [ DefaultValueAttribute(DbCommandBuilder.NameSeparator), ResCategoryAttribute(Res.DataCategory_Schema), ResDescriptionAttribute(Res.DbCommandBuilder_CatalogSeparator), ] virtual public string CatalogSeparator { // V1.2.3300, MDAC 79449 get { string catalogSeparator = _catalogSeparator; return (((null != catalogSeparator) && (0 < catalogSeparator.Length)) ? catalogSeparator : NameSeparator); } set { if (null != _dbSchemaTable) { throw ADP.NoQuoteChange(); } _catalogSeparator = value; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ResDescriptionAttribute(Res.DbCommandBuilder_DataAdapter), ] public DbDataAdapter DataAdapter { // V1.2.3300 get { return _dataAdapter; } set { if (_dataAdapter != value) { RefreshSchema(); if (null != _dataAdapter) { // derived should remove event handler from old adapter SetRowUpdatingHandler(_dataAdapter); _dataAdapter = null; } if (null != value) { // derived should add event handler to new adapter SetRowUpdatingHandler(value); _dataAdapter = value; } } } } internal int ParameterNameMaxLength { get { return _parameterNameMaxLength; } } internal string ParameterNamePattern { get { return _parameterNamePattern; } } private string QuotedBaseTableName { get { return _quotedBaseTableName; } } [ DefaultValueAttribute(""), ResCategoryAttribute(Res.DataCategory_Schema), ResDescriptionAttribute(Res.DbCommandBuilder_QuotePrefix), ] virtual public string QuotePrefix { // V1.2.3300, XXXCommandBuilder V1.0.3300 get { string quotePrefix = _quotePrefix; return ((null != quotePrefix) ? quotePrefix : ADP.StrEmpty); } set { if (null != _dbSchemaTable) { throw ADP.NoQuoteChange(); } _quotePrefix = value; } } [ DefaultValueAttribute(""), ResCategoryAttribute(Res.DataCategory_Schema), ResDescriptionAttribute(Res.DbCommandBuilder_QuoteSuffix), ] virtual public string QuoteSuffix { // V1.2.3300, XXXCommandBuilder V1.0.3300 get { string quoteSuffix = _quoteSuffix; return ((null != quoteSuffix) ? quoteSuffix : ADP.StrEmpty); } set { if (null != _dbSchemaTable) { throw ADP.NoQuoteChange(); } _quoteSuffix = value; } } [ DefaultValueAttribute(DbCommandBuilder.NameSeparator), ResCategoryAttribute(Res.DataCategory_Schema), ResDescriptionAttribute(Res.DbCommandBuilder_SchemaSeparator), ] virtual public string SchemaSeparator { // V1.2.3300, MDAC 79449 get { string schemaSeparator = _schemaSeparator; return (((null != schemaSeparator) && (0 < schemaSeparator.Length)) ? schemaSeparator : NameSeparator); } set { if (null != _dbSchemaTable) { throw ADP.NoQuoteChange(); } _schemaSeparator = value; } } [ DefaultValueAttribute(false), ResCategoryAttribute(Res.DataCategory_Schema), ResDescriptionAttribute(Res.DbCommandBuilder_SetAllValues), ] public bool SetAllValues { get { return _setAllValues; } set { _setAllValues = value; } } private DbCommand InsertCommand { get { return _insertCommand; } set { _insertCommand = value; } } private DbCommand UpdateCommand { get { return _updateCommand; } set { _updateCommand = value; } } private DbCommand DeleteCommand { get { return _deleteCommand; } set { _deleteCommand = value; } } private void BuildCache(bool closeConnection, DataRow dataRow, bool useColumnsForParameterNames) { // V1.2.3300 // Don't bother building the cache if it's done already; wait for // the user to call RefreshSchema first. if ((null != _dbSchemaTable) && (!useColumnsForParameterNames || (null != _parameterNames))) { return; } DataTable schemaTable = null; DbCommand srcCommand = GetSelectCommand(); DbConnection connection = srcCommand.Connection; if (null == connection) { throw ADP.MissingSourceCommandConnection(); } try { if (0 == (ConnectionState.Open & connection.State)) { connection.Open(); } else { closeConnection = false; } if (useColumnsForParameterNames) { DataTable dataTable = connection.GetSchema(DbMetaDataCollectionNames.DataSourceInformation); if (dataTable.Rows.Count == 1) { _parameterNamePattern = dataTable.Rows[0][DbMetaDataColumnNames.ParameterNamePattern] as string; _parameterMarkerFormat = dataTable.Rows[0][DbMetaDataColumnNames.ParameterMarkerFormat] as string; object oParameterNameMaxLength = dataTable.Rows[0][DbMetaDataColumnNames.ParameterNameMaxLength]; _parameterNameMaxLength = (oParameterNameMaxLength is int) ? (int)oParameterNameMaxLength : 0; // note that we protect against errors in the xml file! if (0 == _parameterNameMaxLength || null == _parameterNamePattern || null == _parameterMarkerFormat) { useColumnsForParameterNames = false; } } else { Debug.Assert(false, "Rowcount expected to be 1"); useColumnsForParameterNames = false; } } schemaTable = GetSchemaTable(srcCommand); } finally { if (closeConnection) { connection.Close(); } } if (null == schemaTable) { throw ADP.DynamicSQLNoTableInfo(); } #if DEBUG //if (AdapterSwitches.DbCommandBuilder.TraceVerbose) { // ADP.TraceDataTable("DbCommandBuilder", schemaTable); //} #endif BuildInformation(schemaTable); _dbSchemaTable = schemaTable; DbSchemaRow[] schemaRows = _dbSchemaRows; string[] srcColumnNames = new string[schemaRows.Length]; for (int i = 0; i < schemaRows.Length; ++i) { if (null != schemaRows[i]) { srcColumnNames[i] = schemaRows[i].ColumnName; } } _sourceColumnNames = srcColumnNames; if (useColumnsForParameterNames) { _parameterNames = new ParameterNames(this, schemaRows); } ADP.BuildSchemaTableInfoTableNames(srcColumnNames); } virtual protected DataTable GetSchemaTable (DbCommand sourceCommand) { using (IDataReader dataReader = sourceCommand.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo)){ return dataReader.GetSchemaTable(); } } private void BuildInformation(DataTable schemaTable) { DbSchemaRow[] rows = DbSchemaRow.GetSortedSchemaRows(schemaTable, false); // MDAC 60609 if ((null == rows) || (0 == rows.Length)) { throw ADP.DynamicSQLNoTableInfo(); } string baseServerName = ""; // MDAC 72721, 73599 string baseCatalogName = ""; string baseSchemaName = ""; string baseTableName = null; for (int i = 0; i < rows.Length; ++i) { DbSchemaRow row = rows[i]; string tableName = row.BaseTableName; if ((null == tableName) || (0 == tableName.Length)) { rows[i] = null; continue; } string serverName = row.BaseServerName; string catalogName = row.BaseCatalogName; string schemaName = row.BaseSchemaName; if (null == serverName) { serverName = ""; } if (null == catalogName) { catalogName = ""; } if (null == schemaName) { schemaName = ""; } if (null == baseTableName) { baseServerName = serverName; baseCatalogName = catalogName; baseSchemaName = schemaName; baseTableName = tableName; } else if ( (0 != ADP.SrcCompare(baseTableName, tableName)) || (0 != ADP.SrcCompare(baseSchemaName, schemaName)) || (0 != ADP.SrcCompare(baseCatalogName, catalogName)) || (0 != ADP.SrcCompare(baseServerName, serverName))) { throw ADP.DynamicSQLJoinUnsupported(); } } if (0 == baseServerName.Length) { baseServerName = null; } if (0 == baseCatalogName.Length) { baseServerName = null; baseCatalogName = null; } if (0 == baseSchemaName.Length) { baseServerName = null; baseCatalogName = null; baseSchemaName = null; } if ((null == baseTableName) || (0 == baseTableName.Length)) { throw ADP.DynamicSQLNoTableInfo(); } CatalogLocation location = CatalogLocation; string catalogSeparator = CatalogSeparator; string schemaSeparator = SchemaSeparator; string quotePrefix = QuotePrefix; string quoteSuffix = QuoteSuffix; if (!ADP.IsEmpty(quotePrefix) && (-1 != baseTableName.IndexOf(quotePrefix, StringComparison.Ordinal))) { throw ADP.DynamicSQLNestedQuote(baseTableName, quotePrefix); } if (!ADP.IsEmpty(quoteSuffix) && (-1 != baseTableName.IndexOf(quoteSuffix, StringComparison.Ordinal))) { throw ADP.DynamicSQLNestedQuote(baseTableName, quoteSuffix); } System.Text.StringBuilder builder = new System.Text.StringBuilder(); if (CatalogLocation.Start == location) { // MDAC 79449 if (null != baseServerName) { builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseServerName)); builder.Append(catalogSeparator); } if (null != baseCatalogName) { builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseCatalogName)); builder.Append(catalogSeparator); } // } if (null != baseSchemaName) { builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseSchemaName)); builder.Append(schemaSeparator); } // builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseTableName)); if (CatalogLocation.End == location) { // MDAC 79449 if (null != baseServerName) { builder.Append(catalogSeparator); builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseServerName)); } if (null != baseCatalogName) { builder.Append(catalogSeparator); builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseCatalogName)); } } _quotedBaseTableName = builder.ToString(); _hasPartialPrimaryKey = false; foreach(DbSchemaRow row in rows) { if ((null != row) && (row.IsKey || row.IsUnique) && !row.IsLong && !row.IsRowVersion && row.IsHidden) { _hasPartialPrimaryKey = true; break; } } _dbSchemaRows = rows; } private DbCommand BuildDeleteCommand(DataTableMapping mappings, DataRow dataRow) { DbCommand command = InitializeCommand(DeleteCommand); StringBuilder builder = new StringBuilder(); int parameterCount = 0; Debug.Assert (!ADP.IsEmpty(_quotedBaseTableName), "no table name"); builder.Append(DeleteFrom); builder.Append(QuotedBaseTableName); parameterCount = BuildWhereClause(mappings, dataRow, builder, command, parameterCount, false); command.CommandText = builder.ToString(); RemoveExtraParameters(command, parameterCount); DeleteCommand = command; return command; } private DbCommand BuildInsertCommand(DataTableMapping mappings, DataRow dataRow) { DbCommand command = InitializeCommand(InsertCommand); StringBuilder builder = new StringBuilder(); int parameterCount = 0; string nextSeparator = SpaceLeftParenthesis; Debug.Assert (!ADP.IsEmpty(_quotedBaseTableName), "no table name"); builder.Append(InsertInto); builder.Append(QuotedBaseTableName); // search for the columns in that base table, to be the column clause DbSchemaRow[] schemaRows = _dbSchemaRows; string[] parameterName = new string[schemaRows.Length]; for (int i = 0; i < schemaRows.Length; ++i) { DbSchemaRow row = schemaRows[i]; if ( (null == row) || (0 == row.BaseColumnName.Length) || !IncludeInInsertValues(row) ) continue; object currentValue = null; string sourceColumn = _sourceColumnNames[i]; // If we're building a statement for a specific row, then check the // values to see whether the column should be included in the insert // statement or not if ((null != mappings) && (null != dataRow)) { DataColumn dataColumn = GetDataColumn(sourceColumn, mappings, dataRow); if (null == dataColumn) continue; // Don't bother inserting if the column is readonly in both the data // set and the back end. if (row.IsReadOnly && dataColumn.ReadOnly) continue; currentValue = GetColumnValue(dataRow, dataColumn, DataRowVersion.Current); // If the value is null, and the column doesn't support nulls, then // the user is requesting the server-specified default value, so don't // include it in the set-list. if ( !row.AllowDBNull && (null == currentValue || Convert.IsDBNull(currentValue)) ) continue; } builder.Append(nextSeparator); nextSeparator = Comma; builder.Append(QuotedColumn(row.BaseColumnName)); parameterName[parameterCount] = CreateParameterForValue( command, GetBaseParameterName(i), sourceColumn, DataRowVersion.Current, parameterCount, currentValue, row, StatementType.Insert, false ); parameterCount++; } if (0 == parameterCount) builder.Append(DefaultValues); else { builder.Append(RightParenthesis); builder.Append(Values); builder.Append(LeftParenthesis); builder.Append(parameterName[0]); for (int i = 1; i < parameterCount; ++i) { builder.Append(Comma); builder.Append(parameterName[i]); } builder.Append(RightParenthesis); } command.CommandText = builder.ToString(); RemoveExtraParameters(command, parameterCount); InsertCommand = command; return command; } private DbCommand BuildUpdateCommand(DataTableMapping mappings, DataRow dataRow) { DbCommand command = InitializeCommand(UpdateCommand); StringBuilder builder = new StringBuilder(); string nextSeparator = Set; int parameterCount = 0; Debug.Assert (!ADP.IsEmpty(_quotedBaseTableName), "no table name"); builder.Append(Update); builder.Append(QuotedBaseTableName); // search for the columns in that base table, to build the set clause DbSchemaRow[] schemaRows = _dbSchemaRows; for (int i = 0; i < schemaRows.Length; ++i) { DbSchemaRow row = schemaRows[i]; if ((null == row) || (0 == row.BaseColumnName.Length) || !IncludeInUpdateSet(row)) continue; object currentValue = null; string sourceColumn = _sourceColumnNames[i]; // If we're building a statement for a specific row, then check the // values to see whether the column should be included in the update // statement or not if ((null != mappings) && (null != dataRow)) { DataColumn dataColumn = GetDataColumn(sourceColumn, mappings, dataRow); if (null == dataColumn) continue; // Don't bother updating if the column is readonly in both the data // set and the back end. if (row.IsReadOnly && dataColumn.ReadOnly) continue; // Unless specifically directed to do so, we will not automatically update // a column with it's original value, which means that we must determine // whether the value has changed locally, before we send it up. currentValue = GetColumnValue(dataRow, dataColumn, DataRowVersion.Current); if (!SetAllValues) { object originalValue = GetColumnValue(dataRow, dataColumn, DataRowVersion.Original); if ((originalValue == currentValue) || ((null != originalValue) && originalValue.Equals(currentValue))) { continue; } } } builder.Append(nextSeparator); nextSeparator = Comma; builder.Append(QuotedColumn(row.BaseColumnName)); builder.Append(Equal); builder.Append( CreateParameterForValue( command, GetBaseParameterName(i), sourceColumn, DataRowVersion.Current, parameterCount, currentValue, row, StatementType.Update, false ) ); parameterCount++; } // It is an error to attempt an update when there's nothing to update; bool skipRow = (0 == parameterCount); parameterCount = BuildWhereClause(mappings, dataRow, builder, command, parameterCount, true); command.CommandText = builder.ToString(); RemoveExtraParameters(command, parameterCount); UpdateCommand = command; return (skipRow) ? null : command; } private int BuildWhereClause( DataTableMapping mappings, DataRow dataRow, StringBuilder builder, DbCommand command, int parameterCount, bool isUpdate ) { string beginNewCondition = string.Empty; int whereCount = 0; builder.Append(Where); builder.Append(LeftParenthesis); DbSchemaRow[] schemaRows = _dbSchemaRows; for (int i = 0; i < schemaRows.Length; ++i) { DbSchemaRow row = schemaRows[i]; if ((null == row) || (0 == row.BaseColumnName.Length) || !IncludeInWhereClause(row, isUpdate)) { continue; } builder.Append(beginNewCondition); beginNewCondition = And; object value = null; string sourceColumn = _sourceColumnNames[i]; string baseColumnName = QuotedColumn(row.BaseColumnName); if ((null != mappings) && (null != dataRow)) value = GetColumnValue(dataRow, sourceColumn, mappings, DataRowVersion.Original); if (!row.AllowDBNull) { // (<baseColumnName> = ?) builder.Append(LeftParenthesis); builder.Append(baseColumnName); builder.Append(Equal); builder.Append( CreateParameterForValue( command, GetOriginalParameterName(i), sourceColumn, DataRowVersion.Original, parameterCount, value, row, (isUpdate ? StatementType.Update : StatementType.Delete), true ) ); parameterCount++; builder.Append(RightParenthesis); } else { // ((? = 1 AND <baseColumnName> IS NULL) OR (<baseColumnName> = ?)) builder.Append(LeftParenthesis); builder.Append(LeftParenthesis); builder.Append( CreateParameterForNullTest( command, GetNullParameterName(i), sourceColumn, DataRowVersion.Original, parameterCount, value, row, (isUpdate ? StatementType.Update : StatementType.Delete), true ) ); parameterCount++; builder.Append(EqualOne); builder.Append(And); builder.Append(baseColumnName); builder.Append(IsNull); builder.Append(RightParenthesis); builder.Append(Or); builder.Append(LeftParenthesis); builder.Append(baseColumnName); builder.Append(Equal); builder.Append( CreateParameterForValue( command, GetOriginalParameterName(i), sourceColumn, DataRowVersion.Original, parameterCount, value, row, (isUpdate ? StatementType.Update : StatementType.Delete), true ) ); parameterCount++; builder.Append(RightParenthesis); builder.Append(RightParenthesis); } if (IncrementWhereCount(row)) { whereCount++; } } builder.Append(RightParenthesis); if (0 == whereCount) { if (isUpdate) { if (ConflictOption.CompareRowVersion == ConflictOption) { throw ADP.DynamicSQLNoKeyInfoRowVersionUpdate(); } throw ADP.DynamicSQLNoKeyInfoUpdate(); } else { if (ConflictOption.CompareRowVersion == ConflictOption) { throw ADP.DynamicSQLNoKeyInfoRowVersionDelete(); } throw ADP.DynamicSQLNoKeyInfoDelete(); } } return parameterCount; } private string CreateParameterForNullTest( DbCommand command, string parameterName, string sourceColumn, DataRowVersion version, int parameterCount, object value, DbSchemaRow row, StatementType statementType, bool whereClause ) { DbParameter p = GetNextParameter(command, parameterCount); Debug.Assert(!ADP.IsEmpty(sourceColumn), "empty source column"); if (null == parameterName) { p.ParameterName = GetParameterName(1 + parameterCount); } else { p.ParameterName = parameterName; } p.Direction = ParameterDirection.Input; p.SourceColumn = sourceColumn; p.SourceVersion = version; p.SourceColumnNullMapping = true; p.Value = value; p.Size = 0; // don't specify parameter.Size so that we don't silently truncate to the metadata size ApplyParameterInfo(p, row.DataRow, statementType, whereClause); p.DbType = DbType.Int32; p.Value = ADP.IsNull(value) ? DbDataAdapter.ParameterValueNullValue : DbDataAdapter.ParameterValueNonNullValue; if (!command.Parameters.Contains(p)) { command.Parameters.Add(p); } if (null == parameterName) { return GetParameterPlaceholder(1 + parameterCount); } else { Debug.Assert(null != _parameterNames, "How can we have a parameterName without a _parameterNames collection?"); Debug.Assert(null != _parameterMarkerFormat, "How can we have a _parameterNames collection but no _parameterMarkerFormat?"); return String.Format(CultureInfo.InvariantCulture, _parameterMarkerFormat, parameterName); } } private string CreateParameterForValue( DbCommand command, string parameterName, string sourceColumn, DataRowVersion version, int parameterCount, object value, DbSchemaRow row, StatementType statementType, bool whereClause ) { DbParameter p = GetNextParameter(command, parameterCount); if (null == parameterName) { p.ParameterName = GetParameterName(1 + parameterCount); } else { p.ParameterName = parameterName; } p.Direction = ParameterDirection.Input; p.SourceColumn = sourceColumn; p.SourceVersion = version; p.SourceColumnNullMapping = false; p.Value = value; p.Size = 0; // don't specify parameter.Size so that we don't silently truncate to the metadata size ApplyParameterInfo(p, row.DataRow, statementType, whereClause); if (!command.Parameters.Contains(p)) { command.Parameters.Add(p); } if (null == parameterName) { return GetParameterPlaceholder(1 + parameterCount); } else { Debug.Assert(null != _parameterNames, "How can we have a parameterName without a _parameterNames collection?"); Debug.Assert(null != _parameterMarkerFormat, "How can we have a _parameterNames collection but no _parameterMarkerFormat?"); return String.Format(CultureInfo.InvariantCulture, _parameterMarkerFormat, parameterName); } } override protected void Dispose(bool disposing) { // V1.2.3300, XXXCommandBuilder V1.0.3300 // MDAC 65459 if (disposing) { // release mananged objects DataAdapter = null; } //release unmanaged objects base.Dispose(disposing); // notify base classes } private DataTableMapping GetTableMapping(DataRow dataRow ) { DataTableMapping tableMapping = null; if (null != dataRow) { DataTable dataTable = dataRow.Table; if (null != dataTable) { DbDataAdapter adapter = DataAdapter; if (null != adapter) { tableMapping = adapter.GetTableMapping(dataTable); } else { string tableName = dataTable.TableName; tableMapping = new DataTableMapping(tableName, tableName); } } } return tableMapping; } private string GetBaseParameterName(int index) { if (null != _parameterNames) { return (_parameterNames.GetBaseParameterName(index)); } else { return null; } } private string GetOriginalParameterName(int index) { if (null != _parameterNames) { return (_parameterNames.GetOriginalParameterName(index)); } else { return null; } } private string GetNullParameterName(int index) { if (null != _parameterNames) { return (_parameterNames.GetNullParameterName(index)); } else { return null; } } private DbCommand GetSelectCommand() { // V1.2.3300 DbCommand select = null; DbDataAdapter adapter = DataAdapter; if (null != adapter) { if (0 == _missingMappingAction) { _missingMappingAction = adapter.MissingMappingAction; } select = (DbCommand)adapter.SelectCommand; } if (null == select) { throw ADP.MissingSourceCommand(); } return select; } // open connection is required by OleDb/OdbcCommandBuilder.QuoteIdentifier and UnquoteIdentifier // to get literals quotes from the driver internal DbConnection GetConnection() { DbDataAdapter adapter = DataAdapter; if (adapter != null) { DbCommand select = (DbCommand)adapter.SelectCommand; if (select != null) { return select.Connection; } } return null; } public DbCommand GetInsertCommand() { // V1.2.3300, XXXCommandBuilder V1.0.3300 return GetInsertCommand((DataRow)null, false); } public DbCommand GetInsertCommand(bool useColumnsForParameterNames) { return GetInsertCommand((DataRow)null, useColumnsForParameterNames); } internal DbCommand GetInsertCommand(DataRow dataRow, bool useColumnsForParameterNames) { BuildCache(true, dataRow, useColumnsForParameterNames); BuildInsertCommand(GetTableMapping(dataRow), dataRow); return InsertCommand; } public DbCommand GetUpdateCommand() { // V1.2.3300, XXXCommandBuilder V1.0.3300 return GetUpdateCommand((DataRow)null, false); } public DbCommand GetUpdateCommand(bool useColumnsForParameterNames) { return GetUpdateCommand((DataRow)null, useColumnsForParameterNames); } internal DbCommand GetUpdateCommand(DataRow dataRow, bool useColumnsForParameterNames) { BuildCache(true, dataRow, useColumnsForParameterNames); BuildUpdateCommand(GetTableMapping(dataRow), dataRow); return UpdateCommand; } public DbCommand GetDeleteCommand() { // V1.2.3300, XXXCommandBuilder V1.0.3300 return GetDeleteCommand((DataRow)null, false); } public DbCommand GetDeleteCommand(bool useColumnsForParameterNames) { return GetDeleteCommand((DataRow)null, useColumnsForParameterNames); } internal DbCommand GetDeleteCommand(DataRow dataRow, bool useColumnsForParameterNames) { BuildCache(true, dataRow, useColumnsForParameterNames); BuildDeleteCommand(GetTableMapping(dataRow), dataRow); return DeleteCommand; } private object GetColumnValue(DataRow row, String columnName, DataTableMapping mappings, DataRowVersion version) { return GetColumnValue(row, GetDataColumn(columnName, mappings, row), version); } private object GetColumnValue(DataRow row, DataColumn column, DataRowVersion version) { object value = null; if (null != column) { value = row[column, version]; } return value; } private DataColumn GetDataColumn(string columnName, DataTableMapping tablemapping, DataRow row) { DataColumn column = null; if (!ADP.IsEmpty(columnName)) { column = tablemapping.GetDataColumn(columnName, null, row.Table, _missingMappingAction, MissingSchemaAction.Error); } return column; } static private DbParameter GetNextParameter(DbCommand command, int pcount) { DbParameter p; if (pcount < command.Parameters.Count) { p = command.Parameters[pcount]; } else { p = command.CreateParameter(); /*if (null == p) { // */ } Debug.Assert(null != p, "null CreateParameter"); return p; } private bool IncludeInInsertValues(DbSchemaRow row) { // return (!row.IsAutoIncrement && !row.IsHidden && !row.IsExpression && !row.IsRowVersion && !row.IsReadOnly); } private bool IncludeInUpdateSet(DbSchemaRow row) { // return (!row.IsAutoIncrement && !row.IsRowVersion && !row.IsHidden && !row.IsReadOnly); } private bool IncludeInWhereClause(DbSchemaRow row, bool isUpdate) { bool flag = IncrementWhereCount(row); if (flag && row.IsHidden) { // MDAC 52564 if (ConflictOption.CompareRowVersion == ConflictOption) { throw ADP.DynamicSQLNoKeyInfoRowVersionUpdate(); } throw ADP.DynamicSQLNoKeyInfoUpdate(); } if (!flag && (ConflictOption.CompareAllSearchableValues == ConflictOption)) { // include other searchable values flag = !row.IsLong && !row.IsRowVersion && !row.IsHidden; } return flag; } private bool IncrementWhereCount(DbSchemaRow row) { ConflictOption value = ConflictOption; switch(value) { case ConflictOption.CompareAllSearchableValues: case ConflictOption.OverwriteChanges: // find the primary key return (row.IsKey || row.IsUnique) && !row.IsLong && !row.IsRowVersion; case ConflictOption.CompareRowVersion: // or the row version return (((row.IsKey || row.IsUnique) && !_hasPartialPrimaryKey) || row.IsRowVersion) && !row.IsLong; default: throw ADP.InvalidConflictOptions(value); } } virtual protected DbCommand InitializeCommand(DbCommand command) { // V1.2.3300 if (null == command) { DbCommand select = GetSelectCommand(); command = select.Connection.CreateCommand(); /*if (null == command) { // */ // the following properties are only initialized when the object is created // all other properites are reinitialized on every row /*command.Connection = select.Connection;*/ // initialized by CreateCommand command.CommandTimeout = select.CommandTimeout; command.Transaction = select.Transaction; } command.CommandType = CommandType.Text; command.UpdatedRowSource = UpdateRowSource.None; // no select or output parameters expected return command; } private string QuotedColumn(string column) { return ADP.BuildQuotedString(QuotePrefix, QuoteSuffix, column); } public virtual string QuoteIdentifier(string unquotedIdentifier ) { throw ADP.NotSupported(); } virtual public void RefreshSchema() { // V1.2.3300, XXXCommandBuilder V1.0.3300 _dbSchemaTable = null; _dbSchemaRows = null; _sourceColumnNames = null; _quotedBaseTableName = null; DbDataAdapter adapter = DataAdapter; if (null != adapter) { // MDAC 66016 if (InsertCommand == adapter.InsertCommand) { adapter.InsertCommand = null; } if (UpdateCommand == adapter.UpdateCommand) { adapter.UpdateCommand = null; } if (DeleteCommand == adapter.DeleteCommand) { adapter.DeleteCommand = null; } } DbCommand command; if (null != (command = InsertCommand)) { command.Dispose(); } if (null != (command = UpdateCommand)) { command.Dispose(); } if (null != (command = DeleteCommand)) { command.Dispose(); } InsertCommand = null; UpdateCommand = null; DeleteCommand = null; } static private void RemoveExtraParameters(DbCommand command, int usedParameterCount) { for (int i = command.Parameters.Count-1; i >= usedParameterCount; --i) { command.Parameters.RemoveAt(i); } } protected void RowUpdatingHandler(RowUpdatingEventArgs rowUpdatingEvent) { if (null == rowUpdatingEvent) { throw ADP.ArgumentNull("rowUpdatingEvent"); } try { if (UpdateStatus.Continue == rowUpdatingEvent.Status) { StatementType stmtType = rowUpdatingEvent.StatementType; DbCommand command = (DbCommand)rowUpdatingEvent.Command; if (null != command) { switch(stmtType) { case StatementType.Select: Debug.Assert(false, "how did we get here?"); return; // don't mess with it case StatementType.Insert: command = InsertCommand; break; case StatementType.Update: command = UpdateCommand; break; case StatementType.Delete: command = DeleteCommand; break; default: throw ADP.InvalidStatementType(stmtType); } if (command != rowUpdatingEvent.Command) { command = (DbCommand)rowUpdatingEvent.Command; if ((null != command) && (null == command.Connection)) { // MDAC 87649 DbDataAdapter adapter = DataAdapter; DbCommand select = ((null != adapter) ? ((DbCommand)adapter.SelectCommand) : null); if (null != select) { command.Connection = (DbConnection)select.Connection; } } // user command, not a command builder command } else command = null; } if (null == command) { RowUpdatingHandlerBuilder(rowUpdatingEvent); } } } catch(Exception e) { // if (!ADP.IsCatchableExceptionType(e)) { throw; } ADP.TraceExceptionForCapture(e); rowUpdatingEvent.Status = UpdateStatus.ErrorsOccurred; rowUpdatingEvent.Errors = e; } } private void RowUpdatingHandlerBuilder(RowUpdatingEventArgs rowUpdatingEvent) { // MDAC 58710 - unable to tell Update method that Event opened connection and Update needs to close when done // HackFix - the Update method will close the connection if command was null and returned command.Connection is same as SelectCommand.Connection DataRow datarow = rowUpdatingEvent.Row; BuildCache(false, datarow, false); DbCommand command; switch(rowUpdatingEvent.StatementType) { case StatementType.Insert: command = BuildInsertCommand(rowUpdatingEvent.TableMapping, datarow); break; case StatementType.Update: command = BuildUpdateCommand(rowUpdatingEvent.TableMapping, datarow); break; case StatementType.Delete: command = BuildDeleteCommand(rowUpdatingEvent.TableMapping, datarow); break; #if DEBUG case StatementType.Select: Debug.Assert(false, "how did we get here?"); goto default; #endif default: throw ADP.InvalidStatementType(rowUpdatingEvent.StatementType); } if (null == command) { if (null != datarow) { datarow.AcceptChanges(); } rowUpdatingEvent.Status = UpdateStatus.SkipCurrentRow; } rowUpdatingEvent.Command = command; } public virtual string UnquoteIdentifier(string quotedIdentifier ) { throw ADP.NotSupported(); } abstract protected void ApplyParameterInfo(DbParameter parameter, DataRow row, StatementType statementType, bool whereClause); // V1.2.3300 abstract protected string GetParameterName(int parameterOrdinal); // V1.2.3300 abstract protected string GetParameterName(string parameterName); abstract protected string GetParameterPlaceholder(int parameterOrdinal); // V1.2.3300 abstract protected void SetRowUpdatingHandler(DbDataAdapter adapter); // V1.2.3300 // static internal string[] ParseProcedureName(string name, string quotePrefix, string quoteSuffix) { // Procedure may consist of up to four parts: // 0) Server // 1) Catalog // 2) Schema // 3) ProcedureName // // Parse the string into four parts, allowing the last part to contain '.'s. // If less than four period delimited parts, use the parts from procedure backwards. // const string Separator = "."; string[] qualifiers = new string[4]; if (!ADP.IsEmpty(name)) { bool useQuotes = !ADP.IsEmpty(quotePrefix) && !ADP.IsEmpty(quoteSuffix); int currentPos = 0, parts; for(parts = 0; (parts < qualifiers.Length) && (currentPos < name.Length); ++parts) { int startPos = currentPos; // does the part begin with a quotePrefix? if (useQuotes && (name.IndexOf(quotePrefix, currentPos, quotePrefix.Length, StringComparison.Ordinal) == currentPos)) { currentPos += quotePrefix.Length; // move past the quotePrefix // search for the quoteSuffix (or end of string) while (currentPos < name.Length) { currentPos = name.IndexOf(quoteSuffix, currentPos, StringComparison.Ordinal); if (currentPos < 0) { // error condition, no quoteSuffix currentPos = name.Length; break; } else { currentPos += quoteSuffix.Length; // move past the quoteSuffix // is this a double quoteSuffix? if ((currentPos < name.Length) && (name.IndexOf(quoteSuffix, currentPos, quoteSuffix.Length, StringComparison.Ordinal) == currentPos)) { // a second quoteSuffix, continue search for terminating quoteSuffix currentPos += quoteSuffix.Length; // move past the second quoteSuffix } else { // found the terminating quoteSuffix break; } } } } // search for separator (either no quotePrefix or already past quoteSuffix) if (currentPos < name.Length) { currentPos = name.IndexOf(Separator, currentPos, StringComparison.Ordinal); if ((currentPos < 0) || (parts == qualifiers.Length-1)) { // last part that can be found currentPos = name.Length; } } qualifiers[parts] = name.Substring(startPos, currentPos-startPos); currentPos += Separator.Length; } // allign the qualifiers if we had less than MaxQualifiers for(int j = qualifiers.Length-1; 0 <= j; --j) { qualifiers[j] = ((0 < parts) ? qualifiers[--parts] : null); } } return qualifiers; } } }
using System; using System.Collections.Generic; using System.Text; using System.CodeDom; namespace Thinktecture.Tools.Web.Services.CodeGeneration { internal sealed class DataContractConverter : PascalCaseConverterBase { #region Constructors public DataContractConverter(CodeTypeExtension typeExtension, ExtendedCodeDomTree code) : base(typeExtension, code) { } #endregion #region Protected Method Overrides protected override bool CanConvertTypeName(CodeTypeExtension typeExtension) { return true; } protected override bool CanConvertMember(CodeTypeMemberExtension memberExtension) { // For Data Contracts we change only the public proeperties/fields. if (memberExtension.Kind == CodeTypeMemberKind.Property || memberExtension.Kind == CodeTypeMemberKind.Field) { return ((memberExtension.ExtendedObject.Attributes & MemberAttributes.Public) == MemberAttributes.Public); } return true; } protected override void OnTypeNameChanged(CodeTypeExtension typeExtension, string oldName, string newName) { // Prepare the XmlTypeAttribute attribute to specify the type name on the wire. CodeAttributeDeclaration xmlType = new CodeAttributeDeclaration("System.Xml.Serialization.XmlTypeAttribute", new CodeAttributeArgumentExtended("TypeName", new CodePrimitiveExpression(oldName), true)); // Add the XmlTypeAttribute attribute to ctd. typeExtension.AddAttribute(xmlType); // Do we have an XmlRootAttribute attribute? CodeAttributeDeclaration xmlRoot = typeExtension.FindAttribute("System.Xml.Serialization.XmlRootAttribute"); if (xmlRoot != null) { // Prepare the XmlRootAttribute attribute to specify the type name on the wire. xmlRoot = new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new CodeAttributeArgumentExtended("ElementName", new CodePrimitiveExpression(oldName), true)); // Add XmlRootAttribute attribute to ctd. typeExtension.AddAttribute(xmlRoot); } } protected override void OnFieldNameChanged(CodeTypeMemberExtension memberExtension, string oldName, string newName) { OnFieldOrPropertyNameChanged(memberExtension, oldName, newName); // Make sure the field name change is reflected in the field name references. ConvertFieldReferencesInConstructors(memberExtension.Parent.Constructors, oldName, newName); } protected override void OnPropertyNameChanged(CodeTypeMemberExtension memberExtension, string oldName, string newName) { OnFieldOrPropertyNameChanged(memberExtension, oldName, newName); CodeMemberProperty property = (CodeMemberProperty)memberExtension.ExtendedObject; // Look up for the data binding statement and change the property name there. foreach (CodeStatement statement in property.SetStatements) { CodeExpressionStatement expStatement = statement as CodeExpressionStatement; // Continue if the statement is not a CodeExpressionStatement. if (expStatement == null) { continue; } CodeMethodInvokeExpression miExp = expStatement.Expression as CodeMethodInvokeExpression; // Continue if the statement is not a CodeMethodInvokeExpression. if (miExp == null) { continue; } // Modify the property name in parameters. foreach (CodeExpression pExp in miExp.Parameters) { CodePrimitiveExpression priExp = pExp as CodePrimitiveExpression; // Continue if the statment is not a CodePrimitiveExpression. if (priExp == null) { continue; } if (priExp.Value.ToString() == oldName) { priExp.Value = newName; } } } } protected override void OnEventNameChanged(CodeTypeMemberExtension memberExtension, string oldName, string newName) { // NOP } protected override void OnMethodNameChanged(CodeTypeMemberExtension memberExtension, string oldName, string newName) { // NOP } protected override void OnEnumMemberChanged(CodeTypeMemberExtension memberExtension, string oldName, string newName) { // Fix references found in DefaultValue attributes. foreach (CodeTypeExtension type in Code.DataContracts) { foreach (CodeTypeMemberExtension member in type.Fields) { CodeAttributeDeclaration attribute = member.FindAttribute("System.ComponentModel.DefaultValueAttribute"); if (attribute == null) continue; CodeAttributeArgument argument = attribute.Arguments[0]; CodeFieldReferenceExpression argumentValue = argument.Value as CodeFieldReferenceExpression; if (argumentValue == null) continue; string baseTypeName = ((CodeTypeReferenceExpression)argumentValue.TargetObject).Type.BaseType; string nameOfTypeInAttribute = PascalCaseConverterHelper.GetPascalCaseName(baseTypeName); string nameOfTypeBeingChanged = memberExtension.Parent.ExtendedObject.Name; if (argumentValue.FieldName == oldName && nameOfTypeInAttribute == nameOfTypeBeingChanged) { argumentValue.FieldName = newName; } } // Fix references found in constructor where default values are set. // This is required for fixed references to enum values. // e.g. <xs:attribute ref="xlink:type" fixed="simple"/> foreach (CodeTypeMemberExtension ctorExtension in type.Constructors) { // Get a reference to the actual constructor object. CodeConstructor constructor = (CodeConstructor)ctorExtension.ExtendedObject; // Do this for all statements we have in the constructor. foreach (CodeStatement statement in constructor.Statements) { // Is this an assign statement? CodeAssignStatement assignStatement = statement as CodeAssignStatement; if (assignStatement != null) { // Do we have a field reference on the right side of the assignment statement? CodeFieldReferenceExpression fieldRef = assignStatement.Right as CodeFieldReferenceExpression; if (fieldRef != null) { // Does the referenced field belong to a type reference? if (typeof(CodeTypeReferenceExpression) == fieldRef.TargetObject.GetType()) { string baseTypeName = ((CodeTypeReferenceExpression)fieldRef.TargetObject).Type.BaseType; string nameOfTypeForField = PascalCaseConverterHelper.GetPascalCaseName(baseTypeName); string nameOfTypeBeingChanged = memberExtension.Parent.ExtendedObject.Name; // Change the field name if it's changed. if (fieldRef.FieldName == oldName && nameOfTypeForField == nameOfTypeBeingChanged) { // Fix the field name first. fieldRef.FieldName = newName; // Also fix the name in the type reference. ((CodeTypeReferenceExpression)fieldRef.TargetObject).Type.BaseType = nameOfTypeForField; } } } } } } } // Before adding the XmlEnumAttribute attribute to the CodeTypeMember // we have to make sure that the following attributes are not present. if (memberExtension.FindAttribute("System.Xml.Serialization.XmlAttributeAttribute") != null || memberExtension.FindAttribute("System.Xml.Serialization.XmlAnyElementAttribute") != null || memberExtension.FindAttribute("System.Xml.Serialization.XmlAnyAttributeAttribute") != null) { // We cannot proceed. return; } // Create a CodeAttributeDeclaration for XmlEnumAttribute attribute and // add it to the attributes collection. CodeAttributeDeclaration xmlEnum = new CodeAttributeDeclaration ("System.Xml.Serialization.XmlEnumAttribute"); xmlEnum.Arguments.Add(new CodeAttributeArgumentExtended("Name", new CodePrimitiveExpression(oldName), true)); // Finally add it to the custom attributes collection. memberExtension.AddAttribute(xmlEnum); } #endregion #region Private Methods private void OnFieldOrPropertyNameChanged(CodeTypeMemberExtension memberExtension, string oldName, string newName) { // Here we basically have two cases. Array and non-array. // If it's an non-array type, we have to decorate it with either // XmlAttributeAttribute attribute or XmlElementAttribute attribute. // If it's an array type we have to decorate it with XmlArrayAttribute // attribute. // There is one quickie we can try before anything nevertheless. // Regardless of whether the member type is an array type or not // member can already have an XmlElementAttribute attribute. // If this is the case we can simply add the XML type name information to that. CodeAttributeDeclaration xmlElementAttribute = memberExtension.FindAttribute("System.Xml.Serialization.XmlElementAttribute"); if (xmlElementAttribute != null) { // Create a new CodeAttributeDeclaration with required arguments xmlElementAttribute = new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute", new CodeAttributeArgumentExtended( "ElementName", new CodePrimitiveExpression(oldName), true)); // Add the newly created attribute to CodeTypeMember. memberExtension.AddAttribute(xmlElementAttribute); // No need to proceed, so simply return. return; } // Let's first handle the non-array case. // And then handl the array case. if (!PascalCaseConverterHelper.IsArray(memberExtension)) { // See if we can spot the XmlAttributeAttribute attribute. CodeAttributeDeclaration xmlAttribute = memberExtension.FindAttribute("System.Xml.Serialization.XmlAttributeAttribute"); // If we could, then let's add the AttributeName argument to it. if (xmlAttribute != null) { // Create a new CodeAttributeDeclaration with required arguments. CodeAttributeDeclaration xmlAttributeAttribute = new CodeAttributeDeclaration("System.Xml.Serialization.XmlAttributeAttribute", new CodeAttributeArgumentExtended( "AttributeName", new CodePrimitiveExpression(oldName), true)); // Add the newly created attribute to CodeTypeMember. memberExtension.AddAttribute(xmlAttributeAttribute); } else { // We arrive here if we could not spot the XmlAttributeAttribute attribute. // Therefore we can add the XmlElementAttribute attribute. // However, before we proceed we have to check whether any of the following attributes // already exists. if (memberExtension.FindAttribute("System.Xml.Serialization.XmlTextAttribute") != null || memberExtension.FindAttribute("System.Xml.Serialization.XmlIgnoreAttribute") != null || memberExtension.FindAttribute("System.Xml.Serialization.XmlAnyElementAttribute") != null || memberExtension.FindAttribute("System.Xml.Serialization.XmlAnyAttributeAttribute") != null) { // We cannot add XmlElementAttribute attribute here. return; } // Create a new CodeAttributeDeclaration with required arguments xmlElementAttribute = new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute", new CodeAttributeArgumentExtended( "ElementName", new CodePrimitiveExpression(oldName), true)); // Add the newly created attribute to CodeTypeMember. memberExtension.AddAttribute(xmlElementAttribute); } } else { // We arrive here if we have an array type. // We can proceed to adding XmlArrayAttribue attribute if following attributes are // not present. if (memberExtension.FindAttribute("System.Xml.Serialization.XmlTextAttribute") != null || memberExtension.FindAttribute("System.Xml.Serialization.XmlAnyElementAttribute") != null || memberExtension.FindAttribute("System.Xml.Serialization.XmlAnyAttributeAttribute") != null) { // We cannot add XmlElementAttribute attribute here. return; } // Create a new CodeAttributeDeclaration for XmlArrayAttribute with required arguments. CodeAttributeDeclaration xmlArrayAttribute = new CodeAttributeDeclaration("System.Xml.Serialization.XmlArrayAttribute", new CodeAttributeArgumentExtended( "ElementName", new CodePrimitiveExpression(oldName), true)); // Add the newly created CodeAttributeDeclaration to the attributes collection of // CodeTypeMemeber. memberExtension.AddAttribute(xmlArrayAttribute); } } #endregion } }
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ using System.Diagnostics; using SharpBox2D.Common; using SharpBox2D.Pooling; namespace SharpBox2D.Dynamics.Joints { //Point-to-point constraint //C = p2 - p1 //Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) //J = [-I -r1_skew I r2_skew ] //Identity used: //w k % (rx i + ry j) = w * (-ry i + rx j) //Motor constraint //Cdot = w2 - w1 //J = [0 0 -1 0 0 1] //K = invI1 + invI2 /** * A revolute joint constrains two bodies to share a common point while they are free to rotate * about the point. The relative rotation about the shared point is the joint angle. You can limit * the relative rotation with a joint limit that specifies a lower and upper angle. You can use a * motor to drive the relative rotation about the shared point. A maximum motor torque is provided * so that infinite forces are not generated. * * @author Daniel Murphy */ public class RevoluteJoint : Joint { // Solver shared internal Vec2 m_localAnchorA = new Vec2(); internal Vec2 m_localAnchorB = new Vec2(); private Vec3 m_impulse = new Vec3(); private float m_motorImpulse; private bool m_enableMotor; private float m_maxMotorTorque; private float m_motorSpeed; private bool m_enableLimit; internal float m_referenceAngle; private float m_lowerAngle; private float m_upperAngle; // Solver temp private int m_indexA; private int m_indexB; private Vec2 m_rA = new Vec2(); private Vec2 m_rB = new Vec2(); private Vec2 m_localCenterA = new Vec2(); private Vec2 m_localCenterB = new Vec2(); private float m_invMassA; private float m_invMassB; private float m_invIA; private float m_invIB; private Mat33 m_mass = new Mat33(); // effective mass for point-to-point constraint. private float m_motorMass; // effective mass for motor/limit angular constraint. private LimitState m_limitState; internal RevoluteJoint(IWorldPool argWorld, RevoluteJointDef def) : base(argWorld, def) { m_localAnchorA.set(def.localAnchorA); m_localAnchorB.set(def.localAnchorB); m_referenceAngle = def.referenceAngle; m_motorImpulse = 0; m_lowerAngle = def.lowerAngle; m_upperAngle = def.upperAngle; m_maxMotorTorque = def.maxMotorTorque; m_motorSpeed = def.motorSpeed; m_enableLimit = def.enableLimit; m_enableMotor = def.enableMotor; m_limitState = LimitState.INACTIVE; } public override void initVelocityConstraints(SolverData data) { m_indexA = m_bodyA.m_islandIndex; m_indexB = m_bodyB.m_islandIndex; m_localCenterA.set(m_bodyA.m_sweep.localCenter); m_localCenterB.set(m_bodyB.m_sweep.localCenter); m_invMassA = m_bodyA.m_invMass; m_invMassB = m_bodyB.m_invMass; m_invIA = m_bodyA.m_invI; m_invIB = m_bodyB.m_invI; // Vec2 cA = data.positions[m_indexA].c; float aA = data.positions[m_indexA].a; Vec2 vA = data.velocities[m_indexA].v; float wA = data.velocities[m_indexA].w; // Vec2 cB = data.positions[m_indexB].c; float aB = data.positions[m_indexB].a; Vec2 vB = data.velocities[m_indexB].v; float wB = data.velocities[m_indexB].w; Rot qA = pool.popRot(); Rot qB = pool.popRot(); Vec2 temp = pool.popVec2(); qA.set(aA); qB.set(aB); // Compute the effective masses. temp.set(m_localAnchorA); temp.subLocal(m_localCenterA); Rot.mulToOutUnsafe(qA, temp, ref m_rA); temp.set(m_localAnchorB); temp.subLocal(m_localCenterB); Rot.mulToOutUnsafe(qB, temp, ref m_rB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float mA = m_invMassA, mB = m_invMassB; float iA = m_invIA, iB = m_invIB; bool fixedRotation = (iA + iB == 0.0f); m_mass.ex.x = mA + mB + m_rA.y*m_rA.y*iA + m_rB.y*m_rB.y*iB; m_mass.ey.x = -m_rA.y*m_rA.x*iA - m_rB.y*m_rB.x*iB; m_mass.ez.x = -m_rA.y*iA - m_rB.y*iB; m_mass.ex.y = m_mass.ey.x; m_mass.ey.y = mA + mB + m_rA.x*m_rA.x*iA + m_rB.x*m_rB.x*iB; m_mass.ez.y = m_rA.x*iA + m_rB.x*iB; m_mass.ex.z = m_mass.ez.x; m_mass.ey.z = m_mass.ez.y; m_mass.ez.z = iA + iB; m_motorMass = iA + iB; if (m_motorMass > 0.0f) { m_motorMass = 1.0f/m_motorMass; } if (m_enableMotor == false || fixedRotation) { m_motorImpulse = 0.0f; } if (m_enableLimit && fixedRotation == false) { float jointAngle = aB - aA - m_referenceAngle; if (MathUtils.abs(m_upperAngle - m_lowerAngle) < 2.0f*Settings.angularSlop) { m_limitState = LimitState.EQUAL; } else if (jointAngle <= m_lowerAngle) { if (m_limitState != LimitState.AT_LOWER) { m_impulse.z = 0.0f; } m_limitState = LimitState.AT_LOWER; } else if (jointAngle >= m_upperAngle) { if (m_limitState != LimitState.AT_UPPER) { m_impulse.z = 0.0f; } m_limitState = LimitState.AT_UPPER; } else { m_limitState = LimitState.INACTIVE; m_impulse.z = 0.0f; } } else { m_limitState = LimitState.INACTIVE; } if (data.step.warmStarting) { Vec2 P = pool.popVec2(); // Scale impulses to support a variable time step. m_impulse.x *= data.step.dtRatio; m_impulse.y *= data.step.dtRatio; m_motorImpulse *= data.step.dtRatio; P.x = m_impulse.x; P.y = m_impulse.y; vA.x -= mA*P.x; vA.y -= mA*P.y; wA -= iA*(Vec2.cross(m_rA, P) + m_motorImpulse + m_impulse.z); vB.x += mB*P.x; vB.y += mB*P.y; wB += iB*(Vec2.cross(m_rB, P) + m_motorImpulse + m_impulse.z); pool.pushVec2(1); } else { m_impulse.setZero(); m_motorImpulse = 0.0f; } // data.velocities[m_indexA].v.set(vA); data.velocities[m_indexA].w = wA; // data.velocities[m_indexB].v.set(vB); data.velocities[m_indexB].w = wB; pool.pushVec2(1); pool.pushRot(2); } public override void solveVelocityConstraints(SolverData data) { Vec2 vA = data.velocities[m_indexA].v; float wA = data.velocities[m_indexA].w; Vec2 vB = data.velocities[m_indexB].v; float wB = data.velocities[m_indexB].w; float mA = m_invMassA, mB = m_invMassB; float iA = m_invIA, iB = m_invIB; bool fixedRotation = (iA + iB == 0.0f); // Solve motor constraint. if (m_enableMotor && m_limitState != LimitState.EQUAL && fixedRotation == false) { float Cdot = wB - wA - m_motorSpeed; float impulse = -m_motorMass*Cdot; float oldImpulse = m_motorImpulse; float maxImpulse = data.step.dt*m_maxMotorTorque; m_motorImpulse = MathUtils.clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = m_motorImpulse - oldImpulse; wA -= iA*impulse; wB += iB*impulse; } Vec2 temp = pool.popVec2(); // Solve limit constraint. if (m_enableLimit && m_limitState != LimitState.INACTIVE && fixedRotation == false) { Vec2 Cdot1 = pool.popVec2(); Vec3 Cdot = pool.popVec3(); // Solve point-to-point constraint Vec2.crossToOutUnsafe(wA, m_rA, ref temp); Vec2.crossToOutUnsafe(wB, m_rB, ref Cdot1); Cdot1.addLocal(vB); Cdot1.subLocal(vA); Cdot1.subLocal(temp); float Cdot2 = wB - wA; Cdot.set(Cdot1.x, Cdot1.y, Cdot2); Vec3 impulse = pool.popVec3(); m_mass.solve33ToOut(Cdot, ref impulse); impulse.negateLocal(); if (m_limitState == LimitState.EQUAL) { m_impulse.addLocal(impulse); } else if (m_limitState == LimitState.AT_LOWER) { float newImpulse = m_impulse.z + impulse.z; if (newImpulse < 0.0f) { Vec2 rhs = pool.popVec2(); rhs.set(m_mass.ez.x, m_mass.ez.y); rhs.mulLocal(m_impulse.z); rhs.subLocal(Cdot1); m_mass.solve22ToOut(rhs, ref temp); impulse.x = temp.x; impulse.y = temp.y; impulse.z = -m_impulse.z; m_impulse.x += temp.x; m_impulse.y += temp.y; m_impulse.z = 0.0f; pool.pushVec2(1); } else { m_impulse.addLocal(impulse); } } else if (m_limitState == LimitState.AT_UPPER) { float newImpulse = m_impulse.z + impulse.z; if (newImpulse > 0.0f) { Vec2 rhs = pool.popVec2(); rhs.set(m_mass.ez.x, m_mass.ez.y); rhs.mulLocal(m_impulse.z); rhs.subLocal(Cdot1); m_mass.solve22ToOut(rhs, ref temp); impulse.x = temp.x; impulse.y = temp.y; impulse.z = -m_impulse.z; m_impulse.x += temp.x; m_impulse.y += temp.y; m_impulse.z = 0.0f; pool.pushVec2(1); } else { m_impulse.addLocal(impulse); } } Vec2 P = pool.popVec2(); P.set(impulse.x, impulse.y); vA.x -= mA*P.x; vA.y -= mA*P.y; wA -= iA*(Vec2.cross(m_rA, P) + impulse.z); vB.x += mB*P.x; vB.y += mB*P.y; wB += iB*(Vec2.cross(m_rB, P) + impulse.z); pool.pushVec2(2); pool.pushVec3(2); } else { // Solve point-to-point constraint Vec2 Cdot = pool.popVec2(); Vec2 impulse = pool.popVec2(); Vec2.crossToOutUnsafe(wA, m_rA, ref temp); Vec2.crossToOutUnsafe(wB, m_rB, ref Cdot); Cdot.addLocal(vB); Cdot.subLocal(vA); Cdot.subLocal(temp); Cdot.negateLocal(); m_mass.solve22ToOut(Cdot, ref impulse); // just leave negated m_impulse.x += impulse.x; m_impulse.y += impulse.y; vA.x -= mA*impulse.x; vA.y -= mA*impulse.y; wA -= iA*Vec2.cross(m_rA, impulse); vB.x += mB*impulse.x; vB.y += mB*impulse.y; wB += iB*Vec2.cross(m_rB, impulse); pool.pushVec2(2); } // data.velocities[m_indexA].v.set(vA); data.velocities[m_indexA].w = wA; // data.velocities[m_indexB].v.set(vB); data.velocities[m_indexB].w = wB; pool.pushVec2(1); } public override bool solvePositionConstraints(SolverData data) { Rot qA = pool.popRot(); Rot qB = pool.popRot(); Vec2 cA = data.positions[m_indexA].c; float aA = data.positions[m_indexA].a; Vec2 cB = data.positions[m_indexB].c; float aB = data.positions[m_indexB].a; qA.set(aA); qB.set(aB); float angularError = 0.0f; float positionError = 0.0f; bool fixedRotation = (m_invIA + m_invIB == 0.0f); // Solve angular limit constraint. if (m_enableLimit && m_limitState != LimitState.INACTIVE && fixedRotation == false) { float angle = aB - aA - m_referenceAngle; float limitImpulse = 0.0f; if (m_limitState == LimitState.EQUAL) { // Prevent large angular corrections float C = MathUtils.clamp(angle - m_lowerAngle, -Settings.maxAngularCorrection, Settings.maxAngularCorrection); limitImpulse = -m_motorMass*C; angularError = MathUtils.abs(C); } else if (m_limitState == LimitState.AT_LOWER) { float C = angle - m_lowerAngle; angularError = -C; // Prevent large angular corrections and allow some slop. C = MathUtils.clamp(C + Settings.angularSlop, -Settings.maxAngularCorrection, 0.0f); limitImpulse = -m_motorMass*C; } else if (m_limitState == LimitState.AT_UPPER) { float C = angle - m_upperAngle; angularError = C; // Prevent large angular corrections and allow some slop. C = MathUtils.clamp(C - Settings.angularSlop, 0.0f, Settings.maxAngularCorrection); limitImpulse = -m_motorMass*C; } aA -= m_invIA*limitImpulse; aB += m_invIB*limitImpulse; } // Solve point-to-point constraint. { qA.set(aA); qB.set(aB); Vec2 rA = pool.popVec2(); Vec2 rB = pool.popVec2(); Vec2 C = pool.popVec2(); Vec2 impulse = pool.popVec2(); C.set(m_localAnchorA); C.subLocal(m_localCenterA); Rot.mulToOutUnsafe(qA, C, ref rA); C.set(m_localAnchorB); C.subLocal(m_localCenterB); Rot.mulToOutUnsafe(qB, C, ref rB); C.set(cB); C.addLocal(rB); C.subLocal(cA); C.subLocal(rA); positionError = C.length(); float mA = m_invMassA, mB = m_invMassB; float iA = m_invIA, iB = m_invIB; Mat22 K = pool.popMat22(); K.ex.x = mA + mB + iA*rA.y*rA.y + iB*rB.y*rB.y; K.ex.y = -iA*rA.x*rA.y - iB*rB.x*rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA*rA.x*rA.x + iB*rB.x*rB.x; K.solveToOut(C, ref impulse); impulse.negateLocal(); cA.x -= mA*impulse.x; cA.y -= mA*impulse.y; aA -= iA*Vec2.cross(rA, impulse); cB.x += mB*impulse.x; cB.y += mB*impulse.y; aB += iB*Vec2.cross(rB, impulse); pool.pushVec2(4); pool.pushMat22(1); } // data.positions[m_indexA].c.set(cA); data.positions[m_indexA].a = aA; // data.positions[m_indexB].c.set(cB); data.positions[m_indexB].a = aB; pool.pushRot(2); return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; } public Vec2 getLocalAnchorA() { return m_localAnchorA; } public Vec2 getLocalAnchorB() { return m_localAnchorB; } public float getReferenceAngle() { return m_referenceAngle; } public override void getAnchorA(ref Vec2 argOut) { m_bodyA.getWorldPointToOut(m_localAnchorA, ref argOut); } public override void getAnchorB(ref Vec2 argOut) { m_bodyB.getWorldPointToOut(m_localAnchorB, ref argOut); } public override void getReactionForce(float inv_dt, ref Vec2 argOut) { argOut.set(m_impulse.x, m_impulse.y); argOut.mulLocal(inv_dt); } public override float getReactionTorque(float inv_dt) { return inv_dt*m_impulse.z; } public float getJointAngle() { Body b1 = m_bodyA; Body b2 = m_bodyB; return b2.m_sweep.a - b1.m_sweep.a - m_referenceAngle; } public float getJointSpeed() { Body b1 = m_bodyA; Body b2 = m_bodyB; return b2.m_angularVelocity - b1.m_angularVelocity; } public bool isMotorEnabled() { return m_enableMotor; } public void enableMotor(bool flag) { m_bodyA.setAwake(true); m_bodyB.setAwake(true); m_enableMotor = flag; } public float getMotorTorque(float inv_dt) { return m_motorImpulse*inv_dt; } public void setMotorSpeed(float speed) { m_bodyA.setAwake(true); m_bodyB.setAwake(true); m_motorSpeed = speed; } public void setMaxMotorTorque(float torque) { m_bodyA.setAwake(true); m_bodyB.setAwake(true); m_maxMotorTorque = torque; } public float getMotorSpeed() { return m_motorSpeed; } public float getMaxMotorTorque() { return m_maxMotorTorque; } public bool isLimitEnabled() { return m_enableLimit; } public void enableLimit(bool flag) { if (flag != m_enableLimit) { m_bodyA.setAwake(true); m_bodyB.setAwake(true); m_enableLimit = flag; m_impulse.z = 0.0f; } } public float getLowerLimit() { return m_lowerAngle; } public float getUpperLimit() { return m_upperAngle; } public void setLimits(float lower, float upper) { Debug.Assert(lower <= upper); if (lower != m_lowerAngle || upper != m_upperAngle) { m_bodyA.setAwake(true); m_bodyB.setAwake(true); m_impulse.z = 0.0f; m_lowerAngle = lower; m_upperAngle = upper; } } } }
// 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; /// <summary> /// ToInt32(System.Decimal) /// </summary> public class ConvertToInt32_4 { #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; retVal = PosTest5() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ToInt32(0<decimal<0.5)"); try { double random; do random = TestLibrary.Generator.GetDouble(-55); while (random >= 0.5); decimal d = decimal.Parse(random.ToString()); int actual = Convert.ToInt32(d); int expected = 0; if (actual != expected) { TestLibrary.TestFramework.LogError("001.1", "Method ToInt32 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt32(1>decimal>=0.5)"); try { double random; do random = TestLibrary.Generator.GetDouble(-55); while (random < 0.5); decimal d = decimal.Parse(random.ToString()); int actual = Convert.ToInt32(d); int expected = 1; if (actual != expected) { TestLibrary.TestFramework.LogError("002.1", "Method ToInt32 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt32(0)"); try { decimal d = 0m; int actual = Convert.ToInt32(d); int expected = 0; if (actual != expected) { TestLibrary.TestFramework.LogError("003.1", "Method ToInt32 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt32(int16.max)"); try { decimal d = Int32.MaxValue; int actual = Convert.ToInt32(d); int expected = Int32.MaxValue; if (actual != expected) { TestLibrary.TestFramework.LogError("004.1", "Method ToInt32 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt32(int32.min)"); try { decimal d = Int32.MinValue; int actual = Convert.ToInt32(d); int expected = Int32.MinValue; if (actual != expected) { TestLibrary.TestFramework.LogError("005.1", "Method ToInt32 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is not thrown."); try { decimal d = (decimal)Int32.MaxValue + 1; int i = Convert.ToInt32(d); TestLibrary.TestFramework.LogError("101.1", "OverflowException is not thrown."); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is not thrown."); try { decimal d = (decimal)Int32.MinValue - 1; int i = Convert.ToInt32(d); TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown."); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ConvertToInt32_4 test = new ConvertToInt32_4(); TestLibrary.TestFramework.BeginTestCase("ConvertToInt32_4"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
// 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; namespace System.Xml { // Represents an entity reference node. // <code>EntityReference</code> objects may be inserted into the structure // model when an entity reference is in the source document, or when the user // wishes to insert an entity reference. Note that character references and // references to predefined entities are considered to be expanded by the // HTML or XML processor so that characters are represented by their Unicode // equivalent rather than by an entity reference. Moreover, the XML // processor may completely expand references to entities while building the // structure model, instead of providing <code>EntityReference</code> // objects. If it does provide such objects, then for a given // <code>EntityReference</code> node, it may be that there is no // <code>Entity</code> node representing the referenced entity; but if such // an <code>Entity</code> exists, then the child list of the // <code>EntityReference</code> node is the same as that of the // <code>Entity</code> node. As with the <code>Entity</code> node, all // descendants of the <code>EntityReference</code> are readonly. // <p>The resolution of the children of the <code>EntityReference</code> (the // replacement value of the referenced <code>Entity</code>) may be lazily // evaluated; actions by the user (such as calling the // <code>childNodes</code> method on the <code>EntityReference</code> node) // are assumed to trigger the evaluation. internal class XmlEntityReference : XmlLinkedNode { private string _name; private XmlLinkedNode _lastChild; protected internal XmlEntityReference(string name, XmlDocument doc) : base(doc) { if (!doc.IsLoading) { if (name.Length > 0 && name[0] == '#') { throw new ArgumentException(SR.Xdom_InvalidCharacter_EntityReference); } } _name = doc.NameTable.Add(name); doc.fEntRefNodesPresent = true; } // Gets the name of the node. public override string Name { get { return _name; } } // Gets the name of the node without the namespace prefix. public override string LocalName { get { return _name; } } // Gets or sets the value of the node. public override String Value { get { return null; } set { throw new InvalidOperationException(SR.Xdom_EntRef_SetVal); } } // Gets the type of the node. public override XmlNodeType NodeType { get { return XmlNodeType.EntityReference; } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { Debug.Assert(OwnerDocument != null); XmlEntityReference eref = OwnerDocument.CreateEntityReference(_name); return eref; } // // Microsoft extensions // // Gets a value indicating whether the node is read-only. public override bool IsReadOnly { get { return true; // Make entity references readonly } } internal override bool IsContainer { get { return true; } } internal override void SetParent(XmlNode node) { base.SetParent(node); if (LastNode == null && node != null && node != OwnerDocument) { //first time insert the entity reference into the tree, we should expand its children now XmlLoader loader = new XmlLoader(); loader.ExpandEntityReference(this); } } internal override void SetParentForLoad(XmlNode node) { this.SetParent(node); } internal override XmlLinkedNode LastNode { get { return _lastChild; } set { _lastChild = value; } } internal override bool IsValidChildType(XmlNodeType type) { switch (type) { case XmlNodeType.Element: case XmlNodeType.Text: case XmlNodeType.EntityReference: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.ProcessingInstruction: case XmlNodeType.CDATA: return true; default: return false; } } // Saves the node to the specified XmlWriter. public override void WriteTo(XmlWriter w) { w.WriteEntityRef(_name); } // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { // -- eventually will the fix. commented out waiting for finalizing on the issue. foreach (XmlNode n in this) { n.WriteTo(w); } //still use the old code to generate the output /* foreach( XmlNode n in this ) { if ( n.NodeType != XmlNodeType.EntityReference ) n.WriteTo( w ); else n.WriteContentTo( w ); }*/ } public override String BaseURI { get { return OwnerDocument.BaseURI; } } private string ConstructBaseURI(string baseURI, string systemId) { if (baseURI == null) return systemId; int nCount = baseURI.LastIndexOf('/') + 1; string buf = baseURI; if (nCount > 0 && nCount < baseURI.Length) buf = baseURI.Substring(0, nCount); else if (nCount == 0) buf = buf + "\\"; return (buf + systemId.Replace('\\', '/')); } //childrenBaseURI returns where the entity reference node's children come from internal String ChildBaseURI { get { //get the associate entity and return its baseUri XmlEntity ent = OwnerDocument.GetEntityNode(_name); if (ent != null) { if (!string.IsNullOrEmpty(ent.SystemId)) return ConstructBaseURI(ent.BaseURI, ent.SystemId); else return ent.BaseURI; } return String.Empty; } } } }
// 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 Fixtures.DateTimeOffset { using Microsoft.Rest; using Models; /// <summary> /// A sample API that tests datetimeoffset usage for date-time /// </summary> public partial class SwaggerDateTimeOffsetClient : Microsoft.Rest.ServiceClient<SwaggerDateTimeOffsetClient>, ISwaggerDateTimeOffsetClient { /// <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> /// Initializes a new instance of the SwaggerDateTimeOffsetClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SwaggerDateTimeOffsetClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SwaggerDateTimeOffsetClient 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> public SwaggerDateTimeOffsetClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SwaggerDateTimeOffsetClient 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> public SwaggerDateTimeOffsetClient(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 SwaggerDateTimeOffsetClient 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> public SwaggerDateTimeOffsetClient(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> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new System.Uri("http://localhost:3000/api"); 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() } }; 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(); } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Product>> GetProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Product>> PutProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Product>> PostProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Product>> PatchProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PatchProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } 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.Specialized; using System.Reflection; using System.IO; using System.Web; using Mono.Addins; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenMetaverse.Messages.Linden; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; using OSD = OpenMetaverse.StructuredData.OSD; using OSDMap = OpenMetaverse.StructuredData.OSDMap; using OpenSim.Framework.Capabilities; using ExtraParamType = OpenMetaverse.ExtraParamType; namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class UploadObjectAssetModule : INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; #region IRegionModuleBase Members public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { } public void AddRegion(Scene pScene) { m_scene = pScene; } public void RemoveRegion(Scene scene) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; m_scene = null; } public void RegionLoaded(Scene scene) { m_scene.EventManager.OnRegisterCaps += RegisterCaps; } #endregion #region IRegionModule Members public void Close() { } public string Name { get { return "UploadObjectAssetModuleModule"; } } public void RegisterCaps(UUID agentID, Caps caps) { UUID capID = UUID.Random(); m_log.Info("[UploadObjectAssetModule]: /CAPS/" + capID); caps.RegisterHandler("UploadObjectAsset", new RestHTTPHandler("POST", "/CAPS/OA/" + capID + "/", delegate(Hashtable m_dhttpMethod) { return ProcessAdd(m_dhttpMethod, agentID, caps); })); /* caps.RegisterHandler("NewFileAgentInventoryVariablePrice", new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDNewFileAngentInventoryVariablePriceReplyResponse>("POST", "/CAPS/" + capID.ToString(), delegate(LLSDAssetUploadRequest req) { return NewAgentInventoryRequest(req,agentID); })); */ } #endregion /// <summary> /// Parses ad request /// </summary> /// <param name="request"></param> /// <param name="AgentId"></param> /// <param name="cap"></param> /// <returns></returns> public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap) { Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = 400; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = "Request wasn't what was expected"; ScenePresence avatar; if (!m_scene.TryGetScenePresence(AgentId, out avatar)) return responsedata; OSDMap r = (OSDMap)OSDParser.Deserialize((string)request["requestbody"]); UploadObjectAssetMessage message = new UploadObjectAssetMessage(); try { message.Deserialize(r); } catch (Exception ex) { m_log.Error("[UploadObjectAssetModule]: Error deserializing message " + ex.ToString()); message = null; } if (message == null) { responsedata["int_response_code"] = 400; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = "<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>"; return responsedata; } Vector3 pos = avatar.AbsolutePosition + (Vector3.UnitX * avatar.Rotation); Quaternion rot = Quaternion.Identity; Vector3 rootpos = Vector3.Zero; Quaternion rootrot = Quaternion.Identity; SceneObjectGroup rootGroup = null; SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length]; for (int i = 0; i < message.Objects.Length; i++) { UploadObjectAssetMessage.Object obj = message.Objects[i]; PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox(); if (i == 0) { rootpos = obj.Position; rootrot = obj.Rotation; } // Combine the extraparams data into it's ugly blob again.... //int bytelength = 0; //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++) //{ // bytelength += obj.ExtraParams[extparams].ExtraParamData.Length; //} //byte[] extraparams = new byte[bytelength]; //int position = 0; //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++) //{ // Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position, // obj.ExtraParams[extparams].ExtraParamData.Length); // // position += obj.ExtraParams[extparams].ExtraParamData.Length; // } //pbs.ExtraParams = extraparams; for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++) { UploadObjectAssetMessage.Object.ExtraParam extraParam = obj.ExtraParams[extparams]; switch ((ushort)extraParam.Type) { case (ushort)ExtraParamType.Sculpt: Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0); pbs.SculptEntry = true; pbs.SculptTexture = obj.SculptID; pbs.SculptType = (byte)sculpt.Type; break; case (ushort)ExtraParamType.Flexible: Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0); pbs.FlexiEntry = true; pbs.FlexiDrag = flex.Drag; pbs.FlexiForceX = flex.Force.X; pbs.FlexiForceY = flex.Force.Y; pbs.FlexiForceZ = flex.Force.Z; pbs.FlexiGravity = flex.Gravity; pbs.FlexiSoftness = flex.Softness; pbs.FlexiTension = flex.Tension; pbs.FlexiWind = flex.Wind; break; case (ushort)ExtraParamType.Light: Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0); pbs.LightColorA = light.Color.A; pbs.LightColorB = light.Color.B; pbs.LightColorG = light.Color.G; pbs.LightColorR = light.Color.R; pbs.LightCutoff = light.Cutoff; pbs.LightEntry = true; pbs.LightFalloff = light.Falloff; pbs.LightIntensity = light.Intensity; pbs.LightRadius = light.Radius; break; case 0x40: pbs.ReadProjectionData(extraParam.ExtraParamData, 0); break; } } pbs.PathBegin = (ushort) obj.PathBegin; pbs.PathCurve = (byte) obj.PathCurve; pbs.PathEnd = (ushort) obj.PathEnd; pbs.PathRadiusOffset = (sbyte) obj.RadiusOffset; pbs.PathRevolutions = (byte) obj.Revolutions; pbs.PathScaleX = (byte) obj.ScaleX; pbs.PathScaleY = (byte) obj.ScaleY; pbs.PathShearX = (byte) obj.ShearX; pbs.PathShearY = (byte) obj.ShearY; pbs.PathSkew = (sbyte) obj.Skew; pbs.PathTaperX = (sbyte) obj.TaperX; pbs.PathTaperY = (sbyte) obj.TaperY; pbs.PathTwist = (sbyte) obj.Twist; pbs.PathTwistBegin = (sbyte) obj.TwistBegin; pbs.HollowShape = (HollowShape) obj.ProfileHollow; pbs.PCode = (byte) PCode.Prim; pbs.ProfileBegin = (ushort) obj.ProfileBegin; pbs.ProfileCurve = (byte) obj.ProfileCurve; pbs.ProfileEnd = (ushort) obj.ProfileEnd; pbs.Scale = obj.Scale; pbs.State = (byte) 0; SceneObjectPart prim = new SceneObjectPart(); prim.UUID = UUID.Random(); prim.CreatorID = AgentId; prim.OwnerID = AgentId; prim.GroupID = obj.GroupID; prim.LastOwnerID = prim.OwnerID; prim.CreationDate = Util.UnixTimeSinceEpoch(); prim.Name = obj.Name; prim.Description = ""; prim.PayPrice[0] = -2; prim.PayPrice[1] = -2; prim.PayPrice[2] = -2; prim.PayPrice[3] = -2; prim.PayPrice[4] = -2; Primitive.TextureEntry tmp = new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f")); for (int j = 0; j < obj.Faces.Length; j++) { UploadObjectAssetMessage.Object.Face face = obj.Faces[j]; Primitive.TextureEntryFace primFace = tmp.CreateFace((uint) j); primFace.Bump = face.Bump; primFace.RGBA = face.Color; primFace.Fullbright = face.Fullbright; primFace.Glow = face.Glow; primFace.TextureID = face.ImageID; primFace.Rotation = face.ImageRot; primFace.MediaFlags = ((face.MediaFlags & 1) != 0); primFace.OffsetU = face.OffsetS; primFace.OffsetV = face.OffsetT; primFace.RepeatU = face.ScaleS; primFace.RepeatV = face.ScaleT; primFace.TexMapType = (MappingType) (face.MediaFlags & 6); } pbs.TextureEntry = tmp.GetBytes(); prim.Shape = pbs; prim.Scale = obj.Scale; SceneObjectGroup grp = new SceneObjectGroup(); grp.SetRootPart(prim); prim.ParentID = 0; if (i == 0) { rootGroup = grp; } grp.AttachToScene(m_scene); grp.AbsolutePosition = obj.Position; prim.RotationOffset = obj.Rotation; grp.RootPart.IsAttachment = false; // Required for linking grp.RootPart.UpdateFlag = 0; if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos)) { m_scene.AddSceneObject(grp); grp.AbsolutePosition = obj.Position; } allparts[i] = grp; } for (int j = 1; j < allparts.Length; j++) { rootGroup.RootPart.UpdateFlag = 0; allparts[j].RootPart.UpdateFlag = 0; rootGroup.LinkToGroup(allparts[j]); } rootGroup.ScheduleGroupForFullUpdate(); pos = m_scene.GetNewRezLocation(Vector3.Zero, rootpos, UUID.Zero, rot, (byte)1, 1, true, allparts[0].GroupScale(), false); responsedata["int_response_code"] = 200; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(allparts[0].LocalId)); return responsedata; } private string ConvertUintToBytes(uint val) { byte[] resultbytes = Utils.UIntToBytes(val); if (BitConverter.IsLittleEndian) Array.Reverse(resultbytes); return String.Format("<binary encoding=\"base64\">{0}</binary>", Convert.ToBase64String(resultbytes)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace AwesomeNamespace { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// UsageOperations operations. /// </summary> internal partial class UsageOperations : IServiceOperations<StorageManagementClient>, IUsageOperations { /// <summary> /// Initializes a new instance of the UsageOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal UsageOperations(StorageManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the StorageManagementClient /// </summary> public StorageManagementClient Client { get; private set; } /// <summary> /// Gets the current usage count and the limit for the resources under the /// subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<Usage>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Storage/usages").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<Usage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Usage>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/***************************************************************************** * Automatic import and advanced preview added by Mitch Thompson * Full irrevocable rights and permissions granted to Esoteric Software *****************************************************************************/ using System; using System.Collections.Generic; using UnityEditor; #if !UNITY_4_3 using UnityEditor.AnimatedValues; #endif using UnityEngine; using Spine; [CustomEditor(typeof(SkeletonDataAsset))] public class SkeletonDataAssetInspector : Editor { static bool showAnimationStateData = true; static bool showAnimationList = true; static bool showSlotList = false; static bool showAttachments = false; static bool showUnity = true; static bool bakeAnimations = true; static bool bakeIK = true; static SendMessageOptions bakeEventOptions = SendMessageOptions.DontRequireReceiver; private SerializedProperty atlasAssets, skeletonJSON, scale, fromAnimation, toAnimation, duration, defaultMix, controller; #if SPINE_TK2D private SerializedProperty spriteCollection; #endif private bool m_initialized = false; private SkeletonDataAsset m_skeletonDataAsset; private SkeletonData m_skeletonData; private string m_skeletonDataAssetGUID; private bool needToSerialize; List<string> warnings = new List<string>(); void OnEnable () { SpineEditorUtilities.ConfirmInitialization(); try { atlasAssets = serializedObject.FindProperty("atlasAssets"); skeletonJSON = serializedObject.FindProperty("skeletonJSON"); scale = serializedObject.FindProperty("scale"); fromAnimation = serializedObject.FindProperty("fromAnimation"); toAnimation = serializedObject.FindProperty("toAnimation"); duration = serializedObject.FindProperty("duration"); defaultMix = serializedObject.FindProperty("defaultMix"); controller = serializedObject.FindProperty("controller"); #if SPINE_TK2D spriteCollection = serializedObject.FindProperty("spriteCollection"); #endif m_skeletonDataAsset = (SkeletonDataAsset)target; m_skeletonDataAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_skeletonDataAsset)); EditorApplication.update += Update; } catch { } m_skeletonData = m_skeletonDataAsset.GetSkeletonData(true); showUnity = EditorPrefs.GetBool("SkeletonDataAssetInspector_showUnity", true); RepopulateWarnings(); } void OnDestroy () { m_initialized = false; EditorApplication.update -= Update; this.DestroyPreviewInstances(); if (this.m_previewUtility != null) { this.m_previewUtility.Cleanup(); this.m_previewUtility = null; } } override public void OnInspectorGUI () { serializedObject.Update(); EditorGUI.BeginChangeCheck(); #if !SPINE_TK2D EditorGUILayout.PropertyField(atlasAssets, true); #else EditorGUI.BeginDisabledGroup(spriteCollection.objectReferenceValue != null); EditorGUILayout.PropertyField(atlasAssets, true); EditorGUI.EndDisabledGroup(); EditorGUILayout.PropertyField(spriteCollection, true); #endif EditorGUILayout.PropertyField(skeletonJSON); EditorGUILayout.PropertyField(scale); if (EditorGUI.EndChangeCheck()) { if (serializedObject.ApplyModifiedProperties()) { if (m_previewUtility != null) { m_previewUtility.Cleanup(); m_previewUtility = null; } RepopulateWarnings(); OnEnable(); return; } } if (m_skeletonData != null) { DrawAnimationStateInfo(); DrawAnimationList(); DrawSlotList(); DrawUnityTools(); } else { DrawReimportButton(); //Show Warnings foreach (var str in warnings) EditorGUILayout.LabelField(new GUIContent(str, SpineEditorUtilities.Icons.warning)); } if(!Application.isPlaying) serializedObject.ApplyModifiedProperties(); } void DrawMecanim () { EditorGUILayout.PropertyField(controller, new GUIContent("Controller", SpineEditorUtilities.Icons.controllerIcon)); if (controller.objectReferenceValue == null) { GUILayout.BeginHorizontal(); GUILayout.Space(32); if (GUILayout.Button(new GUIContent("Generate Mecanim Controller"), EditorStyles.toolbarButton, GUILayout.Width(195), GUILayout.Height(20))) SkeletonBaker.GenerateMecanimAnimationClips(m_skeletonDataAsset); //GUILayout.Label(new GUIContent("Alternative to SkeletonAnimation, not a requirement.", SpineEditorUtilities.Icons.warning)); GUILayout.EndHorizontal(); EditorGUILayout.LabelField("Alternative to SkeletonAnimation, not required", EditorStyles.miniLabel); } } void DrawUnityTools () { bool pre = showUnity; showUnity = EditorGUILayout.Foldout(showUnity, new GUIContent("Unity Tools", SpineEditorUtilities.Icons.unityIcon)); if (pre != showUnity) EditorPrefs.SetBool("SkeletonDataAssetInspector_showUnity", showUnity); if (showUnity) { EditorGUI.indentLevel++; EditorGUILayout.LabelField("SkeletonAnimator", EditorStyles.boldLabel); EditorGUI.indentLevel++; DrawMecanim(); EditorGUI.indentLevel--; GUILayout.Space(32); EditorGUILayout.LabelField("Baking", EditorStyles.boldLabel); EditorGUILayout.HelpBox("WARNING!\n\nBaking is NOT the same as SkeletonAnimator!\nDoes not support the following:\n\tFlipX or Y\n\tInheritScale\n\tColor Keys\n\tDraw Order Keys\n\tIK and Curves are sampled at 60fps and are not realtime.\n\tPlease read SkeletonBaker.cs comments for full details.\n\nThe main use of Baking is to export Spine projects to be used without the Spine Runtime (ie: for sale on the Asset Store, or background objects that are animated only with a wind noise generator)", MessageType.Warning, true); EditorGUI.indentLevel++; bakeAnimations = EditorGUILayout.Toggle("Bake Animations", bakeAnimations); EditorGUI.BeginDisabledGroup(bakeAnimations == false); { EditorGUI.indentLevel++; bakeIK = EditorGUILayout.Toggle("Bake IK", bakeIK); bakeEventOptions = (SendMessageOptions)EditorGUILayout.EnumPopup("Event Options", bakeEventOptions); EditorGUI.indentLevel--; } EditorGUI.EndDisabledGroup(); EditorGUI.indentLevel++; GUILayout.BeginHorizontal(); { if (GUILayout.Button(new GUIContent("Bake All Skins", SpineEditorUtilities.Icons.unityIcon), GUILayout.Height(32), GUILayout.Width(150))) SkeletonBaker.BakeToPrefab(m_skeletonDataAsset, m_skeletonData.Skins, "", bakeAnimations, bakeIK, bakeEventOptions); string skinName = "<No Skin>"; if (m_skeletonAnimation != null && m_skeletonAnimation.skeleton != null) { Skin bakeSkin = m_skeletonAnimation.skeleton.Skin; if (bakeSkin == null) { skinName = "Default"; bakeSkin = m_skeletonData.Skins.Items[0]; } else skinName = m_skeletonAnimation.skeleton.Skin.Name; bool oops = false; try { GUILayout.BeginVertical(); if (GUILayout.Button(new GUIContent("Bake " + skinName, SpineEditorUtilities.Icons.unityIcon), GUILayout.Height(32), GUILayout.Width(250))) SkeletonBaker.BakeToPrefab(m_skeletonDataAsset, new ExposedList<Skin>(new Skin[] { bakeSkin }), "", bakeAnimations, bakeIK, bakeEventOptions); GUILayout.BeginHorizontal(); GUILayout.Label(new GUIContent("Skins", SpineEditorUtilities.Icons.skinsRoot), GUILayout.Width(50)); if (GUILayout.Button(skinName, EditorStyles.popup, GUILayout.Width(196))) { SelectSkinContext(); } GUILayout.EndHorizontal(); } catch { oops = true; //GUILayout.BeginVertical(); } if (!oops) GUILayout.EndVertical(); } } GUILayout.EndHorizontal(); EditorGUI.indentLevel--; EditorGUI.indentLevel--; } } void DrawReimportButton () { EditorGUI.BeginDisabledGroup(skeletonJSON.objectReferenceValue == null); if (GUILayout.Button(new GUIContent("Attempt Reimport", SpineEditorUtilities.Icons.warning))) { DoReimport(); return; } EditorGUI.EndDisabledGroup(); } void DoReimport () { SpineEditorUtilities.ImportSpineContent(new string[] { AssetDatabase.GetAssetPath(skeletonJSON.objectReferenceValue) }, true); if (m_previewUtility != null) { m_previewUtility.Cleanup(); m_previewUtility = null; } RepopulateWarnings(); OnEnable(); EditorUtility.SetDirty(m_skeletonDataAsset); } void DrawAnimationStateInfo () { showAnimationStateData = EditorGUILayout.Foldout(showAnimationStateData, "Animation State Data"); if (!showAnimationStateData) return; EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(defaultMix); // Animation names String[] animations = new String[m_skeletonData.Animations.Count]; for (int i = 0; i < animations.Length; i++) animations[i] = m_skeletonData.Animations.Items[i].Name; for (int i = 0; i < fromAnimation.arraySize; i++) { SerializedProperty from = fromAnimation.GetArrayElementAtIndex(i); SerializedProperty to = toAnimation.GetArrayElementAtIndex(i); SerializedProperty durationProp = duration.GetArrayElementAtIndex(i); EditorGUILayout.BeginHorizontal(); from.stringValue = animations[EditorGUILayout.Popup(Math.Max(Array.IndexOf(animations, from.stringValue), 0), animations)]; to.stringValue = animations[EditorGUILayout.Popup(Math.Max(Array.IndexOf(animations, to.stringValue), 0), animations)]; durationProp.floatValue = EditorGUILayout.FloatField(durationProp.floatValue); if (GUILayout.Button("Delete")) { duration.DeleteArrayElementAtIndex(i); toAnimation.DeleteArrayElementAtIndex(i); fromAnimation.DeleteArrayElementAtIndex(i); } EditorGUILayout.EndHorizontal(); } EditorGUILayout.BeginHorizontal(); EditorGUILayout.Space(); if (GUILayout.Button("Add Mix")) { duration.arraySize++; toAnimation.arraySize++; fromAnimation.arraySize++; } EditorGUILayout.Space(); EditorGUILayout.EndHorizontal(); if (EditorGUI.EndChangeCheck()) { m_skeletonDataAsset.FillStateData(); EditorUtility.SetDirty(m_skeletonDataAsset); serializedObject.ApplyModifiedProperties(); needToSerialize = true; } } void DrawAnimationList () { showAnimationList = EditorGUILayout.Foldout(showAnimationList, new GUIContent("Animations", SpineEditorUtilities.Icons.animationRoot)); if (!showAnimationList) return; if (GUILayout.Button(new GUIContent("Setup Pose", SpineEditorUtilities.Icons.skeleton), GUILayout.Width(105), GUILayout.Height(18))) { StopAnimation(); m_skeletonAnimation.skeleton.SetToSetupPose(); m_requireRefresh = true; } EditorGUILayout.LabelField("Name", "Duration"); foreach (Spine.Animation a in m_skeletonData.Animations) { GUILayout.BeginHorizontal(); if (m_skeletonAnimation != null && m_skeletonAnimation.state != null) { if (m_skeletonAnimation.state.GetCurrent(0) != null && m_skeletonAnimation.state.GetCurrent(0).Animation == a) { GUI.contentColor = Color.red; if (GUILayout.Button("\u25BA", EditorStyles.toolbarButton, GUILayout.Width(24))) { StopAnimation(); } GUI.contentColor = Color.white; } else { if (GUILayout.Button("\u25BA", EditorStyles.toolbarButton, GUILayout.Width(24))) { PlayAnimation(a.Name, true); } } } else { GUILayout.Label("?", GUILayout.Width(24)); } EditorGUILayout.LabelField(new GUIContent(a.Name, SpineEditorUtilities.Icons.animation), new GUIContent(a.Duration.ToString("f3") + "s" + ("(" + (Mathf.RoundToInt(a.Duration * 30)) + ")").PadLeft(12, ' '))); GUILayout.EndHorizontal(); } } void DrawSlotList () { showSlotList = EditorGUILayout.Foldout(showSlotList, new GUIContent("Slots", SpineEditorUtilities.Icons.slotRoot)); if (!showSlotList) return; if (m_skeletonAnimation == null || m_skeletonAnimation.skeleton == null) return; EditorGUI.indentLevel++; try { showAttachments = EditorGUILayout.ToggleLeft("Show Attachments", showAttachments); } catch { return; } List<Attachment> slotAttachments = new List<Attachment>(); List<string> slotAttachmentNames = new List<string>(); List<string> defaultSkinAttachmentNames = new List<string>(); var defaultSkin = m_skeletonData.Skins.Items[0]; Skin skin = m_skeletonAnimation.skeleton.Skin; if (skin == null) { skin = defaultSkin; } for (int i = m_skeletonAnimation.skeleton.Slots.Count - 1; i >= 0; i--) { Slot slot = m_skeletonAnimation.skeleton.Slots.Items[i]; EditorGUILayout.LabelField(new GUIContent(slot.Data.Name, SpineEditorUtilities.Icons.slot)); if (showAttachments) { EditorGUI.indentLevel++; slotAttachments.Clear(); slotAttachmentNames.Clear(); defaultSkinAttachmentNames.Clear(); skin.FindNamesForSlot(i, slotAttachmentNames); skin.FindAttachmentsForSlot(i, slotAttachments); if (skin != defaultSkin) { defaultSkin.FindNamesForSlot(i, defaultSkinAttachmentNames); defaultSkin.FindNamesForSlot(i, slotAttachmentNames); defaultSkin.FindAttachmentsForSlot(i, slotAttachments); } else { defaultSkin.FindNamesForSlot(i, defaultSkinAttachmentNames); } for (int a = 0; a < slotAttachments.Count; a++) { Attachment attachment = slotAttachments[a]; string name = slotAttachmentNames[a]; Texture2D icon = null; var type = attachment.GetType(); if (type == typeof(RegionAttachment)) icon = SpineEditorUtilities.Icons.image; else if (type == typeof(MeshAttachment)) icon = SpineEditorUtilities.Icons.mesh; else if (type == typeof(BoundingBoxAttachment)) icon = SpineEditorUtilities.Icons.boundingBox; else if (type == typeof(SkinnedMeshAttachment)) icon = SpineEditorUtilities.Icons.weights; else icon = SpineEditorUtilities.Icons.warning; //TODO: Waterboard Nate //if (name != attachment.Name) //icon = SpineEditorUtilities.Icons.skinPlaceholder; bool initialState = slot.Attachment == attachment; bool toggled = EditorGUILayout.ToggleLeft(new GUIContent(name, icon), slot.Attachment == attachment); if (!defaultSkinAttachmentNames.Contains(name)) { Rect skinPlaceHolderIconRect = GUILayoutUtility.GetLastRect(); skinPlaceHolderIconRect.width = SpineEditorUtilities.Icons.skinPlaceholder.width; skinPlaceHolderIconRect.height = SpineEditorUtilities.Icons.skinPlaceholder.height; GUI.DrawTexture(skinPlaceHolderIconRect, SpineEditorUtilities.Icons.skinPlaceholder); } if (toggled != initialState) { if (toggled) { slot.Attachment = attachment; } else { slot.Attachment = null; } m_requireRefresh = true; } } EditorGUI.indentLevel--; } } EditorGUI.indentLevel--; } void RepopulateWarnings () { warnings.Clear(); if (skeletonJSON.objectReferenceValue == null) warnings.Add("Missing Skeleton JSON"); else { if (SpineEditorUtilities.IsValidSpineData((TextAsset)skeletonJSON.objectReferenceValue) == false) { warnings.Add("Skeleton data file is not a valid JSON or binary file."); } else { bool detectedNullAtlasEntry = false; List<Atlas> atlasList = new List<Atlas>(); for (int i = 0; i < atlasAssets.arraySize; i++) { if (atlasAssets.GetArrayElementAtIndex(i).objectReferenceValue == null) { detectedNullAtlasEntry = true; break; } else { atlasList.Add(((AtlasAsset)atlasAssets.GetArrayElementAtIndex(i).objectReferenceValue).GetAtlas()); } } if (detectedNullAtlasEntry) warnings.Add("AtlasAsset elements cannot be Null"); else { //get requirements var missingPaths = SpineEditorUtilities.GetRequiredAtlasRegions(AssetDatabase.GetAssetPath((TextAsset)skeletonJSON.objectReferenceValue)); foreach (var atlas in atlasList) { for (int i = 0; i < missingPaths.Count; i++) { if (atlas.FindRegion(missingPaths[i]) != null) { missingPaths.RemoveAt(i); i--; } } } foreach (var str in missingPaths) warnings.Add("Missing Region: '" + str + "'"); } } } } //preview window stuff private PreviewRenderUtility m_previewUtility; private GameObject m_previewInstance; private Vector2 previewDir; private SkeletonAnimation m_skeletonAnimation; //private SkeletonData m_skeletonData; private static int sliderHash = "Slider".GetHashCode(); private float m_lastTime; private bool m_playing; private bool m_requireRefresh; private Color m_originColor = new Color(0.3f, 0.3f, 0.3f, 1); private void StopAnimation () { m_skeletonAnimation.state.ClearTrack(0); m_playing = false; } List<Spine.Event> m_animEvents = new List<Spine.Event>(); List<float> m_animEventFrames = new List<float>(); private void PlayAnimation (string animName, bool loop) { m_animEvents.Clear(); m_animEventFrames.Clear(); m_skeletonAnimation.state.SetAnimation(0, animName, loop); Spine.Animation a = m_skeletonAnimation.state.GetCurrent(0).Animation; foreach (Timeline t in a.Timelines) { if (t.GetType() == typeof(EventTimeline)) { EventTimeline et = (EventTimeline)t; for (int i = 0; i < et.Events.Length; i++) { m_animEvents.Add(et.Events[i]); m_animEventFrames.Add(et.Frames[i]); } } } m_playing = true; } private void InitPreview () { if (this.m_previewUtility == null) { this.m_lastTime = Time.realtimeSinceStartup; this.m_previewUtility = new PreviewRenderUtility(true); this.m_previewUtility.m_Camera.orthographic = true; this.m_previewUtility.m_Camera.orthographicSize = 1; this.m_previewUtility.m_Camera.cullingMask = -2147483648; this.m_previewUtility.m_Camera.nearClipPlane = 0.01f; this.m_previewUtility.m_Camera.farClipPlane = 1000f; this.CreatePreviewInstances(); } } private void CreatePreviewInstances () { this.DestroyPreviewInstances(); if (this.m_previewInstance == null) { try { string skinName = EditorPrefs.GetString(m_skeletonDataAssetGUID + "_lastSkin", ""); m_previewInstance = SpineEditorUtilities.InstantiateSkeletonAnimation((SkeletonDataAsset)target, skinName).gameObject; m_previewInstance.hideFlags = HideFlags.HideAndDontSave; m_previewInstance.layer = 0x1f; m_skeletonAnimation = m_previewInstance.GetComponent<SkeletonAnimation>(); m_skeletonAnimation.initialSkinName = skinName; m_skeletonAnimation.LateUpdate(); m_skeletonData = m_skeletonAnimation.skeletonDataAsset.GetSkeletonData(true); m_previewInstance.GetComponent<Renderer>().enabled = false; m_initialized = true; AdjustCameraGoals(true); } catch { } } } private void DestroyPreviewInstances () { if (this.m_previewInstance != null) { DestroyImmediate(this.m_previewInstance); m_previewInstance = null; } m_initialized = false; } public override bool HasPreviewGUI () { //TODO: validate json data for (int i = 0; i < atlasAssets.arraySize; i++) { var prop = atlasAssets.GetArrayElementAtIndex(i); if (prop.objectReferenceValue == null) return false; } return skeletonJSON.objectReferenceValue != null; } Texture m_previewTex = new Texture(); public override void OnInteractivePreviewGUI (Rect r, GUIStyle background) { this.InitPreview(); if (UnityEngine.Event.current.type == EventType.Repaint) { if (m_requireRefresh) { this.m_previewUtility.BeginPreview(r, background); this.DoRenderPreview(true); this.m_previewTex = this.m_previewUtility.EndPreview(); m_requireRefresh = false; } if (this.m_previewTex != null) GUI.DrawTexture(r, m_previewTex, ScaleMode.StretchToFill, false); } DrawSkinToolbar(r); NormalizedTimeBar(r); //TODO: implement panning // this.previewDir = Drag2D(this.previewDir, r); MouseScroll(r); } float m_orthoGoal = 1; Vector3 m_posGoal = new Vector3(0, 0, -10); double m_adjustFrameEndTime = 0; private void AdjustCameraGoals (bool calculateMixTime) { if (this.m_previewInstance == null) return; if (calculateMixTime) { if (m_skeletonAnimation.state.GetCurrent(0) != null) { m_adjustFrameEndTime = EditorApplication.timeSinceStartup + m_skeletonAnimation.state.GetCurrent(0).Mix; } } GameObject go = this.m_previewInstance; Bounds bounds = go.GetComponent<Renderer>().bounds; m_orthoGoal = bounds.size.y; m_posGoal = bounds.center + new Vector3(0, 0, -10); } private void AdjustCameraGoals () { AdjustCameraGoals(false); } private void AdjustCamera () { if (m_previewUtility == null) return; if (EditorApplication.timeSinceStartup < m_adjustFrameEndTime) { AdjustCameraGoals(); } float orthoSet = Mathf.Lerp(this.m_previewUtility.m_Camera.orthographicSize, m_orthoGoal, 0.1f); this.m_previewUtility.m_Camera.orthographicSize = orthoSet; float dist = Vector3.Distance(m_previewUtility.m_Camera.transform.position, m_posGoal); if (dist > 60f * ((SkeletonDataAsset)target).scale) { Vector3 pos = Vector3.Lerp(this.m_previewUtility.m_Camera.transform.position, m_posGoal, 0.1f); pos.x = 0; this.m_previewUtility.m_Camera.transform.position = pos; this.m_previewUtility.m_Camera.transform.rotation = Quaternion.identity; m_requireRefresh = true; } } private void DoRenderPreview (bool drawHandles) { GameObject go = this.m_previewInstance; if (m_requireRefresh && go != null) { go.GetComponent<Renderer>().enabled = true; if (EditorApplication.isPlaying) { //do nothing } else { m_skeletonAnimation.Update((Time.realtimeSinceStartup - m_lastTime)); } m_lastTime = Time.realtimeSinceStartup; if (!EditorApplication.isPlaying) m_skeletonAnimation.LateUpdate(); if (drawHandles) { Handles.SetCamera(m_previewUtility.m_Camera); Handles.color = m_originColor; Handles.DrawLine(new Vector3(-1000 * m_skeletonDataAsset.scale, 0, 0), new Vector3(1000 * m_skeletonDataAsset.scale, 0, 0)); Handles.DrawLine(new Vector3(0, 1000 * m_skeletonDataAsset.scale, 0), new Vector3(0, -1000 * m_skeletonDataAsset.scale, 0)); } this.m_previewUtility.m_Camera.Render(); if (drawHandles) { Handles.SetCamera(m_previewUtility.m_Camera); foreach (var slot in m_skeletonAnimation.skeleton.Slots) { if (slot.Attachment is BoundingBoxAttachment) { DrawBoundingBox(slot.Bone, (BoundingBoxAttachment)slot.Attachment); } } } go.GetComponent<Renderer>().enabled = false; } } void DrawBoundingBox (Bone bone, BoundingBoxAttachment box) { float[] worldVerts = new float[box.Vertices.Length]; box.ComputeWorldVertices(bone, worldVerts); Handles.color = Color.green; Vector3 lastVert = Vector3.back; Vector3 vert = Vector3.back; Vector3 firstVert = new Vector3(worldVerts[0], worldVerts[1], -1); for (int i = 0; i < worldVerts.Length; i += 2) { vert.x = worldVerts[i]; vert.y = worldVerts[i + 1]; if (i > 0) { Handles.DrawLine(lastVert, vert); } lastVert = vert; } Handles.DrawLine(lastVert, firstVert); } void Update () { AdjustCamera(); if (m_playing) { m_requireRefresh = true; Repaint(); } else if (m_requireRefresh) { Repaint(); } else { //only needed if using smooth menus } if (needToSerialize) { needToSerialize = false; serializedObject.ApplyModifiedProperties(); } } void DrawSkinToolbar (Rect r) { if (m_skeletonAnimation == null) return; if (m_skeletonAnimation.skeleton != null) { string label = (m_skeletonAnimation.skeleton != null && m_skeletonAnimation.skeleton.Skin != null) ? m_skeletonAnimation.skeleton.Skin.Name : "default"; Rect popRect = new Rect(r); popRect.y += 32; popRect.x += 4; popRect.height = 24; popRect.width = 40; EditorGUI.DropShadowLabel(popRect, new GUIContent("Skin", SpineEditorUtilities.Icons.skinsRoot)); popRect.y += 11; popRect.width = 150; popRect.x += 44; if (GUI.Button(popRect, label, EditorStyles.popup)) { SelectSkinContext(); } } } void SelectSkinContext () { GenericMenu menu = new GenericMenu(); foreach (Skin s in m_skeletonData.Skins) { menu.AddItem(new GUIContent(s.Name), this.m_skeletonAnimation.skeleton.Skin == s, SetSkin, (object)s); } menu.ShowAsContext(); } void SetSkin (object o) { Skin skin = (Skin)o; m_skeletonAnimation.initialSkinName = skin.Name; m_skeletonAnimation.Reset(); m_requireRefresh = true; EditorPrefs.SetString(m_skeletonDataAssetGUID + "_lastSkin", skin.Name); } void NormalizedTimeBar (Rect r) { if (m_skeletonAnimation == null) return; Rect barRect = new Rect(r); barRect.height = 32; barRect.x += 4; barRect.width -= 4; GUI.Box(barRect, ""); Rect lineRect = new Rect(barRect); float width = lineRect.width; TrackEntry t = m_skeletonAnimation.state.GetCurrent(0); if (t != null) { int loopCount = (int)(t.Time / t.EndTime); float currentTime = t.Time - (t.EndTime * loopCount); float normalizedTime = currentTime / t.Animation.Duration; lineRect.x = barRect.x + (width * normalizedTime) - 0.5f; lineRect.width = 2; GUI.color = Color.red; GUI.DrawTexture(lineRect, EditorGUIUtility.whiteTexture); GUI.color = Color.white; for (int i = 0; i < m_animEvents.Count; i++) { //TODO: Tooltip //Spine.Event spev = animEvents[i]; float fr = m_animEventFrames[i]; Rect evRect = new Rect(barRect); evRect.x = Mathf.Clamp(((fr / t.Animation.Duration) * width) - (SpineEditorUtilities.Icons._event.width / 2), barRect.x, float.MaxValue); evRect.width = SpineEditorUtilities.Icons._event.width; evRect.height = SpineEditorUtilities.Icons._event.height; evRect.y += SpineEditorUtilities.Icons._event.height; GUI.DrawTexture(evRect, SpineEditorUtilities.Icons._event); //TODO: Tooltip /* UnityEngine.Event ev = UnityEngine.Event.current; if(ev.isMouse){ if(evRect.Contains(ev.mousePosition)){ Rect tooltipRect = new Rect(evRect); tooltipRect.width = 500; tooltipRect.y -= 4; tooltipRect.x += 4; GUI.Label(tooltipRect, spev.Data.Name); } } */ } } } void MouseScroll (Rect position) { UnityEngine.Event current = UnityEngine.Event.current; int controlID = GUIUtility.GetControlID(sliderHash, FocusType.Passive); switch (current.GetTypeForControl(controlID)) { case EventType.ScrollWheel: if (position.Contains(current.mousePosition)) { m_orthoGoal += current.delta.y * ((SkeletonDataAsset)target).scale * 10; GUIUtility.hotControl = controlID; current.Use(); } break; } } //TODO: Implement preview panning /* static Vector2 Drag2D(Vector2 scrollPosition, Rect position) { int controlID = GUIUtility.GetControlID(sliderHash, FocusType.Passive); UnityEngine.Event current = UnityEngine.Event.current; switch (current.GetTypeForControl(controlID)) { case EventType.MouseDown: if (position.Contains(current.mousePosition) && (position.width > 50f)) { GUIUtility.hotControl = controlID; current.Use(); EditorGUIUtility.SetWantsMouseJumping(1); } return scrollPosition; case EventType.MouseUp: if (GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; } EditorGUIUtility.SetWantsMouseJumping(0); return scrollPosition; case EventType.MouseMove: return scrollPosition; case EventType.MouseDrag: if (GUIUtility.hotControl == controlID) { scrollPosition -= (Vector2) (((current.delta * (!current.shift ? ((float) 1) : ((float) 3))) / Mathf.Min(position.width, position.height)) * 140f); scrollPosition.y = Mathf.Clamp(scrollPosition.y, -90f, 90f); current.Use(); GUI.changed = true; } return scrollPosition; } return scrollPosition; } */ public override GUIContent GetPreviewTitle () { return new GUIContent("Preview"); } public override void OnPreviewSettings () { if (!m_initialized) { GUILayout.HorizontalSlider(0, 0, 2, GUILayout.MaxWidth(64)); } else { float speed = GUILayout.HorizontalSlider(m_skeletonAnimation.timeScale, 0, 2, GUILayout.MaxWidth(64)); //snap to nearest 0.25 float y = speed / 0.25f; int q = Mathf.RoundToInt(y); speed = q * 0.25f; m_skeletonAnimation.timeScale = speed; } } //TODO: Fix first-import error //TODO: Update preview without thumbnail public override Texture2D RenderStaticPreview (string assetPath, UnityEngine.Object[] subAssets, int width, int height) { Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false); this.InitPreview(); if (this.m_previewUtility.m_Camera == null) return null; m_requireRefresh = true; this.DoRenderPreview(false); AdjustCameraGoals(false); this.m_previewUtility.m_Camera.orthographicSize = m_orthoGoal / 2; this.m_previewUtility.m_Camera.transform.position = m_posGoal; this.m_previewUtility.BeginStaticPreview(new Rect(0, 0, width, height)); this.DoRenderPreview(false); //TODO: Figure out why this is throwing errors on first attempt // if(m_previewUtility != null){ // Handles.SetCamera(this.m_previewUtility.m_Camera); // Handles.BeginGUI(); // GUI.DrawTexture(new Rect(40,60,width,height), SpineEditorUtilities.Icons.spine, ScaleMode.StretchToFill); // Handles.EndGUI(); // } tex = this.m_previewUtility.EndStaticPreview(); return tex; } }
// 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.Linq; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Semantics; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines { /// <summary> /// CA1065: Do not raise exceptions in unexpected locations /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1065"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.DoNotRaiseExceptionsInUnexpectedLocationsTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessagePropertyGetter = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.DoNotRaiseExceptionsInUnexpectedLocationsMessagePropertyGetter), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageHasAllowedExceptions = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.DoNotRaiseExceptionsInUnexpectedLocationsMessageHasAllowedExceptions), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageNoAllowedExceptions = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.DoNotRaiseExceptionsInUnexpectedLocationsMessageNoAllowedExceptions), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.DoNotRaiseExceptionsInUnexpectedLocationsDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private const string helpLinkUri = "https://msdn.microsoft.com/en-us/library/bb386039.aspx"; internal static DiagnosticDescriptor PropertyGetterRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessagePropertyGetter, DiagnosticCategory.Design, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: s_localizableDescription, helpLinkUri: helpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor HasAllowedExceptionsRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageHasAllowedExceptions, DiagnosticCategory.Design, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: s_localizableDescription, helpLinkUri: helpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor NoAllowedExceptionsRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageNoAllowedExceptions, DiagnosticCategory.Design, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: s_localizableDescription, helpLinkUri: helpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(PropertyGetterRule, HasAllowedExceptionsRule, NoAllowedExceptionsRule); public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); analysisContext.RegisterCompilationStartAction(compilationStartContext => { Compilation compilation = compilationStartContext.Compilation; INamedTypeSymbol exceptionType = WellKnownTypes.Exception(compilation); if (exceptionType == null) { return; } // Get a list of interesting categories of methods to analyze. List<MethodCategory> methodCategories = GetMethodCategories(compilation); compilationStartContext.RegisterOperationBlockStartActionInternal(operationBlockContext => { var methodSymbol = operationBlockContext.OwningSymbol as IMethodSymbol; if (methodSymbol == null) { return; } // Find out if this given method is one of the interesting categories of methods. // For eg: certain Equals methods or certain accessors etc. MethodCategory methodCategory = methodCategories.FirstOrDefault(l => l.IsMatch(methodSymbol, compilation)); if (methodCategory == null) { return; } // For the interesting methods, register an operation action to catch all // Throw statements. operationBlockContext.RegisterOperationActionInternal(operationContext => { IThrowStatement operation = operationContext.Operation as IThrowStatement; if (operation.ThrownObject?.Type is INamedTypeSymbol type && type.DerivesFrom(exceptionType)) { // If no exceptions are allowed or if the thrown exceptions is not an allowed one.. if (methodCategory.AllowedExceptions.IsEmpty || !methodCategory.AllowedExceptions.Contains(type)) { operationContext.ReportDiagnostic( operation.Syntax.CreateDiagnostic(methodCategory.Rule, methodSymbol.Name, type.Name)); } } }, OperationKind.ThrowStatement); }); }); } /// <summary> /// This object describes a class of methods where exception throwing statements should be analyzed. /// </summary> private class MethodCategory { /// <summary> /// Function used to determine whether a given method symbol falls into this category. /// </summary> private readonly Func<IMethodSymbol, Compilation, bool> _matchFunction; /// <summary> /// Determines if we should analyze non-public methods of a given type. /// </summary> private readonly bool _analyzeOnlyPublicMethods; /// <summary> /// The rule that should be fired if there is an exception in this kind of method. /// </summary> public DiagnosticDescriptor Rule { get; } /// <summary> /// List of exception types which are allowed to be thrown inside this category of method. /// This list will be empty if no exceptions are allowed. /// </summary> public ImmutableHashSet<ITypeSymbol> AllowedExceptions { get; } public MethodCategory(Func<IMethodSymbol, Compilation, bool> matchFunction, bool analyzeOnlyPublicMethods, DiagnosticDescriptor rule, params ITypeSymbol[] allowedExceptionTypes) { _matchFunction = matchFunction; _analyzeOnlyPublicMethods = analyzeOnlyPublicMethods; this.Rule = rule; AllowedExceptions = allowedExceptionTypes.ToImmutableHashSet(); } /// <summary> /// Checks if the given method belong this category /// </summary> public bool IsMatch(IMethodSymbol method, Compilation compilation) { // If we are supposed to analyze only public methods get the resultant visibility // i.e public method inside an internal class is not considered public. if (_analyzeOnlyPublicMethods && method.GetResultantVisibility() != SymbolVisibility.Public) { return false; } return _matchFunction(method, compilation); } } private static List<MethodCategory> GetMethodCategories(Compilation compilation) { var methodCategories = new List<MethodCategory> { new MethodCategory(IsPropertyGetter, true, PropertyGetterRule, WellKnownTypes.InvalidOperationException(compilation), WellKnownTypes.NotSupportedException(compilation)), new MethodCategory(IsIndexerGetter, true, PropertyGetterRule, WellKnownTypes.InvalidOperationException(compilation), WellKnownTypes.NotSupportedException(compilation), WellKnownTypes.ArgumentException(compilation), WellKnownTypes.KeyNotFoundException(compilation)), new MethodCategory(IsEventAccessor, true, HasAllowedExceptionsRule, WellKnownTypes.InvalidOperationException(compilation), WellKnownTypes.NotSupportedException(compilation), WellKnownTypes.ArgumentException(compilation)), new MethodCategory(IsGetHashCodeInterfaceImplementation, true, HasAllowedExceptionsRule, WellKnownTypes.ArgumentException(compilation)), new MethodCategory(IsEqualsOverrideOrInterfaceImplementation, true, NoAllowedExceptionsRule), new MethodCategory(IsEqualityOperator, true, NoAllowedExceptionsRule), new MethodCategory(IsGetHashCodeOverride, true, NoAllowedExceptionsRule), new MethodCategory(IsToString, true, NoAllowedExceptionsRule), new MethodCategory(IsImplicitCastOperator, true, NoAllowedExceptionsRule), new MethodCategory(IsStaticConstructor, false, NoAllowedExceptionsRule), new MethodCategory(IsFinalizer, false, NoAllowedExceptionsRule), new MethodCategory(IMethodSymbolExtensions.IsDisposeImplementation, true, NoAllowedExceptionsRule), }; return methodCategories; } private static bool IsPropertyGetter(IMethodSymbol method, Compilation compilation) { return method.IsPropertyGetter(); } private static bool IsIndexerGetter(IMethodSymbol method, Compilation compilation) { return method.IsIndexerGetter(); } private static bool IsEventAccessor(IMethodSymbol method, Compilation compilation) { return method.IsEventAccessor(); } private static bool IsEqualsOverrideOrInterfaceImplementation(IMethodSymbol method, Compilation compilation) { return method.IsEqualsOverride() || IsEqualsInterfaceImplementation(method, compilation); } /// <summary> /// Checks if a given method implements IEqualityComparer.Equals or IEquatable.Equals. /// </summary> private static bool IsEqualsInterfaceImplementation(IMethodSymbol method, Compilation compilation) { if (method.Name != WellKnownMemberNames.ObjectEquals) { return false; } int paramCount = method.Parameters.Length; if (method.ReturnType.SpecialType == SpecialType.System_Boolean && (paramCount == 1 || paramCount == 2)) { // Substitute the type of the first parameter of Equals in the generic interface and then check if that // interface method is implemented by the given method. INamedTypeSymbol iEqualityComparer = WellKnownTypes.GenericIEqualityComparer(compilation); if (method.IsImplementationOfInterfaceMethod(method.Parameters.First().Type, iEqualityComparer, WellKnownMemberNames.ObjectEquals)) { return true; } // Substitute the type of the first parameter of Equals in the generic interface and then check if that // interface method is implemented by the given method. INamedTypeSymbol iEquatable = WellKnownTypes.GenericIEquatable(compilation); if (method.IsImplementationOfInterfaceMethod(method.Parameters.First().Type, iEquatable, WellKnownMemberNames.ObjectEquals)) { return true; } } return false; } /// <summary> /// Checks if a given method implements IEqualityComparer.GetHashCode or IHashCodeProvider.GetHashCode. /// </summary> /// <param name="method"></param> /// <param name="compilation"></param> /// <returns></returns> private static bool IsGetHashCodeInterfaceImplementation(IMethodSymbol method, Compilation compilation) { if (method.Name != WellKnownMemberNames.ObjectGetHashCode) { return false; } if (method.ReturnType.SpecialType == SpecialType.System_Int32 && method.Parameters.Length == 1) { // Substitute the type of the first parameter of Equals in the generic interface and then check if that // interface method is implemented by the given method. INamedTypeSymbol iEqualityComparer = WellKnownTypes.GenericIEqualityComparer(compilation); if (method.IsImplementationOfInterfaceMethod(method.Parameters.First().Type, iEqualityComparer, WellKnownMemberNames.ObjectGetHashCode)) { return true; } INamedTypeSymbol iHashCodeProvider = WellKnownTypes.IHashCodeProvider(compilation); if (method.IsImplementationOfInterfaceMethod(null, iHashCodeProvider, WellKnownMemberNames.ObjectGetHashCode)) { return true; } } return false; } private static bool IsGetHashCodeOverride(IMethodSymbol method, Compilation compilation) { return method.IsGetHashCodeOverride(); } private static bool IsToString(IMethodSymbol method, Compilation compilation) { return method.IsToStringOverride(); } private static bool IsStaticConstructor(IMethodSymbol method, Compilation compilation) { return method.MethodKind == MethodKind.StaticConstructor; } private static bool IsFinalizer(IMethodSymbol method, Compilation compilation) { return method.IsFinalizer(); } private static bool IsEqualityOperator(IMethodSymbol method, Compilation compilation) { if (!method.IsStatic || !method.IsPublic()) return false; switch (method.Name) { case WellKnownMemberNames.EqualityOperatorName: case WellKnownMemberNames.InequalityOperatorName: return true; default: return false; } } private static bool IsImplicitCastOperator(IMethodSymbol method, Compilation compilation) { if (!method.IsStatic || !method.IsPublic()) return false; return (method.Name == WellKnownMemberNames.ImplicitConversionName); } } }
using System; using Microsoft.SPOT; using System.Threading; using System.Text; using GT = Gadgeteer; using GTM = Gadgeteer.Modules; using GTI = Gadgeteer.SocketInterfaces; using Gadgeteer; namespace SpiderStarTunesBT { /// <summary> /// A Bluetooth module for Microsoft .NET Gadgeteer /// </summary> public class Bluetooth : GTM.Module { /// <summary> /// Direct access to Serial Port. /// </summary> public GTI.Serial serialPort; private GTI.DigitalOutput reset; private GTI.InterruptInput statusInt; private Thread readerThread; /// <summary> /// Possible states of the Bluetooth module /// </summary> public enum BluetoothState { /// <summary> /// Module is initializing /// </summary> Initializing = 0, /// <summary> /// Module is ready /// </summary> Ready = 1, /// <summary> /// Module is in pairing mode /// </summary> Inquiring = 2, /// <summary> /// Module is making a connection attempt /// </summary> Connecting = 3, /// <summary> /// Module is connected /// </summary> Connected = 4, /// <summary> /// Module is diconnected /// </summary> Disconnected = 5 } // Note: A constructor summary is auto-generated by the doc builder. /// <summary></summary> /// <param name="socketNumber">The socket that this module is plugged in to.</param> public Bluetooth(int socketNumber) { // This finds the Socket instance from the user-specified socket number. // This will generate user-friendly error messages if the socket is invalid. // If there is more than one socket on this module, then instead of "null" for the last parameter, // put text that identifies the socket to the user (e.g. "S" if there is a socket type S) Socket socket = Socket.GetSocket(socketNumber, true, this, null); this.reset = GTI.DigitalOutputFactory.Create(socket, Socket.Pin.Six, false, this); this.statusInt = GTI.InterruptInputFactory.Create(socket, Socket.Pin.Three, GTI.GlitchFilterMode.Off, GTI.ResistorMode.Disabled, GTI.InterruptMode.RisingAndFallingEdge, this); this.serialPort = GTI.SerialFactory.Create(socket, 38400, GTI.SerialParity.None, GTI.SerialStopBits.One, 8, GTI.HardwareFlowControl.NotRequired, this); //this.statusInt.Interrupt += new GTI.InterruptInput.InterruptEventHandler(statusInt_Interrupt); this.serialPort.ReadTimeout = Timeout.Infinite; this.serialPort.Open(); Thread.Sleep(5); this.reset.Write(true); readerThread = new Thread(new ThreadStart(runReaderThread)); readerThread.Start(); Thread.Sleep(500); } /// <summary> /// Hard Reset Bluetooth module /// </summary> public void Reset() { this.reset.Write(false); Thread.Sleep(5); this.reset.Write(true); } /// <summary> /// Gets a value that indicates whether the bluetooth connection is connected. /// </summary> public bool IsConnected { get { return this.statusInt.Read(); } } /// <summary> /// Thread that continuously reads incoming messages from the module, /// parses them and triggers the corresponding events. /// </summary> private void runReaderThread() { Debug.Print("Reader Thread"); while (true) { String response = ""; while (serialPort.BytesToRead > 0) { response = response + (char)serialPort.ReadByte(); } if (response.Length > 0) { Debug.Print(response); //Check Bluetooth State Changed if (response.IndexOf("+BTSTATE:") > -1) { string atCommand = "+BTSTATE:"; //String parsing // Return format: +COPS:<mode>[,<format>,<oper>] int first = response.IndexOf(atCommand) + atCommand.Length; int last = response.IndexOf("\n", first); int state = int.Parse(((response.Substring(first, last - first)).Trim())); OnBluetoothStateChanged(this, (BluetoothState)state); } //Check Pin Requested if (response.IndexOf("+INPIN") > -1) { // EDUARDO : Needs testing OnPinRequested(this); } if (response.IndexOf("+RTINQ") > -1) { //EDUARDO: Needs testing string atCommand = "+RTINQ="; //String parsing int first = response.IndexOf(atCommand) + atCommand.Length; int mid = response.IndexOf(";", first); int last = response.IndexOf("\r", first); // Keep reading until the end of the message while (last < 0) { while (serialPort.BytesToRead > 0) { response = response + (char)serialPort.ReadByte(); } last = response.IndexOf("\r", first); } string address = ((response.Substring(first, mid - first)).Trim()); string name = (response.Substring(mid + 1, last - mid)); OnDeviceInquired(this, address, name); //Debug.Print("Add: " + address + ", Name: " + name ); } else { OnDataReceived(this, response); } } Thread.Sleep(10); } } #region DELEGATES AND EVENTS #region Bluetooth State Changed /// <summary> /// Represents the delegate used for the <see cref="BluetoothStateChanged"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="btState">Current state of the Bluetooth module</param> public delegate void BluetoothStateChangedHandler(Bluetooth sender, BluetoothState btState); /// <summary> /// Event raised when the bluetooth module changes its state. /// </summary> public event BluetoothStateChangedHandler BluetoothStateChanged; private BluetoothStateChangedHandler onBluetoothStateChanged; /// <summary> /// Raises the <see cref="BluetoothStateChanged"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="btState">Current state of the Bluetooth module</param> protected virtual void OnBluetoothStateChanged(Bluetooth sender, BluetoothState btState) { if (onBluetoothStateChanged == null) onBluetoothStateChanged = new BluetoothStateChangedHandler(OnBluetoothStateChanged); if (Program.CheckAndInvoke(BluetoothStateChanged, onBluetoothStateChanged, sender, btState)) { BluetoothStateChanged(sender, btState); } } #endregion #region DataReceived /// <summary> /// Represents the delegate used for the <see cref="DataReceived"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="data">Data received from the Bluetooth module</param> public delegate void DataReceivedHandler(Bluetooth sender, string data); /// <summary> /// Event raised when the bluetooth module changes its state. /// </summary> public event DataReceivedHandler DataReceived; private DataReceivedHandler onDataReceived; /// <summary> /// Raises the <see cref="DataReceived"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="data">Data string received by the Bluetooth module</param> protected virtual void OnDataReceived(Bluetooth sender, string data) { if (onDataReceived == null) onDataReceived = new DataReceivedHandler(OnDataReceived); if (Program.CheckAndInvoke(DataReceived, onDataReceived, sender, data)) { DataReceived(sender, data); } } #endregion #region PinRequested /// <summary> /// Represents the delegate used for the <see cref="PinRequested"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> public delegate void PinRequestedHandler(Bluetooth sender); /// <summary> /// Event raised when the bluetooth module changes its state. /// </summary> public event PinRequestedHandler PinRequested; private PinRequestedHandler onPinRequested; /// <summary> /// Raises the <see cref="PinRequested"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> protected virtual void OnPinRequested(Bluetooth sender) { if (onPinRequested == null) onPinRequested = new PinRequestedHandler(OnPinRequested); if (Program.CheckAndInvoke(PinRequested, onPinRequested, sender)) { PinRequested(sender); } } #endregion #endregion #region DeviceInquired /// <summary> /// Represents the delegate used for the <see cref="DeviceInquired"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="macAddress">MAC Address of the inquired device</param> /// <param name="name">Name of the inquired device</param> public delegate void DeviceInquiredHandler(Bluetooth sender, string macAddress, string name); /// <summary> /// Event raised when the bluetooth module changes its state. /// </summary> public event DeviceInquiredHandler DeviceInquired; private DeviceInquiredHandler onDeviceInquired; /// <summary> /// Raises the <see cref="PinRequested"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="macAddress">MAC Address of the inquired device</param> /// <param name="name">Name of the inquired device</param> protected virtual void OnDeviceInquired(Bluetooth sender, string macAddress, string name) { if (onDeviceInquired == null) onDeviceInquired = new DeviceInquiredHandler(OnDeviceInquired); if (Program.CheckAndInvoke(DeviceInquired, onDeviceInquired, sender, macAddress, name)) { DeviceInquired(sender, macAddress, name); } } #endregion private object _lock = new Object(); private Client _client; /// <summary> /// Sets Bluetooth module to work in Client mode. /// </summary> public Client ClientMode { get { lock (_lock) { if (_host != null) throw new InvalidOperationException("Cannot use both Client and Host modes for Bluetooth module"); if (_client == null) _client = new Client(this); return _client; } } } private Host _host; /// <summary> /// Sets Bluetooth module to work in Host mode. /// </summary> public Host HostMode { get { lock (_lock) { if (_client != null) throw new InvalidOperationException("Cannot use both Client and Host modes for Bluetooth module"); if (_host == null) _host = new Host(this); return _host; } } } /// <summary> /// Sets the device name as seen by other devices /// </summary> /// <param name="name">Name of the device</param> public void SetDeviceName(string name) { this.serialPort.Write("\r\n+STNA=" + name + "\r\n"); } /// <summary> /// Sets the PIN code for the Bluetooth module /// </summary> /// <param name="pinCode"></param> public void SetPinCode(string pinCode) { this.serialPort.Write("\r\n +STPIN=" + pinCode + "\r\n"); } /// <summary> /// Client functionality for the Bluetooth module /// </summary> public class Client { private Bluetooth bluetooth; internal Client(Bluetooth bluetooth) { Debug.Print("Client Mode"); this.bluetooth = bluetooth; bluetooth.serialPort.Write("\r\n+STWMOD=0\r\n"); } /// <summary> /// Enters pairing mode /// </summary> public void EnterPairingMode() { Debug.Print("Enter Pairing Mode"); bluetooth.serialPort.Write("\r\n+INQ=1\r\n"); } /// <summary> /// Inputs pin code /// </summary> /// <param name="pinCode">Module's pin code. Default: 0000</param> public void InputPinCode(string pinCode) { Debug.Print("Inputting pin: " + pinCode); bluetooth.serialPort.Write("\r\n+RTPIN=" + pinCode + "\r\n"); } /// <summary> /// Closes current connection. Doesn't work yet. /// </summary> public void Disconnect() { Debug.Print("Disconnection is not working..."); //NOT WORKING // Documentation states that in order to disconnect, we pull PIO0 HIGH, // but this pin is not available in the socket... (see schematics) } /// <summary> /// Sends data through the connection. /// </summary> /// <param name="message">String containing the data to be sent</param> public void Send(string message) { Debug.Print("Sending: " + message); bluetooth.serialPort.WriteLine(message); } } /// <summary> /// Implements the host functionality for the Bluetooth module /// </summary> public class Host { private Bluetooth bluetooth; internal Host(Bluetooth bluetooth) { Debug.Print("Host mode"); this.bluetooth = bluetooth; bluetooth.serialPort.Write("\r\n+STWMOD=1\r\n"); } /// <summary> /// Starts inquiring for devices /// </summary> public void InquireDevice() { Debug.Print("Inquiring device"); bluetooth.serialPort.Write("\r\n+INQ=1\r\n"); } /// <summary> /// Makes a connection with a device using its MAC address. /// </summary> /// <param name="macAddress">MAC address of the device</param> public void Connect(string macAddress) { Debug.Print("Connecting to: " + macAddress); bluetooth.serialPort.Write("\r\n+CONN=" + macAddress + "\r\n"); } /// <summary> /// Inputs the PIN code. /// </summary> /// <param name="pinCode">PIN code. Default 0000</param> public void InputPinCode(string pinCode) { Debug.Print("Inputting pin: " + pinCode); bluetooth.serialPort.Write("\r\n+RTPIN=" + pinCode + "\r\n"); } /// <summary> /// Closes the current connection. Doesn't work yet. /// </summary> public void Disconnect() { Debug.Print("Disconnection is not working..."); //NOT WORKING // Documentation states that in order to disconnect, we pull PIO0 HIGH, // but this pin is not available in the socket... (see schematics) } } } }
/* * Copyright (C) 2015-2016 Kevin Cotugno * All rights reserved * * Distributed under the terms of the MIT license. See the * accompanying LICENSE file or https://opensource.org/licenses/MIT. * * Author: kcotugno * Date: 2/23/2016 */ using OpenARLog.ADIF; using System; using System.Collections.Generic; using System.IO; using OpenARLog.Data; namespace OpenARLog.ADIF { public class ADIReader { #region Private Members private string _filePath; private StreamReader _streamer; private string _headerText; // Lists to hold the data. private List<_Field> _headerFields; private List<_Field> _qsoFields; private struct _Field { public _FieldHeader _header; public string _data; } // A struct told hold an entry header to be passed to the data parser. private struct _FieldHeader { public string Name; public int Length; public string Type; } #endregion public ADIReader() { } public ADIReader(string filepath) { Open(filepath); } #region Public Functions public void Open(string filepath) { try { _streamer = new StreamReader(filepath, System.Text.Encoding.UTF8); _filePath = filepath; _headerText = string.Empty; _headerFields = new List<_Field>(); _qsoFields = new List<_Field>(); } catch { // TODO } } public void Close() { _streamer.Close(); } public List<QSO> Read() { List<QSO> contacts = new List<QSO>(); if (!_streamer.EndOfStream) { ParseHeader(); ParseRecords(); contacts = GetQSOsFromRecords(); } //_headerFields.ForEach(x => Console.WriteLine(x._header.name + ":" + x._header.length + ":" + x._header.type + ":" + x._data)); //_qsoFields.ForEach(x => Console.WriteLine(x._header.name + ":" + x._header.length + ":" + x._header.type + ":" + x._data)); return contacts; } #endregion #region Private Functions // Parse the file header. As per the format, if "<" is found at index 0, it is assumed // that there is no header and would thus move to scanning records. Otherwise the line is // passed to the line parser for further evaluation. private void ParseHeader() { bool isEOH = false; bool firstLine = true; string buffer = string.Empty; // Continue until there is no more header. while (!isEOH) { buffer = _streamer.ReadLine(); // Make sure there is a header. if (firstLine && (buffer.IndexOf("<") == 0)) return; firstLine = false; // Parse the line. isEOH = ParseHeaderLine(buffer); } } private void ParseRecords() { bool isEOF = false; bool isEOR = false; string buffer = string.Empty; while (!isEOF) { buffer = _streamer.ReadLine(); isEOR = ParseQSOLine(buffer); isEOF = _streamer.EndOfStream; } } // General line parser. private List<_Field> ParseLine(string line) { string sub = string.Empty; int index = 0; _Field record = new _Field(); List<_Field> results = new List<_Field>(); // Multiple fields can be on one line. Thus we must make sure all are accounted for. while (line.IndexOf("<", index) != -1 && line.IndexOf(">", index) != -1) { // Separate and pass just the header. record._header = ParseFieldHeader(line.Substring(index, (line.IndexOf(">", index) - index) + 1)); // Separate and pass the field. record._data = GetFieldDataFromWithHeader(record._header, line.Substring(index, (line.IndexOf(">", index) - index) + record._header.Length + 1)); // Place record in a list in case there are multiple per line. results.Add(record); // Keep the index upto date on what has been parsed. index = line.IndexOf(">", index) + record._header.Length + 1; } return results; } // File header parser. Calls on ParseLine(string). private bool ParseHeaderLine(string line) { // TODO throw an excpetion. // This should only be null if at the end of stream. // If a null line shows up here it means the file is corrupt. if (line == null) return true; int i = line.IndexOf("<"); // If the line is from the header add the text to the header string. if (i == -1 && line != string.Empty) { _headerText += line + "\n"; } else if (line != string.Empty) { _headerFields.AddRange(ParseLine(line)); // This is a pretty inefficient way of finding the EOH. Fix later. // TODO Make more efficient. return _headerFields.Exists(x => x._header.Name == "EOH"); } return false; } private bool ParseQSOLine(string line) { // TODO throw an excpetion. // This should only be null if at the end of stream. // If a null line shows up here it means the file is corrupt. if (line == null) return true; int i = line.IndexOf("<"); // If the line is from the header add the text to the header string. if (line != string.Empty && i != -1) { _qsoFields.AddRange(ParseLine(line)); } return false; } // Parse a field header,e.g., <programid:9>. private _FieldHeader ParseFieldHeader(string header) { // Struct to hold the header data. _FieldHeader results; results.Name = string.Empty; results.Length = 0; results.Type = null; string sub = string.Empty; // These indexs will give us access to the data between the delimiters. int open = header.IndexOf("<"); int first = header.IndexOf(":"); int second = header.IndexOf(":", first + 1); int close = header.IndexOf(">"); // The data name is simple and always in a header. if (first != -1) { results.Name = header.Substring((open + 1), (first - open) - 1).ToUpper(); } else { results.Name = header.Substring((open + 1), (close - open) - 1).ToUpper(); return results; } // Only user defined fields will have a third item in a header. // Currently, in the long run, user defined fields will be ignored. if (second == -1) { results.Length = int.Parse(header.Substring((first + 1), (close - first) - 1)); } else { results.Length = int.Parse(header.Substring((first + 1), (second - first) - 1)); results.Type = header.Substring((second + 1), (close - second) - 1); } return results; } private string GetFieldDataFromWithHeader(_FieldHeader header, string line) { string data; data = line.Substring((line.IndexOf(">") + 1), header.Length); return data; } private List<QSO> GetQSOsFromRecords() { List<QSO> qsos = new List<QSO>(); QSO temp = new QSO(); foreach (_Field x in _qsoFields) { if (x._header.Name == "EOR") { qsos.Add(temp); temp = new QSO(); } else { switch (x._header.Name) { case "NAME": temp.Name = x._data; break; case "CALL": temp.Callsign = x._data; break; case "COUNTRY": temp.Country = x._data; break; case "STATE": temp.State = x._data; break; case "CNTY": temp.County = x._data; break; case "QTH": temp.City = x._data; break; case "GRIDSQUARE": temp.GridSquare = x._data; break; case "FREQ": temp.Frequency = x._data; break; case "BAND": temp.Band = x._data; break; case "MODE": temp.Mode = x._data; break; case "TIME_ON": temp.DateTimeOn = MergeDateAndTime(temp.DateTimeOn, GetTimeFromRecord(x)); break; case "QSO_DATE": temp.DateTimeOn = MergeDateAndTime(temp.DateTimeOn, GetDateFromRecord(x)); break; case "TIME_OFF": temp.DateTimeOff = MergeDateAndTime(temp.DateTimeOff, GetTimeFromRecord(x)); break; case "QSO_DATE_OFF": temp.DateTimeOff = MergeDateAndTime(temp.DateTimeOff, GetDateFromRecord(x)); break; case "OPERATOR": temp.Operator = x._data; break; case "MY_NAME": temp.MyName = x._data; break; case "MY_COUNTRY": temp.MyCountry = x._data; break; case "My_STATE": temp.MyState = x._data; break; case "MY_CNTY": temp.MyCounty = x._data; break; case "MY_CITY": temp.MyCity = x._data; break; case "MY_GRIDSQUARE": temp.MyGridSquare = x._data; break; default: break; } } } return qsos; } // The date and time get stored in different filed in file.We need to merge these so TimeOn/TimeOff store both. private DateTime MergeDateAndTime(DateTime current, DateTime toMerge) { if (current == null) return toMerge; int year = 0; int month = 0; int day = 0; int hours = 0; int minutes = 0; int seconds = 0; if (current.ToString("yyyyMMdd") == "15000101") { year = Convert.ToInt32(toMerge.ToString("yyyy")); month = Convert.ToInt32(toMerge.ToString("%M")); day = Convert.ToInt32(toMerge.ToString("%d")); hours = Convert.ToInt32(current.ToString("%H")); minutes = Convert.ToInt32(current.ToString("%m")); seconds = Convert.ToInt32(current.ToString("%s")); return new DateTime(year, month, day, hours, minutes, seconds, DateTimeKind.Utc); } else { year = Convert.ToInt32(current.ToString("yyyy")); month = Convert.ToInt32(current.ToString("%M")); day = Convert.ToInt32(current.ToString("%d")); hours = Convert.ToInt32(toMerge.ToString("%H")); minutes = Convert.ToInt32(toMerge.ToString("%m")); seconds = Convert.ToInt32(toMerge.ToString("%s")); return new DateTime(year, month, day, hours, minutes, seconds, DateTimeKind.Utc); } } // The ADIF file format stores its times in UTC. We will leave any conversion to the parent program. DateTime GetTimeFromRecord(_Field record) { if (record._header.Length != 6 && record._header.Length != 4) return new DateTime(); string temp = string.Empty; int hours = 0; int minutes = 0; int seconds = 0; hours = Convert.ToInt32(record._data.Substring(0, 2)); minutes = Convert.ToInt32(record._data.Substring(2, 2)); if (record._data.Length == 6) seconds = Convert.ToInt32(record._data.Substring(4, 2)); // The time and date are stored separately. So we will set the date here to 1/1/1500. // This date is such so we can know if the date needs to be updated when merging the // date and time. return new DateTime(1500, 1, 1, hours, minutes, seconds, DateTimeKind.Utc); } // The ADIF file format stores its date with respect to the UTC time. private DateTime GetDateFromRecord(_Field record) { if (record._header.Length != 8) return new DateTime(); int year = 0; int month = 0; int day = 0; year = Convert.ToInt32(record._data.Substring(0, 4)); month = Convert.ToInt32(record._data.Substring(4, 2)); day = Convert.ToInt32(record._data.Substring(6, 2)); return new DateTime(year, month, day); } #endregion } }
namespace Nancy.Testing { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Nancy.Bootstrapper; using Nancy.Configuration; using Nancy.Helpers; using Nancy.IO; /// <summary> /// Provides the capability of executing a request with Nancy, using a specific configuration provided by an <see cref="INancyBootstrapper"/> instance. /// </summary> public class Browser : IHideObjectMembers { private readonly Action<BrowserContext> defaultBrowserContext; private readonly INancyEngine engine; private readonly INancyEnvironment environment; private readonly IDictionary<string, string> cookies = new Dictionary<string, string>(); /// <summary> /// Initializes a new instance of the <see cref="Browser"/> class, with the /// provided <see cref="ConfigurableBootstrapper"/> configuration. /// </summary> /// <param name="action">The <see cref="ConfigurableBootstrapper"/> configuration that should be used by the bootstrapper.</param> /// <param name="defaults">The default <see cref="BrowserContext"/> that should be used in a all requests through this browser object.</param> public Browser(Action<ConfigurableBootstrapper.ConfigurableBootstrapperConfigurator> action, Action<BrowserContext> defaults = null) : this(new ConfigurableBootstrapper(action), defaults) { } /// <summary> /// Initializes a new instance of the <see cref="Browser"/> class. /// </summary> /// <param name="bootstrapper">A <see cref="INancyBootstrapper"/> instance that determines the Nancy configuration that should be used by the browser.</param> /// <param name="defaults">The default <see cref="BrowserContext"/> that should be used in a all requests through this browser object.</param> public Browser(INancyBootstrapper bootstrapper, Action<BrowserContext> defaults = null) { bootstrapper.Initialise(); this.engine = bootstrapper.GetEngine(); this.environment = bootstrapper.GetEnvironment(); this.defaultBrowserContext = defaults ?? DefaultBrowserContext; } /// <summary> /// Performs a DELETE request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Delete(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("DELETE", path, browserContext); } /// <summary> /// Performs a DELETE request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Delete(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("DELETE", url, browserContext); } /// <summary> /// Performs a GET request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Get(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("GET", path, browserContext); } /// <summary> /// Performs a GET request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Get(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("GET", url, browserContext); } /// <summary> /// Performs a HEAD request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Head(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("HEAD", path, browserContext); } /// <summary> /// Performs a HEAD request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Head(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("HEAD", url, browserContext); } /// <summary> /// Performs a OPTIONS request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Options(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("OPTIONS", path, browserContext); } /// <summary> /// Performs a OPTIONS request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Options(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("OPTIONS", url, browserContext); } /// <summary> /// Performs a PATCH request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Patch(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PATCH", path, browserContext); } /// <summary> /// Performs a PATCH request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Patch(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PATCH", url, browserContext); } /// <summary> /// Performs a POST request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Post(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("POST", path, browserContext); } /// <summary> /// Performs a POST request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Post(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("POST", url, browserContext); } /// <summary> /// Performs a PUT request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Put(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PUT", path, browserContext); } /// <summary> /// Performs a PUT request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> Put(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PUT", url, browserContext); } /// <summary> /// Performs a request of the HTTP <paramref name="method"/>, on the given <paramref name="url"/>, using the /// provided <paramref name="browserContext"/> configuration. /// </summary> /// <param name="method">HTTP method to send the request as.</param> /// <param name="url">The URl of the request.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public async Task<BrowserResponse> HandleRequest(string method, Url url, Action<BrowserContext> browserContext) { var browserContextValues = BuildBrowserContextValues(browserContext ?? (with => { })); var request = CreateRequest(method, url, browserContextValues); var context = await this.engine.HandleRequest(request).ConfigureAwait(false); var response = new BrowserResponse(context, this, (BrowserContext)browserContextValues); this.CaptureCookies(response); return response; } /// <summary> /// Performs a request of the HTTP <paramref name="method"/>, on the given <paramref name="path"/>, using the /// provided <paramref name="browserContext"/> configuration. /// </summary> /// <param name="method">HTTP method to send the request as.</param> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public Task<BrowserResponse> HandleRequest(string method, string path, Action<BrowserContext> browserContext) { var url = Uri.IsWellFormedUriString(path, UriKind.Relative) ? new Url { Path = path } : (Url)new Uri(path); return this.HandleRequest(method, url, browserContext); } private static void DefaultBrowserContext(BrowserContext context) { context.HttpRequest(); } private void SetCookies(BrowserContext context) { if (!this.cookies.Any()) { return; } var cookieString = this.cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format("{0}={1};", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value))); context.Header("Cookie", cookieString); } private void CaptureCookies(BrowserResponse response) { if (response.Cookies == null || !response.Cookies.Any()) { return; } foreach (var cookie in response.Cookies) { if (string.IsNullOrEmpty(cookie.Value)) { this.cookies.Remove(cookie.Name); } else { this.cookies[cookie.Name] = cookie.Value; } } } private static void BuildRequestBody(IBrowserContextValues contextValues) { if (contextValues.Body != null) { return; } var useFormValues = !string.IsNullOrEmpty(contextValues.FormValues); var bodyContents = useFormValues ? contextValues.FormValues : contextValues.BodyString; var bodyBytes = bodyContents != null ? Encoding.UTF8.GetBytes(bodyContents) : ArrayCache.Empty<byte>(); if (useFormValues && !contextValues.Headers.ContainsKey("Content-Type")) { contextValues.Headers["Content-Type"] = new[] { "application/x-www-form-urlencoded" }; } contextValues.Body = new MemoryStream(bodyBytes); } private IBrowserContextValues BuildBrowserContextValues(Action<BrowserContext> browserContext) { var context = new BrowserContext(this.environment); this.SetCookies(context); this.defaultBrowserContext.Invoke(context); browserContext.Invoke(context); var contextValues = (IBrowserContextValues)context; if (!contextValues.Headers.ContainsKey("user-agent")) { contextValues.Headers.Add("user-agent", new[] { "Nancy.Testing.Browser" }); } return contextValues; } private static Request CreateRequest(string method, Url url, IBrowserContextValues contextValues) { BuildRequestBody(contextValues); var requestStream = RequestStream.FromStream(contextValues.Body, 0, true); var certBytes = (contextValues.ClientCertificate == null) ? ArrayCache.Empty<byte>() : contextValues.ClientCertificate.GetRawCertData(); var requestUrl = url; requestUrl.Scheme = string.IsNullOrWhiteSpace(contextValues.Protocol) ? requestUrl.Scheme : contextValues.Protocol; requestUrl.HostName = string.IsNullOrWhiteSpace(contextValues.HostName) ? requestUrl.HostName : contextValues.HostName; requestUrl.Query = string.IsNullOrWhiteSpace(url.Query) ? (contextValues.QueryString ?? string.Empty) : url.Query; return new Request(method, requestUrl, requestStream, contextValues.Headers, contextValues.UserHostAddress, certBytes); } } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org/?p=license&r=2.4 // **************************************************************** using System; using NUnit.Framework.Constraints; using NUnit.Framework.SyntaxHelpers; namespace NUnit.Framework.Tests { /// <summary> /// This test fixture attempts to exercise all the syntactic /// variations of Assert without getting into failures, errors /// or corner cases. Thus, some of the tests may be duplicated /// in other fixtures. /// /// Each test performs the same operations using the classic /// syntax (if available) and the new syntax in both the /// helper-based and inherited forms. /// /// This Fixture will eventually be duplicated in other /// supported languages. /// </summary> [TestFixture] public class AssertSyntaxTests : AssertionHelper { [Test] public void IsNull() { // Classic syntax Assert.IsNull(null); // Helper syntax Assert.That(null, Is.Null); // Inherited syntax Expect(null, Null); } [Test] public void IsNotNull() { // Classic syntax Assert.IsNotNull(42); // Helper syntax Assert.That(42, Is.Not.Null); // Inherited syntax Expect( 42, Not.Null ); } [Test] public void IsTrue() { // Classic syntax Assert.IsTrue(2+2==4); // Helper syntax Assert.That(2+2==4, Is.True); Assert.That(2+2==4); // Inherited syntax Expect(2+2==4, True); Expect(2+2==4); } [Test] public void IsFalse() { // Classic syntax Assert.IsFalse(2+2==5); // Helper syntax Assert.That(2+2== 5, Is.False); // Inherited syntax Expect(2+2==5, False); } [Test] public void IsNaN() { double d = double.NaN; float f = float.NaN; // Classic syntax Assert.IsNaN(d); Assert.IsNaN(f); // Helper syntax Assert.That(d, Is.NaN); Assert.That(f, Is.NaN); // Inherited syntax Expect(d, NaN); Expect(f, NaN); } [Test] public void EmptyStringTests() { // Classic syntax Assert.IsEmpty(""); Assert.IsNotEmpty("Hello!"); // Helper syntax Assert.That("", Is.Empty); Assert.That("Hello!", Is.Not.Empty); // Inherited syntax Expect("", Empty); Expect("Hello!", Not.Empty); } [Test] public void EmptyCollectionTests() { // Classic syntax Assert.IsEmpty(new bool[0]); Assert.IsNotEmpty(new int[] { 1, 2, 3 }); // Helper syntax Assert.That(new bool[0], Is.Empty); Assert.That(new int[] { 1, 2, 3 }, Is.Not.Empty); // Inherited syntax Expect(new bool[0], Empty); Expect(new int[] { 1, 2, 3 }, Not.Empty); } [Test] public void ExactTypeTests() { // Classic syntax workarounds Assert.AreEqual(typeof(string), "Hello".GetType()); Assert.AreEqual("System.String", "Hello".GetType().FullName); Assert.AreNotEqual(typeof(int), "Hello".GetType()); Assert.AreNotEqual("System.Int32", "Hello".GetType().FullName); // Helper syntax Assert.That("Hello", Is.TypeOf(typeof(string))); Assert.That("Hello", Is.Not.TypeOf(typeof(int))); // Inherited syntax Expect( "Hello", TypeOf(typeof(string))); Expect( "Hello", Not.TypeOf(typeof(int))); } [Test] public void InstanceOfTypeTests() { // Classic syntax Assert.IsInstanceOfType(typeof(string), "Hello"); Assert.IsNotInstanceOfType(typeof(string), 5); // Helper syntax Assert.That("Hello", Is.InstanceOfType(typeof(string))); Assert.That(5, Is.Not.InstanceOfType(typeof(string))); // Inherited syntax Expect("Hello", InstanceOfType(typeof(string))); Expect(5, Not.InstanceOfType(typeof(string))); } [Test] public void AssignableFromTypeTests() { // Classic syntax Assert.IsAssignableFrom(typeof(string), "Hello"); Assert.IsNotAssignableFrom(typeof(string), 5); // Helper syntax Assert.That( "Hello", Is.AssignableFrom(typeof(string))); Assert.That( 5, Is.Not.AssignableFrom(typeof(string))); // Inherited syntax Expect( "Hello", AssignableFrom(typeof(string))); Expect( 5, Not.AssignableFrom(typeof(string))); } [Test] public void SubstringTests() { string phrase = "Hello World!"; string[] array = new string[] { "abc", "bad", "dba" }; // Classic Syntax StringAssert.Contains("World", phrase); // Helper syntax Assert.That(phrase, Text.Contains("World")); // Only available using new syntax Assert.That(phrase, Text.DoesNotContain("goodbye")); Assert.That(phrase, Text.Contains("WORLD").IgnoreCase); Assert.That(phrase, Text.DoesNotContain("BYE").IgnoreCase); Assert.That(array, Text.All.Contains( "b" ) ); // Inherited syntax Expect(phrase, Contains("World")); // Only available using new syntax Expect(phrase, Not.Contains("goodbye")); Expect(phrase, Contains("WORLD").IgnoreCase); Expect(phrase, Not.Contains("BYE").IgnoreCase); Expect(array, All.Contains("b")); } [Test] public void StartsWithTests() { string phrase = "Hello World!"; string[] greetings = new string[] { "Hello!", "Hi!", "Hola!" }; // Classic syntax StringAssert.StartsWith("Hello", phrase); // Helper syntax Assert.That(phrase, Text.StartsWith("Hello")); // Only available using new syntax Assert.That(phrase, Text.DoesNotStartWith("Hi!")); Assert.That(phrase, Text.StartsWith("HeLLo").IgnoreCase); Assert.That(phrase, Text.DoesNotStartWith("HI").IgnoreCase); Assert.That(greetings, Text.All.StartsWith("h").IgnoreCase); // Inherited syntax Expect(phrase, StartsWith("Hello")); // Only available using new syntax Expect(phrase, Not.StartsWith("Hi!")); Expect(phrase, StartsWith("HeLLo").IgnoreCase); Expect(phrase, Not.StartsWith("HI").IgnoreCase); Expect(greetings, All.StartsWith("h").IgnoreCase); } [Test] public void EndsWithTests() { string phrase = "Hello World!"; string[] greetings = new string[] { "Hello!", "Hi!", "Hola!" }; // Classic Syntax StringAssert.EndsWith("!", phrase); // Helper syntax Assert.That(phrase, Text.EndsWith("!")); // Only available using new syntax Assert.That(phrase, Text.DoesNotEndWith("?")); Assert.That(phrase, Text.EndsWith("WORLD!").IgnoreCase); Assert.That(greetings, Text.All.EndsWith("!")); // Inherited syntax Expect(phrase, EndsWith("!")); // Only available using new syntax Expect(phrase, Not.EndsWith("?")); Expect(phrase, EndsWith("WORLD!").IgnoreCase); Expect(greetings, All.EndsWith("!") ); } [Test] public void EqualIgnoringCaseTests() { string phrase = "Hello World!"; // Classic syntax StringAssert.AreEqualIgnoringCase("hello world!",phrase); // Helper syntax Assert.That(phrase, Is.EqualTo("hello world!").IgnoreCase); //Only available using new syntax Assert.That(phrase, Is.Not.EqualTo("goodbye world!").IgnoreCase); Assert.That(new string[] { "Hello", "World" }, Is.EqualTo(new object[] { "HELLO", "WORLD" }).IgnoreCase); Assert.That(new string[] {"HELLO", "Hello", "hello" }, Is.All.EqualTo( "hello" ).IgnoreCase); // Inherited syntax Expect(phrase, EqualTo("hello world!").IgnoreCase); //Only available using new syntax Expect(phrase, Not.EqualTo("goodbye world!").IgnoreCase); Expect(new string[] { "Hello", "World" }, EqualTo(new object[] { "HELLO", "WORLD" }).IgnoreCase); Expect(new string[] {"HELLO", "Hello", "hello" }, All.EqualTo( "hello" ).IgnoreCase); } [Test] public void RegularExpressionTests() { string phrase = "Now is the time for all good men to come to the aid of their country."; string[] quotes = new string[] { "Never say never", "It's never too late", "Nevermore!" }; // Classic syntax StringAssert.IsMatch( "all good men", phrase ); StringAssert.IsMatch( "Now.*come", phrase ); // Helper syntax Assert.That( phrase, Text.Matches( "all good men" ) ); Assert.That( phrase, Text.Matches( "Now.*come" ) ); // Only available using new syntax Assert.That(phrase, Text.DoesNotMatch("all.*men.*good")); Assert.That(phrase, Text.Matches("ALL").IgnoreCase); Assert.That(quotes, Text.All.Matches("never").IgnoreCase); // Inherited syntax Expect( phrase, Matches( "all good men" ) ); Expect( phrase, Matches( "Now.*come" ) ); // Only available using new syntax Expect(phrase, Not.Matches("all.*men.*good")); Expect(phrase, Matches("ALL").IgnoreCase); Expect(quotes, All.Matches("never").IgnoreCase); } [Test] public void EqualityTests() { int[] i3 = new int[] { 1, 2, 3 }; double[] d3 = new double[] { 1.0, 2.0, 3.0 }; int[] iunequal = new int[] { 1, 3, 2 }; // Classic Syntax Assert.AreEqual(4, 2 + 2); Assert.AreEqual(i3, d3); Assert.AreNotEqual(5, 2 + 2); Assert.AreNotEqual(i3, iunequal); // Helper syntax Assert.That(2 + 2, Is.EqualTo(4)); Assert.That(2 + 2 == 4); Assert.That(i3, Is.EqualTo(d3)); Assert.That(2 + 2, Is.Not.EqualTo(5)); Assert.That(i3, Is.Not.EqualTo(iunequal)); // Inherited syntax Expect(2 + 2, EqualTo(4)); Expect(2 + 2 == 4); Expect(i3, EqualTo(d3)); Expect(2 + 2, Not.EqualTo(5)); Expect(i3, Not.EqualTo(iunequal)); } [Test] public void EqualityTestsWithTolerance() { // CLassic syntax Assert.AreEqual(5.0d, 4.99d, 0.05d); Assert.AreEqual(5.0f, 4.99f, 0.05f); // Helper syntax Assert.That(4.99d, Is.EqualTo(5.0d).Within(0.05d)); Assert.That(4.99f, Is.EqualTo(5.0f).Within(0.05f)); // Inherited syntax Expect(4.99d, EqualTo(5.0d).Within(0.05d)); Expect(4.99f, EqualTo(5.0f).Within(0.05f)); } [Test] public void ComparisonTests() { // Classic Syntax Assert.Greater(7, 3); Assert.GreaterOrEqual(7, 3); Assert.GreaterOrEqual(7, 7); // Helper syntax Assert.That(7, Is.GreaterThan(3)); Assert.That(7, Is.GreaterThanOrEqualTo(3)); Assert.That(7, Is.AtLeast(3)); Assert.That(7, Is.GreaterThanOrEqualTo(7)); Assert.That(7, Is.AtLeast(7)); // Inherited syntax Expect(7, GreaterThan(3)); Expect(7, GreaterThanOrEqualTo(3)); Expect(7, AtLeast(3)); Expect(7, GreaterThanOrEqualTo(7)); Expect(7, AtLeast(7)); // Classic syntax Assert.Less(3, 7); Assert.LessOrEqual(3, 7); Assert.LessOrEqual(3, 3); // Helper syntax Assert.That(3, Is.LessThan(7)); Assert.That(3, Is.LessThanOrEqualTo(7)); Assert.That(3, Is.AtMost(7)); Assert.That(3, Is.LessThanOrEqualTo(3)); Assert.That(3, Is.AtMost(3)); // Inherited syntax Expect(3, LessThan(7)); Expect(3, LessThanOrEqualTo(7)); Expect(3, AtMost(7)); Expect(3, LessThanOrEqualTo(3)); Expect(3, AtMost(3)); } [Test] public void AllItemsTests() { object[] ints = new object[] { 1, 2, 3, 4 }; object[] strings = new object[] { "abc", "bad", "cab", "bad", "dad" }; // Classic syntax CollectionAssert.AllItemsAreNotNull(ints); CollectionAssert.AllItemsAreInstancesOfType(ints, typeof(int)); CollectionAssert.AllItemsAreInstancesOfType(strings, typeof(string)); CollectionAssert.AllItemsAreUnique(ints); // Helper syntax Assert.That(ints, Is.All.Not.Null); Assert.That(ints, Is.All.InstanceOfType(typeof(int))); Assert.That(strings, Is.All.InstanceOfType(typeof(string))); Assert.That(ints, Is.Unique); // Only available using new syntax Assert.That(strings, Is.Not.Unique); Assert.That(ints, Is.All.GreaterThan(0)); Assert.That(strings, Text.All.Contains( "a" ) ); Assert.That(strings, List.Some.StartsWith( "ba" ) ); // Inherited syntax Expect(ints, All.Not.Null); Expect(ints, All.InstanceOfType(typeof(int))); Expect(strings, All.InstanceOfType(typeof(string))); Expect(ints, Unique); // Only available using new syntax Expect(strings, Not.Unique); Expect(ints, All.GreaterThan(0)); Expect(strings, All.Contains( "a" ) ); Expect(strings, Some.StartsWith( "ba" ) ); } [Test] public void SomeItemsTests() { object[] mixed = new object[] { 1, 2, "3", null, "four", 100 }; object[] strings = new object[] { "abc", "bad", "cab", "bad", "dad" }; // Not available using the classic syntax // Helper syntax Assert.That(mixed, Has.Some.Null); Assert.That(mixed, Has.Some.InstanceOfType(typeof(int))); Assert.That(mixed, Has.Some.InstanceOfType(typeof(string))); Assert.That(mixed, Has.Some.GreaterThan(99)); Assert.That(strings, Has.Some.StartsWith( "ba" ) ); Assert.That(strings, Has.Some.Not.StartsWith( "ba" ) ); // Inherited syntax Expect(mixed, Some.Null); Expect(mixed, Some.InstanceOfType(typeof(int))); Expect(mixed, Some.InstanceOfType(typeof(string))); Expect(mixed, Some.GreaterThan(99)); Expect(strings, Some.StartsWith( "ba" ) ); Expect(strings, Some.Not.StartsWith( "ba" ) ); } [Test] public void NoItemsTests() { object[] ints = new object[] { 1, 2, 3, 4, 5 }; object[] strings = new object[] { "abc", "bad", "cab", "bad", "dad" }; // Not available using the classic syntax // Helper syntax Assert.That(ints, Has.None.Null); Assert.That(ints, Has.None.InstanceOfType(typeof(string))); Assert.That(ints, Has.None.GreaterThan(99)); Assert.That(strings, Has.None.StartsWith( "qu" ) ); // Inherited syntax Expect(ints, None.Null); Expect(ints, None.InstanceOfType(typeof(string))); Expect(ints, None.GreaterThan(99)); Expect(strings, None.StartsWith( "qu" ) ); } [Test] public void CollectionContainsTests() { int[] iarray = new int[] { 1, 2, 3 }; string[] sarray = new string[] { "a", "b", "c" }; // Classic syntax Assert.Contains(3, iarray); Assert.Contains("b", sarray); CollectionAssert.Contains(iarray, 3); CollectionAssert.Contains(sarray, "b"); CollectionAssert.DoesNotContain(sarray, "x"); // Helper syntax Assert.That(iarray, List.Contains(3)); Assert.That(sarray, List.Contains("b")); Assert.That(sarray, List.Not.Contains("x")); // Inherited syntax Expect(iarray, Contains(3)); Expect(sarray, Contains("b")); Expect(sarray, Not.Contains("x")); } [Test] public void CollectionEquivalenceTests() { int[] ints1to5 = new int[] { 1, 2, 3, 4, 5 }; // Classic syntax CollectionAssert.AreEquivalent(new int[] { 2, 1, 4, 3, 5 }, ints1to5); CollectionAssert.AreNotEquivalent(new int[] { 2, 2, 4, 3, 5 }, ints1to5); CollectionAssert.AreNotEquivalent(new int[] { 2, 4, 3, 5 }, ints1to5); CollectionAssert.AreEquivalent(new int[] { 2, 2, 1, 1, 4, 3, 5 }, ints1to5); // Helper syntax Assert.That(new int[] { 2, 1, 4, 3, 5 }, Is.EquivalentTo(ints1to5)); Assert.That(new int[] { 2, 2, 4, 3, 5 }, Is.Not.EquivalentTo(ints1to5)); Assert.That(new int[] { 2, 4, 3, 5 }, Is.Not.EquivalentTo(ints1to5)); Assert.That(new int[] { 2, 2, 1, 1, 4, 3, 5 }, Is.EquivalentTo(ints1to5)); // Inherited syntax Expect(new int[] { 2, 1, 4, 3, 5 }, EquivalentTo(ints1to5)); Expect(new int[] { 2, 2, 4, 3, 5 }, Not.EquivalentTo(ints1to5)); Expect(new int[] { 2, 4, 3, 5 }, Not.EquivalentTo(ints1to5)); Expect(new int[] { 2, 2, 1, 1, 4, 3, 5 }, EquivalentTo(ints1to5)); } [Test] public void SubsetTests() { int[] ints1to5 = new int[] { 1, 2, 3, 4, 5 }; // Classic syntax CollectionAssert.IsSubsetOf(new int[] { 1, 3, 5 }, ints1to5); CollectionAssert.IsSubsetOf(new int[] { 1, 2, 3, 4, 5 }, ints1to5); CollectionAssert.IsNotSubsetOf(new int[] { 2, 4, 6 }, ints1to5); // Helper syntax Assert.That(new int[] { 1, 3, 5 }, Is.SubsetOf(ints1to5)); Assert.That(new int[] { 1, 2, 3, 4, 5 }, Is.SubsetOf(ints1to5)); Assert.That(new int[] { 2, 4, 6 }, Is.Not.SubsetOf(ints1to5)); // Inherited syntax Expect(new int[] { 1, 3, 5 }, SubsetOf(ints1to5)); Expect(new int[] { 1, 2, 3, 4, 5 }, SubsetOf(ints1to5)); Expect(new int[] { 2, 4, 6 }, Not.SubsetOf(ints1to5)); } [Test] public void PropertyTests() { string[] array = new string[] { "abc", "bca", "xyz" }; // Helper syntax Assert.That( "Hello", Has.Property("Length", 5) ); Assert.That( "Hello", Has.Length( 5 ) ); Assert.That( array , Has.All.Property( "Length", 3 ) ); Assert.That( array, Has.All.Length( 3 ) ); // Inherited syntax Expect( "Hello", Property("Length", 5) ); Expect( "Hello", Length( 5 ) ); Expect( array, All.Property("Length", 3 ) ); Expect( array, All.Length( 3 ) ); } [Test] public void NotTests() { // Not available using the classic syntax // Helper syntax Assert.That(42, Is.Not.Null); Assert.That(42, Is.Not.True); Assert.That(42, Is.Not.False); Assert.That(2.5, Is.Not.NaN); Assert.That(2 + 2, Is.Not.EqualTo(3)); Assert.That(2 + 2, Is.Not.Not.EqualTo(4)); Assert.That(2 + 2, Is.Not.Not.Not.EqualTo(5)); // Inherited syntax Expect(42, Not.Null); Expect(42, Not.True); Expect(42, Not.False); Expect(2.5, Not.NaN); Expect(2 + 2, Not.EqualTo(3)); Expect(2 + 2, Not.Not.EqualTo(4)); Expect(2 + 2, Not.Not.Not.EqualTo(5)); } [Test] public void NotOperator() { // The ! operator is only available in the new syntax Assert.That(42, !Is.Null); // Inherited syntax Expect( 42, !Null ); } [Test] public void AndOperator() { // The & operator is only available in the new syntax Assert.That(7, Is.GreaterThan(5) & Is.LessThan(10)); // Inherited syntax Expect( 7, GreaterThan(5) & LessThan(10)); } [Test] public void OrOperator() { // The | operator is only available in the new syntax Assert.That(3, Is.LessThan(5) | Is.GreaterThan(10)); Expect( 3, LessThan(5) | GreaterThan(10)); } [Test] public void ComplexTests() { Assert.That(7, Is.Not.Null & Is.Not.LessThan(5) & Is.Not.GreaterThan(10)); Expect(7, Not.Null & Not.LessThan(5) & Not.GreaterThan(10)); Assert.That(7, !Is.Null & !Is.LessThan(5) & !Is.GreaterThan(10)); Expect(7, !Null & !LessThan(5) & !GreaterThan(10)); // TODO: Remove #if when mono compiler can handle null #if MONO Constraint x = null; Assert.That(7, !x & !Is.LessThan(5) & !Is.GreaterThan(10)); Expect(7, !x & !LessThan(5) & !GreaterThan(10)); #else Assert.That(7, !(Constraint)null & !Is.LessThan(5) & !Is.GreaterThan(10)); Expect(7, !(Constraint)null & !LessThan(5) & !GreaterThan(10)); #endif } // This method contains assertions that should not compile // You can check by uncommenting it. //public void WillNotCompile() //{ // Assert.That(42, Is.Not); // Assert.That(42, Is.All); // Assert.That(42, Is.Null.Not); // Assert.That(42, Is.Not.Null.GreaterThan(10)); // Assert.That(42, Is.GreaterThan(10).LessThan(99)); // object[] c = new object[0]; // Assert.That(c, Is.Null.All); // Assert.That(c, Is.Not.All); // Assert.That(c, Is.All.Not); //} } }
#region Copyright (c) 2005 Ian Davis and James Carlyle /*------------------------------------------------------------------------------ COPYRIGHT AND PERMISSION NOTICE Copyright (c) 2005 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.Sparql { using SemPlan.Spiral.Core; using System; using System.Collections; using System.Text.RegularExpressions; using System.Globalization; /// <summary> /// Represents a tokenizer for Sparql graph patterns /// </summary> /// <remarks> /// $Id: QueryTokenizer.cs,v 1.7 2006/02/10 13:26:28 ian Exp $ ///</remarks> public class QueryTokenizer { private string itsInput; private TokenType itsTokenType; private int itsPosition; private int itsLinePosition; private string itsTokenText; private int itsTokenAbsolutePosition; private int itsTokenLinePosition; private int itsTokenLine; private static CaseInsensitiveComparer theComparer; private static Hashtable theKeywords; public enum TokenType { BOF, EOF, ERROR, Comment, Variable, QuotedIRIRef, BlankNode, RDFLiteral, LiteralLanguage, LiteralDatatype, NumericInteger, NumericDecimal, NumericDouble, Boolean, QName, Wildcard, BeginGroup, EndGroup, StatementTerminator, ValueDelimiter, PredicateDelimiter, PrefixName, KeywordSelect, KeywordPrefix, KeywordWhere, KeywordA, KeywordFilter, KeywordStr, KeywordLang, KeywordDataType, KeywordLangMatches, KeywordBound, KeywordIsIri, KeywordIsUri, KeywordIsBlank, KeywordIsLiteral, KeywordRegex, KeywordUnion, KeywordLimit, KeywordOffset, KeywordOrder, KeywordBy, KeywordAsc, KeywordDesc, KeywordFrom, KeywordNamed, KeywordBase, KeywordDistinct, KeywordConstruct, KeywordDescribe, KeywordAsk, KeywordOptional, KeywordGraph, BeginGeneratedBlankNode, EndGeneratedBlankNode, Unknown, } static QueryTokenizer() { CultureInfo usCulture = new CultureInfo("en-US"); theComparer = new CaseInsensitiveComparer( usCulture ); CaseInsensitiveHashCodeProvider hashCodeProvider = new CaseInsensitiveHashCodeProvider( usCulture ); theKeywords = new Hashtable( hashCodeProvider, theComparer ); theKeywords["SELECT"] = TokenType.KeywordSelect; theKeywords["TRUE"] = TokenType.Boolean; theKeywords["FALSE"] = TokenType.Boolean; theKeywords["PREFIX"] = TokenType.KeywordPrefix; theKeywords["WHERE"] = TokenType.KeywordWhere; theKeywords["FILTER"] = TokenType.KeywordFilter; theKeywords["STR"] = TokenType.KeywordStr; theKeywords["LANG"] = TokenType.KeywordLang; theKeywords["DATATYPE"] = TokenType.KeywordDataType; theKeywords["LANGMATCHES"] = TokenType.KeywordLangMatches; theKeywords["BOUND"] = TokenType.KeywordBound; theKeywords["ISIRI"] = TokenType.KeywordIsIri; theKeywords["ISURI"] = TokenType.KeywordIsUri; theKeywords["ISBLANK"] = TokenType.KeywordIsBlank; theKeywords["ISLITERAL"] = TokenType.KeywordIsLiteral; theKeywords["REGEX"] = TokenType.KeywordRegex; theKeywords["UNION"] = TokenType.KeywordUnion; theKeywords["LIMIT"] = TokenType.KeywordLimit; theKeywords["OFFSET"] = TokenType.KeywordOffset; theKeywords["ORDER"] = TokenType.KeywordOrder; theKeywords["BY"] = TokenType.KeywordBy; theKeywords["ASC"] = TokenType.KeywordAsc; theKeywords["DESC"] = TokenType.KeywordDesc; theKeywords["FROM"] = TokenType.KeywordFrom; theKeywords["NAMED"] = TokenType.KeywordNamed; theKeywords["BASE"] = TokenType.KeywordBase; theKeywords["DISTINCT"] = TokenType.KeywordDistinct; theKeywords["CONSTRUCT"] = TokenType.KeywordConstruct; theKeywords["DESCRIBE"] = TokenType.KeywordDescribe; theKeywords["ASK"] = TokenType.KeywordAsk; theKeywords["OPTIONAL"] = TokenType.KeywordOptional; theKeywords["GRAPH"] = TokenType.KeywordGraph; theKeywords["A"] = TokenType.KeywordA; } public QueryTokenizer(String input) { itsInput = input; itsTokenType = TokenType.BOF; itsPosition = 0; itsLinePosition = 0; itsTokenLine = 1; itsTokenLinePosition = 0; itsTokenAbsolutePosition = 0; } ///<summary>Move to the next token</summary> ///<returns>True if there is another token, false if there are no more tokens</returns> public bool MoveNext() { SkipWhitespace(); itsTokenAbsolutePosition = itsPosition; itsTokenLinePosition = itsLinePosition; int i = PeekChar(); if (i == -1) { itsTokenType = TokenType.EOF; return false; } char ch = (char)i; if (ch == '?' || ch == '$') { itsTokenType = TokenType.Variable; ReadChar(); itsTokenText = CollectVariableName(); return true; } else if (ch == '<') { itsTokenType = TokenType.QuotedIRIRef; string s = ""; ReadChar(); while ((i = ReadChar()) != -1) { ch = (char)i; if ( ch == '>' ) { break; } s += ch; }; itsTokenText = s; return true; } else if (ch == '@') { itsTokenType = TokenType.LiteralLanguage; ReadChar(); string s = CollectUntilWhitespace(); itsTokenText = s; return true; } else if (ch == '#') { itsTokenType = TokenType.Comment; ReadChar(); SkipWhitespace(); string s = CollectUntilEndOfLine(); itsTokenText = s; return true; } else if (ch == '^') { itsTokenType = TokenType.LiteralDatatype; ReadChar(); i = PeekChar(); if ( i != -1) { if ( (char)i == '^') { ReadChar(); i = PeekChar(); if ( i != -1) { if ( (char)i == '<') { string s = ""; ReadChar(); while ((i = ReadChar()) != -1) { ch = (char)i; if ( ch == '>' ) { break; } s += ch; }; itsTokenText = s; return true; } } } } itsTokenType = TokenType.ERROR; return false; } else if (ch == '*') { return AssignTokenFromCurrentCharacter(TokenType.Wildcard); } else if (ch == '{' || ch == '(') { return AssignTokenFromCurrentCharacter(TokenType.BeginGroup); } else if (ch == '}' || ch == ')') { return AssignTokenFromCurrentCharacter(TokenType.EndGroup); } else if (ch == '[') { return AssignTokenFromCurrentCharacter(TokenType.BeginGeneratedBlankNode); } else if (ch == ']') { return AssignTokenFromCurrentCharacter(TokenType.EndGeneratedBlankNode); } else if (ch == ';') { return AssignTokenFromCurrentCharacter(TokenType.ValueDelimiter); } else if (ch == ',') { return AssignTokenFromCurrentCharacter(TokenType.PredicateDelimiter); } else if (Char.IsDigit(ch) || ch == '.' || ch == '+' || ch == '-') { bool noExponent = true; string s = ""; if ( ch == '.') { itsTokenType = TokenType.StatementTerminator; } else { itsTokenType = TokenType.NumericInteger; } s += ch; ReadChar(); while ((i = ReadChar()) != -1) { ch = (char)i; if (Char.IsDigit(ch)) { if ( itsTokenType == TokenType.StatementTerminator) { itsTokenType = TokenType.NumericDecimal; } s += ch; } else if ( ch == '.') { if ( itsTokenType == TokenType.NumericInteger) { itsTokenType = TokenType.NumericDecimal; } s += ch; } else if ( noExponent && ch == 'e') { noExponent = false; itsTokenType = TokenType.NumericDouble; s += ch; i = PeekChar(); if ( i != -1) { if ( (char)i == '+' || (char)i == '-') { s += (char)i; ReadChar(); } } } else { break; } }; itsTokenText = s; return true; } else if (ch == '\'' || ch == '\"') { Char quoteType = ch; bool longString = false; itsTokenType = TokenType.RDFLiteral; string s = ""; ReadChar(); i = PeekChar(); if ( i != -1) { if ( (char)i == quoteType) { ReadChar(); i = PeekChar(); if ( i != -1) { if ( (char)i == quoteType) { ReadChar(); longString = true; } else { itsTokenType = TokenType.ERROR; return false; } } } } while ((i = ReadChar()) != -1) { ch = (char)i; if (ch == '\\') { i = ReadChar(); if ( i == -1) { break; } s += (char)i; } else if ( !longString &&( ch == '\n' || ch == '\r') ) { itsTokenType = TokenType.ERROR; return false; } else { if ( ch == quoteType ) { if (longString) { i = PeekChar(); if ( i != -1) { if ( (char)i == quoteType) { ReadChar(); i = PeekChar(); if ( i != -1) { if ( (char)i == quoteType) { ReadChar(); break; } else { s += quoteType; } } else { itsTokenType = TokenType.ERROR; return false; } } } else { itsTokenType = TokenType.ERROR; return false; } } else { break; } } s += ch; } }; itsTokenText = s; return true; } else if (ch == '_') { itsTokenType = TokenType.BlankNode; ReadChar(); i = PeekChar(); if ( i != -1) { if ( (char)i == ':') { ReadChar(); string s = CollectUntilWhitespace(); itsTokenText = s; return true; } } itsTokenType = TokenType.ERROR; return false; } else { string s = CollectUntilWhitespaceOrBrace(); if ( theKeywords.Contains( s ) ) { return AssignTokenFromString(s, (TokenType)theKeywords[s]); } else if ( s.IndexOf(":") > -1 && s.IndexOf(":") != s.Length - 1) { return AssignTokenFromString(s, TokenType.QName); } else if ( s.IndexOf(":") > -1 ) { return AssignTokenFromString(s, TokenType.PrefixName); } else { return AssignTokenFromString(s, TokenType.Unknown); } } } ///<returns>The current token type</returns> public TokenType Type { get { return itsTokenType; } } ///<returns>The current token text</returns> public string TokenText { get { return itsTokenText; } } ///<returns>The current token character position in the entire query</returns> public int TokenAbsolutePosition { get { return itsTokenAbsolutePosition; } } ///<returns>The current token character position in the current line</returns> public int TokenLinePosition { get { return itsTokenLinePosition; } } ///<returns>The line of the query that the current token is on</returns> public int TokenLine { get { return itsTokenLine; } } private int PeekChar() { if (itsPosition < itsInput.Length) { return itsInput[itsPosition]; } else { return -1; } } private int ReadChar() { if (itsPosition < itsInput.Length) { ++itsLinePosition; return itsInput[itsPosition++]; } else { return -1; } } private void SkipWhitespace() { int ch; while ((ch = PeekChar()) != -1) { if (!Char.IsWhiteSpace((char)ch)) { break; } ReadChar(); if ( ch == '\n') { itsLinePosition = 0; ++itsTokenLine; } } } private string CollectUntilWhitespace() { int ch; string s = ""; while ((ch = PeekChar()) != -1) { if (Char.IsWhiteSpace((char)ch)) { break; } s += (char)ReadChar(); } return s; } private string CollectVariableName() { int ch; string s = ""; while ((ch = PeekChar()) != -1) { if ( // TODO: rest of character range (char)ch == '_' || ( (char)ch >= 'A' && (char)ch <= 'Z') || ( (char)ch >= 'a' && (char)ch <= 'z' ) || ( (char)ch >= '0' && (char)ch <= '9' ) ) { s += (char)ReadChar(); } else { break; } } return s; } private string CollectUntilWhitespaceOrBrace() { int ch; string s = ""; while ((ch = PeekChar()) != -1) { if (Char.IsWhiteSpace((char)ch) || (char)ch == '{' || (char)ch == '(' || (char)ch == '}' || (char)ch == ')') { break; } s += (char)ReadChar(); } return s; } private string CollectUntilEndOfLine() { int ch; string s = ""; while ((ch = PeekChar()) != -1) { if ((char)ch == '\n' || (char)ch == '\r') { break; } s += (char)ReadChar(); } return s; } private bool AssignTokenFromCurrentCharacter(TokenType tokenType) { itsTokenType = tokenType; itsTokenText = "" + (char)ReadChar(); return true; } private bool AssignTokenFromString(string data, TokenType tokenType) { itsTokenType = tokenType; itsTokenText = data; return true; } } }