context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * 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 System; using System.Collections.Generic; using System.Net; namespace OpenSim.Framework { /// <summary> /// Maps from client AgentID and RemoteEndPoint values to IClientAPI /// references for all of the connected clients /// </summary> public class ClientManager { /// <summary>An immutable collection of <seealso cref="IClientAPI"/> /// references</summary> private IClientAPI[] m_array; /// <summary>A dictionary mapping from <seealso cref="UUID"/> /// to <seealso cref="IClientAPI"/> references</summary> private Dictionary<UUID, IClientAPI> m_dict1; /// <summary>A dictionary mapping from <seealso cref="IPEndPoint"/> /// to <seealso cref="IClientAPI"/> references</summary> private Dictionary<IPEndPoint, IClientAPI> m_dict2; /// <summary>Synchronization object for writing to the collections</summary> private object m_syncRoot = new object(); /// <summary> /// Default constructor /// </summary> public ClientManager() { m_dict1 = new Dictionary<UUID, IClientAPI>(); m_dict2 = new Dictionary<IPEndPoint, IClientAPI>(); m_array = new IClientAPI[0]; } /// <summary>Number of clients in the collection</summary> public int Count { get { return m_dict1.Count; } } /// <summary> /// Add a client reference to the collection if it does not already /// exist /// </summary> /// <param name="value">Reference to the client object</param> /// <returns>True if the client reference was successfully added, /// otherwise false if the given key already existed in the collection</returns> public bool Add(IClientAPI value) { lock (m_syncRoot) { if (m_dict1.ContainsKey(value.AgentId) || m_dict2.ContainsKey(value.RemoteEndPoint)) return false; m_dict1[value.AgentId] = value; m_dict2[value.RemoteEndPoint] = value; IClientAPI[] oldArray = m_array; int oldLength = oldArray.Length; IClientAPI[] newArray = new IClientAPI[oldLength + 1]; for (int i = 0; i < oldLength; i++) newArray[i] = oldArray[i]; newArray[oldLength] = value; m_array = newArray; } return true; } /// <summary> /// Resets the client collection /// </summary> public void Clear() { lock (m_syncRoot) { m_dict1.Clear(); m_dict2.Clear(); m_array = new IClientAPI[0]; } } /// <summary> /// Checks if a UUID is in the collection /// </summary> /// <param name="key">UUID to check for</param> /// <returns>True if the UUID was found in the collection, otherwise false</returns> public bool ContainsKey(UUID key) { return m_dict1.ContainsKey(key); } /// <summary> /// Checks if an endpoint is in the collection /// </summary> /// <param name="key">Endpoint to check for</param> /// <returns>True if the endpoint was found in the collection, otherwise false</returns> public bool ContainsKey(IPEndPoint key) { return m_dict2.ContainsKey(key); } /// <summary> /// Performs a given task in parallel for each of the elements in the /// collection /// </summary> /// <param name="action">Action to perform on each element</param> public void ForEach(Action<IClientAPI> action) { IClientAPI[] localArray = m_array; Parallel.For(0, localArray.Length, delegate(int i) { action(localArray[i]); } ); } /// <summary> /// Performs a given task synchronously for each of the elements in /// the collection /// </summary> /// <param name="action">Action to perform on each element</param> public void ForEachSync(Action<IClientAPI> action) { IClientAPI[] localArray = m_array; for (int i = 0; i < localArray.Length; i++) action(localArray[i]); } /// <summary> /// Remove a client from the collection /// </summary> /// <param name="key">UUID of the client to remove</param> /// <returns>True if a client was removed, or false if the given UUID /// was not present in the collection</returns> public bool Remove(UUID key) { lock (m_syncRoot) { IClientAPI value; if (m_dict1.TryGetValue(key, out value)) { m_dict1.Remove(key); m_dict2.Remove(value.RemoteEndPoint); IClientAPI[] oldArray = m_array; int oldLength = oldArray.Length; IClientAPI[] newArray = new IClientAPI[oldLength - 1]; int j = 0; for (int i = 0; i < oldLength; i++) { if (oldArray[i] != value) newArray[j++] = oldArray[i]; } m_array = newArray; return true; } } return false; } /// <summary> /// Attempts to fetch a value out of the collection /// </summary> /// <param name="key">UUID of the client to retrieve</param> /// <param name="value">Retrieved client, or null on lookup failure</param> /// <returns>True if the lookup succeeded, otherwise false</returns> public bool TryGetValue(UUID key, out IClientAPI value) { try { return m_dict1.TryGetValue(key, out value); } catch (Exception) { value = null; return false; } } /// <summary> /// Attempts to fetch a value out of the collection /// </summary> /// <param name="key">Endpoint of the client to retrieve</param> /// <param name="value">Retrieved client, or null on lookup failure</param> /// <returns>True if the lookup succeeded, otherwise false</returns> public bool TryGetValue(IPEndPoint key, out IClientAPI value) { try { return m_dict2.TryGetValue(key, out value); } catch (Exception) { value = null; return false; } } } }
// 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.IO; using System.Net.Sockets; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.WebSockets; namespace Microsoft.VisualStudioTools { public abstract class WebSocketProxyBase : IHttpHandler { private static long _lastId; private static Task _currentSession; // represents the current active debugging session, and completes when it is over private static volatile StringWriter _log; private readonly long _id; public WebSocketProxyBase() { _id = Interlocked.Increment(ref _lastId); } public abstract int DebuggerPort { get; } public abstract bool AllowConcurrentConnections { get; } public abstract void ProcessHelpPageRequest(HttpContext context); public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { if (context.IsWebSocketRequest) { context.AcceptWebSocketRequest(WebSocketRequestHandler); } else { context.Response.ContentType = "text/html"; context.Response.ContentEncoding = Encoding.UTF8; switch (context.Request.QueryString["debug"]) { case "startlog": _log = new StringWriter(); context.Response.Write("Logging is now enabled. <a href='?debug=viewlog'>View</a>. <a href='?debug=stoplog'>Disable</a>."); return; case "stoplog": _log = null; context.Response.Write("Logging is now disabled. <a href='?debug=startlog'>Enable</a>."); return; case "clearlog": { var log = _log; if (log != null) { log.GetStringBuilder().Clear(); } context.Response.Write("Log is cleared. <a href='?debug=viewlog'>View</a>."); return; } case "viewlog": { var log = _log; if (log == null) { context.Response.Write("Logging is disabled. <a href='?debug=startlog'>Enable</a>."); } else { context.Response.Write("Logging is enabled. <a href='?debug=clearlog'>Clear</a>. <a href='?debug=stoplog'>Disable</a>. <p><pre>"); context.Response.Write(HttpUtility.HtmlDecode(log.ToString())); context.Response.Write("</pre>"); } context.Response.End(); return; } } ProcessHelpPageRequest(context); } } private async Task WebSocketRequestHandler(AspNetWebSocketContext context) { Log("Accepted web socket request from {0}.", context.UserHostAddress); TaskCompletionSource<bool> tcs = null; if (!AllowConcurrentConnections) { tcs = new TaskCompletionSource<bool>(); while (true) { var currentSession = Interlocked.CompareExchange(ref _currentSession, tcs.Task, null); if (currentSession == null) { break; } Log("Another session is active, waiting for completion."); await currentSession; Log("The other session completed, proceeding."); } } try { var webSocket = context.WebSocket; using (var tcpClient = new TcpClient("localhost", DebuggerPort)) { try { var stream = tcpClient.GetStream(); var cts = new CancellationTokenSource(); // Start the workers that copy data from one socket to the other in both directions, and wait until either // completes. The workers are fully async, and so their loops are transparently interleaved when running. // Usually end of session is caused by VS dropping its connection on detach, and so it will be // CopyFromWebSocketToStream that returns first; but it can be the other one if debuggee process crashes. Log("Starting copy workers."); var copyFromStreamToWebSocketTask = CopyFromStreamToWebSocketWorker(stream, webSocket, cts.Token); var copyFromWebSocketToStreamTask = CopyFromWebSocketToStreamWorker(webSocket, stream, cts.Token); Task completedTask = null; try { completedTask = await Task.WhenAny(copyFromStreamToWebSocketTask, copyFromWebSocketToStreamTask); } catch (IOException ex) { Log(ex); } catch (WebSocketException ex) { Log(ex); } // Now that one worker is done, try to gracefully terminate the other one by issuing a cancellation request. // it is normally blocked on a read, and this will cancel it if possible, and throw OperationCanceledException. Log("One of the workers completed, shutting down the remaining one."); cts.Cancel(); try { await Task.WhenAny(Task.WhenAll(copyFromStreamToWebSocketTask, copyFromWebSocketToStreamTask), Task.Delay(1000)); } catch (OperationCanceledException ex) { Log(ex); } // Try to gracefully close the websocket if it's still open - this is not necessary, but nice to have. Log("Both workers shut down, trying to close websocket."); try { await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None); } catch (WebSocketException ex) { Log(ex); } } finally { // Gracefully close the TCP socket. This is crucial to avoid "Remote debugger already attached" problems. Log("Shutting down TCP socket."); try { tcpClient.Client.Shutdown(SocketShutdown.Both); tcpClient.Client.Disconnect(false); } catch (SocketException ex) { Log(ex); } Log("All done!"); } } } finally { if (tcs != null) { Volatile.Write(ref _currentSession, null); tcs.SetResult(true); } } } private async Task CopyFromStreamToWebSocketWorker(Stream stream, WebSocket webSocket, CancellationToken ct) { var buffer = new byte[0x10000]; while (webSocket.State == WebSocketState.Open) { ct.ThrowIfCancellationRequested(); Log("TCP -> WS: waiting for packet."); int count = await stream.ReadAsync(buffer, 0, buffer.Length, ct); Log("TCP -> WS: received packet:\n{0}", Encoding.UTF8.GetString(buffer, 0, count)); if (count == 0) { Log("TCP -> WS: zero-length TCP packet received, connection closed."); break; } await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, count), WebSocketMessageType.Binary, true, ct); Log("TCP -> WS: packet relayed."); } } private async Task CopyFromWebSocketToStreamWorker(WebSocket webSocket, Stream stream, CancellationToken ct) { var buffer = new ArraySegment<byte>(new byte[0x10000]); while (webSocket.State == WebSocketState.Open) { ct.ThrowIfCancellationRequested(); Log("WS -> TCP: waiting for packet."); var recv = await webSocket.ReceiveAsync(buffer, ct); Log("WS -> TCP: received packet:\n{0}", Encoding.UTF8.GetString(buffer.Array, 0, recv.Count)); await stream.WriteAsync(buffer.Array, 0, recv.Count, ct); Log("WS -> TCP: packet relayed."); } } private void Log(object o) { var log = _log; if (log != null) { log.WriteLine(_id + " :: " + o); } } private void Log(string format, object arg1) { var log = _log; if (log != null) { log.WriteLine(_id + " :: " + format, arg1); } } } }
// 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.Text; namespace System.Net.Http.Headers { // According to the RFC, in places where a "parameter" is required, the value is mandatory // (e.g. Media-Type, Accept). However, we don't introduce a dedicated type for it. So NameValueHeaderValue supports // name-only values in addition to name/value pairs. public class NameValueHeaderValue : ICloneable { private static readonly Func<NameValueHeaderValue> s_defaultNameValueCreator = CreateNameValue; private string _name; private string _value; public string Name { get { return _name; } } public string Value { get { return _value; } set { CheckValueFormat(value); _value = value; } } internal NameValueHeaderValue() { } public NameValueHeaderValue(string name) : this(name, null) { } public NameValueHeaderValue(string name, string value) { CheckNameValueFormat(name, value); _name = name; _value = value; } protected NameValueHeaderValue(NameValueHeaderValue source) { Debug.Assert(source != null); _name = source._name; _value = source._value; } public override int GetHashCode() { Debug.Assert(_name != null); int nameHashCode = StringComparer.OrdinalIgnoreCase.GetHashCode(_name); if (!string.IsNullOrEmpty(_value)) { // If we have a quoted-string, then just use the hash code. If we have a token, convert to lowercase // and retrieve the hash code. if (_value[0] == '"') { return nameHashCode ^ _value.GetHashCode(); } return nameHashCode ^ StringComparer.OrdinalIgnoreCase.GetHashCode(_value); } return nameHashCode; } public override bool Equals(object obj) { NameValueHeaderValue other = obj as NameValueHeaderValue; if (other == null) { return false; } if (!string.Equals(_name, other._name, StringComparison.OrdinalIgnoreCase)) { return false; } // RFC2616: 14.20: unquoted tokens should use case-INsensitive comparison; quoted-strings should use // case-sensitive comparison. The RFC doesn't mention how to compare quoted-strings outside the "Expect" // header. We treat all quoted-strings the same: case-sensitive comparison. if (string.IsNullOrEmpty(_value)) { return string.IsNullOrEmpty(other._value); } if (_value[0] == '"') { // We have a quoted string, so we need to do case-sensitive comparison. return string.Equals(_value, other._value, StringComparison.Ordinal); } else { return string.Equals(_value, other._value, StringComparison.OrdinalIgnoreCase); } } public static NameValueHeaderValue Parse(string input) { int index = 0; return (NameValueHeaderValue)GenericHeaderParser.SingleValueNameValueParser.ParseValue( input, null, ref index); } public static bool TryParse(string input, out NameValueHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.SingleValueNameValueParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (NameValueHeaderValue)output; return true; } return false; } public override string ToString() { if (!string.IsNullOrEmpty(_value)) { return _name + "=" + _value; } return _name; } internal static void ToString(ObjectCollection<NameValueHeaderValue> values, char separator, bool leadingSeparator, StringBuilder destination) { Debug.Assert(destination != null); if ((values == null) || (values.Count == 0)) { return; } foreach (var value in values) { if (leadingSeparator || (destination.Length > 0)) { destination.Append(separator); destination.Append(' '); } destination.Append(value.ToString()); } } internal static string ToString(ObjectCollection<NameValueHeaderValue> values, char separator, bool leadingSeparator) { if ((values == null) || (values.Count == 0)) { return null; } StringBuilder sb = new StringBuilder(); ToString(values, separator, leadingSeparator, sb); return sb.ToString(); } internal static int GetHashCode(ObjectCollection<NameValueHeaderValue> values) { if ((values == null) || (values.Count == 0)) { return 0; } int result = 0; foreach (var value in values) { result = result ^ value.GetHashCode(); } return result; } internal static int GetNameValueLength(string input, int startIndex, out NameValueHeaderValue parsedValue) { return GetNameValueLength(input, startIndex, s_defaultNameValueCreator, out parsedValue); } internal static int GetNameValueLength(string input, int startIndex, Func<NameValueHeaderValue> nameValueCreator, out NameValueHeaderValue parsedValue) { Debug.Assert(input != null); Debug.Assert(startIndex >= 0); Debug.Assert(nameValueCreator != null); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Parse the name, i.e. <name> in name/value string "<name>=<value>". Caller must remove // leading whitespace. int nameLength = HttpRuleParser.GetTokenLength(input, startIndex); if (nameLength == 0) { return 0; } string name = input.Substring(startIndex, nameLength); int current = startIndex + nameLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Parse the separator between name and value if ((current == input.Length) || (input[current] != '=')) { // We only have a name and that's OK. Return. parsedValue = nameValueCreator(); parsedValue._name = name; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // skip whitespace return current - startIndex; } current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Parse the value, i.e. <value> in name/value string "<name>=<value>" int valueLength = GetValueLength(input, current); if (valueLength == 0) { return 0; // We have an invalid value. } // Use parameterless ctor to avoid double-parsing of name and value, i.e. skip public ctor validation. parsedValue = nameValueCreator(); parsedValue._name = name; parsedValue._value = input.Substring(current, valueLength); current = current + valueLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // skip whitespace return current - startIndex; } // Returns the length of a name/value list, separated by 'delimiter'. E.g. "a=b, c=d, e=f" adds 3 // name/value pairs to 'nameValueCollection' if 'delimiter' equals ','. internal static int GetNameValueListLength(string input, int startIndex, char delimiter, ObjectCollection<NameValueHeaderValue> nameValueCollection) { Debug.Assert(nameValueCollection != null); Debug.Assert(startIndex >= 0); if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length)) { return 0; } int current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex); while (true) { NameValueHeaderValue parameter = null; int nameValueLength = NameValueHeaderValue.GetNameValueLength(input, current, s_defaultNameValueCreator, out parameter); if (nameValueLength == 0) { return 0; } nameValueCollection.Add(parameter); current = current + nameValueLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); if ((current == input.Length) || (input[current] != delimiter)) { // We're done and we have at least one valid name/value pair. return current - startIndex; } // input[current] is 'delimiter'. Skip the delimiter and whitespace and try to parse again. current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); } } internal static NameValueHeaderValue Find(ObjectCollection<NameValueHeaderValue> values, string name) { Debug.Assert((name != null) && (name.Length > 0)); if ((values == null) || (values.Count == 0)) { return null; } foreach (var value in values) { if (string.Equals(value.Name, name, StringComparison.OrdinalIgnoreCase)) { return value; } } return null; } internal static int GetValueLength(string input, int startIndex) { Debug.Assert(input != null); if (startIndex >= input.Length) { return 0; } int valueLength = HttpRuleParser.GetTokenLength(input, startIndex); if (valueLength == 0) { // A value can either be a token or a quoted string. Check if it is a quoted string. if (HttpRuleParser.GetQuotedStringLength(input, startIndex, out valueLength) != HttpParseResult.Parsed) { // We have an invalid value. Reset the name and return. return 0; } } return valueLength; } private static void CheckNameValueFormat(string name, string value) { HeaderUtilities.CheckValidToken(name, "name"); CheckValueFormat(value); } private static void CheckValueFormat(string value) { // Either value is null/empty or a valid token/quoted string if (!(string.IsNullOrEmpty(value) || (GetValueLength(value, 0) == value.Length))) { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } } private static NameValueHeaderValue CreateNameValue() { return new NameValueHeaderValue(); } // Implement ICloneable explicitly to allow derived types to "override" the implementation. object ICloneable.Clone() { return new NameValueHeaderValue(this); } } }
#region Apache License // // 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. // #endregion using System; using System.Collections; using System.IO; using log4net.Util; using log4net.Util.PatternStringConverters; using log4net.Core; namespace log4net.Util { /// <summary> /// This class implements a patterned string. /// </summary> /// <remarks> /// <para> /// This string has embedded patterns that are resolved and expanded /// when the string is formatted. /// </para> /// <para> /// This class functions similarly to the <see cref="log4net.Layout.PatternLayout"/> /// in that it accepts a pattern and renders it to a string. Unlike the /// <see cref="log4net.Layout.PatternLayout"/> however the <c>PatternString</c> /// does not render the properties of a specific <see cref="LoggingEvent"/> but /// of the process in general. /// </para> /// <para> /// The recognized conversion pattern names are: /// </para> /// <list type="table"> /// <listheader> /// <term>Conversion Pattern Name</term> /// <description>Effect</description> /// </listheader> /// <item> /// <term>appdomain</term> /// <description> /// <para> /// Used to output the friendly name of the current AppDomain. /// </para> /// </description> /// </item> /// <item> /// <term>date</term> /// <description> /// <para> /// Used to output the current date and time in the local time zone. /// To output the date in universal time use the <c>%utcdate</c> pattern. /// The date conversion /// specifier may be followed by a <i>date format specifier</i> enclosed /// between braces. For example, <b>%date{HH:mm:ss,fff}</b> or /// <b>%date{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is /// given then ISO8601 format is /// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>). /// </para> /// <para> /// The date format specifier admits the same syntax as the /// time pattern string of the <see cref="M:DateTime.ToString(string)"/>. /// </para> /// <para> /// For better results it is recommended to use the log4net date /// formatters. These can be specified using one of the strings /// "ABSOLUTE", "DATE" and "ISO8601" for specifying /// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>, /// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively /// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example, /// <b>%date{ISO8601}</b> or <b>%date{ABSOLUTE}</b>. /// </para> /// <para> /// These dedicated date formatters perform significantly /// better than <see cref="M:DateTime.ToString(string)"/>. /// </para> /// </description> /// </item> /// <item> /// <term>env</term> /// <description> /// <para> /// Used to output the a specific environment variable. The key to /// lookup must be specified within braces and directly following the /// pattern specifier, e.g. <b>%env{COMPUTERNAME}</b> would include the value /// of the <c>COMPUTERNAME</c> environment variable. /// </para> /// <para> /// The <c>env</c> pattern is not supported on the .NET Compact Framework. /// </para> /// </description> /// </item> /// <item> /// <term>identity</term> /// <description> /// <para> /// Used to output the user name for the currently active user /// (Principal.Identity.Name). /// </para> /// </description> /// </item> /// <item> /// <term>newline</term> /// <description> /// <para> /// Outputs the platform dependent line separator character or /// characters. /// </para> /// <para> /// This conversion pattern name offers the same performance as using /// non-portable line separator strings such as "\n", or "\r\n". /// Thus, it is the preferred way of specifying a line separator. /// </para> /// </description> /// </item> /// <item> /// <term>processid</term> /// <description> /// <para> /// Used to output the system process ID for the current process. /// </para> /// </description> /// </item> /// <item> /// <term>property</term> /// <description> /// <para> /// Used to output a specific context property. The key to /// lookup must be specified within braces and directly following the /// pattern specifier, e.g. <b>%property{user}</b> would include the value /// from the property that is keyed by the string 'user'. Each property value /// that is to be included in the log must be specified separately. /// Properties are stored in logging contexts. By default /// the <c>log4net:HostName</c> property is set to the name of machine on /// which the event was originally logged. /// </para> /// <para> /// If no key is specified, e.g. <b>%property</b> then all the keys and their /// values are printed in a comma separated list. /// </para> /// <para> /// The properties of an event are combined from a number of different /// contexts. These are listed below in the order in which they are searched. /// </para> /// <list type="definition"> /// <item> /// <term>the thread properties</term> /// <description> /// The <see cref="ThreadContext.Properties"/> that are set on the current /// thread. These properties are shared by all events logged on this thread. /// </description> /// </item> /// <item> /// <term>the global properties</term> /// <description> /// The <see cref="GlobalContext.Properties"/> that are set globally. These /// properties are shared by all the threads in the AppDomain. /// </description> /// </item> /// </list> /// </description> /// </item> /// <item> /// <term>random</term> /// <description> /// <para> /// Used to output a random string of characters. The string is made up of /// uppercase letters and numbers. By default the string is 4 characters long. /// The length of the string can be specified within braces directly following the /// pattern specifier, e.g. <b>%random{8}</b> would output an 8 character string. /// </para> /// </description> /// </item> /// <item> /// <term>username</term> /// <description> /// <para> /// Used to output the WindowsIdentity for the currently /// active user. /// </para> /// </description> /// </item> /// <item> /// <term>utcdate</term> /// <description> /// <para> /// Used to output the date of the logging event in universal time. /// The date conversion /// specifier may be followed by a <i>date format specifier</i> enclosed /// between braces. For example, <b>%utcdate{HH:mm:ss,fff}</b> or /// <b>%utcdate{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is /// given then ISO8601 format is /// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>). /// </para> /// <para> /// The date format specifier admits the same syntax as the /// time pattern string of the <see cref="M:DateTime.ToString(string)"/>. /// </para> /// <para> /// For better results it is recommended to use the log4net date /// formatters. These can be specified using one of the strings /// "ABSOLUTE", "DATE" and "ISO8601" for specifying /// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>, /// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively /// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example, /// <b>%utcdate{ISO8601}</b> or <b>%utcdate{ABSOLUTE}</b>. /// </para> /// <para> /// These dedicated date formatters perform significantly /// better than <see cref="M:DateTime.ToString(string)"/>. /// </para> /// </description> /// </item> /// <item> /// <term>%</term> /// <description> /// <para> /// The sequence %% outputs a single percent sign. /// </para> /// </description> /// </item> /// </list> /// <para> /// Additional pattern converters may be registered with a specific <see cref="PatternString"/> /// instance using <see cref="M:AddConverter(ConverterInfo)"/> or /// <see cref="M:AddConverter(string, Type)" />. /// </para> /// <para> /// See the <see cref="log4net.Layout.PatternLayout"/> for details on the /// <i>format modifiers</i> supported by the patterns. /// </para> /// </remarks> /// <author>Nicko Cadell</author> public class PatternString : IOptionHandler { #region Static Fields /// <summary> /// Internal map of converter identifiers to converter types. /// </summary> private static Hashtable s_globalRulesRegistry; #endregion Static Fields #region Member Variables /// <summary> /// the pattern /// </summary> private string m_pattern; /// <summary> /// the head of the pattern converter chain /// </summary> private PatternConverter m_head; /// <summary> /// patterns defined on this PatternString only /// </summary> private Hashtable m_instanceRulesRegistry = new Hashtable(); #endregion #region Static Constructor /// <summary> /// Initialize the global registry /// </summary> static PatternString() { s_globalRulesRegistry = new Hashtable(15); s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); #if !NETCF s_globalRulesRegistry.Add("env", typeof(EnvironmentPatternConverter)); s_globalRulesRegistry.Add("envFolderPath", typeof(EnvironmentFolderPathPatternConverter)); #endif s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); s_globalRulesRegistry.Add("processid", typeof(ProcessIdPatternConverter)); s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("random", typeof(RandomStringPatternConverter)); s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); } #endregion Static Constructor #region Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Initialize a new instance of <see cref="PatternString"/> /// </para> /// </remarks> public PatternString() { } /// <summary> /// Constructs a PatternString /// </summary> /// <param name="pattern">The pattern to use with this PatternString</param> /// <remarks> /// <para> /// Initialize a new instance of <see cref="PatternString"/> with the pattern specified. /// </para> /// </remarks> public PatternString(string pattern) { m_pattern = pattern; ActivateOptions(); } #endregion /// <summary> /// Gets or sets the pattern formatting string /// </summary> /// <value> /// The pattern formatting string /// </value> /// <remarks> /// <para> /// The <b>ConversionPattern</b> option. This is the string which /// controls formatting and consists of a mix of literal content and /// conversion specifiers. /// </para> /// </remarks> public string ConversionPattern { get { return m_pattern; } set { m_pattern = value; } } #region Implementation of IOptionHandler /// <summary> /// Initialize object options /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> virtual public void ActivateOptions() { m_head = CreatePatternParser(m_pattern).Parse(); } #endregion /// <summary> /// Create the <see cref="PatternParser"/> used to parse the pattern /// </summary> /// <param name="pattern">the pattern to parse</param> /// <returns>The <see cref="PatternParser"/></returns> /// <remarks> /// <para> /// Returns PatternParser used to parse the conversion string. Subclasses /// may override this to return a subclass of PatternParser which recognize /// custom conversion pattern name. /// </para> /// </remarks> private PatternParser CreatePatternParser(string pattern) { PatternParser patternParser = new PatternParser(pattern); // Add all the builtin patterns foreach(DictionaryEntry entry in s_globalRulesRegistry) { ConverterInfo converterInfo = new ConverterInfo(); converterInfo.Name = (string)entry.Key; converterInfo.Type = (Type)entry.Value; patternParser.PatternConverters.Add(entry.Key, converterInfo); } // Add the instance patterns foreach(DictionaryEntry entry in m_instanceRulesRegistry) { patternParser.PatternConverters[entry.Key] = entry.Value; } return patternParser; } /// <summary> /// Produces a formatted string as specified by the conversion pattern. /// </summary> /// <param name="writer">The TextWriter to write the formatted event to</param> /// <remarks> /// <para> /// Format the pattern to the <paramref name="writer"/>. /// </para> /// </remarks> public void Format(TextWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } PatternConverter c = m_head; // loop through the chain of pattern converters while(c != null) { c.Format(writer, null); c = c.Next; } } /// <summary> /// Format the pattern as a string /// </summary> /// <returns>the pattern formatted as a string</returns> /// <remarks> /// <para> /// Format the pattern to a string. /// </para> /// </remarks> public string Format() { StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); Format(writer); return writer.ToString(); } /// <summary> /// Add a converter to this PatternString /// </summary> /// <param name="converterInfo">the converter info</param> /// <remarks> /// <para> /// This version of the method is used by the configurator. /// Programmatic users should use the alternative <see cref="M:AddConverter(string,Type)"/> method. /// </para> /// </remarks> public void AddConverter(ConverterInfo converterInfo) { if (converterInfo == null) throw new ArgumentNullException("converterInfo"); if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type)) { throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo"); } m_instanceRulesRegistry[converterInfo.Name] = converterInfo; } /// <summary> /// Add a converter to this PatternString /// </summary> /// <param name="name">the name of the conversion pattern for this converter</param> /// <param name="type">the type of the converter</param> /// <remarks> /// <para> /// Add a converter to this PatternString /// </para> /// </remarks> public void AddConverter(string name, Type type) { if (name == null) throw new ArgumentNullException("name"); if (type == null) throw new ArgumentNullException("type"); ConverterInfo converterInfo = new ConverterInfo(); converterInfo.Name = name; converterInfo.Type = type; AddConverter(converterInfo); } } }
using System; using System.Collections.Generic; using System.Linq; using Signum.Entities.DynamicQuery; using Signum.Utilities; using Signum.Entities.UserQueries; using System.Drawing; using System.ComponentModel; using Signum.Entities.UserAssets; namespace Signum.Entities.Chart { public static class ChartUtils { public static bool IsChartColumnType(QueryToken token, ChartColumnType ct) { if (token == null) return false; var type = token.GetChartColumnType(); if (type == null) return false; return Flag(ct, type.Value); } public static ChartColumnType? GetChartColumnType(this QueryToken token) { switch (QueryUtils.TryGetFilterType(token.Type)) { case FilterType.Lite: return ChartColumnType.Lite; case FilterType.Boolean: case FilterType.Enum: return ChartColumnType.Enum; case FilterType.String: case FilterType.Guid: return ChartColumnType.String; case FilterType.Integer: return ChartColumnType.Integer; case FilterType.Decimal: return token.IsGroupable ? ChartColumnType.RealGroupable : ChartColumnType.Real; case FilterType.DateTime: return token.IsGroupable ? ChartColumnType.Date : ChartColumnType.DateTime; } return null; } public static bool Flag(ChartColumnType ct, ChartColumnType flag) { return (ct & flag) == flag; } public static bool IsDateOnly(QueryToken token) { if ((token is DatePartStartToken dt && (dt.Name == QueryTokenMessage.MonthStart || dt.Name == QueryTokenMessage.WeekStart)) || token is DateToken) return true; PropertyRoute? route = token.GetPropertyRoute(); if (route != null && route.PropertyRouteType == PropertyRouteType.FieldOrProperty) { var pp = Validator.TryGetPropertyValidator(route); if (pp != null) { DateTimePrecisionValidatorAttribute? datetimePrecision = pp.Validators.OfType<DateTimePrecisionValidatorAttribute>().SingleOrDefaultEx(); if (datetimePrecision != null && datetimePrecision.Precision == DateTimePrecision.Days) return true; } } return false; } public static bool SynchronizeColumns(this ChartScript chartScript, IChartBase chart, PostRetrievingContext? ctx) { bool result = false; for (int i = 0; i < chartScript.Columns.Count; i++) { if (chart.Columns.Count <= i) { chart.Columns.Add(new ChartColumnEmbedded()); result = true; } chart.Columns[i].parentChart = chart; chart.Columns[i].ScriptColumn = chartScript.Columns[i]; if (!result) result = chart.Columns[i].IntegrityCheck() != null; } if (chart.Columns.Count > chartScript.Columns.Count) { chart.Columns.RemoveRange(chartScript.Columns.Count, chart.Columns.Count - chartScript.Columns.Count); result = true; } if (chart.Parameters.Modified != ModifiedState.Sealed) { var chartScriptParameters = chartScript.AllParameters().ToList(); if (chart.Parameters.Select(a => a.Name).OrderBy().SequenceEqual(chartScriptParameters.Select(a => a.Name).OrderBy())) { foreach (var cp in chart.Parameters) { var sp = chartScriptParameters.FirstEx(a => a.Name == cp.Name); cp.parentChart = chart; cp.ScriptParameter = sp; //if (cp.PropertyCheck(() => cp.Value).HasText()) // cp.Value = sp.DefaultValue(cp.GetToken()); } } else { var byName = chart.Parameters.ToDictionary(a => a.Name); chart.Parameters.Clear(); foreach (var sp in chartScriptParameters) { var cp = byName.TryGetC(sp.Name); if (cp != null) { cp.parentChart = chart; cp.ScriptParameter = sp; ctx?.ForceModifiedState.Add(cp, ModifiedState.SelfModified); //if (cp.PropertyCheck(() => cp.Value).HasText()) // cp.Value = sp.DefaultValue(cp.GetToken()); } else { cp = new ChartParameterEmbedded { Name = sp.Name, parentChart = chart, ScriptParameter = sp, }; cp.Value = sp.ValueDefinition.DefaultValue(sp.GetToken(chart)); } chart.Parameters.Add(cp); } } } return result; } public static ChartRequestModel ToRequest(this UserChartEntity uq) { var result = new ChartRequestModel(uq.QueryName) { ChartScript = uq.ChartScript, Filters = uq.Filters.ToFilterList(), }; result.Columns.ZipForeach(uq.Columns, (r, u) => { r.Token = u.Token; r.DisplayName = u.DisplayName; r.OrderByIndex = u.OrderByIndex; r.OrderByType = u.OrderByType; }); result.Parameters.ForEach(r => { r.Value = uq.Parameters.FirstOrDefault(u => u.Name == r.Name)?.Value ?? r.ScriptParameter.DefaultValue(r.ScriptParameter.GetToken(uq)); }); return result; } internal static void FixParameters(IChartBase chart, ChartColumnEmbedded chartColumn) { int index = chart.Columns.IndexOf(chartColumn); foreach (var p in chart.Parameters.Where(p => p.ScriptParameter.ColumnIndex == index)) { if (p.PropertyCheck(() => p.Value).HasText()) p.Value = p.ScriptParameter.DefaultValue(chartColumn.Token?.Token); } } } public enum ChartMessage { [Description("{0} can only be created from the chart window")] _0CanOnlyBeCreatedFromTheChartWindow, [Description("{0} can only be created from the search window")] _0CanOnlyBeCreatedFromTheSearchWindow, Chart, [Description("Chart")] ChartToken, [Description("Chart settings")] Chart_ChartSettings, [Description("Dimension")] Chart_Dimension, DrawChart, [Description("Group")] Chart_Group, [Description("Query {0} is not allowed")] Chart_Query0IsNotAllowed, [Description("Toggle info")] Chart_ToggleInfo, [Description("Colors for {0}")] ColorsFor0, CreatePalette, [Description("My Charts")] MyCharts, CreateNew, Edit, ViewPalette, [Description("Chart for")] ChartFor, [Description("Chart of {0}")] ChartOf0, [Description("{0} is key, but {1} is an aggregate")] _0IsKeyBut1IsAnAggregate, [Description("{0} should be an aggregate")] _0ShouldBeAnAggregate, [Description("{0} should be set")] _0ShouldBeSet, [Description("{0} should be null")] _0ShouldBeNull, [Description("{0} is not {1}")] _0IsNot1, [Description("{0} is an aggregate, but the chart is not grouping")] _0IsAnAggregateButTheChartIsNotGrouping, [Description("{0} is not optional")] _0IsNotOptional, SavePalette, NewPalette, Data, ChooseABasePalette, DeletePalette, Preview, TypeNotFound, [Description("Type {0} is not in the database")] Type0NotFoundInTheDatabase, Reload, Maximize, Minimize, ShowChartSettings, HideChartSettings, [Description("Query result reached max rows ({0})")] QueryResultReachedMaxRows0 } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Drawing { /// <summary> /// Represents an ordered pair of x and y coordinates that /// define a point in a two-dimensional plane. /// </summary> public struct PointF { /// <summary> /// <para> /// Creates a new instance of the <see cref='System.Drawing.PointF'/> class /// with member data left uninitialized. /// </para> /// </summary> public static readonly PointF Empty = new PointF(); private float _x; private float _y; /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.PointF'/> class /// with the specified coordinates. /// </para> /// </summary> public PointF(float x, float y) { _x = x; _y = y; } /// <summary> /// <para> /// Gets a value indicating whether this <see cref='System.Drawing.PointF'/> is empty. /// </para> /// </summary> public bool IsEmpty { get { return _x == 0f && _y == 0f; } } /// <summary> /// <para> /// Gets the x-coordinate of this <see cref='System.Drawing.PointF'/>. /// </para> /// </summary> public float X { get { return _x; } set { _x = value; } } /// <summary> /// <para> /// Gets the y-coordinate of this <see cref='System.Drawing.PointF'/>. /// </para> /// </summary> public float Y { get { return _y; } set { _y = value; } } /// <summary> /// <para> /// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static PointF operator +(PointF pt, Size sz) { return Add(pt, sz); } /// <summary> /// <para> /// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static PointF operator -(PointF pt, Size sz) { return Subtract(pt, sz); } /// <summary> /// <para> /// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.SizeF'/> . /// </para> /// </summary> public static PointF operator +(PointF pt, SizeF sz) { return Add(pt, sz); } /// <summary> /// <para> /// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.SizeF'/> . /// </para> /// </summary> public static PointF operator -(PointF pt, SizeF sz) { return Subtract(pt, sz); } /// <summary> /// <para> /// Compares two <see cref='System.Drawing.PointF'/> objects. The result specifies /// whether the values of the <see cref='System.Drawing.PointF.X'/> and <see cref='System.Drawing.PointF.Y'/> properties of the two <see cref='System.Drawing.PointF'/> /// objects are equal. /// </para> /// </summary> public static bool operator ==(PointF left, PointF right) { return left.X == right.X && left.Y == right.Y; } /// <summary> /// <para> /// Compares two <see cref='System.Drawing.PointF'/> objects. The result specifies whether the values /// of the <see cref='System.Drawing.PointF.X'/> or <see cref='System.Drawing.PointF.Y'/> properties of the two /// <see cref='System.Drawing.PointF'/> /// objects are unequal. /// </para> /// </summary> public static bool operator !=(PointF left, PointF right) { return !(left == right); } /// <summary> /// <para> /// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static PointF Add(PointF pt, Size sz) { return new PointF(pt.X + sz.Width, pt.Y + sz.Height); } /// <summary> /// <para> /// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static PointF Subtract(PointF pt, Size sz) { return new PointF(pt.X - sz.Width, pt.Y - sz.Height); } /// <summary> /// <para> /// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.SizeF'/> . /// </para> /// </summary> public static PointF Add(PointF pt, SizeF sz) { return new PointF(pt.X + sz.Width, pt.Y + sz.Height); } /// <summary> /// <para> /// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.SizeF'/> . /// </para> /// </summary> public static PointF Subtract(PointF pt, SizeF sz) { return new PointF(pt.X - sz.Width, pt.Y - sz.Height); } public override bool Equals(object obj) { if (!(obj is PointF)) return false; PointF comp = (PointF)obj; return comp.X == X && comp.Y == Y; } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return "{X=" + _x.ToString() + ", Y=" + _y.ToString() + "}"; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { /// <summary> /// Compile expressions at type-scope to support /// expressions in DebuggerDisplayAttribute values. /// </summary> public class DebuggerDisplayAttributeTests : ExpressionCompilerTestBase { [Fact] public void FieldsAndProperties() { var source = @"using System.Diagnostics; [DebuggerDisplay(""{F}, {G}, {P}, {Q}"")] class C { static object F = 1; int G = 2; static int P { get { return 3; } } object Q { get { return 4; } } }"; var compilation0 = CreateStandardCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateTypeContext(runtime, "C"); // Static field. AssertEx.AssertEqualToleratingWhitespaceDifferences( CompileExpression(context, "F"), @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: ldsfld ""object C.F"" IL_0005: ret }"); // Instance field. AssertEx.AssertEqualToleratingWhitespaceDifferences( CompileExpression(context, "G"), @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""int C.G"" IL_0006: ret }"); // Static property. AssertEx.AssertEqualToleratingWhitespaceDifferences( CompileExpression(context, "P"), @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.P.get"" IL_0005: ret }"); // Instance property. AssertEx.AssertEqualToleratingWhitespaceDifferences( CompileExpression(context, "Q"), @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""object C.Q.get"" IL_0006: ret }"); }); } [Fact] public void Constants() { var source = @"using System.Diagnostics; [DebuggerDisplay(""{F[G]}"")] class C { const string F = ""str""; const int G = 2; }"; var compilation0 = CreateStandardCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(compilation0, runtime => { var context = CreateTypeContext(runtime, "C"); AssertEx.AssertEqualToleratingWhitespaceDifferences( CompileExpression(context, "F[G]"), @"{ // Code size 12 (0xc) .maxstack 2 IL_0000: ldstr ""str"" IL_0005: ldc.i4.2 IL_0006: call ""char string.this[int].get"" IL_000b: ret }"); }); } [Fact] public void This() { var source = @"using System.Diagnostics; [DebuggerDisplay(""{F(this)}"")] class C { static object F(C c) { return c; } }"; var compilation0 = CreateStandardCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(compilation0, runtime => { var context = CreateTypeContext(runtime, "C"); AssertEx.AssertEqualToleratingWhitespaceDifferences( CompileExpression(context, "F(this)"), @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object C.F(C)"" IL_0006: ret }"); }); } [Fact] public void Base() { var source = @"using System.Diagnostics; class A { internal object F() { return 1; } } [DebuggerDisplay(""{base.F()}"")] class B : A { new object F() { return 2; } }"; var compilation0 = CreateStandardCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(compilation0, runtime => { var context = CreateTypeContext(runtime, "B"); AssertEx.AssertEqualToleratingWhitespaceDifferences( CompileExpression(context, "base.F()"), @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object A.F()"" IL_0006: ret }"); }); } [Fact] public void GenericType() { var source = @"using System.Diagnostics; class A<T> where T : class { [DebuggerDisplay(""{F(default(T), default(U))}"")] internal class B<U> { static object F<X, Y>(X x, Y y) where X : class { return x ?? (object)y; } } }"; var compilation0 = CreateStandardCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(compilation0, runtime => { var context = CreateTypeContext(runtime, "A.B"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("F(default(T), default(U))", out error, testData); string actualIL = testData.GetMethodData("<>x<T, U>.<>m0").GetMethodIL(); AssertEx.AssertEqualToleratingWhitespaceDifferences( actualIL, @"{ // Code size 24 (0x18) .maxstack 2 .locals init (T V_0, U V_1) IL_0000: ldloca.s V_0 IL_0002: initobj ""T"" IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: initobj ""U"" IL_0011: ldloc.1 IL_0012: call ""object A<T>.B<U>.F<T, U>(T, U)"" IL_0017: ret }"); // Verify generated type is generic, but method is not. using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(result.Assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef(result.TypeName); reader.CheckTypeParameters(typeDef.GetGenericParameters(), "T", "U"); var methodDef = reader.GetMethodDef(typeDef, result.MethodName); reader.CheckTypeParameters(methodDef.GetGenericParameters()); } }); } [Fact] public void Usings() { var source = @"using System.Diagnostics; using A = N; using B = N.C; namespace N { [DebuggerDisplay(""{typeof(A.C) ?? typeof(B) ?? typeof(C)}"")] class C { void M() { } } }"; var compilation0 = CreateStandardCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(compilation0, runtime => { var context = CreateTypeContext(runtime, "N.C"); string error; var testData = new CompilationTestData(); // Expression compilation should succeed without imports. var result = context.CompileExpression("typeof(N.C) ?? typeof(C)", out error, testData); Assert.Null(error); AssertEx.AssertEqualToleratingWhitespaceDifferences( testData.GetMethodData("<>x.<>m0").GetMethodIL(), @"{ // Code size 25 (0x19) .maxstack 2 IL_0000: ldtoken ""N.C"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: dup IL_000b: brtrue.s IL_0018 IL_000d: pop IL_000e: ldtoken ""N.C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ret }"); // Expression compilation should fail using imports since there are no symbols. context = CreateTypeContext(runtime, "N.C"); testData = new CompilationTestData(); result = context.CompileExpression("typeof(A.C) ?? typeof(B) ?? typeof(C)", out error, testData); Assert.Equal(error, "error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)"); testData = new CompilationTestData(); result = context.CompileExpression("typeof(B) ?? typeof(C)", out error, testData); Assert.Equal(error, "error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)"); }); } [Fact] public void PseudoVariable() { var source = @"using System.Diagnostics; [DebuggerDisplay(""{$ReturnValue}"")] class C { }"; var compilation0 = CreateStandardCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(compilation0, runtime => { var context = CreateTypeContext(runtime, "C"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("$ReturnValue", out error, testData); Assert.Equal(error, "error CS0103: The name '$ReturnValue' does not exist in the current context"); }); } [Fact] public void LambdaClosedOverThis() { var source = @"class C { object o; static object F(System.Func<object> f) { return f(); } }"; var compilation0 = CreateStandardCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(compilation0, runtime => { var context = CreateTypeContext(runtime, "C"); AssertEx.AssertEqualToleratingWhitespaceDifferences( @"{ // Code size 29 (0x1d) .maxstack 3 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld ""C <>x.<>c__DisplayClass0_0.<>4__this"" IL_000c: ldftn ""object <>x.<>c__DisplayClass0_0.<<>m0>b__0()"" IL_0012: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0017: call ""object C.F(System.Func<object>)"" IL_001c: ret }", CompileExpression(context, "F(() => this.o)")); }); } [Fact] public void FormatSpecifiers() { var source = @"using System.Diagnostics; [DebuggerDisplay(""{F, nq}, {F}"")] class C { object F = ""f""; }"; var compilation0 = CreateStandardCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(compilation0, runtime => { var context = CreateTypeContext(runtime, "C"); // No format specifiers. string error; var result = context.CompileExpression("F", out error); Assert.NotNull(result.Assembly); Assert.Null(result.FormatSpecifiers); // Format specifiers. result = context.CompileExpression("F, nq,ac", out error); Assert.NotNull(result.Assembly); Assert.Equal(result.FormatSpecifiers.Count, 2); Assert.Equal(result.FormatSpecifiers[0], "nq"); Assert.Equal(result.FormatSpecifiers[1], "ac"); }); } [Fact] public void VirtualMethod() { var source = @" using System.Diagnostics; [DebuggerDisplay(""{GetDebuggerDisplay()}"")] public class Base { protected virtual string GetDebuggerDisplay() { return ""base""; } } public class Derived : Base { protected override string GetDebuggerDisplay() { return ""derived""; } } "; var compilation0 = CreateStandardCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(compilation0, runtime => { var context = CreateTypeContext(runtime, "Derived"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("GetDebuggerDisplay()", out error, testData); Assert.Null(error); var actualIL = testData.GetMethodData("<>x.<>m0").GetMethodIL(); var expectedIL = @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""string Derived.GetDebuggerDisplay()"" IL_0006: ret }"; AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL); }); } private static string CompileExpression(EvaluationContext context, string expr) { string error; var testData = new CompilationTestData(); var result = context.CompileExpression(expr, out error, testData); Assert.NotNull(result.Assembly); Assert.Null(error); return testData.GetMethodData(result.TypeName + "." + result.MethodName).GetMethodIL(); } } }
// *********************************************************************** // Copyright (c) 2012 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. // *********************************************************************** #if PARALLEL using System; using System.Collections.Generic; using System.Threading; namespace NUnit.Framework.Internal.Execution { /// <summary> /// WorkItemQueueState indicates the current state of a WorkItemQueue /// </summary> public enum WorkItemQueueState { /// <summary> /// The queue is paused /// </summary> Paused, /// <summary> /// The queue is running /// </summary> Running, /// <summary> /// The queue is stopped /// </summary> Stopped } /// <summary> /// A WorkItemQueue holds work items that are ready to /// be run, either initially or after some dependency /// has been satisfied. /// </summary> public class WorkItemQueue { private Logger log = InternalTrace.GetLogger("WorkItemQueue"); private Queue<WorkItem> _innerQueue = new Queue<WorkItem>(); private object _syncRoot = new object(); #if NETCF private ManualResetEvent _syncEvent = new ManualResetEvent(false); private int _waitCount = 0; #endif /// <summary> /// Initializes a new instance of the <see cref="WorkItemQueue"/> class. /// </summary> /// <param name="name">The name of the queue.</param> public WorkItemQueue(string name) { this.Name = name; this.State = WorkItemQueueState.Paused; this.MaxCount = 0; this.ItemsProcessed = 0; } #region Properties /// <summary> /// Gets the name of the work item queue. /// </summary> public string Name { get; private set; } /// <summary> /// Gets the total number of items processed so far /// </summary> public int ItemsProcessed { get; private set; } /// <summary> /// Gets the maximum number of work items. /// </summary> public int MaxCount { get; private set; } /// <summary> /// Gets the current state of the queue /// </summary> public WorkItemQueueState State { get; private set; } /// <summary> /// Get a bool indicating whether the queue is empty. /// </summary> public bool IsEmpty { get { return _innerQueue.Count == 0; } } #endregion #region Public Methods /// <summary> /// Enqueue a WorkItem to be processed /// </summary> /// <param name="work">The WorkItem to process</param> public void Enqueue(WorkItem work) { lock (_syncRoot) { _innerQueue.Enqueue(work); if (_innerQueue.Count > MaxCount) MaxCount = _innerQueue.Count; #if NETCF _syncEvent.Set(); while (_waitCount != 0) Thread.Sleep(0); _syncEvent.Reset(); #else Monitor.PulseAll(_syncRoot); #endif } } /// <summary> /// Dequeue a WorkItem for processing /// </summary> /// <returns>A WorkItem or null if the queue has stopped</returns> public WorkItem Dequeue() { lock (_syncRoot) { while (this.IsEmpty || this.State != WorkItemQueueState.Running) { if (State == WorkItemQueueState.Stopped) return null; // Tell worker to terminate else // We are either paused or empty, so wait for something to change #if NETCF { Monitor.Exit(_syncRoot); Interlocked.Increment(ref _waitCount); _syncEvent.WaitOne(); Interlocked.Decrement(ref _waitCount); Monitor.Enter(_syncRoot); } #else Monitor.Wait(_syncRoot); #endif } // Queue is running and non-empty ItemsProcessed++; return _innerQueue.Dequeue(); } } /// <summary> /// Start or restart processing of items from the queue /// </summary> public void Start() { lock (_syncRoot) { log.Info("{0} starting", Name); State = WorkItemQueueState.Running; #if NETCF _syncEvent.Set(); while (_waitCount != 0) Thread.Sleep(0); _syncEvent.Reset(); #else Monitor.PulseAll(_syncRoot); #endif } } /// <summary> /// Signal the queue to stop /// </summary> public void Stop() { lock (_syncRoot) { log.Info("{0} stopping - {1} WorkItems processed, max size {2}", Name, ItemsProcessed, MaxCount); State = WorkItemQueueState.Stopped; #if NETCF _syncEvent.Set(); while (_waitCount != 0) Thread.Sleep(0); _syncEvent.Reset(); #else Monitor.PulseAll(_syncRoot); #endif } } /// <summary> /// Pause the queue for restarting later /// </summary> public void Pause() { lock (_syncRoot) { State = WorkItemQueueState.Paused; } } #endregion } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.IO; using System.Runtime.InteropServices; namespace System.Drawing.Internal { internal sealed class GPStream : Interop.Ole32.IStream { private Stream _dataStream; // to support seeking ahead of the stream length... private long _virtualPosition = -1; internal GPStream(Stream stream, bool makeSeekable = true) { if (makeSeekable && !stream.CanSeek) { // Copy to a memory stream so we can seek MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); _dataStream = memoryStream; } else { _dataStream = stream; } } private void ActualizeVirtualPosition() { if (_virtualPosition == -1) return; if (_virtualPosition > _dataStream.Length) _dataStream.SetLength(_virtualPosition); _dataStream.Position = _virtualPosition; _virtualPosition = -1; } public Interop.Ole32.IStream Clone() { // The cloned object should have the same current "position" return new GPStream(_dataStream) { _virtualPosition = _virtualPosition }; } public void Commit(uint grfCommitFlags) { _dataStream.Flush(); // Extend the length of the file if needed. ActualizeVirtualPosition(); } public unsafe void CopyTo(Interop.Ole32.IStream pstm, ulong cb, ulong* pcbRead, ulong* pcbWritten) { byte[] buffer = ArrayPool<byte>.Shared.Rent(4096); ulong remaining = cb; ulong totalWritten = 0; ulong totalRead = 0; fixed (byte* b = buffer) { while (remaining > 0) { uint read = remaining < (ulong)buffer.Length ? (uint)remaining : (uint)buffer.Length; Read(b, read, &read); remaining -= read; totalRead += read; if (read == 0) { break; } uint written; pstm.Write(b, read, &written); totalWritten += written; } } ArrayPool<byte>.Shared.Return(buffer); if (pcbRead != null) *pcbRead = totalRead; if (pcbWritten != null) *pcbWritten = totalWritten; } public unsafe void Read(byte* pv, uint cb, uint* pcbRead) { ActualizeVirtualPosition(); // Stream Span API isn't available in 2.0 #if netcoreapp20 byte[] buffer = ArrayPool<byte>.Shared.Rent(checked((int)cb)); int read = _dataStream.Read(buffer, 0, checked((int)cb)); Marshal.Copy(buffer, 0, (IntPtr)pv, read); ArrayPool<byte>.Shared.Return(buffer); #else Span<byte> buffer = new Span<byte>(pv, checked((int)cb)); int read = _dataStream.Read(buffer); #endif if (pcbRead != null) *pcbRead = (uint)read; } public void Revert() { // We never report ourselves as Transacted, so we can just ignore this. } public unsafe void Seek(long dlibMove, SeekOrigin dwOrigin, ulong* plibNewPosition) { long position = _virtualPosition; if (_virtualPosition == -1) { position = _dataStream.Position; } long length = _dataStream.Length; switch (dwOrigin) { case SeekOrigin.Begin: if (dlibMove <= length) { _dataStream.Position = dlibMove; _virtualPosition = -1; } else { _virtualPosition = dlibMove; } break; case SeekOrigin.End: if (dlibMove <= 0) { _dataStream.Position = length + dlibMove; _virtualPosition = -1; } else { _virtualPosition = length + dlibMove; } break; case SeekOrigin.Current: if (dlibMove + position <= length) { _dataStream.Position = position + dlibMove; _virtualPosition = -1; } else { _virtualPosition = dlibMove + position; } break; } if (plibNewPosition == null) return; if (_virtualPosition != -1) { *plibNewPosition = (ulong)_virtualPosition; } else { *plibNewPosition = (ulong)_dataStream.Position; } } public void SetSize(ulong value) { _dataStream.SetLength(checked((long)value)); } public void Stat(out Interop.Ole32.STATSTG pstatstg, Interop.Ole32.STATFLAG grfStatFlag) { pstatstg = new Interop.Ole32.STATSTG { cbSize = (ulong)_dataStream.Length, type = Interop.Ole32.STGTY.STGTY_STREAM, // Default read/write access is STGM_READ, which == 0 grfMode = _dataStream.CanWrite ? _dataStream.CanRead ? Interop.Ole32.STGM.STGM_READWRITE : Interop.Ole32.STGM.STGM_WRITE : Interop.Ole32.STGM.Default }; if (grfStatFlag == Interop.Ole32.STATFLAG.STATFLAG_DEFAULT) { // Caller wants a name pstatstg.AllocName(_dataStream is FileStream fs ? fs.Name : _dataStream.ToString()); } } public unsafe void Write(byte* pv, uint cb, uint* pcbWritten) { ActualizeVirtualPosition(); // Stream Span API isn't available in 2.0 #if netcoreapp20 byte[] buffer = ArrayPool<byte>.Shared.Rent(checked((int)cb)); Marshal.Copy((IntPtr)pv, buffer, 0, checked((int)cb)); _dataStream.Write(buffer, 0, checked((int)cb)); ArrayPool<byte>.Shared.Return(buffer); #else Span<byte> buffer = new Span<byte>(pv, checked((int)cb)); _dataStream.Write(buffer); #endif if (pcbWritten != null) *pcbWritten = cb; } public Interop.HRESULT LockRegion(ulong libOffset, ulong cb, uint dwLockType) { // Documented way to say we don't support locking return Interop.HRESULT.STG_E_INVALIDFUNCTION; } public Interop.HRESULT UnlockRegion(ulong libOffset, ulong cb, uint dwLockType) { // Documented way to say we don't support locking return Interop.HRESULT.STG_E_INVALIDFUNCTION; } } }
#region PDFsharp Charting - A .NET charting library based on PDFsharp // // Authors: // Niklas Schneider // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using PdfSharp.Drawing; namespace PdfSharp.Charting.Renderers { /// <summary> /// Represents the base class of all renderer infos. /// Renderer infos are used to hold all necessary information and time consuming calculations /// between rendering cycles. /// </summary> internal abstract class RendererInfo { } /// <summary> /// Base class for all renderer infos which defines an area. /// </summary> internal abstract class AreaRendererInfo : RendererInfo { /// <summary> /// Gets or sets the x coordinate of this rectangle. /// </summary> internal virtual double X { get { return _rect.X; } set { _rect.X = value; } } /// <summary> /// Gets or sets the y coordinate of this rectangle. /// </summary> internal virtual double Y { get { return _rect.Y; } set { _rect.Y = value; } } /// <summary> /// Gets or sets the width of this rectangle. /// </summary> internal virtual double Width { get { return _rect.Width; } set { _rect.Width = value; } } /// <summary> /// Gets or sets the height of this rectangle. /// </summary> internal virtual double Height { get { return _rect.Height; } set { _rect.Height = value; } } /// <summary> /// Gets the area's size. /// </summary> internal XSize Size { get { return _rect.Size; } set { _rect.Size = value; } } /// <summary> /// Gets the area's rectangle. /// </summary> internal XRect Rect { get { return _rect; } set { _rect = value; } } XRect _rect; } /// <summary> /// A ChartRendererInfo stores information of all main parts of a chart like axis renderer info or /// plotarea renderer info. /// </summary> internal class ChartRendererInfo : AreaRendererInfo { internal Chart _chart; internal AxisRendererInfo xAxisRendererInfo; internal AxisRendererInfo yAxisRendererInfo; //internal AxisRendererInfo zAxisRendererInfo; // not yet used internal PlotAreaRendererInfo plotAreaRendererInfo; internal LegendRendererInfo legendRendererInfo; internal SeriesRendererInfo[] seriesRendererInfos; /// <summary> /// Gets the chart's default font for rendering. /// </summary> internal XFont DefaultFont { get { return _defaultFont ?? (_defaultFont = Converter.ToXFont(_chart._font, new XFont("Arial", 12, XFontStyle.Regular))); } } XFont _defaultFont; /// <summary> /// Gets the chart's default font for rendering data labels. /// </summary> internal XFont DefaultDataLabelFont { get { return _defaultDataLabelFont ?? (_defaultDataLabelFont = Converter.ToXFont(_chart._font, new XFont("Arial", 10, XFontStyle.Regular))); } } XFont _defaultDataLabelFont; } /// <summary> /// A CombinationRendererInfo stores information for rendering combination of charts. /// </summary> internal class CombinationRendererInfo : ChartRendererInfo { internal SeriesRendererInfo[] _commonSeriesRendererInfos; internal SeriesRendererInfo[] _areaSeriesRendererInfos; internal SeriesRendererInfo[] _columnSeriesRendererInfos; internal SeriesRendererInfo[] _lineSeriesRendererInfos; } /// <summary> /// PointRendererInfo is used to render one single data point which is part of a data series. /// </summary> internal class PointRendererInfo : RendererInfo { internal Point Point; internal XPen LineFormat; internal XBrush FillFormat; } /// <summary> /// Represents one sector of a series used by a pie chart. /// </summary> internal class SectorRendererInfo : PointRendererInfo { internal XRect Rect; internal double StartAngle; internal double SweepAngle; } /// <summary> /// Represents one data point of a series and the corresponding rectangle. /// </summary> internal class ColumnRendererInfo : PointRendererInfo { internal XRect Rect; } /// <summary> /// Stores rendering specific information for one data label entry. /// </summary> internal class DataLabelEntryRendererInfo : AreaRendererInfo { internal string Text; } /// <summary> /// Stores data label specific rendering information. /// </summary> internal class DataLabelRendererInfo : RendererInfo { internal DataLabelEntryRendererInfo[] Entries; internal string Format; internal XFont Font; internal XBrush FontColor; internal DataLabelPosition Position; internal DataLabelType Type; } /// <summary> /// SeriesRendererInfo holds all data series specific rendering information. /// </summary> internal class SeriesRendererInfo : RendererInfo { internal Series _series; internal DataLabelRendererInfo _dataLabelRendererInfo; internal PointRendererInfo[] _pointRendererInfos; internal XPen LineFormat; internal XBrush FillFormat; // Used if ChartType is set to Line internal MarkerRendererInfo _markerRendererInfo; /// <summary> /// Gets the sum of all points in PointRendererInfo. /// </summary> internal double SumOfPoints { get { double sum = 0; foreach (PointRendererInfo pri in _pointRendererInfos) { if (!double.IsNaN(pri.Point._value)) sum += Math.Abs(pri.Point._value); } return sum; } } } /// <summary> /// Represents a description of a marker for a line chart. /// </summary> internal class MarkerRendererInfo : RendererInfo { internal XUnit MarkerSize; internal MarkerStyle MarkerStyle; internal XColor MarkerForegroundColor; internal XColor MarkerBackgroundColor; } /// <summary> /// An AxisRendererInfo holds all axis specific rendering information. /// </summary> internal class AxisRendererInfo : AreaRendererInfo { internal Axis _axis; internal double MinimumScale; internal double MaximumScale; internal double MajorTick; internal double MinorTick; internal TickMarkType MinorTickMark; internal TickMarkType MajorTickMark; internal double MajorTickMarkWidth; internal double MinorTickMarkWidth; internal XPen MajorTickMarkLineFormat; internal XPen MinorTickMarkLineFormat; //Gridlines internal XPen MajorGridlinesLineFormat; internal XPen MinorGridlinesLineFormat; //AxisTitle internal AxisTitleRendererInfo _axisTitleRendererInfo; //TickLabels internal string TickLabelsFormat; internal XFont TickLabelsFont; internal XBrush TickLabelsBrush; internal double TickLabelsHeight; //LineFormat internal XPen LineFormat; //Chart.XValues, used for X axis only. internal XValues XValues; /// <summary> /// Sets the x coordinate of the inner rectangle. /// </summary> internal override double X { set { base.X = value; InnerRect.X = value; } } /// <summary> /// Sets the y coordinate of the inner rectangle. /// </summary> internal override double Y { set { base.Y = value; InnerRect.Y = value + LabelSize.Height / 2; } } /// <summary> /// Sets the height of the inner rectangle. /// </summary> internal override double Height { set { base.Height = value; InnerRect.Height = value - (InnerRect.Y - Y); } } /// <summary> /// Sets the width of the inner rectangle. /// </summary> internal override double Width { set { base.Width = value; InnerRect.Width = value - LabelSize.Width / 2; } } internal XRect InnerRect; internal XSize LabelSize; } internal class AxisTitleRendererInfo : AreaRendererInfo { internal AxisTitle _axisTitle; internal string AxisTitleText; internal XFont AxisTitleFont; internal XBrush AxisTitleBrush; internal double AxisTitleOrientation; internal HorizontalAlignment AxisTitleAlignment; internal VerticalAlignment AxisTitleVerticalAlignment; internal XSize AxisTitleSize; } /// <summary> /// Represents one description of a legend entry. /// </summary> internal class LegendEntryRendererInfo : AreaRendererInfo { internal SeriesRendererInfo _seriesRendererInfo; internal LegendRendererInfo _legendRendererInfo; internal string EntryText; /// <summary> /// Size for the marker only. /// </summary> internal XSize MarkerSize; internal XPen MarkerPen; internal XBrush MarkerBrush; /// <summary> /// Width for marker area. Extra spacing for line charts are considered. /// </summary> internal XSize MarkerArea; /// <summary> /// Size for text area. /// </summary> internal XSize TextSize; } /// <summary> /// Stores legend specific rendering information. /// </summary> internal class LegendRendererInfo : AreaRendererInfo { internal Legend _legend; internal XFont Font; internal XBrush FontColor; internal XPen BorderPen; internal LegendEntryRendererInfo[] Entries; } /// <summary> /// Stores rendering information common to all plot area renderers. /// </summary> internal class PlotAreaRendererInfo : AreaRendererInfo { internal PlotArea _plotArea; /// <summary> /// Saves the plot area's matrix. /// </summary> internal XMatrix _matrix; internal XPen LineFormat; internal XBrush FillFormat; } }
using Microsoft.Data.SqlClient; using Net.Code.ADONet.Extensions.Mapping; using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Dynamic; using System.Reflection; using System.Text.RegularExpressions; #pragma warning disable namespace Net.Code.ADONet { using static DBNullHelper; public partial class CommandBuilder { private class AsyncExecutor { private readonly DbCommand _command; public AsyncExecutor(DbCommand command) { _command = command; } /// <summary> /// executes the query as a datareader /// </summary> public async Task<DbDataReader> Reader() { var command = await PrepareAsync().ConfigureAwait(false); return await command.ExecuteReaderAsync().ConfigureAwait(false); } /// <summary> /// Executes the command, returning the first column of the first result as a scalar value /// </summary> public async Task<object> Scalar() { var command = await PrepareAsync().ConfigureAwait(false); return await command.ExecuteScalarAsync().ConfigureAwait(false); } /// <summary> /// Executes the command as a SQL statement, returning the number of rows affected /// </summary> public async Task<int> NonQuery() { var command = await PrepareAsync().ConfigureAwait(false); return await command.ExecuteNonQueryAsync().ConfigureAwait(false); } private async Task<DbCommand> PrepareAsync() { Logger.LogCommand(_command); if (_command.Connection.State == ConnectionState.Closed) await _command.Connection.OpenAsync().ConfigureAwait(false); return _command; } } } public partial class CommandBuilder { private readonly DbConfig _config; public CommandBuilder(DbCommand command, DbConfig config) { Command = command; _config = config; } /// <summary> /// Sets the command text /// </summary> /// <param name = "text"></param> public CommandBuilder WithCommandText(string text) { Command.CommandText = text; return this; } /// <summary> /// Sets the command type /// </summary> /// <param name = "type"></param> public CommandBuilder OfType(CommandType type) { Command.CommandType = type; return this; } /// <summary> /// Adds a parameter for each property of the given object, with the property name as the name /// of the parameter and the property value as the corresponding parameter value /// </summary> /// <param name = "parameters"></param> public CommandBuilder WithParameters<T>(T parameters) { if (parameters == null) throw new ArgumentNullException(nameof(parameters)); var getters = FastReflection<T>.Instance.GetGettersForType(); var props = parameters.GetType().GetProperties(); foreach (var property in props) { WithParameter(property.Name, getters[property.Name](parameters)); } return this; } /// <summary> /// Builder method - sets the command timeout /// </summary> /// <param name = "timeout"></param> public CommandBuilder WithTimeout(TimeSpan timeout) { Command.CommandTimeout = (int)timeout.TotalSeconds; return this; } /// <summary> /// Builder method - adds a name/value pair as parameter /// </summary> /// <param name = "name">the parameter name</param> /// <param name = "value">the parameter value</param> /// <returns>the same CommandBuilder instance</returns> public CommandBuilder WithParameter(string name, object? value) { IDbDataParameter p; if (Command.Parameters.Contains(name)) { p = Command.Parameters[name]; p.Value = DBNullHelper.ToDb(value); } else { p = Command.CreateParameter(); p.ParameterName = name; p.Value = DBNullHelper.ToDb(value); Command.Parameters.Add(p); } return this; } public CommandBuilder WithParameter<T>(T p) where T : IDbDataParameter { Command.Parameters.Add(p); return this; } public CommandBuilder InTransaction(DbTransaction tx) { Command.Transaction = tx; return this; } /// <summary> /// The raw IDbCommand instance /// </summary> public DbCommand Command { get; } /// <summary> /// Executes the query and returns the result as a list of dynamic objects. /// </summary> public IEnumerable<dynamic> AsEnumerable() { using var reader = AsReader(); while (reader.Read()) yield return reader.ToExpando(); } /// <summary> /// Executes the query and returns the result as a list of [T]. This method is slightly faster. /// than doing AsEnumerable().Select(selector). The selector is required to map objects as the /// underlying datareader is enumerated. /// </summary> /// <typeparam name = "T"></typeparam> /// <param name = "selector">mapping function that transforms a datarecord (wrapped as a dynamic object) to an instance of type [T]</param> public IEnumerable<T> AsEnumerable<T>(Func<dynamic, T> selector) => Select(selector); /// <summary> /// Executes the query and returns the result as a list of [T] using the 'case-insensitive, underscore-agnostic column name to property mapping convention.' /// </summary> /// <typeparam name = "T"></typeparam> public IEnumerable<T> AsEnumerable<T>() { using var reader = AsReader(); var setterMap = reader.GetSetterMap<T>(_config); while (reader.Read()) yield return reader.MapTo(setterMap); } // enables linq 'select' syntax public IEnumerable<T> Select<T>(Func<dynamic, T> selector) { using var reader = AsReader(); while (reader.Read()) yield return selector(Dynamic.From(reader)); } /// <summary> /// Executes the query and returns the result as a list of lists /// </summary> public IEnumerable<IReadOnlyCollection<dynamic>> AsMultiResultSet() { using var reader = AsReader(); do { var list = new Collection<dynamic>(); while (reader.Read()) list.Add(reader.ToExpando()); yield return list; } while (reader.NextResult()); } /// <summary> /// Executes the query and returns the result as a tuple of lists /// </summary> public (IReadOnlyCollection<T1>, IReadOnlyCollection<T2>) AsMultiResultSet<T1, T2>() { using var reader = AsReader(); return (GetResultSet<T1>(reader, _config, out _), GetResultSet<T2>(reader, _config, out _)); } /// <summary> /// Executes the query and returns the result as a tuple of lists /// </summary> public (IReadOnlyCollection<T1>, IReadOnlyCollection<T2>, IReadOnlyCollection<T3>) AsMultiResultSet<T1, T2, T3>() { using var reader = AsReader(); return (GetResultSet<T1>(reader, _config, out _), GetResultSet<T2>(reader, _config, out _), GetResultSet<T3>(reader, _config, out _)); } /// <summary> /// Executes the query and returns the result as a tuple of lists /// </summary> public (IReadOnlyCollection<T1>, IReadOnlyCollection<T2>, IReadOnlyCollection<T3>, IReadOnlyCollection<T4>) AsMultiResultSet<T1, T2, T3, T4>() { using var reader = AsReader(); return (GetResultSet<T1>(reader, _config, out _), GetResultSet<T2>(reader, _config, out _), GetResultSet<T3>(reader, _config, out _), GetResultSet<T4>(reader, _config, out _)); } /// <summary> /// Executes the query and returns the result as a tuple of lists /// </summary> public (IReadOnlyCollection<T1>, IReadOnlyCollection<T2>, IReadOnlyCollection<T3>, IReadOnlyCollection<T4>, IReadOnlyCollection<T5>) AsMultiResultSet<T1, T2, T3, T4, T5>() { using var reader = AsReader(); return (GetResultSet<T1>(reader, _config, out _), GetResultSet<T2>(reader, _config, out _), GetResultSet<T3>(reader, _config, out _), GetResultSet<T4>(reader, _config, out _), GetResultSet<T5>(reader, _config, out _)); } private static IReadOnlyCollection<T> GetResultSet<T>(IDataReader reader, DbConfig config, out bool moreResults) { var list = new List<T>(); var map = reader.GetSetterMap<T>(config); while (reader.Read()) list.Add(reader.MapTo(map)); moreResults = reader.NextResult(); return list; } /// <summary> /// Executes the command, returning the first column of the first result, converted to the type T /// </summary> /// <typeparam name = "T">return type</typeparam> public T? AsScalar<T>() => ConvertTo<T>.From(AsScalar()); public object AsScalar() => Execute.Scalar(); /// <summary> /// Executes the command as a SQL statement, returning the number of rows affected /// </summary> public int AsNonQuery() => Execute.NonQuery(); /// <summary> /// Executes the command as a datareader. Use this if you need best performance. /// </summary> public IDataReader AsReader() => Execute.Reader(); public T Single<T>() => AsEnumerable<T>().Single(); private Executor Execute => new(Command); /// <summary> /// Executes the command as a statement, returning the number of rows affected asynchronously /// This method is only supported if the underlying provider propertly implements async behaviour. /// </summary> public Task<int> AsNonQueryAsync() => ExecuteAsync.NonQuery(); /// <summary> /// Executes the command, returning the first column of the first result, converted to the type T asynchronously. /// This method is only supported if the underlying provider propertly implements async behaviour. /// </summary> /// <typeparam name = "T">return type</typeparam> public async Task<T?> AsScalarAsync<T>() { var result = await ExecuteAsync.Scalar().ConfigureAwait(false); return ConvertTo<T>.From(result); } /// <summary> /// Executes the query and returns the result as a list of dynamic objects asynchronously /// This method is only supported if the underlying provider propertly implements async behaviour. /// </summary> public async IAsyncEnumerable<dynamic> AsEnumerableAsync() { using var reader = await ExecuteAsync.Reader().ConfigureAwait(false); while (await reader.ReadAsync().ConfigureAwait(false)) yield return reader.ToExpando(); } /// <summary> /// Executes the query and returns the result as a list of [T] asynchronously /// This method is only supported if the underlying provider propertly implements async behaviour. /// </summary> /// <typeparam name = "T"></typeparam> /// <param name = "selector">mapping function that transforms a datarecord (wrapped as a dynamic object) to an instance of type [T]</param> public async IAsyncEnumerable<T> AsEnumerableAsync<T>(Func<dynamic, T> selector) { using var reader = await ExecuteAsync.Reader().ConfigureAwait(false); while (await reader.ReadAsync().ConfigureAwait(false)) { var d = Dynamic.From(reader); var item = selector(d); yield return item; } } /// <summary> /// Executes the query and returns the result as a list of [T] asynchronously /// This method is only supported if the underlying provider propertly implements async behaviour. /// </summary> /// <typeparam name = "T"></typeparam> /// <param name = "selector">mapping function that transforms a datarecord (wrapped as a dynamic object) to an instance of type [T]</param> public async IAsyncEnumerable<T> AsEnumerableAsync<T>() { using var reader = await ExecuteAsync.Reader().ConfigureAwait(false); var setterMap = reader.GetSetterMap<T>(_config); while (await reader.ReadAsync().ConfigureAwait(false)) yield return reader.MapTo(setterMap); } public ValueTask<T> SingleAsync<T>() => AsEnumerableAsync<T>().SingleAsync(); private AsyncExecutor ExecuteAsync => new(Command); } /// <summary> /// Class for runtime type conversion, including DBNull.Value to/from null. Supports reference types, /// value types and nullable value types /// </summary> /// <typeparam name = "T"></typeparam> public static class ConvertTo<T> { // ReSharper disable once StaticFieldInGenericType // clearly we *want* a static field for each instantiation of this generic class... /// <summary> /// The actual conversion method. Converts an object to any type using standard casting functionality, /// taking into account null/nullable types and avoiding DBNull issues. This method is set as a delegate /// at runtime (in the static constructor). /// </summary> public static readonly Func<object?, T?> From; static ConvertTo() { // Sets the From delegate, depending on whether T is a reference type, a nullable value type or a value type. From = CreateConvertFunction(typeof(T)); } private static Func<object?, T?> CreateConvertFunction(Type type) => type switch { Type t when !t.IsValueType => ConvertRefType, Type t when !t.IsNullableType() => ConvertValueType, Type t => CreateConvertNullableValueTypeFunc(t)}; private static Func<object?, T?> CreateConvertNullableValueTypeFunc(Type type) { var delegateType = typeof(Func<object?, T?>); var methodInfo = typeof(ConvertTo<T>).GetMethod("ConvertNullableValueType", BindingFlags.NonPublic | BindingFlags.Static); var genericMethodForElement = methodInfo.MakeGenericMethod(type.GetGenericArguments()[0]); return (Func<object?, T?>)genericMethodForElement.CreateDelegate(delegateType); } #pragma warning disable IDE0051 // Remove unused private members #pragma warning disable RCS1213 // Remove unused member declaration. private static TElem? ConvertNullableValueType<TElem>(object value) where TElem : struct => IsNull(value) ? default(TElem? ) : ConvertPrivate<TElem>(value); #pragma warning restore RCS1213 // Remove unused member declaration. #pragma warning restore IDE0051 // Remove unused private members private static T? ConvertRefType(object? value) => IsNull(value) ? default : ConvertPrivate<T>(value!); private static T ConvertValueType(object? value) { if (IsNull(value)) { throw new NullReferenceException("Value is DbNull"); } return ConvertPrivate<T>(value!); } private static TElem ConvertPrivate<TElem>(object value) => (TElem)(Convert.ChangeType(value, typeof(TElem))); } /// <summary> /// <para>Yet Another Data Access Layer</para> /// <para>usage: </para> /// <para>using (var db = new Db(connectionString, providerFactory)) {};</para> /// <para> /// from there it should be discoverable. /// inline SQL FTW! /// </para> /// </summary> public class Db : IDb { internal DbConfig Config { get; } internal IMappingConvention MappingConvention => Config.MappingConvention; private DbConnection _connection; private readonly bool _externalConnection; /// <summary> /// Instantiate Db with existing connection. The connection is only used for creating commands; /// it should be disposed by the caller when done. /// </summary> /// <param name = "connection">The existing connection</param> /// <param name = "config"></param> public Db(DbConnection connection, DbConfig config) { _connection = connection; _externalConnection = true; Config = config ?? DbConfig.Default; } /// <summary> /// Instantiate Db with connectionString and a custom IConnectionFactory /// </summary> /// <param name = "connectionString">the connection string</param> /// <param name = "providerFactory">the connection provider factory</param> public Db(string connectionString, DbProviderFactory providerFactory) : this(connectionString, DbConfig.FromProviderFactory(providerFactory), providerFactory) { } /// <summary> /// Instantiate Db with connectionString and a custom IConnectionFactory /// </summary> /// <param name = "connectionString">the connection string</param> /// <param name = "config"></param> /// <param name = "connectionFactory">the connection factory</param> internal Db(string connectionString, DbConfig config, DbProviderFactory connectionFactory) { Logger.Log("Db ctor"); _connection = connectionFactory.CreateConnection(); _connection.ConnectionString = connectionString; _externalConnection = false; Config = config; } public void Connect() { Logger.Log("Db connect"); if (_connection.State != ConnectionState.Open) _connection.Open(); } public void Disconnect() { Logger.Log("Db disconnect"); if (_connection.State != ConnectionState.Closed) _connection.Close(); } public async Task ConnectAsync() { Logger.Log("Db connect"); if (_connection.State != ConnectionState.Open) await _connection.OpenAsync().ConfigureAwait(false); } /// <summary> /// The actual IDbConnection (which will be open) /// </summary> public DbConnection Connection { get { Connect(); return _connection; } } public string ConnectionString => _connection.ConnectionString; public void Dispose() { Logger.Log("Db dispose"); if (_connection == null || _externalConnection) return; _connection.Dispose(); _connection = null !; } /// <summary> /// Create a SQL query command builder /// </summary> /// <param name = "sqlQuery"></param> /// <returns>a CommandBuilder instance</returns> public CommandBuilder Sql(string sqlQuery) => CreateCommand(CommandType.Text, sqlQuery); /// <summary> /// Create a Stored Procedure command builder /// </summary> /// <param name = "sprocName">name of the sproc</param> /// <returns>a CommandBuilder instance</returns> public CommandBuilder StoredProcedure(string sprocName) => CreateCommand(CommandType.StoredProcedure, sprocName); private CommandBuilder CreateCommand(CommandType commandType, string command) { var cmd = Connection.CreateCommand(); Config.PrepareCommand(cmd); return new CommandBuilder(cmd, Config).OfType(commandType).WithCommandText(command); } /// <summary> /// Create a SQL command and execute it immediately (non query) /// </summary> /// <param name = "command"></param> public int Execute(string command) => Sql(command).AsNonQuery(); } /// <summary> /// <para> /// The DbConfig class allows to configure database specific behaviour at runtime, without a direct /// dependency on the underlying ADO.Net provider. It does 2 things /// </para> /// <para> /// - provides a hook to configure a DbCommand in case some specific configuration is required. For example, /// Oracle requires the BindByName property to be set to true for named parameters to work. /// - Sets the way database naming conventions are mapped to .Net naming conventions. For example, in Oracle, /// database and column names are upper case and separated by underscores. Postgres defaults to lower case. /// This includes also the escape character that indicates parameter names in queries with named parameters. /// </para> /// </summary> public record DbConfig(Action<IDbCommand> PrepareCommand, IMappingConvention MappingConvention) { public static DbConfig FromProviderName(string providerName) => providerName switch { string s when s.StartsWith("Oracle") => Oracle, string s when s.StartsWith("Npgsql") => PostGreSQL, string s when s.StartsWith("IBM") => DB2, _ => Default }; public static DbConfig FromProviderFactory(DbProviderFactory factory) => FromProviderName(factory.GetType().FullName); // By default, the Oracle driver does not support binding parameters by name; // one has to set the BindByName property on the OracleDbCommand. // Mapping: // Oracle convention is to work with UPPERCASE_AND_UNDERSCORE instead of BookTitleCase public static readonly DbConfig Oracle = new(SetBindByName, new MappingConvention(StringExtensions.ToUpperWithUnderscores, StringExtensions.ToPascalCase, ':')); public static readonly DbConfig DB2 = new(NoOp, new MappingConvention(StringExtensions.ToUpperWithUnderscores, StringExtensions.ToPascalCase, '@')); public static readonly DbConfig PostGreSQL = new(NoOp, new MappingConvention(StringExtensions.ToLowerWithUnderscores, StringExtensions.ToPascalCase, '@')); public static readonly DbConfig Default = new(NoOp, new MappingConvention(StringExtensions.NoOp, StringExtensions.NoOp, '@')); private static void SetBindByName(dynamic c) => c.BindByName = true; private static void NoOp(dynamic c) { } } public static class DBNullHelper { public static bool IsNull(object? o) => o == null || DBNull.Value.Equals(o); public static object? FromDb(object? o) => IsNull(o) ? null : o; public static object? ToDb(object? o) => IsNull(o) ? DBNull.Value : o; } internal static class Dynamic { public static dynamic From(DataRow row) => From(row, (r, s) => r[s]); public static dynamic From(IDataRecord record) => From(record, (r, s) => r[s]); public static dynamic From<TValue>(IDictionary<string, TValue> dictionary) => From(dictionary, (d, s) => d[s]); private static dynamic From<T>(T item, Func<T, string, object?> getter) => new DynamicIndexer<T>(item, getter); private class DynamicIndexer<T> : DynamicObject { private readonly T _item; private readonly Func<T, string, object?> _getter; public DynamicIndexer(T item, Func<T, string, object?> getter) { _item = item; _getter = getter; } public sealed override bool TryGetIndex(GetIndexBinder b, object[] i, out object? r) => ByMemberName(out r, (string)i[0]); public sealed override bool TryGetMember(GetMemberBinder b, out object? r) => ByMemberName(out r, b.Name); private bool ByMemberName(out object? result, string memberName) { var value = _getter(_item, memberName); result = DBNullHelper.FromDb(value); return true; } } } public partial class CommandBuilder { private class Executor { private readonly DbCommand _command; public Executor(DbCommand command) { _command = command; } /// <summary> /// executes the query as a datareader /// </summary> public DbDataReader Reader() => Prepare().ExecuteReader(); /// <summary> /// Executes the command, returning the first column of the first result as a scalar value /// </summary> public object Scalar() => Prepare().ExecuteScalar(); /// <summary> /// Executes the command as a SQL statement, returning the number of rows affected /// </summary> public int NonQuery() => Prepare().ExecuteNonQuery(); private DbCommand Prepare() { Logger.LogCommand(_command); if (_command.Connection.State == ConnectionState.Closed) _command.Connection.Open(); return _command; } } } internal sealed class FastReflection<T> { private FastReflection() { } private static readonly Type Type = typeof(FastReflection<T>); public static FastReflection<T> Instance = new(); public IReadOnlyDictionary<string, Action<T, object?>> GetSettersForType() => _setters.GetOrAdd(typeof(T), d => d.GetProperties().Where(p => p.SetMethod != null).ToDictionary(p => p.Name, GetSetDelegate)); private readonly ConcurrentDictionary<Type, IReadOnlyDictionary<string, Action<T, object?>>> _setters = new(); private static Action<T, object?> GetSetDelegate(PropertyInfo p) { var method = p.GetSetMethod(); var genericHelper = Type.GetMethod(nameof(CreateSetterDelegateHelper), BindingFlags.Static | BindingFlags.NonPublic); var constructedHelper = genericHelper.MakeGenericMethod(typeof(T), method.GetParameters()[0].ParameterType); return (Action<T, object?>)constructedHelper.Invoke(null, new object[]{method}); } // ReSharper disable once UnusedMethodReturnValue.Local // ReSharper disable once UnusedMember.Local private static Action<TTarget, object> CreateSetterDelegateHelper<TTarget, TProperty>(MethodInfo method) { var action = (Action<TTarget, TProperty?>)method.CreateDelegate(typeof(Action<TTarget, TProperty>)); return (target, param) => action(target, ConvertTo<TProperty>.From(param)); } public IReadOnlyDictionary<string, Func<T, object?>> GetGettersForType() => _getters.GetOrAdd(typeof(T), t => t.GetProperties().Where(p => p.GetMethod != null).ToDictionary(p => p.Name, GetGetDelegate)); private readonly ConcurrentDictionary<Type, IReadOnlyDictionary<string, Func<T, object?>>> _getters = new(); private static Func<T, object?> GetGetDelegate(PropertyInfo p) { var method = p.GetGetMethod(); var genericHelper = Type.GetMethod(nameof(CreateGetterDelegateHelper), BindingFlags.Static | BindingFlags.NonPublic); var constructedHelper = genericHelper.MakeGenericMethod(typeof(T), method.ReturnType); return (Func<T, object?>)constructedHelper.Invoke(null, new object[]{method}); } // ReSharper disable once UnusedMethodReturnValue.Local // ReSharper disable once UnusedMember.Local private static Func<TTarget, object?> CreateGetterDelegateHelper<TTarget, TProperty>(MethodInfo method) { var func = (Func<TTarget, TProperty>)method.CreateDelegate(typeof(Func<TTarget, TProperty>)); return target => ConvertTo<TProperty>.From(func(target)); } } public interface IDb : IDisposable { /// <summary> /// Open a connection to the database. Not required. /// </summary> void Connect(); /// <summary> /// Disconnect from the database. /// </summary> void Disconnect(); /// <summary> /// Open a connection to the database. Not required. /// </summary> Task ConnectAsync(); /// <summary> /// The actual DbConnection (which will be open) /// </summary> DbConnection Connection { get; } /// <summary> /// The ADO.Net connection string /// </summary> string ConnectionString { get; } /// <summary> /// Create a SQL query command builder /// </summary> /// <param name = "sqlQuery"></param> /// <returns>a CommandBuilder instance</returns> CommandBuilder Sql(string sqlQuery); /// <summary> /// Create a Stored Procedure command /// </summary> /// <param name = "sprocName">name of the stored procedure</param> /// <returns>a CommandBuilder instance</returns> CommandBuilder StoredProcedure(string sprocName); /// <summary> /// Create a SQL command and execute it immediately (non query) /// </summary> /// <param name = "command"></param> int Execute(string command); } /// <summary> /// To enable logging, set the Log property of the Logger class /// </summary> public static class Logger { public static Action<string> Log = s => { }; internal static void LogCommand(IDbCommand command) { Log(command.CommandText); foreach (IDbDataParameter p in command.Parameters) { Log($"{p.ParameterName} = {p.Value}"); } } } internal static class DataRecordExtensions { internal record struct Setter<T>(int FieldIndex, Action<T, object?> SetValue); internal class SetterMap<T> : List<Setter<T>> { } internal static SetterMap<T> GetSetterMap<T>(this IDataReader reader, DbConfig config) { var map = new SetterMap<T>(); var convention = config.MappingConvention; var setters = FastReflection<T>.Instance.GetSettersForType(); for (var i = 0; i < reader.FieldCount; i++) { var columnName = convention.FromDb(reader.GetName(i)); if (setters.TryGetValue(columnName, out var setter)) { map.Add(new Setter<T>(i, setter)); } } return map; } internal static T MapTo<T>(this IDataRecord record, SetterMap<T> setterMap) { var result = Activator.CreateInstance<T>(); foreach (var setter in setterMap) { var val = DBNullHelper.FromDb(record.GetValue(setter.FieldIndex)); setter.SetValue(result, val); } return result; } /// <summary> /// Convert a datarecord into a dynamic object, so that properties can be simply accessed /// using standard C# syntax. /// </summary> /// <param name = "rdr">the data record</param> /// <returns>A dynamic object with fields corresponding to the database columns</returns> internal static dynamic ToExpando(this IDataRecord rdr) => Dynamic.From(rdr.NameValues().ToDictionary(p => p.name, p => p.value)); internal static IEnumerable<(string name, object? value)> NameValues(this IDataRecord record) { for (var i = 0; i < record.FieldCount; i++) yield return (record.GetName(i), record[i]); } /// <summary> /// Get a value from an IDataRecord by column name. This method supports all types, /// as long as the DbType is convertible to the CLR Type passed as a generic argument. /// Also handles conversion from DbNull to null, including nullable types. /// </summary> public static TResult? Get<TResult>(this IDataRecord record, string name) => record.Get<TResult>(record.GetOrdinal(name)); /// <summary> /// Get a value from an IDataRecord by index. This method supports all types, /// as long as the DbType is convertible to the CLR Type passed as a generic argument. /// Also handles conversion from DbNull to null, including nullable types. /// </summary> public static TResult? Get<TResult>(this IDataRecord record, int c) => ConvertTo<TResult>.From(record[c]); } internal static class DataTableExtensions { public static IEnumerable<dynamic> AsEnumerable(this DataTable dataTable) => dataTable.Rows.OfType<DataRow>().Select(Dynamic.From); public static IEnumerable<T> Select<T>(this DataTable dt, Func<dynamic, T> selector) => dt.AsEnumerable().Select(selector); public static IEnumerable<dynamic> Where(this DataTable dt, Func<dynamic, bool> predicate) => dt.AsEnumerable().Where(predicate); /// <summary> /// Executes the query (using datareader) and fills a datatable /// </summary> public static DataTable AsDataTable(this CommandBuilder commandBuilder) { using var reader = commandBuilder.AsReader(); var tb = new DataTable(); tb.Load(reader); return tb; } public static DataTable ToDataTable<T>(this IEnumerable<T> items) { var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); var table = new DataTable(typeof(T).Name); foreach (var prop in props) { var propType = prop.PropertyType.GetUnderlyingType(); table.Columns.Add(prop.Name, propType); } var values = new object[props.Length]; foreach (var item in items) { for (var i = 0; i < props.Length; i++) values[i] = props[i].GetValue(item, null); table.Rows.Add(values); } return table; } } internal static class EnumerableExtensions { /// <summary> /// Adapter from IEnumerable[T] to IDataReader /// </summary> public static DbDataReader AsDataReader<T>(this IEnumerable<T> input) => new EnumerableDataReaderImpl<T>(input); private class EnumerableDataReaderImpl<T> : DbDataReader { private readonly IEnumerable<T> _list; private readonly IEnumerator<T> _enumerator; private bool _disposed; private static readonly PropertyInfo[] Properties; private static readonly IReadOnlyDictionary<string, int> PropertyIndexesByName; private static readonly IReadOnlyDictionary<string, Func<T, object?>> Getters; static EnumerableDataReaderImpl() { var propertyInfos = typeof(T).GetProperties(); Properties = propertyInfos.ToArray(); Getters = FastReflection<T>.Instance.GetGettersForType(); PropertyIndexesByName = Properties.Select((p, i) => (p, i)).ToDictionary(x => x.p.Name, x => x.i); } public EnumerableDataReaderImpl(IEnumerable<T> list) { _list = list; _enumerator = _list.GetEnumerator(); } public override string GetName(int i) => Properties[i].Name; public override string GetDataTypeName(int i) => Properties[i].PropertyType.Name; public override IEnumerator GetEnumerator() => _enumerator; public override Type GetFieldType(int i) => Properties[i].PropertyType; public override object? GetValue(int i) => DBNullHelper.ToDb(Getters[Properties[i].Name](_enumerator.Current)); public override int GetValues(object? [] values) { var length = Math.Min(values.Length, Properties.Length); for (int i = 0; i < length; i++) { values[i] = GetValue(i); } return length; } public override int GetOrdinal(string name) => PropertyIndexesByName[name]; public override bool GetBoolean(int i) => this.Get<bool>(i); public override byte GetByte(int i) => this.Get<byte>(i); public override long GetBytes(int i, long dataOffset, byte[] buffer, int bufferoffset, int length) => Get(i, dataOffset, buffer, bufferoffset, length); public override char GetChar(int i) => this.Get<char>(i); public override long GetChars(int i, long dataOffset, char[] buffer, int bufferoffset, int length) => Get(i, dataOffset, buffer, bufferoffset, length); public override Guid GetGuid(int i) => this.Get<Guid>(i); public override short GetInt16(int i) => this.Get<short>(i); public override int GetInt32(int i) => this.Get<int>(i); public override long GetInt64(int i) => this.Get<long>(i); public override float GetFloat(int i) => this.Get<float>(i); public override double GetDouble(int i) => this.Get<double>(i); public override string? GetString(int i) => this.Get<string>(i); public override decimal GetDecimal(int i) => this.Get<decimal>(i); public override DateTime GetDateTime(int i) => this.Get<DateTime>(i); private long Get<TElem>(int i, long dataOffset, TElem[] buffer, int bufferoffset, int length) { var data = this.Get<TElem[]>(i); if (data is null) return 0; var maxLength = Math.Min((long)buffer.Length - bufferoffset, length); maxLength = Math.Min(data.Length - dataOffset, maxLength); Array.Copy(data, (int)dataOffset, buffer, bufferoffset, length); return maxLength; } public override bool IsDBNull(int i) => DBNull.Value.Equals(GetValue(i)); public override int FieldCount => Properties.Length; public override bool HasRows => _list.Any(); public override object? this[int i] => GetValue(i); public override object? this[string name] => GetValue(GetOrdinal(name)); public override void Close() => Dispose(); public override DataTable GetSchemaTable() => ( from x in EnumerableDataReaderImpl<T>.Properties.Select((p, i) => (p, i))let p = x.p select new { ColumnName = p.Name, ColumnOrdinal = x.i, ColumnSize = int.MaxValue, // must be filled in and large enough for ToDataTable AllowDBNull = p.PropertyType.IsNullableType() || !p.PropertyType.IsValueType, // assumes string nullable DataType = p.PropertyType.GetUnderlyingType(), } ).ToDataTable(); public override bool NextResult() { _enumerator?.Dispose(); return false; } public override bool Read() => _enumerator.MoveNext(); public override int Depth => 0; public override bool IsClosed => _disposed; public override int RecordsAffected => 0; protected override void Dispose(bool disposing) => _disposed = true; } } internal static class StringExtensions { public static string ToUpperRemoveSpecialChars(this string str) => string.IsNullOrEmpty(str) ? str : Regex.Replace(str, @"([^\w]|_)", "").ToUpperInvariant(); public static string ToPascalCase(this string? str) => str?.Aggregate((sb: new StringBuilder(), transform: (Func<char, char>)char.ToUpper), (t, c) => char.IsLetterOrDigit(c) ? (t.sb.Append(t.transform(c)), char.ToLower) : (t.sb, char.ToUpper)).sb.ToString() ?? string.Empty; public static string PascalCaseToSentence(this string source) => string.IsNullOrEmpty(source) ? source : string.Join(" ", SplitUpperCase(source)); public static string ToUpperWithUnderscores(this string source) => string.Join("_", SplitUpperCase(source).Select(s => s.ToUpperInvariant())); public static string ToLowerWithUnderscores(this string source) => string.Join("_", SplitUpperCase(source).Select(s => s.ToLowerInvariant())); public static string NoOp(this string source) => source; private static IEnumerable<string> SplitUpperCase(string source) { var wordStart = 0; var letters = source.ToCharArray(); var previous = char.MinValue; for (var i = 1; i < letters.Length; i++) { if (char.IsUpper(letters[i]) && !char.IsWhiteSpace(previous)) { yield return new string (letters, wordStart, i - wordStart); wordStart = i; } previous = letters[i]; } yield return new string (letters, wordStart, letters.Length - wordStart); } } internal static class TypeExtensions { public static bool HasCustomAttribute<TAttribute>(this MemberInfo t, Func<TAttribute, bool> whereClause) => t.GetCustomAttributes(false).OfType<TAttribute>().Any(whereClause); public static Type GetUnderlyingType(this Type type) => type.IsNullableType() ? Nullable.GetUnderlyingType(type) : type; public static bool IsNullableType(this Type type) => type.IsGenericType && !type.IsGenericTypeDefinition && typeof(Nullable<>) == type.GetGenericTypeDefinition(); } public interface IMappingConvention { string FromDb(string s); string ToDb(string s); string Parameter(string s); } } namespace Net.Code.ADONet.Extensions.Mapping { public static class DbExtensions { /// <summary> /// Please note: this is an experimental feature, API may change or be removed in future versions" /// </summary> public static void Insert<T>(this IDb db, IEnumerable<T> items) { var query = Query<T>.Create(((Db)db).MappingConvention).Insert; Do(db, items, query); } /// <summary> /// Please note: this is an experimental feature, API may change or be removed in future versions" /// </summary> public static async Task InsertAsync<T>(this IDb db, IEnumerable<T> items) { var query = Query<T>.Create(((Db)db).MappingConvention).Insert; await DoAsync(db, items, query).ConfigureAwait(false); } /// <summary> /// Please note: this is an experimental feature, API may change or be removed in future versions" /// </summary> public static void Update<T>(this IDb db, IEnumerable<T> items) { var query = Query<T>.Create(((Db)db).MappingConvention).Update; Do(db, items, query); } /// <summary> /// Please note: this is an experimental feature, API may change or be removed in future versions" /// </summary> public static async Task UpdateAsync<T>(this IDb db, IEnumerable<T> items) { var query = Query<T>.Create(((Db)db).MappingConvention).Update; await DoAsync(db, items, query).ConfigureAwait(false); } /// <summary> /// Please note: this is an experimental feature, API may change or be removed in future versions" /// </summary> public static void Delete<T>(this IDb db, IEnumerable<T> items) { var query = Query<T>.Create(((Db)db).MappingConvention).Delete; Do(db, items, query); } /// <summary> /// Please note: this is an experimental feature, API may change or be removed in future versions" /// </summary> public static async Task DeleteAsync<T>(this IDb db, IEnumerable<T> items) { var query = Query<T>.Create(((Db)db).MappingConvention).Delete; await DoAsync(db, items, query).ConfigureAwait(false); } private static void Do<T>(IDb db, IEnumerable<T> items, string query) { var commandBuilder = db.Sql(query); foreach (var item in items) { commandBuilder.WithParameters(item).AsNonQuery(); } } private static async Task DoAsync<T>(IDb db, IEnumerable<T> items, string query) { var commandBuilder = db.Sql(query); foreach (var item in items) { await commandBuilder.WithParameters(item).AsNonQueryAsync().ConfigureAwait(false); } } } public interface IQuery { string Insert { get; } string Delete { get; } string Update { get; } string Select { get; } string SelectAll { get; } string Count { get; } } internal record struct MappingConvention(Func<string, string> ToDb, Func<string, string> FromDb, char Escape) : IMappingConvention { /// <summary> /// Maps column names to property names based on exact, case sensitive match. Database artefacts are named exactly /// like the .Net objects. /// </summary> public static readonly IMappingConvention Default = new MappingConvention(NoOp, NoOp, '@'); static string NoOp(string s) => s; public string Parameter(string s) => $"{Escape}{s}"; string IMappingConvention.FromDb(string s) => FromDb(s); string IMappingConvention.ToDb(string s) => ToDb(s); } internal sealed class Query<T> : IQuery { // ReSharper disable StaticMemberInGenericType private static readonly PropertyInfo[] Properties; private static readonly PropertyInfo[] KeyProperties; private static readonly PropertyInfo[] DbGenerated; // ReSharper restore StaticMemberInGenericType internal static IQuery Create(IMappingConvention convention) => new Query<T>(convention); static Query() { Properties = typeof(T).GetProperties(); KeyProperties = Properties.Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))).ToArray(); if (KeyProperties.Length == 0) KeyProperties = Properties.Where(p => p.Name.Equals("Id", StringComparison.OrdinalIgnoreCase)).ToArray(); if (KeyProperties.Length == 0) KeyProperties = Properties.Where(p => p.Name.Equals($"{typeof(T).Name}Id", StringComparison.OrdinalIgnoreCase)).ToArray(); DbGenerated = KeyProperties.Where(p => p.HasCustomAttribute<DatabaseGeneratedAttribute>(a => a.DatabaseGeneratedOption != DatabaseGeneratedOption.None)).ToArray(); } private Query(IMappingConvention convention) { var allPropertyNames = Properties.Select(p => convention.ToDb(p.Name)).ToArray(); var insertPropertyNames = Properties.Except(DbGenerated).Select(p => p.Name).ToArray(); var keyPropertyNames = KeyProperties.Select(p => p.Name).ToArray(); var nonKeyProperties = Properties.Except(KeyProperties).ToArray(); var nonKeyPropertyNames = nonKeyProperties.Select(p => p.Name).ToArray(); string assign(string s) => $"{convention.ToDb(s)} = {convention.Parameter(s)}"; var insertColumns = string.Join(", ", insertPropertyNames.Select(convention.ToDb)); var insertValues = string.Join(", ", insertPropertyNames.Select(s => $"{convention.Parameter(s)}")); var whereClause = string.Join(" AND ", keyPropertyNames.Select(assign)); var updateColumns = string.Join(", ", nonKeyPropertyNames.Select(assign)); var allColumns = string.Join(", ", allPropertyNames); var tableName = convention.ToDb(typeof(T).Name); Insert = $"INSERT INTO {tableName} ({insertColumns}) VALUES ({insertValues})"; Delete = $"DELETE FROM {tableName} WHERE {whereClause}"; Update = $"UPDATE {tableName} SET {updateColumns} WHERE {whereClause}"; Select = $"SELECT {allColumns} FROM {tableName} WHERE {whereClause}"; SelectAll = $"SELECT {allColumns} FROM {tableName}"; Count = $"SELECT COUNT(*) FROM {tableName}"; } public string Insert { get; } public string Delete { get; } public string Update { get; } public string Select { get; } public string SelectAll { get; } public string Count { get; } } } namespace Net.Code.ADONet.Extensions.SqlClient { public static class DbExtensions { /// <summary> /// Adds a table-valued parameter. Only supported on SQL Server (System.Data.SqlClient) /// </summary> /// <typeparam name = "T"></typeparam> /// <param name = "commandBuilder"></param> /// <param name = "name">parameter name</param> /// <param name = "values">list of values</param> /// <param name = "udtTypeName">name of the user-defined table type</param> public static CommandBuilder WithParameter<T>(this CommandBuilder commandBuilder, string name, IEnumerable<T> values, string udtTypeName) { var dataTable = values.ToDataTable(); var p = new SqlParameter(name, SqlDbType.Structured) { TypeName = udtTypeName, Value = dataTable }; return commandBuilder.WithParameter(p); } /// <summary> /// Assumes one to one mapping between /// - tablename and typename /// - property names and column names /// </summary> /// <typeparam name = "T"></typeparam> /// <param name = "db"></param> /// <param name = "items"></param> public static void BulkCopy<T>(this IDb db, IEnumerable<T> items) { using var bcp = new SqlBulkCopy(db.ConnectionString) { DestinationTableName = typeof(T).Name }; // by default, SqlBulkCopy assumes columns in the database // are in same order as the columns of the source data reader // => add explicit column mappings by name foreach (var p in typeof(T).GetProperties()) { bcp.ColumnMappings.Add(p.Name, p.Name); } var datareader = items.AsDataReader(); bcp.WriteToServer(datareader); } } } namespace System.Runtime.CompilerServices { internal class IsExternalInit { } }
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using MsgPack.Serialization; namespace abelkhan { /*this enum code is codegen by abelkhan codegen for c#*/ public enum em_test3{ enum_test3 = 1 } /*this struct code is codegen by abelkhan codegen for c#*/ public class test1 { public Int32 argv1; public string argv2 = "123"; public float argv3; public double argv4; public static Hashtable test1_to_protcol(test1 _struct){ var _protocol = new Hashtable(); _protocol.Add("argv1", _struct.argv1); _protocol.Add("argv2", _struct.argv2); _protocol.Add("argv3", _struct.argv3); _protocol.Add("argv4", _struct.argv4); return _protocol; } public static test1 protcol_to_test1(Hashtable _protocol){ var _structc501822b_22a8_37ff_91a9_9545f4689a3d = new test1(); foreach(DictionaryEntry i in _protocol){ if ((string)i.Key == "argv1"){ _structc501822b_22a8_37ff_91a9_9545f4689a3d.argv1 = (Int32)i.Value; } else if ((string)i.Key == "argv2"){ _structc501822b_22a8_37ff_91a9_9545f4689a3d.argv2 = (string)i.Value; } else if ((string)i.Key == "argv3"){ _structc501822b_22a8_37ff_91a9_9545f4689a3d.argv3 = (float)i.Value; } else if ((string)i.Key == "argv4"){ _structc501822b_22a8_37ff_91a9_9545f4689a3d.argv4 = (double)i.Value; } } return _structc501822b_22a8_37ff_91a9_9545f4689a3d; } } public class test2 { public Int32 argv1 = 0; public test1 argv2; public byte[] bytel = new byte[3]{1,1,9}; public em_test3 t = em_test3.enum_test3; public static Hashtable test2_to_protcol(test2 _struct){ var _protocol = new Hashtable(); _protocol.Add("argv1", _struct.argv1); _protocol.Add("argv2", test1.test1_to_protcol(_struct.argv2)); _protocol.Add("bytel", _struct.bytel); _protocol.Add("t", _struct.t); return _protocol; } public static test2 protcol_to_test2(Hashtable _protocol){ var _structf1917643_06b2_3e6d_ab77_0a5044067d0a = new test2(); foreach(DictionaryEntry i in _protocol){ if ((string)i.Key == "argv1"){ _structf1917643_06b2_3e6d_ab77_0a5044067d0a.argv1 = (Int32)i.Value; } else if ((string)i.Key == "argv2"){ _structf1917643_06b2_3e6d_ab77_0a5044067d0a.argv2 = test1.protcol_to_test1(i.Value); } else if ((string)i.Key == "bytel"){ _structf1917643_06b2_3e6d_ab77_0a5044067d0a.bytel = (byte[])i.Value; } else if ((string)i.Key == "t"){ _structf1917643_06b2_3e6d_ab77_0a5044067d0a.t = (em_test3)i.Value; } } return _structf1917643_06b2_3e6d_ab77_0a5044067d0a; } } /*this caller code is codegen by abelkhan codegen for c#*/ public class test_test3_cb { private UInt64 cb_uuid; private test_rsp_cb module_rsp_cb; public test_test3_cb(UInt64 _cb_uuid, test_rsp_cb _module_rsp_cb) { cb_uuid = _cb_uuid; module_rsp_cb = _module_rsp_cb; } public event Action<test1, Int32> on_test3_cb; public event Action<test1, byte[]> on_test3_err; public event Action on_test3_timeout; public test_test3_cb callBack(Action<test1, Int32> cb, Action<test1, byte[]> err) { on_test3_cb += cb; on_test3_err += err; return this; } public void timeout(UInt64 tick, Action timeout_cb) { TinyTimer.add_timer(tick, ()=>{ module_rsp_cb.test3_timeout(cb_uuid); }); on_test3_timeout += timeout_cb; } public void call_cb(test1 t1, Int32 i) { if (on_test3_cb != null) { on_test3_cb(t1, i); } } public void call_err(test1 err, byte[] bytearray) { if (on_test3_err != null) { on_test3_err(err, bytearray); } } public void call_timeout() { if (on_test3_timeout != null) { on_test3_timeout(); } } } /*this cb code is codegen by abelkhan for c#*/ public class test_rsp_cb : abelkhan.Imodule { public Dictionary<UInt64, test_test3_cb> map_test3; public test_rsp_cb(abelkhan.modulemng modules) : base("test_rsp_cb") { modules.reg_module(this); map_test3 = new Dictionary<UInt64, test_test3_cb>(); reg_method("test3_rsp", test3_rsp); reg_method("test3_err", test3_err); } public void test3_rsp(ArrayList inArray){ var uuid = (UInt64)inArray[0]; var _t1 = test1.protcol_to_test1((Hashtable)inArray[1]); var _i = (Int32)inArray[2]; var rsp = try_get_and_del_test3_cb(uuid); if (rsp != null) { rsp.call_cb(_t1, _i); } } public void test3_err(ArrayList inArray){ var uuid = (UInt64)inArray[0]; var _err = test1.protcol_to_test1((Hashtable)inArray[1]); var _bytearray = (byte[])inArray[2]; var rsp = try_get_and_del_test3_cb(uuid); if (rsp != null) { rsp.call_err(_err, _bytearray); } } public void test3_timeout(UInt64 cb_uuid){ var rsp = try_get_and_del_test3_cb(cb_uuid); if (rsp != null){ rsp.call_timeout(); } } private test_test3_cb try_get_and_del_test3_cb(UInt64 uuid){ lock(map_test3) { var rsp = map_test3[uuid]; map_test3.Remove(uuid); return rsp; } } } public class test_caller : abelkhan.Icaller { public static test_rsp_cb rsp_cb_test_handle = null; private Int64 uuid_45a113ac_c7f2_30b0_90a5_a399ab912716 = (Int64)RandomUUID.random(); public test_caller(abelkhan.Ichannel _ch, abelkhan.modulemng modules) : base("test", _ch) { if (rsp_cb_test_handle == null) { rsp_cb_test_handle = new test_rsp_cb(modules); } } public test_test3_cb test3(test2 t2, em_test3 e = em_test3.enum_test3, string str = "qianqians"){ Interlocked.Increment(ref uuid_45a113ac_c7f2_30b0_90a5_a399ab912716); var uuid_20ca53af_d04c_58a2_a8b3_d02b9e414e80 = (UInt64)uuid_45a113ac_c7f2_30b0_90a5_a399ab912716; var _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7 = new ArrayList(); _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7.Add(uuid_20ca53af_d04c_58a2_a8b3_d02b9e414e80); _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7.Add(test2.test2_to_protcol(t2)); _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7.Add(e); _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7.Add(str); call_module_method("test3", _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7); var cb_test3_obj = new test_test3_cb(uuid_20ca53af_d04c_58a2_a8b3_d02b9e414e80, rsp_cb_test_handle); rsp_cb_test_handle.map_test3.Add(uuid_20ca53af_d04c_58a2_a8b3_d02b9e414e80, cb_test3_obj); return cb_test3_obj; } public void test4(List<test2> argv, float num = (float)0.110){ var _argv_fe584e24_96c8_3d2d_8b39_f1cc6a877f72 = new ArrayList(); var _array_80252816_2442_30bc_bd5c_59666cae8a23 = new ArrayList(); foreach(var v_264317e3_c4ab_53c4_a9a0_63d0058d8148 in argv){ _array_80252816_2442_30bc_bd5c_59666cae8a23.Add(test2.test2_to_protcol(v_264317e3_c4ab_53c4_a9a0_63d0058d8148)); } _argv_fe584e24_96c8_3d2d_8b39_f1cc6a877f72.Add(_array_80252816_2442_30bc_bd5c_59666cae8a23); _argv_fe584e24_96c8_3d2d_8b39_f1cc6a877f72.Add(num); call_module_method("test4", _argv_fe584e24_96c8_3d2d_8b39_f1cc6a877f72); } } /*this module code is codegen by abelkhan codegen for c#*/ public class test_test3_rsp : abelkhan.Response { private UInt64 uuid_77eeaa2a_8150_3cce_bfa0_0b16e18637bd; public test_test3_rsp(abelkhan.Ichannel _ch, UInt64 _uuid) : base("test_rsp_cb", _ch) { uuid_77eeaa2a_8150_3cce_bfa0_0b16e18637bd = _uuid; } public void rsp(test1 t1_ff418b5a_70ba_3756_afdf_1e2b6bdbef8c, Int32 i_72987bfb_ad8a_309a_a6ba_f222ad17c387 = 110){ var _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7 = new ArrayList(); _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7.Add(uuid_77eeaa2a_8150_3cce_bfa0_0b16e18637bd); _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7.Add(test1.test1_to_protcol(t1_ff418b5a_70ba_3756_afdf_1e2b6bdbef8c)); _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7.Add(i_72987bfb_ad8a_309a_a6ba_f222ad17c387); call_module_method("test3_rsp", _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7); } public void err(test1 err_ad2710a2_3dd2_3a8f_a4c8_a7ebbe1df696, byte[] bytearray_f6580f73_3817_3337_ac7a_6f0e34690ee8 = new byte[3]{1,1,0}){ var _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7 = new ArrayList(); _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7.Add(uuid_77eeaa2a_8150_3cce_bfa0_0b16e18637bd); _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7.Add(test1.test1_to_protcol(err_ad2710a2_3dd2_3a8f_a4c8_a7ebbe1df696)); _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7.Add(bytearray_f6580f73_3817_3337_ac7a_6f0e34690ee8); call_module_method("test3_err", _argv_bf7f1e5a_6b28_310c_8f9e_f815dbd56fb7); } } public class test_module : abelkhan.Imodule { private abelkhan.modulemng modules; public test_module(abelkhan.modulemng _modules) : base("test") { modules = _modules; modules.reg_module(this); reg_method("test3", test3); reg_method("test4", test4); } public event Action<test2, em_test3, string> on_test3; public void test3(ArrayList inArray){ var _cb_uuid = (UInt64)inArray[0]; var _t2 = test2.protcol_to_test2((Hashtable)inArray[1]); var _e = (em_test3)inArray[2]; var _str = (string)inArray[3]; rsp = new test_test3_rsp(current_ch, _cb_uuid); if (on_test3 != null){ on_test3(_t2, _e, _str); } rsp = null; } public event Action<List<test2>, float> on_test4; public void test4(ArrayList inArray){ var _argv = new List<test2>(); foreach(var v_51e4d59a_5357_5634_9bc1_e9c2e0aa9ab0 in (ArrayList)inArray[0]){ _argv.Add(test2.protcol_to_test2((Hashtable)v_51e4d59a_5357_5634_9bc1_e9c2e0aa9ab0)); } var _num = (float)inArray[1]; if (on_test4 != null){ on_test4(_argv, _num); } } } }
//------------------------------------------------------------------------------ // <copyright file="MultipartContentParser.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * Multipart content parser. * * Copyright (c) 1998 Microsoft Corporation */ namespace System.Web { using System.Text; using System.Collections; using System.Globalization; using System.Web.Util; /* * Element of the multipart content */ internal sealed class MultipartContentElement { private String _name; private String _filename; private String _contentType; private HttpRawUploadedContent _data; private int _offset; private int _length; internal MultipartContentElement(String name, String filename, String contentType, HttpRawUploadedContent data, int offset, int length) { _name = name; _filename = filename; _contentType = contentType; _data = data; _offset = offset; _length = length; } internal bool IsFile { get { return(_filename != null);} } internal bool IsFormItem { get { return(_filename == null);} } internal String Name { get { return _name;} } internal HttpPostedFile GetAsPostedFile() { return new HttpPostedFile( _filename, _contentType, new HttpInputStream(_data, _offset, _length)); } internal String GetAsString(Encoding encoding) { if (_length > 0) { return encoding.GetString(_data.GetAsByteArray(_offset, _length)); } else { return String.Empty; } } } /* * Multipart content parser. Split content into elements. */ internal sealed class HttpMultipartContentTemplateParser { private HttpRawUploadedContent _data; private int _length; private int _pos; private ArrayList _elements = new ArrayList(); // currently parsed line private int _lineStart = -1; private int _lineLength = -1; // last boundary has extra -- private bool _lastBoundaryFound; // part separator private byte[] _boundary; // current header values private String _partName; private String _partFilename; private String _partContentType; // current part's content data private int _partDataStart = -1; private int _partDataLength = -1; // encoding private Encoding _encoding; private HttpMultipartContentTemplateParser(HttpRawUploadedContent data, int length, byte[] boundary, Encoding encoding) { _data = data; _length = length; _boundary = boundary; _encoding = encoding; } private bool AtEndOfData() { return(_pos >= _length || _lastBoundaryFound); } private bool GetNextLine() { int i = _pos; _lineStart = -1; while (i < _length) { if (_data[i] == 10) { // '\n' _lineStart = _pos; _lineLength = i - _pos; _pos = i+1; // ignore \r if (_lineLength > 0 && _data[i-1] == 13) _lineLength--; // line found break; } if (++i == _length) { // last line doesn't end with \n _lineStart = _pos; _lineLength = i - _pos; _pos = _length; } } return(_lineStart >= 0); } private String ExtractValueFromContentDispositionHeader(String l, int pos, String name) { String pattern = " " + name + "="; int i1 = CultureInfo.InvariantCulture.CompareInfo.IndexOf(l, pattern, pos, CompareOptions.IgnoreCase); if (i1 < 0) { pattern = ";" + name + "="; i1 = CultureInfo.InvariantCulture.CompareInfo.IndexOf(l, pattern, pos, CompareOptions.IgnoreCase); if (i1 < 0) { pattern = name + "="; i1 = CultureInfo.InvariantCulture.CompareInfo.IndexOf(l, pattern, pos, CompareOptions.IgnoreCase); } } if (i1 < 0) return null; i1 += pattern.Length; if (i1 >= l.Length) return String.Empty; if (l[i1] == '"') { i1 += 1; int i2 = l.IndexOf('"', i1); if (i2 < 0) return null; if (i2 == i1) return String.Empty; return l.Substring(i1, i2-i1); } else { int i2 = l.IndexOf(';', i1); if (i2 < 0) i2 = l.Length; return l.Substring(i1, i2-i1).Trim(); } } private void ParsePartHeaders() { _partName = null; _partFilename = null; _partContentType = null; while (GetNextLine()) { if (_lineLength == 0) break; // empty line signals end of headers // get line as String byte[] lineBytes = new byte[_lineLength]; _data.CopyBytes(_lineStart, lineBytes, 0, _lineLength); String line = _encoding.GetString(lineBytes); // parse into header and value int ic = line.IndexOf(':'); if (ic < 0) continue; // not a header // remeber header String header = line.Substring(0, ic); if (StringUtil.EqualsIgnoreCase(header, "Content-Disposition")) { // parse name and filename _partName = ExtractValueFromContentDispositionHeader(line, ic+1, "name"); _partFilename = ExtractValueFromContentDispositionHeader(line, ic+1, "filename"); } else if (StringUtil.EqualsIgnoreCase(header, "Content-Type")) { _partContentType = line.Substring(ic+1).Trim(); } } } private bool AtBoundaryLine() { // check for either regular or last boundary line length int len = _boundary.Length; if (_lineLength != len && _lineLength != len+2) return false; // match with boundary for (int i = 0; i < len; i++) { if (_data[_lineStart+i] != _boundary[i]) return false; } // regular boundary line? if (_lineLength == len) return true; // last boundary line? (has to end with "--") if (_data[_lineStart+len] != 45 || _data[_lineStart+len+1] != 45) return false; _lastBoundaryFound = true; // remember that it is last return true; } private void ParsePartData() { _partDataStart = _pos; _partDataLength = -1; while (GetNextLine()) { if (AtBoundaryLine()) { // calc length: adjust to exclude [\r]\n before the separator int iEnd = _lineStart - 1; if (_data[iEnd] == 10) // \n iEnd--; if (_data[iEnd] == 13) // \r iEnd--; _partDataLength = iEnd - _partDataStart + 1; break; } } } private void ParseIntoElementList() { // // Skip until first boundary // while (GetNextLine()) { if (AtBoundaryLine()) break; } if (AtEndOfData()) return; // // Parse the parts // do { // Parse current part's headers ParsePartHeaders(); if (AtEndOfData()) break; // cannot stop after headers // Parse current part's data ParsePartData(); if (_partDataLength == -1) break; // ending boundary not found // Remember the current part (if named) if (_partName != null) { _elements.Add(new MultipartContentElement( _partName, _partFilename, _partContentType, _data, _partDataStart, _partDataLength)); } } while (!AtEndOfData()); } /* * Static method to do the parsing */ internal static MultipartContentElement[] Parse(HttpRawUploadedContent data, int length, byte[] boundary, Encoding encoding) { HttpMultipartContentTemplateParser parser = new HttpMultipartContentTemplateParser(data, length, boundary, encoding); parser.ParseIntoElementList(); return (MultipartContentElement[])parser._elements.ToArray(typeof(MultipartContentElement)); } } }
using System; using System.Collections.Generic; using System.Reflection; using GodLesZ.Library.Win7.Shell.Resources; namespace GodLesZ.Library.Win7.Shell { /// <summary> /// Contains the GUID identifiers for well-known folders. /// </summary> internal static class FolderIdentifiers { private static Dictionary<Guid, string> folders; static FolderIdentifiers() { folders = new Dictionary<Guid, string>(); Type folderIDs = typeof(FolderIdentifiers); FieldInfo[] fields = folderIDs.GetFields(BindingFlags.NonPublic | BindingFlags.Static); foreach (FieldInfo f in fields) { // Ignore dictionary field. if (f.FieldType == typeof(Guid)) { Guid id = (Guid)f.GetValue(null); string name = f.Name; folders.Add(id, name); } } } /// <summary> /// Returns the friendly name for a specified folder. /// </summary> /// <param name="folderId">The Guid identifier for a known folder.</param> /// <returns>A <see cref="T:System.String"/> value.</returns> internal static string NameForGuid(Guid folderId) { string folder; if (!folders.TryGetValue(folderId, out folder)) { throw new ArgumentException(LocalizedMessages.FolderIdsUnknownGuid, "folderId"); } return folder; } /// <summary> /// Returns a sorted list of name, guid pairs for /// all known folders. /// </summary> /// <returns></returns> internal static SortedList<string, Guid> GetAllFolders() { // Make a copy of the dictionary // because the Keys and Values collections // are mutable. ICollection<Guid> keys = folders.Keys; SortedList<string, Guid> slist = new SortedList<string, Guid>(); foreach (Guid g in keys) { slist.Add(folders[g], g); } return slist; } #region KnownFolder Guids /// <summary> /// Computer /// </summary> internal static Guid Computer = new Guid(0x0AC0837C, 0xBBF8, 0x452A, 0x85, 0x0D, 0x79, 0xD0, 0x8E, 0x66, 0x7C, 0xA7); /// <summary> /// Conflicts /// </summary> internal static Guid Conflict = new Guid(0x4bfefb45, 0x347d, 0x4006, 0xa5, 0xbe, 0xac, 0x0c, 0xb0, 0x56, 0x71, 0x92); /// <summary> /// Control Panel /// </summary> internal static Guid ControlPanel = new Guid(0x82A74AEB, 0xAEB4, 0x465C, 0xA0, 0x14, 0xD0, 0x97, 0xEE, 0x34, 0x6D, 0x63); /// <summary> /// Desktop /// </summary> internal static Guid Desktop = new Guid(0xB4BFCC3A, 0xDB2C, 0x424C, 0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41); /// <summary> /// Internet Explorer /// </summary> internal static Guid Internet = new Guid(0x4D9F7874, 0x4E0C, 0x4904, 0x96, 0x7B, 0x40, 0xB0, 0xD2, 0x0C, 0x3E, 0x4B); /// <summary> /// Network /// </summary> internal static Guid Network = new Guid(0xD20BEEC4, 0x5CA8, 0x4905, 0xAE, 0x3B, 0xBF, 0x25, 0x1E, 0xA0, 0x9B, 0x53); /// <summary> /// Printers /// </summary> internal static Guid Printers = new Guid(0x76FC4E2D, 0xD6AD, 0x4519, 0xA6, 0x63, 0x37, 0xBD, 0x56, 0x06, 0x81, 0x85); /// <summary> /// Sync Center /// </summary> internal static Guid SyncManager = new Guid(0x43668BF8, 0xC14E, 0x49B2, 0x97, 0xC9, 0x74, 0x77, 0x84, 0xD7, 0x84, 0xB7); /// <summary> /// Network Connections /// </summary> internal static Guid Connections = new Guid(0x6F0CD92B, 0x2E97, 0x45D1, 0x88, 0xFF, 0xB0, 0xD1, 0x86, 0xB8, 0xDE, 0xDD); /// <summary> /// Sync Setup /// </summary> internal static Guid SyncSetup = new Guid(0xf214138, 0xb1d3, 0x4a90, 0xbb, 0xa9, 0x27, 0xcb, 0xc0, 0xc5, 0x38, 0x9a); /// <summary> /// Sync Results /// </summary> internal static Guid SyncResults = new Guid(0x289a9a43, 0xbe44, 0x4057, 0xa4, 0x1b, 0x58, 0x7a, 0x76, 0xd7, 0xe7, 0xf9); /// <summary> /// Recycle Bin /// </summary> internal static Guid RecycleBin = new Guid(0xB7534046, 0x3ECB, 0x4C18, 0xBE, 0x4E, 0x64, 0xCD, 0x4C, 0xB7, 0xD6, 0xAC); /// <summary> /// Fonts /// </summary> internal static Guid Fonts = new Guid(0xFD228CB7, 0xAE11, 0x4AE3, 0x86, 0x4C, 0x16, 0xF3, 0x91, 0x0A, 0xB8, 0xFE); /// <summary> /// Startup /// </summary> internal static Guid Startup = new Guid(0xB97D20BB, 0xF46A, 0x4C97, 0xBA, 0x10, 0x5E, 0x36, 0x08, 0x43, 0x08, 0x54); /// <summary> /// Programs /// </summary> internal static Guid Programs = new Guid(0xA77F5D77, 0x2E2B, 0x44C3, 0xA6, 0xA2, 0xAB, 0xA6, 0x01, 0x05, 0x4A, 0x51); /// <summary> /// Start Menu /// </summary> internal static Guid StartMenu = new Guid(0x625B53C3, 0xAB48, 0x4EC1, 0xBA, 0x1F, 0xA1, 0xEF, 0x41, 0x46, 0xFC, 0x19); /// <summary> /// Recent Items /// </summary> internal static Guid Recent = new Guid(0xAE50C081, 0xEBD2, 0x438A, 0x86, 0x55, 0x8A, 0x09, 0x2E, 0x34, 0x98, 0x7A); /// <summary> /// SendTo /// </summary> internal static Guid SendTo = new Guid(0x8983036C, 0x27C0, 0x404B, 0x8F, 0x08, 0x10, 0x2D, 0x10, 0xDC, 0xFD, 0x74); /// <summary> /// Documents /// </summary> internal static Guid Documents = new Guid(0xFDD39AD0, 0x238F, 0x46AF, 0xAD, 0xB4, 0x6C, 0x85, 0x48, 0x03, 0x69, 0xC7); /// <summary> /// Favorites /// </summary> internal static Guid Favorites = new Guid(0x1777F761, 0x68AD, 0x4D8A, 0x87, 0xBD, 0x30, 0xB7, 0x59, 0xFA, 0x33, 0xDD); /// <summary> /// Network Shortcuts /// </summary> internal static Guid NetHood = new Guid(0xC5ABBF53, 0xE17F, 0x4121, 0x89, 0x00, 0x86, 0x62, 0x6F, 0xC2, 0xC9, 0x73); /// <summary> /// Printer Shortcuts /// </summary> internal static Guid PrintHood = new Guid(0x9274BD8D, 0xCFD1, 0x41C3, 0xB3, 0x5E, 0xB1, 0x3F, 0x55, 0xA7, 0x58, 0xF4); /// <summary> /// Templates /// </summary> internal static Guid Templates = new Guid(0xA63293E8, 0x664E, 0x48DB, 0xA0, 0x79, 0xDF, 0x75, 0x9E, 0x05, 0x09, 0xF7); /// <summary> /// Startup /// </summary> internal static Guid CommonStartup = new Guid(0x82A5EA35, 0xD9CD, 0x47C5, 0x96, 0x29, 0xE1, 0x5D, 0x2F, 0x71, 0x4E, 0x6E); /// <summary> /// Programs /// </summary> internal static Guid CommonPrograms = new Guid(0x0139D44E, 0x6AFE, 0x49F2, 0x86, 0x90, 0x3D, 0xAF, 0xCA, 0xE6, 0xFF, 0xB8); /// <summary> /// Start Menu /// </summary> internal static Guid CommonStartMenu = new Guid(0xA4115719, 0xD62E, 0x491D, 0xAA, 0x7C, 0xE7, 0x4B, 0x8B, 0xE3, 0xB0, 0x67); /// <summary> /// Public Desktop /// </summary> internal static Guid PublicDesktop = new Guid(0xC4AA340D, 0xF20F, 0x4863, 0xAF, 0xEF, 0xF8, 0x7E, 0xF2, 0xE6, 0xBA, 0x25); /// <summary> /// ProgramData /// </summary> internal static Guid ProgramData = new Guid(0x62AB5D82, 0xFDC1, 0x4DC3, 0xA9, 0xDD, 0x07, 0x0D, 0x1D, 0x49, 0x5D, 0x97); /// <summary> /// Templates /// </summary> internal static Guid CommonTemplates = new Guid(0xB94237E7, 0x57AC, 0x4347, 0x91, 0x51, 0xB0, 0x8C, 0x6C, 0x32, 0xD1, 0xF7); /// <summary> /// Public Documents /// </summary> internal static Guid PublicDocuments = new Guid(0xED4824AF, 0xDCE4, 0x45A8, 0x81, 0xE2, 0xFC, 0x79, 0x65, 0x08, 0x36, 0x34); /// <summary> /// Roaming /// </summary> internal static Guid RoamingAppData = new Guid(0x3EB685DB, 0x65F9, 0x4CF6, 0xA0, 0x3A, 0xE3, 0xEF, 0x65, 0x72, 0x9F, 0x3D); /// <summary> /// Local /// </summary> internal static Guid LocalAppData = new Guid(0xF1B32785, 0x6FBA, 0x4FCF, 0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91); /// <summary> /// LocalLow /// </summary> internal static Guid LocalAppDataLow = new Guid(0xA520A1A4, 0x1780, 0x4FF6, 0xBD, 0x18, 0x16, 0x73, 0x43, 0xC5, 0xAF, 0x16); /// <summary> /// Temporary Internet Files /// </summary> internal static Guid InternetCache = new Guid(0x352481E8, 0x33BE, 0x4251, 0xBA, 0x85, 0x60, 0x07, 0xCA, 0xED, 0xCF, 0x9D); /// <summary> /// Cookies /// </summary> internal static Guid Cookies = new Guid(0x2B0F765D, 0xC0E9, 0x4171, 0x90, 0x8E, 0x08, 0xA6, 0x11, 0xB8, 0x4F, 0xF6); /// <summary> /// History /// </summary> internal static Guid History = new Guid(0xD9DC8A3B, 0xB784, 0x432E, 0xA7, 0x81, 0x5A, 0x11, 0x30, 0xA7, 0x59, 0x63); /// <summary> /// System32 /// </summary> internal static Guid System = new Guid(0x1AC14E77, 0x02E7, 0x4E5D, 0xB7, 0x44, 0x2E, 0xB1, 0xAE, 0x51, 0x98, 0xB7); /// <summary> /// System32 /// </summary> internal static Guid SystemX86 = new Guid(0xD65231B0, 0xB2F1, 0x4857, 0xA4, 0xCE, 0xA8, 0xE7, 0xC6, 0xEA, 0x7D, 0x27); /// <summary> /// Windows /// </summary> internal static Guid Windows = new Guid(0xF38BF404, 0x1D43, 0x42F2, 0x93, 0x05, 0x67, 0xDE, 0x0B, 0x28, 0xFC, 0x23); /// <summary> /// The user's username (%USERNAME%) /// </summary> internal static Guid Profile = new Guid(0x5E6C858F, 0x0E22, 0x4760, 0x9A, 0xFE, 0xEA, 0x33, 0x17, 0xB6, 0x71, 0x73); /// <summary> /// Pictures /// </summary> internal static Guid Pictures = new Guid(0x33E28130, 0x4E1E, 0x4676, 0x83, 0x5A, 0x98, 0x39, 0x5C, 0x3B, 0xC3, 0xBB); /// <summary> /// Program Files /// </summary> internal static Guid ProgramFilesX86 = new Guid(0x7C5A40EF, 0xA0FB, 0x4BFC, 0x87, 0x4A, 0xC0, 0xF2, 0xE0, 0xB9, 0xFA, 0x8E); /// <summary> /// Common Files /// </summary> internal static Guid ProgramFilesCommonX86 = new Guid(0xDE974D24, 0xD9C6, 0x4D3E, 0xBF, 0x91, 0xF4, 0x45, 0x51, 0x20, 0xB9, 0x17); /// <summary> /// Program Files /// </summary> internal static Guid ProgramFilesX64 = new Guid(0x6d809377, 0x6af0, 0x444b, 0x89, 0x57, 0xa3, 0x77, 0x3f, 0x02, 0x20, 0x0e); /// <summary> /// Common Files /// </summary> internal static Guid ProgramFilesCommonX64 = new Guid(0x6365d5a7, 0xf0d, 0x45e5, 0x87, 0xf6, 0xd, 0xa5, 0x6b, 0x6a, 0x4f, 0x7d); /// <summary> /// Program Files /// </summary> internal static Guid ProgramFiles = new Guid(0x905e63b6, 0xc1bf, 0x494e, 0xb2, 0x9c, 0x65, 0xb7, 0x32, 0xd3, 0xd2, 0x1a); /// <summary> /// Common Files /// </summary> internal static Guid ProgramFilesCommon = new Guid(0xF7F1ED05, 0x9F6D, 0x47A2, 0xAA, 0xAE, 0x29, 0xD3, 0x17, 0xC6, 0xF0, 0x66); /// <summary> /// Administrative Tools /// </summary> internal static Guid AdminTools = new Guid(0x724EF170, 0xA42D, 0x4FEF, 0x9F, 0x26, 0xB6, 0x0E, 0x84, 0x6F, 0xBA, 0x4F); /// <summary> /// Administrative Tools /// </summary> internal static Guid CommonAdminTools = new Guid(0xD0384E7D, 0xBAC3, 0x4797, 0x8F, 0x14, 0xCB, 0xA2, 0x29, 0xB3, 0x92, 0xB5); /// <summary> /// Music /// </summary> internal static Guid Music = new Guid(0x4BD8D571, 0x6D19, 0x48D3, 0xBE, 0x97, 0x42, 0x22, 0x20, 0x08, 0x0E, 0x43); /// <summary> /// Videos /// </summary> internal static Guid Videos = new Guid(0x18989B1D, 0x99B5, 0x455B, 0x84, 0x1C, 0xAB, 0x7C, 0x74, 0xE4, 0xDD, 0xFC); /// <summary> /// Public Pictures /// </summary> internal static Guid PublicPictures = new Guid(0xB6EBFB86, 0x6907, 0x413C, 0x9A, 0xF7, 0x4F, 0xC2, 0xAB, 0xF0, 0x7C, 0xC5); /// <summary> /// Public Music /// </summary> internal static Guid PublicMusic = new Guid(0x3214FAB5, 0x9757, 0x4298, 0xBB, 0x61, 0x92, 0xA9, 0xDE, 0xAA, 0x44, 0xFF); /// <summary> /// Public Videos /// </summary> internal static Guid PublicVideos = new Guid(0x2400183A, 0x6185, 0x49FB, 0xA2, 0xD8, 0x4A, 0x39, 0x2A, 0x60, 0x2B, 0xA3); /// <summary> /// Resources /// </summary> internal static Guid ResourceDir = new Guid(0x8AD10C31, 0x2ADB, 0x4296, 0xA8, 0xF7, 0xE4, 0x70, 0x12, 0x32, 0xC9, 0x72); /// <summary> /// None /// </summary> internal static Guid LocalizedResourcesDir = new Guid(0x2A00375E, 0x224C, 0x49DE, 0xB8, 0xD1, 0x44, 0x0D, 0xF7, 0xEF, 0x3D, 0xDC); /// <summary> /// OEM Links /// </summary> internal static Guid CommonOEMLinks = new Guid(0xC1BAE2D0, 0x10DF, 0x4334, 0xBE, 0xDD, 0x7A, 0xA2, 0x0B, 0x22, 0x7A, 0x9D); /// <summary> /// Temporary Burn Folder /// </summary> internal static Guid CDBurning = new Guid(0x9E52AB10, 0xF80D, 0x49DF, 0xAC, 0xB8, 0x43, 0x30, 0xF5, 0x68, 0x78, 0x55); /// <summary> /// Users /// </summary> internal static Guid UserProfiles = new Guid(0x0762D272, 0xC50A, 0x4BB0, 0xA3, 0x82, 0x69, 0x7D, 0xCD, 0x72, 0x9B, 0x80); /// <summary> /// Playlists /// </summary> internal static Guid Playlists = new Guid(0xDE92C1C7, 0x837F, 0x4F69, 0xA3, 0xBB, 0x86, 0xE6, 0x31, 0x20, 0x4A, 0x23); /// <summary> /// Sample Playlists /// </summary> internal static Guid SamplePlaylists = new Guid(0x15CA69B3, 0x30EE, 0x49C1, 0xAC, 0xE1, 0x6B, 0x5E, 0xC3, 0x72, 0xAF, 0xB5); /// <summary> /// Sample Music /// </summary> internal static Guid SampleMusic = new Guid(0xB250C668, 0xF57D, 0x4EE1, 0xA6, 0x3C, 0x29, 0x0E, 0xE7, 0xD1, 0xAA, 0x1F); /// <summary> /// Sample Pictures /// </summary> internal static Guid SamplePictures = new Guid(0xC4900540, 0x2379, 0x4C75, 0x84, 0x4B, 0x64, 0xE6, 0xFA, 0xF8, 0x71, 0x6B); /// <summary> /// Sample Videos /// </summary> internal static Guid SampleVideos = new Guid(0x859EAD94, 0x2E85, 0x48AD, 0xA7, 0x1A, 0x09, 0x69, 0xCB, 0x56, 0xA6, 0xCD); /// <summary> /// Slide Shows /// </summary> internal static Guid PhotoAlbums = new Guid(0x69D2CF90, 0xFC33, 0x4FB7, 0x9A, 0x0C, 0xEB, 0xB0, 0xF0, 0xFC, 0xB4, 0x3C); /// <summary> /// Public /// </summary> internal static Guid Public = new Guid(0xDFDF76A2, 0xC82A, 0x4D63, 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85); /// <summary> /// Programs and Features /// </summary> internal static Guid ChangeRemovePrograms = new Guid(0xdf7266ac, 0x9274, 0x4867, 0x8d, 0x55, 0x3b, 0xd6, 0x61, 0xde, 0x87, 0x2d); /// <summary> /// Installed Updates /// </summary> internal static Guid AppUpdates = new Guid(0xa305ce99, 0xf527, 0x492b, 0x8b, 0x1a, 0x7e, 0x76, 0xfa, 0x98, 0xd6, 0xe4); /// <summary> /// Get Programs /// </summary> internal static Guid AddNewPrograms = new Guid(0xde61d971, 0x5ebc, 0x4f02, 0xa3, 0xa9, 0x6c, 0x82, 0x89, 0x5e, 0x5c, 0x04); /// <summary> /// Downloads /// </summary> internal static Guid Downloads = new Guid(0x374de290, 0x123f, 0x4565, 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b); /// <summary> /// Public Downloads /// </summary> internal static Guid PublicDownloads = new Guid(0x3d644c9b, 0x1fb8, 0x4f30, 0x9b, 0x45, 0xf6, 0x70, 0x23, 0x5f, 0x79, 0xc0); /// <summary> /// Searches /// </summary> internal static Guid SavedSearches = new Guid(0x7d1d3a04, 0xdebb, 0x4115, 0x95, 0xcf, 0x2f, 0x29, 0xda, 0x29, 0x20, 0xda); /// <summary> /// Quick Launch /// </summary> internal static Guid QuickLaunch = new Guid(0x52a4f021, 0x7b75, 0x48a9, 0x9f, 0x6b, 0x4b, 0x87, 0xa2, 0x10, 0xbc, 0x8f); /// <summary> /// Contacts /// </summary> internal static Guid Contacts = new Guid(0x56784854, 0xc6cb, 0x462b, 0x81, 0x69, 0x88, 0xe3, 0x50, 0xac, 0xb8, 0x82); /// <summary> /// Gadgets /// </summary> internal static Guid SidebarParts = new Guid(0xa75d362e, 0x50fc, 0x4fb7, 0xac, 0x2c, 0xa8, 0xbe, 0xaa, 0x31, 0x44, 0x93); /// <summary> /// Gadgets /// </summary> internal static Guid SidebarDefaultParts = new Guid(0x7b396e54, 0x9ec5, 0x4300, 0xbe, 0xa, 0x24, 0x82, 0xeb, 0xae, 0x1a, 0x26); /// <summary> /// Tree property value folder /// </summary> internal static Guid TreeProperties = new Guid(0x5b3749ad, 0xb49f, 0x49c1, 0x83, 0xeb, 0x15, 0x37, 0x0f, 0xbd, 0x48, 0x82); /// <summary> /// GameExplorer /// </summary> internal static Guid PublicGameTasks = new Guid(0xdebf2536, 0xe1a8, 0x4c59, 0xb6, 0xa2, 0x41, 0x45, 0x86, 0x47, 0x6a, 0xea); /// <summary> /// GameExplorer /// </summary> internal static Guid GameTasks = new Guid(0x54fae61, 0x4dd8, 0x4787, 0x80, 0xb6, 0x9, 0x2, 0x20, 0xc4, 0xb7, 0x0); /// <summary> /// Saved Games /// </summary> internal static Guid SavedGames = new Guid(0x4c5c32ff, 0xbb9d, 0x43b0, 0xb5, 0xb4, 0x2d, 0x72, 0xe5, 0x4e, 0xaa, 0xa4); /// <summary> /// Games /// </summary> internal static Guid Games = new Guid(0xcac52c1a, 0xb53d, 0x4edc, 0x92, 0xd7, 0x6b, 0x2e, 0x8a, 0xc1, 0x94, 0x34); /// <summary> /// Recorded TV /// </summary> internal static Guid RecordedTV = new Guid(0xbd85e001, 0x112e, 0x431e, 0x98, 0x3b, 0x7b, 0x15, 0xac, 0x09, 0xff, 0xf1); /// <summary> /// Microsoft Office Outlook /// </summary> internal static Guid SearchMapi = new Guid(0x98ec0e18, 0x2098, 0x4d44, 0x86, 0x44, 0x66, 0x97, 0x93, 0x15, 0xa2, 0x81); /// <summary> /// Offline Files /// </summary> internal static Guid SearchCsc = new Guid(0xee32e446, 0x31ca, 0x4aba, 0x81, 0x4f, 0xa5, 0xeb, 0xd2, 0xfd, 0x6d, 0x5e); /// <summary> /// Links /// </summary> internal static Guid Links = new Guid(0xbfb9d5e0, 0xc6a9, 0x404c, 0xb2, 0xb2, 0xae, 0x6d, 0xb6, 0xaf, 0x49, 0x68); /// <summary> /// The user's full name (for instance, Jean Philippe Bagel) entered when the user account was created. /// </summary> internal static Guid UsersFiles = new Guid(0xf3ce0f7c, 0x4901, 0x4acc, 0x86, 0x48, 0xd5, 0xd4, 0x4b, 0x04, 0xef, 0x8f); /// <summary> /// Search home /// </summary> internal static Guid SearchHome = new Guid(0x190337d1, 0xb8ca, 0x4121, 0xa6, 0x39, 0x6d, 0x47, 0x2d, 0x16, 0x97, 0x2a); /// <summary> /// Original Images /// </summary> internal static Guid OriginalImages = new Guid(0x2C36C0AA, 0x5812, 0x4b87, 0xbf, 0xd0, 0x4c, 0xd0, 0xdf, 0xb1, 0x9b, 0x39); #endregion #region Win7 KnownFolders Guids /// <summary> /// UserProgramFiles /// </summary> internal static Guid UserProgramFiles = new Guid(0x5cd7aee2, 0x2219, 0x4a67, 0xb8, 0x5d, 0x6c, 0x9c, 0xe1, 0x56, 0x60, 0xcb); /// <summary> /// UserProgramFilesCommon /// </summary> internal static Guid UserProgramFilesCommon = new Guid(0xbcbd3057, 0xca5c, 0x4622, 0xb4, 0x2d, 0xbc, 0x56, 0xdb, 0x0a, 0xe5, 0x16); /// <summary> /// Ringtones /// </summary> internal static Guid Ringtones = new Guid(0xC870044B, 0xF49E, 0x4126, 0xA9, 0xC3, 0xB5, 0x2A, 0x1F, 0xF4, 0x11, 0xE8); /// <summary> /// PublicRingtones /// </summary> internal static Guid PublicRingtones = new Guid(0xE555AB60, 0x153B, 0x4D17, 0x9F, 0x04, 0xA5, 0xFE, 0x99, 0xFC, 0x15, 0xEC); /// <summary> /// UsersLibraries /// </summary> internal static Guid UsersLibraries = new Guid(0xa302545d, 0xdeff, 0x464b, 0xab, 0xe8, 0x61, 0xc8, 0x64, 0x8d, 0x93, 0x9b); /// <summary> /// DocumentsLibrary /// </summary> internal static Guid DocumentsLibrary = new Guid(0x7b0db17d, 0x9cd2, 0x4a93, 0x97, 0x33, 0x46, 0xcc, 0x89, 0x02, 0x2e, 0x7c); /// <summary> /// MusicLibrary /// </summary> internal static Guid MusicLibrary = new Guid(0x2112ab0a, 0xc86a, 0x4ffe, 0xa3, 0x68, 0xd, 0xe9, 0x6e, 0x47, 0x1, 0x2e); /// <summary> /// PicturesLibrary /// </summary> internal static Guid PicturesLibrary = new Guid(0xa990ae9f, 0xa03b, 0x4e80, 0x94, 0xbc, 0x99, 0x12, 0xd7, 0x50, 0x41, 0x4); /// <summary> /// VideosLibrary /// </summary> internal static Guid VideosLibrary = new Guid(0x491e922f, 0x5643, 0x4af4, 0xa7, 0xeb, 0x4e, 0x7a, 0x13, 0x8d, 0x81, 0x74); /// <summary> /// RecordedTVLibrary /// </summary> internal static Guid RecordedTVLibrary = new Guid(0x1a6fdba2, 0xf42d, 0x4358, 0xa7, 0x98, 0xb7, 0x4d, 0x74, 0x59, 0x26, 0xc5); /// <summary> /// OtherUsers /// </summary> internal static Guid OtherUsers = new Guid(0x52528a6b, 0xb9e3, 0x4add, 0xb6, 0xd, 0x58, 0x8c, 0x2d, 0xba, 0x84, 0x2d); /// <summary> /// DeviceMetadataStore /// </summary> internal static Guid DeviceMetadataStore = new Guid(0x5ce4a5e9, 0xe4eb, 0x479d, 0xb8, 0x9f, 0x13, 0x0c, 0x02, 0x88, 0x61, 0x55); /// <summary> /// Libraries /// </summary> internal static Guid Libraries = new Guid(0x1b3ea5dc, 0xb587, 0x4786, 0xb4, 0xef, 0xbd, 0x1d, 0xc3, 0x32, 0xae, 0xae); /// <summary> /// UserPinned /// </summary> internal static Guid UserPinned = new Guid(0x9e3995ab, 0x1f9c, 0x4f13, 0xb8, 0x27, 0x48, 0xb2, 0x4b, 0x6c, 0x71, 0x74); /// <summary> /// ImplicitAppShortcuts /// </summary> internal static Guid ImplicitAppShortcuts = new Guid(0xbcb5256f, 0x79f6, 0x4cee, 0xb7, 0x25, 0xdc, 0x34, 0xe4, 0x2, 0xfd, 0x46); #endregion } }
// // Mono.WebServer.XSP/main.cs: Web Server that uses ASP.NET hosting // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (C) 2002,2003 Ximian, Inc (http://www.ximian.com) // (C) Copyright 2004-2009 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Mono.WebServer.Log; using Mono.WebServer.Options; namespace Mono.WebServer.XSP { public class Server : MarshalByRefObject { static RSA key; static readonly CompatTuple<int, string, ApplicationServer> success = new CompatTuple<int,string,ApplicationServer> (0, null, null); static AsymmetricAlgorithm GetPrivateKey (X509Certificate certificate, string targetHost) { return key; } public static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e) { var ex = (Exception)e.ExceptionObject; Logger.Write (LogLevel.Error, "Handling exception type {0}", ex.GetType ().Name); Logger.Write (LogLevel.Error, "Message is {0}", ex.Message); Logger.Write (LogLevel.Error, "IsTerminating is set to {0}", e.IsTerminating); if (e.IsTerminating) Logger.Write(ex); } public static int Main (string [] args) { return DebugMain (args).Item1; } internal static CompatTuple<int, string, ApplicationServer> DebugMain (string [] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; bool quiet = false; while (true) { try { return new Server ().DebugMain (args, true, null, quiet); } catch (ThreadAbortException ex) { Logger.Write (ex); // Single-app mode and ASP.NET appdomain unloaded Thread.ResetAbort (); quiet = true; // hush 'RealMain' } } } /// <param name="args">Original args passed to the program.</param> /// <param name="root">If set to <c>true</c> it means the caller is in the root domain.</param> /// <param name="ext_apphost">Used when single app mode is used, in a recursive call to RealMain from the single app domain.</param> /// <param name="quiet">If set to <c>true</c> don't show messages. Used to avoid double printing of the banner.</param> public int RealMain (string [] args, bool root, IApplicationHost ext_apphost, bool quiet) { return DebugMain (args, root, ext_apphost, quiet).Item1; } /// <param name="args">Original args passed to the program.</param> /// <param name="root">If set to <c>true</c> it means the caller is in the root domain.</param> /// <param name="ext_apphost">Used when single app mode is used, in a recursive call to RealMain from the single app domain.</param> /// <param name="quiet">If set to <c>true</c> don't show messages. Used to avoid double printing of the banner.</param> internal CompatTuple<int, string, ApplicationServer> DebugMain (string [] args, bool root, IApplicationHost ext_apphost, bool quiet) { var configurationManager = new ConfigurationManager ("xsp", quiet); var security = new SecurityConfiguration (); if (!ParseOptions (configurationManager, args, security)) return new CompatTuple<int,string,ApplicationServer> (1, "Error while parsing options", null); // Show the help and exit. if (configurationManager.Help) { configurationManager.PrintHelp (); #if DEBUG Console.WriteLine ("Press any key..."); Console.ReadKey (); #endif return success; } // Show the version and exit. if (configurationManager.Version) { Version.Show (); return success; } if (!configurationManager.LoadConfigFile ()) return new CompatTuple<int,string,ApplicationServer> (1, "Error while loading the configuration file", null); configurationManager.SetupLogger (); WebSource webSource; if (security.Enabled) { try { key = security.KeyPair; webSource = new XSPWebSource (configurationManager.Address, configurationManager.RandomPort ? default(ushort) : configurationManager.Port, security.Protocol, security.ServerCertificate, GetPrivateKey, security.AcceptClientCertificates, security.RequireClientCertificates, !root); } catch (CryptographicException ce) { Logger.Write (ce); return new CompatTuple<int,string,ApplicationServer> (1, "Error while setting up https", null); } } else { webSource = new XSPWebSource (configurationManager.Address, configurationManager.Port, !root); } var server = new ApplicationServer (webSource, configurationManager.Root) { Verbose = configurationManager.Verbose, SingleApplication = !root }; if (configurationManager.Applications != null) server.AddApplicationsFromCommandLine (configurationManager.Applications); if (configurationManager.AppConfigFile != null) server.AddApplicationsFromConfigFile (configurationManager.AppConfigFile); if (configurationManager.AppConfigDir != null) server.AddApplicationsFromConfigDirectory (configurationManager.AppConfigDir); if (configurationManager.Applications == null && configurationManager.AppConfigDir == null && configurationManager.AppConfigFile == null) server.AddApplicationsFromCommandLine ("/:."); VPathToHost vh = server.GetSingleApp (); if (root && vh != null) { // Redo in new domain vh.CreateHost (server, webSource); var svr = (Server) vh.AppHost.Domain.CreateInstanceAndUnwrap (GetType ().Assembly.GetName ().ToString (), GetType ().FullName); webSource.Dispose (); return svr.DebugMain (args, false, vh.AppHost, configurationManager.Quiet); } server.AppHost = ext_apphost; if (!configurationManager.Quiet) { Logger.Write(LogLevel.Notice, Assembly.GetExecutingAssembly().GetName().Name); Logger.Write(LogLevel.Notice, "Listening on address: {0}", configurationManager.Address); Logger.Write(LogLevel.Notice, "Root directory: {0}", configurationManager.Root); } try { if (!server.Start (!configurationManager.NonStop, (int)configurationManager.Backlog)) return new CompatTuple<int,string,ApplicationServer> (2, "Error while starting server", server); if (!configurationManager.Quiet) { // MonoDevelop depends on this string. If you change it, let them know. Logger.Write(LogLevel.Notice, "Listening on port: {0} {1}", server.Port, security); } if (configurationManager.RandomPort && !configurationManager.Quiet) Logger.Write (LogLevel.Notice, "Random port: {0}", server.Port); if (!configurationManager.NonStop) { if (!configurationManager.Quiet) Console.WriteLine ("Hit Return to stop the server."); while (true) { bool doSleep; try { Console.ReadLine (); break; } catch (IOException) { // This might happen on appdomain unload // until the previous threads are terminated. doSleep = true; } catch (ThreadAbortException) { doSleep = true; } if (doSleep) Thread.Sleep (500); } server.Stop (); } } catch (Exception e) { if (!(e is ThreadAbortException)) Logger.Write (e); else server.ShutdownSockets (); return new CompatTuple<int,string,ApplicationServer> (1, "Error running server", server); } return new CompatTuple<int,string,ApplicationServer> (0, null, server); } static bool ParseOptions (ConfigurationManager manager, string[] args, SecurityConfiguration security) { if (!manager.LoadCommandLineArgs (args)) return false; // TODO: add mutual exclusivity rules if(manager.Https) security.Enabled = true; if (manager.HttpsClientAccept) { security.Enabled = true; security.AcceptClientCertificates = true; security.RequireClientCertificates = false; } if (manager.HttpsClientRequire) { security.Enabled = true; security.AcceptClientCertificates = true; security.RequireClientCertificates = true; } if (manager.P12File != null) security.Pkcs12File = manager.P12File; if(manager.Cert != null) security.CertificateFile = manager.Cert; if (manager.PkFile != null) security.PvkFile = manager.PkFile; if (manager.PkPwd != null) security.Password = manager.PkPwd; security.Protocol = manager.Protocols; int minThreads = manager.MinThreads ?? 0; if(minThreads > 0) ThreadPool.SetMinThreads (minThreads, minThreads); if(!String.IsNullOrEmpty(manager.PidFile)) try { using (StreamWriter sw = File.CreateText (manager.PidFile)) { sw.Write (Process.GetCurrentProcess ().Id); } } catch (Exception ex) { Logger.Write (LogLevel.Error, "Failed to write pidfile {0}: {1}", manager.PidFile, ex.Message); } if(manager.NoHidden) MonoWorkerRequest.CheckFileAccess = false; return true; } public override object InitializeLifetimeService () { return null; } } }
namespace Common.Extensions.Tests { using System; using FluentAssertions; using Xunit; public class StringExtensionsTests { [Theory] [InlineData("a", false)] [InlineData(" ", false)] public void IsEmpty_StrWithValueTest_ShouldBeFalse(string str, bool expected) { // Act & Assert str.IsEmpty().Should().Be(expected); } [Theory] [InlineData(null, true)] [InlineData("", true)] public void IsEmpty_InvalidString_IsEmptyShouldBeTrue(string str, bool expected) { // Act & Assert str.IsEmpty().Should().Be(expected); } [Theory] [InlineData("a", true)] [InlineData(" ", true)] public void IsNotEmpty_StrHasValueTests_ShouldBeTrue(string str, bool expected) { // Act & Assert str.IsNotEmpty().Should().Be(expected); } [Theory] [InlineData(null, false)] [InlineData("", false)] public void IsNotEmpty_InvalidString_ShouldBeFalse(string str, bool expected) { // Act & Assert str.IsNotEmpty().Should().Be(expected); } [Theory] [InlineData(null, true)] [InlineData("", true)] [InlineData(" ", true)] public void IsWhitespace_InvalidString_ShouldBeTrue(string str, bool expected) { // Act & Assert str.IsWhitespace().Should().Be(expected); } [Fact] public void IsWhitespace_StrHasNoWhitespace_ShouldBeFalse() { // Act & Assert "a".IsWhitespace().Should().BeFalse(); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData(" ", false)] [InlineData(" ", false)] public void IsNotWhitespace_InvalidString_ShouldBeFalse(string str, bool expected) { // Act & Assert str.IsNotWhitespace().Should().Be(expected); } [Fact] public void ToUri_StrIsUriWithoutSlash_ShouldBeWellFormedUri() { // Act & Assert "http://test.test".ToUri().Should().Be("http://test.test/"); } [Fact] public void ToUri_StrHasValeOfA_ShouldThrowUriFormatException() { // Act Action act = () => "a".ToUri(); // Assert act.ShouldThrow<UriFormatException>(); } [Fact] public void ToUri_NullString_ShouldThrowArgumentNullException() { // Act Action act = () => ((string) null).ToUri(); // Assert act.ShouldThrow<ArgumentNullException>(); } [Fact] public void ToInt_ValidString_ShouldBe1() { // Act "1".ToInt().Should().Be(1); } [Fact] public void ToInt_InvalidString_ShouldThrowFormatException() { // Act Action act = () => "a".ToInt(); // Assert act.ShouldThrow<FormatException>(); } [Fact] public void ToInt_InvalidString_ShouldThrowOverflowException() { // Act Action act = () => long.MinValue.ToString().ToInt(); // Assert act.ShouldThrow<OverflowException>(); } [Theory] [InlineData(" ", 0)] [InlineData(null, 0)] [InlineData("", 0)] public void ToInt_InvalidString_ShouldBe0(string str, int expected) { // Act str.ToInt().Should().Be(expected); } [Fact] public void ToShort_ValidString_ShouldBe1() { // Act "1".ToShort().Should().Be(1); } [Fact] public void ToShort_InvalidString_ShouldThrowFormatException() { // Act Action act = () => "a".ToShort(); // Assert act.ShouldThrow<FormatException>(); } [Fact] public void ToShort_InvalidString_ShouldThrowOverflowException() { // Act Action act = () => int.MaxValue.ToString().ToShort(); // Assert act.ShouldThrow<OverflowException>(); } [Theory] [InlineData(" ", 0)] [InlineData(null, 0)] [InlineData("", 0)] public void ToShort_InvalidString_ShouldBe0(string str, short expected) { // Act str.ToShort().Should().Be(expected); } [Fact] public void ToLong_ValidString_ShouldBe1() { // Act "1".ToShort().Should().Be(1); } [Fact] public void ToLong_InvalidString_ShouldThrowFormatException() { // Act Action act = () => "a".ToLong(); // Assert act.ShouldThrow<FormatException>(); } [Theory] [InlineData(" ", 0)] [InlineData(null, 0)] [InlineData("", 0)] public void ToLong_InvalidString_ShouldBe0(string str, long expected) { // Act str.ToLong().Should().Be(expected); } [Fact] public void ToBoolean_ValidStringIsTrue_ShouldBeTrue() { // Act "true".ToBoolean().Should().BeTrue(); } [Fact] public void ToBoolean_ValidStringIsFalse_ShouldBeFalse() { // Act "false".ToBoolean().Should().BeFalse(); } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Collections.ObjectModel; using SpatialAnalysis.FieldUtility; using SpatialAnalysis.Miscellaneous; namespace SpatialAnalysis.Agents.MandatoryScenario.Visualization { /// <summary> /// Interaction logic for GenerateSequenceUI.xaml /// </summary> public partial class GenerateSequenceUI : Window { #region Host Definition private static DependencyProperty _hostProperty = DependencyProperty.Register("_host", typeof(OSMDocument), typeof(GenerateSequenceUI), new FrameworkPropertyMetadata(null, GenerateSequenceUI.hostPropertyChanged, GenerateSequenceUI.PropertyCoerce)); private OSMDocument _host { get { return (OSMDocument)GetValue(_hostProperty); } set { SetValue(_hostProperty, value); } } private static void hostPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { GenerateSequenceUI instance = (GenerateSequenceUI)obj; instance._host = (OSMDocument)args.NewValue; } #endregion #region Sequence Definition private static DependencyProperty _sequenceProperty = DependencyProperty.Register("_sequence", typeof(Sequence), typeof(GenerateSequenceUI), new FrameworkPropertyMetadata(null, GenerateSequenceUI.sequencePropertyChanged, GenerateSequenceUI.PropertyCoerce)); private Sequence _sequence { get { return (Sequence)GetValue(_sequenceProperty); } set { SetValue(_sequenceProperty, value); } } private static void sequencePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { GenerateSequenceUI instance = (GenerateSequenceUI)obj; instance._sequence = (Sequence)args.NewValue; } #endregion private static object PropertyCoerce(DependencyObject obj, object value) { return value; } /// <summary> /// Initializes a new instance of the <see cref="GenerateSequenceUI"/> class. /// </summary> /// <param name="host">The main document to which this window belongs.</param> public GenerateSequenceUI(OSMDocument host) { InitializeComponent(); this._host = host; foreach (var item in this._host.AllActivities.Values) { this._availablePoentialFields.Items.Add(item); } this._up.Click += new RoutedEventHandler(_up_Click); this._add.Click += this._add_Click; this._remove.Click += this._remove_Click; this._down.Click += new RoutedEventHandler(_down_Click); this._okay.Click += this._okay_Click; this._addVisualAwareness.Click += _visibilityEvent_Click; this._existingSequences.ItemsSource = this._host.AgentMandatoryScenario.Sequences; this._existingSequences.DisplayMemberPath = "Name"; this._sequenceName.Text = "Sequence " + (this._host.AgentMandatoryScenario.Sequences.Count + 1).ToString(); this._sequenceName.Focus(); this._sequenceName.Select(0, this._sequenceName.Text.Length); this._includeVisualAwarenessField.Unchecked += _includeVisualAwarenessField_Unchecked; } /// <summary> /// Initializes a new instance of the <see cref="GenerateSequenceUI"/> class. /// </summary> /// <param name="host">The main document to which this window belongs.</param> /// <param name="sequence">The sequence.</param> public GenerateSequenceUI(OSMDocument host, Sequence sequence) { InitializeComponent(); this._host = host; this._sequence = sequence; foreach (var item in this._host.AllActivities.Values) { this._availablePoentialFields.Items.Add(item); //if (!this._sequence.ActivityNames.Contains(item.Name)) //{ // this._availablePoentialFields.Items.Add(item); //} } for (int i = 0; i < this._sequence.ActivityCount; i++) { this._orderedActivities.Items.Add(this._host.AllActivities[this._sequence.ActivityNames[i]]); } this._sequenceName.Visibility = System.Windows.Visibility.Collapsed; this._selectedSequenceName.Visibility = System.Windows.Visibility.Visible; this._selectedSequenceName.Text = sequence.Name; this._activationTime.Text = sequence.ActivationLambdaFactor.ToString(); this._up.Click += new RoutedEventHandler(_up_Click); this._add.Click += this._add_Click; this._remove.Click += this._remove_Click; this._down.Click += new RoutedEventHandler(_down_Click); this._okay.Click += this._edit_Click; this._addVisualAwareness.Click += _visibilityEvent_Click; this._existingSequences.ItemsSource = this._host.AgentMandatoryScenario.Sequences; this._existingSequences.DisplayMemberPath = "Name"; this._okay.Content = "Finish"; this._includeVisualAwarenessField.Unchecked += _includeVisualAwarenessField_Unchecked; this._includeVisualAwarenessField.IsChecked = this._sequence.HasVisualAwarenessField; } void _includeVisualAwarenessField_Unchecked(object sender, RoutedEventArgs e) { if (this._sequence != null && this._sequence.HasVisualAwarenessField) { this._sequence.VisualAwarenessField = null; } this._host.sequenceVisibilityEventHost.Clear(); } void _down_Click(object sender, RoutedEventArgs e) { try { int i = this._orderedActivities.SelectedIndex; if (this._orderedActivities.Items.Count > 1 && i < this._orderedActivities.Items.Count - 1) { object field = this._orderedActivities.SelectedItem; this._orderedActivities.Items.RemoveAt(i); this._orderedActivities.Items.Insert(i + 1, field); this._orderedActivities.SelectedIndex = i + 1; } } catch (Exception error) { MessageBox.Show(error.Report()); } } void _up_Click(object sender, RoutedEventArgs e) { try { int i = this._orderedActivities.SelectedIndex; if (this._orderedActivities.Items.Count > 1 && i > 0) { object field = this._orderedActivities.SelectedItem; this._orderedActivities.Items.RemoveAt(i); this._orderedActivities.Items.Insert(i - 1, field); this._orderedActivities.SelectedIndex = i - 1; } } catch (Exception error) { MessageBox.Show(error.Report()); } } void _okay_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(this._sequenceName.Text) || string.IsNullOrWhiteSpace(this._sequenceName.Text)) { MessageBox.Show("Enter a name for the new 'Sequence'", "Erorr", MessageBoxButton.OK, MessageBoxImage.Information); return; } else { foreach (var item in this._host.AgentMandatoryScenario.Sequences) { if (item.Name == this._sequenceName.Text) { MessageBox.Show("A 'Sequence' with the same already exists in the 'Scenario'", "Erorr", MessageBoxButton.OK, MessageBoxImage.Information); return; } } } double lambda = 0; if (!double.TryParse(this._activationTime.Text,out lambda)) { MessageBox.Show("Invalid input for 'Average Activation Time'!", "Erorr", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (lambda<=0) { MessageBox.Show("'Average Activation Time' should be larger than zero!", "Erorr", MessageBoxButton.OK, MessageBoxImage.Information); return; } var activities = new List<string>(); foreach (var item in this._orderedActivities.Items) { activities.Add((item as Activity).Name); } if (activities.Count==0) { MessageBox.Show("At leat one activity is needed for each Sequence", "Sequence Is Empty", MessageBoxButton.OK, MessageBoxImage.Information); return; } Sequence seq = new Sequence(activities, this._sequenceName.Text, lambda); if (this._includeVisualAwarenessField.IsChecked.Value) { if (this._host.sequenceVisibilityEventHost.VisualEvent == null) { var results = MessageBox.Show("Visual Awareness Field is not sssigned!", "invalid input", MessageBoxButton.OK, MessageBoxImage.Information); } else { seq.AssignVisualEvent(this._host.sequenceVisibilityEventHost.VisualEvent); } } this._host.AgentMandatoryScenario.Sequences.Add(seq); this.Close(); } void _edit_Click(object sender, RoutedEventArgs e) { double lambda = 0; if (!double.TryParse(this._activationTime.Text, out lambda)) { MessageBox.Show("Invalid input for 'Average Activation Time'!", "Erorr", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (lambda <= 0) { MessageBox.Show("'Average Activation Time' should be larger than zero!", "Erorr", MessageBoxButton.OK, MessageBoxImage.Information); return; } var activities = new List<string>(); foreach (var item in this._orderedActivities.Items) { activities.Add((item as Activity).Name); } if (activities.Count == 0) { MessageBox.Show("At leat one activity is needed for each Sequence", "Sequence Is Empty", MessageBoxButton.OK, MessageBoxImage.Information); return; } this._sequence.ActivityNames = activities; this._sequence.ActivationLambdaFactor = lambda; if (this._includeVisualAwarenessField.IsChecked.Value) { if (this._host.sequenceVisibilityEventHost.VisualEvent == null) { var results = MessageBox.Show("Visual Awareness Field is not sssigned!", "invalid input", MessageBoxButton.OK, MessageBoxImage.Information); } else { this._sequence.AssignVisualEvent(this._host.sequenceVisibilityEventHost.VisualEvent); } } this.Close(); } void _remove_Click(object sender, RoutedEventArgs e) { if (this._orderedActivities.SelectedIndex != -1) { Activity name = this._orderedActivities.SelectedItem as Activity; this._orderedActivities.Items.RemoveAt(this._orderedActivities.SelectedIndex); //this._availablePoentialFields.Items.Add(name); } } void _add_Click(object sender, RoutedEventArgs e) { try { if (this._availablePoentialFields.SelectedIndex != -1) { var name = this._availablePoentialFields.SelectedItem; //this._availablePoentialFields.Items.RemoveAt(this._availablePoentialFields.SelectedIndex); this._orderedActivities.Items.Add(name); } } catch (Exception error) { MessageBox.Show(error.Report()); } } void _visibilityEvent_Click(object sender, RoutedEventArgs e) { this._host.sequenceVisibilityEventHost.Clear(); this.Owner.Hide(); this.Hide(); this._host.sequenceVisibilityEventHost.SetVisualEvents(visualEventWindowClosed); } void visualEventWindowClosed(object sender, EventArgs e) { this.ShowDialog(); this.Owner.ShowDialog(); } protected override void OnClosed(EventArgs e) { this._host.sequenceVisibilityEventHost.Clear(); base.OnClosed(e); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoMapper; using AutoMapper.QueryableExtensions; using DelegateDecompiler; using DelegateDecompiler.EntityFramework; using JetBrains.Annotations; using RepositoryPattern.Domain; using RepositoryPattern.Domain.Database; namespace RepositoryPattern.Infrastructure { public class EfDbQueryable<T> : IOrderedDbQueryable<T> { private IQueryable<T> _queryable; public EfDbQueryable([NotNull] IQueryable<T> queryable) { if (queryable == null) throw new ArgumentNullException(nameof(queryable)); _queryable = queryable; } public IDbQueryable<T> Where(Expression<Func<T, bool>> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); _queryable = _queryable.Where(predicate); return this; } public IDbQueryable<T> Where(Expression<Func<T, int, bool>> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); _queryable = _queryable.Where(predicate); return this; } public IDbQueryable<T> Take(int count) { _queryable = _queryable.Take(count); return this; } public IDbQueryable<T> Skip(int count) { _queryable = _queryable.Skip(count); return this; } public IDbQueryable<T> Distinct() { _queryable = _queryable.Distinct(); return this; } public IDbQueryable<TResult> Select<TResult>(Expression<Func<T, TResult>> selector) { if (selector == null) throw new ArgumentNullException(nameof(selector)); return new EfDbQueryable<TResult>(_queryable.Select(selector)); } public IOrderedDbQueryable<T> OrderBy<TKey>(Expression<Func<T, TKey>> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var orderedQueryable = _queryable.OrderBy(keySelector); _queryable = orderedQueryable; return this; } public IOrderedDbQueryable<T> OrderByDescending<TKey>(Expression<Func<T, TKey>> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var orderedQueryable = _queryable.OrderBy(keySelector); _queryable = orderedQueryable; return this; } public IOrderedDbQueryable<T> ThenBy<TKey>(Expression<Func<T, TKey>> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var orderedQueryable = _queryable as IOrderedQueryable<T>; if (orderedQueryable == null) throw new InvalidOperationException("Query is not yet sorted"); _queryable = orderedQueryable.ThenBy(keySelector); return this; } public IOrderedDbQueryable<T> ThenByDescending<TKey>(Expression<Func<T, TKey>> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var orderedQueryable = _queryable as IOrderedQueryable<T>; if (orderedQueryable == null) throw new InvalidOperationException("Query is not yet sorted"); _queryable = orderedQueryable.ThenByDescending(keySelector); return this; } // FirstOrDefault public async Task<T> FirstOrDefaultAsync() => await LastCall(_queryable).FirstOrDefaultAsync().ConfigureAwait(false); // First public async Task<T> FirstAsync() => await LastCall(_queryable).FirstAsync().ConfigureAwait(false); // SingleOrDefault public async Task<T> SingleOrDefaultAsync() => await LastCall(_queryable).SingleOrDefaultAsync().ConfigureAwait(false); // Single public async Task<T> SingleAsync() => await LastCall(_queryable).SingleOrDefaultAsync().ConfigureAwait(false); public async Task<List<T>> ToListAsync() => await LastCall(_queryable).ToListAsync().ConfigureAwait(false); public async Task<Dictionary<TKey, TValue>> ToDictionaryAsync<TKey, TValue>(Func<T, TKey> keySelector, Func<T, TValue> elementSelector) => await LastCall(_queryable).ToDictionaryAsync(keySelector, elementSelector).ConfigureAwait(false); public async Task<T[]> ToArrayAsync() => await LastCall(_queryable).ToArrayAsync().ConfigureAwait(false); public async Task<bool> AnyAsync() => await LastCall(_queryable).AnyAsync().ConfigureAwait(false); public async Task<bool> AllAsync(Expression<Func<T, bool>> predicate) => await LastCall(_queryable).AllAsync(predicate).ConfigureAwait(false); public async Task<bool> ContainsAsync(T item) => await LastCall(_queryable).ContainsAsync(item).ConfigureAwait(false); public async Task<int> CountAsync() => await LastCall(_queryable).CountAsync().ConfigureAwait(false); public async Task<long> LongCountAsync() => await LastCall(_queryable).LongCountAsync().ConfigureAwait(false); public async Task<T> MinAsync() => await LastCall(_queryable).MinAsync().ConfigureAwait(false); public async Task<T> MaxAsync() => await LastCall(_queryable).MaxAsync().ConfigureAwait(false); public IDbQueryable<TResult> Join<TInner, TKey, TResult>( IEnumerable<TInner> inner, Expression<Func<T, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<T, TInner, TResult>> resultSelector) { if (inner == null) throw new ArgumentNullException(nameof(inner)); if (outerKeySelector == null) throw new ArgumentNullException(nameof(outerKeySelector)); if (innerKeySelector == null) throw new ArgumentNullException(nameof(innerKeySelector)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return new EfDbQueryable<TResult>(_queryable.Join(inner, outerKeySelector, innerKeySelector, resultSelector)); } public async Task<List<TDestination>> ProjectToListAsync<TDestination>(IConfigurationProvider config) { return await LastCall(_queryable.ProjectTo<TDestination>(config)).ToListAsync(); } public async Task<TDestination[]> ProjectToArrayAsync<TDestination>(IConfigurationProvider config) { return await LastCall(_queryable.ProjectTo<TDestination>(config)).ToArrayAsync(); } public async Task<TDestination> ProjectToSingleOrDefaultAsync<TDestination>(IConfigurationProvider config) { return await LastCall(_queryable.ProjectTo<TDestination>(config)).SingleOrDefaultAsync(); } public async Task<TDestination> ProjectToSingleAsync<TDestination>(IConfigurationProvider config) { return await LastCall(_queryable.ProjectTo<TDestination>(config)).SingleAsync(); } public async Task<TDestination> ProjectToFirstOrDefaultAsync<TDestination>(IConfigurationProvider config) { return await LastCall(_queryable.ProjectTo<TDestination>(config)).FirstOrDefaultAsync(); } public async Task<TDestination> ProjectToFirstAsync<TDestination>(IConfigurationProvider config) { return await LastCall(_queryable.ProjectTo<TDestination>(config)).FirstAsync(); } public IQueryable<TDestination> ProjectToQueryable<TDestination>(IConfigurationProvider config) { return LastCall(_queryable.ProjectTo<TDestination>()); } public IQueryable<T> AsQueryable() { return _queryable; } public IOrderedQueryable<T> AsOrderedQueryable() { return (IOrderedQueryable<T>)_queryable; } public IDbQueryable<T> WithExpression(Func<IQueryable<T>, IQueryable<T>> expression) { _queryable = expression.Invoke(_queryable); return this; } private static IQueryable<TItem> LastCall<TItem>([NotNull] IQueryable<TItem> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); if (predicate.Provider is IDbAsyncQueryProvider) return predicate.DecompileAsync(); return predicate; } } }
using UnityEngine; using UnityEditor; using PrimitivePlus; using System.Collections; namespace PrimitivePlusEditor { public class PrimitivePlusMenuItems { #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/2D Objects/Circle2D", false, -1)] #else [MenuItem("GameObject/Primitive Plus/2D Objects/Circle2D", false, -1)] #endif private static void CreateCircle2D(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Circle2D), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/2D Objects/CircleHalf2D", false, -1)] #else [MenuItem("GameObject/Primitive Plus/2D Objects/CircleHalf2D", false, -1)] #endif private static void CreateCircleHalf2D(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.CircleHalf2D), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Cone", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Cone", false, -1)] #endif private static void CreateCone(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Cone), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/ConeHalf", false, -1)] #else [MenuItem("GameObject/Primitive Plus/ConeHalf", false, -1)] #endif private static void CreateConeHalf(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.ConeHalf), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/ConeHexagon", false, -1)] #else [MenuItem("GameObject/Primitive Plus/ConeHexagon", false, -1)] #endif private static void CreateConeHexagon(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.ConeHexagon), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/ConePentagon", false, -1)] #else [MenuItem("GameObject/Primitive Plus/ConePentagon", false, -1)] #endif private static void CreateConePentagon(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.ConePentagon), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Cross", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Cross", false, -1)] #endif private static void CreateCross(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Cross), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/2D Objects/Cross2D", false, -1)] #else [MenuItem("GameObject/Primitive Plus/2D Objects/Cross2D", false, -1)] #endif private static void CreateCross2D(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Cross2D), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Cube", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Cube", false, -1)] #endif private static void CreateCube(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Cube), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/CubeCorner", false, -1)] #else [MenuItem("GameObject/Primitive Plus/CubeCorner", false, -1)] #endif private static void CreateCubeCorner(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.CubeCorner), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/CubeCornerThin", false, -1)] #else [MenuItem("GameObject/Primitive Plus/CubeCornerThin", false, -1)] #endif private static void CreateCubeCornerThin(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.CubeCornerThin), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/CubeEdgeIn", false, -1)] #else [MenuItem("GameObject/Primitive Plus/CubeEdgeIn", false, -1)] #endif private static void CreateCubeEdgeIn(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.CubeEdgeIn), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/CubeEdgeOut", false, -1)] #else [MenuItem("GameObject/Primitive Plus/CubeEdgeOut", false, -1)] #endif private static void CreateCubeEdgeOut(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.CubeEdgeOut), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/CubeHollow", false, -1)] #else [MenuItem("GameObject/Primitive Plus/CubeHollow", false, -1)] #endif private static void CreateCubeHollow(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.CubeHollow), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/CubeHollowThin", false, -1)] #else [MenuItem("GameObject/Primitive Plus/CubeHollowThin", false, -1)] #endif private static void CreateCubeHollowThin(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.CubeHollowThin), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/CubeTube", false, -1)] #else [MenuItem("GameObject/Primitive Plus/CubeTube", false, -1)] #endif private static void CreateCubeTube(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.CubeTube), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Cylinder", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Cylinder", false, -1)] #endif private static void CreateCylinder(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Cylinder), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/CylinderHalf", false, -1)] #else [MenuItem("GameObject/Primitive Plus/CylinderHalf", false, -1)] #endif private static void CreateCylinderHalf(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.CylinderHalf), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/CylinderTube", false, -1)] #else [MenuItem("GameObject/Primitive Plus/CylinderTube", false, -1)] #endif private static void CreateCylinderTube(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.CylinderTube), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/CylinderTubeThin", false, -1)] #else [MenuItem("GameObject/Primitive Plus/CylinderTubeThin", false, -1)] #endif private static void CreateCylinderTubeThin(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.CylinderTubeThin), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Diamond", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Diamond", false, -1)] #endif private static void CreateDiamond(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Diamond), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/DiamondThick", false, -1)] #else [MenuItem("GameObject/Primitive Plus/DiamondThick", false, -1)] #endif private static void CreateDiamondThick(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.DiamondThick), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Heart", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Heart", false, -1)] #endif private static void CreateHeart(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Heart), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/2D Objects/Heart2D", false, -1)] #else [MenuItem("GameObject/Primitive Plus/2D Objects/Heart2D", false, -1)] #endif private static void CreateHeart2D(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Heart2D), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/2D Objects/Hexagon2D", false, -1)] #else [MenuItem("GameObject/Primitive Plus/2D Objects/Hexagon2D", false, -1)] #endif private static void CreateHexagon2D(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Hexagon2D), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Icosphere", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Icosphere", false, -1)] #endif private static void CreateIcosphere(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Icosphere), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/IcosphereSmall", false, -1)] #else [MenuItem("GameObject/Primitive Plus/IcosphereSmall", false, -1)] #endif private static void CreateIcosphereSmall(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.IcosphereSmall), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Plane", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Plane", false, -1)] #endif private static void CreatePlane(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Plane), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/PrismHexagon", false, -1)] #else [MenuItem("GameObject/Primitive Plus/PrismHexagon", false, -1)] #endif private static void CreatePrismHexagon(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.PrismHexagon), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/PrismOctagon", false, -1)] #else [MenuItem("GameObject/Primitive Plus/PrismOctagon", false, -1)] #endif private static void CreatePrismOctagon(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.PrismOctagon), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/PrismPentagon", false, -1)] #else [MenuItem("GameObject/Primitive Plus/PrismPentagon", false, -1)] #endif private static void CreatePrismPentagon(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.PrismPentagon), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/PrismTriangle", false, -1)] #else [MenuItem("GameObject/Primitive Plus/PrismTriangle", false, -1)] #endif private static void CreatePrismTriangle(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.PrismTriangle), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Pyramid", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Pyramid", false, -1)] #endif private static void CreatePyramid(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Pyramid), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/PyramidCorner", false, -1)] #else [MenuItem("GameObject/Primitive Plus/PyramidCorner", false, -1)] #endif private static void CreatePyramidCorner(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.PyramidCorner), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/PyramidTri", false, -1)] #else [MenuItem("GameObject/Primitive Plus/PyramidTri", false, -1)] #endif private static void CreatePyramidTri(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.PyramidTri), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/2D Objects/Rhombus2D", false, -1)] #else [MenuItem("GameObject/Primitive Plus/2D Objects/Rhombus2D", false, -1)] #endif private static void CreateRhombus2D(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Rhombus2D), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Sphere", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Sphere", false, -1)] #endif private static void CreateSphere(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Sphere), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/SphereHalf", false, -1)] #else [MenuItem("GameObject/Primitive Plus/SphereHalf", false, -1)] #endif private static void CreateSphereHalf(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.SphereHalf), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Star", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Star", false, -1)] #endif private static void CreateStar(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Star), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/2D Objects/Star2D", false, -1)] #else [MenuItem("GameObject/Primitive Plus/2D Objects/Star2D", false, -1)] #endif private static void CreateStar2D(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Star2D), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Torus", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Torus", false, -1)] #endif private static void CreateTorus(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Torus), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/TorusHalf", false, -1)] #else [MenuItem("GameObject/Primitive Plus/TorusHalf", false, -1)] #endif private static void CreateTorusHalf(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.TorusHalf), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/2D Objects/Triangle2D", false, -1)] #else [MenuItem("GameObject/Primitive Plus/2D Objects/Triangle2D", false, -1)] #endif private static void CreateTriangle2D(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Triangle2D), (GameObject)command.context); } #if UNITY_4_5 [MenuItem("GameObject/Create Other/Primitive Plus/Wedge", false, -1)] #else [MenuItem("GameObject/Primitive Plus/Wedge", false, -1)] #endif private static void CreateWedge(MenuCommand command) { AddPrimitiveObjectToScene(PrimitivePlusObject.CreatePrimitivePlus(PrimitivePlusType.Wedge), (GameObject)command.context); } private static void AddPrimitiveObjectToScene(GameObject primitiveObject, GameObject selectedGameObject) { Vector3 newPosition = Vector3.zero; for(int i = 0; i < SceneView.sceneViews.Count; i++) { if(SceneView.sceneViews[i] != null) { if(selectedGameObject == null) newPosition = ((SceneView)SceneView.sceneViews[i]).pivot; break; } } primitiveObject.transform.rotation = Quaternion.identity; if(selectedGameObject != null) primitiveObject.transform.parent = Selection.activeGameObject.transform; primitiveObject.transform.localPosition = newPosition; Selection.activeGameObject = primitiveObject; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Authentication; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace RedditSharp.Things { public class Post : VotableThing { private const string CommentUrl = "/api/comment"; private const string RemoveUrl = "/api/remove"; private const string DelUrl = "/api/del"; private const string GetCommentsUrl = "/comments/{0}.json"; private const string ApproveUrl = "/api/approve"; private const string EditUserTextUrl = "/api/editusertext"; private const string HideUrl = "/api/hide"; private const string UnhideUrl = "/api/unhide"; private const string SetFlairUrl = "/api/flair"; private const string MarkNSFWUrl = "/api/marknsfw"; private const string UnmarkNSFWUrl = "/api/unmarknsfw"; private const string ContestModeUrl = "/api/set_contest_mode"; [JsonIgnore] private Reddit Reddit { get; set; } [JsonIgnore] private IWebAgent WebAgent { get; set; } public Post Init(Reddit reddit, JToken post, IWebAgent webAgent) { CommonInit(reddit, post, webAgent); JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings); return this; } public async Task<Post> InitAsync(Reddit reddit, JToken post, IWebAgent webAgent) { CommonInit(reddit, post, webAgent); await Task.Factory.StartNew(() => JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings)); return this; } private void CommonInit(Reddit reddit, JToken post, IWebAgent webAgent) { base.Init(reddit, webAgent, post); Reddit = reddit; WebAgent = webAgent; } [JsonProperty("author")] public string AuthorName { get; set; } [JsonIgnore] public RedditUser Author { get { return Reddit.GetUser(AuthorName); } } public Comment[] Comments { get { return ListComments().ToArray(); } } [JsonProperty("approved_by")] public string ApprovedBy { get; set; } [JsonProperty("author_flair_css_class")] public string AuthorFlairCssClass { get; set; } [JsonProperty("author_flair_text")] public string AuthorFlairText { get; set; } [JsonProperty("banned_by")] public string BannedBy { get; set; } [JsonProperty("domain")] public string Domain { get; set; } [JsonProperty("edited")] public bool Edited { get; set; } [JsonProperty("is_self")] public bool IsSelfPost { get; set; } [JsonProperty("link_flair_css_class")] public string LinkFlairCssClass { get; set; } [JsonProperty("link_flair_text")] public string LinkFlairText { get; set; } [JsonProperty("num_comments")] public int CommentCount { get; set; } [JsonProperty("over_18")] public bool NSFW { get; set; } [JsonProperty("permalink")] [JsonConverter(typeof(UrlParser))] public Uri Permalink { get; set; } [JsonProperty("score")] public int Score { get; set; } [JsonProperty("selftext")] public string SelfText { get; set; } [JsonProperty("selftext_html")] public string SelfTextHtml { get; set; } [JsonProperty("subreddit")] public string Subreddit { get; set; } [JsonProperty("thumbnail")] [JsonConverter(typeof(UrlParser))] public Uri Thumbnail { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("url")] [JsonConverter(typeof(UrlParser))] public Uri Url { get; set; } [JsonProperty("num_reports")] public int? Reports { get; set; } public Comment Comment(string message) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(CommentUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { text = message, thing_id = FullName, uh = Reddit.User.Modhash, api_type = "json" }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(data); if (json["json"]["ratelimit"] != null) throw new RateLimitException(TimeSpan.FromSeconds(json["json"]["ratelimit"].ValueOrDefault<double>())); return new Comment().Init(Reddit, json["json"]["data"]["things"][0], WebAgent, this); } private string SimpleAction(string endpoint) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(endpoint); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); return data; } private string SimpleActionToggle(string endpoint, bool value) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(endpoint); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, state = value, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); return data; } public void Approve() { var data = SimpleAction(ApproveUrl); } public void Remove() { RemoveImpl(false); } public void RemoveSpam() { RemoveImpl(true); } private void RemoveImpl(bool spam) { var request = WebAgent.CreatePost(RemoveUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, spam = spam, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); } public void Del() { var data = SimpleAction(DelUrl); } public void Hide() { var data = SimpleAction(HideUrl); } public void Unhide() { var data = SimpleAction(UnhideUrl); } public void MarkNSFW() { var data = SimpleAction(MarkNSFWUrl); } public void UnmarkNSFW() { var data = SimpleAction(UnmarkNSFWUrl); } public void ContestMode(bool state) { var data = SimpleActionToggle(ContestModeUrl, state); } #region Obsolete Getter Methods [Obsolete("Use Comments property instead")] public Comment[] GetComments() { return Comments; } #endregion Obsolete Getter Methods /// <summary> /// Replaces the text in this post with the input text. /// </summary> /// <param name="newText">The text to replace the post's contents</param> public void EditText(string newText) { if (Reddit.User == null) throw new Exception("No user logged in."); if (!IsSelfPost) throw new Exception("Submission to edit is not a self-post."); var request = WebAgent.CreatePost(EditUserTextUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", text = newText, thing_id = FullName, uh = Reddit.User.Modhash }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); JToken json = JToken.Parse(result); if (json["json"].ToString().Contains("\"errors\": []")) SelfText = newText; else throw new Exception("Error editing text."); } public void Update() { JToken post = Reddit.GetToken(this.Url); JsonConvert.PopulateObject(post["data"].ToString(), this, Reddit.JsonSerializerSettings); } public void SetFlair(string flairText, string flairClass) { if (Reddit.User == null) throw new Exception("No user logged in."); var request = WebAgent.CreatePost(SetFlairUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", r = Subreddit, css_class = flairClass, link = FullName, //name = Name, text = flairText, uh = Reddit.User.Modhash }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(result); LinkFlairText = flairText; } public List<Comment> ListComments(int? limit = null) { var url = string.Format(GetCommentsUrl, Id); if (limit.HasValue) { var query = HttpUtility.ParseQueryString(string.Empty); query.Add("limit", limit.Value.ToString()); url = string.Format("{0}?{1}", url, query); } var request = WebAgent.CreateGet(url); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JArray.Parse(data); var postJson = json.Last()["data"]["children"]; var comments = new List<Comment>(); foreach (var comment in postJson) { comments.Add(new Comment().Init(Reddit, comment, WebAgent, this)); } return comments; } } }
#if UNITY_EDITOR using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; using UMA; using UMA.Integrations; namespace UMAEditor { public class DNAMasterEditor { //DynamicUMADna:: the following dictionary also needs to use dnaTypeHashes now private readonly Dictionary<int, DNASingleEditor> _dnaValues = new Dictionary<int, DNASingleEditor>(); private readonly int[] _dnaTypeHashes; private readonly Type[] _dnaTypes; private readonly string[] _dnaTypeNames; public int viewDna = 0; public UMAData.UMARecipe recipe; public static UMAGeneratorBase umaGenerator; public DNAMasterEditor(UMAData.UMARecipe recipe) { this.recipe = recipe; UMADnaBase[] allDna = recipe.GetAllDna(); _dnaTypes = new Type[allDna.Length]; //DynamicUMADna:: we need the hashes here too _dnaTypeHashes = new int[allDna.Length]; _dnaTypeNames = new string[allDna.Length]; for (int i = 0; i < allDna.Length; i++) { var entry = allDna[i]; var entryType = entry.GetType(); _dnaTypes[i] = entryType; //DynamicUMADna:: we need to use typehashes now _dnaTypeHashes[i] = entry.DNATypeHash; if (entry is DynamicUMADnaBase) { var dynamicDna = entry as DynamicUMADnaBase; if (dynamicDna.dnaAsset != null) { _dnaTypeNames[i] = dynamicDna.dnaAsset.name + " (DynamicUMADna)"; } else { _dnaTypeNames[i] = "Default " + i + " (DynamicUMADna)"; } } else { _dnaTypeNames[i] = entryType.Name; } _dnaValues[entry.DNATypeHash] = new DNASingleEditor(entry); } } public bool OnGUI(ref bool _dnaDirty, ref bool _textureDirty, ref bool _meshDirty) { GUILayout.BeginHorizontal(); var newToolBarIndex = EditorGUILayout.Popup("DNA", viewDna, _dnaTypeNames); if (newToolBarIndex != viewDna) { viewDna = newToolBarIndex; } GUI.enabled = viewDna >= 0; if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(24))) { if (viewDna >= 0) { //DynamicUMADna:: This needs to use the hash recipe.RemoveDna(_dnaTypeHashes[viewDna]); if (viewDna >= _dnaTypes.Length - 1) viewDna--; GUI.enabled = true; GUILayout.EndHorizontal(); _dnaDirty = true; return true; } } GUI.enabled = true; GUILayout.EndHorizontal(); if (viewDna >= 0) { //DynamicUMADna:: We need to use _dnaTypeHashes now int dnaTypeHash = _dnaTypeHashes[viewDna]; if (_dnaValues[dnaTypeHash].OnGUI()) { _dnaDirty = true; return true; } } return false; } internal bool NeedsReenable() { return _dnaValues == null; } public bool IsValid { get { return !(_dnaTypes == null || _dnaTypes.Length == 0); } } } public class DNASingleEditor { private readonly SortedDictionary<string, DNAGroupEditor> _groups = new SortedDictionary<string, DNAGroupEditor>(); public DNASingleEditor(UMADnaBase dna) { //DynamicUMADna:: needs a different set up if (dna.GetType().ToString().IndexOf("DynamicUMADna") > -1) { string[] dnaNames = ((DynamicUMADnaBase)dna).Names; for (int i = 0; i < dnaNames.Length; i++) { string fieldName = ObjectNames.NicifyVariableName(dnaNames[i]); string groupName = "Other"; string[] chunks = fieldName.Split(' '); if (chunks.Length > 1) { groupName = chunks[0]; fieldName = fieldName.Substring(groupName.Length + 1); } DNAGroupEditor group; _groups.TryGetValue(groupName, out @group); if (group == null) { @group = new DNAGroupEditor(groupName); _groups.Add(groupName, @group); } var entry = new DNAFieldEditor(fieldName, dnaNames[i], dna.GetValue(i), dna); @group.Add(entry); } foreach (var group in _groups.Values) @group.Sort(); } else { var fields = dna.GetType().GetFields(); foreach (FieldInfo field in fields) { if (field.FieldType != typeof(float)) { continue; } string fieldName; string groupName; GetNamesFromField(field, out fieldName, out groupName); DNAGroupEditor group; _groups.TryGetValue(groupName, out @group); if (group == null) { @group = new DNAGroupEditor(groupName); _groups.Add(groupName, @group); } var entry = new DNAFieldEditor(fieldName, field, dna); @group.Add(entry); } foreach (var group in _groups.Values) @group.Sort(); } } private static void GetNamesFromField(FieldInfo field, out string fieldName, out string groupName) { fieldName = ObjectNames.NicifyVariableName(field.Name); groupName = "Other"; string[] chunks = fieldName.Split(' '); if (chunks.Length > 1) { groupName = chunks[0]; fieldName = fieldName.Substring(groupName.Length + 1); } } public bool OnGUI() { bool changed = false; foreach (var dnaGroup in _groups.Values) { changed |= dnaGroup.OnGUI(); } return changed; } } public class DNAGroupEditor { private readonly List<DNAFieldEditor> _fields = new List<DNAFieldEditor>(); private readonly string _groupName; private bool _foldout = true; public DNAGroupEditor(string groupName) { _groupName = groupName; } public bool OnGUI() { _foldout = EditorGUILayout.Foldout(_foldout, _groupName); if (!_foldout) return false; bool changed = false; GUILayout.BeginVertical(EditorStyles.textField); foreach (var field in _fields) { changed |= field.OnGUI(); } GUILayout.EndVertical(); return changed; } public void Add(DNAFieldEditor field) { _fields.Add(field); } public void Sort() { _fields.Sort(DNAFieldEditor.comparer); } } public class DNAFieldEditor { public static Comparer comparer = new Comparer(); private readonly UMADnaBase _dna; private readonly FieldInfo _field; //DynamicUmaDna:: requires the following private readonly string _realName; private readonly string _name; private readonly float _value; //DynamicUmaDna:: needs a different constructor public DNAFieldEditor(string name, string realName, float value, UMADnaBase dna) { _name = name; _realName = realName; _dna = dna; _value = value; } public DNAFieldEditor(string name, FieldInfo field, UMADnaBase dna) { _name = name; _field = field; _dna = dna; _value = (float)field.GetValue(dna); } public bool OnGUI() { float newValue = EditorGUILayout.Slider(_name, _value, 0f, 1f); //float newValue = EditorGUILayout.FloatField(_name, _value); if (newValue != _value) { //DynamicUmaDna:: we need a different setter if (_dna.GetType().ToString().IndexOf("DynamicUMADna") > -1) { ((DynamicUMADnaBase)_dna).SetValue(_realName, newValue); } else { _field.SetValue(_dna, newValue); } return true; } return false; } public class Comparer : IComparer<DNAFieldEditor> { public int Compare(DNAFieldEditor x, DNAFieldEditor y) { return String.CompareOrdinal(x._name, y._name); } } } public class SharedColorsCollectionEditor { private bool _foldout = true; static int selectedChannelCount = 2; String[] names = new string[4] { "1", "2", "3", "4" }; int[] channels = new int[4] { 1, 2, 3, 4 }; static bool[] _ColorFoldouts = new bool[0]; public bool OnGUI(UMAData.UMARecipe _recipe) { GUILayout.BeginHorizontal(EditorStyles.toolbarButton); GUILayout.Space(10); _foldout = EditorGUILayout.Foldout(_foldout, "Shared Colors"); GUILayout.EndHorizontal(); if (_foldout) { bool changed = false; GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f)); EditorGUILayout.BeginHorizontal(); if (_recipe.sharedColors == null) _recipe.sharedColors = new OverlayColorData[0]; if (_recipe.sharedColors.Length == 0) { selectedChannelCount = EditorGUILayout.IntPopup("Channels", selectedChannelCount, names, channels); //DOS these buttons all in a row pushes the UI too wide EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); } else { selectedChannelCount = _recipe.sharedColors[0].channelMask.Length; } if (GUILayout.Button("Add Shared Color")) { List<OverlayColorData> sharedColors = new List<OverlayColorData>(); sharedColors.AddRange(_recipe.sharedColors); sharedColors.Add(new OverlayColorData(selectedChannelCount)); sharedColors[sharedColors.Count - 1].name = "Shared Color " + sharedColors.Count; _recipe.sharedColors = sharedColors.ToArray(); changed = true; } if (GUILayout.Button("Save Collection")) { changed = true; } EditorGUILayout.EndHorizontal(); if (_ColorFoldouts.Length != _recipe.sharedColors.Length) { Array.Resize<bool>(ref _ColorFoldouts, _recipe.sharedColors.Length); } for (int i = 0; i < _recipe.sharedColors.Length; i++) { bool del = false; OverlayColorData ocd = _recipe.sharedColors[i]; GUIHelper.FoldoutBar(ref _ColorFoldouts[i], i + ": " + ocd.name, out del); if (del) { List<OverlayColorData> temp = new List<OverlayColorData>(); temp.AddRange(_recipe.sharedColors); temp.RemoveAt(i); _recipe.sharedColors = temp.ToArray(); //DOS this wasn't setting changed = true changed = true; // TODO: if all the shared colors are deleted anything that was set to use them //fixed @1022 by checking the shared color still exists break; } if (_ColorFoldouts[i]) { if (ocd.name == null) ocd.name = ""; string NewName = EditorGUILayout.TextField("Name", ocd.name); if (NewName != ocd.name) { ocd.name = NewName; //changed = true; } Color NewChannelMask = EditorGUILayout.ColorField("Color Multiplier", ocd.channelMask[0]); if (ocd.channelMask[0] != NewChannelMask) { ocd.channelMask[0] = NewChannelMask; changed = true; } Color NewChannelAdditiveMask = EditorGUILayout.ColorField("Color Additive", ocd.channelAdditiveMask[0]); if (ocd.channelAdditiveMask[0] != NewChannelAdditiveMask) { ocd.channelAdditiveMask[0] = NewChannelAdditiveMask; changed = true; } for (int j = 1; j < ocd.channelMask.Length; j++) { NewChannelMask = EditorGUILayout.ColorField("Texture " + j + "multiplier", ocd.channelMask[j]); if (ocd.channelMask[j] != NewChannelMask) { ocd.channelMask[j] = NewChannelMask; changed = true; } NewChannelAdditiveMask = EditorGUILayout.ColorField("Texture " + j + " additive", ocd.channelAdditiveMask[j]); if (ocd.channelAdditiveMask[j] != NewChannelAdditiveMask) { ocd.channelAdditiveMask[j] = NewChannelAdditiveMask; changed = true; } } } } GUIHelper.EndVerticalPadded(10); return changed; } return false; } } public class SlotMasterEditor { // the last slot dropped. Must live between instances. public static string LastSlot=""; // track open/closed here. Must live between instances. public static Dictionary<string, bool> OpenSlots = new Dictionary<string, bool>(); //DOS Changed this to protected so childs can inherit protected readonly UMAData.UMARecipe _recipe; //DOS Changed this to protected so childs can inherit protected readonly List<SlotEditor> _slotEditors = new List<SlotEditor>(); //DOS Changed this to protected so childs can inherit protected readonly SharedColorsCollectionEditor _sharedColorsEditor = new SharedColorsCollectionEditor(); //DOS Changed this to protected so childs can inherit protected bool DropAreaGUI(Rect dropArea) { int count = 0; var evt = Event.current; if (evt.type == EventType.DragUpdated) { if (dropArea.Contains(evt.mousePosition)) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; } } if (evt.type == EventType.DragPerform) { if (dropArea.Contains(evt.mousePosition)) { DragAndDrop.AcceptDrag(); UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[]; for (int i = 0; i < draggedObjects.Length; i++) { if (draggedObjects[i]) { SlotDataAsset tempSlotDataAsset = draggedObjects[i] as SlotDataAsset; if (tempSlotDataAsset) { LastSlot = tempSlotDataAsset.slotName; AddSlotDataAsset(tempSlotDataAsset); count++; continue; } var path = AssetDatabase.GetAssetPath(draggedObjects[i]); if (System.IO.Directory.Exists(path)) { RecursiveScanFoldersForAssets(path, ref count); } } } if (count > 0) { return true; } } } return false; } //DOS Changed this to protected so childs can inherit protected void AddSlotDataAsset(SlotDataAsset added) { var slot = new SlotData(added); _recipe.MergeSlot(slot, false); } //DOS Changed this to protected so childs can inherit protected void RecursiveScanFoldersForAssets(string path, ref int count) { var assetFiles = System.IO.Directory.GetFiles(path, "*.asset"); foreach (var assetFile in assetFiles) { var tempSlotDataAsset = AssetDatabase.LoadAssetAtPath(assetFile, typeof(SlotDataAsset)) as SlotDataAsset; if (tempSlotDataAsset) { count++; AddSlotDataAsset(tempSlotDataAsset); } } foreach (var subFolder in System.IO.Directory.GetDirectories(path)) { RecursiveScanFoldersForAssets(subFolder.Replace('\\', '/'), ref count); } } public SlotMasterEditor(UMAData.UMARecipe recipe) { _recipe = recipe; if (recipe.slotDataList == null) { recipe.slotDataList = new SlotData[0]; } for (int i = 0; i < recipe.slotDataList.Length; i++) { var slot = recipe.slotDataList[i]; if (slot == null) continue; _slotEditors.Add(new SlotEditor(_recipe, slot, i)); } if (_slotEditors.Count > 1) { // Don't juggle the order - this way, they're in the order they're in the file, or dropped in. List<SlotEditor> sortedSlots = new List<SlotEditor>(_slotEditors); sortedSlots.Sort(SlotEditor.comparer); var overlays1 = sortedSlots[0].GetOverlays(); var overlays2 = sortedSlots[1].GetOverlays(); for (int i = 0; i < sortedSlots.Count - 2; i++) { if (overlays1 == overlays2) sortedSlots[i].sharedOverlays = true; overlays1 = overlays2; overlays2 = sortedSlots[i + 2].GetOverlays(); } } } //DOS made this virtual so children can override public virtual bool OnGUI(ref bool _dnaDirty, ref bool _textureDirty, ref bool _meshDirty) { bool changed = false; //DynamicCharacterSystem:: Wardrobe recipes dont need a race set here as they have their own list of compatible races //Its also better if a race IS NOT SET so that we dont get warnings when rendering about things being incompatible //It would be great to disable the following in that case but unfortunately _recipe is UMAData.UMARecipe - so we cant fix this right now... // Have to be able to assign a race on a new recipe. RaceData newRace = (RaceData)EditorGUILayout.ObjectField("RaceData", _recipe.raceData, typeof(RaceData), false); if (_recipe.raceData == null) { GUIHelper.BeginVerticalPadded(10, new Color(0.55f, 0.25f, 0.25f)); GUILayout.Label("Warning: No race data is set!"); GUIHelper.EndVerticalPadded(10); } if (_recipe.raceData != newRace) { _recipe.SetRace(newRace); changed = true; } if (_sharedColorsEditor.OnGUI(_recipe)) { changed = true; _textureDirty = true; } GUILayout.Space(20); if (GUILayout.Button("Remove Nulls")) { var newList = new List<SlotData>(_recipe.slotDataList.Length); foreach (var slotData in _recipe.slotDataList) { if (slotData != null) newList.Add(slotData); } _recipe.slotDataList = newList.ToArray(); changed |= true; _dnaDirty |= true; _textureDirty |= true; _meshDirty |= true; } GUILayout.Space(20); Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true)); GUI.Box(dropArea, "Drag Slots here"); GUILayout.Space(20); if (DropAreaGUI(dropArea)) { changed |= true; _dnaDirty |= true; _textureDirty |= true; _meshDirty |= true; } var added = (SlotDataAsset)EditorGUILayout.ObjectField("Add Slot", null, typeof(SlotDataAsset), false); if (added != null) { var slot = new SlotData(added); _recipe.MergeSlot(slot, false); changed |= true; _dnaDirty |= true; _textureDirty |= true; _meshDirty |= true; } GUILayout.BeginHorizontal(); if (GUILayout.Button("Collapse All")) { CollapseAll(); } if (GUILayout.Button("Expand All")) { ExpandAll(); } GUILayout.EndHorizontal(); if (LastSlot != "") { if (OpenSlots.ContainsKey(LastSlot)) { CollapseAll(); OpenSlots[LastSlot] = true; LastSlot = ""; } } for (int i = 0; i < _slotEditors.Count; i++) { var editor = _slotEditors[i]; if (editor == null) { GUILayout.Label("Empty Slot"); continue; } changed |= editor.OnGUI(ref _dnaDirty, ref _textureDirty, ref _meshDirty); if (editor.Delete) { _dnaDirty = true; _textureDirty = true; _meshDirty = true; _slotEditors.RemoveAt(i); _recipe.SetSlot(editor.idx, null); i--; changed = true; } } return changed; } private static void ExpandAll() { List<string> keys = new List<string>(OpenSlots.Keys); foreach (string s in keys) { OpenSlots[s] = true; } } private static void CollapseAll() { List<string> keys = new List<string>(OpenSlots.Keys); foreach (string s in keys) { OpenSlots[s] = false; } } } public class SlotEditor { private readonly UMAData.UMARecipe _recipe; private readonly SlotData _slotData; private readonly List<OverlayData> _overlayData = new List<OverlayData>(); private readonly List<OverlayEditor> _overlayEditors = new List<OverlayEditor>(); private readonly string _name; public SlotData Slot { get { return _slotData; } } public bool Delete { get; private set; } public bool FoldOut { get { if (! SlotMasterEditor.OpenSlots.ContainsKey(_slotData.slotName)) SlotMasterEditor.OpenSlots.Add(_slotData.slotName, true); return SlotMasterEditor.OpenSlots[_slotData.slotName]; } set { if (!SlotMasterEditor.OpenSlots.ContainsKey(_slotData.slotName)) SlotMasterEditor.OpenSlots.Add(_slotData.slotName, true); SlotMasterEditor.OpenSlots[_slotData.slotName] = value; } } public bool sharedOverlays = false; public int idx; public SlotEditor(UMAData.UMARecipe recipe, SlotData slotData, int index) { _recipe = recipe; _slotData = slotData; _overlayData = slotData.GetOverlayList(); this.idx = index; _name = slotData.asset.slotName; for (int i = 0; i < _overlayData.Count; i++) { _overlayEditors.Add(new OverlayEditor(_recipe, slotData, _overlayData[i])); } } public List<OverlayData> GetOverlays() { return _overlayData; } public bool OnGUI(ref bool _dnaDirty, ref bool _textureDirty, ref bool _meshDirty) { bool delete; bool _foldOut = FoldOut; GUIHelper.FoldoutBar(ref _foldOut, _name + " (" + _slotData.asset.name + ")", out delete); FoldOut = _foldOut; // Set this before exiting. Delete = delete; if (!FoldOut) return false; bool changed = false; GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f)); if (sharedOverlays) { List<OverlayData> ovr = GetOverlays(); EditorGUILayout.LabelField("Shared Overlays:"); GUIHelper.BeginVerticalPadded(10, new Color(0.85f, 0.85f, 0.85f)); foreach (OverlayData ov in ovr) { EditorGUILayout.LabelField(ov.asset.overlayName); } GUIHelper.EndVerticalPadded(10); } else { var added = (OverlayDataAsset)EditorGUILayout.ObjectField("Add Overlay", null, typeof(OverlayDataAsset), false); if (added != null) { var newOverlay = new OverlayData(added); _overlayEditors.Add(new OverlayEditor(_recipe, _slotData, newOverlay)); _overlayData.Add(newOverlay); _dnaDirty = true; _textureDirty = true; _meshDirty = true; changed = true; } var addedSlot = (SlotDataAsset)EditorGUILayout.ObjectField("Add Slot", null, typeof(SlotDataAsset), false); if (addedSlot != null) { var newSlot = new SlotData(addedSlot); newSlot.SetOverlayList(_slotData.GetOverlayList()); _recipe.MergeSlot(newSlot, false); _dnaDirty = true; _textureDirty = true; _meshDirty = true; changed = true; } for (int i = 0; i < _overlayEditors.Count; i++) { var overlayEditor = _overlayEditors[i]; if (overlayEditor.OnGUI()) { _textureDirty = true; changed = true; } if (overlayEditor.Delete) { _overlayEditors.RemoveAt(i); _overlayData.RemoveAt(i); _textureDirty = true; changed = true; i--; } } for (int i = 0; i < _overlayEditors.Count; i++) { var overlayEditor = _overlayEditors[i]; if (overlayEditor.move > 0 && i + 1 < _overlayEditors.Count) { _overlayEditors[i] = _overlayEditors[i + 1]; _overlayEditors[i + 1] = overlayEditor; var overlayData = _overlayData[i]; _overlayData[i] = _overlayData[i + 1]; _overlayData[i + 1] = overlayData; overlayEditor.move = 0; _textureDirty = true; changed = true; continue; } if (overlayEditor.move < 0 && i > 0) { _overlayEditors[i] = _overlayEditors[i - 1]; _overlayEditors[i - 1] = overlayEditor; var overlayData = _overlayData[i]; _overlayData[i] = _overlayData[i - 1]; _overlayData[i - 1] = overlayData; overlayEditor.move = 0; _textureDirty = true; changed = true; continue; } } } GUIHelper.EndVerticalPadded(10); return changed; } public static NameSorter sorter = new NameSorter(); public class NameSorter : IComparer<SlotEditor> { public int Compare(SlotEditor x, SlotEditor y) { return String.Compare(x._slotData.slotName, y._slotData.slotName); } } public static Comparer comparer = new Comparer(); public class Comparer : IComparer<SlotEditor> { public int Compare(SlotEditor x, SlotEditor y) { if (x._overlayData == y._overlayData) return 0; if (x._overlayData == null) return 1; if (y._overlayData == null) return -1; return x._overlayData.GetHashCode() - y._overlayData.GetHashCode(); } } } public class OverlayEditor { private readonly UMAData.UMARecipe _recipe; protected readonly SlotData _slotData; private readonly OverlayData _overlayData; private ColorEditor[] _colors; private readonly TextureEditor[] _textures; private bool _foldout = true; public bool Delete { get; private set; } public int move; private static OverlayData showExtendedRangeForOverlay; public OverlayEditor(UMAData.UMARecipe recipe, SlotData slotData, OverlayData overlayData) { _recipe = recipe; _overlayData = overlayData; _slotData = slotData; // Sanity check the colors if (_recipe.sharedColors == null) _recipe.sharedColors = new OverlayColorData[0]; else { for (int i = 0; i < _recipe.sharedColors.Length; i++) { OverlayColorData ocd = _recipe.sharedColors[i]; if (!ocd.HasName()) { ocd.name = "Shared Color " + (i + 1); } } } _textures = new TextureEditor[overlayData.asset.textureList.Length]; for (int i = 0; i < overlayData.asset.textureList.Length; i++) { _textures[i] = new TextureEditor(overlayData.asset.textureList[i]); } BuildColorEditors(); } private void BuildColorEditors() { _colors = new ColorEditor[_overlayData.colorData.channelMask.Length * 2]; for (int i = 0; i < _overlayData.colorData.channelMask.Length; i++) { _colors[i * 2] = new ColorEditor( _overlayData.colorData.channelMask[i], String.Format(i == 0 ? "Color multiplier" : "Texture {0} multiplier", i)); _colors[i * 2 + 1] = new ColorEditor( _overlayData.colorData.channelAdditiveMask[i], String.Format(i == 0 ? "Color additive" : "Texture {0} additive", i)); } } public bool OnGUI() { bool delete; GUIHelper.FoldoutBar(ref _foldout, _overlayData.asset.overlayName, out move, out delete); if (!_foldout) return false; Delete = delete; GUIHelper.BeginHorizontalPadded(10, Color.white); GUILayout.BeginVertical(); bool changed = OnColorGUI(); // Edit the rect GUILayout.BeginHorizontal(); GUILayout.Label("Rect"); Rect Save = _overlayData.rect; _overlayData.rect = EditorGUILayout.RectField(_overlayData.rect); if (Save.x != _overlayData.rect.x || Save.y != _overlayData.rect.y || Save.width != _overlayData.rect.width || Save.height != _overlayData.rect.height) { changed = true; } GUILayout.EndHorizontal(); // End rect edit GUILayout.BeginHorizontal(); foreach (var texture in _textures) { changed |= texture.OnGUI(); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUIHelper.EndVerticalPadded(10); return changed; } public bool OnColorGUI() { bool changed = false; int currentsharedcol = 0; string[] sharednames = new string[_recipe.sharedColors.Length]; //DOS 13012016 if we also check here that _recipe.sharedColors still contains //the desired ocd then we can save the collection when colors are deleted if (_overlayData.colorData.IsASharedColor && _recipe.sharedColors.Contains(_overlayData.colorData)) { GUIHelper.BeginVerticalPadded(2f, new Color(0.75f, 0.875f, 1f)); GUILayout.BeginHorizontal(); if (GUILayout.Toggle(true, "Use Shared Color") == false) { // Unshare color _overlayData.colorData = _overlayData.colorData.Duplicate(); _overlayData.colorData.name = OverlayColorData.UNSHARED; changed = true; } for (int i = 0; i < _recipe.sharedColors.Length; i++) { sharednames[i] = i + ": " + _recipe.sharedColors[i].name; if (_overlayData.colorData.GetHashCode() == _recipe.sharedColors[i].GetHashCode()) { currentsharedcol = i; } } int newcol = EditorGUILayout.Popup(currentsharedcol, sharednames); if (newcol != currentsharedcol) { changed = true; _overlayData.colorData = _recipe.sharedColors[newcol]; } GUILayout.EndHorizontal(); GUIHelper.EndVerticalPadded(2f); GUILayout.Space(2f); return changed; } else { GUIHelper.BeginVerticalPadded(2f, new Color(0.75f, 0.875f, 1f)); GUILayout.BeginHorizontal(); if (_recipe.sharedColors.Length > 0) { if (GUILayout.Toggle(false, "Use Shared Color")) { _overlayData.colorData = _recipe.sharedColors[0]; changed = true; } } GUILayout.EndHorizontal(); bool showExtendedRanges = showExtendedRangeForOverlay == _overlayData; var newShowExtendedRanges = EditorGUILayout.Toggle("Show Extended Ranges", showExtendedRanges); if (showExtendedRanges != newShowExtendedRanges) { if (newShowExtendedRanges) { showExtendedRangeForOverlay = _overlayData; } else { showExtendedRangeForOverlay = null; } } for (int k = 0; k < _colors.Length; k++) { Color color; if (showExtendedRanges && k % 2 == 0) { Vector4 colorVector = new Vector4(_colors[k].color.r, _colors[k].color.g, _colors[k].color.b, _colors[k].color.a); colorVector = EditorGUILayout.Vector4Field(_colors[k].description, colorVector); color = new Color(colorVector.x, colorVector.y, colorVector.z, colorVector.w); } else { color = EditorGUILayout.ColorField(_colors[k].description, _colors[k].color); } if (color.r != _colors[k].color.r || color.g != _colors[k].color.g || color.b != _colors[k].color.b || color.a != _colors[k].color.a) { if (k % 2 == 0) { _overlayData.colorData.channelMask[k / 2] = color; } else { _overlayData.colorData.channelAdditiveMask[k / 2] = color; } changed = true; } } GUIHelper.EndVerticalPadded(2f); GUILayout.Space(2f); return changed; } } } public class TextureEditor { private Texture _texture; public TextureEditor(Texture texture) { _texture = texture; } public bool OnGUI() { bool changed = false; float origLabelWidth = EditorGUIUtility.labelWidth; int origIndentLevel = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; EditorGUIUtility.labelWidth = 0; var newTexture = (Texture)EditorGUILayout.ObjectField("", _texture, typeof(Texture), false, GUILayout.Width(100)); EditorGUI.indentLevel = origIndentLevel; EditorGUIUtility.labelWidth = origLabelWidth; if (newTexture != _texture) { _texture = newTexture; changed = true; } return changed; } } public class ColorEditor { public Color color; public string description; public ColorEditor(Color color, string description) { this.color = color; this.description = description; } } public abstract class CharacterBaseEditor : Editor { protected readonly string[] toolbar = { "DNA", "Slots" }; protected string _description; protected string _errorMessage; protected bool _needsUpdate; protected bool _dnaDirty; protected bool _textureDirty; protected bool _meshDirty; protected Object _oldTarget; protected bool showBaseEditor; protected bool _rebuildOnLayout = false; protected UMAData.UMARecipe _recipe; //DOS made protected so childs can override protected static int _LastToolBar = 0; protected int _toolbarIndex = _LastToolBar; protected DNAMasterEditor dnaEditor; protected SlotMasterEditor slotEditor; protected bool NeedsReenable() { if (dnaEditor == null || dnaEditor.NeedsReenable()) return true; if (_oldTarget == target) return false; _oldTarget = target; return true; } /// <summary> /// Override PreInspectorGUI in any derived editors to allow editing of new properties added to recipes. /// </summary> protected virtual bool PreInspectorGUI() { return false; } /// <summary> /// Override PostInspectorGUI in any derived editors to allow editing of new properties added to recipes AFTER the slots/dna section. /// </summary> protected virtual bool PostInspectorGUI() { return false; } public override void OnInspectorGUI() { GUILayout.Label(_description); if (_errorMessage != null) { EditorGUILayout.HelpBox("The Recipe Editor could not be drawn correctly because the libraries could not find some of the required Assets. The error message was...", MessageType.Warning); EditorGUILayout.HelpBox(_errorMessage, MessageType.Error); EditorGUILayout.Space(); //we dont want the user to edit the recipe at all in this case because if they do it will be saved incompletely return; } try { if (target != _oldTarget) { _rebuildOnLayout = true; _oldTarget = target; } if (_rebuildOnLayout && Event.current.type == EventType.layout) { Rebuild(); } _needsUpdate = PreInspectorGUI(); if (ToolbarGUI()) { _needsUpdate = true; } if (PostInspectorGUI()) { _needsUpdate = true; } if (_needsUpdate) { DoUpdate(); } } catch (UMAResourceNotFoundException e) { _errorMessage = e.Message; } if (showBaseEditor) { base.OnInspectorGUI(); } } protected abstract void DoUpdate(); protected virtual void Rebuild() { _rebuildOnLayout = false; if (_recipe != null && dnaEditor != null) { int oldViewDNA = dnaEditor.viewDna; UMAData.UMARecipe oldRecipe = dnaEditor.recipe; dnaEditor = new DNAMasterEditor(_recipe); if (oldRecipe == _recipe) { dnaEditor.viewDna = oldViewDNA; } slotEditor = new SlotMasterEditor(_recipe); } } //DOS Changed Toolbar to be protected virtual so children can override protected virtual bool ToolbarGUI() { _toolbarIndex = GUILayout.Toolbar(_toolbarIndex, toolbar); _LastToolBar = _toolbarIndex; if (dnaEditor != null && slotEditor != null) switch (_toolbarIndex) { case 0: if (!dnaEditor.IsValid) return false; return dnaEditor.OnGUI(ref _dnaDirty, ref _textureDirty, ref _meshDirty); case 1: return slotEditor.OnGUI(ref _dnaDirty, ref _textureDirty, ref _meshDirty); } return false; } } } #endif
#region License // Copyright (c) 2010-2015, Mark Final // 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 BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License namespace MakeFileBuilder { public partial class MakeFileBuilder { public object Build( CSharp.Assembly moduleToBuild, out System.Boolean success) { var assemblyModule = moduleToBuild as Bam.Core.BaseModule; var node = assemblyModule.OwningNode; var target = node.Target; var assemblyOptions = assemblyModule.Options; var options = assemblyOptions as CSharp.OptionCollection; var inputVariables = new MakeFileVariableDictionary(); if (node.ExternalDependents != null) { foreach (var dependentNode in node.ExternalDependents) { if (null != dependentNode.Data) { continue; } var keyFilters = new Bam.Core.Array<Bam.Core.LocationKey>( CSharp.Assembly.OutputFile ); var assemblyLocations = new Bam.Core.LocationArray(); dependentNode.FilterOutputLocations(keyFilters, assemblyLocations); var data = dependentNode.Data as MakeFileData; var csharpOptions = options as CSharp.IOptions; foreach (var loc in assemblyLocations) { csharpOptions.References.Add(loc.GetSinglePath()); inputVariables.Add(CSharp.Assembly.OutputFile, data.VariableDictionary[CSharp.Assembly.OutputDir]); } } } var sourceFiles = new Bam.Core.StringArray(); var fields = moduleToBuild.GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); foreach (var field in fields) { // C# files { var sourceFileAttributes = field.GetCustomAttributes(typeof(Bam.Core.SourceFilesAttribute), false); if (null != sourceFileAttributes && sourceFileAttributes.Length > 0) { var sourceField = field.GetValue(moduleToBuild); if (sourceField is Bam.Core.Location) { var file = sourceField as Bam.Core.Location; var absolutePath = file.GetSinglePath(); if (!System.IO.File.Exists(absolutePath)) { throw new Bam.Core.Exception("Source file '{0}' does not exist", absolutePath); } sourceFiles.Add(absolutePath); } else if (sourceField is Bam.Core.FileCollection) { var sourceCollection = sourceField as Bam.Core.FileCollection; // TODO: convert to var foreach (Bam.Core.Location location in sourceCollection) { var absolutePath = location.GetSinglePath(); if (!System.IO.File.Exists(absolutePath)) { throw new Bam.Core.Exception("Source file '{0}' does not exist", absolutePath); } sourceFiles.Add(absolutePath); } } else { throw new Bam.Core.Exception("Field '{0}' of '{1}' should be of type Bam.Core.File or Bam.Core.FileCollection, not '{2}'", field.Name, node.ModuleName, sourceField.GetType().ToString()); } } } // WPF application definition .xaml file { var xamlFileAttributes = field.GetCustomAttributes(typeof(CSharp.ApplicationDefinitionAttribute), false); if (null != xamlFileAttributes && xamlFileAttributes.Length > 0) { var sourceField = field.GetValue(moduleToBuild); if (sourceField is Bam.Core.Location) { var file = sourceField as Bam.Core.Location; var absolutePath = file.GetSinglePath(); if (!System.IO.File.Exists(absolutePath)) { throw new Bam.Core.Exception("Application definition file '{0}' does not exist", absolutePath); } var csPath = absolutePath + ".cs"; if (!System.IO.File.Exists(csPath)) { throw new Bam.Core.Exception("Associated source file '{0}' to application definition file '{1}' does not exist", csPath, absolutePath); } sourceFiles.Add(csPath); } else if (sourceField is Bam.Core.FileCollection) { var sourceCollection = sourceField as Bam.Core.FileCollection; if (sourceCollection.Count != 1) { throw new Bam.Core.Exception("There can be only one application definition"); } // TODO: convert to var foreach (string absolutePath in sourceCollection) { if (!System.IO.File.Exists(absolutePath)) { throw new Bam.Core.Exception("Application definition file '{0}' does not exist", absolutePath); } var csPath = absolutePath + ".cs"; if (!System.IO.File.Exists(csPath)) { throw new Bam.Core.Exception("Associated source file '{0}' to application definition file '{1}' does not exist", csPath, absolutePath); } sourceFiles.Add(csPath); } } else { throw new Bam.Core.Exception("Field '{0}' of '{1}' should be of type Bam.Core.File or Bam.Core.FileCollection, not '{2}'", field.Name, node.ModuleName, sourceField.GetType().ToString()); } } } // WPF page .xaml files { var xamlFileAttributes = field.GetCustomAttributes(typeof(CSharp.PagesAttribute), false); if (null != xamlFileAttributes && xamlFileAttributes.Length > 0) { var sourceField = field.GetValue(moduleToBuild); if (sourceField is Bam.Core.Location) { var file = sourceField as Bam.Core.Location; var absolutePath = file.GetSinglePath(); if (!System.IO.File.Exists(absolutePath)) { throw new Bam.Core.Exception("Page file '{0}' does not exist", absolutePath); } var csPath = absolutePath + ".cs"; if (!System.IO.File.Exists(csPath)) { throw new Bam.Core.Exception("Associated source file '{0}' to page file '{1}' does not exist", csPath, absolutePath); } sourceFiles.Add(csPath); } else if (sourceField is Bam.Core.FileCollection) { var sourceCollection = sourceField as Bam.Core.FileCollection; if (sourceCollection.Count != 1) { throw new Bam.Core.Exception("There can be only one page file"); } // TODO: convert to var foreach (string absolutePath in sourceCollection) { if (!System.IO.File.Exists(absolutePath)) { throw new Bam.Core.Exception("Page file '{0}' does not exist", absolutePath); } var csPath = absolutePath + ".cs"; if (!System.IO.File.Exists(csPath)) { throw new Bam.Core.Exception("Associated source file '{0}' to page file '{1}' does not exist", csPath, absolutePath); } sourceFiles.Add(csPath); } } else { throw new Bam.Core.Exception("Field '{0}' of '{1}' should be of type Bam.Core.File or Bam.Core.FileCollection, not '{2}'", field.Name, node.ModuleName, sourceField.GetType().ToString()); } } } } if (0 == sourceFiles.Count) { throw new Bam.Core.Exception("There were no source files specified for the module '{0}'", node.ModuleName); } // at this point, we know the node outputs need building // create all directories required var dirsToCreate = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.Directory, Bam.Core.Location.EExists.WillExist); var commandLineBuilder = new Bam.Core.StringArray(); if (options is CommandLineProcessor.ICommandLineSupport) { var commandLineOption = options as CommandLineProcessor.ICommandLineSupport; commandLineOption.ToCommandLineArguments(commandLineBuilder, target, null); } else { throw new Bam.Core.Exception("Compiler options does not support command line translation"); } foreach (var source in sourceFiles) { if (source.Contains(" ")) { commandLineBuilder.Add(System.String.Format("\"{0}\"", source)); } else { commandLineBuilder.Add(source); } } var compilerInstance = target.Toolset.Tool(typeof(CSharp.ICSharpCompilerTool)); var executablePath = compilerInstance.Executable((Bam.Core.BaseTarget)target); var recipes = new Bam.Core.StringArray(); if (executablePath.Contains(" ")) { recipes.Add(System.String.Format("\"{0}\" {1}", executablePath, commandLineBuilder.ToString(' '))); } else { recipes.Add(System.String.Format("{0} {1}", executablePath, commandLineBuilder.ToString(' '))); } var makeFile = new MakeFile(node, this.topLevelMakeFilePath); var rule = new MakeFileRule( moduleToBuild, CSharp.Assembly.OutputFile, node.UniqueModuleName, dirsToCreate, inputVariables, null, recipes); var toolOutputLocKeys = compilerInstance.OutputLocationKeys(moduleToBuild); var outputFileLocations = moduleToBuild.Locations.Keys(Bam.Core.ScaffoldLocation.ETypeHint.File, Bam.Core.Location.EExists.WillExist); var outputFileLocationsOfInterest = outputFileLocations.Intersect(toolOutputLocKeys); rule.OutputLocationKeys = outputFileLocationsOfInterest; makeFile.RuleArray.Add(rule); var makeFilePath = MakeFileBuilder.GetMakeFilePathName(node); System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(makeFilePath)); Bam.Core.Log.DebugMessage("Makefile : '{0}'", makeFilePath); using (System.IO.TextWriter makeFileWriter = new System.IO.StreamWriter(makeFilePath)) { makeFile.Write(makeFileWriter); } success = true; var compilerTool = compilerInstance as Bam.Core.ITool; System.Collections.Generic.Dictionary<string, Bam.Core.StringArray> environment = null; if (compilerTool is Bam.Core.IToolEnvironmentVariables) { environment = (compilerTool as Bam.Core.IToolEnvironmentVariables).Variables((Bam.Core.BaseTarget)target); } var returnData = new MakeFileData(makeFilePath, makeFile.ExportedTargets, makeFile.ExportedVariables, environment); return returnData; } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Wgl { /// <summary> /// [WGL] Value of WGL_IMAGE_BUFFER_MIN_ACCESS_I3D symbol. /// </summary> [RequiredByFeature("WGL_I3D_image_buffer")] [Log(BitmaskName = "WGLImageBufferMaskI3D")] public const int IMAGE_BUFFER_MIN_ACCESS_I3D = 0x00000001; /// <summary> /// [WGL] Value of WGL_IMAGE_BUFFER_LOCK_I3D symbol. /// </summary> [RequiredByFeature("WGL_I3D_image_buffer")] [Log(BitmaskName = "WGLImageBufferMaskI3D")] public const int IMAGE_BUFFER_LOCK_I3D = 0x00000002; /// <summary> /// [WGL] wglCreateImageBufferI3D: Binding for wglCreateImageBufferI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="dwSize"> /// A <see cref="T:int"/>. /// </param> /// <param name="uFlags"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("WGL_I3D_image_buffer")] public static IntPtr CreateImageBufferI3D(IntPtr hDC, int dwSize, uint uFlags) { IntPtr retValue; Debug.Assert(Delegates.pwglCreateImageBufferI3D != null, "pwglCreateImageBufferI3D not implemented"); retValue = Delegates.pwglCreateImageBufferI3D(hDC, dwSize, uFlags); LogCommand("wglCreateImageBufferI3D", retValue, hDC, dwSize, uFlags ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglDestroyImageBufferI3D: Binding for wglDestroyImageBufferI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="pAddress"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("WGL_I3D_image_buffer")] public static bool DestroyImageBufferI3D(IntPtr hDC, IntPtr pAddress) { bool retValue; Debug.Assert(Delegates.pwglDestroyImageBufferI3D != null, "pwglDestroyImageBufferI3D not implemented"); retValue = Delegates.pwglDestroyImageBufferI3D(hDC, pAddress); LogCommand("wglDestroyImageBufferI3D", retValue, hDC, pAddress ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglAssociateImageBufferEventsI3D: Binding for wglAssociateImageBufferEventsI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="pEvent"> /// A <see cref="T:IntPtr[]"/>. /// </param> /// <param name="pAddress"> /// A <see cref="T:IntPtr[]"/>. /// </param> /// <param name="pSize"> /// A <see cref="T:int[]"/>. /// </param> /// <param name="count"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("WGL_I3D_image_buffer")] public static bool AssociateImageBufferEventsI3D(IntPtr hDC, IntPtr[] pEvent, IntPtr[] pAddress, int[] pSize, uint count) { bool retValue; unsafe { fixed (IntPtr* p_pEvent = pEvent) fixed (IntPtr* p_pAddress = pAddress) fixed (int* p_pSize = pSize) { Debug.Assert(Delegates.pwglAssociateImageBufferEventsI3D != null, "pwglAssociateImageBufferEventsI3D not implemented"); retValue = Delegates.pwglAssociateImageBufferEventsI3D(hDC, p_pEvent, p_pAddress, p_pSize, count); LogCommand("wglAssociateImageBufferEventsI3D", retValue, hDC, pEvent, pAddress, pSize, count ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglReleaseImageBufferEventsI3D: Binding for wglReleaseImageBufferEventsI3D. /// </summary> /// <param name="hDC"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="pAddress"> /// A <see cref="T:IntPtr[]"/>. /// </param> /// <param name="count"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("WGL_I3D_image_buffer")] public static bool ReleaseImageBufferEventsI3D(IntPtr hDC, IntPtr[] pAddress, uint count) { bool retValue; unsafe { fixed (IntPtr* p_pAddress = pAddress) { Debug.Assert(Delegates.pwglReleaseImageBufferEventsI3D != null, "pwglReleaseImageBufferEventsI3D not implemented"); retValue = Delegates.pwglReleaseImageBufferEventsI3D(hDC, p_pAddress, count); LogCommand("wglReleaseImageBufferEventsI3D", retValue, hDC, pAddress, count ); } } DebugCheckErrors(retValue); return (retValue); } internal static unsafe partial class Delegates { [RequiredByFeature("WGL_I3D_image_buffer")] [SuppressUnmanagedCodeSecurity] internal delegate IntPtr wglCreateImageBufferI3D(IntPtr hDC, int dwSize, uint uFlags); [RequiredByFeature("WGL_I3D_image_buffer")] internal static wglCreateImageBufferI3D pwglCreateImageBufferI3D; [RequiredByFeature("WGL_I3D_image_buffer")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglDestroyImageBufferI3D(IntPtr hDC, IntPtr pAddress); [RequiredByFeature("WGL_I3D_image_buffer")] internal static wglDestroyImageBufferI3D pwglDestroyImageBufferI3D; [RequiredByFeature("WGL_I3D_image_buffer")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglAssociateImageBufferEventsI3D(IntPtr hDC, IntPtr* pEvent, IntPtr* pAddress, int* pSize, uint count); [RequiredByFeature("WGL_I3D_image_buffer")] internal static wglAssociateImageBufferEventsI3D pwglAssociateImageBufferEventsI3D; [RequiredByFeature("WGL_I3D_image_buffer")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglReleaseImageBufferEventsI3D(IntPtr hDC, IntPtr* pAddress, uint count); [RequiredByFeature("WGL_I3D_image_buffer")] internal static wglReleaseImageBufferEventsI3D pwglReleaseImageBufferEventsI3D; } } }
#region Using directives #define USE_TRACING #define USE_LOGGING using System; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Net; using System.Runtime.Serialization; using System.Security.Permissions; #endregion ////////////////////////////////////////////////////////////////////// // <summary>custom exceptions</summary> ////////////////////////////////////////////////////////////////////// namespace Google.GData.Client { ////////////////////////////////////////////////////////////////////// /// <summary>standard exception class to be used inside the query object /// </summary> ////////////////////////////////////////////////////////////////////// [Serializable] public class LoggedException : Exception { ////////////////////////////////////////////////////////////////////// /// <summary>default constructor so that FxCop does not complain</summary> ////////////////////////////////////////////////////////////////////// public LoggedException() { } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard overloaded constructor</summary> /// <param name="msg">msg for the exception</param> ////////////////////////////////////////////////////////////////////// public LoggedException(string msg) : base(msg) { EnsureLogging(); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard overloaded constructor</summary> /// <param name="msg">msg for the exception</param> /// <param name="exception">inner exception</param> ////////////////////////////////////////////////////////////////////// public LoggedException(string msg, Exception exception) : base(msg, exception) { EnsureLogging(); } ///////////////////////////////////////////////////////////////////////////// /// <summary>here to please FxCop and maybe for future use</summary> protected LoggedException(SerializationInfo info, StreamingContext context) : base(info, context) { } ////////////////////////////////////////////////////////////////////// /// <summary>protected void EnsureLogging()</summary> ////////////////////////////////////////////////////////////////////// [Conditional("USE_LOGGING")] protected static void EnsureLogging() { } ///////////////////////////////////////////////////////////////////////////// } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard exception class to be used inside the query object /// </summary> ////////////////////////////////////////////////////////////////////// [Serializable] public class ClientQueryException : LoggedException { ////////////////////////////////////////////////////////////////////// /// <summary>default constructor so that FxCop does not complain</summary> ////////////////////////////////////////////////////////////////////// public ClientQueryException() { } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard overloaded constructor</summary> /// <param name="msg">msg for the exception</param> ////////////////////////////////////////////////////////////////////// public ClientQueryException(string msg) : base(msg) { } ///////////////////////////////////////////////////////////////////////////// /// <summary>here to please FxCop and for future use</summary> public ClientQueryException(string msg, Exception innerException) : base(msg, innerException) { } /// <summary>here to please FxCop and maybe for future use</summary> protected ClientQueryException(SerializationInfo info, StreamingContext context) : base(info, context) { } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard exception class to be used inside the feed object /// </summary> ////////////////////////////////////////////////////////////////////// [Serializable] public class ClientFeedException : LoggedException { ////////////////////////////////////////////////////////////////////// /// <summary>default constructor so that FxCop does not complain</summary> ////////////////////////////////////////////////////////////////////// public ClientFeedException() { } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard overloaded constructor</summary> /// <param name="msg">msg for the exception</param> ////////////////////////////////////////////////////////////////////// public ClientFeedException(string msg) : base(msg) { } ///////////////////////////////////////////////////////////////////////////// /// <summary>here to please FxCop and for future use</summary> public ClientFeedException(string msg, Exception innerException) : base(msg, innerException) { } ///////////////////////////////////////////////////////////////////////////// /// <summary>here to please FxCop and maybe for future use</summary> protected ClientFeedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard exception class to be used inside the feed object /// </summary> ////////////////////////////////////////////////////////////////////// [Serializable] public class GDataBatchRequestException : LoggedException { ////////////////////////////////////////////////////////////////////// /// <summary>standard overloaded constructor</summary> ////////////////////////////////////////////////////////////////////// public GDataBatchRequestException() { } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>default constructor so that FxCop does not complain</summary> ////////////////////////////////////////////////////////////////////// public GDataBatchRequestException(AtomFeed batchResult) { BatchResult = batchResult; } ////////////////////////////////////////////////////////////////////// /// <summary>standard overloaded constructor</summary> /// <param name="msg">msg for the exception</param> ////////////////////////////////////////////////////////////////////// public GDataBatchRequestException(string msg) : base(msg) { } ///////////////////////////////////////////////////////////////////////////// /// <summary>here to please FxCop and for future use</summary> public GDataBatchRequestException(string msg, Exception innerException) : base(msg, innerException) { } ///////////////////////////////////////////////////////////////////////////// /// <summary>here to please FxCop and maybe for future use</summary> protected GDataBatchRequestException(SerializationInfo info, StreamingContext context) : base(info, context) { } ///////////////////////////////////////////////////////////////////////////// /// <summary> /// Returns the BatchResult Feed that contains the problem /// </summary> public AtomFeed BatchResult { get; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard exception class to be used inside GDataRequest /// </summary> ////////////////////////////////////////////////////////////////////// [Serializable] public class GDataRequestException : LoggedException { /// <summary>cache to hold the responseText in an error scenario</summary> protected string responseText; /// <summary>holds the webresponse object</summary> protected WebResponse webResponse; ////////////////////////////////////////////////////////////////////// /// <summary>default constructor so that FxCop does not complain</summary> ////////////////////////////////////////////////////////////////////// public GDataRequestException() { } ////////////////////////////////////////////////////////////////////// /// <summary>public GDataRequestException(WebException e)</summary> /// <param name="msg"> the exception message as a string</param> /// <param name="exception"> the inner exception</param> ////////////////////////////////////////////////////////////////////// public GDataRequestException(string msg, Exception exception) : base(msg, exception) { } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>public GDataRequestException(WebException e)</summary> /// <param name="msg"> the exception message as a string</param> ////////////////////////////////////////////////////////////////////// public GDataRequestException(string msg) : base(msg) { } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>public GDataRequestException(WebException e)</summary> /// <param name="msg"> the exception message as a string</param> /// <param name="exception"> the inner exception</param> ////////////////////////////////////////////////////////////////////// public GDataRequestException(string msg, WebException exception) : base(msg, exception) { if (exception != null) { webResponse = exception.Response; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>public GDataRequestException(WebException e)</summary> /// <param name="msg"> the exception message as a string</param> /// <param name="response"> the webresponse object that caused the exception</param> ////////////////////////////////////////////////////////////////////// public GDataRequestException(string msg, WebResponse response) : base(msg) { webResponse = response; } ///////////////////////////////////////////////////////////////////////////// /// <summary>here to please FxCop and maybe for future use</summary> protected GDataRequestException(SerializationInfo info, StreamingContext context) : base(info, context) { } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Read only accessor for response</summary> ////////////////////////////////////////////////////////////////////// public WebResponse Response { get { return webResponse; } } /// <summary> /// this is the error message returned by the server /// </summary> public string ResponseString { get { if (responseText == null) responseText = ReadResponseString(); return (responseText); } } /// <summary> /// this uses the webresponse object to get at the /// stream send back from the server. /// </summary> /// <returns>the error message</returns> protected string ReadResponseString() { if (webResponse == null) return (null); Stream responseStream = webResponse.GetResponseStream(); for (int i = 0; i < webResponse.Headers.Count; ++i) { string headerVal = webResponse.Headers[i].ToLower(); if (headerVal.Contains("gzip")) { responseStream = new GZipStream(responseStream, CompressionMode.Decompress); break; } if (headerVal.Contains("deflate")) { responseStream = new DeflateStream(responseStream, CompressionMode.Decompress); break; } } if (responseStream == null) return (null); StreamReader reader = new StreamReader(responseStream); return (reader.ReadToEnd()); } /// <summary>overridden to make FxCop happy and future use</summary> [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>exception class thrown when we encounter an access denied /// (HttpSTatusCode.Forbidden) when accessing a server /// </summary> ////////////////////////////////////////////////////////////////////// public class GDataForbiddenException : GDataRequestException { ////////////////////////////////////////////////////////////////////// /// <summary>constructs a forbidden exception</summary> /// <param name="msg"> the exception message as a string</param> /// <param name="response"> the webresponse object that caused the exception</param> ////////////////////////////////////////////////////////////////////// public GDataForbiddenException(string msg, WebResponse response) : base(msg) { webResponse = response; } } ////////////////////////////////////////////////////////////////////// /// <summary>exception class thrown when we encounter a redirect /// (302 and 307) when accessing a server /// </summary> ////////////////////////////////////////////////////////////////////// public class GDataRedirectException : GDataRequestException { private readonly string redirectLocation; ////////////////////////////////////////////////////////////////////// /// <summary>constructs a redirect execption</summary> /// <param name="msg"> the exception message as a string</param> /// <param name="response"> the webresponse object that caused the exception</param> ////////////////////////////////////////////////////////////////////// public GDataRedirectException(string msg, WebResponse response) : base(msg) { webResponse = response; if (response != null && response.Headers != null) { redirectLocation = response.Headers["Location"]; } } /// <summary> /// returns the location header of the webresponse object /// which should be the location we should redirect to /// </summary> public string Location { get { return redirectLocation != null ? redirectLocation : ""; } } } ////////////////////////////////////////////////////////////////////// /// <summary>exception class thrown when we encounter a not-modified /// response (HttpStatusCode.NotModified) when accessing a server /// </summary> ////////////////////////////////////////////////////////////////////// public class GDataNotModifiedException : GDataRequestException { ////////////////////////////////////////////////////////////////////// /// <summary>constructs a not modified exception</summary> /// <param name="msg"> the exception message as a string</param> /// <param name="response"> the webresponse object that caused the exception</param> ////////////////////////////////////////////////////////////////////// public GDataNotModifiedException(string msg, WebResponse response) : base(msg) { webResponse = response; } } ////////////////////////////////////////////////////////////////////// /// <summary>exception class is thrown when you tried /// to modified/update a resource and the server detected a version /// conflict. /// </summary> ////////////////////////////////////////////////////////////////////// public class GDataVersionConflictException : GDataRequestException { ////////////////////////////////////////////////////////////////////// /// <summary>constructs a version conflict exeception</summary> /// <param name="msg"> the exception message as a string</param> /// <param name="response"> the webresponse object that caused the exception</param> ////////////////////////////////////////////////////////////////////// public GDataVersionConflictException(string msg, WebResponse response) : base(msg) { webResponse = response; } } } /////////////////////////////////////////////////////////////////////////////
// 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.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DevTestLabs { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// ScheduleOperations operations. /// </summary> internal partial class ScheduleOperations : IServiceOperations<DevTestLabsClient>, IScheduleOperations { /// <summary> /// Initializes a new instance of the ScheduleOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ScheduleOperations(DevTestLabsClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the DevTestLabsClient /// </summary> public DevTestLabsClient Client { get; private set; } /// <summary> /// List schedules in a given lab. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Schedule>>> ListWithHttpMessagesAsync(string resourceGroupName, string labName, ODataQuery<Schedule> odataQuery = default(ODataQuery<Schedule>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("labName", labName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/schedules").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Schedule>>(); _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 = SafeJsonConvert.DeserializeObject<Page<Schedule>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get schedule. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Schedule>> GetResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetResource", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/schedules/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<Schedule>(); _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 = SafeJsonConvert.DeserializeObject<Schedule>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or replace an existing schedule. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='schedule'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Schedule>> CreateOrUpdateResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Schedule schedule, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (schedule == null) { throw new ValidationException(ValidationRules.CannotBeNull, "schedule"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("schedule", schedule); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdateResource", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/schedules/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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; if(schedule != null) { _requestContent = SafeJsonConvert.SerializeObject(schedule, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<Schedule>(); _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 = SafeJsonConvert.DeserializeObject<Schedule>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Schedule>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete schedule. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "DeleteResource", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/schedules/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Modify properties of schedules. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='schedule'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Schedule>> PatchResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Schedule schedule, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (schedule == null) { throw new ValidationException(ValidationRules.CannotBeNull, "schedule"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("schedule", schedule); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PatchResource", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/schedules/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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; if(schedule != null) { _requestContent = SafeJsonConvert.SerializeObject(schedule, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<Schedule>(); _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 = SafeJsonConvert.DeserializeObject<Schedule>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Execute a schedule. This operation can take a while to complete. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> ExecuteWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginExecuteWithHttpMessagesAsync( resourceGroupName, labName, name, customHeaders, cancellationToken); return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// Execute a schedule. This operation can take a while to complete. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginExecuteWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginExecute", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/schedules/{name}/execute").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List schedules in a given lab. /// </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> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Schedule>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Schedule>>(); _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 = SafeJsonConvert.DeserializeObject<Page<Schedule>>(_responseContent, this.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; } } }
// 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 Org.Apache.REEF.Common.Tasks; using Org.Apache.REEF.Examples.Tasks.HelloTask; using Org.Apache.REEF.Examples.Tasks.StreamingTasks; using Org.Apache.REEF.Tang.Annotations; using Org.Apache.REEF.Tang.Examples; using Org.Apache.REEF.Tang.Implementations.ClassHierarchy; using Org.Apache.REEF.Tang.Implementations.Tang; using Org.Apache.REEF.Tang.Interface; using Org.Apache.REEF.Tang.Util; using Xunit; namespace Org.Apache.REEF.Tang.Tests.Injection { [DefaultImplementation(typeof(AReferenceClass))] internal interface IAInterface { } public class TestInjection { static Assembly asm = null; public TestInjection() { asm = Assembly.Load(FileNames.Examples); } [Fact] public void TestTimer() { Type timerType = typeof(Timer); ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }); cb.BindNamedParameter<Timer.Seconds, int>(GenericType<Timer.Seconds>.Class, "2"); IConfiguration conf = cb.Build(); IInjector injector = tang.NewInjector(conf); var timer = (Timer)injector.GetInstance(timerType); Assert.NotNull(timer); timer.sleep(); } [Fact] public void TestTimerWithClassHierarchy() { Type timerType = typeof(Timer); ClassHierarchyImpl classHierarchyImpl = new ClassHierarchyImpl(FileNames.Examples); ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder((ICsClassHierarchy)classHierarchyImpl); cb.BindNamedParameter<Timer.Seconds, int>(GenericType<Timer.Seconds>.Class, "2"); IConfiguration conf = cb.Build(); IInjector injector = tang.NewInjector(conf); var timer = (Timer)injector.GetInstance(timerType); Assert.NotNull(timer); timer.sleep(); } [Fact] public void TestDocumentLoadNamedParameter() { Type documentedLocalNamedParameterType = typeof(DocumentedLocalNamedParameter); ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }); cb.BindNamedParameter<DocumentedLocalNamedParameter.Foo, string>(GenericType<DocumentedLocalNamedParameter.Foo>.Class, "Hello"); IConfiguration conf = cb.Build(); IInjector injector = tang.NewInjector(conf); var doc = (DocumentedLocalNamedParameter)injector.GetInstance(documentedLocalNamedParameterType); Assert.NotNull(doc); } [Fact] public void TestDocumentLoadNamedParameterWithDefaultValue() { ITang tang = TangFactory.GetTang(); IConfiguration conf = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }).Build(); IInjector injector = tang.NewInjector(conf); var doc = (DocumentedLocalNamedParameter)injector.GetInstance(typeof(DocumentedLocalNamedParameter)); Assert.NotNull(doc); } [Fact] public void TestSimpleConstructor() { Type simpleConstructorType = typeof(SimpleConstructors); ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }); IConfiguration conf = cb.Build(); IInjector injector = tang.NewInjector(conf); var simpleConstructor = (SimpleConstructors)injector.GetInstance(simpleConstructorType); Assert.NotNull(simpleConstructor); } [Fact] public void TestActivity() { Type activityType = typeof(HelloTask); ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Tasks, FileNames.Common }); IConfiguration conf = cb.Build(); IInjector injector = tang.NewInjector(conf); var activityRef = (ITask)injector.GetInstance(activityType); Assert.NotNull(activityRef); } [Fact] public void TestStreamActivity1() { Type activityType = typeof(StreamTask1); ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Tasks, FileNames.Common }); IConfiguration conf = cb.Build(); IInjector injector = tang.NewInjector(conf); var activityRef = (ITask)injector.GetInstance(activityType); Assert.NotNull(activityRef); } [Fact] public void TestStreamActivity2() { Type activityType = typeof(StreamTask2); ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Tasks, FileNames.Common }); IConfiguration conf = cb.Build(); IInjector injector = tang.NewInjector(conf); var activityRef = (ITask)injector.GetInstance(activityType); Assert.NotNull(activityRef); } [Fact] public void TestMultipleAssemlies() { Type activityInterfaceType1 = typeof(ITask); Type tweeterType = typeof(Tweeter); ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples, FileNames.Tasks, FileNames.Common }); cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class); cb.BindImplementation(GenericType<ITweetFactory>.Class, GenericType<MockTweetFactory>.Class); cb.BindImplementation(GenericType<ISMS>.Class, GenericType<MockSMS>.Class); cb.BindNamedParameter<Tweeter.PhoneNumber, long>(GenericType<Tweeter.PhoneNumber>.Class, "8675309"); IConfiguration conf = cb.Build(); IInjector injector = tang.NewInjector(conf); var activityRef = (ITask)injector.GetInstance(activityInterfaceType1); var tweeter = (Tweeter)injector.GetInstance(tweeterType); Assert.NotNull(activityRef); Assert.NotNull(tweeter); tweeter.sendMessage(); } [Fact] public void TestActivityWithBinding() { Type activityInterfaceType = typeof(ITask); ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Tasks, FileNames.Common }); cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class); cb.BindNamedParameter<TaskConfigurationOptions.Identifier, string>(GenericType<TaskConfigurationOptions.Identifier>.Class, "Hello Task"); IConfiguration conf = cb.Build(); IInjector injector = tang.NewInjector(conf); ITask activityRef1 = injector.GetInstance<ITask>(); var activityRef2 = (ITask)injector.GetInstance(activityInterfaceType); Assert.NotNull(activityRef2); Assert.NotNull(activityRef1); Assert.Equal(activityRef1, activityRef2); } [Fact] public void TestHelloStreamingActivityWithBinding() { Type activityInterfaceType = typeof(ITask); ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Tasks, FileNames.Common }); cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class); cb.BindNamedParameter<TaskConfigurationOptions.Identifier, string>(GenericType<TaskConfigurationOptions.Identifier>.Class, "Hello Stereamingk"); cb.BindNamedParameter<StreamTask1.IpAddress, string>(GenericType<StreamTask1.IpAddress>.Class, "127.0.0.0"); IConfiguration conf = cb.Build(); IInjector injector = tang.NewInjector(conf); var activityRef = (ITask)injector.GetInstance(activityInterfaceType); Assert.NotNull(activityRef); } [Fact] public void TestTweetExample() { Type tweeterType = typeof(Tweeter); ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }); IConfiguration conf = cb.BindImplementation(GenericType<ITweetFactory>.Class, GenericType<MockTweetFactory>.Class) .BindImplementation(GenericType<ISMS>.Class, GenericType<MockSMS>.Class) .BindNamedParameter<Tweeter.PhoneNumber, long>(GenericType<Tweeter.PhoneNumber>.Class, "8675309") .Build(); IInjector injector = tang.NewInjector(conf); var tweeter = (Tweeter)injector.GetInstance(tweeterType); tweeter.sendMessage(); var sms = (ISMS)injector.GetInstance(typeof(ISMS)); var factory = (ITweetFactory)injector.GetInstance(typeof(ITweetFactory)); Assert.NotNull(sms); Assert.NotNull(factory); } [Fact] public void TestReferenceType() { AReferenceClass o = (AReferenceClass)TangFactory.GetTang().NewInjector().GetInstance(typeof(IAInterface)); } [Fact] public void TestGeneric() { var o = (AGenericClass<int>)TangFactory.GetTang().NewInjector().GetInstance(typeof(AGenericClass<int>)); var o2 = (AClassWithGenericArgument<int>)TangFactory.GetTang().NewInjector().GetInstance(typeof(AClassWithGenericArgument<int>)); Assert.NotNull(o); Assert.NotNull(o2); } [Fact] public void TestNestedClass() { ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(); IConfiguration conf = cb .BindNamedParameter<ClassParameter.Named1, int>(GenericType<ClassParameter.Named1>.Class, "5") .BindNamedParameter<ClassParameter.Named2, string>(GenericType<ClassParameter.Named2>.Class, "hello") .Build(); IInjector injector = tang.NewInjector(conf); ClassHasNestedClass h = injector.GetInstance<ClassHasNestedClass>(); Assert.NotNull(h); } [Fact] public void TestExternalObject() { ITang tang = TangFactory.GetTang(); ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(); IInjector injector = tang.NewInjector(cb.Build()); // bind an object to the injetor so that Tang will get this instance from cache directly instead of inject it when injecting ClassWithExternalObject injector.BindVolatileInstance(GenericType<ExternalClass>.Class, new ExternalClass()); ClassWithExternalObject o = injector.GetInstance<ClassWithExternalObject>(); Assert.NotNull(o.ExternalObject is ExternalClass); } /// <summary> /// In this test, interface is a generic of T. Implementations have different generic arguments such as int and string. /// When doing injection, we must specify the interface with a specified argument type /// </summary> [Fact] public void TestInjectionWithGenericArguments() { var c = TangFactory.GetTang().NewConfigurationBuilder() .BindImplementation(GenericType<IMyOperator<int>>.Class, GenericType<MyOperatorImpl<int>>.Class) .BindImplementation(GenericType<IMyOperator<string>>.Class, GenericType<MyOperatorImpl<string>>.Class) .Build(); var injector = TangFactory.GetTang().NewInjector(c); // argument type must be specified in injection var o1 = injector.GetInstance(typeof(IMyOperator<int>)); var o2 = injector.GetInstance(typeof(IMyOperator<string>)); var o3 = injector.GetInstance(typeof(MyOperatorTopology<int>)); Assert.True(o1 is MyOperatorImpl<int>); Assert.True(o2 is MyOperatorImpl<string>); Assert.True(o3 is MyOperatorTopology<int>); } /// <summary> /// In this test, interface argument type is set through Configuration. We can get the argument type and then /// make the interface with the argument type on the fly so that to do the injection /// </summary> [Fact] public void TestInjectionWithGenericArgumentType() { var c = TangFactory.GetTang().NewConfigurationBuilder() .BindImplementation(GenericType<IMyOperator<int[]>>.Class, GenericType<MyOperatorImpl<int[]>>.Class) .BindNamedParameter(typeof(MessageType), typeof(int[]).AssemblyQualifiedName) .Build(); var injector = TangFactory.GetTang().NewInjector(c); // get argument type from configuration var messageTypeAsString = injector.GetNamedInstance<MessageType, string>(GenericType<MessageType>.Class); Type messageType = Type.GetType(messageTypeAsString); // create interface with generic type on the fly Type genericInterfaceType = typeof(IMyOperator<>); Type interfaceOfMessageType = genericInterfaceType.MakeGenericType(messageType); var o = injector.GetInstance(interfaceOfMessageType); Assert.True(o is MyOperatorImpl<int[]>); } } class AReferenceClass : IAInterface { [Inject] public AReferenceClass(AReferenced refclass) { } } class AReferenced { [Inject] public AReferenced() { } } class AGenericClass<T> { [Inject] public AGenericClass() { } } class AClassWithGenericArgument<T> { [Inject] public AClassWithGenericArgument(AGenericClass<T> g) { } } class ClassHasNestedClass { [Inject] public ClassHasNestedClass(ClassParameter h1) { } } class ClassParameter { private int i; private string s; [Inject] public ClassParameter([Parameter(typeof(Named1))] int i, [Parameter(typeof(Named2))] string s) { this.i = i; this.s = s; } [NamedParameter] public class Named1 : Name<int> { } [NamedParameter] public class Named2 : Name<string> { } } class ClassWithExternalObject { [Inject] public ClassWithExternalObject(ExternalClass ec) { ExternalObject = ec; } public ExternalClass ExternalObject { get; set; } } class ExternalClass { public ExternalClass() { } } interface IMyOperator<T> { string OperatorName { get; } } class MyOperatorImpl<T> : IMyOperator<T> { [Inject] public MyOperatorImpl() { } string IMyOperator<T>.OperatorName { get { throw new NotImplementedException(); } } } [NamedParameter] class MessageType : Name<string> { } class MyOperatorTopology<T> { [Inject] public MyOperatorTopology(IMyOperator<T> op) { } } }
namespace android.app { [global::MonoJavaBridge.JavaClass()] public partial class ActivityManager : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ActivityManager() { InitJNI(); } protected ActivityManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class MemoryInfo : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static MemoryInfo() { InitJNI(); } protected MemoryInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _writeToParcel292; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.MemoryInfo._writeToParcel292, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.MemoryInfo.staticClass, global::android.app.ActivityManager.MemoryInfo._writeToParcel292, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents293; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.app.ActivityManager.MemoryInfo._describeContents293); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.ActivityManager.MemoryInfo.staticClass, global::android.app.ActivityManager.MemoryInfo._describeContents293); } internal static global::MonoJavaBridge.MethodId _readFromParcel294; public virtual void readFromParcel(android.os.Parcel arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.MemoryInfo._readFromParcel294, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.MemoryInfo.staticClass, global::android.app.ActivityManager.MemoryInfo._readFromParcel294, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _MemoryInfo295; public MemoryInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.ActivityManager.MemoryInfo.staticClass, global::android.app.ActivityManager.MemoryInfo._MemoryInfo295); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _availMem296; public long availMem { get { return default(long); } set { } } internal static global::MonoJavaBridge.FieldId _threshold297; public long threshold { get { return default(long); } set { } } internal static global::MonoJavaBridge.FieldId _lowMemory298; public bool lowMemory { get { return default(bool); } set { } } internal static global::MonoJavaBridge.FieldId _CREATOR299; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.ActivityManager.MemoryInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/ActivityManager$MemoryInfo")); global::android.app.ActivityManager.MemoryInfo._writeToParcel292 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.MemoryInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.app.ActivityManager.MemoryInfo._describeContents293 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.MemoryInfo.staticClass, "describeContents", "()I"); global::android.app.ActivityManager.MemoryInfo._readFromParcel294 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.MemoryInfo.staticClass, "readFromParcel", "(Landroid/os/Parcel;)V"); global::android.app.ActivityManager.MemoryInfo._MemoryInfo295 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.MemoryInfo.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaClass()] public partial class ProcessErrorStateInfo : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ProcessErrorStateInfo() { InitJNI(); } protected ProcessErrorStateInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _writeToParcel300; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.ProcessErrorStateInfo._writeToParcel300, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.ProcessErrorStateInfo.staticClass, global::android.app.ActivityManager.ProcessErrorStateInfo._writeToParcel300, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents301; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.app.ActivityManager.ProcessErrorStateInfo._describeContents301); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.ActivityManager.ProcessErrorStateInfo.staticClass, global::android.app.ActivityManager.ProcessErrorStateInfo._describeContents301); } internal static global::MonoJavaBridge.MethodId _readFromParcel302; public virtual void readFromParcel(android.os.Parcel arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.ProcessErrorStateInfo._readFromParcel302, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.ProcessErrorStateInfo.staticClass, global::android.app.ActivityManager.ProcessErrorStateInfo._readFromParcel302, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _ProcessErrorStateInfo303; public ProcessErrorStateInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.ActivityManager.ProcessErrorStateInfo.staticClass, global::android.app.ActivityManager.ProcessErrorStateInfo._ProcessErrorStateInfo303); Init(@__env, handle); } public static int NO_ERROR { get { return 0; } } public static int CRASHED { get { return 1; } } public static int NOT_RESPONDING { get { return 2; } } internal static global::MonoJavaBridge.FieldId _condition304; public int condition { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _processName305; public global::java.lang.String processName { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _pid306; public int pid { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _uid307; public int uid { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _tag308; public global::java.lang.String tag { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _shortMsg309; public global::java.lang.String shortMsg { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _longMsg310; public global::java.lang.String longMsg { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _stackTrace311; public global::java.lang.String stackTrace { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _crashData312; public byte[] crashData { get { return default(byte[]); } set { } } internal static global::MonoJavaBridge.FieldId _CREATOR313; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.ActivityManager.ProcessErrorStateInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/ActivityManager$ProcessErrorStateInfo")); global::android.app.ActivityManager.ProcessErrorStateInfo._writeToParcel300 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.ProcessErrorStateInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.app.ActivityManager.ProcessErrorStateInfo._describeContents301 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.ProcessErrorStateInfo.staticClass, "describeContents", "()I"); global::android.app.ActivityManager.ProcessErrorStateInfo._readFromParcel302 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.ProcessErrorStateInfo.staticClass, "readFromParcel", "(Landroid/os/Parcel;)V"); global::android.app.ActivityManager.ProcessErrorStateInfo._ProcessErrorStateInfo303 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.ProcessErrorStateInfo.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaClass()] public partial class RecentTaskInfo : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static RecentTaskInfo() { InitJNI(); } protected RecentTaskInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _writeToParcel314; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RecentTaskInfo._writeToParcel314, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RecentTaskInfo.staticClass, global::android.app.ActivityManager.RecentTaskInfo._writeToParcel314, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents315; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.app.ActivityManager.RecentTaskInfo._describeContents315); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.ActivityManager.RecentTaskInfo.staticClass, global::android.app.ActivityManager.RecentTaskInfo._describeContents315); } internal static global::MonoJavaBridge.MethodId _readFromParcel316; public virtual void readFromParcel(android.os.Parcel arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RecentTaskInfo._readFromParcel316, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RecentTaskInfo.staticClass, global::android.app.ActivityManager.RecentTaskInfo._readFromParcel316, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _RecentTaskInfo317; public RecentTaskInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.ActivityManager.RecentTaskInfo.staticClass, global::android.app.ActivityManager.RecentTaskInfo._RecentTaskInfo317); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _id318; public int id { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _baseIntent319; public global::android.content.Intent baseIntent { get { return default(global::android.content.Intent); } set { } } internal static global::MonoJavaBridge.FieldId _origActivity320; public global::android.content.ComponentName origActivity { get { return default(global::android.content.ComponentName); } set { } } internal static global::MonoJavaBridge.FieldId _CREATOR321; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.ActivityManager.RecentTaskInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/ActivityManager$RecentTaskInfo")); global::android.app.ActivityManager.RecentTaskInfo._writeToParcel314 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RecentTaskInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.app.ActivityManager.RecentTaskInfo._describeContents315 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RecentTaskInfo.staticClass, "describeContents", "()I"); global::android.app.ActivityManager.RecentTaskInfo._readFromParcel316 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RecentTaskInfo.staticClass, "readFromParcel", "(Landroid/os/Parcel;)V"); global::android.app.ActivityManager.RecentTaskInfo._RecentTaskInfo317 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RecentTaskInfo.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaClass()] public partial class RunningAppProcessInfo : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static RunningAppProcessInfo() { InitJNI(); } protected RunningAppProcessInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _writeToParcel322; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningAppProcessInfo._writeToParcel322, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningAppProcessInfo.staticClass, global::android.app.ActivityManager.RunningAppProcessInfo._writeToParcel322, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents323; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.app.ActivityManager.RunningAppProcessInfo._describeContents323); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.ActivityManager.RunningAppProcessInfo.staticClass, global::android.app.ActivityManager.RunningAppProcessInfo._describeContents323); } internal static global::MonoJavaBridge.MethodId _readFromParcel324; public virtual void readFromParcel(android.os.Parcel arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningAppProcessInfo._readFromParcel324, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningAppProcessInfo.staticClass, global::android.app.ActivityManager.RunningAppProcessInfo._readFromParcel324, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _RunningAppProcessInfo325; public RunningAppProcessInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.ActivityManager.RunningAppProcessInfo.staticClass, global::android.app.ActivityManager.RunningAppProcessInfo._RunningAppProcessInfo325); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _RunningAppProcessInfo326; public RunningAppProcessInfo(java.lang.String arg0, int arg1, java.lang.String[] arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.ActivityManager.RunningAppProcessInfo.staticClass, global::android.app.ActivityManager.RunningAppProcessInfo._RunningAppProcessInfo326, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _processName327; public global::java.lang.String processName { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _pid328; public int pid { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _uid329; public int uid { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _pkgList330; public global::java.lang.String[] pkgList { get { return default(global::java.lang.String[]); } set { } } public static int IMPORTANCE_FOREGROUND { get { return 100; } } public static int IMPORTANCE_VISIBLE { get { return 200; } } public static int IMPORTANCE_SERVICE { get { return 300; } } public static int IMPORTANCE_BACKGROUND { get { return 400; } } public static int IMPORTANCE_EMPTY { get { return 500; } } internal static global::MonoJavaBridge.FieldId _importance331; public int importance { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _lru332; public int lru { get { return default(int); } set { } } public static int REASON_UNKNOWN { get { return 0; } } public static int REASON_PROVIDER_IN_USE { get { return 1; } } public static int REASON_SERVICE_IN_USE { get { return 2; } } internal static global::MonoJavaBridge.FieldId _importanceReasonCode333; public int importanceReasonCode { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _importanceReasonPid334; public int importanceReasonPid { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _importanceReasonComponent335; public global::android.content.ComponentName importanceReasonComponent { get { return default(global::android.content.ComponentName); } set { } } internal static global::MonoJavaBridge.FieldId _CREATOR336; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.ActivityManager.RunningAppProcessInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/ActivityManager$RunningAppProcessInfo")); global::android.app.ActivityManager.RunningAppProcessInfo._writeToParcel322 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningAppProcessInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.app.ActivityManager.RunningAppProcessInfo._describeContents323 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningAppProcessInfo.staticClass, "describeContents", "()I"); global::android.app.ActivityManager.RunningAppProcessInfo._readFromParcel324 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningAppProcessInfo.staticClass, "readFromParcel", "(Landroid/os/Parcel;)V"); global::android.app.ActivityManager.RunningAppProcessInfo._RunningAppProcessInfo325 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningAppProcessInfo.staticClass, "<init>", "()V"); global::android.app.ActivityManager.RunningAppProcessInfo._RunningAppProcessInfo326 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningAppProcessInfo.staticClass, "<init>", "(Ljava/lang/String;I[Ljava/lang/String;)V"); } } [global::MonoJavaBridge.JavaClass()] public partial class RunningServiceInfo : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static RunningServiceInfo() { InitJNI(); } protected RunningServiceInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _writeToParcel337; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningServiceInfo._writeToParcel337, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningServiceInfo.staticClass, global::android.app.ActivityManager.RunningServiceInfo._writeToParcel337, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents338; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.app.ActivityManager.RunningServiceInfo._describeContents338); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.ActivityManager.RunningServiceInfo.staticClass, global::android.app.ActivityManager.RunningServiceInfo._describeContents338); } internal static global::MonoJavaBridge.MethodId _readFromParcel339; public virtual void readFromParcel(android.os.Parcel arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningServiceInfo._readFromParcel339, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningServiceInfo.staticClass, global::android.app.ActivityManager.RunningServiceInfo._readFromParcel339, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _RunningServiceInfo340; public RunningServiceInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.ActivityManager.RunningServiceInfo.staticClass, global::android.app.ActivityManager.RunningServiceInfo._RunningServiceInfo340); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _service341; public global::android.content.ComponentName service { get { return default(global::android.content.ComponentName); } set { } } internal static global::MonoJavaBridge.FieldId _pid342; public int pid { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _uid343; public int uid { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _process344; public global::java.lang.String process { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _foreground345; public bool foreground { get { return default(bool); } set { } } internal static global::MonoJavaBridge.FieldId _activeSince346; public long activeSince { get { return default(long); } set { } } internal static global::MonoJavaBridge.FieldId _started347; public bool started { get { return default(bool); } set { } } internal static global::MonoJavaBridge.FieldId _clientCount348; public int clientCount { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _crashCount349; public int crashCount { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _lastActivityTime350; public long lastActivityTime { get { return default(long); } set { } } internal static global::MonoJavaBridge.FieldId _restarting351; public long restarting { get { return default(long); } set { } } public static int FLAG_STARTED { get { return 1; } } public static int FLAG_FOREGROUND { get { return 2; } } public static int FLAG_SYSTEM_PROCESS { get { return 4; } } public static int FLAG_PERSISTENT_PROCESS { get { return 8; } } internal static global::MonoJavaBridge.FieldId _flags352; public int flags { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _clientPackage353; public global::java.lang.String clientPackage { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _clientLabel354; public int clientLabel { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _CREATOR355; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.ActivityManager.RunningServiceInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/ActivityManager$RunningServiceInfo")); global::android.app.ActivityManager.RunningServiceInfo._writeToParcel337 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningServiceInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.app.ActivityManager.RunningServiceInfo._describeContents338 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningServiceInfo.staticClass, "describeContents", "()I"); global::android.app.ActivityManager.RunningServiceInfo._readFromParcel339 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningServiceInfo.staticClass, "readFromParcel", "(Landroid/os/Parcel;)V"); global::android.app.ActivityManager.RunningServiceInfo._RunningServiceInfo340 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningServiceInfo.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaClass()] public partial class RunningTaskInfo : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static RunningTaskInfo() { InitJNI(); } protected RunningTaskInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _writeToParcel356; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningTaskInfo._writeToParcel356, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningTaskInfo.staticClass, global::android.app.ActivityManager.RunningTaskInfo._writeToParcel356, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents357; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.app.ActivityManager.RunningTaskInfo._describeContents357); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.ActivityManager.RunningTaskInfo.staticClass, global::android.app.ActivityManager.RunningTaskInfo._describeContents357); } internal static global::MonoJavaBridge.MethodId _readFromParcel358; public virtual void readFromParcel(android.os.Parcel arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningTaskInfo._readFromParcel358, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.RunningTaskInfo.staticClass, global::android.app.ActivityManager.RunningTaskInfo._readFromParcel358, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _RunningTaskInfo359; public RunningTaskInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.ActivityManager.RunningTaskInfo.staticClass, global::android.app.ActivityManager.RunningTaskInfo._RunningTaskInfo359); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _id360; public int id { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _baseActivity361; public global::android.content.ComponentName baseActivity { get { return default(global::android.content.ComponentName); } set { } } internal static global::MonoJavaBridge.FieldId _topActivity362; public global::android.content.ComponentName topActivity { get { return default(global::android.content.ComponentName); } set { } } internal static global::MonoJavaBridge.FieldId _thumbnail363; public global::android.graphics.Bitmap thumbnail { get { return default(global::android.graphics.Bitmap); } set { } } internal static global::MonoJavaBridge.FieldId _description364; public global::java.lang.CharSequence description { get { return default(global::java.lang.CharSequence); } set { } } internal static global::MonoJavaBridge.FieldId _numActivities365; public int numActivities { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _numRunning366; public int numRunning { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _CREATOR367; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.ActivityManager.RunningTaskInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/ActivityManager$RunningTaskInfo")); global::android.app.ActivityManager.RunningTaskInfo._writeToParcel356 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningTaskInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.app.ActivityManager.RunningTaskInfo._describeContents357 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningTaskInfo.staticClass, "describeContents", "()I"); global::android.app.ActivityManager.RunningTaskInfo._readFromParcel358 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningTaskInfo.staticClass, "readFromParcel", "(Landroid/os/Parcel;)V"); global::android.app.ActivityManager.RunningTaskInfo._RunningTaskInfo359 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.RunningTaskInfo.staticClass, "<init>", "()V"); } } internal static global::MonoJavaBridge.MethodId _getMemoryClass368; public virtual int getMemoryClass() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.app.ActivityManager._getMemoryClass368); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._getMemoryClass368); } internal static global::MonoJavaBridge.MethodId _getRecentTasks369; public virtual global::java.util.List getRecentTasks(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.app.ActivityManager._getRecentTasks369, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.util.List; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._getRecentTasks369, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.util.List; } internal static global::MonoJavaBridge.MethodId _getRunningTasks370; public virtual global::java.util.List getRunningTasks(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.app.ActivityManager._getRunningTasks370, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.List; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._getRunningTasks370, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.List; } internal static global::MonoJavaBridge.MethodId _getRunningServices371; public virtual global::java.util.List getRunningServices(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.app.ActivityManager._getRunningServices371, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.List; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._getRunningServices371, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.List; } internal static global::MonoJavaBridge.MethodId _getRunningServiceControlPanel372; public virtual global::android.app.PendingIntent getRunningServiceControlPanel(android.content.ComponentName arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.ActivityManager._getRunningServiceControlPanel372, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.app.PendingIntent; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._getRunningServiceControlPanel372, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.app.PendingIntent; } internal static global::MonoJavaBridge.MethodId _getMemoryInfo373; public virtual void getMemoryInfo(android.app.ActivityManager.MemoryInfo arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager._getMemoryInfo373, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._getMemoryInfo373, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getProcessesInErrorState374; public virtual global::java.util.List getProcessesInErrorState() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.app.ActivityManager._getProcessesInErrorState374)) as java.util.List; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._getProcessesInErrorState374)) as java.util.List; } internal static global::MonoJavaBridge.MethodId _getRunningAppProcesses375; public virtual global::java.util.List getRunningAppProcesses() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.app.ActivityManager._getRunningAppProcesses375)) as java.util.List; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._getRunningAppProcesses375)) as java.util.List; } internal static global::MonoJavaBridge.MethodId _getProcessMemoryInfo376; public virtual global::android.os.Debug.MemoryInfo[] getProcessMemoryInfo(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.os.Debug.MemoryInfo>(@__env.CallObjectMethod(this.JvmHandle, global::android.app.ActivityManager._getProcessMemoryInfo376, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Debug.MemoryInfo[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.os.Debug.MemoryInfo>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._getProcessMemoryInfo376, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Debug.MemoryInfo[]; } internal static global::MonoJavaBridge.MethodId _restartPackage377; public virtual void restartPackage(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager._restartPackage377, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._restartPackage377, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _killBackgroundProcesses378; public virtual void killBackgroundProcesses(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.ActivityManager._killBackgroundProcesses378, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._killBackgroundProcesses378, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDeviceConfigurationInfo379; public virtual global::android.content.pm.ConfigurationInfo getDeviceConfigurationInfo() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.ActivityManager._getDeviceConfigurationInfo379)) as android.content.pm.ConfigurationInfo; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.ActivityManager.staticClass, global::android.app.ActivityManager._getDeviceConfigurationInfo379)) as android.content.pm.ConfigurationInfo; } internal static global::MonoJavaBridge.MethodId _isUserAMonkey380; public static bool isUserAMonkey() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticBooleanMethod(android.app.ActivityManager.staticClass, global::android.app.ActivityManager._isUserAMonkey380); } public static int RECENT_WITH_EXCLUDED { get { return 1; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.ActivityManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/ActivityManager")); global::android.app.ActivityManager._getMemoryClass368 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "getMemoryClass", "()I"); global::android.app.ActivityManager._getRecentTasks369 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "getRecentTasks", "(II)Ljava/util/List;"); global::android.app.ActivityManager._getRunningTasks370 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "getRunningTasks", "(I)Ljava/util/List;"); global::android.app.ActivityManager._getRunningServices371 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "getRunningServices", "(I)Ljava/util/List;"); global::android.app.ActivityManager._getRunningServiceControlPanel372 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "getRunningServiceControlPanel", "(Landroid/content/ComponentName;)Landroid/app/PendingIntent;"); global::android.app.ActivityManager._getMemoryInfo373 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "getMemoryInfo", "(Landroid/app/ActivityManager$MemoryInfo;)V"); global::android.app.ActivityManager._getProcessesInErrorState374 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "getProcessesInErrorState", "()Ljava/util/List;"); global::android.app.ActivityManager._getRunningAppProcesses375 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "getRunningAppProcesses", "()Ljava/util/List;"); global::android.app.ActivityManager._getProcessMemoryInfo376 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "getProcessMemoryInfo", "([I)[Landroid/os/Debug/MemoryInfo;"); global::android.app.ActivityManager._restartPackage377 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "restartPackage", "(Ljava/lang/String;)V"); global::android.app.ActivityManager._killBackgroundProcesses378 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "killBackgroundProcesses", "(Ljava/lang/String;)V"); global::android.app.ActivityManager._getDeviceConfigurationInfo379 = @__env.GetMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "getDeviceConfigurationInfo", "()Landroid/content/pm/ConfigurationInfo;"); global::android.app.ActivityManager._isUserAMonkey380 = @__env.GetStaticMethodIDNoThrow(global::android.app.ActivityManager.staticClass, "isUserAMonkey", "()Z"); } } }
// Inflater.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // ************************************************************************* // // Name: Inflater.cs // // Created: 19-02-2008 SharedCache.com, rschuetz // Modified: 19-02-2008 SharedCache.com, rschuetz : Creation // ************************************************************************* using System; using SharedCache.WinServiceCommon.SharpZipLib.Checksum; using SharedCache.WinServiceCommon.SharpZipLib.Zip.Compression.Streams; namespace SharedCache.WinServiceCommon.SharpZipLib.Zip.Compression { /// <summary> /// Inflater is used to decompress data that has been compressed according /// to the "deflate" standard described in rfc1951. /// /// By default Zlib (rfc1950) headers and footers are expected in the input. /// You can use constructor <code> public Inflater(bool noHeader)</code> passing true /// if there is no Zlib header information /// /// The usage is as following. First you have to set some input with /// <code>SetInput()</code>, then Inflate() it. If inflate doesn't /// inflate any bytes there may be three reasons: /// <ul> /// <li>IsNeedingInput() returns true because the input buffer is empty. /// You have to provide more input with <code>SetInput()</code>. /// NOTE: IsNeedingInput() also returns true when, the stream is finished. /// </li> /// <li>IsNeedingDictionary() returns true, you have to provide a preset /// dictionary with <code>SetDictionary()</code>.</li> /// <li>IsFinished returns true, the inflater has finished.</li> /// </ul> /// Once the first output byte is produced, a dictionary will not be /// needed at a later stage. /// /// author of the original java version : John Leuner, Jochen Hoenicke /// </summary> public class Inflater { #region Constants/Readonly /// <summary> /// Copy lengths for literal codes 257..285 /// </summary> static readonly int[] CPLENS = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }; /// <summary> /// Extra bits for literal codes 257..285 /// </summary> static readonly int[] CPLEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; /// <summary> /// Copy offsets for distance codes 0..29 /// </summary> static readonly int[] CPDIST = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; /// <summary> /// Extra bits for distance codes /// </summary> static readonly int[] CPDEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; /// <summary> /// These are the possible states for an inflater /// </summary> const int DECODE_HEADER = 0; const int DECODE_DICT = 1; const int DECODE_BLOCKS = 2; const int DECODE_STORED_LEN1 = 3; const int DECODE_STORED_LEN2 = 4; const int DECODE_STORED = 5; const int DECODE_DYN_HEADER = 6; const int DECODE_HUFFMAN = 7; const int DECODE_HUFFMAN_LENBITS = 8; const int DECODE_HUFFMAN_DIST = 9; const int DECODE_HUFFMAN_DISTBITS = 10; const int DECODE_CHKSUM = 11; const int FINISHED = 12; #endregion #region Instance Fields /// <summary> /// This variable contains the current state. /// </summary> int mode; /// <summary> /// The adler checksum of the dictionary or of the decompressed /// stream, as it is written in the header resp. footer of the /// compressed stream. /// Only valid if mode is DECODE_DICT or DECODE_CHKSUM. /// </summary> int readAdler; /// <summary> /// The number of bits needed to complete the current state. This /// is valid, if mode is DECODE_DICT, DECODE_CHKSUM, /// DECODE_HUFFMAN_LENBITS or DECODE_HUFFMAN_DISTBITS. /// </summary> int neededBits; int repLength; int repDist; int uncomprLen; /// <summary> /// True, if the last block flag was set in the last block of the /// inflated stream. This means that the stream ends after the /// current block. /// </summary> bool isLastBlock; /// <summary> /// The total number of inflated bytes. /// </summary> long totalOut; /// <summary> /// The total number of bytes set with setInput(). This is not the /// value returned by the TotalIn property, since this also includes the /// unprocessed input. /// </summary> long totalIn; /// <summary> /// This variable stores the noHeader flag that was given to the constructor. /// True means, that the inflated stream doesn't contain a Zlib header or /// footer. /// </summary> bool noHeader; StreamManipulator input; OutputWindow outputWindow; InflaterDynHeader dynHeader; InflaterHuffmanTree litlenTree, distTree; Adler32 adler; #endregion #region Constructors /// <summary> /// Creates a new inflater or RFC1951 decompressor /// RFC1950/Zlib headers and footers will be expected in the input data /// </summary> public Inflater() : this(false) { } /// <summary> /// Creates a new inflater. /// </summary> /// <param name="noHeader"> /// True if no RFC1950/Zlib header and footer fields are expected in the input data /// /// This is used for GZIPed/Zipped input. /// /// For compatibility with /// Sun JDK you should provide one byte of input more than needed in /// this case. /// </param> public Inflater(bool noHeader) { this.noHeader = noHeader; this.adler = new Adler32(); input = new StreamManipulator(); outputWindow = new OutputWindow(); mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER; } #endregion /// <summary> /// Resets the inflater so that a new stream can be decompressed. All /// pending input and output will be discarded. /// </summary> public void Reset() { mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER; totalIn = 0; totalOut = 0; input.Reset(); outputWindow.Reset(); dynHeader = null; litlenTree = null; distTree = null; isLastBlock = false; adler.Reset(); } /// <summary> /// Decodes a zlib/RFC1950 header. /// </summary> /// <returns> /// False if more input is needed. /// </returns> /// <exception cref="SharpZipBaseException"> /// The header is invalid. /// </exception> private bool DecodeHeader() { int header = input.PeekBits(16); if (header < 0) { return false; } input.DropBits(16); // The header is written in "wrong" byte order header = ((header << 8) | (header >> 8)) & 0xffff; if (header % 31 != 0) { throw new SharpZipBaseException("Header checksum illegal"); } if ((header & 0x0f00) != (Deflater.DEFLATED << 8)) { throw new SharpZipBaseException("Compression Method unknown"); } /* Maximum size of the backwards window in bits. * We currently ignore this, but we could use it to make the * inflater window more space efficient. On the other hand the * full window (15 bits) is needed most times, anyway. int max_wbits = ((header & 0x7000) >> 12) + 8; */ if ((header & 0x0020) == 0) { // Dictionary flag? mode = DECODE_BLOCKS; } else { mode = DECODE_DICT; neededBits = 32; } return true; } /// <summary> /// Decodes the dictionary checksum after the deflate header. /// </summary> /// <returns> /// False if more input is needed. /// </returns> private bool DecodeDict() { while (neededBits > 0) { int dictByte = input.PeekBits(8); if (dictByte < 0) { return false; } input.DropBits(8); readAdler = (readAdler << 8) | dictByte; neededBits -= 8; } return false; } /// <summary> /// Decodes the huffman encoded symbols in the input stream. /// </summary> /// <returns> /// false if more input is needed, true if output window is /// full or the current block ends. /// </returns> /// <exception cref="SharpZipBaseException"> /// if deflated stream is invalid. /// </exception> private bool DecodeHuffman() { int free = outputWindow.GetFreeSpace(); while (free >= 258) { int symbol; switch (mode) { case DECODE_HUFFMAN: // This is the inner loop so it is optimized a bit while (((symbol = litlenTree.GetSymbol(input)) & ~0xff) == 0) { outputWindow.Write(symbol); if (--free < 258) { return true; } } if (symbol < 257) { if (symbol < 0) { return false; } else { // symbol == 256: end of block distTree = null; litlenTree = null; mode = DECODE_BLOCKS; return true; } } try { repLength = CPLENS[symbol - 257]; neededBits = CPLEXT[symbol - 257]; } catch (Exception) { throw new SharpZipBaseException("Illegal rep length code"); } goto case DECODE_HUFFMAN_LENBITS; // fall through case DECODE_HUFFMAN_LENBITS: if (neededBits > 0) { mode = DECODE_HUFFMAN_LENBITS; int i = input.PeekBits(neededBits); if (i < 0) { return false; } input.DropBits(neededBits); repLength += i; } mode = DECODE_HUFFMAN_DIST; goto case DECODE_HUFFMAN_DIST; // fall through case DECODE_HUFFMAN_DIST: symbol = distTree.GetSymbol(input); if (symbol < 0) { return false; } try { repDist = CPDIST[symbol]; neededBits = CPDEXT[symbol]; } catch (Exception) { throw new SharpZipBaseException("Illegal rep dist code"); } goto case DECODE_HUFFMAN_DISTBITS; // fall through case DECODE_HUFFMAN_DISTBITS: if (neededBits > 0) { mode = DECODE_HUFFMAN_DISTBITS; int i = input.PeekBits(neededBits); if (i < 0) { return false; } input.DropBits(neededBits); repDist += i; } outputWindow.Repeat(repLength, repDist); free -= repLength; mode = DECODE_HUFFMAN; break; default: throw new SharpZipBaseException("Inflater unknown mode"); } } return true; } /// <summary> /// Decodes the adler checksum after the deflate stream. /// </summary> /// <returns> /// false if more input is needed. /// </returns> /// <exception cref="SharpZipBaseException"> /// If checksum doesn't match. /// </exception> private bool DecodeChksum() { while (neededBits > 0) { int chkByte = input.PeekBits(8); if (chkByte < 0) { return false; } input.DropBits(8); readAdler = (readAdler << 8) | chkByte; neededBits -= 8; } if ((int)adler.Value != readAdler) { throw new SharpZipBaseException("Adler chksum doesn't match: " + (int)adler.Value + " vs. " + readAdler); } mode = FINISHED; return false; } /// <summary> /// Decodes the deflated stream. /// </summary> /// <returns> /// false if more input is needed, or if finished. /// </returns> /// <exception cref="SharpZipBaseException"> /// if deflated stream is invalid. /// </exception> private bool Decode() { switch (mode) { case DECODE_HEADER: return DecodeHeader(); case DECODE_DICT: return DecodeDict(); case DECODE_CHKSUM: return DecodeChksum(); case DECODE_BLOCKS: if (isLastBlock) { if (noHeader) { mode = FINISHED; return false; } else { input.SkipToByteBoundary(); neededBits = 32; mode = DECODE_CHKSUM; return true; } } int type = input.PeekBits(3); if (type < 0) { return false; } input.DropBits(3); if ((type & 1) != 0) { isLastBlock = true; } switch (type >> 1) { case DeflaterConstants.STORED_BLOCK: input.SkipToByteBoundary(); mode = DECODE_STORED_LEN1; break; case DeflaterConstants.STATIC_TREES: litlenTree = InflaterHuffmanTree.defLitLenTree; distTree = InflaterHuffmanTree.defDistTree; mode = DECODE_HUFFMAN; break; case DeflaterConstants.DYN_TREES: dynHeader = new InflaterDynHeader(); mode = DECODE_DYN_HEADER; break; default: throw new SharpZipBaseException("Unknown block type " + type); } return true; case DECODE_STORED_LEN1: { if ((uncomprLen = input.PeekBits(16)) < 0) { return false; } input.DropBits(16); mode = DECODE_STORED_LEN2; } goto case DECODE_STORED_LEN2; // fall through case DECODE_STORED_LEN2: { int nlen = input.PeekBits(16); if (nlen < 0) { return false; } input.DropBits(16); if (nlen != (uncomprLen ^ 0xffff)) { throw new SharpZipBaseException("broken uncompressed block"); } mode = DECODE_STORED; } goto case DECODE_STORED; // fall through case DECODE_STORED: { int more = outputWindow.CopyStored(input, uncomprLen); uncomprLen -= more; if (uncomprLen == 0) { mode = DECODE_BLOCKS; return true; } return !input.IsNeedingInput; } case DECODE_DYN_HEADER: if (!dynHeader.Decode(input)) { return false; } litlenTree = dynHeader.BuildLitLenTree(); distTree = dynHeader.BuildDistTree(); mode = DECODE_HUFFMAN; goto case DECODE_HUFFMAN; // fall through case DECODE_HUFFMAN: case DECODE_HUFFMAN_LENBITS: case DECODE_HUFFMAN_DIST: case DECODE_HUFFMAN_DISTBITS: return DecodeHuffman(); case FINISHED: return false; default: throw new SharpZipBaseException("Inflater.Decode unknown mode"); } } /// <summary> /// Sets the preset dictionary. This should only be called, if /// needsDictionary() returns true and it should set the same /// dictionary, that was used for deflating. The getAdler() /// function returns the checksum of the dictionary needed. /// </summary> /// <param name="buffer"> /// The dictionary. /// </param> public void SetDictionary(byte[] buffer) { SetDictionary(buffer, 0, buffer.Length); } /// <summary> /// Sets the preset dictionary. This should only be called, if /// needsDictionary() returns true and it should set the same /// dictionary, that was used for deflating. The getAdler() /// function returns the checksum of the dictionary needed. /// </summary> /// <param name="buffer"> /// The dictionary. /// </param> /// <param name="index"> /// The index into buffer where the dictionary starts. /// </param> /// <param name="count"> /// The number of bytes in the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// No dictionary is needed. /// </exception> /// <exception cref="SharpZipBaseException"> /// The adler checksum for the buffer is invalid /// </exception> public void SetDictionary(byte[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (!IsNeedingDictionary) { throw new InvalidOperationException("Dictionary is not needed"); } adler.Update(buffer, index, count); if ((int)adler.Value != readAdler) { throw new SharpZipBaseException("Wrong adler checksum"); } adler.Reset(); outputWindow.CopyDict(buffer, index, count); mode = DECODE_BLOCKS; } /// <summary> /// Sets the input. This should only be called, if needsInput() /// returns true. /// </summary> /// <param name="buffer"> /// the input. /// </param> public void SetInput(byte[] buffer) { SetInput(buffer, 0, buffer.Length); } /// <summary> /// Sets the input. This should only be called, if needsInput() /// returns true. /// </summary> /// <param name="buffer"> /// The source of input data /// </param> /// <param name="index"> /// The index into buffer where the input starts. /// </param> /// <param name="count"> /// The number of bytes of input to use. /// </param> /// <exception cref="System.InvalidOperationException"> /// No input is needed. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// The index and/or count are wrong. /// </exception> public void SetInput(byte[] buffer, int index, int count) { input.SetInput(buffer, index, count); totalIn += (long)count; } /// <summary> /// Inflates the compressed stream to the output buffer. If this /// returns 0, you should check, whether IsNeedingDictionary(), /// IsNeedingInput() or IsFinished() returns true, to determine why no /// further output is produced. /// </summary> /// <param name="buffer"> /// the output buffer. /// </param> /// <returns> /// The number of bytes written to the buffer, 0 if no further /// output can be produced. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// if buffer has length 0. /// </exception> /// <exception cref="System.FormatException"> /// if deflated stream is invalid. /// </exception> public int Inflate(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } return Inflate(buffer, 0, buffer.Length); } /// <summary> /// Inflates the compressed stream to the output buffer. If this /// returns 0, you should check, whether needsDictionary(), /// needsInput() or finished() returns true, to determine why no /// further output is produced. /// </summary> /// <param name="buffer"> /// the output buffer. /// </param> /// <param name="offset"> /// the offset in buffer where storing starts. /// </param> /// <param name="count"> /// the maximum number of bytes to output. /// </param> /// <returns> /// the number of bytes written to the buffer, 0 if no further output can be produced. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// if count is less than 0. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// if the index and / or count are wrong. /// </exception> /// <exception cref="System.FormatException"> /// if deflated stream is invalid. /// </exception> public int Inflate(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "count cannot be negative"); #endif } if (offset < 0) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "offset cannot be negative"); #endif } if (offset + count > buffer.Length) { throw new ArgumentException("count exceeds buffer bounds"); } // Special case: count may be zero if (count == 0) { if (!IsFinished) { // -jr- 08-Nov-2003 INFLATE_BUG fix.. Decode(); } return 0; } int bytesCopied = 0; do { if (mode != DECODE_CHKSUM) { /* Don't give away any output, if we are waiting for the * checksum in the input stream. * * With this trick we have always: * IsNeedingInput() and not IsFinished() * implies more output can be produced. */ int more = outputWindow.CopyOutput(buffer, offset, count); if (more > 0) { adler.Update(buffer, offset, more); offset += more; bytesCopied += more; totalOut += (long)more; count -= more; if (count == 0) { return bytesCopied; } } } } while (Decode() || ((outputWindow.GetAvailable() > 0) && (mode != DECODE_CHKSUM))); return bytesCopied; } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method also returns true when the stream is finished. /// </summary> public bool IsNeedingInput { get { return input.IsNeedingInput; } } /// <summary> /// Returns true, if a preset dictionary is needed to inflate the input. /// </summary> public bool IsNeedingDictionary { get { return mode == DECODE_DICT && neededBits == 0; } } /// <summary> /// Returns true, if the inflater has finished. This means, that no /// input is needed and no output can be produced. /// </summary> public bool IsFinished { get { return mode == FINISHED && outputWindow.GetAvailable() == 0; } } /// <summary> /// Gets the adler checksum. This is either the checksum of all /// uncompressed bytes returned by inflate(), or if needsDictionary() /// returns true (and thus no output was yet produced) this is the /// adler checksum of the expected dictionary. /// </summary> /// <returns> /// the adler checksum. /// </returns> public int Adler { get { return IsNeedingDictionary ? readAdler : (int)adler.Value; } } /// <summary> /// Gets the total number of output bytes returned by Inflate(). /// </summary> /// <returns> /// the total number of output bytes. /// </returns> public long TotalOut { get { return totalOut; } } /// <summary> /// Gets the total number of processed compressed input bytes. /// </summary> /// <returns> /// The total number of bytes of processed input bytes. /// </returns> public long TotalIn { get { return totalIn - (long)RemainingInput; } } /// <summary> /// Gets the number of unprocessed input bytes. Useful, if the end of the /// stream is reached and you want to further process the bytes after /// the deflate stream. /// </summary> /// <returns> /// The number of bytes of the input which have not been processed. /// </returns> public int RemainingInput { // TODO: This should be a long? get { return input.AvailableBytes; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using TemperatureAndHumidityApi.Areas.HelpPage.Models; namespace TemperatureAndHumidityApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System.Linq; using System.Web.Mvc; using CRP.Controllers.Filter; using CRP.Controllers.Services; using CRP.Controllers.ViewModels; using CRP.Core.Domain; using CRP.Core.Resources; using MvcContrib; using UCDArch.Web.Helpers; using UCDArch.Web.Validator; namespace CRP.Controllers { [AnyoneWithRole] public class MapPinController : ApplicationController { private readonly IAccessControlService _accessControlService; public MapPinController(IAccessControlService AccessControlService) { _accessControlService = AccessControlService; } /// <summary> /// GET: /MapPin/Create /// #1 /// Tested 20200422 /// </summary> /// <param name="id">Item Id</param> /// <returns></returns> public ActionResult Create(int itemId) { var item = Repository.OfType<Item>().GetNullableById(itemId); if (item == null || !_accessControlService.HasItemAccess(CurrentUser, item)) { //Don't Have editor rights Message = NotificationMessages.STR_NoEditorRights; return this.RedirectToAction<ItemManagementController>(a => a.List(null)); } var viewModel = MapPinViewModel.Create(Repository, item); viewModel.MapPin = new MapPin(); return View(viewModel); } /// <summary> /// POST: /MapPin/Create /// #2 /// Tested 20200422 /// </summary> /// <param name="itemId"></param> /// <param name="mapPin"></param> /// <returns></returns> [HttpPost] public ActionResult Create(int itemId, [Bind(Exclude = "Id")]MapPin mapPin) { ModelState.Clear(); var item = Repository.OfType<Item>().GetNullableById(itemId); if (item == null || !_accessControlService.HasItemAccess(CurrentUser, item)) { //Don't Have editor rights Message = NotificationMessages.STR_NoEditorRights; return this.RedirectToAction<ItemManagementController>(a => a.List(null)); } mapPin.IsPrimary = !Repository.OfType<MapPin>().Queryable.Where(a => a.Item == item && a.IsPrimary).Any(); mapPin.Item = item; mapPin.TransferValidationMessagesTo(ModelState); if(ModelState.IsValid) { //could replace with EnsurePersistent(item), but this is working fine. Repository.OfType<MapPin>().EnsurePersistent(mapPin); Message = NotificationMessages.STR_ObjectCreated.Replace(NotificationMessages.ObjectType, "Map Pin"); //return Redirect(Url.EditItemUrl(itemId, StaticValues.Tab_MapPins)); return this.RedirectToAction<ItemManagementController>(a => a.Map(item.Id)); } var viewModel = MapPinViewModel.Create(Repository, item); viewModel.MapPin = mapPin; return View(viewModel); } /// <summary> /// GET: /MapPin/Edit/5 /// #3 /// Tested 20200422 /// </summary> /// <param name="itemId"></param> /// <param name="mapPinId"></param> /// <returns></returns> public ActionResult Edit(int itemId, int mapPinId) { var item = Repository.OfType<Item>().GetNullableById(itemId); if (item == null || !_accessControlService.HasItemAccess(CurrentUser, item)) { //Don't Have editor rights Message = NotificationMessages.STR_NoEditorRights; return this.RedirectToAction<ItemManagementController>(a => a.List(null)); } var mapPin = Repository.OfType<MapPin>().GetNullableById(mapPinId); if (mapPin == null || !item.MapPins.Contains(mapPin)) { Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "MapPin"); //return Redirect(Url.EditItemUrl(itemId, StaticValues.Tab_MapPins)); return this.RedirectToAction<ItemManagementController>(a => a.Map(item.Id)); } var viewModel = MapPinViewModel.Create(Repository, item); viewModel.MapPin = mapPin; return View(viewModel); } /// <summary> /// POST: /MapPin/Edit/5 /// #4 /// Tested 20200422 /// </summary> /// <param name="itemId"></param> /// <param name="mapPinId"></param> /// <param name="mapPin"></param> /// <returns></returns> [HttpPost] public ActionResult Edit(int itemId, int mapPinId, MapPin mapPin) { ModelState.Clear(); var item = Repository.OfType<Item>().GetNullableById(itemId); if (item == null || !_accessControlService.HasItemAccess(CurrentUser, item)) { //Don't Have editor rights Message = NotificationMessages.STR_NoEditorRights; return this.RedirectToAction<ItemManagementController>(a => a.List(null)); } var mapPinToUpdate = Repository.OfType<MapPin>().GetNullableById(mapPinId); if (mapPinToUpdate == null || !item.MapPins.Contains(mapPinToUpdate)) { Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "MapPin"); //return Redirect(Url.EditItemUrl(itemId, StaticValues.Tab_MapPins)); return this.RedirectToAction<ItemManagementController>(a => a.Map(item.Id)); } mapPinToUpdate.Latitude = mapPin.Latitude; mapPinToUpdate.Longitude = mapPin.Longitude; mapPinToUpdate.Title = mapPin.Title; mapPinToUpdate.Description = mapPin.Description; //mapPinToUpdate.Item = item; mapPinToUpdate.TransferValidationMessagesTo(ModelState); item.TransferValidationMessagesTo(ModelState); if(ModelState.IsValid) { //could replace with EnsurePersistent(item), but this is working fine. Repository.OfType<MapPin>().EnsurePersistent(mapPinToUpdate); Message = NotificationMessages.STR_ObjectSaved.Replace(NotificationMessages.ObjectType, "Map Pin"); //return Redirect(Url.EditItemUrl(itemId, StaticValues.Tab_MapPins)); return this.RedirectToAction<ItemManagementController>(a => a.Map(item.Id)); } Message = "Unable to save Map Pin changes."; var viewModel = MapPinViewModel.Create(Repository, item); viewModel.MapPin = mapPinToUpdate; return View(viewModel); } /// <summary> /// Tested 20200422 /// </summary> /// <param name="itemId"></param> /// <param name="mapPinId"></param> /// <returns></returns> public ActionResult RemoveMapPin(int itemId, int mapPinId) { var item = Repository.OfType<Item>().GetNullableById(itemId); if (item == null || !_accessControlService.HasItemAccess(CurrentUser, item)) { //Don't Have editor rights Message = NotificationMessages.STR_NoEditorRights; return this.RedirectToAction<ItemManagementController>(a => a.List(null)); } var mapPin = Repository.OfType<MapPin>().GetNullableById(mapPinId); if(mapPin == null || !item.MapPins.Contains(mapPin)) { Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "MapPin"); //return Redirect(Url.EditItemUrl(itemId, StaticValues.Tab_MapPins)); return this.RedirectToAction<ItemManagementController>(a => a.Map(item.Id)); } item.RemoveMapPin(mapPin); MvcValidationAdapter.TransferValidationMessagesTo(ModelState, item.ValidationResults()); if(mapPin.IsPrimary && item.MapPins.Count > 0) { ModelState.AddModelError("MapPin", "Can't remove the primary pin when there are still other pins."); Message = "Can't remove the primary pin when there are still other pins."; } if (ModelState.IsValid) { Repository.OfType<Item>().EnsurePersistent(item); Message = NotificationMessages.STR_ObjectRemoved.Replace(NotificationMessages.ObjectType, "MapPin"); } if(string.IsNullOrEmpty(Message)) { Message = "Unable to save item/remove map pin."; } //return Redirect(Url.EditItemUrl(itemId, StaticValues.Tab_MapPins)); return this.RedirectToAction<ItemManagementController>(a => a.Map(item.Id)); } } }
using ClosedXML.Excel; using NUnit.Framework; using System; using System.Linq; namespace ClosedXML.Tests.Excel { [TestFixture] public class RowTests { [Test] public void RowsUsedIsFast() { using var wb = new XLWorkbook(); var ws = wb.AddWorksheet(); ws.FirstCell().SetValue("Hello world!"); var rowsUsed = ws.Column(1).AsRange().RowsUsed(); Assert.AreEqual(1, rowsUsed.Count()); } [Test] public void CopyRow() { var wb = new XLWorkbook(); IXLWorksheet ws = wb.AddWorksheet("Sheet1"); ws.FirstCell().SetValue("Test").Style.Font.SetBold(); ws.FirstRow().CopyTo(ws.Row(2)); Assert.IsTrue(ws.Cell("A2").Style.Font.Bold); } [Test] public void InsertingRowsAbove1() { var wb = new XLWorkbook(); IXLWorksheet ws = wb.Worksheets.Add("Sheet1"); ws.Rows("1,3").Style.Fill.SetBackgroundColor(XLColor.Red); ws.Row(2).Style.Fill.SetBackgroundColor(XLColor.Yellow); ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green); IXLRow row1 = ws.Row(1); IXLRow row2 = ws.Row(2); IXLRow row3 = ws.Row(3); IXLRow rowIns = ws.Row(1).InsertRowsAbove(1).First(); Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Row(1).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Row(1).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Row(1).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Green, ws.Row(3).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual("X", ws.Row(3).Cell(2).GetString()); Assert.AreEqual(ws.Style.Fill.BackgroundColor, rowIns.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(ws.Style.Fill.BackgroundColor, rowIns.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(ws.Style.Fill.BackgroundColor, rowIns.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row1.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row1.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row1.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, row2.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Green, row2.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, row2.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row3.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row3.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row3.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual("X", row2.Cell(2).GetString()); } [Test] public void InsertingRowsAbove2() { var wb = new XLWorkbook(); IXLWorksheet ws = wb.Worksheets.Add("Sheet1"); ws.Rows("1,3").Style.Fill.SetBackgroundColor(XLColor.Red); ws.Row(2).Style.Fill.SetBackgroundColor(XLColor.Yellow); ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green); IXLRow row1 = ws.Row(1); IXLRow row2 = ws.Row(2); IXLRow row3 = ws.Row(3); IXLRow rowIns = ws.Row(2).InsertRowsAbove(1).First(); Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Green, ws.Row(3).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual("X", ws.Row(3).Cell(2).GetString()); Assert.AreEqual(XLColor.Red, rowIns.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, rowIns.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, rowIns.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row1.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row1.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row1.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, row2.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Green, row2.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, row2.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row3.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row3.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row3.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual("X", row2.Cell(2).GetString()); } [Test] public void InsertingRowsAbove3() { var wb = new XLWorkbook(); IXLWorksheet ws = wb.Worksheets.Add("Sheet1"); ws.Rows("1,3").Style.Fill.SetBackgroundColor(XLColor.Red); ws.Row(2).Style.Fill.SetBackgroundColor(XLColor.Yellow); ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green); IXLRow row1 = ws.Row(1); IXLRow row2 = ws.Row(2); IXLRow row3 = ws.Row(3); IXLRow rowIns = ws.Row(3).InsertRowsAbove(1).First(); Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, ws.Row(2).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Green, ws.Row(2).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, ws.Row(2).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Green, ws.Row(3).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual("X", ws.Row(2).Cell(2).GetString()); Assert.AreEqual(XLColor.Yellow, rowIns.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Green, rowIns.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, rowIns.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row1.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row1.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row1.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, row2.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Green, row2.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Yellow, row2.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row3.Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row3.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, row3.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual("X", row2.Cell(2).GetString()); } [Test] public void InsertingRowsAbove4() { using (var wb = new XLWorkbook()) { var ws = wb.Worksheets.Add("Sheet1"); ws.Row(2).Height = 15; ws.Row(3).Height = 20; ws.Row(4).Height = 25; ws.Row(5).Height = 35; ws.Row(2).FirstCell().SetValue("Row height: 15"); ws.Row(3).FirstCell().SetValue("Row height: 20"); ws.Row(4).FirstCell().SetValue("Row height: 25"); ws.Row(5).FirstCell().SetValue("Row height: 35"); ws.Range("3:3").InsertRowsAbove(1); Assert.AreEqual(15, ws.Row(2).Height); Assert.AreEqual(20, ws.Row(4).Height); Assert.AreEqual(25, ws.Row(5).Height); Assert.AreEqual(35, ws.Row(6).Height); Assert.AreEqual(20, ws.Row(3).Height); ws.Row(3).ClearHeight(); Assert.AreEqual(ws.RowHeight, ws.Row(3).Height); } } [Test] public void NoRowsUsed() { var wb = new XLWorkbook(); IXLWorksheet ws = wb.Worksheets.Add("Sheet1"); Int32 count = 0; foreach (IXLRow row in ws.RowsUsed()) count++; foreach (IXLRangeRow row in ws.Range("A1:C3").RowsUsed()) count++; Assert.AreEqual(0, count); } [Test] public void RowUsed() { var wb = new XLWorkbook(); IXLWorksheet ws = wb.Worksheets.Add("Sheet1"); ws.Cell(1, 2).SetValue("Test"); ws.Cell(1, 3).SetValue("Test"); IXLRangeRow fromRow = ws.Row(1).RowUsed(); Assert.AreEqual("B1:C1", fromRow.RangeAddress.ToStringRelative()); IXLRangeRow fromRange = ws.Range("A1:E1").FirstRow().RowUsed(); Assert.AreEqual("B1:C1", fromRange.RangeAddress.ToStringRelative()); } [Test] public void RowsUsedWithDataValidation() { using var wb = new XLWorkbook(); var ws = wb.AddWorksheet(); ws.FirstCell().SetValue("Hello world!"); ws.Range("A1:A100").CreateDataValidation().WholeNumber.EqualTo(1); var range = ws.Column(1).AsRange(); Assert.AreEqual(100, range.RowsUsed(XLCellsUsedOptions.DataValidation).Count()); Assert.AreEqual(100, range.RowsUsed(XLCellsUsedOptions.All).Count()); } [Test] public void RowsUsedWithConditionalFormatting() { using var wb = new XLWorkbook(); var ws = wb.AddWorksheet(); ws.FirstCell().SetValue("Hello world!"); ws.Range("A1:A100").AddConditionalFormat().WhenStartsWith("Hell").Fill.SetBackgroundColor(XLColor.Red).Font.SetFontColor(XLColor.White); var range = ws.Column(1).AsRange(); Assert.AreEqual(100, range.RowsUsed(XLCellsUsedOptions.ConditionalFormats).Count()); Assert.AreEqual(100, range.RowsUsed(XLCellsUsedOptions.All).Count()); } [Test] public void UngroupFromAll() { IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1"); ws.Rows(1, 2).Group(); ws.Rows(1, 2).Ungroup(true); } [Test] public void NegativeRowNumberIsInvalid() { var ws = new XLWorkbook().AddWorksheet("Sheet1") as XLWorksheet; var row = new XLRow(ws, -1); Assert.IsFalse(row.RangeAddress.IsValid); } [Test] public void DeleteRowOnWorksheetWithComment() { var ws = new XLWorkbook().AddWorksheet(); ws.Cell(4, 1).GetComment().AddText("test"); ws.Column(1).Width = 100; Assert.DoesNotThrow(() => ws.Row(1).Delete()); } } }
// 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. // TypeDelegator // // This class wraps a Type object and delegates all methods to that Type. namespace System.Reflection { using System; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class TypeDelegator : TypeInfo { public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){ if(typeInfo==null) return false; return IsAssignableFrom(typeInfo.AsType()); } protected Type typeImpl; #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated #endif protected TypeDelegator() {} public TypeDelegator(Type delegatingType) { if (delegatingType == null) throw new ArgumentNullException("delegatingType"); Contract.EndContractBlock(); typeImpl = delegatingType; } public override Guid GUID { get {return typeImpl.GUID;} } public override int MetadataToken { get { return typeImpl.MetadataToken; } } public override Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder,Object target, Object[] args,ParameterModifier[] modifiers,CultureInfo culture,String[] namedParameters) { return typeImpl.InvokeMember(name,invokeAttr,binder,target,args,modifiers,culture,namedParameters); } public override Module Module { get {return typeImpl.Module;} } public override Assembly Assembly { get {return typeImpl.Assembly;} } public override RuntimeTypeHandle TypeHandle { get{return typeImpl.TypeHandle;} } public override String Name { get{return typeImpl.Name;} } public override String FullName { get{return typeImpl.FullName;} } public override String Namespace { get{return typeImpl.Namespace;} } public override String AssemblyQualifiedName { get { return typeImpl.AssemblyQualifiedName; } } public override Type BaseType { get{return typeImpl.BaseType;} } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { return typeImpl.GetConstructor(bindingAttr,binder,callConvention,types,modifiers); } [System.Runtime.InteropServices.ComVisible(true)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return typeImpl.GetConstructors(bindingAttr); } protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { // This is interesting there are two paths into the impl. One that validates // type as non-null and one where type may be null. if (types == null) return typeImpl.GetMethod(name,bindingAttr); else return typeImpl.GetMethod(name,bindingAttr,binder,callConvention,types,modifiers); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return typeImpl.GetMethods(bindingAttr); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { return typeImpl.GetField(name,bindingAttr); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return typeImpl.GetFields(bindingAttr); } public override Type GetInterface(String name, bool ignoreCase) { return typeImpl.GetInterface(name,ignoreCase); } public override Type[] GetInterfaces() { return typeImpl.GetInterfaces(); } public override EventInfo GetEvent(String name,BindingFlags bindingAttr) { return typeImpl.GetEvent(name,bindingAttr); } public override EventInfo[] GetEvents() { return typeImpl.GetEvents(); } protected override PropertyInfo GetPropertyImpl(String name,BindingFlags bindingAttr,Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { if (returnType == null && types == null) return typeImpl.GetProperty(name,bindingAttr); else return typeImpl.GetProperty(name,bindingAttr,binder,returnType,types,modifiers); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return typeImpl.GetProperties(bindingAttr); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { return typeImpl.GetEvents(bindingAttr); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { return typeImpl.GetNestedTypes(bindingAttr); } public override Type GetNestedType(String name, BindingFlags bindingAttr) { return typeImpl.GetNestedType(name,bindingAttr); } public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { return typeImpl.GetMember(name,type,bindingAttr); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return typeImpl.GetMembers(bindingAttr); } protected override TypeAttributes GetAttributeFlagsImpl() { return typeImpl.Attributes; } protected override bool IsArrayImpl() { return typeImpl.IsArray; } protected override bool IsPrimitiveImpl() { return typeImpl.IsPrimitive; } protected override bool IsByRefImpl() { return typeImpl.IsByRef; } protected override bool IsPointerImpl() { return typeImpl.IsPointer; } protected override bool IsValueTypeImpl() { return typeImpl.IsValueType; } protected override bool IsCOMObjectImpl() { return typeImpl.IsCOMObject; } public override bool IsConstructedGenericType { get { return typeImpl.IsConstructedGenericType; } } public override Type GetElementType() { return typeImpl.GetElementType(); } protected override bool HasElementTypeImpl() { return typeImpl.HasElementType; } public override Type UnderlyingSystemType { get {return typeImpl.UnderlyingSystemType;} } // ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return typeImpl.GetCustomAttributes(inherit); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return typeImpl.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return typeImpl.IsDefined(attributeType, inherit); } [System.Runtime.InteropServices.ComVisible(true)] public override InterfaceMapping GetInterfaceMap(Type interfaceType) { return typeImpl.GetInterfaceMap(interfaceType); } } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace ZXing.QrCode.Internal { /// <summary> /// /// </summary> /// <author>Satoru Takabayashi</author> /// <author>Daniel Switkin</author> /// <author>Sean Owen</author> internal static class MaskUtil { // Penalty weights from section 6.8.2.1 private const int N1 = 3; private const int N2 = 3; private const int N3 = 40; private const int N4 = 10; /// <summary> /// Apply mask penalty rule 1 and return the penalty. Find repetitive cells with the same color and /// give penalty to them. Example: 00000 or 11111. /// </summary> /// <param name="matrix">The matrix.</param> /// <returns></returns> public static int applyMaskPenaltyRule1(ByteMatrix matrix) { return applyMaskPenaltyRule1Internal(matrix, true) + applyMaskPenaltyRule1Internal(matrix, false); } /// <summary> /// Apply mask penalty rule 2 and return the penalty. Find 2x2 blocks with the same color and give /// penalty to them. This is actually equivalent to the spec's rule, which is to find MxN blocks and give a /// penalty proportional to (M-1)x(N-1), because this is the number of 2x2 blocks inside such a block. /// </summary> /// <param name="matrix">The matrix.</param> /// <returns></returns> public static int applyMaskPenaltyRule2(ByteMatrix matrix) { int penalty = 0; var array = matrix.Array; int width = matrix.Width; int height = matrix.Height; for (int y = 0; y < height - 1; y++) { for (int x = 0; x < width - 1; x++) { int value = array[y][x]; if (value == array[y][x + 1] && value == array[y + 1][x] && value == array[y + 1][x + 1]) { penalty++; } } } return N2 * penalty; } /// <summary> /// Apply mask penalty rule 3 and return the penalty. Find consecutive cells of 00001011101 or /// 10111010000, and give penalty to them. If we find patterns like 000010111010000, we give /// penalties twice (i.e. 40 * 2). /// </summary> /// <param name="matrix">The matrix.</param> /// <returns></returns> public static int applyMaskPenaltyRule3(ByteMatrix matrix) { int numPenalties = 0; byte[][] array = matrix.Array; int width = matrix.Width; int height = matrix.Height; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { byte[] arrayY = array[y]; // We can at least optimize this access if (x + 6 < width && arrayY[x] == 1 && arrayY[x + 1] == 0 && arrayY[x + 2] == 1 && arrayY[x + 3] == 1 && arrayY[x + 4] == 1 && arrayY[x + 5] == 0 && arrayY[x + 6] == 1 && (isWhiteHorizontal(arrayY, x - 4, x) || isWhiteHorizontal(arrayY, x + 7, x + 11))) { numPenalties++; } if (y + 6 < height && array[y][x] == 1 && array[y + 1][x] == 0 && array[y + 2][x] == 1 && array[y + 3][x] == 1 && array[y + 4][x] == 1 && array[y + 5][x] == 0 && array[y + 6][x] == 1 && (isWhiteVertical(array, x, y - 4, y) || isWhiteVertical(array, x, y + 7, y + 11))) { numPenalties++; } } } return numPenalties * N3; } private static bool isWhiteHorizontal(byte[] rowArray, int from, int to) { for (int i = from; i < to; i++) { if (i >= 0 && i < rowArray.Length && rowArray[i] == 1) { return false; } } return true; } private static bool isWhiteVertical(byte[][] array, int col, int from, int to) { for (int i = from; i < to; i++) { if (i >= 0 && i < array.Length && array[i][col] == 1) { return false; } } return true; } /// <summary> /// Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give /// penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance. /// </summary> /// <param name="matrix">The matrix.</param> /// <returns></returns> public static int applyMaskPenaltyRule4(ByteMatrix matrix) { int numDarkCells = 0; var array = matrix.Array; int width = matrix.Width; int height = matrix.Height; for (int y = 0; y < height; y++) { var arrayY = array[y]; for (int x = 0; x < width; x++) { if (arrayY[x] == 1) { numDarkCells++; } } } var numTotalCells = matrix.Height * matrix.Width; var darkRatio = (double)numDarkCells / numTotalCells; var fivePercentVariances = (int)(Math.Abs(darkRatio - 0.5) * 20.0); // * 100.0 / 5.0 return fivePercentVariances * N4; } /// <summary> /// Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask /// pattern conditions. /// </summary> /// <param name="maskPattern">The mask pattern.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <returns></returns> public static bool getDataMaskBit(int maskPattern, int x, int y) { int intermediate, temp; switch (maskPattern) { case 0: intermediate = (y + x) & 0x1; break; case 1: intermediate = y & 0x1; break; case 2: intermediate = x % 3; break; case 3: intermediate = (y + x) % 3; break; case 4: intermediate = (((int)((uint)y >> 1)) + (x / 3)) & 0x1; break; case 5: temp = y * x; intermediate = (temp & 0x1) + (temp % 3); break; case 6: temp = y * x; intermediate = (((temp & 0x1) + (temp % 3)) & 0x1); break; case 7: temp = y * x; intermediate = (((temp % 3) + ((y + x) & 0x1)) & 0x1); break; default: throw new ArgumentException("Invalid mask pattern: " + maskPattern); } return intermediate == 0; } /// <summary> /// Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both /// vertical and horizontal orders respectively. /// </summary> /// <param name="matrix">The matrix.</param> /// <param name="isHorizontal">if set to <c>true</c> [is horizontal].</param> /// <returns></returns> private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, bool isHorizontal) { int penalty = 0; int iLimit = isHorizontal ? matrix.Height : matrix.Width; int jLimit = isHorizontal ? matrix.Width : matrix.Height; var array = matrix.Array; for (int i = 0; i < iLimit; i++) { int numSameBitCells = 0; int prevBit = -1; for (int j = 0; j < jLimit; j++) { int bit = isHorizontal ? array[i][j] : array[j][i]; if (bit == prevBit) { numSameBitCells++; } else { if (numSameBitCells >= 5) { penalty += N1 + (numSameBitCells - 5); } numSameBitCells = 1; // Include the cell itself. prevBit = bit; } } if (numSameBitCells >= 5) { penalty += N1 + (numSameBitCells - 5); } } return penalty; } } }
#region OMIT_ALTERTABLE #if !OMIT_ALTERTABLE using System; using System.Diagnostics; using System.Text; namespace Core.Command { public class Alter { static void RenameTableFunc(FuncContext fctx, int notUsed, Mem[] argv) { Context ctx = Vdbe.Context_Ctx(fctx); string sql = Vdbe.Value_Text(argv[0]); string tableName = Vdbe.Value_Text(argv[1]); if (string.IsNullOrEmpty(sql)) return; int length = 0; TK token = 0; Token tname = new Token(); int z = 0, zLoc = 0; // The principle used to locate the table name in the CREATE TABLE statement is that the table name is the first non-space token that // is immediately followed by a TK_LP or TK_USING token. do { if (z == sql.Length) return; // Ran out of input before finding an opening bracket. Return NULL. // Store the token that zCsr points to in tname. zLoc = z; tname.data = sql.Substring(z); tname.length = (uint)length; // Advance zCsr to the next token. Store that token type in 'token', and its length in 'len' (to be used next iteration of this loop). do { z += length; length = (z == sql.Length ? 1 : Parse.GetToken(sql, z, ref token)); } while (token == TK.SPACE); Debug.Assert(length > 0); } while (token != TK.LP && token != TK.USING); string r = C._mtagprintf(ctx, "%.*s\"%w\"%s", zLoc, sql.Substring(0, zLoc), tableName, sql.Substring(zLoc + (int)tname.length)); Vdbe.Result_Text(fctx, r, -1, DESTRUCTOR_DYNAMIC); } #if !OMIT_FOREIGN_KEY static void RenameParentFunc(FuncContext fctx, int notUsed, Mem[] argv) { Context ctx = Vdbe.Context_Ctx(fctx); string input = Vdbe.Value_Text(argv[0]); string oldName = Vdbe.Value_Text(argv[1]); string newName = Vdbe.Value_Text(argv[2]); int zIdx; // Pointer to token int zLeft = 0; // Pointer to remainder of String TK token = 0; // Type of token string output = string.Empty; int n; // Length of token z for (int z = 0; z < input.Length; z += n) { n = Parse.GetToken(input, z, ref token); if (token == TK.REFERENCES) { string parent; do { z += n; n = Parse.GetToken(input, z, ref token); } while (token == TK.SPACE); parent = (z + n < input.Length ? input.Substring(z, n) : string.Empty); if (string.IsNullOrEmpty(parent)) break; Parse.Dequote(ref parent); if (oldName.Equals(parent, StringComparison.OrdinalIgnoreCase)) { string out_ = C._mtagprintf(ctx, "%s%.*s\"%w\"", output, z - zLeft, input.Substring(zLeft), newName); C._tagfree(ctx, ref output); output = out_; z += n; zLeft = z; } C._tagfree(ctx, ref parent); } } string r = C._mtagprintf(ctx, "%s%s", output, input.Substring(zLeft)); Vdbe.Result_Text(fctx, r, -1, DESTRUCTOR.DYNAMIC); C._tagfree(ctx, ref output); } #endif #if !OMIT_TRIGGER static void RenameTriggerFunc(FuncContext fctx, int notUsed, Mem[] argv) { Context ctx = Vdbe.Context_Ctx(fctx); string sql = Vdbe.Value_Text(argv[0]); string tableName = Vdbe.Value_Text(argv[1]); int z = 0, zLoc = 0; int length = 1; TK token = 0; Token tname = new Token(); int dist = 3; // The principle used to locate the table name in the CREATE TRIGGER statement is that the table name is the first token that is immediatedly // preceded by either TK_ON or TK_DOT and immediatedly followed by one of TK_WHEN, TK_BEGIN or TK_FOR. if (sql != null) return; do { if (z == sql.Length) return; // Ran out of input before finding the table name. Return NULL. // Store the token that zCsr points to in tname. zLoc = z; tname.data = sql.Substring(z, length); tname.length = (uint)length; // Advance zCsr to the next token. Store that token type in 'token', and its length in 'len' (to be used next iteration of this loop). do { z += length; length = (z == sql.Length ? 1 : Parse.GetToken(sql, z, ref token)); } while (token == TK.SPACE); Debug.Assert(length > 0); // Variable 'dist' stores the number of tokens read since the most recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN // token is read and 'dist' equals 2, the condition stated above to be met. // // Note that ON cannot be a database, table or column name, so there is no need to worry about syntax like // "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc. dist++; if (token == TK.DOT || token == TK.ON) dist = 0; } while (dist != 2 || (token != TK.WHEN && token != TK.FOR && token != TK.BEGIN)); // Variable tname now contains the token that is the old table-name in the CREATE TRIGGER statement. string r = C._mtagprintf(ctx, "%.*s\"%w\"%s", zLoc, sql.Substring(0, zLoc), tableName, sql.Substring(zLoc + (int)tname.length)); Vdbe.Result_Text(fctx, r, -1, C.DESTRUCTOR_DYNAMIC); } #endif static FuncDef[] _alterTableFuncs = new FuncDef[] { FUNCTION("sqlite_rename_table", 2, 0, 0, RenameTableFunc), #if !OMIT_TRIGGER FUNCTION("sqlite_rename_trigger", 2, 0, 0, RenameTriggerFunc), #endif #if !OMIT_FOREIGN_KEY FUNCTION("sqlite_rename_parent", 3, 0, 0, RenameParentFunc), #endif }; public static void Functions() { FuncDefHash hash = Main.GlobalFunctions; FuncDef[] funcs = _alterTableFuncs; for (int i = 0; i < _alterTableFuncs.Length; i++) Callback.FuncDefInsert(hash, funcs[i]); } static string WhereOrName(Context ctx, string where_, string constant) { string newExpr; if (string.IsNullOrEmpty(where_)) newExpr = C._mtagprintf(ctx, "name=%Q", constant); else { newExpr = C._mtagprintf(ctx, "%s OR name=%Q", where_, constant); C._tagfree(ctx, ref where_); } return newExpr; } #if !OMIT_FOREIGN_KEY&& !OMIT_TRIGGER static string WhereForeignKeys(Parse parse, Table table) { string where_ = string.Empty; for (FKey p = Parse.FKReferences(table); p != null; p = p.NextTo) where_ = WhereOrName(parse.Ctx, where_, p.From.Name); return where_; } #endif static string WhereTempTriggers(Parse parse, Table table) { Context ctx = parse.Ctx; string where_ = string.Empty; Schema tempSchema = ctx.DBs[1].Schema; // Temp db schema // If the table is not located in the temp.db (in which case NULL is returned, loop through the tables list of triggers. For each trigger // that is not part of the temp.db schema, add a clause to the WHERE expression being built up in zWhere. if (table.Schema != tempSchema) for (Trigger trig = Trigger.List(parse, table); trig != null; trig = trig.Next) if (trig.Schema == tempSchema) where_ = WhereOrName(ctx, where_, trig.Name); if (!string.IsNullOrEmpty(where_)) where_ = C._mtagprintf(ctx, "type='trigger' AND (%s)", where_); return where_; } static void ReloadTableSchema(Parse parse, Table table, string name) { Context ctx = parse.Ctx; string where_; #if !SQLITE_OMIT_TRIGGER Trigger trig; #endif Vdbe v = parse.GetVdbe(); if (C._NEVER(v == null)) return; Debug.Assert(Btree.HoldsAllMutexes(ctx)); int db = Prepare.SchemaToIndex(ctx, table.Schema); // Index of database containing pTab Debug.Assert(db >= 0); #if !OMIT_TRIGGER // Drop any table triggers from the internal schema. for (trig = Trigger.List(parse, table); trig != null; trig = trig.Next) { int trigDb = Prepare.SchemaToIndex(ctx, trig.Schema); Debug.Assert(trigDb == db || trigDb == 1); v.AddOp4(OP.DropTrigger, trigDb, 0, 0, trig.Name, 0); } #endif // Drop the table and index from the internal schema. v.AddOp4(OP.DropTable, db, 0, 0, table.Name, 0); // Reload the table, index and permanent trigger schemas. where_ = C._mtagprintf(ctx, "tbl_name=%Q", name); if (where_ == null) return; v.AddParseSchemaOp(db, where_); #if !OMIT_TRIGGER // Now, if the table is not stored in the temp database, reload any temp triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. if ((where_ = WhereTempTriggers(parse, table)) != "") v.AddParseSchemaOp(1, where_); #endif } static bool IsSystemTable(Parse parse, string name) { if (name.StartsWith("sqlite_", StringComparison.OrdinalIgnoreCase)) { parse.ErrorMsg("table %s may not be altered", name); return true; } return false; } public static void RenameTable(Parse parse, SrcList src, Token name) { Context ctx = parse.Ctx; // Database connection Context.FLAG savedDbFlags = ctx.Flags; // Saved value of db->flags //if (C._NEVER(ctx.MallocFailed)) goto exit_rename_table; Debug.Assert(src.Srcs == 1); Debug.Assert(Btree.HoldsAllMutexes(ctx)); Table table = parse.LocateTableItem(false, src.Ids[0]); // Table being renamed if (table == null) goto exit_rename_table; int db = Prepare.SchemaToIndex(ctx, table.Schema); // Database that contains the table string dbName = ctx.DBs[db].Name; // Name of database iDb ctx.Flags |= Context.FLAG.PreferBuiltin; // Get a NULL terminated version of the new table name. string nameAsString = Parse.NameFromToken(ctx, name); // NULL-terminated version of pName if (nameAsString == null) goto exit_rename_table; // Check that a table or index named 'zName' does not already exist in database iDb. If so, this is an error. if (Parse.FindTable(ctx, nameAsString, dbName) != null || Parse.FindIndex(ctx, nameAsString, dbName) != null) { parse.ErrorMsg("there is already another table or index with this name: %s", nameAsString); goto exit_rename_table; } // Make sure it is not a system table being altered, or a reserved name that the table is being renamed to. if (IsSystemTable(parse, table.Name) || parse->CheckObjectName(nameAsString) != RC.OK) goto exit_rename_table; #if !OMIT_VIEW if (table.Select != null) { parse.ErrorMsg("view %s may not be altered", table.Name); goto exit_rename_table; } #endif #if !OMIT_AUTHORIZATION // Invoke the authorization callback. if (Auth.Check(parse, AUTH.ALTER_TABLE, dbName, table.Name, null)) goto exit_rename_table; #endif VTable vtable = null; // Non-zero if this is a v-tab with an xRename() #if !OMIT_VIRTUALTABLE if (parse->ViewGetColumnNames(table) != 0) goto exit_rename_table; if (E.IsVirtual(table)) { vtable = VTable.GetVTable(ctx, table); if (vtable.IVTable.IModule.Rename == null) vtable = null; } #endif // Begin a transaction and code the VerifyCookie for database iDb. Then modify the schema cookie (since the ALTER TABLE modifies the // schema). Open a statement transaction if the table is a virtual table. Vdbe v = parse.GetVdbe(); if (v == null) goto exit_rename_table; parse.BeginWriteOperation((vtable != null ? 1 : 0), db); parse.ChangeCookie(db); // If this is a virtual table, invoke the xRename() function if one is defined. The xRename() callback will modify the names // of any resources used by the v-table implementation (including other SQLite tables) that are identified by the name of the virtual table. #if !OMIT_VIRTUALTABLE if (vtable != null) { int i = ++parse.Mems; v.AddOp4(OP.String8, 0, i, 0, nameAsString, 0); v.AddOp4(OP.VRename, i, 0, 0, vtable, Vdbe.P4T.VTAB); parse.MayAbort(); } #endif // figure out how many UTF-8 characters are in zName string tableName = table.Name; // Original name of the table int tableNameLength = C._utf8charlength(tableName, -1); // Number of UTF-8 characters in zTabName #if !OMIT_TRIGGER string where_ = string.Empty; // Where clause to locate temp triggers #endif #if !OMIT_FOREIGN_KEY && !OMIT_TRIGGER if ((ctx.Flags & Context.FLAG.ForeignKeys) != 0) { // If foreign-key support is enabled, rewrite the CREATE TABLE statements corresponding to all child tables of foreign key constraints // for which the renamed table is the parent table. if ((where_ = WhereForeignKeys(parse, table)) != null) { parse.NestedParse( "UPDATE \"%w\".%s SET " + "sql = sqlite_rename_parent(sql, %Q, %Q) " + "WHERE %s;", dbName, E.SCHEMA_TABLE(db), tableName, nameAsString, where_); C._tagfree(ctx, ref where_); } } #endif // Modify the sqlite_master table to use the new table name. parse.NestedParse( "UPDATE %Q.%s SET " + #if OMIT_TRIGGER "sql = sqlite_rename_table(sql, %Q), " + #else "sql = CASE " + "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" + "ELSE sqlite_rename_table(sql, %Q) END, " + #endif "tbl_name = %Q, " + "name = CASE " + "WHEN type='table' THEN %Q " + "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " + "'sqlite_autoindex_' || %Q || substr(name,%d+18) " + "ELSE name END " + "WHERE tbl_name=%Q AND " + "(type='table' OR type='index' OR type='trigger');", dbName, SCHEMA_TABLE(db), nameAsString, nameAsString, nameAsString, #if !OMIT_TRIGGER nameAsString, #endif nameAsString, tableNameLength, tableName); #if !OMIT_AUTOINCREMENT // If the sqlite_sequence table exists in this database, then update it with the new table name. if (Parse.FindTable(ctx, "sqlite_sequence", dbName) != null) parse.NestedParse( "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", dbName, nameAsString, table.Name); #endif #if !OMIT_TRIGGER // If there are TEMP triggers on this table, modify the sqlite_temp_master table. Don't do this if the table being ALTERed is itself located in the temp database. if ((where_ = WhereTempTriggers(parse, table)) != "") { parse.NestedParse( "UPDATE sqlite_temp_master SET " + "sql = sqlite_rename_trigger(sql, %Q), " + "tbl_name = %Q " + "WHERE %s;", nameAsString, nameAsString, where_); C._tagfree(ctx, ref where_); } #endif #if !(OMIT_FOREIGN_KEY) && !(OMIT_TRIGGER) if ((ctx.Flags & Context.FLAG.ForeignKeys) != 0) { for (FKey p = Parse.FkReferences(table); p != null; p = p.NextTo) { Table from = p.From; if (from != table) ReloadTableSchema(parse, p.From, from.Name); } } #endif // Drop and reload the internal table schema. ReloadTableSchema(parse, table, nameAsString); exit_rename_table: Expr.SrcListDelete(ctx, ref src); C._tagfree(ctx, ref nameAsString); ctx.Flags = savedDbFlags; } public static void MinimumFileFormat(Parse parse, int db, int minFormat) { Vdbe v = parse.GetVdbe(); // The VDBE should have been allocated before this routine is called. If that allocation failed, we would have quit before reaching this point if (C._ALWAYS(v != null)) { int r1 = Expr.GetTempReg(parse); int r2 = Expr.GetTempReg(parse); v.AddOp3(OP.ReadCookie, db, r1, Btree.META.FILE_FORMAT); v.UsesBtree(db); v.AddOp2(OP.Integer, minFormat, r2); int j1 = v.AddOp3(OP.Ge, r2, 0, r1); v.AddOp3(OP.SetCookie, db, Btree.META.FILE_FORMAT, r2); v.JumpHere(j1); Expr.ReleaseTempReg(parse, r1); Expr.ReleaseTempReg(parse, r2); } } public static void FinishAddColumn(Parse parse, Token colDef) { Context ctx = parse.Ctx; // The database connection if (parse.Errs != 0 || ctx.MallocFailed) return; Table newTable = parse.NewTable; // Copy of pParse.pNewTable Debug.Assert(newTable != null); Debug.Assert(Btree.HoldsAllMutexes(ctx)); int db = Prepare.SchemaToIndex(ctx, newTable.Schema); // Database number string dbName = ctx.DBs[db].Name;// Database name string tableName = newTable.Name.Substring(16); // Table name: Skip the "sqlite_altertab_" prefix on the name Column col = newTable.Cols[newTable.Cols.length - 1]; // The new column Expr dflt = col.Dflt; // Default value for the new column Table table = Parse.FindTable(ctx, tableName, dbName); // Table being altered Debug.Assert(table != null); #if !OMIT_AUTHORIZATION // Invoke the authorization callback. if (Auth.Check(parse, AUTH.ALTER_TABLE, dbName, table.Name, null)) return; #endif // If the default value for the new column was specified with a literal NULL, then set pDflt to 0. This simplifies checking // for an SQL NULL default below. if (dflt != null && dflt.OP == TK.NULL) dflt = null; // Check that the new column is not specified as PRIMARY KEY or UNIQUE. If there is a NOT NULL constraint, then the default value for the // column must not be NULL. if ((col.ColFlags & COLFLAG.PRIMKEY) != 0) { parse.ErrorMsg("Cannot add a PRIMARY KEY column"); return; } if (newTable.Index != null) { parse.ErrorMsg("Cannot add a UNIQUE column"); return; } if ((ctx.Flags & Context.FLAG.ForeignKeys) != 0 && newTable.FKeys != null && dflt != null) { parse.ErrorMsg("Cannot add a REFERENCES column with non-NULL default value"); return; } if (col.NotNull != 0 && dflt == null) { parse.ErrorMsg("Cannot add a NOT NULL column with default value NULL"); return; } // Ensure the default expression is something that sqlite3ValueFromExpr() can handle (i.e. not CURRENT_TIME etc.) if (dflt != null) { Mem val = null; if (Mem_FromExpr(ctx, dflt, TEXTENCODE.UTF8, AFF.NONE, ref val) != 0) { ctx.MallocFailed = true; return; } if (val == null) { parse.ErrorMsg("Cannot add a column with non-constant default"); return; } Mem_Free(ref val); } // Modify the CREATE TABLE statement. string colDefAsString = colDef.data.Substring(0, (int)colDef.length).Replace(";", " ").Trim(); // Null-terminated column definition if (colDefAsString != null) { Context.FLAG savedDbFlags = ctx.Flags; ctx.Flags |= Context.FLAG.PreferBuiltin; parse.NestedParse( "UPDATE \"%w\".%s SET " + "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " + "WHERE type = 'table' AND name = %Q", dbName, E.SCHEMA_TABLE(db), newTable.AddColOffset, colDefAsString, newTable.AddColOffset + 1, tableName); C._tagfree(ctx, ref colDefAsString); ctx.Flags = savedDbFlags; } // If the default value of the new column is NULL, then set the file format to 2. If the default value of the new column is not NULL, // the file format becomes 3. MinimumFileFormat(parse, db, (dflt != null ? 3 : 2)); // Reload the schema of the modified table. ReloadTableSchema(parse, table, table.Name); } public static void BeginAddColumn(Parse parse, SrcList src) { Context ctx = parse.Ctx; // Look up the table being altered. Debug.Assert(parse.NewTable == null); Debug.Assert(Btree.HoldsAllMutexes(ctx)); //if (ctx.MallocFailed) goto exit_begin_add_column; Table table = parse.LocateTableItem(false, src.Ids[0]); if (table == null) goto exit_begin_add_column; #if !OMIT_VIRTUALTABLE if (IsVirtual(table)) { parse.ErrorMsg("virtual tables may not be altered"); goto exit_begin_add_column; } #endif // Make sure this is not an attempt to ALTER a view. if (table.Select != null) { parse.ErrorMsg("Cannot add a column to a view"); goto exit_begin_add_column; } if (IsSystemTable(parse, table.Name)) goto exit_begin_add_column; Debug.Assert(table.AddColOffset > 0); int db = Prepare.SchemaToIndex(ctx, table.Schema); // Put a copy of the Table struct in Parse.pNewTable for the sqlite3AddColumn() function and friends to modify. But modify // the name by adding an "sqlite_altertab_" prefix. By adding this prefix, we insure that the name will not collide with an existing // table because user table are not allowed to have the "sqlite_" prefix on their name. Table newTable = new Table(); if (newTable == null) goto exit_begin_add_column; parse.NewTable = newTable; newTable.Refs = 1; newTable.Cols.length = table.Cols.length; Debug.Assert(newTable.Cols.length > 0); int allocs = (((newTable.Cols.length - 1) / 8) * 8) + 8; Debug.Assert(allocs >= newTable.Cols.length && allocs % 8 == 0 && allocs - newTable.Cols.length < 8); newTable.Cols.data = new Column[allocs]; newTable.Name = C._mtagprintf(ctx, "sqlite_altertab_%s", table.Name); if (newTable.Cols.data == null || newTable.Name == null) { ctx.MallocFailed = true; goto exit_begin_add_column; } for (int i = 0; i < newTable.Cols.length; i++) { Column col = table.Cols[i].memcpy(); col.Coll = null; col.Type = null; col.Dflt = null; col.Dflt = null; newTable.Cols[i] = col; } newTable.Schema = ctx.DBs[db].Schema; newTable.AddColOffset = table.AddColOffset; newTable.Refs = 1; // Begin a transaction and increment the schema cookie. parse.BeginWriteOperation(0, db); Vdbe v = parse.V; if (v == null) goto exit_begin_add_column; parse.ChangeCookie(db); exit_begin_add_column: sqlite3SrcListDelete(ctx, ref src); return; } } } #endif #endregion
using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace OmniSharp.Intellisense { static partial class MemberDeclarationSyntaxExtensions { public static SyntaxList<AttributeListSyntax> GetAttributes(this MemberDeclarationSyntax member) { if (member != null) { switch (member.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)member).AttributeLists; case SyntaxKind.EnumMemberDeclaration: return ((EnumMemberDeclarationSyntax)member).AttributeLists; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: return ((TypeDeclarationSyntax)member).AttributeLists; case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)member).AttributeLists; case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)member).AttributeLists; case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)member).AttributeLists; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)member).AttributeLists; case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)member).AttributeLists; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)member).AttributeLists; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)member).AttributeLists; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)member).AttributeLists; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)member).AttributeLists; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)member).AttributeLists; case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member).AttributeLists; case SyntaxKind.IncompleteMember: return ((IncompleteMemberSyntax)member).AttributeLists; } } return SyntaxFactory.List<AttributeListSyntax>(); } public static SyntaxToken GetNameToken(this MemberDeclarationSyntax member) { if (member != null) { switch (member.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)member).Identifier; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: return ((TypeDeclarationSyntax)member).Identifier; case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)member).Identifier; case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)member).Declaration.Variables.First().Identifier; case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)member).Declaration.Variables.First().Identifier; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)member).Identifier; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)member).Identifier; case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member).Identifier; } } // Constructors, destructors, indexers and operators don't have names. return default(SyntaxToken); } public static int GetArity(this MemberDeclarationSyntax member) { if (member != null) { switch (member.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: return ((TypeDeclarationSyntax)member).Arity; case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)member).Arity; case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member).Arity; } } return 0; } public static TypeParameterListSyntax GetTypeParameterList(this MemberDeclarationSyntax member) { if (member != null) { switch (member.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: return ((TypeDeclarationSyntax)member).TypeParameterList; case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)member).TypeParameterList; case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member).TypeParameterList; } } return null; } public static BaseParameterListSyntax GetParameterList(this MemberDeclarationSyntax member) { if (member != null) { switch (member.Kind()) { case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)member).ParameterList; case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member).ParameterList; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)member).ParameterList; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)member).ParameterList; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)member).ParameterList; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)member).ParameterList; } } return null; } public static MemberDeclarationSyntax WithParameterList( this MemberDeclarationSyntax member, BaseParameterListSyntax parameterList) { if (member != null) { switch (member.Kind()) { case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)member).WithParameterList((ParameterListSyntax)parameterList); case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member).WithParameterList((ParameterListSyntax)parameterList); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)member).WithParameterList((ParameterListSyntax)parameterList); case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)member).WithParameterList((BracketedParameterListSyntax)parameterList); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)member).WithParameterList((ParameterListSyntax)parameterList); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)member).WithParameterList((ParameterListSyntax)parameterList); } } return null; } public static MemberDeclarationSyntax AddAttributeLists( this MemberDeclarationSyntax member, params AttributeListSyntax[] attributeLists) { return member.WithAttributeLists(member.GetAttributes().AddRange(attributeLists)); } public static MemberDeclarationSyntax WithAttributeLists( this MemberDeclarationSyntax member, SyntaxList<AttributeListSyntax> attributeLists) { if (member != null) { switch (member.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.EnumMemberDeclaration: return ((EnumMemberDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: return ((TypeDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member).WithAttributeLists(attributeLists); case SyntaxKind.IncompleteMember: return ((IncompleteMemberSyntax)member).WithAttributeLists(attributeLists); } } return null; } public static TypeSyntax GetMemberType(this MemberDeclarationSyntax member) { if (member != null) { switch (member.Kind()) { case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)member).ReturnType; case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member).ReturnType; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)member).ReturnType; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)member).Type; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)member).Type; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)member).Type; case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)member).Declaration.Type; case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)member).Declaration.Type; } } return null; } public static bool HasMethodShape(this MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration != null) { switch (memberDeclaration.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return true; } } return false; } public static BlockSyntax GetBody(this MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration != null) { switch (memberDeclaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)memberDeclaration).Body; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)memberDeclaration).Body; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)memberDeclaration).Body; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)memberDeclaration).Body; case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)memberDeclaration).Body; } } return null; } public static MemberDeclarationSyntax WithBody( this MemberDeclarationSyntax memberDeclaration, BlockSyntax body) { if (memberDeclaration != null) { switch (memberDeclaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)memberDeclaration).WithBody(body); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)memberDeclaration).WithBody(body); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)memberDeclaration).WithBody(body); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)memberDeclaration).WithBody(body); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)memberDeclaration).WithBody(body); } } return null; } } }
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 TeamManager.Areas.HelpPage.SampleGeneration { /// <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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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.ActionDescriptor.ReturnType; 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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace ClosedXML.Excel { [DebuggerDisplay("{Name}")] internal class XLPivotTable : IXLPivotTable { private String _name; public Guid Guid { get; private set; } public XLPivotTable(IXLWorksheet worksheet) { this.Worksheet = worksheet ?? throw new ArgumentNullException(nameof(worksheet)); this.Guid = Guid.NewGuid(); Fields = new XLPivotFields(this); ReportFilters = new XLPivotFields(this); ColumnLabels = new XLPivotFields(this); RowLabels = new XLPivotFields(this); Values = new XLPivotValues(this); Theme = XLPivotTableTheme.PivotStyleLight16; SetExcelDefaults(); } public IXLCell TargetCell { get; set; } private IXLRange sourceRange; public IXLRange SourceRange { get { return sourceRange; } set { if (value is IXLTable) SourceType = XLPivotTableSourceType.Table; else SourceType = XLPivotTableSourceType.Range; sourceRange = value; } } public IXLTable SourceTable { get { return SourceRange as IXLTable; } set { SourceRange = value; } } public XLPivotTableSourceType SourceType { get; private set; } public IEnumerable<string> SourceRangeFieldsAvailable { get { return this.SourceRange.FirstRow().Cells().Select(c => c.GetString()); } } public IXLPivotFields Fields { get; private set; } public IXLPivotFields ReportFilters { get; private set; } public IXLPivotFields ColumnLabels { get; private set; } public IXLPivotFields RowLabels { get; private set; } public IXLPivotValues Values { get; private set; } public XLPivotTableTheme Theme { get; set; } public IXLPivotTable SetTheme(XLPivotTableTheme value) { Theme = value; return this; } public String Name { get { return _name; } set { if (_name == value) return; var oldname = _name ?? string.Empty; if (!XLHelper.ValidateName("pivot table", value, oldname, Worksheet.PivotTables.Select(pvt => pvt.Name), out String message)) throw new ArgumentException(message, nameof(value)); _name = value; if (!String.IsNullOrWhiteSpace(oldname) && !String.Equals(oldname, _name, StringComparison.OrdinalIgnoreCase)) { Worksheet.PivotTables.Delete(oldname); (Worksheet.PivotTables as XLPivotTables).Add(_name, this); } } } public IXLPivotTable SetName(String value) { Name = value; return this; } public String Title { get; set; } public IXLPivotTable SetTitle(String value) { Title = value; return this; } public String Description { get; set; } public IXLPivotTable SetDescription(String value) { Description = value; return this; } public String ColumnHeaderCaption { get; set; } public IXLPivotTable SetColumnHeaderCaption(String value) { ColumnHeaderCaption = value; return this; } public String RowHeaderCaption { get; set; } public IXLPivotTable SetRowHeaderCaption(String value) { RowHeaderCaption = value; return this; } public Boolean MergeAndCenterWithLabels { get; set; } public IXLPivotTable SetMergeAndCenterWithLabels() { MergeAndCenterWithLabels = true; return this; } public IXLPivotTable SetMergeAndCenterWithLabels(Boolean value) { MergeAndCenterWithLabels = value; return this; } public Int32 RowLabelIndent { get; set; } public IXLPivotTable SetRowLabelIndent(Int32 value) { RowLabelIndent = value; return this; } public XLFilterAreaOrder FilterAreaOrder { get; set; } public IXLPivotTable SetFilterAreaOrder(XLFilterAreaOrder value) { FilterAreaOrder = value; return this; } public Int32 FilterFieldsPageWrap { get; set; } public IXLPivotTable SetFilterFieldsPageWrap(Int32 value) { FilterFieldsPageWrap = value; return this; } public String ErrorValueReplacement { get; set; } public IXLPivotTable SetErrorValueReplacement(String value) { ErrorValueReplacement = value; return this; } public String EmptyCellReplacement { get; set; } public IXLPivotTable SetEmptyCellReplacement(String value) { EmptyCellReplacement = value; return this; } public Boolean AutofitColumns { get; set; } public IXLPivotTable SetAutofitColumns() { AutofitColumns = true; return this; } public IXLPivotTable SetAutofitColumns(Boolean value) { AutofitColumns = value; return this; } public Boolean PreserveCellFormatting { get; set; } public IXLPivotTable SetPreserveCellFormatting() { PreserveCellFormatting = true; return this; } public IXLPivotTable SetPreserveCellFormatting(Boolean value) { PreserveCellFormatting = value; return this; } public Boolean ShowGrandTotalsRows { get; set; } public IXLPivotTable SetShowGrandTotalsRows() { ShowGrandTotalsRows = true; return this; } public IXLPivotTable SetShowGrandTotalsRows(Boolean value) { ShowGrandTotalsRows = value; return this; } public Boolean ShowGrandTotalsColumns { get; set; } public IXLPivotTable SetShowGrandTotalsColumns() { ShowGrandTotalsColumns = true; return this; } public IXLPivotTable SetShowGrandTotalsColumns(Boolean value) { ShowGrandTotalsColumns = value; return this; } public Boolean FilteredItemsInSubtotals { get; set; } public IXLPivotTable SetFilteredItemsInSubtotals() { FilteredItemsInSubtotals = true; return this; } public IXLPivotTable SetFilteredItemsInSubtotals(Boolean value) { FilteredItemsInSubtotals = value; return this; } public Boolean AllowMultipleFilters { get; set; } public IXLPivotTable SetAllowMultipleFilters() { AllowMultipleFilters = true; return this; } public IXLPivotTable SetAllowMultipleFilters(Boolean value) { AllowMultipleFilters = value; return this; } public Boolean UseCustomListsForSorting { get; set; } public IXLPivotTable SetUseCustomListsForSorting() { UseCustomListsForSorting = true; return this; } public IXLPivotTable SetUseCustomListsForSorting(Boolean value) { UseCustomListsForSorting = value; return this; } public Boolean ShowExpandCollapseButtons { get; set; } public IXLPivotTable SetShowExpandCollapseButtons() { ShowExpandCollapseButtons = true; return this; } public IXLPivotTable SetShowExpandCollapseButtons(Boolean value) { ShowExpandCollapseButtons = value; return this; } public Boolean ShowContextualTooltips { get; set; } public IXLPivotTable SetShowContextualTooltips() { ShowContextualTooltips = true; return this; } public IXLPivotTable SetShowContextualTooltips(Boolean value) { ShowContextualTooltips = value; return this; } public Boolean ShowPropertiesInTooltips { get; set; } public IXLPivotTable SetShowPropertiesInTooltips() { ShowPropertiesInTooltips = true; return this; } public IXLPivotTable SetShowPropertiesInTooltips(Boolean value) { ShowPropertiesInTooltips = value; return this; } public Boolean DisplayCaptionsAndDropdowns { get; set; } public IXLPivotTable SetDisplayCaptionsAndDropdowns() { DisplayCaptionsAndDropdowns = true; return this; } public IXLPivotTable SetDisplayCaptionsAndDropdowns(Boolean value) { DisplayCaptionsAndDropdowns = value; return this; } public Boolean ClassicPivotTableLayout { get; set; } public IXLPivotTable SetClassicPivotTableLayout() { ClassicPivotTableLayout = true; return this; } public IXLPivotTable SetClassicPivotTableLayout(Boolean value) { ClassicPivotTableLayout = value; return this; } public Boolean ShowValuesRow { get; set; } public IXLPivotTable SetShowValuesRow() { ShowValuesRow = true; return this; } public IXLPivotTable SetShowValuesRow(Boolean value) { ShowValuesRow = value; return this; } public Boolean ShowEmptyItemsOnRows { get; set; } public IXLPivotTable SetShowEmptyItemsOnRows() { ShowEmptyItemsOnRows = true; return this; } public IXLPivotTable SetShowEmptyItemsOnRows(Boolean value) { ShowEmptyItemsOnRows = value; return this; } public Boolean ShowEmptyItemsOnColumns { get; set; } public IXLPivotTable SetShowEmptyItemsOnColumns() { ShowEmptyItemsOnColumns = true; return this; } public IXLPivotTable SetShowEmptyItemsOnColumns(Boolean value) { ShowEmptyItemsOnColumns = value; return this; } public Boolean DisplayItemLabels { get; set; } public IXLPivotTable SetDisplayItemLabels() { DisplayItemLabels = true; return this; } public IXLPivotTable SetDisplayItemLabels(Boolean value) { DisplayItemLabels = value; return this; } public Boolean SortFieldsAtoZ { get; set; } public IXLPivotTable SetSortFieldsAtoZ() { SortFieldsAtoZ = true; return this; } public IXLPivotTable SetSortFieldsAtoZ(Boolean value) { SortFieldsAtoZ = value; return this; } public Boolean PrintExpandCollapsedButtons { get; set; } public IXLPivotTable SetPrintExpandCollapsedButtons() { PrintExpandCollapsedButtons = true; return this; } public IXLPivotTable SetPrintExpandCollapsedButtons(Boolean value) { PrintExpandCollapsedButtons = value; return this; } public Boolean RepeatRowLabels { get; set; } public IXLPivotTable SetRepeatRowLabels() { RepeatRowLabels = true; return this; } public IXLPivotTable SetRepeatRowLabels(Boolean value) { RepeatRowLabels = value; return this; } public Boolean PrintTitles { get; set; } public IXLPivotTable SetPrintTitles() { PrintTitles = true; return this; } public IXLPivotTable SetPrintTitles(Boolean value) { PrintTitles = value; return this; } public Boolean SaveSourceData { get; set; } public IXLPivotTable SetSaveSourceData() { SaveSourceData = true; return this; } public IXLPivotTable SetSaveSourceData(Boolean value) { SaveSourceData = value; return this; } public Boolean EnableShowDetails { get; set; } public IXLPivotTable SetEnableShowDetails() { EnableShowDetails = true; return this; } public IXLPivotTable SetEnableShowDetails(Boolean value) { EnableShowDetails = value; return this; } public Boolean RefreshDataOnOpen { get; set; } public IXLPivotTable SetRefreshDataOnOpen() { RefreshDataOnOpen = true; return this; } public IXLPivotTable SetRefreshDataOnOpen(Boolean value) { RefreshDataOnOpen = value; return this; } public XLItemsToRetain ItemsToRetainPerField { get; set; } public IXLPivotTable SetItemsToRetainPerField(XLItemsToRetain value) { ItemsToRetainPerField = value; return this; } public Boolean EnableCellEditing { get; set; } public IXLPivotTable SetEnableCellEditing() { EnableCellEditing = true; return this; } public IXLPivotTable SetEnableCellEditing(Boolean value) { EnableCellEditing = value; return this; } public Boolean ShowRowHeaders { get; set; } public IXLPivotTable SetShowRowHeaders() { ShowRowHeaders = true; return this; } public IXLPivotTable SetShowRowHeaders(Boolean value) { ShowRowHeaders = value; return this; } public Boolean ShowColumnHeaders { get; set; } public IXLPivotTable SetShowColumnHeaders() { ShowColumnHeaders = true; return this; } public IXLPivotTable SetShowColumnHeaders(Boolean value) { ShowColumnHeaders = value; return this; } public Boolean ShowRowStripes { get; set; } public IXLPivotTable SetShowRowStripes() { ShowRowStripes = true; return this; } public IXLPivotTable SetShowRowStripes(Boolean value) { ShowRowStripes = value; return this; } public Boolean ShowColumnStripes { get; set; } public IXLPivotTable SetShowColumnStripes() { ShowColumnStripes = true; return this; } public IXLPivotTable SetShowColumnStripes(Boolean value) { ShowColumnStripes = value; return this; } public XLPivotSubtotals Subtotals { get; set; } public IXLPivotTable SetSubtotals(XLPivotSubtotals value) { Subtotals = value; return this; } public XLPivotLayout Layout { set { Fields.ForEach(f => f.SetLayout(value)); } } public IXLPivotTable SetLayout(XLPivotLayout value) { Layout = value; return this; } public Boolean InsertBlankLines { set { Fields.ForEach(f => f.SetInsertBlankLines(value)); } } public IXLPivotTable SetInsertBlankLines() { InsertBlankLines = true; return this; } public IXLPivotTable SetInsertBlankLines(Boolean value) { InsertBlankLines = value; return this; } internal String RelId { get; set; } internal String CacheDefinitionRelId { get; set; } internal String WorkbookCacheRelId { get; set; } private void SetExcelDefaults() { EmptyCellReplacement = String.Empty; SaveSourceData = true; ShowColumnHeaders = true; ShowRowHeaders = true; // source http://www.datypic.com/sc/ooxml/e-ssml_pivotTableDefinition.html DisplayItemLabels = true; // Show Item Names ShowExpandCollapseButtons = true; // Show Expand Collapse PrintExpandCollapsedButtons = false; // Print Drill Indicators ShowPropertiesInTooltips = true; // Show Member Property ToolTips ShowContextualTooltips = true; // Show ToolTips on Data EnableShowDetails = true; // Enable Drill Down PreserveCellFormatting = true; // Preserve Formatting AutofitColumns = false; // Auto Formatting FilterAreaOrder = XLFilterAreaOrder.DownThenOver; // Page Over Then Down FilteredItemsInSubtotals = false; // Subtotal Hidden Items ShowGrandTotalsRows = true; // Row Grand Totals ShowGrandTotalsColumns = true; // Grand Totals On Columns PrintTitles = false; // Field Print Titles RepeatRowLabels = false; // Item Print Titles MergeAndCenterWithLabels = false; // Merge Titles RowLabelIndent = 1; // Indentation for Compact Axis ShowEmptyItemsOnRows = false; // Show Empty Row ShowEmptyItemsOnColumns = false; // Show Empty Column DisplayCaptionsAndDropdowns = true; // Show Field Headers ClassicPivotTableLayout = false; // Enable Drop Zones AllowMultipleFilters = true; // Multiple Field Filters SortFieldsAtoZ = false; // Default Sort Order UseCustomListsForSorting = true; // Custom List AutoSort } public IXLWorksheet Worksheet { get; } } }
namespace Geocrest.Web.Mvc.Documentation { 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; using System.Web.Http; using System.Web.Http.Description; using System.Web.Http.Routing; using System.Xml.Linq; using Newtonsoft.Json; using Geocrest.Web.Infrastructure; using Geocrest.Web.Mvc; /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="T:Geocrest.Web.Mvc.Documentation.HelpPageSampleGenerator" /> class. /// </summary> public HelpPageSampleGenerator() :this(true) { } /// <summary> /// Initializes a new instance of the <see cref="T:Geocrest.Web.Mvc.Documentation.HelpPageSampleGenerator" /> class. /// </summary> /// <param name="useDataMembersOnly">if set to <b>true</b> use data members only.</param> public HelpPageSampleGenerator(bool useDataMembersOnly) { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); HtmlSamples = new List<KeyValuePair<HelpPageSampleKey, HtmlSample>>(); DataMembersOnly = useDataMembersOnly; } /// <summary> /// Gets a value indicating whether to use only those properties that are marked as /// <see cref="T:System.Runtime.Serialization.DataMemberAttribute"/>s. /// </summary> /// <value> /// <c>true</c> if this instance uses data members only; otherwise, <c>false</c>. /// </value> public bool DataMembersOnly { get; private set; } /// <summary> /// Gets CLR types that are used as the content of <see cref="T:System.Net.Http.HttpRequestMessage"/> or /// <see cref="T:System.Net.Http.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 the objects used to render HTML on the sample page. /// </summary> public List<KeyValuePair<HelpPageSampleKey, HtmlSample>> HtmlSamples { get; internal set; } ///// <summary> ///// Gets the HTML samples for a given <see cref="T:System.Web.Http.Description.ApiDescription" />. ///// </summary> ///// <param name="api">The <see cref="T:System.Web.Http.Description.ApiDescription" />.</param> ///// <returns> ///// Returns an instance of <see cref="List&lt;Geocrest.Web.Mvc.Documentation.HtmlSample&gt;"> ///// List&lt;Geocrest.Web.Mvc.Documentation.HtmlSample&gt;</see>. ///// </returns> ///// <exception cref="System.ArgumentNullException">api</exception> //public List<HtmlSample> GetLiveSamples(System.Web.Http.Description.ApiDescription api) //{ // Throw.IfArgumentNull(api, "api"); // string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; // string actionName = api.ActionDescriptor.ActionName; // IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); // var samples = new List<HtmlSample>(); // var actionSamples = GetAllLiveSamples(api, parameterNames); // foreach (var actionSample in actionSamples) // { // samples.Add(actionSample.Value); // } // return samples; //} /// <summary> /// Gets the request body samples for a given <see cref="T:System.Web.Http.Description.ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="T:System.Web.Http.Description.ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(System.Web.Http.Description.ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="T:System.Web.Http.Description.ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="System.Web.Http.Description.ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(System.Web.Http.Description.ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the HTML samples associated with the given route parameters /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <returns> /// The associated <see cref="T:Geocrest.Web.Mvc.Documentation.HtmlSample"/>. /// </returns> /// <exception cref="System.ArgumentNullException">controllerName</exception> /// <exception cref="System.ArgumentNullException">actionName</exception> /// <exception cref="System.ArgumentNullException">parameterNames</exception> public virtual IEnumerable<HtmlSample> GetHtmlSamples(string controllerName, string actionName, IEnumerable<string> parameterNames) { Throw.IfArgumentNullOrEmpty(controllerName, "controllerName"); Throw.IfArgumentNullOrEmpty(actionName, "actionName"); Throw.IfArgumentNull(parameterNames, "parameterNames"); var samples = new List<HtmlSample>(); HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in HtmlSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && parameterNamesSet.Count == sampleKey.ParameterNames.Count && parameterNamesSet.All(x => sampleKey.ParameterNames.Contains(x))) { samples.Add(sample.Value); } } return samples.AsEnumerable(); } ///// <summary> ///// Gets the HTML sample associated with a given <see cref="T:System.Web.Http.Description.ApiDescription" />. ///// </summary> ///// <param name="api">The API description containing the route values.</param> ///// <returns> ///// The associated <see cref="T:Geocrest.Web.Mvc.Documentation.HtmlSample" />. ///// </returns> ///// <exception cref="System.ArgumentNullException">api</exception> //public virtual HtmlSample GetHtmlSample(System.Web.Http.Description.ApiDescription api) //{ // Throw.IfArgumentNull(api, "api"); // string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; // string actionName = api.ActionDescriptor.ActionName; // IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); // return GetHtmlSample(controllerName, actionName, parameterNames); //} /// <summary> /// Gets the HTML samples associated with a given <see cref="T:System.Web.Http.Description.ApiDescription" />. /// </summary> /// <param name="api">The API description containing the route values.</param> /// <returns> /// Returns a collection of <see cref="T:Geocrest.Web.Mvc.Documentation.HtmlSample"/>s. /// </returns> /// <exception cref="T:System.ArgumentNullException">api</exception> public virtual IEnumerable<HtmlSample> GetHtmlSamples(System.Web.Http.Description.ApiDescription api) { Throw.IfArgumentNull(api, "api"); string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); return GetHtmlSamples(controllerName, actionName, parameterNames); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="T:System.Web.Http.Description.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> /// <exception cref="System.ArgumentNullException">api</exception> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(System.Web.Http.Description.ApiDescription api, SampleDirection sampleDirection) { Throw.IfArgumentNull(api, "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(api, 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, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(api,formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample, formatter)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through /// <see cref="P:Geocrest.Web.Mvc.Documentation.HelpPageSampleGenerator.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="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, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || // The following line was removed so that a sample is required to match the parameters //ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new string[] { }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), 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="P:Geocrest.Web.Mvc.Documentation.HelpPageSampleGenerator.SampleObjects"/>. /// If no sample object is found, it will try to create one using <see cref="T:Geocrest.Web.Mvc.Documentation.ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type,this.DataMembersOnly); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when /// <see cref="T:System.Net.Http.HttpRequestMessage" /> or <see cref="T:System.Net.Http.HttpResponseMessage" /> is used. /// </summary> /// <param name="api">The API description.</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> /// <returns> /// Returns the return type for the action, the request body parameter type, or <see langword="null"/>. /// </returns> /// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException"><paramref name="sampleDirection" /> is not defined.</exception> /// <exception cref="T:System.ArgumentNullException">api</exception> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(System.Web.Http.Description.ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { Throw.IfEnumNotDefined<SampleDirection>(sampleDirection, "sampleDirection"); Throw.IfArgumentNull(api, "api"); Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new string[] { }), 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: System.Web.Http.Description.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.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="api">The API.</param> /// <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 an instance of <see cref="T:System.Object"/>. /// </returns> /// <exception cref="T:System.ArgumentNullException"> /// formatter /// or /// mediaType /// </exception> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(System.Web.Http.Description.ApiDescription api, MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { Throw.IfArgumentNull(formatter, "formatter"); Throw.IfArgumentNull(mediaType, "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); var request = new HttpRequestMessage(HttpMethod.Get, api.RelativePath.ToAbsoluteUrl()); request.Properties["MS_HttpConfiguration"] = GlobalConfiguration.Configuration; request.Properties["MS_HttpRouteData"] = api.Route.GetRouteData( GlobalConfiguration.Configuration.VirtualPathRoot,request); request.Properties["MS_HttpContext"] = new HttpContextWrapper(HttpContext.Current); UrlHelper helper = new UrlHelper(request); var enrichers = GlobalConfiguration.Configuration.GetResponseEnrichers(); var enriched = enrichers.Where(e => e.CanEnrich(type,helper,mediaType)) .Aggregate(value, (url, enricher) => enricher.Enrich(api.RelativePath.ToAbsoluteUrl(),helper,value)); formatter.WriteToStreamAsync(type, enriched, 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,formatter.SupportedMediaTypes); } 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, e.GetExceptionMessages())); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } #region Helper Methods [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); JsonSerializerSettings settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings; settings.Formatting = Formatting.Indented; return JsonConvert.SerializeObject(parsedJson, settings); } 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(System.Web.Http.Description.ApiDescription api, 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(api.ActionDescriptor.ControllerDescriptor.ControllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(api.ActionDescriptor.ActionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && api.ParameterDescriptions.Count == sampleKey.ParameterNames.Count && api.ParameterDescriptions.All(x => sampleKey.ParameterNames.Contains(x.Name)) && //(sampleKey.ParameterNames.SetEquals(new string[] { }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } //private IEnumerable<KeyValuePair<HelpPageSampleKey, HtmlSample>> GetAllLiveSamples(System.Web.Http.Description.ApiDescription api, // IEnumerable<string> parameterNames) //{ // HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); // foreach (var sample in HtmlSamples) // { // HelpPageSampleKey sampleKey = sample.Key; // if (String.Equals(api.ActionDescriptor.ControllerDescriptor.ControllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && // String.Equals(api.ActionDescriptor.ActionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && // api.ParameterDescriptions.Count == sampleKey.ParameterNames.Count && // api.ParameterDescriptions.All(x => sampleKey.ParameterNames.Contains(x.Name))) // { // yield return sample; // } // } //} private static object WrapSampleIfString(object sample, MediaTypeFormatter formatter = null) { string stringSample = sample as string; if (stringSample != null) { if (formatter == null) return new TextSample(stringSample); else return new TextSample(stringSample, formatter.SupportedMediaTypes); } return sample; } #endregion } }
using ICSharpCode.TextEditor.Document; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace ICSharpCode.TextEditor { public class IconBarMargin : AbstractMargin { private const int iconBarWidth = 18; private static readonly Size iconBarSize = new Size(18, -1); public override Size Size { get { return IconBarMargin.iconBarSize; } } public override bool IsVisible { get { return this.textArea.TextEditorProperties.IsIconBarVisible; } } public IconBarMargin(TextArea textArea) : base(textArea) { } public override void Paint(Graphics g, Rectangle rect) { if (rect.Width <= 0 || rect.Height <= 0) { return; } g.FillRectangle(SystemBrushes.Control, new Rectangle(this.drawingPosition.X, rect.Top, this.drawingPosition.Width - 1, rect.Height)); g.DrawLine(SystemPens.ControlDark, this.drawingPosition.Right - 1, rect.Top, this.drawingPosition.Right - 1, rect.Bottom); foreach (Bookmark current in this.textArea.Document.BookmarkManager.Marks) { int visibleLine = this.textArea.Document.GetVisibleLine(current.LineNumber); int fontHeight = this.textArea.TextView.FontHeight; int num = visibleLine * fontHeight - this.textArea.VirtualTop.Y; if (IconBarMargin.IsLineInsideRegion(num, num + fontHeight, rect.Y, rect.Bottom) && visibleLine != this.textArea.Document.GetVisibleLine(current.LineNumber - 1)) { current.Draw(this, g, new Point(0, num)); } } base.Paint(g, rect); } public override void HandleMouseDown(Point mousePos, MouseButtons mouseButtons) { int lineNumber = (mousePos.Y + this.textArea.VirtualTop.Y) / this.textArea.TextView.FontHeight; int firstLogicalLine = this.textArea.Document.GetFirstLogicalLine(lineNumber); if ((mouseButtons & MouseButtons.Right) == MouseButtons.Right && this.textArea.Caret.Line != firstLogicalLine) { this.textArea.Caret.Line = firstLogicalLine; } IList<Bookmark> marks = this.textArea.Document.BookmarkManager.Marks; List<Bookmark> list = new List<Bookmark>(); int count = marks.Count; foreach (Bookmark current in marks) { if (current.LineNumber == firstLogicalLine) { list.Add(current); } } for (int i = list.Count - 1; i >= 0; i--) { Bookmark bookmark = list[i]; if (bookmark.Click(this.textArea, new MouseEventArgs(mouseButtons, 1, mousePos.X, mousePos.Y, 0))) { if (count != marks.Count) { this.textArea.UpdateLine(firstLogicalLine); } return; } } base.HandleMouseDown(mousePos, mouseButtons); } public void DrawBreakpoint(Graphics g, int y, bool isEnabled, bool isHealthy) { int num = Math.Min(16, this.textArea.TextView.FontHeight); Rectangle rect = new Rectangle(1, y + (this.textArea.TextView.FontHeight - num) / 2, num, num); using (GraphicsPath graphicsPath = new GraphicsPath()) { graphicsPath.AddEllipse(rect); using (PathGradientBrush pathGradientBrush = new PathGradientBrush(graphicsPath)) { pathGradientBrush.CenterPoint = new PointF((float)(rect.Left + rect.Width / 3), (float)(rect.Top + rect.Height / 3)); pathGradientBrush.CenterColor = Color.MistyRose; Color[] surroundColors = new Color[] { isHealthy ? Color.Firebrick : Color.Olive }; pathGradientBrush.SurroundColors = surroundColors; if (isEnabled) { g.FillEllipse(pathGradientBrush, rect); } else { g.FillEllipse(SystemBrushes.Control, rect); using (Pen pen = new Pen(pathGradientBrush)) { g.DrawEllipse(pen, new Rectangle(rect.X + 1, rect.Y + 1, rect.Width - 2, rect.Height - 2)); } } } } } public void DrawBookmark(Graphics g, int y, bool isEnabled) { int num = this.textArea.TextView.FontHeight / 8; Rectangle r = new Rectangle(1, y + num, this.drawingPosition.Width - 4, this.textArea.TextView.FontHeight - num * 2); if (isEnabled) { using (Brush brush = new LinearGradientBrush(new Point(r.Left, r.Top), new Point(r.Right, r.Bottom), Color.SkyBlue, Color.White)) { this.FillRoundRect(g, brush, r); goto IL_9A; } } this.FillRoundRect(g, Brushes.White, r); IL_9A: using (Brush brush2 = new LinearGradientBrush(new Point(r.Left, r.Top), new Point(r.Right, r.Bottom), Color.SkyBlue, Color.Blue)) { using (Pen pen = new Pen(brush2)) { this.DrawRoundRect(g, pen, r); } } } public void DrawArrow(Graphics g, int y) { int num = this.textArea.TextView.FontHeight / 8; Rectangle r = new Rectangle(1, y + num, this.drawingPosition.Width - 4, this.textArea.TextView.FontHeight - num * 2); using (Brush brush = new LinearGradientBrush(new Point(r.Left, r.Top), new Point(r.Right, r.Bottom), Color.LightYellow, Color.Yellow)) { this.FillArrow(g, brush, r); } using (Brush brush2 = new LinearGradientBrush(new Point(r.Left, r.Top), new Point(r.Right, r.Bottom), Color.Yellow, Color.Brown)) { using (Pen pen = new Pen(brush2)) { this.DrawArrow(g, pen, r); } } } private GraphicsPath CreateArrowGraphicsPath(Rectangle r) { GraphicsPath graphicsPath = new GraphicsPath(); int num = r.Width / 2; int num2 = r.Height / 2; graphicsPath.AddLine(r.X, r.Y + num2 / 2, r.X + num, r.Y + num2 / 2); graphicsPath.AddLine(r.X + num, r.Y + num2 / 2, r.X + num, r.Y); graphicsPath.AddLine(r.X + num, r.Y, r.Right, r.Y + num2); graphicsPath.AddLine(r.Right, r.Y + num2, r.X + num, r.Bottom); graphicsPath.AddLine(r.X + num, r.Bottom, r.X + num, r.Bottom - num2 / 2); graphicsPath.AddLine(r.X + num, r.Bottom - num2 / 2, r.X, r.Bottom - num2 / 2); graphicsPath.AddLine(r.X, r.Bottom - num2 / 2, r.X, r.Y + num2 / 2); graphicsPath.CloseFigure(); return graphicsPath; } private GraphicsPath CreateRoundRectGraphicsPath(Rectangle r) { GraphicsPath graphicsPath = new GraphicsPath(); int num = r.Width / 2; graphicsPath.AddLine(r.X + num, r.Y, r.Right - num, r.Y); graphicsPath.AddArc(r.Right - num, r.Y, num, num, 270f, 90f); graphicsPath.AddLine(r.Right, r.Y + num, r.Right, r.Bottom - num); graphicsPath.AddArc(r.Right - num, r.Bottom - num, num, num, 0f, 90f); graphicsPath.AddLine(r.Right - num, r.Bottom, r.X + num, r.Bottom); graphicsPath.AddArc(r.X, r.Bottom - num, num, num, 90f, 90f); graphicsPath.AddLine(r.X, r.Bottom - num, r.X, r.Y + num); graphicsPath.AddArc(r.X, r.Y, num, num, 180f, 90f); graphicsPath.CloseFigure(); return graphicsPath; } private void DrawRoundRect(Graphics g, Pen p, Rectangle r) { using (GraphicsPath graphicsPath = this.CreateRoundRectGraphicsPath(r)) { g.DrawPath(p, graphicsPath); } } private void FillRoundRect(Graphics g, Brush b, Rectangle r) { using (GraphicsPath graphicsPath = this.CreateRoundRectGraphicsPath(r)) { g.FillPath(b, graphicsPath); } } private void DrawArrow(Graphics g, Pen p, Rectangle r) { using (GraphicsPath graphicsPath = this.CreateArrowGraphicsPath(r)) { g.DrawPath(p, graphicsPath); } } private void FillArrow(Graphics g, Brush b, Rectangle r) { using (GraphicsPath graphicsPath = this.CreateArrowGraphicsPath(r)) { g.FillPath(b, graphicsPath); } } private static bool IsLineInsideRegion(int top, int bottom, int regionTop, int regionBottom) { return (top >= regionTop && top <= regionBottom) || (regionTop > top && regionTop < bottom); } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2017-2018 FUJIWARA, Yusuke // // 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 -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; namespace MsgPack { /// <summary> /// Represents high resolution timestamp for MessagePack eco-system. /// </summary> /// <remarks> /// The <c>timestamp</c> consists of 64bit Unix epoc seconds and 32bit unsigned nanoseconds offset from the calculated datetime with the epoc. /// So this type supports wider range than <see cref="System.DateTime" /> and <see cref="System.DateTimeOffset" /> and supports 1 or 10 nano seconds precision. /// However, this type does not support local date time and time zone information, so this type always represents UTC time. /// </remarks> #if FEATURE_BINARY_SERIALIZATION [Serializable] #endif // FEATURE_BINARY_SERIALIZATION public partial struct Timestamp { /// <summary> /// MessagePack ext type code for msgpack timestamp type. /// </summary> public const byte TypeCode = 0xFF; /// <summary> /// An instance represents zero. This is 1970-01-01T00:00:00.000000000. /// </summary> public static readonly Timestamp Zero = new Timestamp( 0, 0 ); /// <summary> /// An instance represents minimum value of this instance. This is <c>[<see cref="Int64.MinValue"/>, 0]</c> in encoded format. /// </summary> public static readonly Timestamp MinValue = new Timestamp( Int64.MinValue, 0 ); /// <summary> /// An instance represents maximum value of this instance. This is <c>[<see cref="Int64.MaxValue"/>, 999999999]</c> in encoded format. /// </summary> public static readonly Timestamp MaxValue = new Timestamp( Int64.MaxValue, MaxNanoSeconds ); private static readonly int[] LastDays = new[] { 0, // There are no month=0 31, 0, // 28 or 29 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private const long MinUnixEpochSecondsForTicks = -62135596800L; private const long MaxUnixEpochSecondsForTicks = 253402300799; private const int MaxNanoSeconds = 999999999; private const long UnixEpochTicks = 621355968000000000; private const long UnixEpochInSeconds = 62135596800; private const int SecondsToTicks = 10 * 1000 * 1000; private const int NanoToTicks = 100; private const int SecondsToNanos = 1000 * 1000 * 1000; private readonly long unixEpochSeconds; private readonly uint nanoseconds; // 0 - 999,999,999 /// <summary> /// Initializes a new instance of <see cref="Timestamp"/> structure. /// </summary> /// <param name="unixEpochSeconds">A unit epoc seconds part of the msgpack timestamp.</param> /// <param name="nanoseconds">A unit nanoseconds part of the msgpack timestamp.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="nanoseconds"/> is negative or is greater than <c>999,999,999</c> exclusive. /// </exception> public Timestamp( long unixEpochSeconds, int nanoseconds ) { if ( nanoseconds > MaxNanoSeconds || nanoseconds < 0 ) { throw new ArgumentOutOfRangeException( "nanoseconds", "nanoseconds must be non negative value and lessor than 999,999,999." ); } this.unixEpochSeconds = unixEpochSeconds; this.nanoseconds = unchecked( ( uint )nanoseconds ); } internal static Timestamp FromComponents( ref Value value, bool isLeapYear ) { long epoc; checked { var days = YearsToDaysOfNewYear( value.Year ) + ToDaysOffsetFromNewYear( value.Month, value.Day, isLeapYear ) - Timestamp.UnixEpochInSeconds / Timestamp.SecondsPerDay; // First set time offset to avoid overflow. epoc = value.Hour * 60 * 60; epoc += value.Minute * 60; epoc += value.Second; if ( days < 0 ) { // Avoid right side overflow. epoc += ( days + 1 ) * Timestamp.SecondsPerDay; epoc -= Timestamp.SecondsPerDay; } else { epoc += days * Timestamp.SecondsPerDay; } } return new Timestamp( epoc, unchecked( ( int )value.Nanoseconds ) ); } private static long YearsToDaysOfNewYear( long years ) { long remainOf400Years, remainOf100Years, remainOf4Years; // For AD, uses offset from 0001, so decrement 1 at first. var numberOf400Years = DivRem( years > 0 ? ( years - 1 ) : years, 400, out remainOf400Years ); var numberOf100Years = DivRem( remainOf400Years, 100, out remainOf100Years ); var numberOf4Years = DivRem( remainOf100Years, 4, out remainOf4Years ); var days = DaysPer400Years * numberOf400Years + DaysPer100Years * numberOf100Years + DaysPer4Years * numberOf4Years + DaysPerYear * remainOf4Years; if ( years <= 0 ) { // For BC, subtract year 0000 offset. days -= ( DaysPerYear + 1 ); } return days; } private static int ToDaysOffsetFromNewYear( int month, int day, bool isLeapYear ) { var result = -1; // 01-01 should be 0, so starts with -1. for ( var i = 1; i < month; i++ ) { result += LastDays[ i ]; if ( i == 2 ) { result += isLeapYear ? 29 : 28; } } result += day; return result; } #if NETSTANDARD1_1 || NETSTANDARD1_3 || SILVERLIGHT // Slow alternative internal static long DivRem( long dividend, long divisor, out long remainder ) { remainder = dividend % divisor; return dividend / divisor; } #else // NETSTANDARD1_1 || NETSTANDARD1_3 || SILVERLIGHT internal static long DivRem( long dividend, long divisor, out long remainder ) { return Math.DivRem( dividend, divisor, out remainder ); } #endif // NETSTANDARD1_1 || NETSTANDARD1_3 || SILVERLIGHT #if UNITY && DEBUG public #else internal #endif struct Value { public long Year; public int Month; public int Day; public int Hour; public int Minute; public int Second; public uint Nanoseconds; public Value( Timestamp encoded ) { int dayOfYear; encoded.GetDatePart( out this.Year, out this.Month, out this.Day, out dayOfYear ); this.Hour = encoded.Hour; this.Minute = encoded.Minute; this.Second = encoded.Second; this.Nanoseconds = encoded.nanoseconds; } #if DEBUG public Value( long year, int month, int day, int hour, int minute, int second, uint nanoseconds ) { this.Year = year; this.Month = month; this.Day = day; this.Hour = hour; this.Minute = minute; this.Second = second; this.Nanoseconds = nanoseconds; } #endif // DEBUG } } }
// 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> /// Convert.ToBoolean(Decimal) /// Converts the value of the specified decimal value to an equivalent Boolean value. /// </summary> public class ConvertToBoolean { public static int Main() { ConvertToBoolean testObj = new ConvertToBoolean(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToBoolean(Decimal)"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } 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; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string errorDesc; decimal d; bool expectedValue; bool actualValue; d = (decimal)TestLibrary.Generator.GetSingle(-55); TestLibrary.TestFramework.BeginScenario("PosTest1: Random decimal value between 0.0 and 1.0."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of decimal value " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("001", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe decimal value is " + d; TestLibrary.TestFramework.LogError("002", errorDesc); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string errorDesc; decimal d; bool expectedValue; bool actualValue; d = decimal.MaxValue; TestLibrary.TestFramework.BeginScenario("PosTest2: value is decimal.MaxValue."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of decimal value " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("003", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe decimal value is " + d; TestLibrary.TestFramework.LogError("004", errorDesc); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string errorDesc; decimal d; bool expectedValue; bool actualValue; d = decimal.MinValue; TestLibrary.TestFramework.BeginScenario("PosTest3: value is decimal.MinValue."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of decimal integer " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("005", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe decimal value is " + d; TestLibrary.TestFramework.LogError("006", errorDesc); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string errorDesc; decimal d; bool expectedValue; bool actualValue; d = decimal.Zero; TestLibrary.TestFramework.BeginScenario("PosTest4: value is decimal.Zero."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of decimal integer " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("007", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe decimal value is " + d; TestLibrary.TestFramework.LogError("008", errorDesc); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string errorDesc; decimal d; bool expectedValue; bool actualValue; d = -1 * (decimal)TestLibrary.Generator.GetSingle(-55); TestLibrary.TestFramework.BeginScenario("PosTest5: Random decimal value between -0.0 and -1.0."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of decimal integer " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("009", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe decimal value is " + d; TestLibrary.TestFramework.LogError("010", errorDesc); retVal = false; } return retVal; } #endregion }
// 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.AcceptanceTestsAzureBodyDurationAllSync { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// DurationOperations operations. /// </summary> internal partial class DurationOperations : IServiceOperations<AutoRestDurationTestService>, IDurationOperations { /// <summary> /// Initializes a new instance of the DurationOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DurationOperations(AutoRestDurationTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestDurationTestService /// </summary> public AutoRestDurationTestService Client { get; private set; } /// <summary> /// Get null duration value /// </summary> /// <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="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<TimeSpan?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // 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, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<TimeSpan?>(); _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 = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put a positive duration value /// </summary> /// <param name='durationBody'> /// </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> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutPositiveDurationWithHttpMessagesAsync(TimeSpan durationBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("durationBody", durationBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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; _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a positive duration value /// </summary> /// <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="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<TimeSpan?>> GetPositiveDurationWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // 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, "GetPositiveDuration", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<TimeSpan?>(); _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 = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get an invalid duration value /// </summary> /// <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="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<TimeSpan?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // 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, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<TimeSpan?>(); _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 = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.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; } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Data.Edm.Expressions; using Microsoft.Data.Edm.Library.Values; using Microsoft.Data.Edm.Validation; using Microsoft.Data.Edm.Values; namespace Microsoft.Data.Edm.Evaluation { /// <summary> /// Expression evaluator. /// </summary> public class EdmExpressionEvaluator { private readonly IDictionary<IEdmFunction, Func<IEdmValue[], IEdmValue>> builtInFunctions; private readonly Dictionary<IEdmLabeledExpression, DelayedValue> labeledValues = new Dictionary<IEdmLabeledExpression, DelayedValue>(); private readonly Func<string, IEdmValue[], IEdmValue> lastChanceFunctionApplier; /// <summary> /// Initializes a new instance of the EdmExpressionEvaluator class. /// </summary> /// <param name="builtInFunctions">Builtin functions dictionary to the evaluators for the functions.</param> public EdmExpressionEvaluator(IDictionary<IEdmFunction, Func<IEdmValue[], IEdmValue>> builtInFunctions) { this.builtInFunctions = builtInFunctions; } /// <summary> /// Initializes a new instance of the EdmExpressionEvaluator class. /// </summary> /// <param name="builtInFunctions">Builtin functions dictionary to the evaluators for the functions.</param> /// <param name="lastChanceFunctionApplier">Function to call to evaluate an application of a function with no static binding.</param> public EdmExpressionEvaluator(IDictionary<IEdmFunction, Func<IEdmValue[], IEdmValue>> builtInFunctions, Func<string, IEdmValue[], IEdmValue> lastChanceFunctionApplier) : this(builtInFunctions) { this.lastChanceFunctionApplier = lastChanceFunctionApplier; } /// <summary> /// Evaluates an expression with no value context. /// </summary> /// <param name="expression">Expression to evaluate. The expression must not contain paths, because no context for evaluating a path is supplied.</param> /// <returns>The value that results from evaluating the expression in the context of the supplied value.</returns> public IEdmValue Evaluate(IEdmExpression expression) { EdmUtil.CheckArgumentNull(expression, "expression"); return this.Eval(expression, null); } /// <summary> /// Evaluates an expression in the context of a value. /// </summary> /// <param name="expression">Expression to evaluate.</param> /// <param name="context">Value to use as context in evaluating the expression. Cannot be null if the expression contains paths.</param> /// <returns>The value that results from evaluating the expression in the context of the supplied value.</returns> public IEdmValue Evaluate(IEdmExpression expression, IEdmStructuredValue context) { EdmUtil.CheckArgumentNull(expression, "expression"); return this.Eval(expression, context); } /// <summary> /// Evaluates an expression in the context of a value and a target type. /// </summary> /// <param name="expression">Expression to evaluate.</param> /// <param name="context">Value to use as context in evaluating the expression. Cannot be null if the expression contains paths.</param> /// <param name="targetType">Type to which the result value is expected to conform.</param> /// <returns>The value that results from evaluating the expression in the context of the supplied value, asserted to be of the target type.</returns> public IEdmValue Evaluate(IEdmExpression expression, IEdmStructuredValue context, IEdmTypeReference targetType) { EdmUtil.CheckArgumentNull(expression, "expression"); EdmUtil.CheckArgumentNull(targetType, "targetType"); return AssertType(targetType, this.Eval(expression, context)); } private static bool InRange(Int64 value, Int64 min, Int64 max) { return value >= min && value <= max; } private static bool FitsInSingle(double value) { return value >= Single.MinValue && value <= Single.MaxValue; } private static bool MatchesType(IEdmTypeReference targetType, IEdmValue operand) { return MatchesType(targetType, operand, true); } private static bool MatchesType(IEdmTypeReference targetType, IEdmValue operand, bool testPropertyTypes) { IEdmTypeReference operandType = operand.Type; EdmValueKind operandKind = operand.ValueKind; if (operandType != null && operandKind != EdmValueKind.Null && operandType.Definition.IsOrInheritsFrom(targetType.Definition)) { return true; } switch (operandKind) { case EdmValueKind.Binary: if (targetType.IsBinary()) { IEdmBinaryTypeReference targetBinary = targetType.AsBinary(); return targetBinary.IsUnbounded || !targetBinary.MaxLength.HasValue || targetBinary.MaxLength.Value >= ((IEdmBinaryValue)operand).Value.Length; } break; case EdmValueKind.Boolean: return targetType.IsBoolean(); case EdmValueKind.DateTime: return targetType.IsDateTime(); case EdmValueKind.DateTimeOffset: return targetType.IsDateTimeOffset(); case EdmValueKind.Decimal: return targetType.IsDecimal(); case EdmValueKind.Guid: return targetType.IsGuid(); case EdmValueKind.Null: return targetType.IsNullable; case EdmValueKind.Time: return targetType.IsTime(); case EdmValueKind.String: if (targetType.IsString()) { IEdmStringTypeReference targetString = targetType.AsString(); return targetString.IsUnbounded || !targetString.MaxLength.HasValue || targetString.MaxLength.Value >= ((IEdmStringValue)operand).Value.Length; } break; case EdmValueKind.Floating: return targetType.IsDouble() || (targetType.IsSingle() && FitsInSingle(((IEdmFloatingValue)operand).Value)); case EdmValueKind.Integer: if (targetType.TypeKind() == EdmTypeKind.Primitive) { switch (targetType.AsPrimitive().PrimitiveKind()) { case EdmPrimitiveTypeKind.Int16: return InRange(((IEdmIntegerValue)operand).Value, Int16.MinValue, Int16.MaxValue); case EdmPrimitiveTypeKind.Int32: return InRange(((IEdmIntegerValue)operand).Value, Int32.MinValue, Int32.MaxValue); case EdmPrimitiveTypeKind.SByte: return InRange(((IEdmIntegerValue)operand).Value, SByte.MinValue, SByte.MaxValue); case EdmPrimitiveTypeKind.Byte: return InRange(((IEdmIntegerValue)operand).Value, Byte.MinValue, Byte.MaxValue); case EdmPrimitiveTypeKind.Int64: case EdmPrimitiveTypeKind.Single: case EdmPrimitiveTypeKind.Double: return true; } } break; case EdmValueKind.Collection: if (targetType.IsCollection()) { IEdmTypeReference targetElementType = targetType.AsCollection().ElementType(); // This enumerates the entire collection, which is unfortunate. foreach (IEdmDelayedValue elementValue in ((IEdmCollectionValue)operand).Elements) { if (!MatchesType(targetElementType, elementValue.Value)) { return false; } } return true; } break; case EdmValueKind.Enum: return ((IEdmEnumValue)operand).Type.Definition.IsEquivalentTo(targetType.Definition); case EdmValueKind.Structured: if (targetType.IsStructured()) { return AssertOrMatchStructuredType(targetType.AsStructured(), (IEdmStructuredValue)operand, testPropertyTypes, null); } break; } return false; } private static IEdmValue AssertType(IEdmTypeReference targetType, IEdmValue operand) { IEdmTypeReference operandType = operand.Type; EdmValueKind operandKind = operand.ValueKind; if ((operandType != null && operandKind != EdmValueKind.Null && operandType.Definition.IsOrInheritsFrom(targetType.Definition)) || targetType.TypeKind() == EdmTypeKind.None) { return operand; } bool matches = true; switch (operandKind) { case EdmValueKind.Collection: if (targetType.IsCollection()) { // Avoid enumerating the collection at this point. return new AssertTypeCollectionValue(targetType.AsCollection(), (IEdmCollectionValue)operand); } else { matches = false; } break; case EdmValueKind.Structured: if (targetType.IsStructured()) { IEdmStructuredTypeReference structuredTargetType = targetType.AsStructured(); List<IEdmPropertyValue> newProperties = new List<IEdmPropertyValue>(); matches = AssertOrMatchStructuredType(structuredTargetType, (IEdmStructuredValue)operand, true, newProperties); if (matches) { return new EdmStructuredValue(structuredTargetType, newProperties); } } else { matches = false; } break; default: matches = MatchesType(targetType, operand); break; } if (!matches) { throw new InvalidOperationException(Edm.Strings.Edm_Evaluator_FailedTypeAssertion(targetType.ToTraceString())); } return operand; } private static bool AssertOrMatchStructuredType(IEdmStructuredTypeReference structuredTargetType, IEdmStructuredValue structuredValue, bool testPropertyTypes, List<IEdmPropertyValue> newProperties) { // If the value has a nominal type, the target type must be derived from the nominal type for a type match to be possible. IEdmTypeReference operandType = structuredValue.Type; if (operandType != null && operandType.TypeKind() != EdmTypeKind.Row && !structuredTargetType.StructuredDefinition().InheritsFrom(operandType.AsStructured().StructuredDefinition())) { return false; } Internal.HashSetInternal<IEdmPropertyValue> visitedProperties = new Internal.HashSetInternal<IEdmPropertyValue>(); foreach (IEdmProperty property in structuredTargetType.StructuralProperties()) { IEdmPropertyValue propertyValue = structuredValue.FindPropertyValue(property.Name); if (propertyValue == null) { return false; } visitedProperties.Add(propertyValue); if (testPropertyTypes) { if (newProperties != null) { newProperties.Add(new EdmPropertyValue(propertyValue.Name, AssertType(property.Type, propertyValue.Value))); } else if (!MatchesType(property.Type, propertyValue.Value)) { return false; } } } if (structuredTargetType.IsEntity()) { foreach (IEdmNavigationProperty property in structuredTargetType.AsEntity().NavigationProperties()) { IEdmPropertyValue propertyValue = structuredValue.FindPropertyValue(property.Name); if (propertyValue == null) { return false; } // Make a superficial test of the navigation property value--check that it has a valid set of properties, // but don't test their types. if (testPropertyTypes && !MatchesType(property.Type, propertyValue.Value, false)) { return false; } visitedProperties.Add(propertyValue); if (newProperties != null) { newProperties.Add(propertyValue); } } } //// Allow property values not mentioned in the target type, whether or not the target type is open. if (newProperties != null) { foreach (IEdmPropertyValue propertyValue in structuredValue.PropertyValues) { if (!visitedProperties.Contains(propertyValue)) { newProperties.Add(propertyValue); } } } return true; } private IEdmValue Eval(IEdmExpression expression, IEdmStructuredValue context) { switch (expression.ExpressionKind) { case EdmExpressionKind.IntegerConstant: return (IEdmIntegerConstantExpression)expression; case EdmExpressionKind.StringConstant: return (IEdmStringConstantExpression)expression; case EdmExpressionKind.BinaryConstant: return (IEdmBinaryConstantExpression)expression; case EdmExpressionKind.BooleanConstant: return (IEdmBooleanConstantExpression)expression; case EdmExpressionKind.DateTimeConstant: return (IEdmDateTimeConstantExpression)expression; case EdmExpressionKind.DateTimeOffsetConstant: return (IEdmDateTimeOffsetConstantExpression)expression; case EdmExpressionKind.DecimalConstant: return (IEdmDecimalConstantExpression)expression; case EdmExpressionKind.FloatingConstant: return (IEdmFloatingConstantExpression)expression; case EdmExpressionKind.GuidConstant: return (IEdmGuidConstantExpression)expression; case EdmExpressionKind.TimeConstant: return (IEdmTimeConstantExpression)expression; case EdmExpressionKind.Null: return (IEdmNullExpression)expression; case EdmExpressionKind.Path: { EdmUtil.CheckArgumentNull(context, "context"); IEdmPathExpression pathExpression = (IEdmPathExpression)expression; IEdmValue result = context; foreach (string hop in pathExpression.Path) { result = this.FindProperty(hop, result); if (result == null) { throw new InvalidOperationException(Edm.Strings.Edm_Evaluator_UnboundPath(hop)); } } return result; } case EdmExpressionKind.FunctionApplication: { IEdmApplyExpression apply = (IEdmApplyExpression)expression; IEdmExpression targetReference = apply.AppliedFunction; IEdmFunctionReferenceExpression targetFunctionReference = targetReference as IEdmFunctionReferenceExpression; if (targetFunctionReference != null) { IList<IEdmExpression> argumentExpressions = apply.Arguments.ToList(); IEdmValue[] arguments = new IEdmValue[argumentExpressions.Count()]; { int argumentIndex = 0; foreach (IEdmExpression argument in argumentExpressions) { arguments[argumentIndex++] = this.Eval(argument, context); } } IEdmFunction target = targetFunctionReference.ReferencedFunction; if (!target.IsBad()) { //// Static validation will have checked that the number and types of arguments are correct, //// so those checks are not performed dynamically. Func<IEdmValue[], IEdmValue> functionEvaluator; if (this.builtInFunctions.TryGetValue(target, out functionEvaluator)) { return functionEvaluator(arguments); } } if (this.lastChanceFunctionApplier != null) { return this.lastChanceFunctionApplier(target.FullName(), arguments); } } throw new InvalidOperationException(Edm.Strings.Edm_Evaluator_UnboundFunction(targetFunctionReference != null ? targetFunctionReference.ReferencedFunction.ToTraceString() : string.Empty)); } case EdmExpressionKind.If: { IEdmIfExpression ifExpression = (IEdmIfExpression)expression; if (((IEdmBooleanValue)this.Eval(ifExpression.TestExpression, context)).Value) { return this.Eval(ifExpression.TrueExpression, context); } return this.Eval(ifExpression.FalseExpression, context); } case EdmExpressionKind.IsType: { IEdmIsTypeExpression isType = (IEdmIsTypeExpression)expression; IEdmValue operand = this.Eval(isType.Operand, context); IEdmTypeReference targetType = isType.Type; return new EdmBooleanConstant(MatchesType(targetType, operand)); } case EdmExpressionKind.AssertType: { IEdmAssertTypeExpression assertType = (IEdmAssertTypeExpression)expression; IEdmValue operand = this.Eval(assertType.Operand, context); IEdmTypeReference targetType = assertType.Type; return AssertType(targetType, operand); } case EdmExpressionKind.Record: { IEdmRecordExpression record = (IEdmRecordExpression)expression; DelayedExpressionContext recordContext = new DelayedExpressionContext(this, context); List<IEdmPropertyValue> propertyValues = new List<IEdmPropertyValue>(); //// Static validation will have checked that the set of supplied properties are appropriate //// for the supplied type and have no duplicates, so those checks are not performed dynamically. foreach (IEdmPropertyConstructor propertyConstructor in record.Properties) { propertyValues.Add(new DelayedRecordProperty(recordContext, propertyConstructor)); } EdmStructuredValue result = new EdmStructuredValue(record.DeclaredType != null ? record.DeclaredType.AsStructured() : null, propertyValues); return result; } case EdmExpressionKind.Collection: { IEdmCollectionExpression collection = (IEdmCollectionExpression)expression; DelayedExpressionContext collectionContext = new DelayedExpressionContext(this, context); List<IEdmDelayedValue> elementValues = new List<IEdmDelayedValue>(); //// Static validation will have checked that the result types of the element expressions are //// appropriate and so these checks are not performed dynamically. foreach (IEdmExpression element in collection.Elements) { elementValues.Add(this.MapLabeledExpressionToDelayedValue(element, collectionContext, context)); } EdmCollectionValue result = new EdmCollectionValue(collection.DeclaredType != null ? collection.DeclaredType.AsCollection() : null, elementValues); return result; } case EdmExpressionKind.LabeledExpressionReference: { return this.MapLabeledExpressionToDelayedValue(((IEdmLabeledExpressionReferenceExpression)expression).ReferencedLabeledExpression, null, context).Value; } case EdmExpressionKind.Labeled: return this.MapLabeledExpressionToDelayedValue(expression, new DelayedExpressionContext(this, context), context).Value; case EdmExpressionKind.ParameterReference: case EdmExpressionKind.FunctionReference: case EdmExpressionKind.PropertyReference: case EdmExpressionKind.ValueTermReference: case EdmExpressionKind.EntitySetReference: case EdmExpressionKind.EnumMemberReference: throw new InvalidOperationException("Not yet implemented: evaluation of " + expression.ExpressionKind.ToString() + " expressions."); default: throw new InvalidOperationException(Edm.Strings.Edm_Evaluator_UnrecognizedExpressionKind(((int)expression.ExpressionKind).ToString(System.Globalization.CultureInfo.InvariantCulture))); } } private IEdmDelayedValue MapLabeledExpressionToDelayedValue(IEdmExpression expression, DelayedExpressionContext delayedContext, IEdmStructuredValue context) { //// Labeled expressions map to delayed values either at the point of definition or at a point of reference //// (evaluation of a LabeledExpressionReference that refers to the expression). All of these must map to //// a single delayed value (so that the value itself is evaluated only once). IEdmLabeledExpression labeledExpression = expression as IEdmLabeledExpression; if (labeledExpression == null) { //// If an expression has no label, there can be no references to it and so only the point of definition needs a mapping to a delayed value, //// and so there is no need to cache the delayed value. The point of definition always supplies a context. System.Diagnostics.Debug.Assert(delayedContext != null, "Labeled element definition failed to supply an evaluation context."); return new DelayedCollectionElement(delayedContext, expression); } DelayedValue expressionValue; if (this.labeledValues.TryGetValue(labeledExpression, out expressionValue)) { return expressionValue; } expressionValue = new DelayedCollectionElement(delayedContext ?? new DelayedExpressionContext(this, context), labeledExpression.Expression); this.labeledValues[labeledExpression] = expressionValue; return expressionValue; } private IEdmValue FindProperty(string name, IEdmValue context) { IEdmValue result = null; IEdmStructuredValue structuredContext = context as IEdmStructuredValue; if (structuredContext != null) { IEdmPropertyValue propertyValue = structuredContext.FindPropertyValue(name); if (propertyValue != null) { result = propertyValue.Value; } } return result; } private class DelayedExpressionContext { private readonly EdmExpressionEvaluator expressionEvaluator; private readonly IEdmStructuredValue context; public DelayedExpressionContext(EdmExpressionEvaluator expressionEvaluator, IEdmStructuredValue context) { this.expressionEvaluator = expressionEvaluator; this.context = context; } public IEdmValue Eval(IEdmExpression expression) { return this.expressionEvaluator.Eval(expression, this.context); } } private abstract class DelayedValue : IEdmDelayedValue { private readonly DelayedExpressionContext context; private IEdmValue value; public DelayedValue(DelayedExpressionContext context) { this.context = context; } public abstract IEdmExpression Expression { get; } public IEdmValue Value { get { if (this.value == null) { this.value = this.context.Eval(this.Expression); } return this.value; } } } private class DelayedRecordProperty : DelayedValue, IEdmPropertyValue { private readonly IEdmPropertyConstructor constructor; public DelayedRecordProperty(DelayedExpressionContext context, IEdmPropertyConstructor constructor) : base(context) { this.constructor = constructor; } public string Name { get { return this.constructor.Name; } } public override IEdmExpression Expression { get { return this.constructor.Value; } } } private class DelayedCollectionElement : DelayedValue { private readonly IEdmExpression expression; public DelayedCollectionElement(DelayedExpressionContext context, IEdmExpression expression) : base(context) { this.expression = expression; } public override IEdmExpression Expression { get { return this.expression; } } } private class AssertTypeCollectionValue : Library.EdmElement, IEdmCollectionValue, IEnumerable<IEdmDelayedValue> { private readonly IEdmCollectionTypeReference targetCollectionType; private readonly IEdmCollectionValue collectionValue; public AssertTypeCollectionValue(IEdmCollectionTypeReference targetCollectionType, IEdmCollectionValue collectionValue) { this.targetCollectionType = targetCollectionType; this.collectionValue = collectionValue; } IEnumerable<IEdmDelayedValue> IEdmCollectionValue.Elements { get { return this; } } IEdmTypeReference IEdmValue.Type { get { return this.targetCollectionType; } } EdmValueKind IEdmValue.ValueKind { get { return EdmValueKind.Collection; } } IEnumerator<IEdmDelayedValue> IEnumerable<IEdmDelayedValue>.GetEnumerator() { return new AssertTypeCollectionValueEnumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new AssertTypeCollectionValueEnumerator(this); } private class AssertTypeCollectionValueEnumerator : IEnumerator<IEdmDelayedValue> { private readonly AssertTypeCollectionValue value; private readonly IEnumerator<IEdmDelayedValue> enumerator; public AssertTypeCollectionValueEnumerator(AssertTypeCollectionValue value) { this.value = value; this.enumerator = value.collectionValue.Elements.GetEnumerator(); } public IEdmDelayedValue Current { get { return new DelayedAssertType(this.value.targetCollectionType.ElementType(), this.enumerator.Current); } } object System.Collections.IEnumerator.Current { get { return this.Current; } } bool System.Collections.IEnumerator.MoveNext() { return this.enumerator.MoveNext(); } void System.Collections.IEnumerator.Reset() { this.enumerator.Reset(); } void IDisposable.Dispose() { this.enumerator.Dispose(); } private class DelayedAssertType : IEdmDelayedValue { private readonly IEdmDelayedValue delayedValue; private readonly IEdmTypeReference targetType; private IEdmValue value; public DelayedAssertType(IEdmTypeReference targetType, IEdmDelayedValue value) { this.delayedValue = value; this.targetType = targetType; } public IEdmValue Value { get { if (this.value == null) { this.value = EdmExpressionEvaluator.AssertType(this.targetType, this.delayedValue.Value); } return this.value; } } } } } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.Params.cs // // 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. #pragma warning disable 1717 namespace Org.Apache.Http.Client.Params { /// <summary> /// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/ClientPNames /// </java-name> [Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IClientPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the class name of the default org.apache.http.conn.ClientConnectionManager </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// CONNECTION_MANAGER_FACTORY_CLASS_NAME /// </java-name> [Dot42.DexImport("CONNECTION_MANAGER_FACTORY_CLASS_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string CONNECTION_MANAGER_FACTORY_CLASS_NAME = "http.connection-manager.factory-class-name"; /// <summary> /// <para>Defines the factory to create a default org.apache.http.conn.ClientConnectionManager. </para><para>This parameters expects a value of type org.apache.http.conn.ClientConnectionManagerFactory. </para> /// </summary> /// <java-name> /// CONNECTION_MANAGER_FACTORY /// </java-name> [Dot42.DexImport("CONNECTION_MANAGER_FACTORY", "Ljava/lang/String;", AccessFlags = 25)] public const string CONNECTION_MANAGER_FACTORY = "http.connection-manager.factory-object"; /// <summary> /// <para>Defines whether redirects should be handled automatically </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// HANDLE_REDIRECTS /// </java-name> [Dot42.DexImport("HANDLE_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)] public const string HANDLE_REDIRECTS = "http.protocol.handle-redirects"; /// <summary> /// <para>Defines whether relative redirects should be rejected. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// REJECT_RELATIVE_REDIRECT /// </java-name> [Dot42.DexImport("REJECT_RELATIVE_REDIRECT", "Ljava/lang/String;", AccessFlags = 25)] public const string REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect"; /// <summary> /// <para>Defines the maximum number of redirects to be followed. The limit on number of redirects is intended to prevent infinite loops. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_REDIRECTS /// </java-name> [Dot42.DexImport("MAX_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_REDIRECTS = "http.protocol.max-redirects"; /// <summary> /// <para>Defines whether circular redirects (redirects to the same location) should be allowed. The HTTP spec is not sufficiently clear whether circular redirects are permitted, therefore optionally they can be enabled </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// ALLOW_CIRCULAR_REDIRECTS /// </java-name> [Dot42.DexImport("ALLOW_CIRCULAR_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)] public const string ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects"; /// <summary> /// <para>Defines whether authentication should be handled automatically. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// HANDLE_AUTHENTICATION /// </java-name> [Dot42.DexImport("HANDLE_AUTHENTICATION", "Ljava/lang/String;", AccessFlags = 25)] public const string HANDLE_AUTHENTICATION = "http.protocol.handle-authentication"; /// <summary> /// <para>Defines the name of the cookie specification to be used for HTTP state management. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// COOKIE_POLICY /// </java-name> [Dot42.DexImport("COOKIE_POLICY", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_POLICY = "http.protocol.cookie-policy"; /// <summary> /// <para>Defines the virtual host name. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para> /// </summary> /// <java-name> /// VIRTUAL_HOST /// </java-name> [Dot42.DexImport("VIRTUAL_HOST", "Ljava/lang/String;", AccessFlags = 25)] public const string VIRTUAL_HOST = "http.virtual-host"; /// <summary> /// <para>Defines the request headers to be sent per default with each request. </para><para>This parameter expects a value of type java.util.Collection. The collection is expected to contain org.apache.http.Headers. </para> /// </summary> /// <java-name> /// DEFAULT_HEADERS /// </java-name> [Dot42.DexImport("DEFAULT_HEADERS", "Ljava/lang/String;", AccessFlags = 25)] public const string DEFAULT_HEADERS = "http.default-headers"; /// <summary> /// <para>Defines the default host. The default value will be used if the target host is not explicitly specified in the request URI. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para> /// </summary> /// <java-name> /// DEFAULT_HOST /// </java-name> [Dot42.DexImport("DEFAULT_HOST", "Ljava/lang/String;", AccessFlags = 25)] public const string DEFAULT_HOST = "http.default-host"; } /// <summary> /// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/ClientPNames /// </java-name> [Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537)] public partial interface IClientPNames /* scope: __dot42__ */ { } /// <summary> /// <para>An adaptor for accessing HTTP client parameters in HttpParams.</para><para><para></para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/HttpClientParams /// </java-name> [Dot42.DexImport("org/apache/http/client/params/HttpClientParams", AccessFlags = 33)] public partial class HttpClientParams /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal HttpClientParams() /* MethodBuilder.Create */ { } /// <java-name> /// isRedirecting /// </java-name> [Dot42.DexImport("isRedirecting", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool IsRedirecting(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setRedirecting /// </java-name> [Dot42.DexImport("setRedirecting", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetRedirecting(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } /// <java-name> /// isAuthenticating /// </java-name> [Dot42.DexImport("isAuthenticating", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool IsAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setAuthenticating /// </java-name> [Dot42.DexImport("setAuthenticating", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } /// <java-name> /// getCookiePolicy /// </java-name> [Dot42.DexImport("getCookiePolicy", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// setCookiePolicy /// </java-name> [Dot42.DexImport("setCookiePolicy", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params, string cookiePolicy) /* MethodBuilder.Create */ { } } /// <java-name> /// org/apache/http/client/params/AuthPolicy /// </java-name> [Dot42.DexImport("org/apache/http/client/params/AuthPolicy", AccessFlags = 49)] public sealed partial class AuthPolicy /* scope: __dot42__ */ { /// <summary> /// <para>The NTLM scheme is a proprietary Microsoft Windows Authentication protocol (considered to be the most secure among currently supported authentication schemes). </para> /// </summary> /// <java-name> /// NTLM /// </java-name> [Dot42.DexImport("NTLM", "Ljava/lang/String;", AccessFlags = 25)] public const string NTLM = "NTLM"; /// <summary> /// <para>Digest authentication scheme as defined in RFC2617. </para> /// </summary> /// <java-name> /// DIGEST /// </java-name> [Dot42.DexImport("DIGEST", "Ljava/lang/String;", AccessFlags = 25)] public const string DIGEST = "Digest"; /// <summary> /// <para>Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported) </para> /// </summary> /// <java-name> /// BASIC /// </java-name> [Dot42.DexImport("BASIC", "Ljava/lang/String;", AccessFlags = 25)] public const string BASIC = "Basic"; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal AuthPolicy() /* MethodBuilder.Create */ { } } /// <java-name> /// org/apache/http/client/params/ClientParamBean /// </java-name> [Dot42.DexImport("org/apache/http/client/params/ClientParamBean", AccessFlags = 33)] public partial class ClientParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ClientParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionManagerFactoryClassName /// </java-name> [Dot42.DexImport("setConnectionManagerFactoryClassName", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetConnectionManagerFactoryClassName(string factory) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionManagerFactory /// </java-name> [Dot42.DexImport("setConnectionManagerFactory", "(Lorg/apache/http/conn/ClientConnectionManagerFactory;)V", AccessFlags = 1)] public virtual void SetConnectionManagerFactory(global::Org.Apache.Http.Conn.IClientConnectionManagerFactory factory) /* MethodBuilder.Create */ { } /// <java-name> /// setHandleRedirects /// </java-name> [Dot42.DexImport("setHandleRedirects", "(Z)V", AccessFlags = 1)] public virtual void SetHandleRedirects(bool handle) /* MethodBuilder.Create */ { } /// <java-name> /// setRejectRelativeRedirect /// </java-name> [Dot42.DexImport("setRejectRelativeRedirect", "(Z)V", AccessFlags = 1)] public virtual void SetRejectRelativeRedirect(bool reject) /* MethodBuilder.Create */ { } /// <java-name> /// setMaxRedirects /// </java-name> [Dot42.DexImport("setMaxRedirects", "(I)V", AccessFlags = 1)] public virtual void SetMaxRedirects(int maxRedirects) /* MethodBuilder.Create */ { } /// <java-name> /// setAllowCircularRedirects /// </java-name> [Dot42.DexImport("setAllowCircularRedirects", "(Z)V", AccessFlags = 1)] public virtual void SetAllowCircularRedirects(bool allow) /* MethodBuilder.Create */ { } /// <java-name> /// setHandleAuthentication /// </java-name> [Dot42.DexImport("setHandleAuthentication", "(Z)V", AccessFlags = 1)] public virtual void SetHandleAuthentication(bool handle) /* MethodBuilder.Create */ { } /// <java-name> /// setCookiePolicy /// </java-name> [Dot42.DexImport("setCookiePolicy", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetCookiePolicy(string policy) /* MethodBuilder.Create */ { } /// <java-name> /// setVirtualHost /// </java-name> [Dot42.DexImport("setVirtualHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)] public virtual void SetVirtualHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */ { } /// <java-name> /// setDefaultHeaders /// </java-name> [Dot42.DexImport("setDefaultHeaders", "(Ljava/util/Collection;)V", AccessFlags = 1, Signature = "(Ljava/util/Collection<Lorg/apache/http/Header;>;)V")] public virtual void SetDefaultHeaders(global::Java.Util.ICollection<global::Org.Apache.Http.IHeader> headers) /* MethodBuilder.Create */ { } /// <java-name> /// setDefaultHost /// </java-name> [Dot42.DexImport("setDefaultHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)] public virtual void SetDefaultHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ClientParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Collected parameter names for the HttpClient module. This interface combines the parameter definitions of the HttpClient module and all dependency modules or informational units. It does not define additional parameter names, but references other interfaces defining parameter names. <br></br> This interface is meant as a navigation aid for developers. When referring to parameter names, you should use the interfaces in which the respective constants are actually defined.</para><para><para></para><title>Revision:</title><para>576078 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/AllClientPNames /// </java-name> [Dot42.DexImport("org/apache/http/client/params/AllClientPNames", AccessFlags = 1537)] public partial interface IAllClientPNames : global::Org.Apache.Http.Params.ICoreConnectionPNames, global::Org.Apache.Http.Params.ICoreProtocolPNames, global::Org.Apache.Http.Client.Params.IClientPNames, global::Org.Apache.Http.Auth.Params.IAuthPNames, global::Org.Apache.Http.Cookie.Params.ICookieSpecPNames, global::Org.Apache.Http.Conn.Params.IConnConnectionPNames, global::Org.Apache.Http.Conn.Params.IConnManagerPNames, global::Org.Apache.Http.Conn.Params.IConnRoutePNames /* scope: __dot42__ */ { } /// <java-name> /// org/apache/http/client/params/CookiePolicy /// </java-name> [Dot42.DexImport("org/apache/http/client/params/CookiePolicy", AccessFlags = 49)] public sealed partial class CookiePolicy /* scope: __dot42__ */ { /// <summary> /// <para>The policy that provides high degree of compatibilty with common cookie management of popular HTTP agents. </para> /// </summary> /// <java-name> /// BROWSER_COMPATIBILITY /// </java-name> [Dot42.DexImport("BROWSER_COMPATIBILITY", "Ljava/lang/String;", AccessFlags = 25)] public const string BROWSER_COMPATIBILITY = "compatibility"; /// <summary> /// <para>The Netscape cookie draft compliant policy. </para> /// </summary> /// <java-name> /// NETSCAPE /// </java-name> [Dot42.DexImport("NETSCAPE", "Ljava/lang/String;", AccessFlags = 25)] public const string NETSCAPE = "netscape"; /// <summary> /// <para>The RFC 2109 compliant policy. </para> /// </summary> /// <java-name> /// RFC_2109 /// </java-name> [Dot42.DexImport("RFC_2109", "Ljava/lang/String;", AccessFlags = 25)] public const string RFC_2109 = "rfc2109"; /// <summary> /// <para>The RFC 2965 compliant policy. </para> /// </summary> /// <java-name> /// RFC_2965 /// </java-name> [Dot42.DexImport("RFC_2965", "Ljava/lang/String;", AccessFlags = 25)] public const string RFC_2965 = "rfc2965"; /// <summary> /// <para>The default 'best match' policy. </para> /// </summary> /// <java-name> /// BEST_MATCH /// </java-name> [Dot42.DexImport("BEST_MATCH", "Ljava/lang/String;", AccessFlags = 25)] public const string BEST_MATCH = "best-match"; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal CookiePolicy() /* MethodBuilder.Create */ { } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Abp; using Abp.Configuration.Startup; using Abp.Domain.Uow; using Abp.Runtime.Session; using Abp.TestBase; using Kinare.FormSystem.Authorization.Users; using Kinare.FormSystem.EntityFramework; using Kinare.FormSystem.Migrations.SeedData; using Kinare.FormSystem.MultiTenancy; using Kinare.FormSystem.Users; using Castle.MicroKernel.Registration; using Effort; using EntityFramework.DynamicFilters; namespace Kinare.FormSystem.Tests { public abstract class FormSystemTestBase : AbpIntegratedTestBase<FormSystemTestModule> { private DbConnection _hostDb; private Dictionary<int, DbConnection> _tenantDbs; //only used for db per tenant architecture protected FormSystemTestBase() { //Seed initial data for host AbpSession.TenantId = null; UsingDbContext(context => { new InitialHostDbBuilder(context).Create(); new DefaultTenantCreator(context).Create(); }); //Seed initial data for default tenant AbpSession.TenantId = 1; UsingDbContext(context => { new TenantRoleAndUserBuilder(context, 1).Create(); }); LoginAsDefaultTenantAdmin(); } protected override void PreInitialize() { base.PreInitialize(); /* You can switch database architecture here: */ UseSingleDatabase(); //UseDatabasePerTenant(); } /* Uses single database for host and all tenants. */ private void UseSingleDatabase() { _hostDb = DbConnectionFactory.CreateTransient(); LocalIocManager.IocContainer.Register( Component.For<DbConnection>() .UsingFactoryMethod(() => _hostDb) .LifestyleSingleton() ); } /* Uses single database for host and Default tenant, * but dedicated databases for all other tenants. */ private void UseDatabasePerTenant() { _hostDb = DbConnectionFactory.CreateTransient(); _tenantDbs = new Dictionary<int, DbConnection>(); LocalIocManager.IocContainer.Register( Component.For<DbConnection>() .UsingFactoryMethod((kernel) => { lock (_tenantDbs) { var currentUow = kernel.Resolve<ICurrentUnitOfWorkProvider>().Current; var abpSession = kernel.Resolve<IAbpSession>(); var tenantId = currentUow != null ? currentUow.GetTenantId() : abpSession.TenantId; if (tenantId == null || tenantId == 1) //host and default tenant are stored in host db { return _hostDb; } if (!_tenantDbs.ContainsKey(tenantId.Value)) { _tenantDbs[tenantId.Value] = DbConnectionFactory.CreateTransient(); } return _tenantDbs[tenantId.Value]; } }, true) .LifestyleTransient() ); } #region UsingDbContext protected IDisposable UsingTenantId(int? tenantId) { var previousTenantId = AbpSession.TenantId; AbpSession.TenantId = tenantId; return new DisposeAction(() => AbpSession.TenantId = previousTenantId); } protected void UsingDbContext(Action<FormSystemDbContext> action) { UsingDbContext(AbpSession.TenantId, action); } protected Task UsingDbContextAsync(Func<FormSystemDbContext, Task> action) { return UsingDbContextAsync(AbpSession.TenantId, action); } protected T UsingDbContext<T>(Func<FormSystemDbContext, T> func) { return UsingDbContext(AbpSession.TenantId, func); } protected Task<T> UsingDbContextAsync<T>(Func<FormSystemDbContext, Task<T>> func) { return UsingDbContextAsync(AbpSession.TenantId, func); } protected void UsingDbContext(int? tenantId, Action<FormSystemDbContext> action) { using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<FormSystemDbContext>()) { context.DisableAllFilters(); action(context); context.SaveChanges(); } } } protected async Task UsingDbContextAsync(int? tenantId, Func<FormSystemDbContext, Task> action) { using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<FormSystemDbContext>()) { context.DisableAllFilters(); await action(context); await context.SaveChangesAsync(); } } } protected T UsingDbContext<T>(int? tenantId, Func<FormSystemDbContext, T> func) { T result; using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<FormSystemDbContext>()) { context.DisableAllFilters(); result = func(context); context.SaveChanges(); } } return result; } protected async Task<T> UsingDbContextAsync<T>(int? tenantId, Func<FormSystemDbContext, Task<T>> func) { T result; using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<FormSystemDbContext>()) { context.DisableAllFilters(); result = await func(context); await context.SaveChangesAsync(); } } return result; } #endregion #region Login protected void LoginAsHostAdmin() { LoginAsHost(User.AdminUserName); } protected void LoginAsDefaultTenantAdmin() { LoginAsTenant(Tenant.DefaultTenantName, User.AdminUserName); } protected void LogoutAsDefaultTenant() { LogoutAsTenant(Tenant.DefaultTenantName); } protected void LoginAsHost(string userName) { AbpSession.TenantId = null; var user = UsingDbContext( context => context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName)); if (user == null) { throw new Exception("There is no user: " + userName + " for host."); } AbpSession.UserId = user.Id; } protected void LogoutAsHost() { Resolve<IMultiTenancyConfig>().IsEnabled = true; AbpSession.TenantId = null; AbpSession.UserId = null; } protected void LoginAsTenant(string tenancyName, string userName) { var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName)); if (tenant == null) { throw new Exception("There is no tenant: " + tenancyName); } AbpSession.TenantId = tenant.Id; var user = UsingDbContext( context => context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName)); if (user == null) { throw new Exception("There is no user: " + userName + " for tenant: " + tenancyName); } AbpSession.UserId = user.Id; } protected void LogoutAsTenant(string tenancyName) { var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName)); if (tenant == null) { throw new Exception("There is no tenant: " + tenancyName); } AbpSession.TenantId = tenant.Id; AbpSession.UserId = null; } #endregion /// <summary> /// Gets current user if <see cref="IAbpSession.UserId"/> is not null. /// Throws exception if it's null. /// </summary> protected async Task<User> GetCurrentUserAsync() { var userId = AbpSession.GetUserId(); return await UsingDbContext(context => context.Users.SingleAsync(u => u.Id == userId)); } /// <summary> /// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null. /// Throws exception if there is no current tenant. /// </summary> protected async Task<Tenant> GetCurrentTenantAsync() { var tenantId = AbpSession.GetTenantId(); return await UsingDbContext(context => context.Tenants.SingleAsync(t => t.Id == tenantId)); } } }
// 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.Runtime.InteropServices; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Data.SqlTypes { /// <summary> /// Represents a floating-point number within the range of -1.79E /// +308 through 1.79E +308 to be stored in or retrieved from a database. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] [XmlSchemaProvider("GetXsdType")] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct SqlDouble : INullable, IComparable, IXmlSerializable { private bool m_fNotNull; // false if null. Do not rename (binary serialization) private double m_value; // Do not rename (binary serialization) // constructor // construct a Null private SqlDouble(bool fNull) { m_fNotNull = false; m_value = 0.0; } public SqlDouble(double value) { if (!double.IsFinite(value)) { throw new OverflowException(SQLResource.ArithOverflowMessage); } else { m_value = value; m_fNotNull = true; } } // INullable public bool IsNull { get { return !m_fNotNull; } } // property: Value public double Value { get { if (m_fNotNull) return m_value; else throw new SqlNullValueException(); } } // Implicit conversion from double to SqlDouble public static implicit operator SqlDouble(double x) { return new SqlDouble(x); } // Explicit conversion from SqlDouble to double. Throw exception if x is Null. public static explicit operator double(SqlDouble x) { return x.Value; } public override string ToString() { return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null); } public static SqlDouble Parse(string s) { if (s == SQLResource.NullString) return SqlDouble.Null; else return new SqlDouble(double.Parse(s, CultureInfo.InvariantCulture)); } // Unary operators public static SqlDouble operator -(SqlDouble x) { return x.IsNull ? Null : new SqlDouble(-x.m_value); } // Binary operators // Arithmetic operators public static SqlDouble operator +(SqlDouble x, SqlDouble y) { if (x.IsNull || y.IsNull) return Null; double value = x.m_value + y.m_value; if (double.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlDouble(value); } public static SqlDouble operator -(SqlDouble x, SqlDouble y) { if (x.IsNull || y.IsNull) return Null; double value = x.m_value - y.m_value; if (double.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlDouble(value); } public static SqlDouble operator *(SqlDouble x, SqlDouble y) { if (x.IsNull || y.IsNull) return Null; double value = x.m_value * y.m_value; if (double.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlDouble(value); } public static SqlDouble operator /(SqlDouble x, SqlDouble y) { if (x.IsNull || y.IsNull) return Null; if (y.m_value == 0.0) throw new DivideByZeroException(SQLResource.DivideByZeroMessage); double value = x.m_value / y.m_value; if (double.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlDouble(value); } // Implicit conversions // Implicit conversion from SqlBoolean to SqlDouble public static explicit operator SqlDouble(SqlBoolean x) { return x.IsNull ? Null : new SqlDouble(x.ByteValue); } // Implicit conversion from SqlByte to SqlDouble public static implicit operator SqlDouble(SqlByte x) { return x.IsNull ? Null : new SqlDouble(x.Value); } // Implicit conversion from SqlInt16 to SqlDouble public static implicit operator SqlDouble(SqlInt16 x) { return x.IsNull ? Null : new SqlDouble(x.Value); } // Implicit conversion from SqlInt32 to SqlDouble public static implicit operator SqlDouble(SqlInt32 x) { return x.IsNull ? Null : new SqlDouble(x.Value); } // Implicit conversion from SqlInt64 to SqlDouble public static implicit operator SqlDouble(SqlInt64 x) { return x.IsNull ? Null : new SqlDouble(x.Value); } // Implicit conversion from SqlSingle to SqlDouble public static implicit operator SqlDouble(SqlSingle x) { return x.IsNull ? Null : new SqlDouble(x.Value); } // Implicit conversion from SqlMoney to SqlDouble public static implicit operator SqlDouble(SqlMoney x) { return x.IsNull ? Null : new SqlDouble(x.ToDouble()); } // Implicit conversion from SqlDecimal to SqlDouble public static implicit operator SqlDouble(SqlDecimal x) { return x.IsNull ? Null : new SqlDouble(x.ToDouble()); } // Explicit conversions // Explicit conversion from SqlString to SqlDouble // Throws FormatException or OverflowException if necessary. public static explicit operator SqlDouble(SqlString x) { if (x.IsNull) return SqlDouble.Null; return Parse(x.Value); } // Overloading comparison operators public static SqlBoolean operator ==(SqlDouble x, SqlDouble y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value == y.m_value); } public static SqlBoolean operator !=(SqlDouble x, SqlDouble y) { return !(x == y); } public static SqlBoolean operator <(SqlDouble x, SqlDouble y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value < y.m_value); } public static SqlBoolean operator >(SqlDouble x, SqlDouble y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value > y.m_value); } public static SqlBoolean operator <=(SqlDouble x, SqlDouble y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value <= y.m_value); } public static SqlBoolean operator >=(SqlDouble x, SqlDouble y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value >= y.m_value); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator + public static SqlDouble Add(SqlDouble x, SqlDouble y) { return x + y; } // Alternative method for operator - public static SqlDouble Subtract(SqlDouble x, SqlDouble y) { return x - y; } // Alternative method for operator * public static SqlDouble Multiply(SqlDouble x, SqlDouble y) { return x * y; } // Alternative method for operator / public static SqlDouble Divide(SqlDouble x, SqlDouble y) { return x / y; } // Alternative method for operator == public static SqlBoolean Equals(SqlDouble x, SqlDouble y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlDouble x, SqlDouble y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlDouble x, SqlDouble y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlDouble x, SqlDouble y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlDouble x, SqlDouble y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlDouble x, SqlDouble y) { return (x >= y); } // Alternative method for conversions. public SqlBoolean ToSqlBoolean() { return (SqlBoolean)this; } public SqlByte ToSqlByte() { return (SqlByte)this; } public SqlInt16 ToSqlInt16() { return (SqlInt16)this; } public SqlInt32 ToSqlInt32() { return (SqlInt32)this; } public SqlInt64 ToSqlInt64() { return (SqlInt64)this; } public SqlMoney ToSqlMoney() { return (SqlMoney)this; } public SqlDecimal ToSqlDecimal() { return (SqlDecimal)this; } public SqlSingle ToSqlSingle() { return (SqlSingle)this; } public SqlString ToSqlString() { return (SqlString)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object value) { if (value is SqlDouble) { SqlDouble i = (SqlDouble)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlDouble)); } public int CompareTo(SqlDouble value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this < value) return -1; if (this > value) return 1; return 0; } // Compares this instance with a specified object public override bool Equals(object value) { if (!(value is SqlDouble)) { return false; } SqlDouble i = (SqlDouble)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // For hashing purpose public override int GetHashCode() { return IsNull ? 0 : Value.GetHashCode(); } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); m_fNotNull = false; } else { m_value = XmlConvert.ToDouble(reader.ReadElementString()); m_fNotNull = true; } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { writer.WriteString(XmlConvert.ToString(m_value)); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("double", XmlSchema.Namespace); } public static readonly SqlDouble Null = new SqlDouble(true); public static readonly SqlDouble Zero = new SqlDouble(0.0); public static readonly SqlDouble MinValue = new SqlDouble(double.MinValue); public static readonly SqlDouble MaxValue = new SqlDouble(double.MaxValue); } // SqlDouble } // namespace System.Data.SqlTypes
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Rewrite; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.PlatformAbstractions; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.IO; using System.Linq; using IdentityServer4; using IdentityServer4.Models; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Swashbuckle.AspNetCore.Swagger; using Nether.Common.DependencyInjection; using Nether.Common.ApplicationPerformanceMonitoring; using Nether.Data.Leaderboard; using Nether.Data.PlayerManagement; using Nether.Data.Identity; using Nether.Data.Analytics; using Nether.Web.Features.Analytics; using Nether.Web.Features.Common; using Nether.Web.Features.Identity; using Nether.Web.Features.Leaderboard; using Nether.Web.Features.PlayerManagement; using Nether.Web.Utilities; namespace Nether.Web { public class Startup { private readonly IHostingEnvironment _hostingEnvironment; private readonly ILogger _logger; public Startup(IHostingEnvironment env, ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<Startup>(); _hostingEnvironment = env; var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddJsonFile($"config/appsettings.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); loggerFactory.AddTrace(LogLevel.Information); loggerFactory.AddAzureWebAppDiagnostics(); // docs: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging#appservice _logger.LogInformation(@" _ _ _ _ | \ | | ___| |_| |__ ___ _ __ | \| |/ _ \ __| '_ \ / _ \ '__| | |\ | __/ |_| | | | __/ | |_| \_|\___|\__|_| |_|\___|_| - Nether.Web - "); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IConfiguration>(Configuration); services.AddApplicationPerformanceMonitoring(Configuration, _logger, _hostingEnvironment); // Initialize switches for nether services var serviceSwitches = new NetherServiceSwitchSettings(); services.AddSingleton(serviceSwitches); // Add framework services. services .AddMvc(options => { options.Conventions.Add(new FeatureConvention()); options.Filters.AddService(typeof(ExceptionLoggingFilterAttribute)); options.InputFormatters.Add(new PlainTextInputFormatter()); }) .ConfigureApplicationPartManager(partManager => { // swap out the default ControllerFeatureProvider for ours which filters based on the nether service switches var defaultProvider = partManager.FeatureProviders.FirstOrDefault(p => p is ControllerFeatureProvider); if (defaultProvider != null) { partManager.FeatureProviders.Remove(defaultProvider); } partManager.FeatureProviders.Add(new NetherServiceControllerFeatureProvider(serviceSwitches)); }) .AddRazorOptions(options => { // {0} - Action Name // {1} - Controller Name // {2} - Area Name // {3} - Feature Name options.AreaViewLocationFormats.Clear(); options.AreaViewLocationFormats.Add("/Areas/{2}/Features/{3}/Views/{1}/{0}.cshtml"); options.AreaViewLocationFormats.Add("/Areas/{2}/Features/{3}/Views/{0}.cshtml"); options.AreaViewLocationFormats.Add("/Areas/{2}/Features/Views/Shared/{0}.cshtml"); options.AreaViewLocationFormats.Add("/Areas/Shared/{0}.cshtml"); // replace normal view location entirely options.ViewLocationFormats.Clear(); options.ViewLocationFormats.Add("/Features/{3}/Views/{1}/{0}.cshtml"); options.ViewLocationFormats.Add("/Features/{3}/Views/Shared/{0}.cshtml"); options.ViewLocationFormats.Add("/Features/{3}/Views/{0}.cshtml"); options.ViewLocationFormats.Add("/Features/Views/Shared/{0}.cshtml"); options.ViewLocationExpanders.Add(new FeatureViewLocationExpander()); }) .AddJsonOptions(options => { options.SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); }); services.AddCors(); services.ConfigureSwaggerGen(options => { string commentsPath = Path.Combine( PlatformServices.Default.Application.ApplicationBasePath, "Nether.Web.xml"); options.IncludeXmlComments(commentsPath); }); services.AddSwaggerGen(options => { options.SwaggerDoc("v0.1", new Info { Version = "v0.1", Title = "Project Nether", License = new License { Name = "MIT", Url = "https://github.com/MicrosoftDX/nether/blob/master/LICENSE" } }); options.CustomSchemaIds(type => type.FullName); options.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = "/identity/connect/authorize", Scopes = new Dictionary<string, string> { { "nether-all", "nether API access" }, } }); options.OperationFilter<SecurityRequirementsOperationFilter>(); }); services.AddSingleton<ExceptionLoggingFilterAttribute>(); services.AddIdentityServices(Configuration, _logger, serviceSwitches, _hostingEnvironment); services.AddLeaderboardServices(Configuration, _logger, serviceSwitches, _hostingEnvironment); services.AddPlayerManagementServices(Configuration, _logger, serviceSwitches, _hostingEnvironment); services.AddAnalyticsServices(Configuration, _logger, serviceSwitches, _hostingEnvironment); services.AddAuthorization(options => { options.AddPolicy( PolicyName.NetherIdentityClientId, policy => policy.RequireClaim( "client_id", "nether_identity" )); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { var logger = loggerFactory.CreateLogger<Startup>(); bool redirectToHttps = bool.Parse(Configuration["Common:RedirectToHttps"] ?? "false"); if (redirectToHttps) { _logger.LogInformation("Enabling RedirectToHttps"); var rewriteOptions = new RewriteOptions() .AddRedirectToHttps(); app.UseRewriter(rewriteOptions); } var serviceSwitchSettings = app.ApplicationServices.GetRequiredService<NetherServiceSwitchSettings>(); app.Initialize<IUserStore>(); app.Initialize<IPlayerManagementStore>(); app.Initialize<ILeaderboardStore>(); app.Initialize<IAnalyticsStore>(); app.Initialize<IApplicationPerformanceMonitor>(); // Set up separate web pipelines for identity, MVC UI, and API // as they each have different auth requirements! if (serviceSwitchSettings.IsServiceEnabled("Identity")) { app.Map("/identity", idapp => { JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); idapp.UseIdentityServer(); idapp.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme, AutomaticAuthenticate = false, AutomaticChallenge = false }); var facebookEnabled = bool.Parse(Configuration["Identity:SignInMethods:Facebook:EnableImplicit"] ?? "false"); if (facebookEnabled) { var appId = Configuration["Identity:SignInMethods:Facebook:AppId"]; var appSecret = Configuration["Identity:SignInMethods:Facebook:AppSecret"]; idapp.UseFacebookAuthentication(new FacebookOptions() { DisplayName = "Facebook", SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme, CallbackPath = "/signin-facebook", AppId = appId, AppSecret = appSecret }); } idapp.UseStaticFiles(); idapp.UseMvc(routes => { routes.MapRoute( name: "account", template: "account/{action}", defaults: new { controller = "Account" }); }); }); } app.Map("/api", apiapp => { apiapp.UseCors(options => { logger.LogInformation("CORS options:"); var config = Configuration.GetSection("Common:Cors"); var allowedOrigins = config.ParseStringArray("AllowedOrigins").ToArray(); logger.LogInformation("AllowedOrigins: {0}", string.Join(",", allowedOrigins)); options.WithOrigins(allowedOrigins); // TODO - allow configuration of headers/methods options .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); var idsvrConfig = Configuration.GetSection("Identity:IdentityServer"); string authority = idsvrConfig["Authority"]; bool requireHttps = idsvrConfig.GetValue("RequireHttps", true); apiapp.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions { Authority = authority, RequireHttpsMetadata = requireHttps, ApiName = "nether-all", AllowedScopes = { "nether-all" }, }); // TODO filter which routes this matches (i.e. only API routes) apiapp.UseMvc(); apiapp.UseSwagger(options => { options.RouteTemplate = "swagger/{documentName}/swagger.json"; }); apiapp.UseSwaggerUI(options => { options.RoutePrefix = "swagger/ui"; options.SwaggerEndpoint("/api/swagger/v0.1/swagger.json", "v0.1 Docs"); options.ConfigureOAuth2("swaggerui", "swaggeruisecret".Sha256(), "swagger-ui-realm", "Swagger UI"); }); }); app.Map("/ui", uiapp => { uiapp.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookies" }); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); var authority = Configuration["Identity:IdentityServer:Authority"]; var uiBaseUrl = Configuration["Identity:IdentityServer:UiBaseUrl"]; // hybrid uiapp.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { AuthenticationScheme = "oidc", SignInScheme = "Cookies", Authority = authority, RequireHttpsMetadata = false, PostLogoutRedirectUri = uiBaseUrl, ClientId = "mvc2", ClientSecret = "secret", ResponseType = "code id_token", Scope = { "api1", "offline_access" }, GetClaimsFromUserInfoEndpoint = true, SaveTokens = true }); uiapp.UseMvc(); // TODO filter which routes this matches (i.e. only non-API routes) }); // serve Landing page static files at root app.UseStaticFiles(new StaticFileOptions { RequestPath = "", FileProvider = new PhysicalFileProvider(Path.Combine(_hostingEnvironment.WebRootPath, "Features", "LandingPage")) }); app.UseMvc(routes => { routes.MapRoute( name: "landing-page", template: "", defaults: new { controller = "LandingPage", action = "Index" } ); }); } } }
// 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.Runtime.CompilerServices; internal class List { const int LOOP = 847; public SmallGC dat; public List next; public static void Main(string[] p_args) { long iterations = 200; //Large Object Collection CreateLargeObjects(); GC.Collect(); GC.WaitForPendingFinalizers(); for(long i = 0; i < iterations; i++) { CreateLargeObjects(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } //Large Object Collection (half array) CreateLargeObjectsHalf(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); for(long i = 0; i < iterations; i++) { CreateLargeObjectsHalf(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } //Promote from Gen1 to Gen2 SmallGC [] sgc; sgc = new SmallGC [LOOP]; for (int j = 0; j < LOOP; j++) sgc[j] = new SmallGC(0); GC.Collect(); for (int j = 0; j < LOOP; j++) sgc[j] = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); for(long i = 0; i < iterations; i++) { // allocate into gen 0 sgc = new SmallGC [LOOP]; for (int j = 0; j < LOOP; j++) sgc[j] = new SmallGC(0); // promote to gen 1 while (GC.GetGeneration(sgc[LOOP-1])<1) { GC.Collect(); } while (GC.GetGeneration(sgc[LOOP-1])<2) { // promote to gen 2 GC.Collect(); } for (int j = 0; j < LOOP; j++) sgc[j] = null; GC.Collect(); GC.WaitForPendingFinalizers(); } //Promote from Gen1 to Gen2 (Gen1 ptr updates) List node = PopulateList(LOOP); GC.Collect(); GC.WaitForPendingFinalizers(); if(List.ValidateList(node, LOOP) == 0) Console.WriteLine("Pointers after promotion are not valid"); for(long i = 0; i < iterations; i++) { // allocate into gen 0 node = PopulateList(LOOP); // promote to gen 1 while (GC.GetGeneration(node)<1) { GC.Collect(); } while (GC.GetGeneration(node)<2) { //promote to gen 2 GC.Collect(); GC.WaitForPendingFinalizers(); if(ValidateList(node, LOOP) == 0) Console.WriteLine("Pointers after promotion are not valid"); } } } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static List PopulateList(int len) { if (len == 0) return null; List Node = new List(); Node.dat = new SmallGC(1); Node.dat.AttachSmallObjects(); Node.next = null; for (int i = len -1; i > 0; i--) { List cur = new List(); cur.dat = new SmallGC(1); cur.dat.AttachSmallObjects(); cur.next = Node; Node = cur; } return Node; } public static int ValidateList(List First, int len) { List tmp1 = First; int i = 0; LargeGC tmp2; while(tmp1 != null) { //Check the list have correct small object pointers after collection if(tmp1.dat == null) break; tmp2 = tmp1.dat.m_pLarge; //check the large object has non zero small object pointers if (tmp2.m_pSmall == null) break; //check the large object has correct small object pointers if(tmp2.m_pSmall != tmp1.dat) break; tmp1 = tmp1.next; i++; } if (i == len) return 1; else return 0; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void CreateLargeObjects() { LargeGC [] lgc; lgc = new LargeGC[LOOP]; for (int i=0; i < LOOP ; i++) lgc[i] = new LargeGC(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void CreateLargeObjectsHalf() { LargeGC [] lgc; lgc = new LargeGC[LOOP]; for(int i = 0; i < LOOP; i++) lgc[i] = new LargeGC(); for(int i = 0; i < LOOP; i+=2) lgc[i] = null; } } internal class LargeGC { public double [] d; public SmallGC m_pSmall; public LargeGC() { d = new double [10625]; //85 KB m_pSmall = null; } public virtual void AttachSmallObjects(SmallGC small) { m_pSmall = small; } } internal class SmallGC { public LargeGC m_pLarge; public SmallGC(int HasLargeObj) { if (HasLargeObj == 1) m_pLarge = new LargeGC(); else m_pLarge = null; } public virtual void AttachSmallObjects() { m_pLarge.AttachSmallObjects(this); } }
//------------------------------------------------------------------------------ // <copyright file="PersonalizationProvider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls.WebParts { using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Configuration; using System.Configuration.Provider; using System.Security.Principal; using System.Web; using System.Web.Configuration; using System.Web.Hosting; using System.Web.Util; /// <devdoc> /// The provider used to access the personalization store for WebPart pages. /// </devdoc> public abstract class PersonalizationProvider : ProviderBase { private const string scopeFieldName = "__WPPS"; private const string sharedScopeFieldValue = "s"; private const string userScopeFieldValue = "u"; private ICollection _supportedUserCapabilities; /// <devdoc> /// Initializes an instance of PersonalizationProvider. /// </devdoc> protected PersonalizationProvider() { } /// <devdoc> /// The name of the application that this provider should use to store /// and retrieve personalization data from. /// </devdoc> public abstract string ApplicationName { get; set; } /// <devdoc> /// </devdoc> protected virtual IList CreateSupportedUserCapabilities() { ArrayList list = new ArrayList(); list.Add(WebPartPersonalization.EnterSharedScopeUserCapability); list.Add(WebPartPersonalization.ModifyStateUserCapability); return list; } /// <devdoc> /// </devdoc> public virtual PersonalizationScope DetermineInitialScope(WebPartManager webPartManager, PersonalizationState loadedState) { if (webPartManager == null) { throw new ArgumentNullException("webPartManager"); } Page page = webPartManager.Page; if (page == null) { throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "Page"), "webPartManager"); } HttpRequest request = page.RequestInternal; if (request == null) { throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "Page.Request"), "webPartManager"); } PersonalizationScope scope = webPartManager.Personalization.InitialScope; IPrincipal user = null; if (request.IsAuthenticated) { user = page.User; } if (user == null) { // if no user has been authenticated, then just load all user data scope = PersonalizationScope.Shared; } else { if (page.IsPostBack) { string postedMode = page.Request[scopeFieldName]; if (postedMode == sharedScopeFieldValue) { scope = PersonalizationScope.Shared; } else if (postedMode == userScopeFieldValue) { scope = PersonalizationScope.User; } } else if ((page.PreviousPage != null) && (page.PreviousPage.IsCrossPagePostBack == false)) { WebPartManager previousWebPartManager = WebPartManager.GetCurrentWebPartManager(page.PreviousPage); if (previousWebPartManager != null) { // Note that we check the types of the page, so we don't // look the at the PreviousPage in a cross-page posting scenario scope = previousWebPartManager.Personalization.Scope; } } // Special-case Web Part Export so it executes in the same security context as the page itself (VSWhidbey 426574) // Setting the initial scope from what's been asked for in the export parameters else if (page.IsExportingWebPart) { scope = (page.IsExportingWebPartShared ? PersonalizationScope.Shared : PersonalizationScope.User); } if ((scope == PersonalizationScope.Shared) && (webPartManager.Personalization.CanEnterSharedScope == false)) { scope = PersonalizationScope.User; } } string fieldValue = (scope == PersonalizationScope.Shared) ? sharedScopeFieldValue : userScopeFieldValue; page.ClientScript.RegisterHiddenField(scopeFieldName, fieldValue); return scope; } /// <devdoc> /// </devdoc> public virtual IDictionary DetermineUserCapabilities(WebPartManager webPartManager) { if (webPartManager == null) { throw new ArgumentNullException("webPartManager"); } Page page = webPartManager.Page; if (page == null) { throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "Page"), "webPartManager"); } HttpRequest request = page.RequestInternal; if (request == null) { throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "Page.Request"), "webPartManager"); } IPrincipal user = null; if (request.IsAuthenticated) { user = page.User; } if (user != null) { if (_supportedUserCapabilities == null) { _supportedUserCapabilities = CreateSupportedUserCapabilities(); } if ((_supportedUserCapabilities != null) && (_supportedUserCapabilities.Count != 0)) { WebPartsSection configSection = RuntimeConfig.GetConfig().WebParts; if (configSection != null) { WebPartsPersonalizationAuthorization authConfig = configSection.Personalization.Authorization; if (authConfig != null) { IDictionary capabilities = new HybridDictionary(); foreach (WebPartUserCapability capability in _supportedUserCapabilities) { if (authConfig.IsUserAllowed(user, capability.Name)) { capabilities[capability] = capability; } } return capabilities; } } } } return new HybridDictionary(); } public abstract PersonalizationStateInfoCollection FindState(PersonalizationScope scope, PersonalizationStateQuery query, int pageIndex, int pageSize, out int totalRecords); public abstract int GetCountOfState(PersonalizationScope scope, PersonalizationStateQuery query); /// <devdoc> /// </devdoc> private void GetParameters(WebPartManager webPartManager, out string path, out string userName) { if (webPartManager == null) { throw new ArgumentNullException("webPartManager"); } Page page = webPartManager.Page; if (page == null) { throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "Page"), "webPartManager"); } HttpRequest request = page.RequestInternal; if (request == null) { throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "Page.Request"), "webPartManager"); } path = request.AppRelativeCurrentExecutionFilePath; userName = null; if ((webPartManager.Personalization.Scope == PersonalizationScope.User) && page.Request.IsAuthenticated) { userName = page.User.Identity.Name; } } /// <devdoc> /// Loads the data from the data store for the specified path and user. /// If only shared data is to be loaded, userName is null or empty. /// </devdoc> protected abstract void LoadPersonalizationBlobs(WebPartManager webPartManager, string path, string userName, ref byte[] sharedDataBlob, ref byte[] userDataBlob); /// <devdoc> /// Allows the provider to load personalization data. The specified /// WebPartManager is used to access the current page, which can be used /// to retrieve the path and user information. /// </devdoc> public virtual PersonalizationState LoadPersonalizationState(WebPartManager webPartManager, bool ignoreCurrentUser) { if (webPartManager == null) { throw new ArgumentNullException("webPartManager"); } string path; string userName; GetParameters(webPartManager, out path, out userName); if (ignoreCurrentUser) { userName = null; } byte[] sharedDataBlob = null; byte[] userDataBlob = null; LoadPersonalizationBlobs(webPartManager, path, userName, ref sharedDataBlob, ref userDataBlob); BlobPersonalizationState blobState = new BlobPersonalizationState(webPartManager); blobState.LoadDataBlobs(sharedDataBlob, userDataBlob); return blobState; } /// <devdoc> /// Removes the data from the data store for the specified path and user. /// If userName is null or empty, the shared data is to be reset. /// </devdoc> protected abstract void ResetPersonalizationBlob(WebPartManager webPartManager, string path, string userName); /// <devdoc> /// Allows the provider to reset personalization data. The specified /// WebPartManager is used to access the current page, which can be used /// to retrieve the path and user information. /// </devdoc> public virtual void ResetPersonalizationState(WebPartManager webPartManager) { if (webPartManager == null) { throw new ArgumentNullException("webPartManager"); } string path; string userName; GetParameters(webPartManager, out path, out userName); ResetPersonalizationBlob(webPartManager, path, userName); } public abstract int ResetState(PersonalizationScope scope, string[] paths, string[] usernames); public abstract int ResetUserState(string path, DateTime userInactiveSinceDate); /// <devdoc> /// Saves the data into the data store for the specified path and user. /// If only shared data is to be saved, userName is null or empty. /// </devdoc> protected abstract void SavePersonalizationBlob(WebPartManager webPartManager, string path, string userName, byte[] dataBlob); /// <devdoc> /// Allows the provider to save personalization data. The specified information /// contains a reference to the WebPartManager, which is used to access the /// current Page, and its path and user information. /// </devdoc> public virtual void SavePersonalizationState(PersonalizationState state) { if (state == null) { throw new ArgumentNullException("state"); } BlobPersonalizationState blobState = state as BlobPersonalizationState; if (blobState == null) { throw new ArgumentException(SR.GetString(SR.PersonalizationProvider_WrongType), "state"); } WebPartManager webPartManager = blobState.WebPartManager; string path; string userName; GetParameters(webPartManager, out path, out userName); byte[] dataBlob = null; bool reset = blobState.IsEmpty; if (reset == false) { dataBlob = blobState.SaveDataBlob(); reset = (dataBlob == null) || (dataBlob.Length == 0); } if (reset) { ResetPersonalizationBlob(webPartManager, path, userName); } else { SavePersonalizationBlob(webPartManager, path, userName, dataBlob); } } } }
// // LiteTestCase.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // #if DEBUG #define __CONSOLE__ #else #define __CONSOLE__ #endif using System; using System.Diagnostics; namespace Couchbase.Lite.Util { class CouchbaseTraceListener : DefaultTraceListener { const string Indent = " "; const string Category = "Trace"; SourceLevels Level; public CouchbaseTraceListener() { } public CouchbaseTraceListener(SourceLevels logLevel) { Level = logLevel; Name = "Couchbase"; TraceOutputOptions = Level.HasFlag(SourceLevels.All) ? TraceOptions.ThreadId | TraceOptions.DateTime /*| TraceOptions.Timestamp*/ : TraceOptions.None; } void WriteOptionalTraceInfo() { #if !__MOBILE__ && !NET_3_5 var traceInfo = new TraceEventCache(); if (TraceOutputOptions.HasFlag(TraceOptions.ThreadId)) { PrintThreadId(traceInfo); } if (TraceOutputOptions.HasFlag(TraceOptions.DateTime)) { PrintDateTime(traceInfo); } if (TraceOutputOptions.HasFlag(TraceOptions.Timestamp)) { PrintTimeStamp(traceInfo); } #endif } #if !__MOBILE__ && !NET_3_5 void PrintThreadId(TraceEventCache info) { #if __DEBUGGER__ Debugger.Log((int)SourceLevels.Critical, Category, "Thread Name: " + info.ThreadId + Environment.NewLine); #endif #if __CONSOLE__ WriteIndent(); Console.Out.Write("Thread Name: "); Console.Out.Write(info.ThreadId); Console.Out.Write(Environment.NewLine); #endif } void PrintDateTime(TraceEventCache info) { #if __DEBUGGER__ Debugger.Log((int)SourceLevels.Critical, Category, "Date Time: " + info.DateTime + Environment.NewLine); #endif #if __CONSOLE__ WriteIndent(); Console.Out.Write("Date Time: "); Console.Out.Write(info.DateTime); Console.Out.Write(Environment.NewLine); #endif } void PrintTimeStamp(TraceEventCache info) { #if __DEBUGGER__ Debugger.Log((int)SourceLevels.Critical, Category, "Timestamp: " + info.Timestamp + Environment.NewLine); #endif #if __CONSOLE__ WriteIndent(); Console.Out.Write("Timestamp: "); Console.Out.Write(info.Timestamp); Console.Out.Write(Environment.NewLine); #endif } #endif public void WriteLine(SourceLevels level, string message, string category) { Level = level; WriteLine(message, category); } #region implemented abstract members of TraceListener public override string Name { get; set; } public override void Write(string message) { #if __DEBUGGER__ Debugger.Log((int)Level, null, message); #endif #if __CONSOLE__ Console.Out.Write(message); Console.Out.Flush(); #endif } public override void WriteLine(string message) { WriteLine(message, null); } public override void WriteLine(string message, string category) { #if __DEBUGGER__ Debugger.Log((int)Level, category, message + Environment.NewLine); #endif #if __CONSOLE__ Console.Out.Write(category); Console.Out.Write(": "); Console.Out.Write(message); Console.Out.Write(Environment.NewLine); Console.Out.Flush(); #endif WriteOptionalTraceInfo(); } public override void Write(object o) { Write(o.ToString()); } public override void Write(object o, string category) { Write(o.ToString(), category); } public override void WriteLine(object o) { WriteLine(o.ToString()); } public override void WriteLine(object o, string category) { WriteLine(o.ToString(), category); } public override void Write(string message, string category) { #if __DEBUGGER__ Debugger.Log((int)Level, category, message); #endif #if __CONSOLE__ Console.Out.Write(category); Console.Out.Write(": "); Console.Out.Write(message); Console.Out.Flush(); #endif } protected override void WriteIndent() { Write(Indent); } public override void Fail (string message) { #if __DEBUGGER__ Debugger.Log((int)SourceLevels.Critical, Category, message + Environment.NewLine); #endif #if __CONSOLE__ Console.Out.Write(message); Console.Out.Write(Environment.NewLine); #endif WriteOptionalTraceInfo(); } public override void Fail (string message, string detailMessage) { Fail (message); var lines = detailMessage.Split(new[] { Environment.NewLine }, StringSplitOptions.None); foreach(var line in lines) { WriteIndent(); Write(line); Write(Environment.NewLine); } } #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.Algo.Positions.Algo File: PositionManager.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Positions { using System; using System.Collections.Generic; using Ecng.Collections; using StockSharp.Logging; using StockSharp.Messages; /// <summary> /// The position calculation manager. /// </summary> public class PositionManager : BaseLogReceiver, IPositionManager { private class OrderInfo { public OrderInfo(long transactionId, SecurityId securityId, string portfolioName, Sides side, decimal volume, decimal balance) { TransactionId = transactionId; SecurityId = securityId; PortfolioName = portfolioName; Side = side; Volume = volume; Balance = balance; } public long TransactionId { get; } public SecurityId SecurityId { get; } public string PortfolioName { get; } public Sides Side { get; } public decimal Volume { get; } public decimal Balance { get; set; } public override string ToString() => $"{TransactionId}: {Balance}/{Volume}"; } private class PositionInfo { public decimal Value { get; set; } public override string ToString() => Value.ToString(); } private readonly Dictionary<long, OrderInfo> _ordersInfo = new(); private readonly Dictionary<Tuple<SecurityId, string>, PositionInfo> _positions = new(); /// <summary> /// Initializes a new instance of the <see cref="PositionManager"/>. /// </summary> /// <param name="byOrders">To calculate the position on realized volume for orders (<see langword="true" />) or by trades (<see langword="false" />).</param> public PositionManager(bool byOrders) { ByOrders = byOrders; } /// <summary> /// To calculate the position on realized volume for orders (<see langword="true" />) or by trades (<see langword="false" />). /// </summary> public bool ByOrders { get; } /// <inheritdoc /> public virtual PositionChangeMessage ProcessMessage(Message message) { static Tuple<SecurityId, string> CreateKey(SecurityId secId, string pf) => Tuple.Create(secId, pf.ToLowerInvariant()); static Tuple<SecurityId, string> CreateKey2<TMessage>(TMessage message) where TMessage : Message, ISecurityIdMessage, IPortfolioNameMessage => CreateKey(message.SecurityId, message.PortfolioName); OrderInfo EnsureGetInfo<TMessage>(TMessage msg, Sides side, decimal volume, decimal balance) where TMessage : Message, ITransactionIdMessage, ISecurityIdMessage, IPortfolioNameMessage { this.AddDebugLog("{0} bal_new {1}/{2}.", msg.TransactionId, balance, volume); return _ordersInfo.SafeAdd(msg.TransactionId, key => new OrderInfo(key, msg.SecurityId, msg.PortfolioName, side, volume, balance)); } void ProcessRegOrder(OrderRegisterMessage regMsg) => EnsureGetInfo(regMsg, regMsg.Side, regMsg.Volume, regMsg.Volume); PositionChangeMessage UpdatePositions(SecurityId secId, string portfolioName, decimal diff, DateTimeOffset time) { var position = _positions.SafeAdd(CreateKey(secId, portfolioName)); position.Value += diff; return new PositionChangeMessage { SecurityId = secId, PortfolioName = portfolioName, ServerTime = time, BuildFrom = DataType.Transactions, }.Add(PositionChangeTypes.CurrentValue, position.Value); } switch (message.Type) { case MessageTypes.Reset: { _ordersInfo.Clear(); _positions.Clear(); break; } case MessageTypes.OrderRegister: case MessageTypes.OrderReplace: { ProcessRegOrder((OrderRegisterMessage)message); break; } case MessageTypes.OrderPairReplace: { var pairMsg = (OrderPairReplaceMessage)message; ProcessRegOrder(pairMsg.Message1); ProcessRegOrder(pairMsg.Message2); break; } case MessageTypes.Execution: { var execMsg = (ExecutionMessage)message; if (execMsg.IsMarketData()) break; var isOrderInfo = execMsg.HasOrderInfo(); var info = isOrderInfo ? execMsg.TransactionId != 0 ? EnsureGetInfo(execMsg, execMsg.Side, execMsg.OrderVolume ?? 0, execMsg.Balance ?? 0) : _ordersInfo.TryGetValue(execMsg.OriginalTransactionId) : execMsg.OriginalTransactionId != 0 && execMsg.HasTradeInfo() ? _ordersInfo.TryGetValue(execMsg.OriginalTransactionId) : null; var canUpdateOrder = isOrderInfo && info != null; decimal? balDiff = null; if (canUpdateOrder) { var oldBalance = execMsg.TransactionId != 0 ? execMsg.OrderVolume : info.Balance; balDiff = oldBalance - execMsg.Balance; if (balDiff.HasValue && balDiff != 0) { // ReSharper disable once PossibleInvalidOperationException info.Balance = execMsg.Balance.Value; this.AddDebugLog("{0} bal_upd {1}/{2}.", info.TransactionId, info.Balance, info.Volume); } } if (ByOrders) { if (!canUpdateOrder) break; if (balDiff.HasValue && balDiff != 0) { var posDiff = info.Side == Sides.Buy ? balDiff.Value : -balDiff.Value; return UpdatePositions(info.SecurityId, info.PortfolioName, posDiff, execMsg.ServerTime); } } else { if (!execMsg.HasTradeInfo()) break; var tradeVol = execMsg.TradeVolume; if (tradeVol == null) break; if (tradeVol == 0) { this.AddWarningLog("Trade {0}/{1} of order {2} has zero volume.", execMsg.TradeId, execMsg.TradeStringId, execMsg.OriginalTransactionId); break; } if (execMsg.Side == Sides.Sell) tradeVol = -tradeVol; var secId = info?.SecurityId ?? execMsg.SecurityId; var portfolioName = info?.PortfolioName ?? execMsg.PortfolioName; return UpdatePositions(secId, portfolioName, tradeVol.Value, execMsg.ServerTime); } break; } case MessageTypes.PositionChange: { var posMsg = (PositionChangeMessage)message; if (posMsg.Changes.TryGetValue(PositionChangeTypes.CurrentValue, out var curr)) _positions.SafeAdd(CreateKey2(posMsg)).Value = (decimal)curr; break; } } return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// SnapshotsOperations operations. /// </summary> public partial interface ISnapshotsOperations { /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource /// group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<Snapshot>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Snapshot snapshot, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource /// group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot /// operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<Snapshot>> UpdateWithHttpMessagesAsync(string resourceGroupName, string snapshotName, SnapshotUpdate snapshot, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource /// group. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<Snapshot>> GetWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource /// group. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<OperationStatusResponse>> DeleteWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<IPage<Snapshot>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<IPage<Snapshot>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource /// group. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<AccessUri>> GrantAccessWithHttpMessagesAsync(string resourceGroupName, string snapshotName, GrantAccessData grantAccessData, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource /// group. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<OperationStatusResponse>> RevokeAccessWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource /// group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<Snapshot>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Snapshot snapshot, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource /// group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot /// operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<Snapshot>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string snapshotName, SnapshotUpdate snapshot, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource /// group. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<OperationStatusResponse>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource /// group. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<AccessUri>> BeginGrantAccessWithHttpMessagesAsync(string resourceGroupName, string snapshotName, GrantAccessData grantAccessData, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource /// group. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<OperationStatusResponse>> BeginRevokeAccessWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<IPage<Snapshot>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<IPage<Snapshot>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.ICollection&lt;System.Collections.Generic.KeyValuePair&lt;TKey,TValue&gt;&gt;.CopyTo(System.Collections.Generic.KeyValuePair&lt;TKey,TValue&gt;[],System.Int32) /// </summary> public class DictionaryICollectionCopyTo { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ICollectionCopyTo ."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = new KeyValuePair<string,string>[dictionary.Count]; dictionary.CopyTo(kvpArray, 0); bool actual = (kvpArray[0].Equals(kvp1)) && (kvpArray[1].Equals(kvp2)) && (kvpArray[2].Equals(kvp3)) && (kvpArray[3].Equals(kvp4)); bool expected = true; if (actual != expected) { TestLibrary.TestFramework.LogError("001.1", "Method ICollectionCopyTo 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; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown when array is null ref."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = null; dictionary.CopyTo(kvpArray, 0); TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown."); retVal = false; } catch (ArgumentNullException) { } 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: ArgumentOutOfRangeException is not thrown ."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = new KeyValuePair<string, string>[dictionary.Count]; dictionary.CopyTo(kvpArray, -1); TestLibrary.TestFramework.LogError("102.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentException is not thrown ."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = new KeyValuePair<string, string>[dictionary.Count]; dictionary.CopyTo(kvpArray, 4); TestLibrary.TestFramework.LogError("103.1", "ArgumentException is not thrown."); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentException is not thrown ."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = new KeyValuePair<string, string>[dictionary.Count - 1]; dictionary.CopyTo(kvpArray, 0); TestLibrary.TestFramework.LogError("104.1", "ArgumentException is not thrown."); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { DictionaryICollectionCopyTo test = new DictionaryICollectionCopyTo(); TestLibrary.TestFramework.BeginTestCase("DictionaryICollectionCopyTo"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
/******************************************************************************* * Copyright 2019 Viridian Software Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Threading; using Microsoft.Xna.Framework.Audio; using monogame.Files; using Org.Mini2Dx.Core; using Org.Mini2Dx.Core.Audio; using Org.Mini2Dx.Core.Files; namespace monogame.Audio { public class MonoGameSound : global::Java.Lang.Object, Sound { private readonly SoundEffect _sound; private readonly List<long> _thisInstancesIds; public MonoGameSound(FileHandle fileHandle) { lock(Mdx.audio_) { _sound = ((MonoGameFileHandle)fileHandle).loadFromContentManager<SoundEffect>(); } _thisInstancesIds = new List<long>(); } //todo implement a proper solution for disposing SoundEffects public void dispose_EFE09FC0() { for (int i = _thisInstancesIds.Count - 1; i >= 0; i--) { if (_thisInstancesIds[i] != -1 && MonoGameSoundInstance.InstancesById.ContainsKey(_thisInstancesIds[i])) { MonoGameSoundInstance.InstancesById[_thisInstancesIds[i]].Dispose(); } } //_sound.Dispose(); } public long play_0BE0CBD4() { return play_9B414416(1); } public long play_9B414416(float volume) { return play_4956CC16(volume, 1, 0); } private static float convertPitch(float pitch) { pitch -= 1; return pitch < 0 ? pitch * 2 : pitch; } public long play_4956CC16(float volume, float pitch, float pan) { var soundEffectInstance = _sound.CreateInstance(); var soundInstance = MonoGameSoundInstance.Allocate(this, soundEffectInstance); soundEffectInstance.Volume = volume; soundEffectInstance.Pan = pan; soundEffectInstance.Pitch = convertPitch(pitch); soundEffectInstance.Play(); return soundInstance.Id; } public long loop_0BE0CBD4() { return loop_9B414416(1); } public long loop_9B414416(float volume) { return loop_4956CC16(volume, 1, 1); } public long loop_4956CC16(float volume, float pitch, float pan) { long index = play_4956CC16(volume, pitch, pan); setLooping_98E3C020(index, true); return index; } public void stop_EFE09FC0() { for (int i = 0; i < _thisInstancesIds.Count; i++) { stop_5FE5E296(_thisInstancesIds[i]); } } public void pause_EFE09FC0() { for (int i = 0; i < _thisInstancesIds.Count; i++) { pause_5FE5E296(_thisInstancesIds[i]); } } public void resume_EFE09FC0() { for (int i = 0; i < _thisInstancesIds.Count; i++) { resume_5FE5E296(_thisInstancesIds[i]); } } public void stopTracking(long soundId) { _thisInstancesIds.Remove(soundId); } public void stop_5FE5E296(long soundId) { if (soundId == -1) { return; } if (!MonoGameSoundInstance.InstancesById.ContainsKey(soundId)) { return; } var soundInstance = MonoGameSoundInstance.InstancesById[soundId]; var soundEffectInstance = soundInstance.SoundEffectInstance; if (soundEffectInstance != null) { soundEffectInstance.Stop(); soundEffectInstance.Dispose(); MonoGameAudio.soundCompleted(soundId); } soundInstance.Dispose(); } public void pause_5FE5E296(long soundId) { if (soundId == -1) { return; } if (!MonoGameSoundInstance.InstancesById.ContainsKey(soundId)) { return; } var soundInstance = MonoGameSoundInstance.InstancesById[soundId]; var soundEffectInstance = soundInstance.SoundEffectInstance; soundEffectInstance.Pause(); } public void resume_5FE5E296(long soundId) { if (soundId == -1) { return; } if (!MonoGameSoundInstance.InstancesById.ContainsKey(soundId)) { return; } var soundInstance = MonoGameSoundInstance.InstancesById[soundId]; var soundEffectInstance = soundInstance.SoundEffectInstance; soundEffectInstance.Resume(); } public void setLooping_98E3C020(long soundId, bool looping) { if (soundId == -1) { return; } if (!MonoGameSoundInstance.InstancesById.ContainsKey(soundId)) { return; } var soundInstance = MonoGameSoundInstance.InstancesById[soundId]; var soundEffectInstance = soundInstance.SoundEffectInstance; soundEffectInstance.IsLooped = true; } public void setPitch_F9247704(long soundId, float pitch) { if (soundId == -1) { return; } if (!MonoGameSoundInstance.InstancesById.ContainsKey(soundId)) { return; } var soundInstance = MonoGameSoundInstance.InstancesById[soundId]; var soundEffectInstance = soundInstance.SoundEffectInstance; soundEffectInstance.Pitch = convertPitch(pitch); } public void setVolume_F9247704(long soundId, float volume) { if (soundId == -1) { return; } if (!MonoGameSoundInstance.InstancesById.ContainsKey(soundId)) { return; } var soundInstance = MonoGameSoundInstance.InstancesById[soundId]; var soundEffectInstance = soundInstance.SoundEffectInstance; soundEffectInstance.Volume = volume; } public void setPan_3604DC16(long soundId, float pan, float volume) { if (soundId == -1) { return; } if (!MonoGameSoundInstance.InstancesById.ContainsKey(soundId)) { return; } var soundInstance = MonoGameSoundInstance.InstancesById[soundId]; var soundEffectInstance = soundInstance.SoundEffectInstance; soundEffectInstance.Volume = volume; soundEffectInstance.Pan = pan; } } public class MonoGameSoundInstance { public static readonly List<MonoGameSoundInstance> Instances = new List<MonoGameSoundInstance>(); public static readonly Dictionary<long, MonoGameSoundInstance> InstancesById = new Dictionary<long, MonoGameSoundInstance>(); private static List<MonoGameSoundInstance> POOL = new List<MonoGameSoundInstance>(); private static long ID_ALLOCATOR = 0; public MonoGameSound Sound { get; private set; } public SoundEffectInstance SoundEffectInstance { get; private set; } public long Id { get; private set; } private MonoGameSoundInstance(){} public void Dispose() { Monitor.Enter(POOL); try { Instances.Remove(this); InstancesById.Remove(Id); SoundEffectInstance.Dispose(); Sound.stopTracking(Id); Sound = null; SoundEffectInstance = null; POOL.Add(this); } finally { Monitor.Exit(POOL); } } public static MonoGameSoundInstance Allocate(MonoGameSound sound, SoundEffectInstance soundEffectInstance) { Monitor.Enter(POOL); try { MonoGameSoundInstance result = null; if (POOL.Count == 0) { result = new MonoGameSoundInstance(); } else { result = POOL[0]; POOL.RemoveAt(0); } result.Id = ID_ALLOCATOR++; result.Sound = sound; result.SoundEffectInstance = soundEffectInstance; if(ID_ALLOCATOR >= long.MaxValue) { ID_ALLOCATOR = 0; } Instances.Add(result); InstancesById.Add(result.Id, result); return result; } finally { Monitor.Exit(POOL); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Manufacturing.Api.Areas.HelpPage.ModelDescriptions; using Manufacturing.Api.Areas.HelpPage.Models; namespace Manufacturing.Api.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//--------------------------------------------------------------------------- // // File: InkPresenter.cs // // Description: // A rendering element which binds to the strokes data // // Features: // // History: // 12/02/2004 waynezen: Created // // Copyright (C) 2001 by Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Diagnostics; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Media; using System.Windows.Controls; using System.Windows.Ink; using System.Windows.Threading; using System.Windows.Input; using MS.Internal.Ink; using System.Windows.Automation.Peers; namespace System.Windows.Controls { /// <summary> /// Renders the specified StrokeCollection data. /// </summary> public class InkPresenter : Decorator { //------------------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------------------- #region Constructors /// <summary> /// The constructor of InkPresenter /// </summary> public InkPresenter() { // Create the internal Renderer object. _renderer = new Ink.Renderer(); SetStrokesChangedHandlers(this.Strokes, null); _contrastCallback = new InkPresenterHighContrastCallback(this); // Register rti high contrast callback. Then check whether we are under the high contrast already. HighContrastHelper.RegisterHighContrastCallback(_contrastCallback); if ( SystemParameters.HighContrast ) { _contrastCallback.TurnHighContrastOn(SystemColors.WindowTextColor); } _constraintSize = Size.Empty; } #endregion Constructors //------------------------------------------------------------------------------- // // Public Methods // //------------------------------------------------------------------------------- #region Public Methods /// <summary> /// AttachVisual method /// </summary> /// <param name="visual">The stroke visual which needs to be attached</param> /// <param name="drawingAttributes">The DrawingAttributes of the stroke</param> public void AttachVisuals(Visual visual, DrawingAttributes drawingAttributes) { VerifyAccess(); EnsureRootVisual(); _renderer.AttachIncrementalRendering(visual, drawingAttributes); } /// <summary> /// DetachVisual method /// </summary> /// <param name="visual">The stroke visual which needs to be detached</param> public void DetachVisuals(Visual visual) { VerifyAccess(); EnsureRootVisual(); _renderer.DetachIncrementalRendering(visual); } #endregion Public Methods //------------------------------------------------------------------------------- // // Public Properties // //------------------------------------------------------------------------------- #region Public Properties /// <summary> /// The DependencyProperty for the Strokes property. /// </summary> public static readonly DependencyProperty StrokesProperty = DependencyProperty.Register( "Strokes", typeof(StrokeCollection), typeof(InkPresenter), new FrameworkPropertyMetadata( new StrokeCollectionDefaultValueFactory(), new PropertyChangedCallback(OnStrokesChanged)), (ValidateValueCallback)delegate(object value) { return value != null; }); /// <summary> /// Gets/Sets the Strokes property. /// </summary> public StrokeCollection Strokes { get { return (StrokeCollection)GetValue(StrokesProperty); } set { SetValue(StrokesProperty, value); } } private static void OnStrokesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { InkPresenter inkPresenter = (InkPresenter)d; StrokeCollection oldValue = (StrokeCollection)e.OldValue; StrokeCollection newValue = (StrokeCollection)e.NewValue; inkPresenter.SetStrokesChangedHandlers(newValue, oldValue); inkPresenter.OnStrokeChanged(inkPresenter, EventArgs.Empty); } #endregion Public Properties //------------------------------------------------------------------------------- // // Protected Methods // //------------------------------------------------------------------------------- #region Protected Methods /// <summary> /// Override of <seealso cref="FrameworkElement.MeasureOverride" /> /// </summary> /// <param name="constraint">Constraint size.</param> /// <returns>Computed desired size.</returns> protected override Size MeasureOverride(Size constraint) { // No need to call VerifyAccess since we call the method on the base here. StrokeCollection strokes = Strokes; // Measure the child first Size newSize = base.MeasureOverride(constraint); // If there are strokes in IP, we need to combine the size to final size. if ( strokes != null && strokes.Count != 0 ) { // Get the bounds of the stroks Rect boundingRect = StrokesBounds; // If we have an empty bounding box or the Right/Bottom value is negative, // an empty size will be returned. if ( !boundingRect.IsEmpty && boundingRect.Right > 0.0 && boundingRect.Bottom > 0.0 ) { // The new size needs to contain the right boundary and bottom boundary. Size sizeStrokes = new Size(boundingRect.Right, boundingRect.Bottom); newSize.Width = Math.Max(newSize.Width, sizeStrokes.Width); newSize.Height = Math.Max(newSize.Height, sizeStrokes.Height); } } if ( Child != null ) { _constraintSize = constraint; } else { _constraintSize = Size.Empty; } return newSize; } /// <summary> /// Override of <seealso cref="FrameworkElement.ArrangeOverride" />. /// </summary> /// <param name="arrangeSize">Size that element should use to arrange itself and its children.</param> /// <returns>The InkPresenter's desired size.</returns> protected override Size ArrangeOverride(Size arrangeSize) { VerifyAccess(); EnsureRootVisual(); // NTRAID-WINDOWSOS#1091908-WAYNEZEN, // When we arrange the child, we shouldn't count in the strokes' bounds. // We only use the constraint size for the child. Size availableSize = arrangeSize; if ( !_constraintSize.IsEmpty ) { availableSize = new Size(Math.Min(arrangeSize.Width, _constraintSize.Width), Math.Min(arrangeSize.Height, _constraintSize.Height)); } // We arrange our child as what Decorator does // exceopt we are using the available size computed from our cached measure size. UIElement child = Child; if ( child != null ) { child.Arrange(new Rect(availableSize)); } return arrangeSize; } /// <summary> /// The overridden GetLayoutClip method /// </summary> /// <returns>Geometry to use as additional clip if ClipToBounds=true</returns> protected override Geometry GetLayoutClip(Size layoutSlotSize) { // NTRAID:WINDOWSOS#1516798-2006/02/17-WAYNEZEN // By default an FE will clip its content if the ink size exceeds the layout size (the final arrange size). // Since we are auto growing, the ink size is same as the desired size. So it ends up the strokes will be clipped // regardless ClipToBounds is set or not. // We override the GetLayoutClip method so that we can bypass the default layout clip if ClipToBounds is set to false. // So we allow the ink to be drown anywhere when no clip is set. if ( ClipToBounds ) { return base.GetLayoutClip(layoutSlotSize); } else return null; } /// <summary> /// Returns the child at the specified index. /// </summary> protected override Visual GetVisualChild(int index) { int count = VisualChildrenCount; if(count == 2) { switch (index) { case 0: return base.Child; case 1: return _renderer.RootVisual; default: throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } } else if (index == 0 && count == 1) { if ( _hasAddedRoot ) { return _renderer.RootVisual; } else if(base.Child != null) { return base.Child; } } throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } /// <summary> /// Derived classes override this property to enable the Visual code to enumerate /// the Visual children. Derived classes need to return the number of children /// from this method. /// /// By default a Visual does not have any children. /// /// Remark: During this virtual method the Visual tree must not be modified. /// </summary> protected override int VisualChildrenCount { get { // we can have 4 states:- // 1. no children // 2. only base.Child // 3. only _renderer.RootVisual as the child // 4. both base.Child and _renderer.RootVisual if(base.Child != null) { if ( _hasAddedRoot ) { return 2; } else { return 1; } } else if ( _hasAddedRoot ) { return 1; } return 0; } } /// <summary> /// UIAutomation support /// </summary> protected override AutomationPeer OnCreateAutomationPeer() { return new InkPresenterAutomationPeer(this); } #endregion Protected Methods #region Internal Methods /// <summary> /// Internal helper used to indicate if a visual was previously attached /// via a call to AttachIncrementalRendering /// </summary> internal bool ContainsAttachedVisual(Visual visual) { VerifyAccess(); return _renderer.ContainsAttachedIncrementalRenderingVisual(visual); } /// <summary> /// Internal helper used to determine if a visual is in the right spot in the visual tree /// </summary> internal bool AttachedVisualIsPositionedCorrectly(Visual visual, DrawingAttributes drawingAttributes) { VerifyAccess(); return _renderer.AttachedVisualIsPositionedCorrectly(visual, drawingAttributes); } #endregion Internal Methods //------------------------------------------------------ // // Private Classes // //------------------------------------------------------ #region Private Classes /// <summary> /// A helper class for the high contrast support /// </summary> private class InkPresenterHighContrastCallback : HighContrastCallback { //------------------------------------------------------ // // Cnostructors // //------------------------------------------------------ #region Constructors internal InkPresenterHighContrastCallback(InkPresenter inkPresenter) { _thisInkPresenter = inkPresenter; } private InkPresenterHighContrastCallback() { } #endregion Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// TurnHighContrastOn /// </summary> /// <param name="highContrastColor"></param> internal override void TurnHighContrastOn(Color highContrastColor) { _thisInkPresenter._renderer.TurnHighContrastOn(highContrastColor); _thisInkPresenter.OnStrokeChanged(); } /// <summary> /// TurnHighContrastOff /// </summary> internal override void TurnHighContrastOff() { _thisInkPresenter._renderer.TurnHighContrastOff(); _thisInkPresenter.OnStrokeChanged(); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties /// <summary> /// Returns the dispatcher if the object is associated to a UIContext. /// </summary> internal override Dispatcher Dispatcher { get { return _thisInkPresenter.Dispatcher; } } #endregion Internal Properties //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private InkPresenter _thisInkPresenter; #endregion Private Fields } #endregion Private Classes //------------------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------------------- #region Private Methods private void SetStrokesChangedHandlers(StrokeCollection newStrokes, StrokeCollection oldStrokes) { Debug.Assert(newStrokes != null, "Cannot set a null to InkPresenter"); // Remove the event handlers from the old stroke collection if ( null != oldStrokes ) { // Stop listening on events from the stroke collection. oldStrokes.StrokesChanged -= new StrokeCollectionChangedEventHandler(OnStrokesChanged); } // Start listening on events from the stroke collection. newStrokes.StrokesChanged += new StrokeCollectionChangedEventHandler(OnStrokesChanged); // Replace the renderer stroke collection. _renderer.Strokes = newStrokes; SetStrokeChangedHandlers(newStrokes, oldStrokes); } /// <summary> /// StrokeCollectionChanged event handler /// </summary> private void OnStrokesChanged(object sender, StrokeCollectionChangedEventArgs eventArgs) { System.Diagnostics.Debug.Assert(sender == this.Strokes); SetStrokeChangedHandlers(eventArgs.Added, eventArgs.Removed); OnStrokeChanged(this, EventArgs.Empty); } private void SetStrokeChangedHandlers(StrokeCollection addedStrokes, StrokeCollection removedStrokes) { Debug.Assert(addedStrokes != null, "The added StrokeCollection cannot be null."); int count, i; if ( removedStrokes != null ) { // Deal with removed strokes first count = removedStrokes.Count; for ( i = 0; i < count; i++ ) { StopListeningOnStrokeEvents(removedStrokes[i]); } } // Add new strokes count = addedStrokes.Count; for ( i = 0; i < count; i++ ) { StartListeningOnStrokeEvents(addedStrokes[i]); } } private void OnStrokeChanged(object sender, EventArgs e) { OnStrokeChanged(); } /// <summary> /// The method is called from Stroke setter, OnStrokesChanged, DrawingAttributesChanged and OnPacketsChanged /// </summary> private void OnStrokeChanged() { // Recalculate the bound of the StrokeCollection _cachedBounds = null; // Invalidate the current measure when any change happens on the stroke or strokes. InvalidateMeasure(); } /// <summary> /// Attaches event handlers to stroke events /// </summary> private void StartListeningOnStrokeEvents(Stroke stroke) { System.Diagnostics.Debug.Assert(stroke != null); stroke.Invalidated += new EventHandler(OnStrokeChanged); } /// <summary> /// Detaches event handlers from stroke /// </summary> private void StopListeningOnStrokeEvents(Stroke stroke) { System.Diagnostics.Debug.Assert(stroke != null); stroke.Invalidated -= new EventHandler(OnStrokeChanged); } /// <summary> /// Ensure the renderer root to be connected. The method is called from /// AttachVisuals /// DetachVisuals /// ArrangeOverride /// </summary> private void EnsureRootVisual() { if ( !_hasAddedRoot ) { // Ideally we should set _hasAddedRoot to true before calling AddVisualChild. // So that VisualDiagnostics.OnVisualChildChanged can get correct child index. // However it is not clear what can regress. For now we'll temporary set // _parentIndex property. We'll use _parentIndex. // Note that there is a comment in Visual.cs stating that _parentIndex should // be set to -1 in DEBUG builds when child is removed. We are not going to // honor it. There is no _parentIndex == -1 validation is performed anywhere. _renderer.RootVisual._parentIndex = 0; AddVisualChild(_renderer.RootVisual); _hasAddedRoot = true; } } #endregion Private Methods //------------------------------------------------------------------------------- // // Private Properties // //------------------------------------------------------------------------------- #region Private Properties private Rect StrokesBounds { get { if ( _cachedBounds == null ) { _cachedBounds = Strokes.GetBounds(); } return _cachedBounds.Value; } } #endregion Private Properties //------------------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------------------- #region Private Fields private Ink.Renderer _renderer; private Nullable<Rect> _cachedBounds = null; private bool _hasAddedRoot; // // HighContrast support // private InkPresenterHighContrastCallback _contrastCallback; private Size _constraintSize; #endregion Private Fields } }
// 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.PetstoreV2NoSync.Models { using Fixtures.PetstoreV2NoSync; using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; public partial class Pet { /// <summary> /// Initializes a new instance of the Pet class. /// </summary> public Pet() { } /// <summary> /// Initializes a new instance of the Pet class. /// </summary> /// <param name="status">pet status in the store. Possible values /// include: 'available', 'pending', 'sold'</param> public Pet(string name, IList<string> photoUrls, long? id = default(long?), Category category = default(Category), IList<Tag> tags = default(IList<Tag>), byte[] sByteProperty = default(byte[]), System.DateTime? birthday = default(System.DateTime?), IDictionary<string, Category> dictionary = default(IDictionary<string, Category>), string status = default(string)) { Id = id; Category = category; Name = name; PhotoUrls = photoUrls; Tags = tags; SByteProperty = sByteProperty; Birthday = birthday; Dictionary = dictionary; Status = status; } /// <summary> /// </summary> [JsonProperty(PropertyName = "id")] public long? Id { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "category")] public Category Category { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "photoUrls")] public IList<string> PhotoUrls { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "tags")] public IList<Tag> Tags { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "sByte")] public byte[] SByteProperty { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "birthday")] public System.DateTime? Birthday { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "dictionary")] public IDictionary<string, Category> Dictionary { get; set; } /// <summary> /// Gets or sets pet status in the store. Possible values include: /// 'available', 'pending', 'sold' /// </summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Name"); } if (PhotoUrls == null) { throw new ValidationException(ValidationRules.CannotBeNull, "PhotoUrls"); } } /// <summary> /// Serializes the object to an XML node /// </summary> internal XElement XmlSerialize(XElement result) { if( null != Id ) { result.Add(new XElement("id", Id) ); } if( null != Category ) { result.Add(Category.XmlSerialize(new XElement( "category" ))); } if( null != Name ) { result.Add(new XElement("name", Name) ); } if( null != PhotoUrls ) { var seq = new XElement("photoUrl"); foreach( var value in PhotoUrls ){ seq.Add(new XElement( "photoUrl", value ) ); } result.Add(seq); } if( null != Tags ) { var seq = new XElement("tag"); foreach( var value in Tags ){ seq.Add(value.XmlSerialize( new XElement( "tag") ) ); } result.Add(seq); } if( null != SByteProperty ) { result.Add(new XElement("sByte", SByteProperty) ); } if( null != Birthday ) { result.Add(new XElement("birthday", Birthday) ); } if( null != Dictionary ) { var dict = new XElement("dictionary"); foreach( var key in Dictionary.Keys ) { dict.Add(Dictionary[key].XmlSerialize(new XElement(key) ) ); } result.Add(dict); } if( null != Status ) { result.Add(new XElement("status", Status) ); } return result; } /// <summary> /// Deserializes an XML node to an instance of Pet /// </summary> internal static Pet XmlDeserialize(string payload) { // deserialize to xml and use the overload to do the work return XmlDeserialize( XElement.Parse( payload ) ); } internal static Pet XmlDeserialize(XElement payload) { var result = new Pet(); var deserializeId = XmlSerialization.ToDeserializer(e => (long?)e); long? resultId; if (deserializeId(payload, "id", out resultId)) { result.Id = resultId; } var deserializeCategory = XmlSerialization.ToDeserializer(e => Category.XmlDeserialize(e)); Category resultCategory; if (deserializeCategory(payload, "category", out resultCategory)) { result.Category = resultCategory; } var deserializeName = XmlSerialization.ToDeserializer(e => (string)e); string resultName; if (deserializeName(payload, "name", out resultName)) { result.Name = resultName; } var deserializePhotoUrls = XmlSerialization.CreateListXmlDeserializer(XmlSerialization.ToDeserializer(e => (string)e), "photoUrl"); IList<string> resultPhotoUrls; if (deserializePhotoUrls(payload, "photoUrl", out resultPhotoUrls)) { result.PhotoUrls = resultPhotoUrls; } var deserializeTags = XmlSerialization.CreateListXmlDeserializer(XmlSerialization.ToDeserializer(e => Tag.XmlDeserialize(e)), "tag"); IList<Tag> resultTags; if (deserializeTags(payload, "tag", out resultTags)) { result.Tags = resultTags; } var deserializeSByteProperty = XmlSerialization.ToDeserializer(e => System.Convert.FromBase64String(e.Value)); byte[] resultSByteProperty; if (deserializeSByteProperty(payload, "sByte", out resultSByteProperty)) { result.SByteProperty = resultSByteProperty; } var deserializeBirthday = XmlSerialization.ToDeserializer(e => (System.DateTime?)e); System.DateTime? resultBirthday; if (deserializeBirthday(payload, "birthday", out resultBirthday)) { result.Birthday = resultBirthday; } var deserializeDictionary = XmlSerialization.CreateDictionaryXmlDeserializer(XmlSerialization.ToDeserializer(e => Category.XmlDeserialize(e))); IDictionary<string, Category> resultDictionary; if (deserializeDictionary(payload, "dictionary", out resultDictionary)) { result.Dictionary = resultDictionary; } var deserializeStatus = XmlSerialization.ToDeserializer(e => (string)e); string resultStatus; if (deserializeStatus(payload, "status", out resultStatus)) { result.Status = resultStatus; } return result; } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Web; using MbUnit.Framework; using Moq; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Routing; using Subtext.Framework.Syndication; using Subtext.Framework.Web.HttpModules; using UnitTests.Subtext.Framework.Util; namespace UnitTests.Subtext.Framework.Syndication { /// <summary> /// Unit tests for the RSSWriter classes. /// </summary> [TestFixture] public class RssWriterTests : SyndicationTestBase { [RowTest] [Row("Subtext.Web", "", "http://localhost/Subtext.Web/images/RSS2Image.gif")] [Row("Subtext.Web", "blog", "http://localhost/Subtext.Web/images/RSS2Image.gif")] [Row("", "", "http://localhost/images/RSS2Image.gif")] [Row("", "blog", "http://localhost/images/RSS2Image.gif")] [RollBack] public void RssImageUrlConcatenatedProperly(string application, string subfolder, string expected) { UnitTestHelper.SetHttpContextWithBlogRequest("localhost", subfolder, application); var blogInfo = new Blog(); BlogRequest.Current.Blog = blogInfo; blogInfo.Host = "localhost"; blogInfo.Subfolder = subfolder; blogInfo.Title = "My Blog Is Better Than Yours"; blogInfo.Email = "Subtext@example.com"; blogInfo.RFC3229DeltaEncodingEnabled = true; HttpContext.Current.Items.Add("BlogInfo-", blogInfo); var subtextContext = new Mock<ISubtextContext>(); subtextContext.FakeSyndicationContext(blogInfo, "/", application, null); Mock<HttpContextBase> httpContext = Mock.Get(subtextContext.Object.RequestContext.HttpContext); httpContext.Setup(h => h.Request.ApplicationPath).Returns(application); var writer = new RssWriter(new StringWriter(), new List<Entry>(), DateTime.Now, false, subtextContext.Object); Uri rssImageUrl = writer.GetRssImage(); Assert.AreEqual(expected, rssImageUrl.ToString(), "not the expected url."); } /// <summary> /// Tests writing a simple RSS feed. /// </summary> [Test] [RollBack] public void RssWriterProducesValidFeed() { UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "", "Subtext.Web"); var blogInfo = new Blog(); BlogRequest.Current.Blog = blogInfo; blogInfo.Host = "localhost"; blogInfo.Title = "My Blog Is Better Than Yours"; blogInfo.Email = "Subtext@example.com"; blogInfo.RFC3229DeltaEncodingEnabled = true; blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId; blogInfo.ShowEmailAddressInRss = true; blogInfo.TrackbacksEnabled = true; HttpContext.Current.Items.Add("BlogInfo-", blogInfo); var entries = new List<Entry>(CreateSomeEntries()); entries[0].Categories.AddRange(new[] {"Category1", "Category2"}); entries[0].Email = "nobody@example.com"; entries[2].Categories.Add("Category 3"); var enc = new Enclosure(); enc.Url = "http://perseus.franklins.net/hanselminutes_0107.mp3"; enc.Title = "<Digital Photography Explained (for Geeks) with Aaron Hockley/>"; enc.Size = 26707573; enc.MimeType = "audio/mp3"; enc.AddToFeed = true; entries[2].Enclosure = enc; var enc1 = new Enclosure(); enc1.Url = "http://perseus.franklins.net/hanselminutes_0107.mp3"; enc1.Title = "<Digital Photography Explained (for Geeks) with Aaron Hockley/>"; enc1.Size = 26707573; enc1.MimeType = "audio/mp3"; enc1.AddToFeed = false; entries[3].Enclosure = enc1; var subtextContext = new Mock<ISubtextContext>(); subtextContext.FakeSyndicationContext(blogInfo, "/", "Subtext.Web", null); Mock<UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper); urlHelper.Setup(u => u.BlogUrl()).Returns("/Subtext.Web/"); urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns<Entry>( e => "/Subtext.Web/whatever/" + e.Id + ".aspx"); var writer = new RssWriter(new StringWriter(), entries, NullValue.NullDateTime, false, subtextContext.Object); string expected = @"<rss version=""2.0"" " + @"xmlns:dc=""http://purl.org/dc/elements/1.1/"" " + @"xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" " + @"xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" " + @"xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" " + @"xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" " + @"xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine + indent() + @"<channel>" + Environment.NewLine + indent(2) + @"<title>My Blog Is Better Than Yours</title>" + Environment.NewLine + indent(2) + @"<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(2) + @"<description />" + Environment.NewLine + indent(2) + @"<language>en-US</language>" + Environment.NewLine + indent(2) + @"<copyright>Subtext Weblog</copyright>" + Environment.NewLine + indent(2) + @"<managingEditor>Subtext@example.com</managingEditor>" + Environment.NewLine + indent(2) + @"<generator>{0}</generator>" + Environment.NewLine + indent(2) + @"<image>" + Environment.NewLine + indent(3) + @"<title>My Blog Is Better Than Yours</title>" + Environment.NewLine + indent(3) + @"<url>http://localhost/Subtext.Web/images/RSS2Image.gif</url>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(3) + @"<width>77</width>" + Environment.NewLine + indent(3) + @"<height>60</height>" + Environment.NewLine + indent(2) + @"</image>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>Title of 1001.</title>" + Environment.NewLine + indent(3) + @"<category>Category1</category>" + Environment.NewLine + indent(3) + @"<category>Category2</category>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever/1001.aspx</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1001&lt;img src=""http://localhost/Subtext.Web/aggbug/1001.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever/1001.aspx</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Sun, 23 Feb 1975 08:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever/1001.aspx#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1001.aspx</wfw:commentRss>" + Environment.NewLine + indent(3) + @"<trackback:ping>http://localhost/Subtext.Web/services/trackbacks/1001.aspx</trackback:ping>" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>Title of 1002.</title>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever/1002.aspx</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1002&lt;img src=""http://localhost/Subtext.Web/aggbug/1002.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever/1002.aspx</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Fri, 25 Jun 1976 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever/1002.aspx#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1002.aspx</wfw:commentRss>" + Environment.NewLine + indent(3) + @"<trackback:ping>http://localhost/Subtext.Web/services/trackbacks/1002.aspx</trackback:ping>" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>Title of 1003.</title>" + Environment.NewLine + indent(3) + @"<category>Category 3</category>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever/1003.aspx</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1003&lt;img src=""http://localhost/Subtext.Web/aggbug/1003.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever/1003.aspx</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Tue, 16 Oct 1979 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever/1003.aspx#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1003.aspx</wfw:commentRss>" + Environment.NewLine + indent(3) + @"<trackback:ping>http://localhost/Subtext.Web/services/trackbacks/1003.aspx</trackback:ping>" + Environment.NewLine + indent(3) + @"<enclosure url=""http://perseus.franklins.net/hanselminutes_0107.mp3"" length=""26707573"" type=""audio/mp3"" />" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>Title of 1004.</title>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever/1004.aspx</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1004&lt;img src=""http://localhost/Subtext.Web/aggbug/1004.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever/1004.aspx</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Mon, 14 Jul 2003 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever/1004.aspx#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1004.aspx</wfw:commentRss>" + Environment.NewLine + indent(3) + @"<trackback:ping>http://localhost/Subtext.Web/services/trackbacks/1004.aspx</trackback:ping>" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent() + @"</channel>" + Environment.NewLine + @"</rss>"; expected = string.Format(expected, VersionInfo.VersionDisplayText); UnitTestHelper.AssertStringsEqualCharacterByCharacter(expected, writer.Xml); } /// <summary> /// Makes sure the RSS Writer can write the delta of a feed based /// on the RFC3229 with feeds /// <see href="http://bobwyman.pubsub.com/main/2004/09/using_rfc3229_w.html"/>. /// </summary> [Test] [RollBack] public void RssWriterHandlesRFC3229DeltaEncoding() { UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "", "Subtext.Web"); var blogInfo = new Blog(); BlogRequest.Current.Blog = blogInfo; blogInfo.Host = "localhost"; blogInfo.Subfolder = ""; blogInfo.Email = "Subtext@example.com"; blogInfo.RFC3229DeltaEncodingEnabled = true; blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId; HttpContext.Current.Items.Add("BlogInfo-", blogInfo); var entries = new List<Entry>(CreateSomeEntriesDescending()); var subtextContext = new Mock<ISubtextContext>(); subtextContext.FakeSyndicationContext(blogInfo, "/", "Subtext.Web", null); Mock<UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper); urlHelper.Setup(u => u.BlogUrl()).Returns("/Subtext.Web/"); urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/Subtext.Web/whatever"); // Tell the write we already received 1002 published 6/25/1976. var writer = new RssWriter(new StringWriter(), entries, DateTime.ParseExact("06/25/1976", "MM/dd/yyyy", CultureInfo.InvariantCulture), true, subtextContext.Object); // We only expect 1003 and 1004 string expected = @"<rss version=""2.0"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine + indent() + "<channel>" + Environment.NewLine + indent(2) + "<title />" + Environment.NewLine + indent(2) + "<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(2) + "<description />" + Environment.NewLine + indent(2) + "<language>en-US</language>" + Environment.NewLine + indent(2) + "<copyright>Subtext Weblog</copyright>" + Environment.NewLine + indent(2) + "<generator>{0}</generator>" + Environment.NewLine + indent(2) + "<image>" + Environment.NewLine + indent(3) + "<title />" + Environment.NewLine + indent(3) + "<url>http://localhost/Subtext.Web/images/RSS2Image.gif</url>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(3) + "<width>77</width>" + Environment.NewLine + indent(3) + "<height>60</height>" + Environment.NewLine + indent(2) + "</image>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>Title of 1004.</title>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1004&lt;img src=""http://localhost/Subtext.Web/aggbug/1004.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Mon, 14 Jul 2003 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1004.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + "<title>Title of 1003.</title>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/whatever</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1003&lt;img src=""http://localhost/Subtext.Web/aggbug/1003.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Tue, 16 Oct 1979 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1003.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + "</item>" + Environment.NewLine + indent() + "</channel>" + Environment.NewLine + "</rss>"; expected = string.Format(expected, VersionInfo.VersionDisplayText); Assert.AreEqual(expected, writer.Xml); Assert.AreEqual(DateTime.ParseExact("06/25/1976", "MM/dd/yyyy", CultureInfo.InvariantCulture), writer.DateLastViewedFeedItemPublished, "The Item ID Last Viewed (according to If-None-Since is wrong."); Assert.AreEqual(DateTime.ParseExact("07/14/2003", "MM/dd/yyyy", CultureInfo.InvariantCulture), writer.LatestPublishDate, "The Latest Feed Item ID sent to the client is wrong."); } /// <summary> /// Tests writing a simple RSS feed. /// </summary> [Test] [RollBack] public void RssWriterSendsWholeFeedWhenRFC3229Disabled() { UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "", "Subtext.Web"); var blogInfo = new Blog(); BlogRequest.Current.Blog = blogInfo; blogInfo.Host = "localhost"; blogInfo.Subfolder = ""; blogInfo.Email = "Subtext@example.com"; blogInfo.RFC3229DeltaEncodingEnabled = false; blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId; HttpContext.Current.Items.Add("BlogInfo-", blogInfo); var entries = new List<Entry>(CreateSomeEntriesDescending()); var subtextContext = new Mock<ISubtextContext>(); subtextContext.FakeSyndicationContext(blogInfo, "/Subtext.Web/", "Subtext.Web", null); Mock<UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper); urlHelper.Setup(u => u.BlogUrl()).Returns("/Subtext.Web/"); urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns<Entry>(e => "/Subtext.Web/whatever/" + e.Id); var writer = new RssWriter(new StringWriter(), entries, DateTime.ParseExact("07/14/2003", "MM/dd/yyyy", CultureInfo.InvariantCulture), false, subtextContext.Object); string expected = @"<rss version=""2.0"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine + indent() + "<channel>" + Environment.NewLine + indent(2) + "<title />" + Environment.NewLine + indent(2) + "<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(2) + "<description />" + Environment.NewLine + indent(2) + "<language>en-US</language>" + Environment.NewLine + indent(2) + "<copyright>Subtext Weblog</copyright>" + Environment.NewLine + indent(2) + "<generator>{0}</generator>" + Environment.NewLine + indent(2) + "<image>" + Environment.NewLine + indent(3) + "<title />" + Environment.NewLine + indent(3) + "<url>http://localhost/Subtext.Web/images/RSS2Image.gif</url>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(3) + "<width>77</width>" + Environment.NewLine + indent(3) + "<height>60</height>" + Environment.NewLine + indent(2) + "</image>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + "<title>Title of 1004.</title>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/whatever/1004</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1004&lt;img src=""http://localhost/Subtext.Web/aggbug/1004.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + "<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + "<guid>http://localhost/Subtext.Web/whatever/1004</guid>" + Environment.NewLine + indent(3) + "<pubDate>Mon, 14 Jul 2003 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + "<comments>http://localhost/Subtext.Web/whatever/1004#feedback</comments>" + Environment.NewLine + indent(3) + "<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1004.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + "</item>" + Environment.NewLine + indent(2) + "<item>" + Environment.NewLine + indent(3) + "<title>Title of 1003.</title>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever/1003</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1003&lt;img src=""http://localhost/Subtext.Web/aggbug/1003.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + "<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + "<guid>http://localhost/Subtext.Web/whatever/1003</guid>" + Environment.NewLine + indent(3) + "<pubDate>Tue, 16 Oct 1979 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + "<comments>http://localhost/Subtext.Web/whatever/1003#feedback</comments>" + Environment.NewLine + indent(3) + "<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1003.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + "</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + "<title>Title of 1002.</title>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/whatever/1002</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1002&lt;img src=""http://localhost/Subtext.Web/aggbug/1002.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + "<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + "<guid>http://localhost/Subtext.Web/whatever/1002</guid>" + Environment.NewLine + indent(3) + "<pubDate>Fri, 25 Jun 1976 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + "<comments>http://localhost/Subtext.Web/whatever/1002#feedback</comments>" + Environment.NewLine + indent(3) + "<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1002.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + "</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + "<title>Title of 1001.</title>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/whatever/1001</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1001&lt;img src=""http://localhost/Subtext.Web/aggbug/1001.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + "<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + "<guid>http://localhost/Subtext.Web/whatever/1001</guid>" + Environment.NewLine + indent(3) + "<pubDate>Sun, 23 Feb 1975 08:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + "<comments>http://localhost/Subtext.Web/whatever/1001#feedback</comments>" + Environment.NewLine + indent(3) + "<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1001.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + "</item>" + Environment.NewLine + indent() + "</channel>" + Environment.NewLine + "</rss>"; expected = string.Format(expected, VersionInfo.VersionDisplayText); UnitTestHelper.AssertStringsEqualCharacterByCharacter(expected, writer.Xml); } Entry[] CreateSomeEntries() { return new[] { CreateEntry(1001, "Title of 1001.", "Body of 1001", DateTime.ParseExact("01/23/1975", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1002, "Title of 1002.", "Body of 1002", DateTime.ParseExact("05/25/1976", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1003, "Title of 1003.", "Body of 1003", DateTime.ParseExact("09/16/1979", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1004, "Title of 1004.", "Body of 1004", DateTime.ParseExact("06/14/2003", "MM/dd/yyyy", CultureInfo.InvariantCulture)) }; } Entry[] CreateSomeEntriesDescending() { return new[] { CreateEntry(1004, "Title of 1004.", "Body of 1004", DateTime.ParseExact("06/14/2003", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1003, "Title of 1003.", "Body of 1003", DateTime.ParseExact("09/16/1979", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1002, "Title of 1002.", "Body of 1002", DateTime.ParseExact("05/25/1976", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1001, "Title of 1001.", "Body of 1001", DateTime.ParseExact("01/23/1975", "MM/dd/yyyy", CultureInfo.InvariantCulture)) }; } static Entry CreateEntry(int id, string title, string body, DateTime dateCreated) { var entry = new Entry(PostType.BlogPost) { DateCreated = dateCreated, Title = title, Author = "Phil Haack", Body = body, Id = id }; entry.DateModified = entry.DateCreated; entry.DateSyndicated = entry.DateCreated.AddMonths(1); return entry; } /// <summary> /// Sets the up test fixture. This is called once for /// this test fixture before all the tests run. /// </summary> [TestFixtureSetUp] public void SetUpTestFixture() { //Confirm app settings UnitTestHelper.AssertAppSettings(); } [SetUp] public void SetUp() { } [TearDown] public void TearDown() { } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// // <OWNER>[....]</OWNER> // <OWNER>[....]</OWNER> // namespace System.Reflection { using System; using System.Diagnostics.SymbolStore; using System.Runtime.Remoting; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.IO; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum PortableExecutableKinds { NotAPortableExecutableImage = 0x0, ILOnly = 0x1, Required32Bit = 0x2, PE32Plus = 0x4, Unmanaged32Bit = 0x8, [ComVisible(false)] Preferred32Bit = 0x10, } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum ImageFileMachine { I386 = 0x014c, IA64 = 0x0200, AMD64 = 0x8664, ARM = 0x01c4, } [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_Module))] [System.Runtime.InteropServices.ComVisible(true)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)] #pragma warning restore 618 public abstract class Module : _Module, ISerializable, ICustomAttributeProvider { #region Static Constructor static Module() { __Filters _fltObj; _fltObj = new __Filters(); FilterTypeName = new TypeFilter(_fltObj.FilterTypeName); FilterTypeNameIgnoreCase = new TypeFilter(_fltObj.FilterTypeNameIgnoreCase); } #endregion #region Constructor protected Module() { } #endregion #region Public Statics public static readonly TypeFilter FilterTypeName; public static readonly TypeFilter FilterTypeNameIgnoreCase; #if !FEATURE_CORECLR public static bool operator ==(Module left, Module right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeModule || right is RuntimeModule) { return false; } return left.Equals(right); } public static bool operator !=(Module left, Module right) { return !(left == right); } #endif // !FEATURE_CORECLR #if FEATURE_NETCORE || !FEATURE_CORECLR public override bool Equals(object o) { return base.Equals(o); } public override int GetHashCode() { return base.GetHashCode(); } #endif //FEATURE_NETCORE || !FEATURE_CORECLR #endregion #region Literals private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; #endregion #region object overrides public override String ToString() { return ScopeName; } #endregion public virtual IEnumerable<CustomAttributeData> CustomAttributes { get { return GetCustomAttributesData(); } } #region ICustomAttributeProvider Members public virtual Object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public virtual Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public virtual bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } public virtual IList<CustomAttributeData> GetCustomAttributesData() { throw new NotImplementedException(); } #endregion #region public instances members public MethodBase ResolveMethod(int metadataToken) { return ResolveMethod(metadataToken, null, null); } public virtual MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); throw new NotImplementedException(); } public FieldInfo ResolveField(int metadataToken) { return ResolveField(metadataToken, null, null); } public virtual FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); throw new NotImplementedException(); } public Type ResolveType(int metadataToken) { return ResolveType(metadataToken, null, null); } public virtual Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); throw new NotImplementedException(); } public MemberInfo ResolveMember(int metadataToken) { return ResolveMember(metadataToken, null, null); } public virtual MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments); throw new NotImplementedException(); } public virtual byte[] ResolveSignature(int metadataToken) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveSignature(metadataToken); throw new NotImplementedException(); } public virtual string ResolveString(int metadataToken) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveString(metadataToken); throw new NotImplementedException(); } public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) rtModule.GetPEKind(out peKind, out machine); throw new NotImplementedException(); } public virtual int MDStreamVersion { get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.MDStreamVersion; throw new NotImplementedException(); } } [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } [System.Runtime.InteropServices.ComVisible(true)] public virtual Type GetType(String className, bool ignoreCase) { return GetType(className, false, ignoreCase); } [System.Runtime.InteropServices.ComVisible(true)] public virtual Type GetType(String className) { return GetType(className, false, false); } [System.Runtime.InteropServices.ComVisible(true)] public virtual Type GetType(String className, bool throwOnError, bool ignoreCase) { throw new NotImplementedException(); } public virtual String FullyQualifiedName { #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { throw new NotImplementedException(); } } public virtual Type[] FindTypes(TypeFilter filter,Object filterCriteria) { Type[] c = GetTypes(); int cnt = 0; for (int i = 0;i<c.Length;i++) { if (filter!=null && !filter(c[i],filterCriteria)) c[i] = null; else cnt++; } if (cnt == c.Length) return c; Type[] ret = new Type[cnt]; cnt=0; for (int i=0;i<c.Length;i++) { if (c[i] != null) ret[cnt++] = c[i]; } return ret; } public virtual Type[] GetTypes() { throw new NotImplementedException(); } public virtual Guid ModuleVersionId { get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ModuleVersionId; throw new NotImplementedException(); } } public virtual int MetadataToken { get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.MetadataToken; throw new NotImplementedException(); } } public virtual bool IsResource() { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.IsResource(); throw new NotImplementedException(); } public FieldInfo[] GetFields() { return GetFields(Module.DefaultLookup); } public virtual FieldInfo[] GetFields(BindingFlags bindingFlags) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.GetFields(bindingFlags); throw new NotImplementedException(); } public FieldInfo GetField(String name) { return GetField(name,Module.DefaultLookup); } public virtual FieldInfo GetField(String name, BindingFlags bindingAttr) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.GetField(name, bindingAttr); throw new NotImplementedException(); } public MethodInfo[] GetMethods() { return GetMethods(Module.DefaultLookup); } public virtual MethodInfo[] GetMethods(BindingFlags bindingFlags) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.GetMethods(bindingFlags); throw new NotImplementedException(); } public MethodInfo GetMethod( String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { if (name == null) throw new ArgumentNullException("name"); if (types == null) throw new ArgumentNullException("types"); Contract.EndContractBlock(); for (int i = 0; i < types.Length; i++) { if (types[i] == null) throw new ArgumentNullException("types"); } return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers); } public MethodInfo GetMethod(String name, Type[] types) { if (name == null) throw new ArgumentNullException("name"); if (types == null) throw new ArgumentNullException("types"); Contract.EndContractBlock(); for (int i = 0; i < types.Length; i++) { if (types[i] == null) throw new ArgumentNullException("types"); } return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, types, null); } public MethodInfo GetMethod(String name) { if (name == null) throw new ArgumentNullException("name"); Contract.EndContractBlock(); return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, null, null); } protected virtual MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } public virtual String ScopeName { get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ScopeName; throw new NotImplementedException(); } } public virtual String Name { [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.Name; throw new NotImplementedException(); } } public virtual Assembly Assembly { [Pure] get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.Assembly; throw new NotImplementedException(); } } // This API never fails, it will return an empty handle for non-runtime handles and // a valid handle for reflection only modules. public ModuleHandle ModuleHandle { get { return GetModuleHandle(); } } // Used to provide implementation and overriding point for ModuleHandle. // To get a module handle inside mscorlib, use GetNativeHandle instead. internal virtual ModuleHandle GetModuleHandle() { return ModuleHandle.EmptyHandle; } #if FEATURE_X509 && FEATURE_CAS_POLICY public virtual System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() { throw new NotImplementedException(); } #endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion void _Module.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _Module.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _Module.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _Module.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } } #if !FEATURE_CORECLR [System.Runtime.ForceTokenStabilization] #endif //!FEATURE_CORECLR [Serializable] internal class RuntimeModule : Module { internal RuntimeModule() { throw new NotSupportedException(); } #region FCalls [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type); [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [DllImport(JitHelpers.QCall)] [SuppressUnmanagedCodeSecurity] private static extern bool nIsTransientInternal(RuntimeModule module); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static RuntimeType[] GetTypes(RuntimeModule module); [System.Security.SecuritySafeCritical] // auto-generated internal RuntimeType[] GetDefinedTypes() { return GetTypes(GetNativeHandle()); } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static bool IsResource(RuntimeModule module); #if FEATURE_X509 && FEATURE_CAS_POLICY [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static private extern void GetSignerCertificate(RuntimeModule module, ObjectHandleOnStack retData); #endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion #region Module overrides private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments) { if (genericArguments == null) return null; int size = genericArguments.Length; RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size]; for (int i = 0; i < size; i++) { Type typeArg = genericArguments[i]; if (typeArg == null) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); typeArg = typeArg.UnderlyingSystemType; if (typeArg == null) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); if (!(typeArg is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); typeHandleArgs[i] = typeArg.GetTypeHandleInternal(); } return typeHandleArgs; } [System.Security.SecuritySafeCritical] // auto-generated public override byte[] ResolveSignature(int metadataToken) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", Environment.GetResourceString("Argument_InvalidToken", tk, this)); if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidToken", tk, this), "metadataToken"); ConstArray signature; if (tk.IsMemberRef) signature = MetadataImport.GetMemberRefProps(metadataToken); else signature = MetadataImport.GetSignatureFromToken(metadataToken); byte[] sig = new byte[signature.Length]; for (int i = 0; i < signature.Length; i++) sig[i] = signature[i]; return sig; } [System.Security.SecuritySafeCritical] // auto-generated public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", Environment.GetResourceString("Argument_InvalidToken", tk, this)); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { if (!tk.IsMethodDef && !tk.IsMethodSpec) { if (!tk.IsMemberRef) throw new ArgumentException("metadataToken", Environment.GetResourceString("Argument_ResolveMethod", tk, this)); unsafe { ConstArray sig = MetadataImport.GetMemberRefProps(tk); if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) throw new ArgumentException("metadataToken", Environment.GetResourceString("Argument_ResolveMethod", tk, this)); } } IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs); Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle); if (declaringType.IsGenericType || declaringType.IsArray) { MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk)); if (tk.IsMethodSpec) tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType)); declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); } return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle); } catch (BadImageFormatException e) { throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); } } [System.Security.SecurityCritical] // auto-generated private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef) throw new ArgumentOutOfRangeException("metadataToken", String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this))); int tkDeclaringType; string fieldName; fieldName = MetadataImport.GetName(tk).ToString(); tkDeclaringType = MetadataImport.GetParentToken(tk); Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); declaringType.GetFields(); try { return declaringType.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); } catch { throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), "metadataToken"); } } [System.Security.SecuritySafeCritical] // auto-generated public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", Environment.GetResourceString("Argument_InvalidToken", tk, this)); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { IRuntimeFieldInfo fieldHandle = null; if (!tk.IsFieldDef) { if (!tk.IsMemberRef) throw new ArgumentException("metadataToken", Environment.GetResourceString("Argument_ResolveField", tk, this)); unsafe { ConstArray sig = MetadataImport.GetMemberRefProps(tk); if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field) throw new ArgumentException("metadataToken", Environment.GetResourceString("Argument_ResolveField", tk, this)); } fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs); } fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs); RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value); if (declaringType.IsGenericType || declaringType.IsArray) { int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken); declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); } return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle); } catch(MissingFieldException) { return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments); } catch (BadImageFormatException e) { throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); } } [System.Security.SecuritySafeCritical] // auto-generated public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (tk.IsGlobalTypeDefToken) throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), "metadataToken"); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", Environment.GetResourceString("Argument_InvalidToken", tk, this)); if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef) throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), "metadataToken"); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { Type t = GetModuleHandle().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType(); if (t == null) throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), "metadataToken"); return t; } catch (BadImageFormatException e) { throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); } } [System.Security.SecuritySafeCritical] // auto-generated public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (tk.IsProperty) throw new ArgumentException(Environment.GetResourceString("InvalidOperation_PropertyInfoNotAvailable")); if (tk.IsEvent) throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EventInfoNotAvailable")); if (tk.IsMethodSpec || tk.IsMethodDef) return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); if (tk.IsFieldDef) return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec) return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); if (tk.IsMemberRef) { if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", Environment.GetResourceString("Argument_InvalidToken", tk, this)); ConstArray sig = MetadataImport.GetMemberRefProps(tk); unsafe { if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) { return ResolveField(tk, genericTypeArguments, genericMethodArguments); } else { return ResolveMethod(tk, genericTypeArguments, genericMethodArguments); } } } throw new ArgumentException("metadataToken", Environment.GetResourceString("Argument_ResolveMember", tk, this)); } [System.Security.SecuritySafeCritical] // auto-generated public override string ResolveString(int metadataToken) { MetadataToken tk = new MetadataToken(metadataToken); if (!tk.IsString) throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString())); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this))); string str = MetadataImport.GetUserString(metadataToken); if (str == null) throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString())); return str; } public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine); } public override int MDStreamVersion { [System.Security.SecuritySafeCritical] // auto-generated get { return ModuleHandle.GetMDStreamVersion(GetNativeHandle()); } } #endregion #region Data Members #pragma warning disable 169 // If you add any data members, you need to update the native declaration ReflectModuleBaseObject. private RuntimeType m_runtimeType; private RuntimeAssembly m_runtimeAssembly; private IntPtr m_pRefClass; #if !FEATURE_CORECLR [System.Runtime.ForceTokenStabilization] #endif //!FEATURE_CORECLR private IntPtr m_pData; private IntPtr m_pGlobals; private IntPtr m_pFields; #pragma warning restore 169 #endregion #region Protected Virtuals protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); } internal MethodInfo GetMethodInternal(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { if (RuntimeType == null) return null; if (types == null) { return RuntimeType.GetMethod(name, bindingAttr); } else { return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } } #endregion #region Internal Members internal RuntimeType RuntimeType { get { if (m_runtimeType == null) m_runtimeType = ModuleHandle.GetModuleType(GetNativeHandle()); return m_runtimeType; } } [System.Security.SecuritySafeCritical] internal bool IsTransientInternal() { return RuntimeModule.nIsTransientInternal(this.GetNativeHandle()); } internal MetadataImport MetadataImport { [System.Security.SecurityCritical] // auto-generated get { unsafe { return ModuleHandle.GetMetadataImport(GetNativeHandle()); } } } #endregion #region ICustomAttributeProvider Members public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region Public Virtuals [System.Security.SecurityCritical] // auto-generated_required public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } Contract.EndContractBlock(); UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly()); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public override Type GetType(String className, bool throwOnError, bool ignoreCase) { // throw on null strings regardless of the value of "throwOnError" if (className == null) throw new ArgumentNullException("className"); RuntimeType retType = null; GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType)); return retType; } [System.Security.SecurityCritical] // auto-generated internal string GetFullyQualifiedName() { String fullyQualifiedName = null; GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName)); return fullyQualifiedName; } public override String FullyQualifiedName { #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { String fullyQualifiedName = GetFullyQualifiedName(); if (fullyQualifiedName != null) { bool checkPermission = true; try { Path.GetFullPathInternal(fullyQualifiedName); } catch(ArgumentException) { checkPermission = false; } if (checkPermission) { new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullyQualifiedName ).Demand(); } } return fullyQualifiedName; } } [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetTypes() { return GetTypes(GetNativeHandle()); } #endregion #region Public Members public override Guid ModuleVersionId { [System.Security.SecuritySafeCritical] // auto-generated get { unsafe { Guid mvid; MetadataImport.GetScopeProps(out mvid); return mvid; } } } public override int MetadataToken { [System.Security.SecuritySafeCritical] // auto-generated get { return ModuleHandle.GetToken(GetNativeHandle()); } } public override bool IsResource() { return IsResource(GetNativeHandle()); } public override FieldInfo[] GetFields(BindingFlags bindingFlags) { if (RuntimeType == null) return new FieldInfo[0]; return RuntimeType.GetFields(bindingFlags); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { if (name == null) throw new ArgumentNullException("name"); if (RuntimeType == null) return null; return RuntimeType.GetField(name, bindingAttr); } public override MethodInfo[] GetMethods(BindingFlags bindingFlags) { if (RuntimeType == null) return new MethodInfo[0]; return RuntimeType.GetMethods(bindingFlags); } public override String ScopeName { [System.Security.SecuritySafeCritical] // auto-generated get { string scopeName = null; GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName)); return scopeName; } } public override String Name { [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] [System.Security.SecuritySafeCritical] // auto-generated get { String s = GetFullyQualifiedName(); #if !FEATURE_PAL int i = s.LastIndexOf('\\'); #else int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar); #endif if (i == -1) return s; return new String(s.ToCharArray(), i + 1, s.Length - i - 1); } } public override Assembly Assembly { [Pure] get { return GetRuntimeAssembly(); } } internal RuntimeAssembly GetRuntimeAssembly() { return m_runtimeAssembly; } internal override ModuleHandle GetModuleHandle() { return new ModuleHandle(this); } internal RuntimeModule GetNativeHandle() { return this; } #if FEATURE_X509 && FEATURE_CAS_POLICY [System.Security.SecuritySafeCritical] // auto-generated public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() { byte[] data = null; GetSignerCertificate(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref data)); return (data != null) ? new System.Security.Cryptography.X509Certificates.X509Certificate(data) : null; } #endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Microsoft.DotNet.InternalAbstractions; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.MultilevelSDKLookup { public class GivenThatICareAboutMultilevelSDKLookup : IDisposable { private static IDictionary<string, string> s_DefaultEnvironment = new Dictionary<string, string>() { {"COREHOST_TRACE", "1" }, // The SDK being used may be crossgen'd for a different architecture than we are building for. // Turn off ready to run, so an x64 crossgen'd SDK can be loaded in an x86 process. {"COMPlus_ReadyToRun", "0" }, }; private RepoDirectoriesProvider RepoDirectories; private TestProjectFixture PreviouslyBuiltAndRestoredPortableTestProjectFixture; private string _currentWorkingDir; private string _userDir; private string _exeDir; private string _regDir; private string _cwdSdkBaseDir; private string _userSdkBaseDir; private string _exeSdkBaseDir; private string _regSdkBaseDir; private string _cwdSelectedMessage; private string _userSelectedMessage; private string _exeSelectedMessage; private string _regSelectedMessage; private string _sdkDir; private string _multilevelDir; private const string _dotnetSdkDllMessageTerminator = "dotnet.dll]"; public GivenThatICareAboutMultilevelSDKLookup() { // From the artifacts dir, it's possible to find where the sharedFrameworkPublish folder is. We need // to locate it because we'll copy its contents into other folders string artifactsDir = Environment.GetEnvironmentVariable("TEST_ARTIFACTS"); string builtDotnet = Path.Combine(artifactsDir, "sharedFrameworkPublish"); // The dotnetMultilevelSDKLookup dir will contain some folders and files that will be // necessary to perform the tests string baseMultilevelDir = Path.Combine(artifactsDir, "dotnetMultilevelSDKLookup"); _multilevelDir = SharedFramework.CalculateUniqueTestDirectory(baseMultilevelDir); // The three tested locations will be the cwd, the user folder and the exe dir. cwd and user are no longer supported. // All dirs will be placed inside the multilevel folder _currentWorkingDir = Path.Combine(_multilevelDir, "cwd"); _userDir = Path.Combine(_multilevelDir, "user"); _exeDir = Path.Combine(_multilevelDir, "exe"); _regDir = Path.Combine(_multilevelDir, "reg"); // It's necessary to copy the entire publish folder to the exe dir because // we'll need to build from it. The CopyDirectory method automatically creates the dest dir SharedFramework.CopyDirectory(builtDotnet, _exeDir); RepoDirectories = new RepoDirectoriesProvider(builtDotnet: _exeDir); // SdkBaseDirs contain all available version folders _cwdSdkBaseDir = Path.Combine(_currentWorkingDir, "sdk"); _userSdkBaseDir = Path.Combine(_userDir, ".dotnet", RepoDirectories.BuildArchitecture, "sdk"); _exeSdkBaseDir = Path.Combine(_exeDir, "sdk"); _regSdkBaseDir = Path.Combine(_regDir, "sdk"); // Create directories Directory.CreateDirectory(_cwdSdkBaseDir); Directory.CreateDirectory(_userSdkBaseDir); Directory.CreateDirectory(_exeSdkBaseDir); Directory.CreateDirectory(_regSdkBaseDir); // Restore and build PortableApp from exe dir PreviouslyBuiltAndRestoredPortableTestProjectFixture = new TestProjectFixture("PortableApp", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .BuildProject(); var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture; // Set a dummy framework version (9999.0.0) in the exe sharedFx location. We will // always pick the framework from this to avoid interference with the sharedFxLookup string exeDirDummyFxVersion = Path.Combine(_exeDir, "shared", "Microsoft.NETCore.App", "9999.0.0"); string builtSharedFxDir = fixture.BuiltDotnet.GreatestVersionSharedFxPath; SharedFramework.CopyDirectory(builtSharedFxDir, exeDirDummyFxVersion); // The actual SDK version can be obtained from the built fixture. We'll use it to // locate the sdkDir from which we can get the files contained in the version folder string sdkBaseDir = Path.Combine(fixture.SdkDotnet.BinPath, "sdk"); var sdkVersionDirs = Directory.EnumerateDirectories(sdkBaseDir) .Select(p => Path.GetFileName(p)); string greatestVersionSdk = sdkVersionDirs .Where(p => !string.Equals(p, "NuGetFallbackFolder", StringComparison.OrdinalIgnoreCase)) .OrderByDescending(p => p.ToLower()) .First(); _sdkDir = Path.Combine(sdkBaseDir, greatestVersionSdk); // Trace messages used to identify from which folder the SDK was picked _cwdSelectedMessage = $"Using dotnet SDK dll=[{_cwdSdkBaseDir}"; _userSelectedMessage = $"Using dotnet SDK dll=[{_userSdkBaseDir}"; _exeSelectedMessage = $"Using dotnet SDK dll=[{_exeSdkBaseDir}"; _regSelectedMessage = $"Using dotnet SDK dll=[{_regSdkBaseDir}"; } public void Dispose() { PreviouslyBuiltAndRestoredPortableTestProjectFixture.Dispose(); if (!TestProject.PreserveTestRuns()) { Directory.Delete(_multilevelDir, true); } } [Fact] public void SdkMultilevelLookup_Global_Json_Single_Digit_Patch_Rollup() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Multi-level lookup is only supported on Windows. return; } var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture .Copy(); var dotnet = fixture.BuiltDotnet; // Set specified SDK version = 9999.3.4-global-dummy SetGlobalJsonVersion("SingleDigit-global.json"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: empty // Reg: empty // Expected: no compatible version and a specific error messages dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("A compatible installed dotnet SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.4.1", "9999.3.4-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy // Reg: empty // Expected: no compatible version and a specific error message dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("A compatible installed dotnet SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.3"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy // Reg: 9999.3.3 // Expected: no compatible version and a specific error message dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("A compatible installed dotnet SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4 // Reg: 9999.3.3 // Expected: 9999.3.4 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.5-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4 // Reg: 9999.3.3, 9999.3.5-dummy // Expected: 9999.3.5-dummy from reg dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.600"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4, 9999.3.600 // Reg: 9999.3.3, 9999.3.5-dummy // Expected: 9999.3.5-dummy from reg dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4-global-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4, 9999.3.600, 9999.3.4-global-dummy // Reg: 9999.3.3, 9999.3.5-dummy // Expected: 9999.3.4-global-dummy from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions dotnet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("9999.3.4-dummy") .And .HaveStdOutContaining("9999.3.4-global-dummy") .And .HaveStdOutContaining("9999.4.1") .And .HaveStdOutContaining("9999.3.3") .And .HaveStdOutContaining("9999.3.4") .And .HaveStdOutContaining("9999.3.600") .And .HaveStdOutContaining("9999.3.5-dummy"); } [Fact] public void SdkMultilevelLookup_Global_Json_Two_Part_Patch_Rollup() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Multi-level lookup is only supported on Windows. return; } var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture .Copy(); var dotnet = fixture.BuiltDotnet; // Set specified SDK version = 9999.3.304-global-dummy SetGlobalJsonVersion("TwoPart-global.json"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: empty // Reg: empty // Expected: no compatible version and a specific error messages dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("A compatible installed dotnet SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.57", "9999.3.4-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: empty // Reg: 9999.3.57, 9999.3.4-dummy // Expected: no compatible version and a specific error message dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("A compatible installed dotnet SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.300", "9999.7.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: 9999.3.300, 9999.7.304-global-dummy // Reg: 9999.3.57, 9999.3.4-dummy // Expected: no compatible version and a specific error message dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("A compatible installed dotnet SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.304"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: 9999.3.300, 9999.7.304-global-dummy // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304 // Expected: 9999.3.304 from reg dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.304", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.399", "9999.3.399-dummy", "9999.3.400"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: 9999.3.300, 9999.7.304-global-dummy, 9999.3.399, 9999.3.399-dummy, 9999.3.400 // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304 // Expected: 9999.3.399 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.2400, 9999.3.3004"); AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.2400, 9999.3.3004"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: 9999.3.300, 9999.7.304-global-dummy, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004 // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304, 9999.3.2400, 9999.3.3004 // Expected: 9999.3.399 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: 9999.3.300, 9999.7.304-global-dummy, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004 // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304, 9999.3.2400, 9999.3.3004, 9999.3.304-global-dummy // Expected: 9999.3.304-global-dummy from reg dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.304-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions dotnet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("9999.3.57") .And .HaveStdOutContaining("9999.3.4-dummy") .And .HaveStdOutContaining("9999.3.300") .And .HaveStdOutContaining("9999.7.304-global-dummy") .And .HaveStdOutContaining("9999.3.399") .And .HaveStdOutContaining("9999.3.399-dummy") .And .HaveStdOutContaining("9999.3.400") .And .HaveStdOutContaining("9999.3.2400") .And .HaveStdOutContaining("9999.3.3004") .And .HaveStdOutContaining("9999.3.304") .And .HaveStdOutContaining("9999.3.304-global-dummy"); } [Fact] public void SdkMultilevelLookup_Precedential_Order() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Multi-level lookup is only supported on Windows. return; } var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture .Copy(); var dotnet = fixture.BuiltDotnet; // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.4"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: empty // Reg: 9999.0.4 // Expected: 9999.0.4 from reg dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.4"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: 9999.0.4 // Reg: 9999.0.4 // Expected: 9999.0.4 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); } [Fact] public void SdkMultilevelLookup_Must_Pick_The_Highest_Semantic_Version() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Multi-level lookup is only supported on Windows. return; } var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture .Copy(); var dotnet = fixture.BuiltDotnet; // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.0", "9999.0.3-dummy"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: empty // Reg: 9999.0.0, 9999.0.3-dummy // Expected: 9999.0.3-dummy from reg dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.3-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.3"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: 9999.0.3 // Reg: 9999.0.0, 9999.0.3-dummy // Expected: 9999.0.3 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.3", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_userSdkBaseDir, "9999.0.200"); AddAvailableSdkVersions(_cwdSdkBaseDir, "10000.0.0"); AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.100"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.3 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100 // Expected: 9999.0.100 from reg dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.80"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.3, 9999.0.80 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100 // Expected: 9999.0.100 from reg dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.5500000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.3, 9999.0.80, 9999.0.5500000 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100 // Expected: 9999.0.5500000 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.5500000", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.52000000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.3, 9999.0.80, 9999.0.5500000 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100, 9999.0.52000000 // Expected: 9999.0.52000000 from reg dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.52000000", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions dotnet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable("_DOTNET_TEST_SDK_SELF_REGISTERED_DIR", _regDir) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("9999.0.0") .And .HaveStdOutContaining("9999.0.3-dummy") .And .HaveStdOutContaining("9999.0.3") .And .HaveStdOutContaining("9999.0.100") .And .HaveStdOutContaining("9999.0.80") .And .HaveStdOutContaining("9999.0.5500000") .And .HaveStdOutContaining("9999.0.52000000"); } // This method adds a list of new sdk version folders in the specified // sdkBaseDir. The files are copied from the _sdkDir. Also, the dotnet.runtimeconfig.json // file is overwritten in order to use a dummy framework version (9999.0.0) // Remarks: // - If the sdkBaseDir does not exist, then a DirectoryNotFoundException // is thrown. // - If a specified version folder already exists, then it is deleted and replaced // with the contents of the _builtSharedFxDir. private void AddAvailableSdkVersions(string sdkBaseDir, params string[] availableVersions) { DirectoryInfo sdkBaseDirInfo = new DirectoryInfo(sdkBaseDir); if (!sdkBaseDirInfo.Exists) { throw new DirectoryNotFoundException(); } string dummyRuntimeConfig = Path.Combine(RepoDirectories.RepoRoot, "src", "test", "Assets", "TestUtils", "SDKLookup", "dotnet.runtimeconfig.json"); foreach (string version in availableVersions) { string newSdkDir = Path.Combine(sdkBaseDir, version); SharedFramework.CopyDirectory(_sdkDir, newSdkDir); string runtimeConfig = Path.Combine(newSdkDir, "dotnet.runtimeconfig.json"); File.Copy(dummyRuntimeConfig, runtimeConfig, true); } } // Put a global.json file in the cwd in order to specify a CLI public void SetGlobalJsonVersion(string globalJsonFileName) { string destFile = Path.Combine(_currentWorkingDir, "global.json"); string srcFile = Path.Combine(RepoDirectories.RepoRoot, "src", "test", "Assets", "TestUtils", "SDKLookup", globalJsonFileName); File.Copy(srcFile, destFile, true); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.IO; using DiscUtils.Compression; namespace DiscUtils.Wim { /// <summary> /// Implements the XPRESS decompression algorithm. /// </summary> /// <remarks>This class is optimized for the case where the entire stream contents /// fit into memory, it is not suitable for unbounded streams.</remarks> internal class XpressStream : Stream { private readonly byte[] _buffer; private readonly Stream _compressedStream; private long _position; /// <summary> /// Initializes a new instance of the XpressStream class. /// </summary> /// <param name="compressed">The stream of compressed data.</param> /// <param name="count">The length of this stream (in uncompressed bytes).</param> public XpressStream(Stream compressed, int count) { _compressedStream = new BufferedStream(compressed); _buffer = Buffer(count); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { return _buffer.Length; } } public override long Position { get { return _position; } set { _position = value; } } public override void Flush() {} public override int Read(byte[] buffer, int offset, int count) { if (_position > Length) { return 0; } int numToRead = (int)Math.Min(count, _buffer.Length - _position); Array.Copy(_buffer, (int)_position, buffer, offset, numToRead); _position += numToRead; return numToRead; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } private HuffmanTree ReadHuffmanTree() { uint[] lengths = new uint[256 + 16 * 16]; for (int i = 0; i < lengths.Length; i += 2) { int b = ReadCompressedByte(); lengths[i] = (uint)(b & 0xF); lengths[i + 1] = (uint)(b >> 4); } return new HuffmanTree(lengths); } private byte[] Buffer(int count) { byte[] buffer = new byte[count]; int numRead = 0; HuffmanTree tree = ReadHuffmanTree(); XpressBitStream bitStream = new XpressBitStream(_compressedStream); while (numRead < count) { uint symbol = tree.NextSymbol(bitStream); if (symbol < 256) { // The first 256 symbols are literal byte values buffer[numRead] = (byte)symbol; numRead++; } else { // The next 256 symbols are 4 bits each for offset and length. int offsetBits = (int)((symbol - 256) / 16); int len = (int)((symbol - 256) % 16); // The actual offset int offset = (int)((1 << offsetBits) - 1 + bitStream.Read(offsetBits)); // Lengths up to 15 bytes are stored directly in the symbol bits, beyond that // the length is stored in the compression stream. if (len == 15) { // Note this access is directly to the underlying stream - we're not going // through the bit stream. This makes the precise behaviour of the bit stream, // in terms of read-ahead critical. int b = ReadCompressedByte(); if (b == 0xFF) { // Again, note this access is directly to the underlying stream - we're not going // through the bit stream. len = ReadCompressedUShort(); } else { len += b; } } // Minimum length for a match is 3 bytes, so all lengths are stored as an offset // from 3. len += 3; // Simply do the copy for (int i = 0; i < len; ++i) { buffer[numRead] = buffer[numRead - offset - 1]; numRead++; } } } return buffer; } private int ReadCompressedByte() { int b = _compressedStream.ReadByte(); if (b < 0) { throw new InvalidDataException("Truncated stream"); } return b; } private int ReadCompressedUShort() { int result = ReadCompressedByte(); return result | ReadCompressedByte() << 8; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Internal; using System.Text; namespace Microsoft.PowerShell.Commands { /// <summary> /// PSTuple is a helper class used to create Tuple from an input array. /// </summary> internal static class PSTuple { /// <summary> /// ArrayToTuple is a helper method used to create a tuple for the supplied input array. /// </summary> /// <param name="inputObjects">Input objects used to create a tuple.</param> /// <returns>Tuple object.</returns> internal static object ArrayToTuple(object[] inputObjects) { Diagnostics.Assert(inputObjects != null, "inputObjects is null"); Diagnostics.Assert(inputObjects.Length > 0, "inputObjects is empty"); return ArrayToTuple(inputObjects, 0); } /// <summary> /// ArrayToTuple is a helper method used to create a tuple for the supplied input array. /// </summary> /// <param name="inputObjects">Input objects used to create a tuple</param> /// <param name="startIndex">Start index of the array from which the objects have to considered for the tuple creation.</param> /// <returns>Tuple object.</returns> internal static object ArrayToTuple(object[] inputObjects, int startIndex) { Diagnostics.Assert(inputObjects != null, "inputObjects is null"); Diagnostics.Assert(inputObjects.Length > 0, "inputObjects is empty"); switch (inputObjects.Length - startIndex) { case 0: return null; case 1: return Tuple.Create(inputObjects[startIndex]); case 2: return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1]); case 3: return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2]); case 4: return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3]); case 5: return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3], inputObjects[startIndex + 4]); case 6: return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3], inputObjects[startIndex + 4], inputObjects[startIndex + 5]); case 7: return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3], inputObjects[startIndex + 4], inputObjects[startIndex + 5], inputObjects[startIndex + 6]); case 8: return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3], inputObjects[startIndex + 4], inputObjects[startIndex + 5], inputObjects[startIndex + 6], inputObjects[startIndex + 7]); default: return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3], inputObjects[startIndex + 4], inputObjects[startIndex + 5], inputObjects[startIndex + 6], ArrayToTuple(inputObjects, startIndex + 7)); } } } /// <summary> /// Emitted by Group-Object when the NoElement option is true /// </summary> public sealed class GroupInfoNoElement : GroupInfo { internal GroupInfoNoElement(OrderByPropertyEntry groupValue) : base(groupValue) { } internal override void Add(PSObject groupValue) { Count++; } } /// <summary> /// Emitted by Group-Object /// </summary> public class GroupInfo { internal GroupInfo(OrderByPropertyEntry groupValue) { Group = new Collection<PSObject>(); this.Add(groupValue.inputObject); GroupValue = groupValue; Name = BuildName(groupValue.orderValues); } internal virtual void Add(PSObject groupValue) { Group.Add(groupValue); Count++; } private static string BuildName(List<ObjectCommandPropertyValue> propValues) { StringBuilder sb = new StringBuilder(); foreach (ObjectCommandPropertyValue propValue in propValues) { if (propValue != null && propValue.PropertyValue != null) { var propertyValueItems = propValue.PropertyValue as ICollection; if (propertyValueItems != null) { sb.Append("{"); var length = sb.Length; foreach (object item in propertyValueItems) { sb.Append(string.Format(CultureInfo.InvariantCulture, "{0}, ", item.ToString())); } sb = sb.Length > length ? sb.Remove(sb.Length - 2, 2) : sb; sb.Append("}, "); } else { sb.Append(string.Format(CultureInfo.InvariantCulture, "{0}, ", propValue.PropertyValue.ToString())); } } } return sb.Length >= 2 ? sb.Remove(sb.Length - 2, 2).ToString() : string.Empty; } /// <summary> /// /// Values of the group /// /// </summary> public ArrayList Values { get { ArrayList values = new ArrayList(); foreach (ObjectCommandPropertyValue propValue in GroupValue.orderValues) { values.Add(propValue.PropertyValue); } return values; } } /// <summary> /// /// Number of objects in the group /// /// </summary> public int Count { get; internal set; } /// <summary> /// /// The list of objects in this group /// /// </summary> public Collection<PSObject> Group { get; } = null; /// <summary> /// /// The name of the group /// /// </summary> public string Name { get; } = null; /// <summary> /// /// The OrderByPropertyEntry used to build this group object /// /// </summary> internal OrderByPropertyEntry GroupValue { get; } = null; } /// <summary> /// /// Group-Object implementation /// /// </summary> [Cmdlet("Group", "Object", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113338", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(Hashtable), typeof(GroupInfo))] public class GroupObjectCommand : ObjectBase { #region tracer /// <summary> /// An instance of the PSTraceSource class used for trace output /// </summary> [TraceSourceAttribute( "GroupObjectCommand", "Class that has group base implementation")] private static PSTraceSource s_tracer = PSTraceSource.GetTracer("GroupObjectCommand", "Class that has group base implementation"); #endregion tracer #region Command Line Switches /// <summary> /// /// Flatten the groups /// /// </summary> /// <value></value> [Parameter] public SwitchParameter NoElement { get { return _noElement; } set { _noElement = value; } } private bool _noElement; /// <summary> /// the Ashashtable parameter /// </summary> /// <value></value> [Parameter(ParameterSetName = "HashTable")] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HashTable")] [Alias("AHT")] public SwitchParameter AsHashTable { get; set; } /// <summary> /// /// </summary> /// <value></value> [Parameter(ParameterSetName = "HashTable")] public SwitchParameter AsString { get; set; } private List<GroupInfo> _groups = new List<GroupInfo>(); private OrderByProperty _orderByProperty = new OrderByProperty(); private bool _hasProcessedFirstInputObject; private Dictionary<object, GroupInfo> _tupleToGroupInfoMappingDictionary = new Dictionary<object, GroupInfo>(); private OrderByPropertyComparer _orderByPropertyComparer = null; #endregion #region utils /// <summary> /// Utility function called by Group-Object to create Groups. /// </summary> /// <param name="currentObjectEntry">Input object that needs to be grouped.</param> /// <param name="noElement">true if we are not acumulating objects</param> /// <param name="groups">List containing Groups.</param> /// <param name="groupInfoDictionary">Dictionary used to keep track of the groups with hash of the property values being the key.</param> /// <param name="orderByPropertyComparer">The Comparer to be used while comparing to check if new group has to be created.</param> internal static void DoGrouping(OrderByPropertyEntry currentObjectEntry, bool noElement, List<GroupInfo> groups, Dictionary<object, GroupInfo> groupInfoDictionary, OrderByPropertyComparer orderByPropertyComparer) { if (currentObjectEntry != null && currentObjectEntry.orderValues != null && currentObjectEntry.orderValues.Count > 0) { object currentTupleObject = PSTuple.ArrayToTuple(currentObjectEntry.orderValues.ToArray()); GroupInfo currentGroupInfo = null; if (groupInfoDictionary.TryGetValue(currentTupleObject, out currentGroupInfo)) { if (currentGroupInfo != null) { //add this inputObject to an existing group currentGroupInfo.Add(currentObjectEntry.inputObject); } } else { bool isCurrentItemGrouped = false; for (int groupsIndex = 0; groupsIndex < groups.Count; groupsIndex++) { // Check if the current input object can be converted to one of the already known types // by looking up in the type to GroupInfo mapping. if (orderByPropertyComparer.Compare(groups[groupsIndex].GroupValue, currentObjectEntry) == 0) { groups[groupsIndex].Add(currentObjectEntry.inputObject); isCurrentItemGrouped = true; break; } } if (!isCurrentItemGrouped) { // create a new group s_tracer.WriteLine("Create a new group: {0}", currentObjectEntry.orderValues); GroupInfo newObjGrp = noElement ? new GroupInfoNoElement(currentObjectEntry) : new GroupInfo(currentObjectEntry); groups.Add(newObjGrp); groupInfoDictionary.Add(currentTupleObject, newObjGrp); } } } } private void WriteNonTerminatingError(Exception exception, string resourceIdAndErrorId, ErrorCategory category) { Exception ex = new Exception(StringUtil.Format(resourceIdAndErrorId), exception); WriteError(new ErrorRecord(ex, resourceIdAndErrorId, category, null)); } #endregion utils /// <summary> /// Process every input object to group them. /// </summary> protected override void ProcessRecord() { if (InputObject != null && InputObject != AutomationNull.Value) { OrderByPropertyEntry currentEntry = null; if (!_hasProcessedFirstInputObject) { if (Property == null) { Property = OrderByProperty.GetDefaultKeyPropertySet(InputObject); } _orderByProperty.ProcessExpressionParameter(this, Property); currentEntry = _orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo); bool[] ascending = new bool[currentEntry.orderValues.Count]; for (int index = 0; index < currentEntry.orderValues.Count; index++) { ascending[index] = true; } _orderByPropertyComparer = new OrderByPropertyComparer(ascending, _cultureInfo, CaseSensitive); _hasProcessedFirstInputObject = true; } else { currentEntry = _orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo); } DoGrouping(currentEntry, this.NoElement, _groups, _tupleToGroupInfoMappingDictionary, _orderByPropertyComparer); } } /// <summary> /// /// </summary> protected override void EndProcessing() { s_tracer.WriteLine(_groups.Count); if (_groups.Count > 0) { if (AsHashTable) { Hashtable _table = CollectionsUtil.CreateCaseInsensitiveHashtable(); try { foreach (GroupInfo _grp in _groups) { if (AsString) { _table.Add(_grp.Name, _grp.Group); } else { if (_grp.Values.Count == 1) { _table.Add(_grp.Values[0], _grp.Group); } else { ArgumentException ex = new ArgumentException(UtilityCommonStrings.GroupObjectSingleProperty); ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, Property); ThrowTerminatingError(er); } } } } catch (ArgumentException e) { WriteNonTerminatingError(e, UtilityCommonStrings.InvalidOperation, ErrorCategory.InvalidArgument); return; } WriteObject(_table); } else { if (AsString) { ArgumentException ex = new ArgumentException(UtilityCommonStrings.GroupObjectWithHashTable); ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, AsString); ThrowTerminatingError(er); } else { WriteObject(_groups, true); } } } } } }
// // TreeViewBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using AppKit; using CoreGraphics; using Foundation; using Xwt.Backends; namespace Xwt.Mac { public class TreeViewBackend: TableViewBackend<NSOutlineView,ITreeViewEventSink>, ITreeViewBackend { ITreeDataSource source; TreeSource tsource; class TreeDelegate: NSOutlineViewDelegate { public TreeViewBackend Backend; public override void ItemDidExpand (NSNotification notification) { Backend.EventSink.OnRowExpanded (((TreeItem)notification.UserInfo["NSObject"]).Position); } public override void ItemWillExpand (NSNotification notification) { Backend.EventSink.OnRowExpanding (((TreeItem)notification.UserInfo["NSObject"]).Position); } public override void ItemDidCollapse (NSNotification notification) { Backend.EventSink.OnRowCollapsed (((TreeItem)notification.UserInfo["NSObject"]).Position); } public override void ItemWillCollapse (NSNotification notification) { Backend.EventSink.OnRowCollapsing (((TreeItem)notification.UserInfo["NSObject"]).Position); } public override nfloat GetRowHeight (NSOutlineView outlineView, NSObject item) { nfloat height; var treeItem = (TreeItem)item; if (!Backend.RowHeights.TryGetValue (treeItem, out height) || height <= 0) height = Backend.RowHeights [treeItem] = Backend.CalcRowHeight (treeItem, false); return height; } public override NSTableRowView RowViewForItem (NSOutlineView outlineView, NSObject item) { return outlineView.GetRowView (outlineView.RowForItem (item), false) ?? new TableRowView (); } public override NSView GetView (NSOutlineView outlineView, NSTableColumn tableColumn, NSObject item) { var col = tableColumn as TableColumn; var cell = outlineView.MakeView (tableColumn.Identifier, this) as CompositeCell; if (cell == null) cell = col.CreateNewView (); if (cell.ObjectValue != item) cell.ObjectValue = item; return cell; } public override nfloat GetSizeToFitColumnWidth (NSOutlineView outlineView, nint column) { var tableColumn = Backend.Columns[(int)column] as TableColumn; var width = tableColumn.HeaderCell.CellSize.Width; CompositeCell templateCell = null; for (int i = 0; i < outlineView.RowCount; i++) { var cellView = outlineView.GetView (column, i, false) as CompositeCell; if (cellView == null) { // use template for invisible rows cellView = templateCell ?? (templateCell = (tableColumn as TableColumn)?.DataView?.Copy () as CompositeCell); if (cellView != null) cellView.ObjectValue = outlineView.ItemAtRow (i); } if (cellView != null) { if (column == 0) // first column contains expanders width = (nfloat)Math.Max (width, cellView.Frame.X + cellView.FittingSize.Width); else width = (nfloat)Math.Max (width, cellView.FittingSize.Width); } } return width; } public override NSIndexSet GetSelectionIndexes(NSOutlineView outlineView, NSIndexSet proposedSelectionIndexes) { return Backend.SelectionMode != SelectionMode.None ? proposedSelectionIndexes : new NSIndexSet(); } } OutlineViewBackend Tree { get { return (OutlineViewBackend) Table; } } protected override NSTableView CreateView () { var t = new OutlineViewBackend (this); t.Delegate = new TreeDelegate () { Backend = this }; return t; } public bool AnimationsEnabled { get { return Tree.AnimationsEnabled; } set { Tree.AnimationsEnabled = value; } } protected override string SelectionChangeEventName { get { return "NSOutlineViewSelectionDidChangeNotification"; } } public TreePosition CurrentEventRow { get; internal set; } public override NSTableColumn AddColumn (ListViewColumn col) { NSTableColumn tcol = base.AddColumn (col); if (Tree.OutlineTableColumn == null) Tree.OutlineTableColumn = tcol; return tcol; } public void SetSource (ITreeDataSource source, IBackend sourceBackend) { this.source = source; RowHeights.Clear (); tsource = new TreeSource (source); Tree.DataSource = tsource; source.NodeInserted += (sender, e) => { var parent = tsource.GetItem (source.GetParent (e.Node)); Tree.ReloadItem (parent, parent == null || Tree.IsItemExpanded (parent)); }; source.NodeDeleted += (sender, e) => { var parent = tsource.GetItem (e.Node); var item = tsource.GetItem(e.Child); if (item != null) RowHeights.Remove (null); Tree.ReloadItem (parent, parent == null || Tree.IsItemExpanded (parent)); }; source.NodeChanged += (sender, e) => { var item = tsource.GetItem (e.Node); if (item != null) { Tree.ReloadItem (item, false); UpdateRowHeight (item); } }; source.NodesReordered += (sender, e) => { var parent = tsource.GetItem (e.Node); Tree.ReloadItem (parent, parent == null || Tree.IsItemExpanded (parent)); }; source.Cleared += (sender, e) => { Tree.ReloadData (); RowHeights.Clear (); }; } public override object GetValue (object pos, int nField) { return source.GetValue ((TreePosition)pos, nField); } public override void SetValue (object pos, int nField, object value) { source.SetValue ((TreePosition)pos, nField, value); } public override void InvalidateRowHeight (object pos) { UpdateRowHeight (tsource.GetItem((TreePosition)pos)); } Dictionary<TreeItem, nfloat> RowHeights = new Dictionary<TreeItem, nfloat> (); bool updatingRowHeight; void UpdateRowHeight (TreeItem pos) { if (updatingRowHeight) return; var row = Tree.RowForItem (pos); if (row >= 0) { // calculate new height now by reusing the visible cell to avoid using the template cell with unnecessary data reloads // NOTE: cell reusing is not supported in Delegate.GetRowHeight and would require an other data reload to the template cell RowHeights[pos] = CalcRowHeight (pos); Table.NoteHeightOfRowsWithIndexesChanged (NSIndexSet.FromIndex (row)); } else // Invalidate the height, to force recalculation in Delegate.GetRowHeight RowHeights[pos] = -1; } nfloat CalcRowHeight (TreeItem pos, bool tryReuse = true) { updatingRowHeight = true; var height = Table.RowHeight; var row = Tree.RowForItem (pos); for (int i = 0; i < Columns.Count; i++) { CompositeCell cell = tryReuse && row >= 0 ? Tree.GetView (i, row, false) as CompositeCell : null; if (cell == null) { cell = (Columns [i] as TableColumn)?.DataView as CompositeCell; cell.ObjectValue = pos; height = (nfloat)Math.Max (height, cell.FittingSize.Height); } else { height = (nfloat)Math.Max (height, cell.GetRequiredHeightForWidth (cell.Frame.Width)); } } updatingRowHeight = false; return height; } public TreePosition[] SelectedRows { get { TreePosition[] res = new TreePosition [Table.SelectedRowCount]; int n = 0; if (Table.SelectedRowCount > 0) { foreach (var i in Table.SelectedRows) { res [n] = ((TreeItem)Tree.ItemAtRow ((int)i)).Position; n++; } } return res; } } public TreePosition FocusedRow { get { if (Table.SelectedRowCount > 0) return ((TreeItem)Tree.ItemAtRow ((int)Table.SelectedRows.FirstIndex)).Position; return null; } set { SelectRow (value); ScrollToRow (value); } } public override void SetCurrentEventRow (object pos) { CurrentEventRow = (TreePosition)pos; } public void SelectRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) Table.SelectRow ((int)Tree.RowForItem (it), Table.AllowsMultipleSelection); } public void UnselectRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) Table.DeselectRow (Tree.RowForItem (it)); } public bool IsRowSelected (TreePosition pos) { var it = tsource.GetItem (pos); return it != null && Table.IsRowSelected (Tree.RowForItem (it)); } public bool IsRowExpanded (TreePosition pos) { var it = tsource.GetItem (pos); return it != null && Tree.IsItemExpanded (it); } public void ExpandRow (TreePosition pos, bool expandChildren) { var it = tsource.GetItem (pos); if (it != null) Tree.ExpandItem (it, expandChildren); } public void CollapseRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) Tree.CollapseItem (it); } public void ScrollToRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) ScrollToRow ((int)Tree.RowForItem (it)); } public void ExpandToRow (TreePosition pos) { var p = source.GetParent (pos); if (p == null) return; var s = new Stack<TreePosition> (); while (p != null) { s.Push (p); p = source.GetParent (p); } while (s.Count > 0) { var it = tsource.GetItem (s.Pop ()); if (it == null) break; Tree.ExpandItem (it, false); } } public TreePosition GetRowAtPosition (Point p) { var row = Table.GetRow (new CGPoint ((float)p.X, (float)p.Y)); return row >= 0 ? ((TreeItem)Tree.ItemAtRow (row)).Position : null; } public Rectangle GetCellBounds (TreePosition pos, CellView cell, bool includeMargin) { var it = tsource.GetItem (pos); if (it == null) return Rectangle.Zero; var row = (int)Tree.RowForItem (it); return GetCellBounds (row, cell, includeMargin); } public Rectangle GetRowBounds (TreePosition pos, bool includeMargin) { var it = tsource.GetItem (pos); if (it == null) return Rectangle.Zero; var row = (int)Tree.RowForItem (it); return GetRowBounds (row, includeMargin); } public bool GetDropTargetRow (double x, double y, out RowDropPosition pos, out TreePosition nodePosition) { // Get row nint row = Tree.GetRow(new CGPoint ((nfloat)x, (nfloat)y)); pos = RowDropPosition.Into; nodePosition = null; if (row >= 0) { nodePosition = ((TreeItem)Tree.ItemAtRow (row)).Position; } return nodePosition != null; } /* protected override void OnDragOverCheck (NSDraggingInfo di, DragOverCheckEventArgs args) { base.OnDragOverCheck (di, args); var row = Tree.GetRow (new CGPoint (di.DraggingLocation.X, di.DraggingLocation.Y)); if (row != -1) { var item = Tree.ItemAtRow (row); Tree.SetDropItem (item, row); } } protected override void OnDragOver (NSDraggingInfo di, DragOverEventArgs args) { base.OnDragOver (di, args); var p = Tree.ConvertPointFromView (di.DraggingLocation, null); var row = Tree.GetRow (p); if (row != -1) { Tree.SetDropRowDropOperation (row, NSTableViewDropOperation.On); var item = Tree.ItemAtRow (row); Tree.SetDropItem (item, 0); } }*/ } class TreeItem: NSObject, ITablePosition { public TreePosition Position; public TreeItem () { } public TreeItem (IntPtr p): base (p) { } object ITablePosition.Position { get { return Position; } } public override NSObject Copy () { return new TreeItem { Position = this.Position }; } } class TreeSource: NSOutlineViewDataSource { ITreeDataSource source; Dictionary<TreePosition,TreeItem> items = new Dictionary<TreePosition, TreeItem> (); public TreeSource (ITreeDataSource source) { this.source = source; source.NodeInserted += (sender, e) => { if (!items.ContainsKey (e.Node)) items.Add (e.Node, new TreeItem { Position = e.Node }); }; source.NodeDeleted += (sender, e) => { items.Remove (e.Child); }; source.Cleared += (sender, e) => { items.Clear (); }; } public TreeItem GetItem (TreePosition pos) { if (pos == null) return null; TreeItem it; items.TryGetValue (pos, out it); return it; } public override bool AcceptDrop (NSOutlineView outlineView, NSDraggingInfo info, NSObject item, nint index) { return false; } public override string[] FilesDropped (NSOutlineView outlineView, NSUrl dropDestination, NSArray items) { throw new NotImplementedException (); } public override NSObject GetChild (NSOutlineView outlineView, nint childIndex, NSObject item) { var treeItem = (TreeItem) item; var pos = source.GetChild (treeItem != null ? treeItem.Position : null, (int) childIndex); if (pos != null) { TreeItem res; if (!items.TryGetValue (pos, out res)) items [pos] = res = new TreeItem () { Position = pos }; return res; } else return null; } public override nint GetChildrenCount (NSOutlineView outlineView, NSObject item) { var it = (TreeItem) item; return source.GetChildrenCount (it != null ? it.Position : null); } public override NSObject GetObjectValue (NSOutlineView outlineView, NSTableColumn forTableColumn, NSObject byItem) { return byItem; } public override void SetObjectValue (NSOutlineView outlineView, NSObject theObject, NSTableColumn tableColumn, NSObject item) { } public override bool ItemExpandable (NSOutlineView outlineView, NSObject item) { return GetChildrenCount (outlineView, item) > 0; } public override NSObject ItemForPersistentObject (NSOutlineView outlineView, NSObject theObject) { return null; } public override bool OutlineViewwriteItemstoPasteboard (NSOutlineView outlineView, NSArray items, NSPasteboard pboard) { return false; } public override NSObject PersistentObjectForItem (NSOutlineView outlineView, NSObject item) { return null; } public override void SortDescriptorsChanged (NSOutlineView outlineView, NSSortDescriptor[] oldDescriptors) { } public override NSDragOperation ValidateDrop (NSOutlineView outlineView, NSDraggingInfo info, NSObject item, nint index) { return NSDragOperation.None; } protected override void Dispose (bool disposing) { base.Dispose (disposing); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Globalization; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using System.Management.Automation.Runspaces; using System.Runtime.CompilerServices; using Microsoft.PowerShell.Commands; using System.IO; namespace System.Management.Automation.Language { internal enum ScopeType { Type, // class or enum Method, // class method Function, // function ScriptBlock // script or anonymous script block } internal class TypeLookupResult { public TypeLookupResult(TypeDefinitionAst type = null) { Type = type; } public TypeDefinitionAst Type { get; set; } public List<string> ExternalNamespaces { get; set; } public bool IsAmbiguous() { return (ExternalNamespaces != null && ExternalNamespaces.Count > 1); } } internal class Scope { internal Ast _ast; internal ScopeType _scopeType; /// <summary> /// TypeTable maps namespace (currently it's module name) to the types under this namespace. /// For the types defined in the current namespace (module) we use CURRENT_NAMESPACE as a namespace. /// </summary> private readonly Dictionary<string, TypeLookupResult> _typeTable; private readonly Dictionary<string, Ast> _variableTable; internal Scope(IParameterMetadataProvider ast, ScopeType scopeType) { _ast = (Ast)ast; _scopeType = scopeType; _typeTable = new Dictionary<string, TypeLookupResult>(StringComparer.OrdinalIgnoreCase); _variableTable = new Dictionary<string, Ast>(StringComparer.OrdinalIgnoreCase); } internal Scope(TypeDefinitionAst typeDefinition) { _ast = typeDefinition; _scopeType = ScopeType.Type; _typeTable = new Dictionary<string, TypeLookupResult>(StringComparer.OrdinalIgnoreCase); _variableTable = new Dictionary<string, Ast>(StringComparer.OrdinalIgnoreCase); foreach (var member in typeDefinition.Members) { var propertyMember = member as PropertyMemberAst; if (propertyMember != null) { // Duplicate members are an error, but we catch that later after all types // have been resolved. We could report errors for properties here, but // we couldn't compare methods becaues overloads can't be compared until types // are resolved. if (!_variableTable.ContainsKey(propertyMember.Name)) { _variableTable.Add(propertyMember.Name, propertyMember); } } } } internal void AddType(Parser parser, TypeDefinitionAst typeDefinitionAst) { TypeLookupResult result; if (_typeTable.TryGetValue(typeDefinitionAst.Name, out result)) { if (result.ExternalNamespaces != null) { // override external type by the type defined in the current namespace result.ExternalNamespaces = null; result.Type = typeDefinitionAst; } else { parser.ReportError(typeDefinitionAst.Extent, () => ParserStrings.MemberAlreadyDefined, typeDefinitionAst.Name); } } else { _typeTable.Add(typeDefinitionAst.Name, new TypeLookupResult(typeDefinitionAst)); } } internal void AddTypeFromUsingModule(Parser parser, TypeDefinitionAst typeDefinitionAst, PSModuleInfo moduleInfo) { TypeLookupResult result; if (_typeTable.TryGetValue(typeDefinitionAst.Name, out result)) { if (result.ExternalNamespaces != null) { // override external type by the type defined in the current namespace result.ExternalNamespaces.Add(moduleInfo.Name); } } else { var newLookupEntry = new TypeLookupResult(typeDefinitionAst) { ExternalNamespaces = new List<string>() }; newLookupEntry.ExternalNamespaces.Add(moduleInfo.Name); _typeTable.Add(typeDefinitionAst.Name, newLookupEntry); } string fullName = SymbolResolver.GetModuleQualifiedName(moduleInfo.Name, typeDefinitionAst.Name); if (_typeTable.TryGetValue(fullName, out result)) { parser.ReportError(typeDefinitionAst.Extent, () => ParserStrings.MemberAlreadyDefined, fullName); } else { _typeTable.Add(fullName, new TypeLookupResult(typeDefinitionAst)); } } internal TypeLookupResult LookupType(TypeName typeName) { if (typeName.AssemblyName != null) { return null; } TypeLookupResult typeLookupResult; _typeTable.TryGetValue(typeName.Name, out typeLookupResult); return typeLookupResult; } public Ast LookupVariable(VariablePath variablePath) { Ast variabledefinition; _variableTable.TryGetValue(variablePath.UserPath, out variabledefinition); return variabledefinition; } } internal class SymbolTable { internal readonly List<Scope> _scopes; internal readonly Parser _parser; internal SymbolTable(Parser parser) { _scopes = new List<Scope>(); _parser = parser; } internal void AddTypesInScope(Ast ast) { // On entering a scope, we first add all the types defined in this scope (but not any nested scopes) // This way, we can support types that refer to each other, e.g. // class C1 { [C2]$x } // class C2 { [C1]$c1 } var types = ast.FindAll(x => x is TypeDefinitionAst, searchNestedScriptBlocks: false); foreach (var type in types) { AddType((TypeDefinitionAst)type); } } internal void EnterScope(IParameterMetadataProvider ast, ScopeType scopeType) { var scope = new Scope(ast, scopeType); _scopes.Add(scope); AddTypesInScope((Ast)ast); } internal void EnterScope(TypeDefinitionAst typeDefinition) { var scope = new Scope(typeDefinition); _scopes.Add(scope); AddTypesInScope(typeDefinition); } internal void LeaveScope() { Diagnostics.Assert(_scopes.Count > 0, "Scope stack can't be empty when leaving a scope"); _scopes.RemoveAt(_scopes.Count - 1); } /// <summary> /// Add Type to the symbol Table. /// </summary> /// <param name="typeDefinitionAst"></param> public void AddType(TypeDefinitionAst typeDefinitionAst) { _scopes[_scopes.Count - 1].AddType(_parser, typeDefinitionAst); } /// <summary> /// Add Type from the different module to the symbol Table. /// </summary> /// <param name="typeDefinitionAst"></param> /// <param name="moduleInfo"></param> public void AddTypeFromUsingModule(TypeDefinitionAst typeDefinitionAst, PSModuleInfo moduleInfo) { _scopes[_scopes.Count - 1].AddTypeFromUsingModule(_parser, typeDefinitionAst, moduleInfo); } public TypeLookupResult LookupType(TypeName typeName) { TypeLookupResult result = null; for (int i = _scopes.Count - 1; i >= 0; i--) { result = _scopes[i].LookupType(typeName); if (result != null) break; } return result; } public Ast LookupVariable(VariablePath variablePath) { Ast result = null; for (int i = _scopes.Count - 1; i >= 0; i--) { result = _scopes[i].LookupVariable(variablePath); if (result != null) break; } return result; } /// <summary> /// Return the most deep typeDefinitionAst in the current context. /// </summary> /// <returns>typeDefinitionAst or null, if currently not in type definition</returns> public TypeDefinitionAst GetCurrentTypeDefinitionAst() { for (int i = _scopes.Count - 1; i >= 0; i--) { TypeDefinitionAst ast = _scopes[i]._ast as TypeDefinitionAst; if (ast != null) { return ast; } } return null; } public bool IsInMethodScope() { return _scopes[_scopes.Count - 1]._scopeType == ScopeType.Method; } } internal class SymbolResolver : AstVisitor2, IAstPostVisitHandler { private readonly SymbolResolvePostActionVisitor _symbolResolvePostActionVisitor; internal readonly SymbolTable _symbolTable; internal readonly Parser _parser; internal readonly TypeResolutionState _typeResolutionState; [ThreadStatic] private static PowerShell t_usingStatementResolvePowerShell; private static PowerShell UsingStatementResolvePowerShell { get { // The goal is to re-use runspaces, because creating runspace is an expensive part in creating PowerShell instance. if (t_usingStatementResolvePowerShell == null) { if (Runspace.DefaultRunspace != null) { t_usingStatementResolvePowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace); } else { // Create empty iss and populate only commands, that we want to use. InitialSessionState iss = InitialSessionState.Create(); iss.Commands.Add(new SessionStateCmdletEntry("Get-Module", typeof(GetModuleCommand), null)); var sessionStateProviderEntry = new SessionStateProviderEntry(FileSystemProvider.ProviderName, typeof(FileSystemProvider), null); var snapin = PSSnapInReader.ReadEnginePSSnapIns().FirstOrDefault(snapIn => snapIn.Name.Equals("Microsoft.PowerShell.Core", StringComparison.OrdinalIgnoreCase)); sessionStateProviderEntry.SetPSSnapIn(snapin); iss.Providers.Add(sessionStateProviderEntry); t_usingStatementResolvePowerShell = PowerShell.Create(iss); } } else if (Runspace.DefaultRunspace != null && t_usingStatementResolvePowerShell.Runspace != Runspace.DefaultRunspace) { t_usingStatementResolvePowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace); } return t_usingStatementResolvePowerShell; } } private SymbolResolver(Parser parser, TypeResolutionState typeResolutionState) { _symbolTable = new SymbolTable(parser); _parser = parser; _typeResolutionState = typeResolutionState; _symbolResolvePostActionVisitor = new SymbolResolvePostActionVisitor { _symbolResolver = this }; } internal static void ResolveSymbols(Parser parser, ScriptBlockAst scriptBlockAst) { Diagnostics.Assert(scriptBlockAst.Parent == null, "Can only resolve starting from the root"); var usingState = scriptBlockAst.UsingStatements.Count > 0 ? new TypeResolutionState(TypeOps.GetNamespacesForTypeResolutionState(scriptBlockAst.UsingStatements), TypeResolutionState.emptyAssemblies) : TypeResolutionState.GetDefaultUsingState(null); var resolver = new SymbolResolver(parser, usingState); resolver._symbolTable.EnterScope(scriptBlockAst, ScopeType.ScriptBlock); scriptBlockAst.Visit(resolver); resolver._symbolTable.LeaveScope(); Diagnostics.Assert(resolver._symbolTable._scopes.Count == 0, "Somebody missed removing a scope"); } public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) { _symbolTable.EnterScope(typeDefinitionAst); return AstVisitAction.Continue; } public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { _symbolTable.EnterScope(scriptBlockExpressionAst.ScriptBlock, ScopeType.ScriptBlock); return AstVisitAction.Continue; } public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { if (!(functionDefinitionAst.Parent is FunctionMemberAst)) { _symbolTable.EnterScope(functionDefinitionAst.Body, ScopeType.Function); } return AstVisitAction.Continue; } public override AstVisitAction VisitPropertyMember(PropertyMemberAst propertyMemberAst) { return AstVisitAction.Continue; } public override AstVisitAction VisitFunctionMember(FunctionMemberAst functionMemberAst) { _symbolTable.EnterScope(functionMemberAst.Body, ScopeType.Method); return AstVisitAction.Continue; } public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { if (_symbolTable.IsInMethodScope()) { var targets = assignmentStatementAst.GetAssignmentTargets().ToArray(); foreach (var expressionAst in targets) { var expression = expressionAst; var variableExpressionAst = expression as VariableExpressionAst; while (variableExpressionAst == null && expression != null) { var convertExpressionAst = expression as ConvertExpressionAst; if (convertExpressionAst != null) { expression = convertExpressionAst.Child; variableExpressionAst = convertExpressionAst.Child as VariableExpressionAst; } else { break; } } if (variableExpressionAst != null && variableExpressionAst.VariablePath.IsVariable) { var ast = _symbolTable.LookupVariable(variableExpressionAst.VariablePath); var propertyMember = ast as PropertyMemberAst; if (propertyMember != null) { if (propertyMember.IsStatic) { var typeAst = _symbolTable.GetCurrentTypeDefinitionAst(); Diagnostics.Assert(typeAst != null, "Method scopes can exist only inside type definitions."); _parser.ReportError(variableExpressionAst.Extent, () => ParserStrings.MissingTypeInStaticPropertyAssignment, String.Format(CultureInfo.InvariantCulture, "[{0}]::", typeAst.Name), propertyMember.Name); } else { _parser.ReportError(variableExpressionAst.Extent, () => ParserStrings.MissingThis, "$this.", propertyMember.Name); } } } } // TODO: static look for alias and function. } return AstVisitAction.Continue; } public override AstVisitAction VisitTypeExpression(TypeExpressionAst typeExpressionAst) { DispatchTypeName(typeExpressionAst.TypeName, genericArgumentCount: 0, isAttribute: false); return AstVisitAction.Continue; } public override AstVisitAction VisitTypeConstraint(TypeConstraintAst typeConstraintAst) { DispatchTypeName(typeConstraintAst.TypeName, genericArgumentCount: 0, isAttribute: false); return AstVisitAction.Continue; } /// <summary> /// Resolves using module to a collection of PSModuleInfos. Doesn't throw. /// PSModuleInfo objects are retunred in the right order: i.e. if multiply verions of the module /// is presented on the system and user didn't specify version, we will return all of them, but newer one would go first. /// </summary> /// <param name="usingStatementAst">using statement</param> /// <param name="exception">If exception happens, return exception object.</param> /// <param name="wildcardCharactersUsed"> /// True if in the module name uses wildcardCharacter. /// We don't want to resolve any wild-cards in using module. /// </param> /// <param name="isConstant">True if module hashtable contains constant value (it's our requirement).</param> /// <returns>Modules, if can resolve it. null if any problems happens.</returns> private Collection<PSModuleInfo> GetModulesFromUsingModule(UsingStatementAst usingStatementAst, out Exception exception, out bool wildcardCharactersUsed, out bool isConstant) { exception = null; wildcardCharactersUsed = false; isConstant = true; // fullyQualifiedName can be string or hashtable object fullyQualifiedName; if (usingStatementAst.ModuleSpecification != null) { object resultObject; if (!IsConstantValueVisitor.IsConstant(usingStatementAst.ModuleSpecification, out resultObject, forAttribute: false, forRequires: true)) { isConstant = false; return null; } var hashtable = resultObject as System.Collections.Hashtable; var ms = new ModuleSpecification(); exception = ModuleSpecification.ModuleSpecificationInitHelper(ms, hashtable); if (exception != null) { return null; } if (WildcardPattern.ContainsWildcardCharacters(ms.Name)) { wildcardCharactersUsed = true; return null; } fullyQualifiedName = ms; } else { string fullyQualifiedNameStr = usingStatementAst.Name.Value; if (WildcardPattern.ContainsWildcardCharacters(fullyQualifiedNameStr)) { wildcardCharactersUsed = true; return null; } // case 1: relative path. Relative for file in the same folder should include .\ bool isPath = fullyQualifiedNameStr.Contains(@"\"); if (isPath && !LocationGlobber.IsAbsolutePath(fullyQualifiedNameStr)) { string rootPath = Path.GetDirectoryName(_parser._fileName); if (rootPath != null) { fullyQualifiedNameStr = Path.Combine(rootPath, fullyQualifiedNameStr); } } // case 2: Module by name // case 3: Absolute Path // We don't need to do anything for these cases, FullyQualifiedName already handle it. fullyQualifiedName = fullyQualifiedNameStr; } var commandInfo = new CmdletInfo("Get-Module", typeof(GetModuleCommand)); // TODO(sevoroby): we should consider an async call with cancellation here. UsingStatementResolvePowerShell.Commands.Clear(); try { return UsingStatementResolvePowerShell.AddCommand(commandInfo) .AddParameter("FullyQualifiedName", fullyQualifiedName) .AddParameter("ListAvailable", true) .Invoke<PSModuleInfo>(); } catch (Exception e) { exception = e; return null; } } public override AstVisitAction VisitUsingStatement(UsingStatementAst usingStatementAst) { if (usingStatementAst.UsingStatementKind == UsingStatementKind.Module) { Exception exception; bool wildcardCharactersUsed; bool isConstant; var moduleInfo = GetModulesFromUsingModule(usingStatementAst, out exception, out wildcardCharactersUsed, out isConstant); if (!isConstant) { _parser.ReportError(usingStatementAst.Extent, () => ParserStrings.RequiresArgumentMustBeConstant); } else if (exception != null) { // we re-using RequiresModuleInvalid string, semantic is very similar so it's fine to do that. _parser.ReportError(usingStatementAst.Extent, () => ParserStrings.RequiresModuleInvalid, exception.Message); } else if (wildcardCharactersUsed) { _parser.ReportError(usingStatementAst.Extent, () => ParserStrings.WildCardModuleNameError); } else if (moduleInfo != null && moduleInfo.Count > 0) { // it's ok, if we get more then one module. They are already sorted in the right order // we just need to use the first one // We must add the same objects (in sense of object refs) to usingStatementAst typeTable and to symbolTable. // Later, this same TypeDefinitionAsts would be used in DefineTypes(), by the module, where it was imported from at compile time. var exportedTypes = usingStatementAst.DefineImportedModule(moduleInfo[0]); foreach (var typePairs in exportedTypes) { _symbolTable.AddTypeFromUsingModule(typePairs.Value, moduleInfo[0]); } } else { // if there is no exception, but we didn't find the module then it's not present string moduleText = usingStatementAst.Name != null ? usingStatementAst.Name.Value : usingStatementAst.ModuleSpecification.Extent.Text; _parser.ReportError(usingStatementAst.Extent, () => ParserStrings.ModuleNotFoundDuringParse, moduleText); } } return AstVisitAction.Continue; } public override AstVisitAction VisitAttribute(AttributeAst attributeAst) { DispatchTypeName(attributeAst.TypeName, genericArgumentCount: 0, isAttribute: true); return AstVisitAction.Continue; } private bool DispatchTypeName(ITypeName type, int genericArgumentCount, bool isAttribute) { RuntimeHelpers.EnsureSufficientExecutionStack(); var typeName = type as TypeName; if (typeName != null) { return VisitTypeName(typeName, genericArgumentCount, isAttribute); } else { var arrayTypeName = type as ArrayTypeName; if (arrayTypeName != null) { return VisitArrayTypeName(arrayTypeName); } else { var genericTypeName = type as GenericTypeName; if (genericTypeName != null) { return VisitGenericTypeName(genericTypeName); } } } return false; } private bool VisitArrayTypeName(ArrayTypeName arrayTypeName) { bool resolved = DispatchTypeName(arrayTypeName.ElementType, genericArgumentCount: 0, isAttribute: false); if (resolved) { var resolvedType = arrayTypeName.GetReflectionType(); TypeCache.Add(arrayTypeName, _typeResolutionState, resolvedType); } return resolved; } private bool VisitTypeName(TypeName typeName, int genericArgumentCount, bool isAttribute) { var classDefn = _symbolTable.LookupType(typeName); if (classDefn != null && classDefn.IsAmbiguous()) { _parser.ReportError(typeName.Extent, () => ParserStrings.AmbiguousTypeReference, typeName.Name, GetModuleQualifiedName(classDefn.ExternalNamespaces[0], typeName.Name), GetModuleQualifiedName(classDefn.ExternalNamespaces[1], typeName.Name)); } else if (classDefn != null && genericArgumentCount == 0) { typeName.SetTypeDefinition(classDefn.Type); } else { Exception e; TypeResolutionState trs = genericArgumentCount > 0 || isAttribute ? new TypeResolutionState(_typeResolutionState, genericArgumentCount, isAttribute) : _typeResolutionState; var type = TypeResolver.ResolveTypeNameWithContext(typeName, out e, null, trs); if (type == null) { if (_symbolTable.GetCurrentTypeDefinitionAst() != null) { // [ordered] is an attribute, but it's looks like a type constraint. if (!typeName.FullName.Equals(LanguagePrimitives.OrderedAttribute, StringComparison.OrdinalIgnoreCase)) { _parser.ReportError(typeName.Extent, isAttribute ? (Expression<Func<string>>)(() => ParserStrings.CustomAttributeTypeNotFound) : () => ParserStrings.TypeNotFound, typeName.Name); } } } else { ((ISupportsTypeCaching)typeName).CachedType = type; return true; } } return false; } private bool VisitGenericTypeName(GenericTypeName genericTypeName) { var foundType = TypeCache.Lookup(genericTypeName, _typeResolutionState); if (foundType != null) { ((ISupportsTypeCaching)genericTypeName).CachedType = foundType; return true; } bool resolved = true; resolved &= DispatchTypeName(genericTypeName.TypeName, genericTypeName.GenericArguments.Count, isAttribute: false); foreach (var typeArg in genericTypeName.GenericArguments) { resolved &= DispatchTypeName(typeArg, genericArgumentCount: 0, isAttribute: false); } if (resolved) { var resolvedType = genericTypeName.GetReflectionType(); TypeCache.Add(genericTypeName, _typeResolutionState, resolvedType); } return resolved; } public void PostVisit(Ast ast) { ast.Accept(_symbolResolvePostActionVisitor); } internal static string GetModuleQualifiedName(string namespaceName, string typeName) { const char NAMESPACE_SEPARATOR = '.'; return namespaceName + NAMESPACE_SEPARATOR + typeName; } } internal class SymbolResolvePostActionVisitor : DefaultCustomAstVisitor2 { internal SymbolResolver _symbolResolver; public override object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { if (!(functionDefinitionAst.Parent is FunctionMemberAst)) { _symbolResolver._symbolTable.LeaveScope(); } return null; } public override object VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { _symbolResolver._symbolTable.LeaveScope(); return null; } public override object VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) { _symbolResolver._symbolTable.LeaveScope(); return null; } public override object VisitFunctionMember(FunctionMemberAst functionMemberAst) { _symbolResolver._symbolTable.LeaveScope(); return null; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // EventSource for Task.Parallel. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections.Generic; using System.Text; using System.Security; using System.Diagnostics.Tracing; namespace System.Threading.Tasks { /// <summary>Provides an event source for tracing TPL information.</summary> [EventSource(Name = "System.Threading.Tasks.Parallel.EventSource")] internal sealed class ParallelEtwProvider : EventSource { /// <summary> /// Defines the singleton instance for the Task.Parallel ETW provider. /// </summary> public static readonly ParallelEtwProvider Log = new ParallelEtwProvider(); /// <summary>Prevent external instantiation. All logging should go through the Log instance.</summary> private ParallelEtwProvider() { } /// <summary>Type of a fork/join operation.</summary> public enum ForkJoinOperationType { /// <summary>Parallel.Invoke.</summary> ParallelInvoke = 1, /// <summary>Parallel.For.</summary> ParallelFor = 2, /// <summary>Parallel.ForEach.</summary> ParallelForEach = 3 } /// <summary>ETW tasks that have start/stop events.</summary> public class Tasks { // this name is important for EventSource /// <summary>A parallel loop.</summary> public const EventTask Loop = (EventTask)1; /// <summary>A parallel invoke.</summary> public const EventTask Invoke = (EventTask)2; // Do not use 3, it is used for "TaskExecute" in the TPL provider. // Do not use 4, it is used for "TaskWait" in the TPL provider. /// <summary>A fork/join task within a loop or invoke.</summary> public const EventTask ForkJoin = (EventTask)5; } /// <summary>Enabled for all keywords.</summary> private const EventKeywords ALL_KEYWORDS = (EventKeywords)(-1); //----------------------------------------------------------------------------------- // // TPL Event IDs (must be unique) // /// <summary>The beginning of a parallel loop.</summary> private const int PARALLELLOOPBEGIN_ID = 1; /// <summary>The ending of a parallel loop.</summary> private const int PARALLELLOOPEND_ID = 2; /// <summary>The beginning of a parallel invoke.</summary> private const int PARALLELINVOKEBEGIN_ID = 3; /// <summary>The ending of a parallel invoke.</summary> private const int PARALLELINVOKEEND_ID = 4; /// <summary>A task entering a fork/join construct.</summary> private const int PARALLELFORK_ID = 5; /// <summary>A task leaving a fork/join construct.</summary> private const int PARALLELJOIN_ID = 6; //----------------------------------------------------------------------------------- // // Parallel Events // #region ParallelLoopBegin /// <summary> /// Denotes the entry point for a Parallel.For or Parallel.ForEach loop /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The loop ID.</param> /// <param name="OperationType">The kind of fork/join operation.</param> /// <param name="InclusiveFrom">The lower bound of the loop.</param> /// <param name="ExclusiveTo">The upper bound of the loop.</param> [Event(PARALLELLOOPBEGIN_ID, Level = EventLevel.Informational, Task = ParallelEtwProvider.Tasks.Loop, Opcode = EventOpcode.Start)] public void ParallelLoopBegin(int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID, ForkJoinOperationType OperationType, // PFX_FORKJOIN_COMMON_EVENT_HEADER long InclusiveFrom, long ExclusiveTo) { if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS)) { // There is no explicit WriteEvent() overload matching this event's fields. Therefore calling // WriteEvent() would hit the "params" overload, which leads to an object allocation every time // this event is fired. To prevent that problem we will call WriteEventCore(), which works with // a stack based EventData array populated with the event fields. unsafe { EventData* eventPayload = stackalloc EventData[6]; eventPayload[0] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)) }; eventPayload[1] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&OriginatingTaskID)) }; eventPayload[2] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&ForkJoinContextID)) }; eventPayload[3] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&OperationType)) }; eventPayload[4] = new EventData { Size = sizeof(long), DataPointer = ((IntPtr)(&InclusiveFrom)) }; eventPayload[5] = new EventData { Size = sizeof(long), DataPointer = ((IntPtr)(&ExclusiveTo)) }; WriteEventCore(PARALLELLOOPBEGIN_ID, 6, eventPayload); } } } #endregion ParallelLoopBegin #region ParallelLoopEnd /// <summary> /// Denotes the end of a Parallel.For or Parallel.ForEach loop. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The loop ID.</param> /// <param name="TotalIterations">the total number of iterations processed.</param> [Event(PARALLELLOOPEND_ID, Level = EventLevel.Informational, Task = ParallelEtwProvider.Tasks.Loop, Opcode = EventOpcode.Stop)] public void ParallelLoopEnd(int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID, long TotalIterations) { if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS)) { // There is no explicit WriteEvent() overload matching this event's fields. // Therefore calling WriteEvent() would hit the "params" overload, which leads to an object allocation every time this event is fired. // To prevent that problem we will call WriteEventCore(), which works with a stack based EventData array populated with the event fields unsafe { EventData* eventPayload = stackalloc EventData[4]; eventPayload[0] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)) }; eventPayload[1] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&OriginatingTaskID)) }; eventPayload[2] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&ForkJoinContextID)) }; eventPayload[3] = new EventData { Size = sizeof(long), DataPointer = ((IntPtr)(&TotalIterations)) }; WriteEventCore(PARALLELLOOPEND_ID, 4, eventPayload); } } } #endregion ParallelLoopEnd #region ParallelInvokeBegin /// <summary>Denotes the entry point for a Parallel.Invoke call.</summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The invoke ID.</param> /// <param name="OperationType">The kind of fork/join operation.</param> /// <param name="ActionCount">The number of actions being invoked.</param> [Event(PARALLELINVOKEBEGIN_ID, Level = EventLevel.Informational, Task = ParallelEtwProvider.Tasks.Invoke, Opcode = EventOpcode.Start)] public void ParallelInvokeBegin(int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID, ForkJoinOperationType OperationType, // PFX_FORKJOIN_COMMON_EVENT_HEADER int ActionCount) { if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS)) { // There is no explicit WriteEvent() overload matching this event's fields. // Therefore calling WriteEvent() would hit the "params" overload, which leads to an object allocation every time this event is fired. // To prevent that problem we will call WriteEventCore(), which works with a stack based EventData array populated with the event fields unsafe { EventData* eventPayload = stackalloc EventData[5]; eventPayload[0] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)) }; eventPayload[1] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&OriginatingTaskID)) }; eventPayload[2] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&ForkJoinContextID)) }; eventPayload[3] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&OperationType)) }; eventPayload[4] = new EventData { Size = sizeof(int), DataPointer = ((IntPtr)(&ActionCount)) }; WriteEventCore(PARALLELINVOKEBEGIN_ID, 5, eventPayload); } } } #endregion ParallelInvokeBegin #region ParallelInvokeEnd /// <summary> /// Denotes the exit point for a Parallel.Invoke call. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The invoke ID.</param> [Event(PARALLELINVOKEEND_ID, Level = EventLevel.Informational, Task = ParallelEtwProvider.Tasks.Invoke, Opcode = EventOpcode.Stop)] public void ParallelInvokeEnd(int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID) { if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS)) WriteEvent(PARALLELINVOKEEND_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID); } #endregion ParallelInvokeEnd #region ParallelFork /// <summary> /// Denotes the start of an individual task that's part of a fork/join context. /// Before this event is fired, the start of the new fork/join context will be marked /// with another event that declares a unique context ID. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The invoke ID.</param> [Event(PARALLELFORK_ID, Level = EventLevel.Verbose, Task = ParallelEtwProvider.Tasks.ForkJoin, Opcode = EventOpcode.Start)] public void ParallelFork(int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID) { if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS)) WriteEvent(PARALLELFORK_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID); } #endregion ParallelFork #region ParallelJoin /// <summary> /// Denotes the end of an individual task that's part of a fork/join context. /// This should match a previous ParallelFork event with a matching "OriginatingTaskID" /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The invoke ID.</param> [Event(PARALLELJOIN_ID, Level = EventLevel.Verbose, Task = ParallelEtwProvider.Tasks.ForkJoin, Opcode = EventOpcode.Stop)] public void ParallelJoin(int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID) { if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS)) WriteEvent(PARALLELJOIN_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID); } #endregion ParallelJoin } // class ParallelEtwProvider } // namespace
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.IO.Safe { using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; /// <summary> /// Implements IOutputStream on top of memory buffer /// </summary> public class OutputBuffer : IOutputStream { const int BlockCopyMin = 32; internal byte[] buffer; internal int position; internal int length; /// <summary> /// Gets data inside the buffer /// </summary> public ArraySegment<byte> Data { get { return new ArraySegment<byte>(buffer, 0, position); } } /// <summary> /// Gets or sets the current position within the buffer /// </summary> public virtual long Position { get { return position; } set { position = checked ((int)value); } } public OutputBuffer(int length = 64 * 1024) : this(new byte[length]) {} public OutputBuffer(byte[] buffer) { Debug.Assert(BitConverter.IsLittleEndian); this.buffer = buffer; length = buffer.Length; position = 0; } #region IOutputStream /// <summary> /// Write 8-bit unsigned integer /// </summary> public void WriteUInt8(byte value) { if (position >= length) { Grow(sizeof(byte)); } buffer[position++] = value; } /// <summary> /// Write little-endian encoded 16-bit unsigned integer /// </summary> public void WriteUInt16(ushort value) { if (position + sizeof(ushort) > length) { Grow(sizeof(ushort)); } var i = position; var b = buffer; b[i++] = (byte)value; b[i++] = (byte)(value >> 8); position = i; } /// <summary> /// Write little-endian encoded 32-bit unsigned integer /// </summary> public virtual void WriteUInt32(uint value) { if (position + sizeof(uint) > length) { Grow(sizeof(uint)); } var i = position; var b = buffer; b[i++] = (byte)value; b[i++] = (byte)(value >> 8); b[i++] = (byte)(value >> 16); b[i++] = (byte)(value >> 24); position = i; } /// <summary> /// Write little-endian encoded 64-bit unsigned integer /// </summary> public virtual void WriteUInt64(ulong value) { if (position + sizeof(ulong) > length) { Grow(sizeof(ulong)); } var i = position; var b = buffer; b[i++] = (byte)value; b[i++] = (byte)(value >> 8); b[i++] = (byte)(value >> 16); b[i++] = (byte)(value >> 24); b[i++] = (byte)(value >> 32); b[i++] = (byte)(value >> 40); b[i++] = (byte)(value >> 48); b[i++] = (byte)(value >> 56); position = i; } /// <summary> /// Write little-endian encoded single precision IEEE 754 float /// </summary> public virtual void WriteFloat(float value) { WriteUInt32(new FloatLayout { value = value }.bytes); } /// <summary> /// Write little-endian encoded double precision IEEE 754 float /// </summary> public virtual void WriteDouble(double value) { WriteUInt64(new DoubleLayout { value = value }.bytes); } /// <summary> /// Write an array of bytes verbatim /// </summary> /// <param name="data">Array segment specifying bytes to write</param> public virtual void WriteBytes(ArraySegment<byte> data) { var newOffset = position + data.Count; if (newOffset > length) { Grow(data.Count); } if (data.Count < BlockCopyMin) { for (int i = position, j = data.Offset; i < newOffset; ++i, ++j) { buffer[i] = data.Array[j]; } } else { Buffer.BlockCopy(data.Array, data.Offset, buffer, position, data.Count); } position = newOffset; } /// <summary> /// Write variable encoded 16-bit unsigned integer /// </summary> public void WriteVarUInt16(ushort value) { if (position + IntegerHelper.MaxBytesVarInt16 > length) { Grow(IntegerHelper.MaxBytesVarInt16); } position = IntegerHelper.EncodeVarUInt16(buffer, value, position); } /// <summary> /// Write variable encoded 32-bit unsigned integer /// </summary> public void WriteVarUInt32(uint value) { if (position + IntegerHelper.MaxBytesVarInt32 > length) { Grow(IntegerHelper.MaxBytesVarInt32); } position = IntegerHelper.EncodeVarUInt32(buffer, value, position); } /// <summary> /// Write variable encoded 64-bit unsigned integer /// </summary> public void WriteVarUInt64(ulong value) { if (position + IntegerHelper.MaxBytesVarInt64 > length) { Grow(IntegerHelper.MaxBytesVarInt64); } position = IntegerHelper.EncodeVarUInt64(buffer, value, position); } /// <summary> /// Write UTF-8 or UTF-16 encoded string /// </summary> /// <param name="encoding">String encoding</param> /// <param name="value">String value</param> /// <param name="size">Size in bytes of encoded string</param> public virtual void WriteString(Encoding encoding, string value, int size) { if (position + size > length) { Grow(size); } position += encoding.GetBytes(value, 0, value.Length, buffer, position); } #endregion // Grow the buffer so that there is enough space to write 'count' bytes internal virtual void Grow(int count) { int minLength = checked(position + count); length = checked(length + (length >> 1)); const int ArrayIndexMaxValue = 0x7FFFFFC7; if ((uint)length > ArrayIndexMaxValue) { length = ArrayIndexMaxValue; } else if (length < minLength) { length = minLength; } Array.Resize(ref buffer, length); } #region layouts [StructLayout(LayoutKind.Explicit)] struct DoubleLayout { [FieldOffset(0)] public readonly ulong bytes; [FieldOffset(0)] public double value; } [StructLayout(LayoutKind.Explicit)] struct FloatLayout { [FieldOffset(0)] public readonly uint bytes; [FieldOffset(0)] public float value; } #endregion } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.DotNet.Cli.Utils; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace Microsoft.DotNet.Tools.Test.Utilities { public class TestCommand { private string _baseDirectory; private List<string> _cliGeneratedEnvironmentVariables = new List<string> { "MSBuildSDKsPath" }; protected string _command; public Process CurrentProcess { get; private set; } public Dictionary<string, string> Environment { get; } = new Dictionary<string, string>(); public event DataReceivedEventHandler ErrorDataReceived; public event DataReceivedEventHandler OutputDataReceived; public string WorkingDirectory { get; set; } public TestCommand(string command) { _command = command; _baseDirectory = GetBaseDirectory(); } public void KillTree() { if (CurrentProcess == null) { throw new InvalidOperationException("No process is available to be killed"); } CurrentProcess.KillTree(); } public virtual CommandResult Execute(string args = "") { return Task.Run(async () => await ExecuteAsync(args)).Result; } public async virtual Task<CommandResult> ExecuteAsync(string args = "") { var resolvedCommand = _command; ResolveCommand(ref resolvedCommand, ref args); Console.WriteLine($"Executing - {resolvedCommand} {args} - {WorkingDirectoryInfo()}"); return await ExecuteAsyncInternal(resolvedCommand, args); } public virtual CommandResult ExecuteWithCapturedOutput(string args = "") { var resolvedCommand = _command; ResolveCommand(ref resolvedCommand, ref args); Console.WriteLine($"Executing (Captured Output) - {resolvedCommand} {args} - {WorkingDirectoryInfo()}"); return Task.Run(async () => await ExecuteAsyncInternal(resolvedCommand, args)).Result; } private async Task<CommandResult> ExecuteAsyncInternal(string executable, string args) { var stdOut = new List<String>(); var stdErr = new List<String>(); CurrentProcess = CreateProcess(executable, args); CurrentProcess.ErrorDataReceived += (s, e) => { stdErr.Add(e.Data); var handler = ErrorDataReceived; if (handler != null) { handler(s, e); } }; CurrentProcess.OutputDataReceived += (s, e) => { stdOut.Add(e.Data); var handler = OutputDataReceived; if (handler != null) { handler(s, e); } }; var completionTask = CurrentProcess.StartAndWaitForExitAsync(); CurrentProcess.BeginOutputReadLine(); CurrentProcess.BeginErrorReadLine(); await completionTask; CurrentProcess.WaitForExit(); RemoveNullTerminator(stdOut); RemoveNullTerminator(stdErr); return new CommandResult( CurrentProcess.StartInfo, CurrentProcess.ExitCode, String.Join(System.Environment.NewLine, stdOut), String.Join(System.Environment.NewLine, stdErr)); } private Process CreateProcess(string executable, string args) { var psi = new ProcessStartInfo { FileName = executable, Arguments = args, RedirectStandardError = true, RedirectStandardOutput = true, RedirectStandardInput = true, UseShellExecute = false }; RemoveCliGeneratedEnvironmentVariablesFrom(psi); AddEnvironmentVariablesTo(psi); AddWorkingDirectoryTo(psi); var process = new Process { StartInfo = psi }; process.EnableRaisingEvents = true; return process; } private string WorkingDirectoryInfo() { if (WorkingDirectory == null) { return ""; } return $" in pwd {WorkingDirectory}"; } private void RemoveNullTerminator(List<string> strings) { var count = strings.Count; if (count < 1) { return; } if (strings[count - 1] == null) { strings.RemoveAt(count - 1); } } private string GetBaseDirectory() { #if NET451 return AppDomain.CurrentDomain.BaseDirectory; #else return AppContext.BaseDirectory; #endif } private void ResolveCommand(ref string executable, ref string args) { if (executable.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { var newArgs = ArgumentEscaper.EscapeSingleArg(executable); if (!string.IsNullOrEmpty(args)) { newArgs += " " + args; } args = newArgs; executable = new Muxer().MuxerPath; } else if ( executable == "dotnet") { executable = new Muxer().MuxerPath; } else if (!Path.IsPathRooted(executable)) { executable = Env.GetCommandPath(executable) ?? Env.GetCommandPathFromRootPath(_baseDirectory, executable); } } private void RemoveCliGeneratedEnvironmentVariablesFrom(ProcessStartInfo psi) { foreach (var name in _cliGeneratedEnvironmentVariables) { #if NET451 psi.EnvironmentVariables.Remove(name); #else psi.Environment.Remove(name); #endif } } private void AddEnvironmentVariablesTo(ProcessStartInfo psi) { foreach (var item in Environment) { #if NET451 psi.EnvironmentVariables[item.Key] = item.Value; #else psi.Environment[item.Key] = item.Value; #endif } } private void AddWorkingDirectoryTo(ProcessStartInfo psi) { if (!string.IsNullOrWhiteSpace(WorkingDirectory)) { psi.WorkingDirectory = WorkingDirectory; } } } }
#if ASYNC // Copyright (c) ServiceStack, Inc. All Rights Reserved. // License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading; using System.Threading.Tasks; using ServiceStack.Data; using ServiceStack.Logging; namespace ServiceStack.OrmLite { internal static class OrmLiteWriteCommandExtensionsAsync { internal static ILog Log = LogManager.GetLogger(typeof(OrmLiteWriteCommandExtensionsAsync)); internal static Task<int> ExecuteSqlAsync(this IDbCommand dbCmd, string sql, IEnumerable<IDbDataParameter> sqlParams, CancellationToken token) { return dbCmd.SetParameters(sqlParams).ExecuteSqlAsync(sql, token); } internal static Task<int> ExecuteSqlAsync(this IDbCommand dbCmd, string sql, CancellationToken token) { dbCmd.CommandText = sql; if (Log.IsDebugEnabled) Log.DebugCommand(dbCmd); OrmLiteConfig.BeforeExecFilter?.Invoke(dbCmd); if (OrmLiteConfig.ResultsFilter != null) return OrmLiteConfig.ResultsFilter.ExecuteSql(dbCmd).InTask(); return dbCmd.GetDialectProvider().ExecuteNonQueryAsync(dbCmd, token); } internal static Task<int> ExecuteSqlAsync(this IDbCommand dbCmd, string sql, object anonType, CancellationToken token) { if (anonType != null) dbCmd.SetParameters(anonType.ToObjectDictionary(), excludeDefaults: false, sql:ref sql); dbCmd.CommandText = sql; if (Log.IsDebugEnabled) Log.DebugCommand(dbCmd); OrmLiteConfig.BeforeExecFilter?.Invoke(dbCmd); if (OrmLiteConfig.ResultsFilter != null) return OrmLiteConfig.ResultsFilter.ExecuteSql(dbCmd).InTask(); return dbCmd.GetDialectProvider().ExecuteNonQueryAsync(dbCmd, token); } internal static async Task<int> UpdateAsync<T>(this IDbCommand dbCmd, T obj, CancellationToken token, Action<IDbCommand> commandFilter) { OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, obj); var dialectProvider = dbCmd.GetDialectProvider(); var hadRowVersion = dialectProvider.PrepareParameterizedUpdateStatement<T>(dbCmd); if (string.IsNullOrEmpty(dbCmd.CommandText)) return 0; dialectProvider.SetParameterValues<T>(dbCmd, obj); commandFilter?.Invoke(dbCmd); var rowsUpdated = await dialectProvider.ExecuteNonQueryAsync(dbCmd, token); if (hadRowVersion && rowsUpdated == 0) throw new OptimisticConcurrencyException(); return rowsUpdated; } internal static Task<int> UpdateAsync<T>(this IDbCommand dbCmd, Action<IDbCommand> commandFilter, CancellationToken token, T[] objs) { return dbCmd.UpdateAllAsync(objs, commandFilter, token); } internal static async Task<int> UpdateAllAsync<T>(this IDbCommand dbCmd, IEnumerable<T> objs, Action<IDbCommand> commandFilter, CancellationToken token) { IDbTransaction dbTrans = null; int count = 0; if (dbCmd.Transaction == null) dbCmd.Transaction = dbTrans = dbCmd.Connection.BeginTransaction(); var dialectProvider = dbCmd.GetDialectProvider(); var hadRowVersion = dialectProvider.PrepareParameterizedUpdateStatement<T>(dbCmd); if (string.IsNullOrEmpty(dbCmd.CommandText)) return 0; using (dbTrans) { foreach (var obj in objs) { OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, obj); dialectProvider.SetParameterValues<T>(dbCmd, obj); commandFilter?.Invoke(dbCmd); commandFilter = null; var rowsUpdated = await dbCmd.ExecNonQueryAsync(token); if (hadRowVersion && rowsUpdated == 0) throw new OptimisticConcurrencyException(); count += rowsUpdated; } dbTrans?.Commit(); } return count; } private static async Task<int> AssertRowsUpdatedAsync(IDbCommand dbCmd, bool hadRowVersion, CancellationToken token) { var rowsUpdated = await dbCmd.ExecNonQueryAsync(token); if (hadRowVersion && rowsUpdated == 0) throw new OptimisticConcurrencyException(); return rowsUpdated; } internal static Task<int> DeleteAsync<T>(this IDbCommand dbCmd, T filter, CancellationToken token) { return dbCmd.DeleteAsync<T>((object)filter, token); } internal static Task<int> DeleteAsync<T>(this IDbCommand dbCmd, object anonType, CancellationToken token) { var dialectProvider = dbCmd.GetDialectProvider(); var hadRowVersion = dialectProvider.PrepareParameterizedDeleteStatement<T>( dbCmd, anonType.AllFieldsMap<T>()); dialectProvider.SetParameterValues<T>(dbCmd, anonType); return AssertRowsUpdatedAsync(dbCmd, hadRowVersion, token); } internal static Task<int> DeleteNonDefaultsAsync<T>(this IDbCommand dbCmd, T filter, CancellationToken token) { var dialectProvider = dbCmd.GetDialectProvider(); var hadRowVersion = dialectProvider.PrepareParameterizedDeleteStatement<T>( dbCmd, filter.AllFieldsMap<T>().NonDefaultsOnly()); dialectProvider.SetParameterValues<T>(dbCmd, filter); return AssertRowsUpdatedAsync(dbCmd, hadRowVersion, token); } internal static Task<int> DeleteAsync<T>(this IDbCommand dbCmd, CancellationToken token, params T[] objs) { if (objs.Length == 0) return TaskResult.Zero; return DeleteAllAsync(dbCmd, objs, fieldValuesFn:null, token: token); } internal static Task<int> DeleteNonDefaultsAsync<T>(this IDbCommand dbCmd, CancellationToken token, params T[] filters) { if (filters.Length == 0) return TaskResult.Zero; return DeleteAllAsync(dbCmd, filters, o => o.AllFieldsMap<T>().NonDefaultsOnly(), token); } private static async Task<int> DeleteAllAsync<T>(IDbCommand dbCmd, IEnumerable<T> objs, Func<object, Dictionary<string, object>> fieldValuesFn = null, CancellationToken token=default(CancellationToken)) { IDbTransaction dbTrans = null; int count = 0; if (dbCmd.Transaction == null) dbCmd.Transaction = dbTrans = dbCmd.Connection.BeginTransaction(); var dialectProvider = dbCmd.GetDialectProvider(); using (dbTrans) { foreach (var obj in objs) { var fieldValues = fieldValuesFn != null ? fieldValuesFn(obj) : obj.AllFieldsMap<T>(); dialectProvider.PrepareParameterizedDeleteStatement<T>(dbCmd, fieldValues); dialectProvider.SetParameterValues<T>(dbCmd, obj); var rowsAffected = await dbCmd.ExecNonQueryAsync(token); count += rowsAffected; } dbTrans?.Commit(); } return count; } internal static Task<int> DeleteByIdAsync<T>(this IDbCommand dbCmd, object id, CancellationToken token) { var sql = dbCmd.DeleteByIdSql<T>(id); return dbCmd.ExecuteSqlAsync(sql, token); } internal static async Task DeleteByIdAsync<T>(this IDbCommand dbCmd, object id, ulong rowVersion, CancellationToken token) { var sql = dbCmd.DeleteByIdSql<T>(id, rowVersion); var rowsAffected = await dbCmd.ExecuteSqlAsync(sql, token); if (rowsAffected == 0) throw new OptimisticConcurrencyException("The row was modified or deleted since the last read"); } internal static Task<int> DeleteByIdsAsync<T>(this IDbCommand dbCmd, IEnumerable idValues, CancellationToken token) { var sqlIn = dbCmd.SetIdsInSqlParams(idValues); if (string.IsNullOrEmpty(sqlIn)) return TaskResult.Zero; var sql = OrmLiteWriteCommandExtensions.GetDeleteByIdsSql<T>(sqlIn, dbCmd.GetDialectProvider()); return dbCmd.ExecuteSqlAsync(sql, token); } internal static Task<int> DeleteAllAsync<T>(this IDbCommand dbCmd, CancellationToken token) { return DeleteAllAsync(dbCmd, typeof(T), token); } internal static Task<int> DeleteAllAsync(this IDbCommand dbCmd, Type tableType, CancellationToken token) { var dialectProvider = dbCmd.GetDialectProvider(); return dbCmd.ExecuteSqlAsync(dialectProvider.ToDeleteStatement(tableType, null), token); } internal static Task<int> DeleteAsync<T>(this IDbCommand dbCmd, string sql, object anonType, CancellationToken token) { if (anonType != null) dbCmd.SetParameters<T>(anonType, excludeDefaults: false, sql: ref sql); return dbCmd.ExecuteSqlAsync(dbCmd.GetDialectProvider().ToDeleteStatement(typeof(T), sql), token); } internal static Task<int> DeleteAsync(this IDbCommand dbCmd, Type tableType, string sql, object anonType, CancellationToken token) { if (anonType != null) dbCmd.SetParameters(tableType, anonType, excludeDefaults: false, sql: ref sql); return dbCmd.ExecuteSqlAsync(dbCmd.GetDialectProvider().ToDeleteStatement(tableType, sql), token); } internal static async Task<long> InsertAsync<T>(this IDbCommand dbCmd, T obj, Action<IDbCommand> commandFilter, bool selectIdentity, CancellationToken token) { OrmLiteConfig.InsertFilter?.Invoke(dbCmd, obj); var dialectProvider = dbCmd.GetDialectProvider(); dialectProvider.PrepareParameterizedInsertStatement<T>(dbCmd, insertFields: dialectProvider.GetNonDefaultValueInsertFields(obj)); dialectProvider.SetParameterValues<T>(dbCmd, obj); commandFilter?.Invoke(dbCmd); if (dialectProvider.HasInsertReturnValues(ModelDefinition<T>.Definition)) { using (var reader = await dbCmd.ExecReaderAsync(dbCmd.CommandText, token)) using (reader) { return reader.PopulateReturnValues(dialectProvider, obj); } } if (selectIdentity) return await dialectProvider.InsertAndGetLastInsertIdAsync<T>(dbCmd, token); return await dbCmd.ExecNonQueryAsync(token); } internal static Task InsertAsync<T>(this IDbCommand dbCmd, Action<IDbCommand> commandFilter, CancellationToken token, T[] objs) { return InsertAllAsync(dbCmd, objs, commandFilter, token); } internal static async Task InsertUsingDefaultsAsync<T>(this IDbCommand dbCmd, T[] objs, CancellationToken token) { IDbTransaction dbTrans = null; if (dbCmd.Transaction == null) dbCmd.Transaction = dbTrans = dbCmd.Connection.BeginTransaction(); var dialectProvider = dbCmd.GetDialectProvider(); var modelDef = typeof(T).GetModelDefinition(); var fieldsWithoutDefaults = modelDef.FieldDefinitionsArray .Where(x => x.DefaultValue == null) .Select(x => x.Name) .ToHashSet(); dialectProvider.PrepareParameterizedInsertStatement<T>(dbCmd, insertFields: fieldsWithoutDefaults); using (dbTrans) { foreach (var obj in objs) { OrmLiteConfig.InsertFilter?.Invoke(dbCmd, obj); dialectProvider.SetParameterValues<T>(dbCmd, obj); await dbCmd.ExecNonQueryAsync(token); } dbTrans?.Commit(); } } internal static async Task<long> InsertIntoSelectAsync<T>(this IDbCommand dbCmd, ISqlExpression query, Action<IDbCommand> commandFilter, CancellationToken token) => OrmLiteReadCommandExtensions.ToLong(await dbCmd.InsertIntoSelectInternal<T>(query, commandFilter).ExecNonQueryAsync(token: token)); internal static async Task InsertAllAsync<T>(this IDbCommand dbCmd, IEnumerable<T> objs, Action<IDbCommand> commandFilter, CancellationToken token) { IDbTransaction dbTrans = null; if (dbCmd.Transaction == null) dbCmd.Transaction = dbTrans = dbCmd.Connection.BeginTransaction(); var dialectProvider = dbCmd.GetDialectProvider(); dialectProvider.PrepareParameterizedInsertStatement<T>(dbCmd); commandFilter?.Invoke(dbCmd); using (dbTrans) { foreach (var obj in objs) { OrmLiteConfig.InsertFilter?.Invoke(dbCmd, obj); dialectProvider.SetParameterValues<T>(dbCmd, obj); await dbCmd.ExecNonQueryAsync(token); } dbTrans?.Commit(); } } internal static Task<int> SaveAsync<T>(this IDbCommand dbCmd, CancellationToken token, params T[] objs) { return SaveAllAsync(dbCmd, objs, token); } internal static async Task<bool> SaveAsync<T>(this IDbCommand dbCmd, T obj, CancellationToken token) { var modelDef = typeof(T).GetModelDefinition(); var id = modelDef.GetPrimaryKey(obj); var existingRow = id != null ? await dbCmd.SingleByIdAsync<T>(id, token) : default(T); if (Equals(existingRow, default(T))) { if (modelDef.HasAutoIncrementId) { var newId = await dbCmd.InsertAsync(obj, commandFilter: null, selectIdentity: true, token:token); var safeId = dbCmd.GetDialectProvider().FromDbValue(newId, modelDef.PrimaryKey.FieldType); modelDef.PrimaryKey.SetValueFn(obj, safeId); id = newId; } else { await dbCmd.InsertAsync(obj, commandFilter:null, selectIdentity:false, token:token); } modelDef.RowVersion?.SetValueFn(obj, await dbCmd.GetRowVersionAsync(modelDef, id, token)); return true; } await dbCmd.UpdateAsync(obj, token, null); modelDef.RowVersion?.SetValueFn(obj, await dbCmd.GetRowVersionAsync(modelDef, id, token)); return false; } internal static async Task<int> SaveAllAsync<T>(this IDbCommand dbCmd, IEnumerable<T> objs, CancellationToken token) { var saveRows = objs.ToList(); var firstRow = saveRows.FirstOrDefault(); if (Equals(firstRow, default(T))) return 0; var modelDef = typeof(T).GetModelDefinition(); var firstRowId = modelDef.GetPrimaryKey(firstRow); var defaultIdValue = firstRowId?.GetType().GetDefaultValue(); var idMap = defaultIdValue != null ? saveRows.Where(x => !defaultIdValue.Equals(modelDef.GetPrimaryKey(x))).ToSafeDictionary(x => modelDef.GetPrimaryKey(x)) : saveRows.Where(x => modelDef.GetPrimaryKey(x) != null).ToSafeDictionary(x => modelDef.GetPrimaryKey(x)); var existingRowsMap = (await dbCmd.SelectByIdsAsync<T>(idMap.Keys, token)).ToDictionary(x => modelDef.GetPrimaryKey(x)); var rowsAdded = 0; IDbTransaction dbTrans = null; if (dbCmd.Transaction == null) dbCmd.Transaction = dbTrans = dbCmd.Connection.BeginTransaction(); var dialectProvider = dbCmd.GetDialectProvider(); using (dbTrans) { foreach (var row in saveRows) { var id = modelDef.GetPrimaryKey(row); if (id != defaultIdValue && existingRowsMap.ContainsKey(id)) { await dbCmd.UpdateAsync(row, token, null); } else { if (modelDef.HasAutoIncrementId) { var newId = await dbCmd.InsertAsync(row, commandFilter:null, selectIdentity:true, token:token); var safeId = dialectProvider.FromDbValue(newId, modelDef.PrimaryKey.FieldType); modelDef.PrimaryKey.SetValueFn(row, safeId); id = newId; } else { await dbCmd.InsertAsync(row, commandFilter:null, selectIdentity:false, token:token); } rowsAdded++; } modelDef.RowVersion?.SetValueFn(row, await dbCmd.GetRowVersionAsync(modelDef, id, token)); } dbTrans?.Commit(); } return rowsAdded; } public static async Task SaveAllReferencesAsync<T>(this IDbCommand dbCmd, T instance, CancellationToken token) { var modelDef = ModelDefinition<T>.Definition; var pkValue = modelDef.PrimaryKey.GetValue(instance); var fieldDefs = modelDef.AllFieldDefinitionsArray.Where(x => x.IsReference); foreach (var fieldDef in fieldDefs) { var listInterface = fieldDef.FieldType.GetTypeWithGenericInterfaceOf(typeof(IList<>)); if (listInterface != null) { var refType = listInterface.GetGenericArguments()[0]; var refModelDef = refType.GetModelDefinition(); var refField = modelDef.GetRefFieldDef(refModelDef, refType); var results = (IEnumerable)fieldDef.GetValue(instance); if (results != null) { foreach (var oRef in results) { refField.SetValueFn(oRef, pkValue); } await dbCmd.CreateTypedApi(refType).SaveAllAsync(results, token); } } else { var refType = fieldDef.FieldType; var refModelDef = refType.GetModelDefinition(); var refSelf = modelDef.GetSelfRefFieldDefIfExists(refModelDef, fieldDef); var result = fieldDef.GetValue(instance); var refField = refSelf == null ? modelDef.GetRefFieldDef(refModelDef, refType) : modelDef.GetRefFieldDefIfExists(refModelDef); if (result != null) { refField?.SetValueFn(result, pkValue); await dbCmd.CreateTypedApi(refType).SaveAsync(result, token); //Save Self Table.RefTableId PK if (refSelf != null) { var refPkValue = refModelDef.PrimaryKey.GetValue(result); refSelf.SetValueFn(instance, refPkValue); await dbCmd.UpdateAsync(instance, token, null); } } } } } public static async Task SaveReferencesAsync<T, TRef>(this IDbCommand dbCmd, CancellationToken token, T instance, params TRef[] refs) { var modelDef = ModelDefinition<T>.Definition; var pkValue = modelDef.PrimaryKey.GetValue(instance); var refType = typeof(TRef); var refModelDef = ModelDefinition<TRef>.Definition; var refSelf = modelDef.GetSelfRefFieldDefIfExists(refModelDef, null); foreach (var oRef in refs) { var refField = refSelf == null ? modelDef.GetRefFieldDef(refModelDef, refType) : modelDef.GetRefFieldDefIfExists(refModelDef); refField?.SetValueFn(oRef, pkValue); } await dbCmd.SaveAllAsync(refs, token); foreach (var oRef in refs) { //Save Self Table.RefTableId PK if (refSelf != null) { var refPkValue = refModelDef.PrimaryKey.GetValue(oRef); refSelf.SetValueFn(instance, refPkValue); await dbCmd.UpdateAsync(instance, token, null); } } } // Procedures internal static Task ExecuteProcedureAsync<T>(this IDbCommand dbCommand, T obj, CancellationToken token) { var dialectProvider = dbCommand.GetDialectProvider(); string sql = dialectProvider.ToExecuteProcedureStatement(obj); dbCommand.CommandType = CommandType.StoredProcedure; return dbCommand.ExecuteSqlAsync(sql, token); } internal static async Task<object> GetRowVersionAsync(this IDbCommand dbCmd, ModelDefinition modelDef, object id, CancellationToken token) { var sql = dbCmd.RowVersionSql(modelDef, id); var rowVersion = await dbCmd.ScalarAsync<object>(sql, token); return dbCmd.GetDialectProvider().FromDbRowVersion(modelDef.RowVersion.FieldType, rowVersion); } } } #endif
namespace System.Threading.Tasks { public static partial class TaskFactoryExtensions { public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay) { return StartNewDelayed(factory, millisecondsDelay, CancellationToken.None); } public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken) { // Validate arguments if (factory == null) throw new ArgumentNullException("factory"); if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay"); // Create the timed task var tcs = new TaskCompletionSource<object>(factory.CreationOptions); var ctr = default(CancellationTokenRegistration); // Create the timer but don't start it yet. If we start it now, // it might fire before ctr has been set to the right registration. var timer = new Timer(self => { // Clean up both the cancellation token and the timer, and try to transition to completed ctr.Dispose(); ((Timer)self).Dispose(); tcs.TrySetResult(null); }); // Register with the cancellation token. if (cancellationToken.CanBeCanceled) { // When cancellation occurs, cancel the timer and try to transition to canceled. // There could be a race, but it's benign. ctr = cancellationToken.Register(() => { timer.Dispose(); tcs.TrySetCanceled(); }); } // Start the timer and hand back the task... timer.Change(millisecondsDelay, Timeout.Infinite); return tcs.Task; } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action action) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, factory.CancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action action, TaskCreationOptions creationOptions) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, factory.CancellationToken, creationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action action, CancellationToken cancellationToken) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, cancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { if (factory == null) throw new ArgumentNullException("factory"); if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay"); if (action == null) throw new ArgumentNullException("action"); if (scheduler == null) throw new ArgumentNullException("scheduler"); return factory .StartNewDelayed(millisecondsDelay, cancellationToken) .ContinueWith(_ => action(), cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, scheduler); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action<object> action, object state) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, state, factory.CancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action<object> action, object state, TaskCreationOptions creationOptions) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, state, factory.CancellationToken, creationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action<object> action, object state, CancellationToken cancellationToken) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, state, cancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { if (factory == null) throw new ArgumentNullException("factory"); if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay"); if (action == null) throw new ArgumentNullException("action"); if (scheduler == null) throw new ArgumentNullException("scheduler"); // Create the task that will be returned; workaround for no ContinueWith(..., state) overload. var result = new TaskCompletionSource<object>(state); // Delay a continuation to run the action factory .StartNewDelayed(millisecondsDelay, cancellationToken) .ContinueWith(t => { if (t.IsCanceled) result.TrySetCanceled(); else { try { action(state); result.TrySetResult(null); } catch (Exception exc) { result.TrySetException(exc); } } }, scheduler); // Return the task return result.Task; } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<TResult> function) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, factory.CancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<TResult> function, TaskCreationOptions creationOptions) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, factory.CancellationToken, creationOptions, factory.GetTargetScheduler()); } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<TResult> function, CancellationToken cancellationToken) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, cancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { if (factory == null) throw new ArgumentNullException("factory"); if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay"); if (function == null) throw new ArgumentNullException("function"); if (scheduler == null) throw new ArgumentNullException("scheduler"); // Create the trigger and the timer to start it var tcs = new TaskCompletionSource<object>(); var timer = new Timer(obj => ((TaskCompletionSource<object>)obj).SetResult(null), tcs, millisecondsDelay, Timeout.Infinite); // Return a task that executes the function when the trigger fires return tcs.Task.ContinueWith(_ => { timer.Dispose(); return function(); }, cancellationToken, ContinuationOptionsFromCreationOptions(creationOptions), scheduler); } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<object, TResult> function, object state) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, state, factory.CancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<object, TResult> function, object state, CancellationToken cancellationToken) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, state, cancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } /// <summary>Creates and schedules a task for execution after the specified time delay.</summary> /// <param name="factory">The factory to use to create the task.</param> /// <param name="millisecondsDelay">The delay after which the task will be scheduled.</param> /// <param name="function">The delegate executed by the task.</param> /// <param name="state">An object provided to the delegate.</param> /// <param name="creationOptions">Options that control the task's behavior.</param> /// <returns>The created Task.</returns> public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<object, TResult> function, object state, TaskCreationOptions creationOptions) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, state, factory.CancellationToken, creationOptions, factory.GetTargetScheduler()); } /// <summary>Creates and schedules a task for execution after the specified time delay.</summary> /// <param name="factory">The factory to use to create the task.</param> /// <param name="millisecondsDelay">The delay after which the task will be scheduled.</param> /// <param name="function">The delegate executed by the task.</param> /// <param name="state">An object provided to the delegate.</param> /// <param name="cancellationToken">The CancellationToken to assign to the Task.</param> /// <param name="creationOptions">Options that control the task's behavior.</param> /// <param name="scheduler">The scheduler to which the Task will be scheduled.</param> /// <returns>The created Task.</returns> public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { if (factory == null) throw new ArgumentNullException("factory"); if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay"); if (function == null) throw new ArgumentNullException("action"); if (scheduler == null) throw new ArgumentNullException("scheduler"); // Create the task that will be returned var result = new TaskCompletionSource<TResult>(state); Timer timer = null; // Create the task that will run the user's function var functionTask = new Task<TResult>(function, state, creationOptions); // When the function task completes, transfer the results to the returned task functionTask.ContinueWith(t => { result.SetFromTask(t); timer.Dispose(); }, cancellationToken, ContinuationOptionsFromCreationOptions(creationOptions) | TaskContinuationOptions.ExecuteSynchronously, scheduler); // Start the timer for the trigger timer = new Timer(obj => ((Task)obj).Start(scheduler), functionTask, millisecondsDelay, Timeout.Infinite); return result.Task; } /// <summary>Gets the TaskScheduler instance that should be used to schedule tasks.</summary> public static TaskScheduler GetTargetScheduler(this TaskFactory factory) { if (factory == null) throw new ArgumentNullException("factory"); return factory.Scheduler ?? TaskScheduler.Current; } /// <summary>Gets the TaskScheduler instance that should be used to schedule tasks.</summary> public static TaskScheduler GetTargetScheduler<TResult>(this TaskFactory<TResult> factory) { if (factory == null) throw new ArgumentNullException("factory"); return factory.Scheduler != null ? factory.Scheduler : TaskScheduler.Current; } /// <summary>Converts TaskCreationOptions into TaskContinuationOptions.</summary> /// <param name="creationOptions"></param> /// <returns></returns> private static TaskContinuationOptions ContinuationOptionsFromCreationOptions(TaskCreationOptions creationOptions) { return (TaskContinuationOptions) ((creationOptions & TaskCreationOptions.AttachedToParent) | (creationOptions & TaskCreationOptions.PreferFairness) | (creationOptions & TaskCreationOptions.LongRunning)); } } }
using System; using System.Linq; using Akka.Actor; using Akka.Event; using Akka.MultiNodeTestRunner.Shared.Reporting; namespace Akka.MultiNodeTestRunner.Shared.Sinks { /// <summary> /// <see cref="MessageSinkActor"/> implementation that logs all of its output directly to the <see cref="Console"/>. /// /// Has no persitence capabilities. Can optionally use a <see cref="TestRunCoordinator"/> to provide total "end of test" reporting. /// </summary> public class ConsoleMessageSinkActor : TestCoordinatorEnabledMessageSink { public ConsoleMessageSinkActor(bool useTestCoordinator) : base(useTestCoordinator) { } #region Message handling protected override void AdditionalReceives() { Receive<FactData>(data => ReceiveFactData(data)); } protected override void ReceiveFactData(FactData data) { PrintSpecRunResults(data); } private void PrintSpecRunResults(FactData data) { WriteSpecMessage(string.Format("Results for {0}", data.FactName)); WriteSpecMessage(string.Format("Start time: {0}", new DateTime(data.StartTime, DateTimeKind.Utc))); foreach (var node in data.NodeFacts) { WriteSpecMessage(string.Format(" --> Node {0}: {1} [{2} elapsed]", node.Value.NodeIndex, node.Value.Passed.GetValueOrDefault(false) ? "PASS" : "FAIL", node.Value.Elapsed)); } WriteSpecMessage(string.Format("End time: {0}", new DateTime(data.EndTime.GetValueOrDefault(DateTime.UtcNow.Ticks), DateTimeKind.Utc))); WriteSpecMessage(string.Format("FINAL RESULT: {0} after {1}.", data.Passed.GetValueOrDefault(false) ? "PASS" : "FAIL", data.Elapsed)); //If we had a failure if (data.Passed.GetValueOrDefault(false) == false) { WriteSpecMessage("Failure messages by Node"); foreach (var node in data.NodeFacts) { if (node.Value.Passed.GetValueOrDefault(false) == false) { WriteSpecMessage(string.Format("<----------- BEGIN NODE {0} ----------->", node.Key)); foreach (var resultMessage in node.Value.ResultMessages) { WriteSpecMessage(String.Format(" --> {0}", resultMessage.Message)); } if(node.Value.ResultMessages == null || node.Value.ResultMessages.Count == 0) WriteSpecMessage("[received no messages - SILENT FAILURE]."); WriteSpecMessage(string.Format("<----------- END NODE {0} ----------->", node.Key)); } } } } protected override void HandleNodeSpecFail(NodeCompletedSpecWithFail nodeFail) { WriteSpecFail(nodeFail.NodeIndex, nodeFail.Message); base.HandleNodeSpecFail(nodeFail); } protected override void HandleTestRunEnd(EndTestRun endTestRun) { WriteSpecMessage("Test run complete."); base.HandleTestRunEnd(endTestRun); } protected override void HandleTestRunTree(TestRunTree tree) { var passedSpecs = tree.Specs.Count(x => x.Passed.GetValueOrDefault(false)); WriteSpecMessage(string.Format("Test run completed in [{0}] with {1}/{2} specs passed.", tree.Elapsed, passedSpecs, tree.Specs.Count())); foreach (var factData in tree.Specs) { PrintSpecRunResults(factData); } } protected override void HandleNewSpec(BeginNewSpec newSpec) { WriteSpecMessage(string.Format("Beginning spec {0}.{1} on {2} nodes", newSpec.ClassName, newSpec.MethodName, newSpec.Nodes.Count)); base.HandleNewSpec(newSpec); } protected override void HandleEndSpec(EndSpec endSpec) { WriteSpecMessage("Spec completed."); base.HandleEndSpec(endSpec); } protected override void HandleNodeMessage(LogMessageForNode logMessage) { WriteNodeMessage(logMessage); base.HandleNodeMessage(logMessage); } protected override void HandleNodeMessageFragment(LogMessageFragmentForNode logMessage) { WriteNodeMessage(logMessage); base.HandleNodeMessageFragment(logMessage); } protected override void HandleRunnerMessage(LogMessageForTestRunner node) { WriteRunnerMessage(node); base.HandleRunnerMessage(node); } protected override void HandleNodeSpecPass(NodeCompletedSpecWithSuccess nodeSuccess) { WriteSpecPass(nodeSuccess.NodeIndex, nodeSuccess.Message); base.HandleNodeSpecPass(nodeSuccess); } #endregion #region Console output methods /// <summary> /// Used to print a spec status message (spec starting, finishing, failed, etc...) /// </summary> private void WriteSpecMessage(string message) { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("[RUNNER][{0}]: {1}", DateTime.UtcNow.ToShortTimeString(), message); Console.ResetColor(); } private void WriteSpecPass(int nodeIndex, string message) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[NODE{0}][{1}]: SPEC PASSED: {2}", nodeIndex, DateTime.UtcNow.ToShortTimeString(), message); Console.ResetColor(); } private void WriteSpecFail(int nodeIndex, string message) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[NODE{0}][{1}]: SPEC FAILED: {2}", nodeIndex, DateTime.UtcNow.ToShortTimeString(), message); Console.ResetColor(); } private void WriteRunnerMessage(LogMessageForTestRunner nodeMessage) { Console.ForegroundColor = ColorForLogLevel(nodeMessage.Level); Console.WriteLine(nodeMessage.ToString()); Console.ResetColor(); } private void WriteNodeMessage(LogMessageForNode nodeMessage) { Console.ForegroundColor = ColorForLogLevel(nodeMessage.Level); Console.WriteLine(nodeMessage.ToString()); Console.ResetColor(); } private void WriteNodeMessage(LogMessageFragmentForNode nodeMessage) { Console.WriteLine(nodeMessage.ToString()); } private static ConsoleColor ColorForLogLevel(LogLevel level) { var color = ConsoleColor.DarkGray; switch (level) { case LogLevel.DebugLevel: color = ConsoleColor.Gray; break; case LogLevel.InfoLevel: color = ConsoleColor.White; break; case LogLevel.WarningLevel: color = ConsoleColor.Yellow; break; case LogLevel.ErrorLevel: color = ConsoleColor.Red; break; } return color; } #endregion } /// <summary> /// <see cref="IMessageSink"/> implementation that writes directly to the console. /// </summary> public class ConsoleMessageSink : MessageSink { public ConsoleMessageSink() : base(Props.Create(() => new ConsoleMessageSinkActor(true))) { } protected override void HandleUnknownMessageType(string message) { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Unknown message: {0}", message); Console.ResetColor(); } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudioTools.Project { // This class is No longer used by project system, retained for backwards for languages // which have already shipped this public type. #if SHAREDPROJECT_OLESERVICEPROVIDER public class OleServiceProvider : IOleServiceProvider, IDisposable { #region Public Types [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public delegate object ServiceCreatorCallback(Type serviceType); #endregion #region Private Types private class ServiceData : IDisposable { private Type serviceType; private object instance; private ServiceCreatorCallback creator; private bool shouldDispose; public ServiceData(Type serviceType, object instance, ServiceCreatorCallback callback, bool shouldDispose) { Utilities.ArgumentNotNull("serviceType", serviceType); if ((null == instance) && (null == callback)) { throw new ArgumentNullException("instance"); } this.serviceType = serviceType; this.instance = instance; this.creator = callback; this.shouldDispose = shouldDispose; } public object ServiceInstance { get { if (null == instance) { Debug.Assert(serviceType != null); instance = creator(serviceType); } return instance; } } public Guid Guid { get { return serviceType.GUID; } } public void Dispose() { if ((shouldDispose) && (null != instance)) { IDisposable disp = instance as IDisposable; if (null != disp) { disp.Dispose(); } instance = null; } creator = null; GC.SuppressFinalize(this); } } #endregion #region fields private Dictionary<Guid, ServiceData> services = new Dictionary<Guid, ServiceData>(); private bool isDisposed; /// <summary> /// Defines an object that will be a mutex for this object for synchronizing thread calls. /// </summary> private static volatile object Mutex = new object(); #endregion #region ctors public OleServiceProvider() { } #endregion #region IOleServiceProvider Members public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject) { ppvObject = (IntPtr)0; int hr = VSConstants.S_OK; ServiceData serviceInstance = null; if (services != null && services.ContainsKey(guidService)) { serviceInstance = services[guidService]; } if (serviceInstance == null) { return VSConstants.E_NOINTERFACE; } // Now check to see if the user asked for an IID other than // IUnknown. If so, we must do another QI. // if (riid.Equals(NativeMethods.IID_IUnknown)) { object inst = serviceInstance.ServiceInstance; if (inst == null) { return VSConstants.E_NOINTERFACE; } ppvObject = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance); } else { IntPtr pUnk = IntPtr.Zero; try { pUnk = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance); hr = Marshal.QueryInterface(pUnk, ref riid, out ppvObject); } finally { if (pUnk != IntPtr.Zero) { Marshal.Release(pUnk); } } } return hr; } #endregion #region Dispose /// <summary> /// The IDispose interface Dispose method for disposing the object determinastically. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion /// <summary> /// Adds the given service to the service container. /// </summary> /// <param name="serviceType">The type of the service to add.</param> /// <param name="serviceInstance">An instance of the service.</param> /// <param name="shouldDisposeServiceInstance">true if the Dipose of the service provider is allowed to dispose the sevice instance.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The services created here will be disposed in the Dispose method of this type.")] public void AddService(Type serviceType, object serviceInstance, bool shouldDisposeServiceInstance) { // Create the description of this service. Note that we don't do any validation // of the parameter here because the constructor of ServiceData will do it for us. ServiceData service = new ServiceData(serviceType, serviceInstance, null, shouldDisposeServiceInstance); // Now add the service desctription to the dictionary. AddService(service); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The services created here will be disposed in the Dispose method of this type.")] public void AddService(Type serviceType, ServiceCreatorCallback callback, bool shouldDisposeServiceInstance) { // Create the description of this service. Note that we don't do any validation // of the parameter here because the constructor of ServiceData will do it for us. ServiceData service = new ServiceData(serviceType, null, callback, shouldDisposeServiceInstance); // Now add the service desctription to the dictionary. AddService(service); } private void AddService(ServiceData data) { // Make sure that the collection of services is created. if (null == services) { services = new Dictionary<Guid, ServiceData>(); } // Disallow the addition of duplicate services. if (services.ContainsKey(data.Guid)) { throw new InvalidOperationException(); } services.Add(data.Guid, data); } /// <devdoc> /// Removes the given service type from the service container. /// </devdoc> public void RemoveService(Type serviceType) { Utilities.ArgumentNotNull("serviceType", serviceType); if (services.ContainsKey(serviceType.GUID)) { services.Remove(serviceType.GUID); } } #region helper methods /// <summary> /// The method that does the cleanup. /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { // Everybody can go here. if (!this.isDisposed) { // Synchronize calls to the Dispose simulteniously. lock (Mutex) { if (disposing) { // Remove all our services if (services != null) { foreach (ServiceData data in services.Values) { data.Dispose(); } services.Clear(); services = null; } } this.isDisposed = true; } } } #endregion } #endif }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Compiler.Framework; using System.Diagnostics; namespace Mosa.Platform.x86.Stages { /// <summary> /// /// </summary> public sealed class TweakTransformationStage : BaseTransformationStage { #region IX86Visitor /// <summary> /// Visitation function for <see cref="IX86Visitor.Mov"/> instructions. /// </summary> /// <param name="context">The context.</param> public override void Mov(Context context) { Debug.Assert(!context.Result.IsConstant); // Convert moves to float moves, if necessary if (context.Result.IsR4) { context.SetInstruction(X86.Movss, InstructionSize.Size32, context.Result, context.Operand1); } else if (context.Result.IsR8) { context.SetInstruction(X86.Movsd, InstructionSize.Size64, context.Result, context.Operand1); } else if (context.Operand1.IsConstant && (context.Result.Type.IsUI1 || context.Result.Type.IsUI2 || context.Result.IsBoolean || context.Result.IsChar)) { // Correct source size of constant based on destination size context.Operand1 = Operand.CreateConstant(context.Result.Type, context.Operand1.ConstantUnsignedLongInteger); } } /// <summary> /// Visitation function for <see cref="IX86Visitor.Cvttsd2si"/> instructions. /// </summary> /// <param name="context">The context.</param> public override void Cvttsd2si(Context context) { Operand result = context.Result; if (!result.IsRegister) { Operand register = AllocateVirtualRegister(result.Type); context.Result = register; context.AppendInstruction(X86.Mov, result, register); } } /// <summary> /// Visitation function for <see cref="IX86Visitor.Cvttss2si"/> instructions. /// </summary> /// <param name="context">The context.</param> public override void Cvttss2si(Context context) { Operand result = context.Result; Operand register = AllocateVirtualRegister(result.Type); if (!result.IsRegister) { context.Result = register; context.AppendInstruction(X86.Mov, result, register); } } /// <summary> /// Visitation function for <see cref="IX86Visitor.Cvtss2sd" /> instructions. /// </summary> /// <param name="context">The context.</param> public override void Cvtss2sd(Context context) { Operand result = context.Result; if (!result.IsRegister) { Operand register = AllocateVirtualRegister(result.Type); context.Result = register; context.AppendInstruction(X86.Movsd, InstructionSize.Size64, result, register); } } /// <summary> /// Visitation function for <see cref="IX86Visitor.Cvtsd2ss"/> instructions. /// </summary> /// <param name="context">The context.</param> public override void Cvtsd2ss(Context context) { Operand result = context.Result; if (!result.IsRegister) { Operand register = AllocateVirtualRegister(result.Type); context.Result = register; context.AppendInstruction(X86.Movss, InstructionSize.Size32, result, register); } } /// <summary> /// Visitation function for <see cref="IX86Visitor.Movsx"/> instructions. /// </summary> /// <param name="context">The context.</param> public override void Movsx(Context context) { if (context.Operand1.IsInt || context.Operand1.IsPointer || !context.Operand1.IsValueType) { context.ReplaceInstructionOnly(X86.Mov); } } /// <summary> /// Visitation function for <see cref="IX86Visitor.Movzx"/> instructions. /// </summary> /// <param name="context">The context.</param> public override void Movzx(Context context) { if (context.Operand1.IsInt || context.Operand1.IsPointer || !context.Operand1.IsValueType) { context.ReplaceInstructionOnly(X86.Mov); } } /// <summary> /// Visitation function for <see cref="IX86Visitor.Cmp"/> instructions. /// </summary> /// <param name="context">The context.</param> public override void Cmp(Context context) { Operand left = context.Operand1; Operand right = context.Operand2; if (left.IsConstant) { Operand ecx = AllocateVirtualRegister(left.Type); Context before = context.InsertBefore(); before.AppendInstruction(X86.Mov, ecx, left); context.Operand1 = ecx; } if (right.IsConstant && (left.IsChar || left.IsShort || left.IsByte)) { Operand edx = AllocateVirtualRegister(TypeSystem.BuiltIn.I4); Context before = context.InsertBefore(); if (left.IsSigned) { before.AppendInstruction(X86.Movsx, edx, left); } else { before.AppendInstruction(X86.Movzx, edx, left); } context.Operand1 = edx; } } /// <summary> /// Visitation function for <see cref="IX86Visitor.Sar"/> instructions. /// </summary> /// <param name="context">The context.</param> public override void Sar(Context context) { ConvertShiftConstantToByte(context); } /// <summary> /// Visitation function for <see cref="IX86Visitor.Shl"/> instructions. /// </summary> /// <param name="context">The context.</param> public override void Shl(Context context) { ConvertShiftConstantToByte(context); } /// <summary> /// Visitation function for <see cref="IX86Visitor.Shr"/> instructions. /// </summary> /// <param name="context">The context.</param> public override void Shr(Context context) { ConvertShiftConstantToByte(context); } /// <summary> /// Visitation function for <see cref="IX86Visitor.Call"/> instructions. /// </summary> /// <param name="context">The context.</param> public override void Call(Context context) { // FIXME: Result operand should be used instead of Operand1 for the result // FIXME: Move to FixedRegisterAssignmentStage Operand destinationOperand = context.Operand1; if (destinationOperand == null || destinationOperand.IsSymbol) return; if (!destinationOperand.IsRegister) { Context before = context.InsertBefore(); Operand eax = AllocateVirtualRegister(destinationOperand.Type); before.SetInstruction(X86.Mov, eax, destinationOperand); context.Operand1 = eax; } } #endregion IX86Visitor /// <summary> /// Adjusts the shift constant. /// </summary> /// <param name="context">The context.</param> private void ConvertShiftConstantToByte(Context context) { if (!context.Operand2.IsConstant) return; if (context.Operand2.IsByte) return; context.Operand2 = Operand.CreateConstant(TypeSystem.BuiltIn.U1, context.Operand2.ConstantUnsignedLongInteger); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Runtime.InteropServices; using SandRibbon.Utils.Microphone.Native; namespace SandRibbon.Utils.Microphone { #region Delegates Implementation /// <summary> /// Represents the method that will handle the <b>WavRecorder.BufferFull</b> event. /// </summary> /// <param name="buffer">Recorded data.</param> public delegate void BufferFullHandler(byte[] buffer); #endregion /// <summary> /// This class implements streaming microphone wav data receiver. /// </summary> public class WaveIn { #region class BufferItem /// <summary> /// This class holds queued recording buffer. /// </summary> private class BufferItem { private GCHandle m_HeaderHandle; private GCHandle m_DataHandle; private int m_DataSize = 0; /// <summary> /// Default constructor. /// </summary> /// <param name="headerHandle">Header handle.</param> /// <param name="header">Wav header.</param> /// <param name="dataHandle">Wav header data handle.</param> /// <param name="dataSize">Data size in bytes.</param> public BufferItem(ref GCHandle headerHandle,ref GCHandle dataHandle,int dataSize) { m_HeaderHandle = headerHandle; m_DataHandle = dataHandle; m_DataSize = dataSize; } #region method Dispose /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { m_HeaderHandle.Free(); m_DataHandle.Free(); } #endregion #region Properties Implementation /// <summary> /// Gets header handle. /// </summary> public GCHandle HeaderHandle { get{ return m_HeaderHandle; } } /// <summary> /// Gets header. /// </summary> public WAVEHDR Header { get{ return (WAVEHDR)m_HeaderHandle.Target; } } /// <summary> /// Gets wav header data pointer handle. /// </summary> public GCHandle DataHandle { get{ return m_DataHandle; } } /// <summary> /// Gets wav header data. /// </summary> public byte[] Data { get{ return (byte[])m_DataHandle.Target; } } /// <summary> /// Gets wav header data size in bytes. /// </summary> public int DataSize { get{ return m_DataSize; } } #endregion } #endregion private WavInDevice m_pInDevice = null; private int m_SamplesPerSec = 8000; private int m_BitsPerSample = 8; private int m_Channels = 1; private int m_BufferSize = 400; private IntPtr m_pWavDevHandle = IntPtr.Zero; private int m_BlockSize = 0; private List<BufferItem> m_pBuffers = null; private waveInProc m_pWaveInProc = null; private bool m_IsRecording = false; private bool m_IsDisposed = false; /// <summary> /// Default constructor. /// </summary> /// <param name="outputDevice">Input device.</param> /// <param name="samplesPerSec">Sample rate, in samples per second (hertz). For PCM common values are /// 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz.</param> /// <param name="bitsPerSample">Bits per sample. For PCM 8 or 16 are the only valid values.</param> /// <param name="channels">Number of channels.</param> /// <param name="bufferSize">Specifies recording buffer size.</param> /// <exception cref="ArgumentNullException">Is raised when <b>outputDevice</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the aruments has invalid value.</exception> public WaveIn(WavInDevice device,int samplesPerSec,int bitsPerSample,int channels,int bufferSize) { if(device == null){ throw new ArgumentNullException("device"); } if(samplesPerSec < 8000){ throw new ArgumentException("Argument 'samplesPerSec' value must be >= 8000."); } if(bitsPerSample < 8){ throw new ArgumentException("Argument 'bitsPerSample' value must be >= 8."); } if(channels < 1){ throw new ArgumentException("Argument 'channels' value must be >= 1."); } m_pInDevice = device; m_SamplesPerSec = samplesPerSec; m_BitsPerSample = bitsPerSample; m_Channels = channels; m_BufferSize = bufferSize; m_BlockSize = m_Channels * (m_BitsPerSample / 8); m_pBuffers = new List<BufferItem>(); // Try to open wav device. WAVEFORMATEX format = new WAVEFORMATEX(); format.wFormatTag = WavFormat.PCM; format.nChannels = (ushort)m_Channels; format.nSamplesPerSec = (uint)samplesPerSec; format.nAvgBytesPerSec = (uint)(m_SamplesPerSec * m_Channels * (m_BitsPerSample / 8)); format.nBlockAlign = (ushort)m_BlockSize; format.wBitsPerSample = (ushort)m_BitsPerSample; format.cbSize = 0; // We must delegate reference, otherwise GC will collect it. m_pWaveInProc = new waveInProc(this.OnWaveInProc); int result = WavMethods.waveInOpen(out m_pWavDevHandle,m_pInDevice.Index,format,m_pWaveInProc,0,WavConstants.CALLBACK_FUNCTION); if(result != MMSYSERR.NOERROR){ throw new Exception("Failed to open wav device, error: " + result.ToString() + "."); } EnsureBuffers(); } /// <summary> /// Default destructor. /// </summary> ~WaveIn() { Dispose(); } #region method Dispose /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if(m_IsDisposed){ return; } m_IsDisposed = true; // Release events. this.BufferFull = null; try{ // If recording, we need to reset wav device first. WavMethods.waveInReset(m_pWavDevHandle); // If there are unprepared wav headers, we need to unprepare these. foreach(BufferItem item in m_pBuffers){ WavMethods.waveInUnprepareHeader(m_pWavDevHandle,item.HeaderHandle.AddrOfPinnedObject(),Marshal.SizeOf(item.Header)); item.Dispose(); } // Close input device. WavMethods.waveInClose(m_pWavDevHandle); m_pInDevice = null; m_pWavDevHandle = IntPtr.Zero; } catch{ } } #endregion #region method Start /// <summary> /// Starts recording. /// </summary> public void Start() { if(m_IsRecording){ return; } m_IsRecording = true; int result = WavMethods.waveInStart(m_pWavDevHandle); if(result != MMSYSERR.NOERROR){ throw new Exception("Failed to start wav device, error: " + result + "."); } } #endregion #region method Stop /// <summary> /// Stops recording. /// </summary> public void Stop() { if(!m_IsRecording){ return; } m_IsRecording = false; int result = WavMethods.waveInStop(m_pWavDevHandle); if(result != MMSYSERR.NOERROR){ throw new Exception("Failed to stop wav device, error: " + result + "."); } } #endregion #region method OnWaveInProc /// <summary> /// This method is called when wav device generates some event. /// </summary> /// <param name="hdrvr">Handle to the waveform-audio device associated with the callback.</param> /// <param name="uMsg">Waveform-audio input message.</param> /// <param name="dwUser">User-instance data specified with waveOutOpen.</param> /// <param name="dwParam1">Message parameter.</param> /// <param name="dwParam2">Message parameter.</param> private void OnWaveInProc(IntPtr hdrvr,int uMsg,int dwUser,int dwParam1,int dwParam2) { // NOTE: MSDN warns, we may not call any wav related methods here. try{ if(uMsg == WavConstants.MM_WIM_DATA){ ThreadPool.QueueUserWorkItem(new WaitCallback(this.ProcessFirstBuffer)); } } catch{ } } #endregion #region method ProcessFirstBuffer /// <summary> /// Processes first first filled buffer in queue and disposes it if done. /// </summary> /// <param name="state">User data.</param> private void ProcessFirstBuffer(object state) { try{ lock(m_pBuffers){ BufferItem item = m_pBuffers[0]; // Raise BufferFull event. OnBufferFull(item.Data); // Clean up. WavMethods.waveInUnprepareHeader(m_pWavDevHandle,item.HeaderHandle.AddrOfPinnedObject(),Marshal.SizeOf(item.Header)); m_pBuffers.Remove(item); item.Dispose(); } EnsureBuffers(); } catch{ } } #endregion #region method EnsureBuffers /// <summary> /// Fills recording buffers. /// </summary> private void EnsureBuffers() { // We keep 3 x buffer. lock(m_pBuffers){ while(m_pBuffers.Count < 3){ byte[] data = new byte[m_BufferSize]; GCHandle dataHandle = GCHandle.Alloc(data,GCHandleType.Pinned); WAVEHDR wavHeader = new WAVEHDR(); wavHeader.lpData = dataHandle.AddrOfPinnedObject(); wavHeader.dwBufferLength = (uint)data.Length; wavHeader.dwBytesRecorded = 0; wavHeader.dwUser = IntPtr.Zero; wavHeader.dwFlags = 0; wavHeader.dwLoops = 0; wavHeader.lpNext = IntPtr.Zero; wavHeader.reserved = 0; GCHandle headerHandle = GCHandle.Alloc(wavHeader,GCHandleType.Pinned); int result = 0; result = WavMethods.waveInPrepareHeader(m_pWavDevHandle,headerHandle.AddrOfPinnedObject(),Marshal.SizeOf(wavHeader)); if(result == MMSYSERR.NOERROR){ m_pBuffers.Add(new BufferItem(ref headerHandle,ref dataHandle,m_BufferSize)); result = WavMethods.waveInAddBuffer(m_pWavDevHandle,headerHandle.AddrOfPinnedObject(),Marshal.SizeOf(wavHeader)); if(result != MMSYSERR.NOERROR){ throw new Exception("Error adding wave in buffer, error: " + result + "."); } } } } } #endregion #region Properties Implementation /// <summary> /// Gets all available input audio devices. /// </summary> public static WavInDevice[] Devices { get{ List<WavInDevice> retVal = new List<WavInDevice>(); // Get all available output devices and their info. int devicesCount = WavMethods.waveInGetNumDevs(); for(int i=0;i<devicesCount;i++){ WAVEOUTCAPS pwoc = new WAVEOUTCAPS(); if(WavMethods.waveInGetDevCaps((uint)i,ref pwoc,Marshal.SizeOf(pwoc)) == MMSYSERR.NOERROR){ retVal.Add(new WavInDevice(i,pwoc.szPname,pwoc.wChannels)); } } return retVal.ToArray(); } } /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get{ return m_IsDisposed; } } /// <summary> /// Gets current input device. /// </summary> /// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception> public WavInDevice InputDevice { get{ if(m_IsDisposed){ throw new ObjectDisposedException("WavRecorder"); } return m_pInDevice; } } /// <summary> /// Gets number of samples per second. /// </summary> /// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception> public int SamplesPerSec { get{ if(m_IsDisposed){ throw new ObjectDisposedException("WavRecorder"); } return m_SamplesPerSec; } } /// <summary> /// Gets number of buts per sample. /// </summary> /// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception> public int BitsPerSample { get{ if(m_IsDisposed){ throw new ObjectDisposedException("WavRecorder"); } return m_BitsPerSample; } } /// <summary> /// Gets number of channels. /// </summary> /// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception> public int Channels { get{ if(m_IsDisposed){ throw new ObjectDisposedException("WavRecorder"); } return m_Channels; } } /// <summary> /// Gets recording buffer size. /// </summary> /// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception> public int BufferSize { get{ if(m_IsDisposed){ throw new ObjectDisposedException("WavRecorder"); } return m_BufferSize; } } // <summary> /// Gets one smaple block size in bytes. /// </summary> /// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception> public int BlockSize { get{ if(m_IsDisposed){ throw new ObjectDisposedException("WavRecorder"); } return m_BlockSize; } } #endregion #region Events Implementation /// <summary> /// This event is raised when record buffer is full and application should process it. /// </summary> public event BufferFullHandler BufferFull = null; /// <summary> /// This method raises event <b>BufferFull</b> event. /// </summary> /// <param name="buffer">Receive buffer.</param> private void OnBufferFull(byte[] buffer) { if(this.BufferFull != null){ this.BufferFull(buffer); } } #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.IO; using System.Net.Http.Headers; using System.Net.Test.Common; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; // Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary // to separately Dispose (or have a 'using' statement) for the handler. [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "dotnet/corefx #20010")] public class PostScenarioTest { private const string ExpectedContent = "Test contest"; private const string UserName = "user1"; private const string Password = "password1"; private static readonly Uri BasicAuthServerUri = Configuration.Http.BasicAuthUriForCreds(false, UserName, Password); private static readonly Uri SecureBasicAuthServerUri = Configuration.Http.BasicAuthUriForCreds(true, UserName, Password); private readonly ITestOutputHelper _output; public static readonly object[][] EchoServers = Configuration.Http.EchoServers; public static readonly object[][] BasicAuthEchoServers = new object[][] { new object[] { BasicAuthServerUri }, new object[] { SecureBasicAuthServerUri } }; public PostScenarioTest(ITestOutputHelper output) { _output = output; } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostNoContentUsingContentLengthSemantics_Success(Uri serverUri) { await PostHelper(serverUri, string.Empty, null, useContentLengthUpload: true, useChunkedEncodingUpload: false); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostEmptyContentUsingContentLengthSemantics_Success(Uri serverUri) { await PostHelper(serverUri, string.Empty, new StringContent(string.Empty), useContentLengthUpload: true, useChunkedEncodingUpload: false); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostEmptyContentUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, string.Empty, new StringContent(string.Empty), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostUsingContentLengthSemantics_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: true, useChunkedEncodingUpload: false); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostSyncBlockingContentUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new SyncBlockingContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostRepeatedFlushContentUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new RepeatedFlushContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostUsingUsingConflictingSemantics_UsesChunkedSemantics(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: true, useChunkedEncodingUpload: true); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx behaves differently and will buffer content and use 'Content-Length' semantics")] public async Task PostUsingNoSpecifiedSemantics_UsesChunkedSemantics(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: false); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(5 * 1024)] [InlineData(63 * 1024)] public async Task PostLongerContentLengths_UsesChunkedSemantics(int contentLength) { var rand = new Random(42); var sb = new StringBuilder(contentLength); for (int i = 0; i < contentLength; i++) { sb.Append((char)(rand.Next(0, 26) + 'a')); } string content = sb.ToString(); await PostHelper(Configuration.Http.RemoteEchoServer, content, new StringContent(content), useContentLengthUpload: true, useChunkedEncodingUpload: false); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(BasicAuthEchoServers))] public async Task PostRewindableContentUsingAuth_NoPreAuthenticate_Success(Uri serverUri) { HttpContent content = CustomContent.Create(ExpectedContent, true); var credential = new NetworkCredential(UserName, Password); await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, false); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(BasicAuthEchoServers))] public async Task PostNonRewindableContentUsingAuth_NoPreAuthenticate_ThrowsHttpRequestException(Uri serverUri) { HttpContent content = CustomContent.Create(ExpectedContent, false); var credential = new NetworkCredential(UserName, Password); await Assert.ThrowsAsync<HttpRequestException>(() => PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: false)); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(BasicAuthEchoServers))] [ActiveIssue(9228, TestPlatforms.Windows)] public async Task PostNonRewindableContentUsingAuth_PreAuthenticate_Success(Uri serverUri) { HttpContent content = CustomContent.Create(ExpectedContent, false); var credential = new NetworkCredential(UserName, Password); await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: true); } private async Task PostHelper( Uri serverUri, string requestBody, HttpContent requestContent, bool useContentLengthUpload, bool useChunkedEncodingUpload) { using (var client = new HttpClient()) { if (!useContentLengthUpload && requestContent != null) { requestContent.Headers.ContentLength = null; } if (useChunkedEncodingUpload) { client.DefaultRequestHeaders.TransferEncodingChunked = true; } using (HttpResponseMessage response = await client.PostAsync(serverUri, requestContent)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); if (!useContentLengthUpload && !useChunkedEncodingUpload) { useChunkedEncodingUpload = true; } TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, useChunkedEncodingUpload, requestBody); } } } private async Task PostUsingAuthHelper( Uri serverUri, string requestBody, HttpContent requestContent, NetworkCredential credential, bool preAuthenticate) { var handler = new HttpClientHandler(); handler.PreAuthenticate = preAuthenticate; handler.Credentials = credential; using (var client = new HttpClient(handler)) { // Send HEAD request to help bypass the 401 auth challenge for the latter POST assuming // that the authentication will be cached and re-used later when PreAuthenticate is true. var request = new HttpRequestMessage(HttpMethod.Head, serverUri); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } // Now send POST request. request = new HttpRequestMessage(HttpMethod.Post, serverUri); request.Content = requestContent; requestContent.Headers.ContentLength = null; request.Headers.TransferEncodingChunked = true; using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, true, requestBody); } } } } }
// ------------------------------------- // Domain : IBT / Realtime.co // Author : Nicholas Ventimiglia // Product : Messaging and Storage // Published : 2014 // ------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Foundation.Tasks; using UnityEngine; #if UNITY_WSA using System.Collections.Concurrent; #else #endif using Realtime.Messaging.Internal; namespace Realtime.Messaging { /// <summary> /// IBT Real Time SJ type client. /// </summary> public class UnityOrtcClient : OrtcClient { #region Constants (11) // REGEX patterns private const string OPERATION_PATTERN = @"^a\[""{""op"":""(?<op>[^\""]+)"",(?<args>.*)}""\]$"; private const string CLOSE_PATTERN = @"^c\[?(?<code>[^""]+),?""?(?<message>.*)""?\]?$"; private const string VALIDATED_PATTERN = @"^(""up"":){1}(?<up>.*)?,""set"":(?<set>.*)$"; private const string CHANNEL_PATTERN = @"^""ch"":""(?<channel>.*)""$"; private const string EXCEPTION_PATTERN = @"^""ex"":{(""op"":""(?<op>[^""]+)"",)?(""ch"":""(?<channel>.*)"",)?""ex"":""(?<error>.*)""}$"; private const string RECEIVED_PATTERN = @"^a\[""{""ch"":""(?<channel>.*)"",""m"":""(?<message>[\s\S]*)""}""\]$"; private const string MULTI_PART_MESSAGE_PATTERN = @"^(?<messageId>.[^_]*)_(?<messageCurrentPart>.[^-]*)-(?<messageTotalPart>.[^_]*)_(?<message>[\s\S]*)$"; private const string PERMISSIONS_PATTERN = @"""(?<key>[^""]+)"":{1}""(?<value>[^,""]+)"",?"; #endregion #region Attributes (17) private string _url; private string _clusterUrl; private string _applicationKey; private string _authenticationToken; private bool _alreadyConnectedFirstTime; private bool _forcedClosed; private bool _waitingServerResponse; private bool _enableReconnect = true; private int _sessionExpirationTime; // minutes private List<KeyValuePair<string, string>> _permissions; private ConcurrentDictionary<string, ChannelSubscription> _subscribedChannels; private ConcurrentDictionary<string, ConcurrentDictionary<int, BufferedMessage>> _multiPartMessagesBuffer; private WebSocketConnection _webSocketConnection; private TaskTimer _reconnectTimer; private TaskTimer _heartbeatTimer; #endregion #region Properties (9) /// <summary> /// Gets or sets the gateway URL. /// </summary> /// <value>Gateway URL where the socket is going to connect.</value> public override string Url { get { return _url; } set { IsCluster = false; _url = String.IsNullOrEmpty(value) ? String.Empty : value.Trim(); } } /// <summary> /// Gets or sets the cluster gateway URL. /// </summary> public override string ClusterUrl { get { return _clusterUrl; } set { IsCluster = true; _clusterUrl = String.IsNullOrEmpty(value) ? String.Empty : value.Trim(); } } /// <summary> /// Gets or sets the heartbeat interval. /// </summary> /// <value> /// Interval in seconds between heartbeats. /// </value> public override int HeartbeatTime { get { return _heartbeatTimer.Interval; } set { _heartbeatTimer.Interval = value > HEARTBEAT_MAX_TIME ? HEARTBEAT_MAX_TIME : (value < HEARTBEAT_MIN_TIME ? HEARTBEAT_MIN_TIME : value); } } public override int HeartbeatFails { get; set; } public override int ConnectionTimeout { get; set; } public override string ConnectionMetadata { get; set; } public override string AnnouncementSubChannel { get; set; } public override bool HeartbeatActive { get { return _heartbeatTimer.IsRunning; } set { if (value) _heartbeatTimer.Start(); else _heartbeatTimer.Stop(); } } public override bool EnableReconnect { get { return _enableReconnect; } set { _enableReconnect = value; } } #endregion #region Events (7) event OnConnectedDelegate _onConnected = delegate { }; event OnDisconnectedDelegate _onDisconnected = delegate { }; event OnSubscribedDelegate _onSubscribed = delegate { }; event OnUnsubscribedDelegate _onUnsubscribed = delegate { }; event OnExceptionDelegate _onException = delegate { }; event OnReconnectingDelegate _onReconnecting = delegate { }; event OnReconnectedDelegate _onReconnected = delegate { }; /// <summary> /// Occurs when a connection attempt was successful. /// </summary> public override event OnConnectedDelegate OnConnected { // note : IOS WTF for Unity5 add { _onConnected = (OnConnectedDelegate)Delegate.Combine(_onConnected, value); } remove { _onConnected = (OnConnectedDelegate)Delegate.Remove(_onConnected, value); } } /// <summary> /// Occurs when the client connection terminated. /// </summary> public override event OnDisconnectedDelegate OnDisconnected { add { _onDisconnected = (OnDisconnectedDelegate)Delegate.Combine(_onDisconnected, value); } remove { _onDisconnected = (OnDisconnectedDelegate)Delegate.Remove(_onDisconnected, value); } } /// <summary> /// Occurs when the client subscribed to a channel. /// </summary> public override event OnSubscribedDelegate OnSubscribed { add { _onSubscribed = (OnSubscribedDelegate)Delegate.Combine(_onSubscribed, value); } remove { _onSubscribed = (OnSubscribedDelegate)Delegate.Remove(_onSubscribed, value); } } /// <summary> /// Occurs when the client unsubscribed from a channel. /// </summary> public override event OnUnsubscribedDelegate OnUnsubscribed { add { _onUnsubscribed = (OnUnsubscribedDelegate)Delegate.Combine(_onUnsubscribed, value); } remove { _onUnsubscribed = (OnUnsubscribedDelegate)Delegate.Remove(_onUnsubscribed, value); } } /// <summary> /// Occurs when there is an error. /// </summary> public override event OnExceptionDelegate OnException { add { _onException = (OnExceptionDelegate)Delegate.Combine(_onException, value); } remove { _onException = (OnExceptionDelegate)Delegate.Remove(_onException, value); } } /// <summary> /// Occurs when a client attempts to reconnect. /// </summary> public override event OnReconnectingDelegate OnReconnecting { add { _onReconnecting = (OnReconnectingDelegate)Delegate.Combine(_onReconnecting, value); } remove { _onReconnecting = (OnReconnectingDelegate)Delegate.Remove(_onReconnecting, value); } } /// <summary> /// Occurs when a client reconnected. /// </summary> public override event OnReconnectedDelegate OnReconnected { add { _onReconnected = (OnReconnectedDelegate)Delegate.Combine(_onReconnected, value); } remove { _onReconnected = (OnReconnectedDelegate)Delegate.Remove(_onReconnected, value); } } #endregion #region Constructor (1) /// <summary> /// Initializes a new instance of the <see cref="UnityOrtcClient"/> class. /// </summary> public UnityOrtcClient() { _heartbeatTimer = new TaskTimer { Interval = 2, AutoReset = true }; _heartbeatTimer.Elapsed += _heartbeatTimer_Elapsed; _heartbeatTimer.Start(); _reconnectTimer = new TaskTimer { Interval = 2, AutoReset = false }; _reconnectTimer.Elapsed += _reconnectTimer_Elapsed; _permissions = new List<KeyValuePair<string, string>>(); _subscribedChannels = new ConcurrentDictionary<string, ChannelSubscription>(); _multiPartMessagesBuffer = new ConcurrentDictionary<string, ConcurrentDictionary<int, BufferedMessage>>(); // To catch unobserved exceptions // TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException); MakeSocket(); } void MakeSocket() { if (_webSocketConnection != null) { _webSocketConnection.OnOpened -= _webSocketConnection_OnOpened; _webSocketConnection.OnClosed -= _webSocketConnection_OnClosed; _webSocketConnection.OnError -= _webSocketConnection_OnError; _webSocketConnection.OnMessageReceived -= _webSocketConnection_OnMessageReceived; _webSocketConnection.Dispose(); } _webSocketConnection = new WebSocketConnection(); _webSocketConnection.OnOpened += _webSocketConnection_OnOpened; _webSocketConnection.OnClosed += _webSocketConnection_OnClosed; _webSocketConnection.OnError += _webSocketConnection_OnError; _webSocketConnection.OnMessageReceived += _webSocketConnection_OnMessageReceived; } #endregion #region Public Methods (6) /// <summary> /// Connects to the gateway with the application key and authentication token. The gateway must be set before using this method. /// </summary> /// <param name="appKey">Your application key to use ORTC.</param> /// <param name="authToken">Authentication token that identifies your permissions.</param> /// <example> /// <code> /// ortcClient.Connect("myApplicationKey", "myAuthenticationToken"); /// </code> /// </example> public override void Connect(string appKey, string authToken) { #region Sanity Checks if (IsConnected) { DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Already connected")); } else if (IsConnecting) { DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Already trying to connect")); } else if (String.IsNullOrEmpty(ClusterUrl) && String.IsNullOrEmpty(Url)) { DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "URL and Cluster URL are null or empty")); } else if (String.IsNullOrEmpty(appKey)) { DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Application Key is null or empty")); } else if (String.IsNullOrEmpty(authToken)) { DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Authentication ToKen is null or empty")); } else if (!IsCluster && !Url.OrtcIsValidUrl()) { DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Invalid URL")); } else if (IsCluster && !ClusterUrl.OrtcIsValidUrl()) { DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Invalid Cluster URL")); } else if (!appKey.OrtcIsValidInput()) { DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Application Key has invalid characters")); } else if (!authToken.OrtcIsValidInput()) { DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Authentication Token has invalid characters")); } else if (AnnouncementSubChannel != null && !AnnouncementSubChannel.OrtcIsValidInput()) { DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Announcement Subchannel has invalid characters")); } else if (!String.IsNullOrEmpty(ConnectionMetadata) && ConnectionMetadata.Length > MAX_CONNECTION_METADATA_SIZE) { DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, String.Format("Connection metadata size exceeds the limit of {0} characters", MAX_CONNECTION_METADATA_SIZE))); } else #endregion { _forcedClosed = false; _authenticationToken = authToken; _applicationKey = appKey; TaskManager.StartRoutine(DoConnect()); } } /// <summary> /// Sends a message to a channel. /// </summary> /// <param name="channel">Channel name.</param> /// <param name="message">Message to be sent.</param> /// <example> /// <code> /// ortcClient.Send("channelName", "messageToSend"); /// </code> /// </example> public override void Send(string channel, string message) { #region Sanity Checks if (!IsConnected) { DelegateExceptionCallback(new OrtcException("Not connected")); } else if (String.IsNullOrEmpty(channel)) { DelegateExceptionCallback(new OrtcException("Channel is null or empty")); } else if (!channel.OrtcIsValidInput()) { DelegateExceptionCallback(new OrtcException("Channel has invalid characters")); } else if (String.IsNullOrEmpty(message)) { DelegateExceptionCallback(new OrtcException("Message is null or empty")); } else #endregion { byte[] channelBytes = Encoding.UTF8.GetBytes(channel); if (channelBytes.Length > MAX_CHANNEL_SIZE) { DelegateExceptionCallback(new OrtcException(String.Format("Channel size exceeds the limit of {0} characters", MAX_CHANNEL_SIZE))); } else { var domainChannelCharacterIndex = channel.IndexOf(':'); var channelToValidate = channel; if (domainChannelCharacterIndex > 0) { channelToValidate = channel.Substring(0, domainChannelCharacterIndex + 1) + "*"; } string hash = GetChannelHash(channel, channelToValidate); if (_permissions != null && _permissions.Count > 0 && String.IsNullOrEmpty(hash)) { DelegateExceptionCallback(new OrtcException(String.Format("No permission found to send to the channel '{0}'", channel))); } else { message = message.Replace(Environment.NewLine, "\n"); if (channel != String.Empty && message != String.Empty) { try { byte[] messageBytes = Encoding.UTF8.GetBytes(message); List<string> messageParts = new List<string>(); int pos = 0; int remaining; string messageId = Strings.GenerateId(8); // Multi part while ((remaining = messageBytes.Length - pos) > 0) { byte[] messagePart; if (remaining >= MAX_MESSAGE_SIZE - channelBytes.Length) { messagePart = new byte[MAX_MESSAGE_SIZE - channelBytes.Length]; } else { messagePart = new byte[remaining]; } Array.Copy(messageBytes, pos, messagePart, 0, messagePart.Length); #if UNITY_WSA var b = (byte[])messagePart; messageParts.Add(Encoding.UTF8.GetString(b, 0, b.Length)); #else messageParts.Add(Encoding.UTF8.GetString((byte[])messagePart)); #endif pos += messagePart.Length; } for (int i = 0;i < messageParts.Count;i++) { string s = String.Format("send;{0};{1};{2};{3};{4}", _applicationKey, _authenticationToken, channel, hash, String.Format("{0}_{1}-{2}_{3}", messageId, i + 1, messageParts.Count, messageParts[i])); DoSend(s); } } catch (Exception ex) { string exName = null; if (ex.InnerException != null) { exName = ex.InnerException.GetType().Name; } switch (exName) { case "OrtcNotConnectedException": // Server went down if (IsConnected) { DoDisconnect(); } break; default: DelegateExceptionCallback(new OrtcException(String.Format("Unable to send: {0}", ex))); break; } } } } } } } public override void SendProxy(string applicationKey, string privateKey, string channel, string message) { #region Sanity Checks if (!IsConnected) { DelegateExceptionCallback(new OrtcException("Not connected")); } else if (String.IsNullOrEmpty(applicationKey)) { DelegateExceptionCallback(new OrtcException("Application Key is null or empty")); } else if (String.IsNullOrEmpty(privateKey)) { DelegateExceptionCallback(new OrtcException("Private Key is null or empty")); } else if (String.IsNullOrEmpty(channel)) { DelegateExceptionCallback(new OrtcException("Channel is null or empty")); } else if (!channel.OrtcIsValidInput()) { DelegateExceptionCallback(new OrtcException("Channel has invalid characters")); } else if (String.IsNullOrEmpty(message)) { DelegateExceptionCallback(new OrtcException("Message is null or empty")); } else #endregion { byte[] channelBytes = Encoding.UTF8.GetBytes(channel); if (channelBytes.Length > MAX_CHANNEL_SIZE) { DelegateExceptionCallback(new OrtcException(String.Format("Channel size exceeds the limit of {0} characters", MAX_CHANNEL_SIZE))); } else { message = message.Replace(Environment.NewLine, "\n"); if (channel != String.Empty && message != String.Empty) { try { byte[] messageBytes = Encoding.UTF8.GetBytes(message); var messageParts = new List<string>(); int pos = 0; int remaining; string messageId = Strings.GenerateId(8); // Multi part while ((remaining = messageBytes.Length - pos) > 0) { byte[] messagePart; if (remaining >= MAX_MESSAGE_SIZE - channelBytes.Length) { messagePart = new byte[MAX_MESSAGE_SIZE - channelBytes.Length]; } else { messagePart = new byte[remaining]; } Array.Copy(messageBytes, pos, messagePart, 0, messagePart.Length); #if UNITY_WSA var b = (byte[])messagePart; messageParts.Add(Encoding.UTF8.GetString(b, 0, b.Length)); #else messageParts.Add(Encoding.UTF8.GetString((byte[])messagePart)); #endif pos += messagePart.Length; } for (int i = 0;i < messageParts.Count;i++) { string s = String.Format("sendproxy;{0};{1};{2};{3}", applicationKey, privateKey, channel, String.Format("{0}_{1}-{2}_{3}", messageId, i + 1, messageParts.Count, messageParts[i])); DoSend(s); } } catch (Exception ex) { string exName = null; if (ex.InnerException != null) { exName = ex.InnerException.GetType().Name; } switch (exName) { case "OrtcNotConnectedException": // Server went down if (IsConnected) { DoDisconnect(); } break; default: DelegateExceptionCallback(new OrtcException(String.Format("Unable to send: {0}", ex))); break; } } } } } } /// <summary> /// Subscribes to a channel. /// </summary> /// <param name="channel">Channel name.</param> /// <param name="onMessage"><see cref="OnMessageDelegate"/> callback.</param> /// <example> /// <code> /// ortcClient.Subscribe("channelName", true, OnMessageCallback); /// private void OnMessageCallback(object sender, string channel, string message) /// { /// // Do something /// } /// </code> /// </example> public override void Subscribe(string channel, OnMessageDelegate onMessage) { #region Sanity Checks bool sanityChecked = true; if (!IsConnected) { DelegateExceptionCallback(new OrtcException("Not connected")); sanityChecked = false; } else if (String.IsNullOrEmpty(channel)) { DelegateExceptionCallback(new OrtcException("Channel is null or empty")); sanityChecked = false; } else if (!channel.OrtcIsValidInput()) { DelegateExceptionCallback(new OrtcException("Channel has invalid characters")); sanityChecked = false; } else if (_subscribedChannels.ContainsKey(channel)) { ChannelSubscription channelSubscription = null; _subscribedChannels.TryGetValue(channel, out channelSubscription); if (channelSubscription != null) { if (channelSubscription.IsSubscribing) { DelegateExceptionCallback(new OrtcException(String.Format("Already subscribing to the channel {0}", channel))); sanityChecked = false; } else if (channelSubscription.IsSubscribed) { DelegateExceptionCallback(new OrtcException(String.Format("Already subscribed to the channel {0}", channel))); sanityChecked = false; } } } else { byte[] channelBytes = Encoding.UTF8.GetBytes(channel); if (channelBytes.Length > MAX_CHANNEL_SIZE) { if (_subscribedChannels.ContainsKey(channel)) { ChannelSubscription channelSubscription = null; _subscribedChannels.TryGetValue(channel, out channelSubscription); if (channelSubscription != null) { channelSubscription.IsSubscribing = false; } } DelegateExceptionCallback(new OrtcException(String.Format("Channel size exceeds the limit of {0} characters", MAX_CHANNEL_SIZE))); sanityChecked = false; } } #endregion if (sanityChecked) { var domainChannelCharacterIndex = channel.IndexOf(':'); var channelToValidate = channel; if (domainChannelCharacterIndex > 0) { channelToValidate = channel.Substring(0, domainChannelCharacterIndex + 1) + "*"; } string hash = GetChannelHash(channel, channelToValidate); if (_permissions != null && _permissions.Count > 0 && String.IsNullOrEmpty(hash)) { DelegateExceptionCallback(new OrtcException(String.Format("No permission found to subscribe to the channel '{0}'", channel))); } else { if (!_subscribedChannels.ContainsKey(channel)) { _subscribedChannels.TryAdd(channel, new ChannelSubscription { IsSubscribing = true, IsSubscribed = false, SubscribeOnReconnected = true, OnMessage = onMessage }); } try { if (_subscribedChannels.ContainsKey(channel)) { ChannelSubscription channelSubscription = null; _subscribedChannels.TryGetValue(channel, out channelSubscription); channelSubscription.IsSubscribing = true; channelSubscription.IsSubscribed = false; channelSubscription.SubscribeOnReconnected = true; channelSubscription.OnMessage = onMessage; } string s = String.Format("subscribe;{0};{1};{2};{3}", _applicationKey, _authenticationToken, channel, hash); DoSend(s); } catch (Exception ex) { string exName = null; if (ex.InnerException != null) { exName = ex.InnerException.GetType().Name; } switch (exName) { case "OrtcNotConnectedException": // Server went down if (IsConnected) { DoDisconnect(); } break; default: DelegateExceptionCallback(new OrtcException(String.Format("Unable to subscribe: {0}", ex))); break; } } } } } /// <summary> /// Unsubscribes from a channel. /// </summary> /// <param name="channel">Channel name.</param> /// <example> /// <code> /// ortcClient.Unsubscribe("channelName"); /// </code> /// </example> public override void Unsubscribe(string channel) { #region Sanity Checks bool sanityChecked = true; if (!IsConnected) { DelegateExceptionCallback(new OrtcException("Not connected")); sanityChecked = false; } else if (String.IsNullOrEmpty(channel)) { DelegateExceptionCallback(new OrtcException("Channel is null or empty")); sanityChecked = false; } else if (!channel.OrtcIsValidInput()) { DelegateExceptionCallback(new OrtcException("Channel has invalid characters")); sanityChecked = false; } else if (!_subscribedChannels.ContainsKey(channel)) { DelegateExceptionCallback(new OrtcException(String.Format("Not subscribed to the channel {0}", channel))); sanityChecked = false; } else if (_subscribedChannels.ContainsKey(channel)) { ChannelSubscription channelSubscription = null; _subscribedChannels.TryGetValue(channel, out channelSubscription); if (channelSubscription != null && !channelSubscription.IsSubscribed) { DelegateExceptionCallback(new OrtcException(String.Format("Not subscribed to the channel {0}", channel))); sanityChecked = false; } } else { byte[] channelBytes = Encoding.UTF8.GetBytes(channel); if (channelBytes.Length > MAX_CHANNEL_SIZE) { DelegateExceptionCallback(new OrtcException(String.Format("Channel size exceeds the limit of {0} characters", MAX_CHANNEL_SIZE))); sanityChecked = false; } } #endregion if (sanityChecked) { try { string s = String.Format("unsubscribe;{0};{1}", _applicationKey, channel); DoSend(s); } catch (Exception ex) { string exName = null; if (ex.InnerException != null) { exName = ex.InnerException.GetType().Name; } switch (exName) { case "OrtcNotConnectedException": // Server went down if (IsConnected) { DoDisconnect(); } break; default: DelegateExceptionCallback(new OrtcException(String.Format("Unable to unsubscribe: {0}", ex))); break; } } } } /// <summary> /// Disconnects from the gateway. /// </summary> /// <example> /// <code> /// ortcClient.Disconnect(); /// </code> /// </example> public override void Disconnect() { // Clear subscribed channels _subscribedChannels.Clear(); #region Sanity Checks if (!IsConnecting && !IsConnected) { DelegateExceptionCallback(new OrtcException("Not connected")); } else #endregion { DoDisconnect(); } } /// <summary> /// Indicates whether is subscribed to a channel. /// </summary> /// <param name="channel">The channel name.</param> /// <returns> /// <c>true</c> if subscribed to the channel; otherwise, <c>false</c>. /// </returns> public override bool IsSubscribed(string channel) { bool result = false; #region Sanity Checks if (!IsConnected) { DelegateExceptionCallback(new OrtcException("Not connected")); } else if (String.IsNullOrEmpty(channel)) { DelegateExceptionCallback(new OrtcException("Channel is null or empty")); } else if (!channel.OrtcIsValidInput()) { DelegateExceptionCallback(new OrtcException("Channel has invalid characters")); } else #endregion { result = false; if (_subscribedChannels.ContainsKey(channel)) { ChannelSubscription channelSubscription = null; _subscribedChannels.TryGetValue(channel, out channelSubscription); if (channelSubscription != null && channelSubscription.IsSubscribed) { result = true; } } } return result; } #endregion #region Private Methods (13) string GetChannelHash(string channel, string channelToValidate) { foreach (var keyValuePair in _permissions) { if (keyValuePair.Key == channel) return keyValuePair.Value; if (keyValuePair.Key == channelToValidate) return keyValuePair.Value; } return null; } /// <summary> /// Processes the operation validated. /// </summary> /// <param name="arguments">The arguments.</param> private void ProcessOperationValidated(string arguments) { if (!String.IsNullOrEmpty(arguments)) { bool isValid = false; // Try to match with authentication Match validatedAuthMatch = Regex.Match(arguments, VALIDATED_PATTERN); if (validatedAuthMatch.Success) { isValid = true; string userPermissions = String.Empty; if (validatedAuthMatch.Groups["up"].Length > 0) { userPermissions = validatedAuthMatch.Groups["up"].Value; } if (validatedAuthMatch.Groups["set"].Length > 0) { _sessionExpirationTime = int.Parse(validatedAuthMatch.Groups["set"].Value); } if (String.IsNullOrEmpty(ReadLocalStorage(_applicationKey, _sessionExpirationTime))) { CreateLocalStorage(_applicationKey); } if (!String.IsNullOrEmpty(userPermissions) && userPermissions != "null") { MatchCollection matchCollection = Regex.Matches(userPermissions, PERMISSIONS_PATTERN); var permissions = new List<KeyValuePair<string, string>>(); foreach (Match match in matchCollection) { string channel = match.Groups["key"].Value; string hash = match.Groups["value"].Value; permissions.Add(new KeyValuePair<string, string>(channel, hash)); } _permissions = new List<KeyValuePair<string, string>>(permissions); } } if (isValid) { IsConnecting = false; if (_alreadyConnectedFirstTime) { var channelsToRemove = new List<string>(); // Subscribe to the previously subscribed channels foreach (KeyValuePair<string, ChannelSubscription> item in _subscribedChannels) { string channel = item.Key; ChannelSubscription channelSubscription = item.Value; // Subscribe again if (channelSubscription.SubscribeOnReconnected && (channelSubscription.IsSubscribing || channelSubscription.IsSubscribed)) { channelSubscription.IsSubscribing = true; channelSubscription.IsSubscribed = false; var domainChannelCharacterIndex = channel.IndexOf(':'); var channelToValidate = channel; if (domainChannelCharacterIndex > 0) { channelToValidate = channel.Substring(0, domainChannelCharacterIndex + 1) + "*"; } string hash = GetChannelHash(channel, channelToValidate); string s = String.Format("subscribe;{0};{1};{2};{3}", _applicationKey, _authenticationToken, channel, hash); DoSend(s); } else { channelsToRemove.Add(channel); } } for (int i = 0;i < channelsToRemove.Count;i++) { ChannelSubscription removeResult = null; _subscribedChannels.TryRemove(channelsToRemove[i].ToString(), out removeResult); } // Clean messages buffer (can have lost message parts in memory) _multiPartMessagesBuffer.Clear(); DelegateReconnectedCallback(); } else { _alreadyConnectedFirstTime = true; // Clear subscribed channels _subscribedChannels.Clear(); DelegateConnectedCallback(); } if (arguments.IndexOf("busy") < 0) { StopReconnect(); } } } } /// <summary> /// Processes the operation subscribed. /// </summary> /// <param name="arguments">The arguments.</param> private void ProcessOperationSubscribed(string arguments) { if (!String.IsNullOrEmpty(arguments)) { Match subscribedMatch = Regex.Match(arguments, CHANNEL_PATTERN); if (subscribedMatch.Success) { string channelSubscribed = String.Empty; if (subscribedMatch.Groups["channel"].Length > 0) { channelSubscribed = subscribedMatch.Groups["channel"].Value; } if (!String.IsNullOrEmpty(channelSubscribed)) { ChannelSubscription channelSubscription = null; _subscribedChannels.TryGetValue(channelSubscribed, out channelSubscription); if (channelSubscription != null) { channelSubscription.IsSubscribing = false; channelSubscription.IsSubscribed = true; } DelegateSubscribedCallback(channelSubscribed); } } } } /// <summary> /// Processes the operation unsubscribed. /// </summary> /// <param name="arguments">The arguments.</param> private void ProcessOperationUnsubscribed(string arguments) { // UnityEngine.Debug.Log("ProcessOperationUnsubscribed"); if (!String.IsNullOrEmpty(arguments)) { Match unsubscribedMatch = Regex.Match(arguments, CHANNEL_PATTERN); if (unsubscribedMatch.Success) { string channelUnsubscribed = String.Empty; if (unsubscribedMatch.Groups["channel"].Length > 0) { channelUnsubscribed = unsubscribedMatch.Groups["channel"].Value; } if (!String.IsNullOrEmpty(channelUnsubscribed)) { ChannelSubscription channelSubscription = null; _subscribedChannels.TryGetValue(channelUnsubscribed, out channelSubscription); if (channelSubscription != null) { channelSubscription.IsSubscribed = false; } DelegateUnsubscribedCallback(channelUnsubscribed); } } } } /// <summary> /// Processes the operation error. /// </summary> /// <param name="arguments">The arguments.</param> private void ProcessOperationError(string arguments) { if (!String.IsNullOrEmpty(arguments)) { Match errorMatch = Regex.Match(arguments, EXCEPTION_PATTERN); if (errorMatch.Success) { string op = String.Empty; string error = String.Empty; string channel = String.Empty; if (errorMatch.Groups["op"].Length > 0) { op = errorMatch.Groups["op"].Value; } if (errorMatch.Groups["error"].Length > 0) { error = errorMatch.Groups["error"].Value; } if (errorMatch.Groups["channel"].Length > 0) { channel = errorMatch.Groups["channel"].Value; } if (!String.IsNullOrEmpty(error)) { DelegateExceptionCallback(new OrtcException(error)); } if (!String.IsNullOrEmpty(op)) { switch (op) { case "validate": if (!String.IsNullOrEmpty(error) && (error.Contains("Unable to connect") || error.Contains("Server is too busy"))) { DelegateExceptionCallback(new Exception(error)); DoReconnectOrDisconnect(); } else { DoDisconnect(); } break; case "subscribe": if (!String.IsNullOrEmpty(channel)) { ChannelSubscription channelSubscription = null; _subscribedChannels.TryGetValue(channel, out channelSubscription); if (channelSubscription != null) { channelSubscription.IsSubscribing = false; } } break; case "subscribe_maxsize": case "unsubscribe_maxsize": case "send_maxsize": if (!String.IsNullOrEmpty(channel)) { ChannelSubscription channelSubscription = null; _subscribedChannels.TryGetValue(channel, out channelSubscription); if (channelSubscription != null) { channelSubscription.IsSubscribing = false; } } DoDisconnect(); break; default: break; } } } } } private void ProcessOperationReceived(string message) { Match receivedMatch = Regex.Match(message, RECEIVED_PATTERN); // Received if (receivedMatch.Success) { string channelReceived = String.Empty; string messageReceived = String.Empty; if (receivedMatch.Groups["channel"].Length > 0) { channelReceived = receivedMatch.Groups["channel"].Value; } if (receivedMatch.Groups["message"].Length > 0) { messageReceived = receivedMatch.Groups["message"].Value; } if (!String.IsNullOrEmpty(channelReceived) && !String.IsNullOrEmpty(messageReceived) && _subscribedChannels.ContainsKey(channelReceived)) { messageReceived = messageReceived.Replace(@"\\n", Environment.NewLine).Replace("\\\\\"", @"""").Replace("\\\\\\\\", @"\"); // Multi part Match multiPartMatch = Regex.Match(messageReceived, MULTI_PART_MESSAGE_PATTERN); string messageId = String.Empty; int messageCurrentPart = 1; int messageTotalPart = 1; bool lastPart = false; ConcurrentDictionary<int, BufferedMessage> messageParts = null; if (multiPartMatch.Success) { if (multiPartMatch.Groups["messageId"].Length > 0) { messageId = multiPartMatch.Groups["messageId"].Value; } if (multiPartMatch.Groups["messageCurrentPart"].Length > 0) { messageCurrentPart = Int32.Parse(multiPartMatch.Groups["messageCurrentPart"].Value); } if (multiPartMatch.Groups["messageTotalPart"].Length > 0) { messageTotalPart = Int32.Parse(multiPartMatch.Groups["messageTotalPart"].Value); } if (multiPartMatch.Groups["message"].Length > 0) { messageReceived = multiPartMatch.Groups["message"].Value; } } lock (_multiPartMessagesBuffer) { // Is a message part if (!String.IsNullOrEmpty(messageId)) { if (!_multiPartMessagesBuffer.ContainsKey(messageId)) { _multiPartMessagesBuffer.TryAdd(messageId, new ConcurrentDictionary<int, BufferedMessage>()); } _multiPartMessagesBuffer.TryGetValue(messageId, out messageParts); if (messageParts != null) { lock (messageParts) { messageParts.TryAdd(messageCurrentPart, new BufferedMessage(messageCurrentPart, messageReceived)); // Last message part if (messageParts.Count == messageTotalPart) { //messageParts.Sort(); lastPart = true; } } } } // Message does not have multipart, like the messages received at announcement channels else { lastPart = true; } if (lastPart) { if (_subscribedChannels.ContainsKey(channelReceived)) { ChannelSubscription channelSubscription = null; _subscribedChannels.TryGetValue(channelReceived, out channelSubscription); if (channelSubscription != null) { var ev = channelSubscription.OnMessage; if (ev != null) { if (!String.IsNullOrEmpty(messageId) && _multiPartMessagesBuffer.ContainsKey(messageId)) { messageReceived = String.Empty; //lock (messageParts) //{ var bufferedMultiPartMessages = new List<BufferedMessage>(); foreach (var part in messageParts.Keys) { bufferedMultiPartMessages.Add(messageParts[part]); } bufferedMultiPartMessages.Sort(); foreach (var part in bufferedMultiPartMessages) { if (part != null) { messageReceived = String.Format("{0}{1}", messageReceived, part.Message); } } //} // Remove from messages buffer ConcurrentDictionary<int, BufferedMessage> removeResult = null; _multiPartMessagesBuffer.TryRemove(messageId, out removeResult); } if (!String.IsNullOrEmpty(messageReceived)) { TaskManager.RunOnMainThread(() => { ev(channelReceived, messageReceived); }); } } } } } } } } else { // Unknown DelegateExceptionCallback(new OrtcException(String.Format("Unknown message received: {0}", message))); } } /// <summary> /// Do the Connect Task /// </summary> IEnumerator DoConnect() { IsConnecting = true; if (IsCluster) { var cTask = ClusterClient.GetClusterServer(ClusterUrl, _applicationKey); yield return TaskManager.StartRoutine(cTask.WaitRoutine()); if (cTask.IsFaulted) { DoReconnectOrDisconnect(); DelegateExceptionCallback(new OrtcException("Connection Failed. Unable to get URL from cluster")); yield break; } Url = cTask.Result; IsCluster = true; if (String.IsNullOrEmpty(Url)) { DoReconnectOrDisconnect(); DelegateExceptionCallback(new OrtcException("Connection Failed. Unable to get URL from cluster")); yield break; } } if (!String.IsNullOrEmpty(Url)) { try { // make a new socket MakeSocket(); // use socket _webSocketConnection.Connect(Url); // Just in case the server does not respond _waitingServerResponse = true; } catch (Exception ex) { DoReconnectOrDisconnect(); DelegateExceptionCallback(new OrtcException("Connection Failed. " + ex.Message)); } } } /// <summary> /// Disconnect the TCP client. /// </summary> private void DoDisconnect() { _forcedClosed = true; StopReconnect(); if (IsConnected) { try { _webSocketConnection.Close(); } catch (Exception ex) { DelegateExceptionCallback(new OrtcException(String.Format("Error disconnecting: {0}", ex))); DelegateDisconnectedCallback(); } } else { DelegateDisconnectedCallback(); } } /// <summary> /// Sends a message through the TCP client. /// </summary> /// <param name="message"></param> private void DoSend(string message) { try { _webSocketConnection.Send(message); } catch (Exception ex) { DelegateExceptionCallback(new OrtcException(String.Format("Unable to send: {0}", ex))); } } public override string ReadLocalStorage(string applicationKey, int sessionExpirationTime) { //server sends multiple messages if reconnecting. new session to be safe. return string.Empty; var created = PlayerPrefs.GetString(string.Format("{0}-{1}-{2}", SESSION_STORAGE_NAME, "created", applicationKey)); var session = PlayerPrefs.GetString(string.Format("{0}-{1}-{2}", SESSION_STORAGE_NAME, "session", applicationKey)); if (string.IsNullOrEmpty(created)) return string.Empty; if (string.IsNullOrEmpty(session)) return string.Empty; var createdDate = DateTime.Parse(created); var currentDateTime = DateTime.Now; var interval = currentDateTime.Subtract(createdDate); if (createdDate != DateTime.MinValue && interval.TotalMinutes >= sessionExpirationTime) { return string.Empty; } SessionId = session; return session; } public override void CreateLocalStorage(string applicationKey) { //server sends multiple messages if reconnecting. new session to be safe. return; PlayerPrefs.SetString(string.Format("{0}-{1}-{2}", SESSION_STORAGE_NAME, "created", applicationKey), DateTime.UtcNow.ToString()); PlayerPrefs.SetString(string.Format("{0}-{1}-{2}", SESSION_STORAGE_NAME, "session", applicationKey), SessionId); } private void DoReconnectOrDisconnect() { if (EnableReconnect) DoReconnect(); else DoDisconnect(); } private void DoReconnect() { IsConnecting = true; DelegateReconnectingCallback(); _reconnectTimer.Start(); } private void StopReconnect() { IsConnecting = false; _reconnectTimer.Stop(); } #endregion #region Events handlers (6) void _reconnectTimer_Elapsed() { if (!IsConnected) { if (_waitingServerResponse) { _waitingServerResponse = false; DelegateExceptionCallback(new OrtcException("Unable to connect")); } DelegateReconnectingCallback(); TaskManager.StartRoutine(DoConnect()); } } void _heartbeatTimer_Elapsed() { if (IsConnected) { DoSend("b"); } } /// <summary> /// /// </summary> private void _webSocketConnection_OnOpened() { // Do nothing } /// <summary> /// /// </summary> private void _webSocketConnection_OnClosed() { IsConnected = false; if (!_forcedClosed && EnableReconnect) DoReconnect(); else DoDisconnect(); } /// <summary> /// /// </summary> /// <param name="error"></param> private void _webSocketConnection_OnError(string error) { DelegateExceptionCallback(new OrtcException(error)); } /// <summary> /// /// </summary> /// <param name="message"></param> private void _webSocketConnection_OnMessageReceived(string message) { if (!String.IsNullOrEmpty(message)) { // Open if (message == "o") { try { SessionId = Strings.GenerateId(16); string s; if (HeartbeatActive) { s = String.Format("validate;{0};{1};{2};{3};{4};{5};{6}", _applicationKey, _authenticationToken, AnnouncementSubChannel, SessionId, ConnectionMetadata, HeartbeatTime, HeartbeatFails); } else { s = String.Format("validate;{0};{1};{2};{3};{4}", _applicationKey, _authenticationToken, AnnouncementSubChannel, SessionId, ConnectionMetadata); } DoSend(s); } catch (Exception ex) { DelegateExceptionCallback(new OrtcException(String.Format("Exception sending validate: {0}", ex))); } } // Heartbeat else if (message == "h") { // Do nothing } else { message = message.Replace("\\\"", @""""); // UnityEngine.Debug.Log(message); // Operation Match operationMatch = Regex.Match(message, OPERATION_PATTERN); // Debug.Log(operationMatch.Success); if (operationMatch.Success) { string operation = operationMatch.Groups["op"].Value; string arguments = operationMatch.Groups["args"].Value; // Debug.Log(operation); // Debug.Log(arguments); switch (operation) { case "ortc-validated": ProcessOperationValidated(arguments); break; case "ortc-subscribed": ProcessOperationSubscribed(arguments); break; case "ortc-unsubscribed": ProcessOperationUnsubscribed(arguments); break; case "ortc-error": ProcessOperationError(arguments); break; default: // Unknown operation DelegateExceptionCallback(new OrtcException(String.Format("Unknown operation \"{0}\" for the message \"{1}\"", operation, message))); DoDisconnect(); break; } } else { // Close Match closeOperationMatch = Regex.Match(message, CLOSE_PATTERN); if (!closeOperationMatch.Success) { ProcessOperationReceived(message); } } } } } #endregion #region Events calls (7) private void DelegateConnectedCallback() { IsConnected = true; IsConnecting = false; _reconnectTimer.Stop(); //_heartbeatTimer.Start(); TaskManager.RunOnMainThread(() => { //Debug.Log("Ortc.Connected"); var ev = _onConnected; if (ev != null) { ev(); } }); } private void DelegateDisconnectedCallback() { IsConnected = false; IsConnecting = false; _alreadyConnectedFirstTime = false; _reconnectTimer.Stop(); //_heartbeatTimer.Stop(); // Clear user permissions _permissions.Clear(); UnityTask.RunOnMain(() => { //Debug.Log("Ortc.Disconnected"); var ev = _onDisconnected; if (ev != null) { ev(); } }); } private void DelegateSubscribedCallback(string channel) { TaskManager.RunOnMainThread(() => { var ev = _onSubscribed; if (ev != null) { ev(channel); } }); } private void DelegateUnsubscribedCallback(string channel) { // Debug.Log("DelegateUnsubscribedCallback"); TaskManager.RunOnMainThread(() => { var ev = _onUnsubscribed; if (ev != null) { ev(channel); } }); } private void DelegateExceptionCallback(Exception ex) { TaskManager.RunOnMainThread(() => { var ev = _onException; if (ev != null) { ev(ex); } }); } private void DelegateReconnectingCallback() { TaskManager.RunOnMainThread(() => { // Debug.Log("Ortc.Reconnecting"); var ev = _onReconnecting; if (ev != null) { ev(); } }); } private void DelegateReconnectedCallback() { IsConnected = true; IsConnecting = false; _reconnectTimer.Stop(); TaskManager.RunOnMainThread(() => { //Debug.Log("Ortc.Reconnected"); var ev = _onReconnected; if (ev != null) { ev(); } }); } #endregion } }
namespace Boo.Lang.Resources { public static class StringResources { public const string BCE0000 = "'{0}'"; public const string BCE0001 = "The class '{0}' already has '{1}' as its super class."; public const string BCE0002 = "Parameter name must be an identifier."; public const string BCE0003 = "Named arguments are only allowed when creating objects."; public const string BCE0004 = "Ambiguous reference '{0}': {1}."; public const string BCE0005 = "Unknown identifier: '{0}'."; public const string BCE0006 = "'{0}' is a value type. The 'as' operator can only be used with reference types."; public const string BCE0007 = "The name '{0}' does not represent a writable public property or field of the type '{1}'."; public const string BCE0008 = "The '{0}' type does not have a constructor with the signature '{1}'."; public const string BCE0009 = "An error occurred during the resolution of the '{0}' ast attribute: '{1}'."; public const string BCE0010 = "'{0}' is an internal type. Ast attributes must be compiled to a separate assembly before they can be used."; public const string BCE0011 = "An error occurred during the execution of the step '{0}': '{1}'."; public const string BCE0012 = "The type '{0}' does not implement the ICompilerStep interface."; public const string BCE0013 = "The element '{0}' must specify the attribute '{1}'."; public const string BCE0014 = "AssemblyBuilder was not correctly set up."; public const string BCE0015 = "Node '{0}' has not been correctly processed."; public const string BCE0016 = "No overload of the method '{0}' takes '{1}' parameter(s)."; public const string BCE0017 = "The best overload for the method '{0}' is not compatible with the argument list '{1}'."; public const string BCE0018 = "The name '{0}' does not denote a valid type ('{1}'). {2}"; public const string BCE0019 = "'{0}' is not a member of '{1}'. {2}"; public const string BCE0020 = "An instance of type '{0}' is required to access non static member '{1}'."; public const string BCE0021 = "Namespace '{0}' not found, maybe you forgot to add an assembly reference?"; public const string BCE0022 = "Cannot convert '{1}' to '{0}'."; public const string BCE0023 = "No appropriate version of '{1}' for the argument list '{0}' was found."; public const string BCE0024 = "The type '{0}' does not have a visible constructor that matches the argument list '{1}'."; public const string BCE0025 = "Only uni-dimensional arrays are supported."; public const string BCE0026 = "'{0}' cannot be used in a boolean context."; public const string BCE0027 = "Ambiguous type reference, it could be any of the following: '{0}'."; public const string BCE0028 = "No entry point found."; public const string BCE0029 = "More than one entry point found."; public const string BCE0030 = "The node '{0}' is not in the collection."; public const string BCE0031 = "Language feature not implemented: {0}."; public const string BCE0032 = "The event '{0}' expects a {2} reference compatible with '{1}'."; public const string BCE0033 = "The type '{0}' is not a valid attribute."; public const string BCE0034 = "Expressions in statements must only be executed for their side-effects."; public const string BCE0035 = "'{0}' conflicts with inherited member '{1}'."; public const string BCE0036 = "typeof must be used with a type reference as its single argument."; public const string BCE0037 = "Unknown macro: '{0}'."; public const string BCE0038 = "'{0}' is not a valid macro."; public const string BCE0039 = "Internal macro '{0}' could not be compiled. Errors were reported."; public const string BCE0040 = "Generic error."; public const string BCE0041 = "Failed to load assembly '{0}'."; public const string BCE0042 = "Error reading from '{0}': '{1}'."; public const string BCE0043 = "Unexpected token: {0}."; public const string BCE0044 = "{0}."; public const string BCE0045 = "Macro expansion error: {0}."; public const string BCE0046 = "'{0}' can't be used with a value type ('{1}')"; public const string BCE0047 = "Non virtual method '{0}' cannot be overridden."; public const string BCE0048 = "Type '{0}' does not support slicing."; public const string BCE0049 = "Expression '{0}' cannot be assigned to."; public const string BCE0050 = "Operator '{0}' cannot be used with an expression of type '{1}'."; public const string BCE0051 = "Operator '{0}' cannot be used with a left hand side of type '{1}' and a right hand side of type '{2}'."; public const string BCE0052 = "Type '{0}' is not a valid argument for 'len'."; public const string BCE0053 = "Property '{0}' is read only."; public const string BCE0054 = "'{0}' expects a type reference, a System.Type instance or a type array."; public const string BCE0055 = "Internal compiler error: {0}."; public const string BCE0056 = "File '{0}' was not found."; public const string BCE0057 = "Primitive '{0}' can't be redefined."; public const string BCE0058 = "'{0}' is not valid in a static method, static property, or static field initializer."; public const string BCE0059 = "The 'lock' macro expects at least one argument."; public const string BCE0060 = "'{0}': no suitable method found to override. {1}"; public const string BCE0060_IncompatibleSignature = "Method of same name has been found with incompatible signature(s)."; public const string BCE0061 = "'{0}' is not an override."; public const string BCE0062 = "Could not infer the return type for the method '{0}'."; public const string BCE0063 = "No enclosing loop out of which to break or continue."; public const string BCE0064 = "No attribute with the name '{0}' or '{0}Attribute' was found (attribute names are case insensitive). {1}"; public const string BCE0065 = "Cannot iterate over expression of type '{0}'."; public const string BCE0066 = "The attribute '{0}' can only be applied to '{1}' nodes."; public const string BCE0067 = "There is already a local variable with the name '{0}'."; public const string BCE0068 = "The property '{0}' cannot be used without parameters."; public const string BCE0069 = "Interface '{0}' can only inherit from another interface but the type '{1}' is not an interface."; public const string BCE0070 = "Definition of '{0}' depends on '{1}' whose type could not be resolved because of a cycle. Explicitly declare the type of either one to break the cycle."; public const string BCE0071 = "Inheritance cycle detected: '{0}'."; public const string BCE0072 = "Overridden method '{0}' has a return type of '{1}' not '{2}'."; public const string BCE0073 = "Abstract method '{0}' cannot have a body."; public const string BCE0074 = "'{0}' cannot be used outside a method."; public const string BCE0075 = "'{0}' is a namespace. Namespaces cannot be used as expressions."; public const string BCE0076 = "Run-time and PInvoke methods must have an empty body."; public const string BCE0077 = "It is not possible to invoke an expression of type '{0}'."; public const string BCE0078 = "A method reference was expected."; public const string BCE0079 = "__addressof__ built-in function can only be used in delegate constructors."; public const string BCE0080 = "'{0}' built-in function cannot be used as an expression."; public const string BCE0081 = "A {0} statement with no arguments is not allowed outside an exception handler."; public const string BCE0082 = "'{0}' is not a {1} type. Event type must be a {1} type."; public const string BCE0083 = "Static constructors must be private."; public const string BCE0084 = "Static constructors cannot declare parameters."; public const string BCE0085 = "Cannot create instance of abstract class '{0}'."; public const string BCE0086 = "Cannot create instance of interface '{0}'."; public const string BCE0087 = "Cannot create instance of enum '{0}'."; public const string BCE0089 = "Type '{0}' already has a definition for '{1}'."; public const string BCE0090 = "Derived method '{0}' can not reduce the accessibility of '{1}' from '{2}' to '{3}'."; public const string BCE0091 = "Event reference '{0}' cannot be used as an expression."; public const string BCE0092 = "'{0}' is not a valid argument type for {1}, only strings and exceptions are allowed."; public const string BCE0093 = "Cannot branch into {0} block."; public const string BCE0094 = "Cannot branch into exception handler."; public const string BCE0095 = "No such label '{0}'."; public const string BCE0096 = "Method '{0}' already has a label '{1}'."; public const string BCE0097 = "Cannot branch into {0} block."; public const string BCE0098 = "Invalid arguments for __switch__."; public const string BCE0099 = "yield cannot be used inside a {0}, {1} or {2} block."; public const string BCE0100 = "yield cannot be used inside constructors."; public const string BCE0101 = "Return type '{0}' cannot be used on a generator. Did you mean '{1}'? You can also use 'System.Collections.IEnumerable' or 'object'."; public const string BCE0102 = "Generators cannot return values."; public const string BCE0103 = "Cannot extend final type '{0}'."; public const string BCE0104 = "'transient' can only be applied to class, field and event definitions."; public const string BCE0105 = "'abstract' can only be applied to class, method, property and event definitions."; public const string BCE0106 = "Failed to access the types defined in assembly {0}."; public const string BCE0107 = "Value types cannot declare parameter-less constructors."; public const string BCE0108 = "Value type fields cannot have initializers."; public const string BCE0109 = "Array '{0}' is rank '{1}', not rank '{2}'."; public const string BCE0110 = "'{0}' is not a namespace."; public const string BCE0111 = "Destructors cannot have any attributes or modifiers"; public const string BCE0112 = "Destructors cannot be passed parameters"; public const string BCE0113 = "Invalid character literal: '{0}'"; public const string BCE0114 = "Explicit interface implementation for non interface type '{0}'"; public const string BCE0115 = "Cannot implement interface item '{0}.{1}' when not implementing the interface '{0}'"; public const string BCE0116 = "Explicit member implementation for '{0}.{1}' must not declare any modifiers."; public const string BCE0117 = "Field '{0}' is read only."; public const string BCE0118 = "Target of explode expression must be an array."; public const string BCE0119 = "Explode expression can only be used as the last argument to {0} that takes a variable number of arguments."; public const string BCE0120 = "'{0}' is inaccessible due to its protection level."; public const string BCE0121 = "'super' is not valid in this context."; public const string BCE0122 = "Value type '{0}' does not provide an implementation for '{1}'. Value types cannot have abstract members."; public const string BCE0123 = "Invalid {1}parameter type '{0}'."; public const string BCE0124 = "Invalid field type '{0}'."; public const string BCE0125 = "Invalid declaration type '{0}'."; public const string BCE0126 = "It is not possible to evaluate an expression of type '{0}'."; public const string BCE0127 = "A ref or out argument must be an lvalue: '{0}'"; public const string BCE0128 = "'{0}' block must be followed by at least one '{1}' block or either a '{2}' or '{3}' block."; public const string BCE0129 = "Invalid extension definition, only static methods with at least one argument are allowed."; public const string BCE0130 = "'partial' can only be applied to top level class, interface and enum definitions."; public const string BCE0131 = "Invalid combination of modifiers on '{0}': {1}."; public const string BCE0132 = "The namespace '{0}' already contains a definition for '{1}'."; public const string BCE0133 = "Invalid signature for Main. It should be one of: 'Main() as void', 'Main() as int', 'Main(argv as (string)) as void', 'Main(argv as (string)) as int'."; public const string BCE0134 = "'{0}' cannot return values."; public const string BCE0135 = "Invalid name: '{0}'"; public const string BCE0136 = "Use a colon (:) instead of equal sign (=) for named parameters."; public const string BCE0137 = "Property '{0}' is write only."; public const string BCE0138 = "'{0}' is not a generic definition."; public const string BCE0139 = "'{0}' requires '{1}' arguments."; public const string BCE0140 = "Yield statement type '{0}' does not match generator element type '{1}'."; public const string BCE0141 = "Duplicate parameter name '{0}' in '{1}'."; public const string BCE0142 = "Cannot bind [default] attribute to value type parameter '{0}' in '{1}'."; public const string BCE0143 = "Cannot return from an {0} block."; public const string BCE0144 = "'{0}' is obsolete. {1}"; public const string BCE0145 = "Cannot catch type '{0}'; '{1}' blocks can only catch exceptions derived from 'System.Exception'. To catch non-CLS compliant exceptions, use a default exception handler or catch 'System.Runtime.CompilerServices.RuntimeWrappedException'."; public const string BCE0146 = "The type '{0}' must be a reference type in order to substitute the generic parameter '{1}' in '{2}'."; public const string BCE0147 = "The type '{0}' must be a value type in order to substitute the generic parameter '{1}' in '{2}'."; public const string BCE0148 = "The type '{0}' must have a public default constructor in order to substitute the generic parameter '{1}' in '{2}'."; public const string BCE0149 = "The type '{0}' must derive from '{1}' in order to substitute the generic parameter '{2}' in '{3}'."; public const string BCE0150 = "'final' cannot be applied to interface, struct, or enum definitions."; public const string BCE0151 = "'static' cannot be applied to interface, struct, or enum definitions."; public const string BCE0152 = "Constructors cannot be marked virtual, abstract, or override: '{0}'."; public const string BCE0153 = "'{0}' can be applied on one of these targets only : {1}."; public const string BCE0154 = "'{0}' cannot be applied multiple times on the same target."; public const string BCE0155 = "Instantiating generic parameters is not yet supported."; public const string BCE0156 = "Event '{0}' can only be triggered from within its declaring type ('{1}')."; public const string BCE0157 = "Generic types without all generic parameters defined cannot be instantiated."; public const string BCE0158 = "Cannot invoke instance method '{0}' before object initialization. Move your call after '{1}' or 'super'."; public const string BCE0159 = "Generic parameter '{0}' cannot have both a reference type constraint and a value type constraint."; public const string BCE0160 = "Generic parameter '{0}' cannot have both a value type constraint and a default constructor constraint."; public const string BCE0161 = "Type constraint '{1}' cannot be used together with the '{2}' constraint on generic parameter '{0}'."; public const string BCE0162 = "Type '{1}' must be an interface type or a non-final class type to be used as a type constraint on generic parameter '{0}'."; public const string BCE0163 = "Type constraint '{1}' on generic parameter '{0}' conflicts with type constraint '{2}'. At most one non-interface type constraint can be specified for a generic parameter."; public const string BCE0164 = "Cannot infer generic arguments for method '{0}'. Provide stronger type information through arguments, or explicitly state the generic arguments."; public const string BCE0165 = "'{0}' is already handled by {3} block for '{1}' at {2}."; public const string BCE0166 = "Unknown macro '{0}'. Did you mean to declare the field '{0} as object'?"; public const string BCE0167 = "Namespace '{0}' not found in assembly '{1}'"; public const string BCE0168 = "Cannot take the address of, get the size of, or declare a pointer to managed type `{0}'."; public const string BCE0169 = "`{0}' in explicit interface declaration is not a member of interface `{1}'."; public const string BCE0170 = "An enum member must be a constant integer value."; public const string BCE0171 = "Constant value `{0}' cannot be converted to a `{1}'."; public const string BCE0172 = "`{0}' interface member implementation must be public or explicit."; public const string BCE0173 = "`{0}' is not a regex option. Valid options are: g, i, m, s, x, l, n, c and e."; public const string BCE0174 = "'{0}' is not an interface. Only interface members can be explicitly implemented."; public const string BCE0175 = "Nested type '{0}' cannot extend enclosing type '{1}'."; public const string BCE0176 = "Incompatible partial definition for type '{0}', expecting '{1}' but got '{2}'."; public const string BCE0177 = "Default expression requires a type."; public const string BCE0178 = "Async methods must return void, Task, or Task<T>"; public const string BCE0179 = "Await requires an expression of type Task or Task<T>"; public const string BCE0180 = "Type '{0}' is not valid in an async method"; public const string BCE0181 = "Unsafe method calls returning a pointer are not valid in an async method"; public const string BCE0182 = "Type {0} does not contain a valid GetAwaiter method"; public const string BCW0000 = "WARNING: {0}"; public const string BCW0001 = "WARNING: Type '{0}' does not provide an implementation for '{1}' and will be marked abstract."; public const string BCW0002 = "WARNING: Statement modifiers have no effect in labels."; public const string BCW0003 = "WARNING: Unused local variable '{0}'."; public const string BCW0004 = "WARNING: Right hand side of '{0}' operator is a type reference, are you sure you do not want to use '{1}' instead?"; public const string BCW0005 = "WARNING: Unsubscribing from event '{0}' with an adapted method reference. Either change the signature of the method to '{1}' or use a cached reference of the correct type."; public const string BCW0006 = "WARNING: Assignment to temporary."; public const string BCW0007 = "WARNING: Assignment inside a conditional. Did you mean '==' instead of '=' here: '{0}'?"; public const string BCW0008 = "WARNING: Duplicate namespace: '{0}'."; public const string BCW0009 = "WARNING: The -keyfile option will override your AssemblyKeyFile attribute."; public const string BCW0010 = "WARNING: The -keycontainer option will override your AssemblyKeyName attribute."; public const string BCW0011 = "WARNING: Type '{0}' does not provide an implementation for '{1}', a stub has been created."; public const string BCW0012 = "WARNING: '{0}' is obsolete. {1}"; public const string BCW0013 = "WARNING: '{1}' on static type '{0}' is redundantly marked static. All members of static types are automatically assumed to be static."; public const string BCW0014 = "WARNING: {0} {1} '{2}' is never used."; public const string BCW0015 = "WARNING: Unreachable code detected."; public const string BCW0016 = "WARNING: Namespace '{0}' is never used."; public const string BCW0017 = "WARNING: New protected {0} '{1}' declared in sealed class '{2}'."; public const string BCW0018 = "WARNING: Overriding 'object.Finalize()' is bad practice. You should use destructor syntax instead."; public const string BCW0019 = "WARNING: 'except {0}:' is ambiguous. Did you mean 'except as {0}:'?"; public const string BCW0020 = "WARNING: Assignment made to same expression. Did you mean to assign to something else?"; public const string BCW0021 = "WARNING: Comparison made with same expression. Did you mean to compare with something else?"; public const string BCW0022 = "WARNING: Boolean expression will always have the same value."; public const string BCW0023 = "WARNING: This method could return default value implicitly."; public const string BCW0024 = "WARNING: Visible {0} does not declare {1} type explicitely."; public const string BCW0025 = "WARNING: Variable '{0}' has the same name as a private field of super type '{1}'. Did you mean to use the field?"; public const string BCW0026 = "WARNING: Likely typo in member name '{0}'. Did you mean '{1}'?"; public const string BCW0027 = "WARNING: Obsolete syntax '{0}'. Use '{1}'."; public const string BCW0028 = "WARNING: Implicit downcast from '{0}' to '{1}'."; public const string BCW0029 = "WARNING: Method '{0}' hides inherited non virtual method '{1}'. Declare '{0}' as a 'new' method."; public const string BCW0030 = "WARNING: This async method lacks \'await\' operators and will run synchronously. Consider using the \'await\' operator to await non-blocking API calls, or \'await Task.Run(...)\' to do CPU-bound work on a background thread."; public const string BCW0031 = "WARNING: Resource file '{0}' could not be found."; public const string BCE0500 = "Response file '{0}' listed more than once."; public const string BCE0501 = "Response file '{0}' could not be found."; public const string BCE0502 = "An error occurred while loading response file '{0}'."; public const string Boo_Lang_Compiler_GlobalNamespaceIsNotSet = "Global namespace is not set!"; public const string BooC_Errors = "{0} error(s)."; public const string BooC_Warnings = "{0} warning(s)."; public const string BooC_ProcessingTime = "{0} module(s) processed in {1}ms after {2}ms of environment setup."; public const string BooC_FatalError = "Fatal error: {0}."; public const string BooC_InvalidOption = "Invalid option: {0}. {1}"; public const string BooC_CantRunWithoutPipeline = "A pipeline must be specified!"; public const string BooC_InvalidPipeline = "'{0}' is neither a built-in pipeline nor a valid custom pipeline name."; public const string BooC_VerifyPipelineUnsupported = "PEVerify pipeline is not supported on this platform."; public const string BooC_UnableToLoadPipeline = "Failed to load pipeline {0}, cause: {1}."; public const string BooC_NoPipeline = "No compilation pipeline specified (/p:<PIPELINE>)"; public const string BooC_NoInputSpecified = "No inputs specified"; public const string BooC_NoOutputSpecified = "No output specified"; public const string BooC_UnableToLoadAssembly = "Unable to load assembly: {0}"; public const string BooC_BadFormat = "Unable to load assembly (bad file format): {0}"; public const string BooC_NullAssembly = "Unable to load assembly (null argument)"; public const string BooC_CannotFindAssembly = "Cannot find assembly: '{0}'"; public const string BooC_NoSystemPath = "Cannot find path to mscorlib."; public const string BooC_BadLibPath = "Not a valid directory for -lib argument: '{0}'"; public const string BooC_PkgConfigNotFound = "Cannot execute pkg-config, is it in your PATH ?"; public const string BooC_PkgConfigReportedErrors = "pkg-config returned errors: {0}"; public const string BooC_DidYouMean = "Did you mean '{0}'?"; public const string BooC_Return = "return"; public const string BooC_NamedArgument = "'{0}' argument"; public const string BooC_InvalidNestedMacroContext = "Invalid nested macro context. Check your macro hierarchy"; public const string ListWasModified = "The list was modified."; public const string ArgumentNotEnumerable = "Argument is not enumerable (does not implement System.Collections.IEnumerable)."; public const string CantEnumerateNull = "Cannot enumerate null."; public const string UnpackListOfWrongSize = "Unpack list of wrong size."; public const string CantUnpackNull = "Cannot unpack null."; public const string UnpackArrayOfWrongSize = "Unpack array of wrong size (expected={0}, actual={1})."; public const string CantCompareItems = "At least one side must implement IComparable or both sides should implement IEnumerable."; public const string AssertArgCount = "expecting 1 or 2 args to assert; got {0}"; public const string boo_CommandLine_culture = "the culture {code} to use when running the application"; public const string boo_CommandLine_debug = "emit debugging information"; public const string boo_CommandLine_ducky = "treat object references as duck"; public const string boo_CommandLine_embedres = "embeds the specified file as a unmanaged resource"; public const string boo_CommandLine_output = "file name for the generated assembly"; public const string boo_CommandLine_pipeline = "which compilation pipeline to use, it can be either the name of a built-in pipeline like 'boo' or a full type name"; public const string boo_CommandLine_reference = "references an assembly"; public const string boo_CommandLine_resource = "adds a managed resource"; public const string boo_CommandLine_target = "one of exe, winexe, library"; public const string boo_CommandLine_utf8 = "use UTF8 when writing to the console"; public const string boo_CommandLine_wsa = "use the white space agnostic parser"; public const string boo_CommandLine_help = "display help information and exit"; public const string boo_CommandLine_header = "boo command line utility"; public const string boo_CommandLine_usage = "Usage: boo [options] [source files]"; } }
using Xunit; using Glav.CognitiveServices.UnitTests.Helpers; using Glav.CognitiveServices.FluentApi.Core; using System.Threading.Tasks; using Glav.CognitiveServices.FluentApi.Face; using Glav.CognitiveServices.FluentApi.Face.Domain; using Glav.CognitiveServices.FluentApi.Core.Contracts; namespace Glav.CognitiveServices.UnitTests.TextAnalytic { /// <summary> /// Class that tests each Api result that results in an error is parsed correctly. it ensures that the ApiResult class uses the parsing /// strategy correctly. /// </summary> public class FaceApiErrorParsingTests { private TestDataHelper _helper = new TestDataHelper(); private readonly string _inputData; public FaceApiErrorParsingTests() { _inputData = _helper.GetFileDataEmbeddedInAssembly("FaceApiErrorResponse.json"); } [Fact] public async Task ShouldParseLargePersonGroupCreateError() { var result = await FaceConfigurationSettings.CreateUsingConfigurationKeys("some key", LocationKeyIdentifier.AustraliaEast) .SetDiagnosticLoggingLevel(LoggingLevel.Everything) .AddConsoleAndTraceLogging() .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .CreateLargePersonGroup("$@#!", "should fail") .AnalyseAllAsync(); ResponseErrorAssertion(result, result.LargePersonGroupCreateAnalysis); } [Fact] public async Task ShouldParsefaceIdentificationError() { var identifyResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("123", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .IdentifyFace("123", "456") .AnalyseAllAsync(); ResponseErrorAssertion(identifyResult, identifyResult.FaceIdentificationAnalysis); } [Fact] public async Task ShouldParsefaceDetectionError() { var detectResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("whatevs", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .AddUriForFaceDetection(new System.Uri("http://blah/blah/blah.jpg"), FaceDetectionAttributes.Age) .AnalyseAllAsync(); ResponseErrorAssertion(detectResult, detectResult.FaceDetectionAnalysis); } [Fact] public async Task ShouldParseLargePersonDeleteError() { var deleteResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("heyho", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .DeleteLargePersonGroup("Notexists") .AnalyseAllAsync(); ResponseErrorAssertion(deleteResult, deleteResult.LargePersonGroupDeleteAnalysis); } [Fact] public async Task ShouldParseLargePersonGetError() { var getResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("biteme", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .GetLargePersonGroup("not here") .AnalyseAllAsync(); ResponseErrorAssertion(getResult, getResult.LargePersonGroupGetAnalysis); } [Fact] public async Task ShouldParseLargePersonListError() { var listResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("eeek", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .ListLargePersonGroups(new string('*', 1000)) .AnalyseAllAsync(); ResponseErrorAssertion(listResult, listResult.LargePersonGroupListAnalysis); } [Fact] public async Task ShouldParseLargePersonStartTrainError() { var trainResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("eeek", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .StartTrainingLargePersonGroup("123") .AnalyseAllAsync(); ResponseErrorAssertion(trainResult, trainResult.LargePersonGroupTrainStartAnalysis); } [Fact] public async Task ShouldParseLargePersonStartStatusError() { var trainResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("eeek", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .CheckTrainingStatusLargePersonGroup("123") .AnalyseAllAsync(); ResponseErrorAssertion(trainResult, trainResult.LargePersonGroupTrainStatusAnalysis); } [Fact] public async Task ShouldParseLargePersonGroupPersonCreateError() { var lpgpcResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("oops", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .CreateLargePersonGroupPerson("123","mopey") .AnalyseAllAsync(); ResponseErrorAssertion(lpgpcResult, lpgpcResult.LargePersonGroupPersonCreateAnalysis); } [Fact] public async Task ShouldParseLargePersonGroupPersonDeleteError() { var lpgpdResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("oops", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .DeleteLargePersonGroupPerson("123", "mopey") .AnalyseAllAsync(); ResponseErrorAssertion(lpgpdResult, lpgpdResult.LargePersonGroupPersonDeleteAnalysis); } [Fact] public async Task ShouldParseLargePersonGroupPersonFaceAddError() { var faceAddResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("oops", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .AddFaceToPersonGroupPerson("123", "mopey", new System.Uri("http://host/endpoint")) .AnalyseAllAsync(); ResponseErrorAssertion(faceAddResult, faceAddResult.LargePersonGroupPersonFaceAddAnalysis); } [Fact] public async Task ShouldParseLargePersonGroupPersonFaceDeleteError() { var faceDelResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("oops", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .DeleteFaceForPersonGroupPerson("123", "mopey", "someface") .AnalyseAllAsync(); ResponseErrorAssertion(faceDelResult, faceDelResult.LargePersonGroupPersonFaceDeleteAnalysis); } [Fact] public async Task ShouldParseLargePersonGroupPersonFaceGetError() { var faceGetResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("oops", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .GetFaceForPersonGroupPerson("123", "mopey", "someface") .AnalyseAllAsync(); ResponseErrorAssertion(faceGetResult, faceGetResult.LargePersonGroupPersonFaceGetAnalysis); } [Fact] public async Task ShouldParseLargePersonGroupPersonGetError() { var getResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("oops", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .GetLargePersonGroupPerson("hoochey", "coochey" ) .AnalyseAllAsync(); ResponseErrorAssertion(getResult, getResult.LargePersonGroupPersonGetAnalysis); } [Fact] public async Task ShouldParseLargePersonGroupPersonListError() { var listResult = await FaceConfigurationSettings.CreateUsingConfigurationKeys("oops", LocationKeyIdentifier.AustraliaEast) .AddConsoleAndTraceLogging() .SetDiagnosticLoggingLevel(LoggingLevel.WarningsAndErrors) .UsingCustomCommunication(new MockCommsEngine(new MockCommsResult(_inputData, System.Net.HttpStatusCode.BadRequest))) .WithFaceAnalysisActions() .ListLargePersonGroupPersons("some group") .AnalyseAllAsync(); ResponseErrorAssertion(listResult, listResult.LargePersonGroupPersonListAnalysis); } private static void ResponseErrorAssertion(IAnalysisResults root, dynamic analysisContext) { Assert.NotNull(root); Assert.NotNull(analysisContext); Assert.NotEmpty(analysisContext.AnalysisResults); Assert.NotNull(analysisContext.AnalysisResult.ResponseData); Assert.NotNull(analysisContext.AnalysisResult.ResponseData.error); Assert.Equal("BadArgument", analysisContext.AnalysisResult.ResponseData.error.code); } } }
namespace Nancy.Bootstrappers.Windsor { using System; using System.Collections.Generic; using System.Linq; using Castle.Core; using Castle.MicroKernel.Lifestyle; using Castle.MicroKernel.Lifestyle.Scoped; using Castle.MicroKernel.Registration; using Castle.MicroKernel.Resolvers.SpecializedResolvers; using Castle.Facilities.TypedFactory; using Castle.Windsor; using Diagnostics; using Bootstrapper; using Routing; /// <summary> /// Nancy bootstrapper for the Windsor container. /// </summary> public abstract class WindsorNancyBootstrapper : NancyBootstrapperBase<IWindsorContainer> { private bool modulesRegistered; /// <summary> /// Gets the diagnostics for intialisation /// </summary> /// <returns>IDiagnostics implementation</returns> protected override IDiagnostics GetDiagnostics() { return this.ApplicationContainer.Resolve<IDiagnostics>(); } /// <summary> /// Get all NancyModule implementation instances /// </summary> /// <param name="context">The current context</param> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="NancyModule"/> instances.</returns> public override IEnumerable<INancyModule> GetAllModules(NancyContext context) { var currentScope = CallContextLifetimeScope.ObtainCurrentScope(); if (currentScope != null) { return this.ApplicationContainer.ResolveAll<INancyModule>(); } using (this.ApplicationContainer.BeginScope()) { return this.ApplicationContainer.ResolveAll<INancyModule>(); } } /// <summary> /// Gets the application level container /// </summary> /// <returns>Container instance</returns> protected override IWindsorContainer GetApplicationContainer() { if (this.ApplicationContainer != null) { return this.ApplicationContainer; } var container = new WindsorContainer(); return container; } /// <summary> /// Configures the container for use with Nancy. /// </summary> /// <param name="existingContainer"> /// An existing container. /// </param> protected override void ConfigureApplicationContainer(IWindsorContainer existingContainer) { var factoryType = typeof(TypedFactoryFacility); if (!existingContainer.Kernel.GetFacilities() .Any(x => x.GetType() == factoryType)) { existingContainer.AddFacility<TypedFactoryFacility>(); } existingContainer.Kernel.Resolver.AddSubResolver(new CollectionResolver(existingContainer.Kernel, true)); existingContainer.Register(Component.For<IWindsorContainer>().Instance(existingContainer)); existingContainer.Register(Component.For<NancyRequestScopeInterceptor>()); existingContainer.Kernel.ProxyFactory.AddInterceptorSelector(new NancyRequestScopeInterceptorSelector()); foreach (var requestStartupType in this.RequestStartupTasks) { this.ApplicationContainer.Register( Component.For(requestStartupType, typeof(IRequestStartup)) .LifestyleScoped(typeof(NancyPerWebRequestScopeAccessor)) .ImplementedBy(requestStartupType)); } base.ConfigureApplicationContainer(existingContainer); } /// <summary> /// Gets all registered application registration tasks /// </summary> /// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IRegistrations"/> instances.</returns> protected override IEnumerable<IRegistrations> GetRegistrationTasks() { return this.ApplicationContainer.ResolveAll<IRegistrations>(); } /// <summary> /// Gets all registered application startup tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IApplicationStartup"/> instances.</returns> protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks() { return this.ApplicationContainer.ResolveAll<IApplicationStartup>(); } /// <summary> /// Gets all registered request startup tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRequestStartup"/> instances.</returns> protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(IWindsorContainer container, Type[] requestStartupTypes) { return container.ResolveAll<IRequestStartup>(); } /// <summary> /// Resolve INancyEngine /// </summary> /// <returns>INancyEngine implementation</returns> protected override INancyEngine GetEngineInternal() { return this.ApplicationContainer.Resolve<INancyEngine>(); } /// <summary> /// Retrieves a specific <see cref="INancyModule"/> implementation - should be per-request lifetime /// </summary> /// <param name="moduleType">Module type</param> /// <param name="context">The current context</param> /// <returns>The <see cref="INancyModule"/> instance</returns> public override INancyModule GetModule(Type moduleType, NancyContext context) { var currentScope = CallContextLifetimeScope.ObtainCurrentScope(); if (currentScope != null) { return this.ApplicationContainer.Resolve<INancyModule>(moduleType.FullName); } using (this.ApplicationContainer.BeginScope()) { return this.ApplicationContainer.Resolve<INancyModule>(moduleType.FullName); } } /// <summary> /// Register the given module types into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="moduleRegistrationTypes">NancyModule types</param> protected override void RegisterModules(IWindsorContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes) { if (this.modulesRegistered) { return; } this.modulesRegistered = true; var components = moduleRegistrationTypes.Select(r => Component.For(typeof(INancyModule)) .ImplementedBy(r.ModuleType).Named(r.ModuleType.FullName).LifeStyle.Scoped<NancyPerWebRequestScopeAccessor>()) .Cast<IRegistration>().ToArray(); this.ApplicationContainer.Register(components); } /// <summary> /// Register the bootstrapper's implemented types into the container. /// This is necessary so a user can pass in a populated container but not have /// to take the responsibility of registering things like INancyModuleCatalog manually. /// </summary> /// <param name="applicationContainer">Application container to register into</param> protected override void RegisterBootstrapperTypes(IWindsorContainer applicationContainer) { applicationContainer.Register(Component.For<INancyModuleCatalog>().Instance(this)); // DefaultRouteCacheProvider doesn't have a parameterless constructor. // It has a Func<IRouteCache> parameter, which Castle Windsor doesn't know how to handle var routeCacheFactory = new Func<IRouteCache>(applicationContainer.Resolve<IRouteCache>); applicationContainer.Register(Component.For<Func<IRouteCache>>().Instance(routeCacheFactory)); } /// <summary> /// Register the default implementations of internally used types into the container as singletons /// </summary> /// <param name="container"> Container to register into </param> /// <param name="typeRegistrations"> Type registrations to register </param> protected override void RegisterTypes(IWindsorContainer container, IEnumerable<TypeRegistration> typeRegistrations) { foreach (var typeRegistration in typeRegistrations) { RegisterNewOrAddService(container, typeRegistration.RegistrationType, typeRegistration.ImplementationType, typeRegistration.Lifetime); } } /// <summary> /// Register the various collections into the container as singletons to later be resolved by IEnumerable{Type} constructor dependencies. /// </summary> /// <param name="container"> Container to register into </param> /// <param name="collectionTypeRegistrations"> Collection type registrations to register </param> protected override void RegisterCollectionTypes(IWindsorContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations) { foreach (var typeRegistration in collectionTypeRegistrations) { foreach (var implementationType in typeRegistration.ImplementationTypes) { RegisterNewOrAddService(container, typeRegistration.RegistrationType, implementationType, typeRegistration.Lifetime); } } } /// <summary> /// Register the given instances into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="instanceRegistrations">Instance registration types</param> protected override void RegisterInstances(IWindsorContainer container, IEnumerable<InstanceRegistration> instanceRegistrations) { foreach (var instanceRegistration in instanceRegistrations) { container.Register(Component.For(instanceRegistration.RegistrationType) .Instance(instanceRegistration.Implementation)); } } private static void RegisterNewOrAddService(IWindsorContainer container, Type registrationType, Type implementationType, Lifetime lifetime) { var handler = container.Kernel.GetHandler(implementationType); if (handler != null) { handler.ComponentModel.AddService(registrationType); return; } var lifeStyle = LifestyleType.Singleton; switch (lifetime) { case Lifetime.Transient: container.Register( Component.For(implementationType, registrationType) .LifestyleTransient() .ImplementedBy(implementationType)); break; case Lifetime.Singleton: container.Register( Component.For(implementationType, registrationType) .LifestyleSingleton() .ImplementedBy(implementationType)); break; case Lifetime.PerRequest: container.Register( Component.For(implementationType, registrationType) .LifestyleScoped(typeof(NancyPerWebRequestScopeAccessor)) .ImplementedBy(implementationType)); break; default: throw new ArgumentOutOfRangeException("lifetime"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Text; using System.Text.RegularExpressions; namespace System.Data.Common { public abstract class DbCommandBuilder : Component { 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 = string.Empty; private string _quoteSuffix = string.Empty; private string _parameterNamePattern = null; private string _parameterMarkerFormat = null; private int _parameterNameMaxLength = 0; protected DbCommandBuilder() : base() { } [DefaultValueAttribute(ConflictOption.CompareAllSearchableValues)] public virtual ConflictOption ConflictOption { 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)] public virtual CatalogLocation CatalogLocation { 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)] public virtual string CatalogSeparator { 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)] public DbDataAdapter DataAdapter { 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("")] public virtual string QuotePrefix { get { return _quotePrefix ?? string.Empty; } set { if (null != _dbSchemaTable) { throw ADP.NoQuoteChange(); } _quotePrefix = value; } } [DefaultValueAttribute("")] public virtual string QuoteSuffix { get { string quoteSuffix = _quoteSuffix; return ((null != quoteSuffix) ? quoteSuffix : string.Empty); } set { if (null != _dbSchemaTable) { throw ADP.NoQuoteChange(); } _quoteSuffix = value; } } [DefaultValueAttribute(DbCommandBuilder.NameSeparator)] public virtual string SchemaSeparator { get { string schemaSeparator = _schemaSeparator; return (((null != schemaSeparator) && (0 < schemaSeparator.Length)) ? schemaSeparator : NameSeparator); } set { if (null != _dbSchemaTable) { throw ADP.NoQuoteChange(); } _schemaSeparator = value; } } [DefaultValueAttribute(false)] 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) { // 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(); } 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); } protected virtual 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); if ((null == rows) || (0 == rows.Length)) { throw ADP.DynamicSQLNoTableInfo(); } string baseServerName = string.Empty; string baseCatalogName = string.Empty; string baseSchemaName = string.Empty; 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 = string.Empty; } if (null == catalogName) { catalogName = string.Empty; } if (null == schemaName) { schemaName = string.Empty; } 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 (!string.IsNullOrEmpty(quotePrefix) && (-1 != baseTableName.IndexOf(quotePrefix, StringComparison.Ordinal))) { throw ADP.DynamicSQLNestedQuote(baseTableName, quotePrefix); } if (!string.IsNullOrEmpty(quoteSuffix) && (-1 != baseTableName.IndexOf(quoteSuffix, StringComparison.Ordinal))) { throw ADP.DynamicSQLNestedQuote(baseTableName, quoteSuffix); } System.Text.StringBuilder builder = new System.Text.StringBuilder(); if (CatalogLocation.Start == location) { 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) { 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(!string.IsNullOrEmpty(_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(!string.IsNullOrEmpty(_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(!string.IsNullOrEmpty(_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(!string.IsNullOrEmpty(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.s_parameterValueNullValue : DbDataAdapter.s_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); } } protected override void Dispose(bool disposing) { 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() { DbCommand select = null; DbDataAdapter adapter = DataAdapter; if (null != adapter) { if (0 == _missingMappingAction) { _missingMappingAction = adapter.MissingMappingAction; } select = 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 = adapter.SelectCommand; if (select != null) { return select.Connection; } } return null; } public DbCommand GetInsertCommand() { return GetInsertCommand(null, false); } public DbCommand GetInsertCommand(bool useColumnsForParameterNames) { return GetInsertCommand(null, useColumnsForParameterNames); } internal DbCommand GetInsertCommand(DataRow dataRow, bool useColumnsForParameterNames) { BuildCache(true, dataRow, useColumnsForParameterNames); BuildInsertCommand(GetTableMapping(dataRow), dataRow); return InsertCommand; } public DbCommand GetUpdateCommand() { return GetUpdateCommand(null, false); } public DbCommand GetUpdateCommand(bool useColumnsForParameterNames) { return GetUpdateCommand(null, useColumnsForParameterNames); } internal DbCommand GetUpdateCommand(DataRow dataRow, bool useColumnsForParameterNames) { BuildCache(true, dataRow, useColumnsForParameterNames); BuildUpdateCommand(GetTableMapping(dataRow), dataRow); return UpdateCommand; } public DbCommand GetDeleteCommand() { return GetDeleteCommand(null, false); } public DbCommand GetDeleteCommand(bool useColumnsForParameterNames) { return GetDeleteCommand(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 (!string.IsNullOrEmpty(columnName)) { column = tablemapping.GetDataColumn(columnName, null, row.Table, _missingMappingAction, MissingSchemaAction.Error); } return column; } private static DbParameter GetNextParameter(DbCommand command, int pcount) { DbParameter p; if (pcount < command.Parameters.Count) { p = command.Parameters[pcount]; } else { p = command.CreateParameter(); /*if (null == p) { // CONSIDER: throw exception }*/ } Debug.Assert(null != p, "null CreateParameter"); return p; } private bool IncludeInInsertValues(DbSchemaRow row) { // NOTE: Include ignore condition - i.e. ignore if 'row' is IsReadOnly else include return (!row.IsAutoIncrement && !row.IsHidden && !row.IsExpression && !row.IsRowVersion && !row.IsReadOnly); } private bool IncludeInUpdateSet(DbSchemaRow row) { // NOTE: Include ignore condition - i.e. ignore if 'row' is IsReadOnly else include return (!row.IsAutoIncrement && !row.IsRowVersion && !row.IsHidden && !row.IsReadOnly); } private bool IncludeInWhereClause(DbSchemaRow row, bool isUpdate) { bool flag = IncrementWhereCount(row); if (flag && row.IsHidden) { 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); } } protected virtual DbCommand InitializeCommand(DbCommand command) { if (null == command) { DbCommand select = GetSelectCommand(); command = select.Connection.CreateCommand(); /*if (null == command) { // CONSIDER: throw exception }*/ // 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(); } public virtual void RefreshSchema() { _dbSchemaTable = null; _dbSchemaRows = null; _sourceColumnNames = null; _quotedBaseTableName = null; DbDataAdapter adapter = DataAdapter; if (null != adapter) { 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; } private static 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(nameof(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)) { DbDataAdapter adapter = DataAdapter; DbCommand select = ((null != adapter) ? adapter.SelectCommand : null); if (null != select) { command.Connection = select.Connection; } } // user command, not a command builder command } else command = null; } if (null == command) { RowUpdatingHandlerBuilder(rowUpdatingEvent); } } } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ADP.TraceExceptionForCapture(e); rowUpdatingEvent.Status = UpdateStatus.ErrorsOccurred; rowUpdatingEvent.Errors = e; } } private void RowUpdatingHandlerBuilder(RowUpdatingEventArgs rowUpdatingEvent) { // 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(); } protected abstract void ApplyParameterInfo(DbParameter parameter, DataRow row, StatementType statementType, bool whereClause); protected abstract string GetParameterName(int parameterOrdinal); protected abstract string GetParameterName(string parameterName); protected abstract string GetParameterPlaceholder(int parameterOrdinal); protected abstract void SetRowUpdatingHandler(DbDataAdapter adapter); // Note: Per definition (ODBC reference) the CatalogSeparator comes before and after the // catalog name, the SchemaSeparator is undefined. Does it come between Schema and Table? // internal static 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 (!string.IsNullOrEmpty(name)) { bool useQuotes = !string.IsNullOrEmpty(quotePrefix) && !string.IsNullOrEmpty(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 UnityEngine; using System.Collections; public class GameOverPage : FPage { private static Starfield background; private static Starfield background2; public FSprite menuBackground; public static FSprite menuAnims; private FButton btnInstructions; private FButton btnGameCenter; private bool playingTransition = false; private bool playReverse = false; private bool transitionIn = false; private int frameCount = 0; private int animationCounter = 0; private FSprite digit1, digit2, digit3; private FSprite hsDigit1, hsDigit2, hsDigit3; private int value1, value2, value3; private FSprite flash; private bool goingtoMenu = false; private static FButton btnPlay; // Use this for initialization override public void Start () { transitionIn = true; InitScript.inGame = false; background = new Starfield(0,false); Futile.stage.AddChild(background); background2 = new Starfield(320 + 80, false); Futile.stage.AddChild(background2); menuBackground = new FSprite("MenuStatic.png"); menuBackground.scale = 2.0f; menuBackground.x = 0; menuBackground.isVisible = false; Futile.stage.AddChild(menuBackground); menuAnims = new FSprite("Menutoplay6.png"); menuAnims.scale = 2.0f; menuAnims.x = 0; Futile.stage.AddChild(menuAnims); btnInstructions = new FButton("MenuButton.png"); btnInstructions.x -= 1; btnInstructions.y -= 126; btnInstructions.scale = 2.0f; btnInstructions.isVisible = false; Futile.stage.AddChild(btnInstructions); btnGameCenter = new FButton("GCButton.png"); btnGameCenter.x -= 1; btnGameCenter.y -= 166; btnGameCenter.scale = 2.0f; btnGameCenter.isVisible = false; Futile.stage.AddChild(btnGameCenter); //score stuffffff digit1 = new FSprite("0.png"); digit1.scale = 2.0f; digit1.x = -159.7772f + 180; digit1.y = Futile.screen.halfHeight - 57; Futile.stage.AddChild(digit1); digit2 = new FSprite("0.png"); digit2.scale = 2.0f; digit2.x = -159.7772f + 160; digit2.y = Futile.screen.halfHeight - 57; Futile.stage.AddChild(digit2); digit3 = new FSprite("0.png"); digit3.scale = 2.0f; digit3.x = -159.7772f + 140; digit3.y = Futile.screen.halfHeight - 57; Futile.stage.AddChild(digit3); hsDigit1 = new FSprite("0.png"); hsDigit1.scale = 2.0f; hsDigit1.x = -159.7772f + 180; hsDigit1.y = Futile.screen.halfHeight - 123; hsDigit1.isVisible = false; Futile.stage.AddChild(hsDigit1); hsDigit2 = new FSprite("0.png"); hsDigit2.scale = 2.0f; hsDigit2.x = -159.7772f + 160; hsDigit2.y = Futile.screen.halfHeight - 123; hsDigit2.isVisible = false; Futile.stage.AddChild(hsDigit2); hsDigit3 = new FSprite("0.png"); hsDigit3.scale = 2.0f; hsDigit3.x = -159.7772f + 140; hsDigit3.y = Futile.screen.halfHeight - 123; hsDigit3.isVisible = false; Futile.stage.AddChild(hsDigit3); flash = new FSprite("GameOverAnim0.png"); flash.scale = 2.0f; flash.x = 0; flash.isVisible = false; Futile.stage.AddChild(flash); btnPlay = new FButton("PlayButton.png"); btnPlay.x = 0; btnPlay.y = 0; btnPlay.scale = 2.0f; Futile.stage.AddChild(btnPlay); btnInstructions.SignalRelease += HandleInfoButtonRelease; btnGameCenter.SignalRelease += HandleGCButtonRelease; btnPlay.SignalRelease += HandlePlayButtonRelease; Futile.instance.SignalUpdate += HandleUpdate; //score things if (InitScript.hsD1 == 0) hsDigit1.SetElementByName("0.png"); else if (InitScript.hsD1 == 1) hsDigit1.SetElementByName("1.png"); else if (InitScript.hsD1 == 2) hsDigit1.SetElementByName("2.png"); else if (InitScript.hsD1 == 3) hsDigit1.SetElementByName("3.png"); else if (InitScript.hsD1 == 4) hsDigit1.SetElementByName("4.png"); else if (InitScript.hsD1 == 5) hsDigit1.SetElementByName("5.png"); else if (InitScript.hsD1 == 6) hsDigit1.SetElementByName("6.png"); else if (InitScript.hsD1 == 7) hsDigit1.SetElementByName("7.png"); else if (InitScript.hsD1 == 8) hsDigit1.SetElementByName("8.png"); else if (InitScript.hsD1 == 9) hsDigit1.SetElementByName("9.png"); //the second value if (InitScript.hsD2 == 0) hsDigit2.SetElementByName("0.png"); else if (InitScript.hsD2 == 1) hsDigit2.SetElementByName("1.png"); else if (InitScript.hsD2 == 2) hsDigit2.SetElementByName("2.png"); else if (InitScript.hsD2 == 3) hsDigit2.SetElementByName("3.png"); else if (InitScript.hsD2 == 4) hsDigit2.SetElementByName("4.png"); else if (InitScript.hsD2 == 5) hsDigit2.SetElementByName("5.png"); else if (InitScript.hsD2 == 6) hsDigit2.SetElementByName("6.png"); else if (InitScript.hsD2 == 7) hsDigit2.SetElementByName("7.png"); else if (InitScript.hsD2 == 8) hsDigit2.SetElementByName("8.png"); else if (InitScript.hsD2 == 9) hsDigit2.SetElementByName("9.png"); //the third digit if (InitScript.hsD3 == 0) hsDigit3.SetElementByName("0.png"); else if (InitScript.hsD3 == 1) hsDigit3.SetElementByName("1.png"); else if (InitScript.hsD3 == 2) hsDigit3.SetElementByName("2.png"); else if (InitScript.hsD3 == 3) hsDigit3.SetElementByName("3.png"); else if (InitScript.hsD3 == 4) hsDigit3.SetElementByName("4.png"); else if (InitScript.hsD3 == 5) hsDigit3.SetElementByName("5.png"); else if (InitScript.hsD3 == 6) hsDigit3.SetElementByName("6.png"); else if (InitScript.hsD3 == 7) hsDigit3.SetElementByName("7.png"); else if (InitScript.hsD3 == 8) hsDigit3.SetElementByName("8.png"); else if (InitScript.hsD3 == 9) hsDigit3.SetElementByName("9.png"); //non highscores if (InitScript.oldD1 == 0) digit1.SetElementByName("0.png"); else if (InitScript.oldD1 == 1) digit1.SetElementByName("1.png"); else if (InitScript.oldD1 == 2) digit1.SetElementByName("2.png"); else if (InitScript.oldD1 == 3) digit1.SetElementByName("3.png"); else if (InitScript.oldD1 == 4) digit1.SetElementByName("4.png"); else if (InitScript.oldD1 == 5) digit1.SetElementByName("5.png"); else if (InitScript.oldD1 == 6) digit1.SetElementByName("6.png"); else if (InitScript.oldD1 == 7) digit1.SetElementByName("7.png"); else if (InitScript.oldD1 == 8) digit1.SetElementByName("8.png"); else if (InitScript.oldD1 == 9) digit1.SetElementByName("9.png"); if (InitScript.oldD2 == 0) digit2.SetElementByName("0.png"); else if (InitScript.oldD2 == 1) digit2.SetElementByName("1.png"); else if (InitScript.oldD2 == 2) digit2.SetElementByName("2.png"); else if (InitScript.oldD2 == 3) digit2.SetElementByName("3.png"); else if (InitScript.oldD2 == 4) digit2.SetElementByName("4.png"); else if (InitScript.oldD2 == 5) digit2.SetElementByName("5.png"); else if (InitScript.oldD2 == 6) digit2.SetElementByName("6.png"); else if (InitScript.oldD2 == 7) digit2.SetElementByName("7.png"); else if (InitScript.oldD2 == 8) digit2.SetElementByName("8.png"); else if (InitScript.oldD2 == 9) digit2.SetElementByName("9.png"); if (InitScript.oldD3 == 0) digit3.SetElementByName("0.png"); else if (InitScript.oldD3 == 1) digit3.SetElementByName("1.png"); else if (InitScript.oldD3 == 2) digit3.SetElementByName("2.png"); else if (InitScript.oldD3 == 3) digit3.SetElementByName("3.png"); else if (InitScript.oldD3 == 4) digit3.SetElementByName("4.png"); else if (InitScript.oldD3 == 5) digit3.SetElementByName("5.png"); else if (InitScript.oldD3 == 6) digit3.SetElementByName("6.png"); else if (InitScript.oldD3 == 7) digit3.SetElementByName("7.png"); else if (InitScript.oldD3 == 8) digit3.SetElementByName("8.png"); else if (InitScript.oldD3 == 9) digit3.SetElementByName("9.png"); InitScript.blackBar1.MoveToTop(); InitScript.blackBar2.MoveToTop(); } override public void HandleAddedToStage() { base.HandleAddedToStage(); } private void HandlePlayButtonRelease(FButton button) { if (InitScript.inGame == false) playAnimation(); } override public void HandleRemovedFromStage() { Destroy(); Futile.instance.SignalUpdate -= HandleUpdate; base.HandleRemovedFromStage(); } public static void Destroy() { Futile.stage.RemoveChild(background); Futile.stage.RemoveChild(background2); Futile.stage.RemoveChild(menuAnims); //Futile.stage.RemoveChild(btnInstructions); } private void HandleInfoButtonRelease (FButton button) { if (InitScript.inGame == false) { Social.ShowLeaderboardUI(); } } // Update is called once per frame private void HandleGCButtonRelease (FButton button) { if (InitScript.inGame == false) { goingtoMenu = true; InitScript.shouldPlayMenuTransition = true; playMenuAnim(); } } private void playMenuAnim() { Futile.stage.RemoveChild(menuBackground); btnInstructions.isVisible = false; playingTransition = true; Futile.stage.RemoveChild(flash); Futile.stage.RemoveChild(digit1); Futile.stage.RemoveChild(digit2); Futile.stage.RemoveChild(digit3); Futile.stage.RemoveChild(hsDigit1); Futile.stage.RemoveChild(hsDigit2); Futile.stage.RemoveChild(hsDigit3); } private void playAnimation() { Futile.stage.RemoveChild(menuBackground); btnInstructions.isVisible = false; playingTransition = true; Futile.stage.RemoveChild(flash); Futile.stage.RemoveChild(digit1); Futile.stage.RemoveChild(digit2); Futile.stage.RemoveChild(digit3); Futile.stage.RemoveChild(hsDigit1); Futile.stage.RemoveChild(hsDigit2); Futile.stage.RemoveChild(hsDigit3); } protected void HandleUpdate () { background.Update(); InitScript.bg1Pos = background.x; background2.Update(); InitScript.bg2Pos = background2.x; frameCount++; if (transitionIn == true) { if (frameCount % 3 == 0) { animationCounter++; if (animationCounter == 0) menuAnims.SetElementByName("GametoGameover0.png"); else if (animationCounter == 1) menuAnims.SetElementByName("GametoGameover1.png"); else if (animationCounter == 2) menuAnims.SetElementByName("GametoGameover2.png"); else if (animationCounter == 3) menuAnims.SetElementByName("GametoGameover3.png"); else if (animationCounter == 4) menuAnims.SetElementByName("GametoGameover4.png"); else if (animationCounter == 5) menuAnims.SetElementByName("GametoGameover5.png"); else if (animationCounter == 6) menuAnims.SetElementByName("GametoGameover6.png"); else if (animationCounter == 7) { //menuAnims.isVisible = true; transitionIn = false; menuAnims.SetElementByName("GameOverStatic.png"); flash.isVisible = true; hsDigit1.isVisible = true; hsDigit2.isVisible = true; hsDigit3.isVisible = true; } } } if (playingTransition == false && transitionIn == false) { if (frameCount % 5 == 0) { animationCounter++; if (animationCounter >= 4) animationCounter = 0; if (animationCounter == 0) flash.SetElementByName("GameOverAnim0.png"); else if (animationCounter == 1) flash.SetElementByName("GameOverAnim1.png"); else if (animationCounter == 2) flash.SetElementByName("GameOverAnim2.png"); else if (animationCounter == 3) flash.SetElementByName("GameOverAnim3.png"); } } else if (playingTransition == true) { if (frameCount % 3 == 0) { animationCounter++; if (animationCounter == 0) menuAnims.SetElementByName("GametoGameover6.png"); else if (animationCounter == 1) menuAnims.SetElementByName("GametoGameover5.png"); else if (animationCounter == 2) menuAnims.SetElementByName("GametoGameover4.png"); else if (animationCounter == 3) menuAnims.SetElementByName("GametoGameover3.png"); else if (animationCounter == 4) menuAnims.SetElementByName("GametoGameover2.png"); else if (animationCounter == 5) menuAnims.SetElementByName("GametoGameover1.png"); else if (animationCounter == 6) menuAnims.SetElementByName("GametoGameover0.png"); else if (animationCounter == 7) { if (goingtoMenu == true) InitScript.gotoMenu(); else InitScript.goToGame(); } } } /*if (Input.GetMouseButtonDown(0)) { if (InitScript.inGame == false) InitScript.goToGame(); }*/ } }
using System; using System.IO; using System.Net.Sockets; using System.Text; using System.Reflection; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using FluentFTP.Proxy; using SysSslProtocols = System.Security.Authentication.SslProtocols; using FluentFTP.Servers; using FluentFTP.Helpers; #if !CORE using System.Web; #endif #if (CORE || NETFX) using System.Threading; #endif #if ASYNC using System.Threading.Tasks; #endif namespace FluentFTP { /// <summary> /// A connection to a single FTP server. Interacts with any FTP/FTPS server and provides a high-level and low-level API to work with files and folders. /// /// Debugging problems with FTP is much easier when you enable logging. See the FAQ on our Github project page for more info. /// </summary> public partial class FtpClient : IDisposable { #region Constructor / Destructor /// <summary> /// Creates a new instance of an FTP Client. /// </summary> public FtpClient() { m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host. /// </summary> public FtpClient(string host) { Host = host ?? throw new ArgumentNullException(nameof(host), "Host must be provided"); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host and credentials. /// </summary> public FtpClient(string host, NetworkCredential credentials) { Host = host ?? throw new ArgumentNullException(nameof(host), "Host must be provided"); Credentials = credentials ?? throw new ArgumentNullException(nameof(credentials), "Credentials must be provided"); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, port and credentials. /// </summary> public FtpClient(string host, int port, NetworkCredential credentials) { Host = host ?? throw new ArgumentNullException(nameof(host), "Host must be provided"); Port = port; Credentials = credentials ?? throw new ArgumentNullException(nameof(credentials), "Credentials must be provided"); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, username and password. /// </summary> public FtpClient(string host, string user, string pass) { Host = host; Credentials = new NetworkCredential(user, pass); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, username, password and account /// </summary> public FtpClient(string host, string user, string pass, string account) { Host = host; Credentials = new NetworkCredential(user, pass, account); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, port, username and password. /// </summary> public FtpClient(string host, int port, string user, string pass) { Host = host; Port = port; Credentials = new NetworkCredential(user, pass); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, port, username, password and account /// </summary> public FtpClient(string host, int port, string user, string pass, string account) { Host = host; Port = port; Credentials = new NetworkCredential(user, pass, account); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host. /// </summary> public FtpClient(Uri host) { Host = ValidateHost(host); Port = host.Port; m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host and credentials. /// </summary> public FtpClient(Uri host, NetworkCredential credentials) { Host = ValidateHost(host); Port = host.Port; Credentials = credentials; m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host and credentials. /// </summary> public FtpClient(Uri host, string user, string pass) { Host = ValidateHost(host); Port = host.Port; Credentials = new NetworkCredential(user, pass); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host and credentials. /// </summary> public FtpClient(Uri host, string user, string pass, string account) { Host = ValidateHost(host); Port = host.Port; Credentials = new NetworkCredential(user, pass, account); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, port and credentials. /// </summary> public FtpClient(Uri host, int port, string user, string pass) { Host = ValidateHost(host); Port = port; Credentials = new NetworkCredential(user, pass); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, port and credentials. /// </summary> public FtpClient(Uri host, int port, string user, string pass, string account) { Host = ValidateHost(host); Port = port; Credentials = new NetworkCredential(user, pass, account); m_listParser = new FtpListParser(this); } /// <summary> /// Check if the host parameter is valid /// </summary> /// <param name="host"></param> private static string ValidateHost(Uri host) { if (host == null) { throw new ArgumentNullException(nameof(host), "Host is required"); } #if !CORE if (host.Scheme != Uri.UriSchemeFtp) { throw new ArgumentException("Host is not a valid FTP path"); } #endif return host.Host; } /// <summary> /// Creates a new instance of this class. Useful in FTP proxy classes. /// </summary> /// <returns></returns> protected virtual FtpClient Create() { return new FtpClient(); } /// <summary> /// Disconnects from the server, releases resources held by this /// object. /// </summary> public virtual void Dispose() { #if !CORE14 lock (m_lock) { #endif if (IsDisposed) { return; } // Fix: Hard catch and suppress all exceptions during disposing as there are constant issues with this method try { LogFunc(nameof(Dispose)); LogStatus(FtpTraceLevel.Verbose, "Disposing FtpClient object..."); } catch (Exception ex) { } try { if (IsConnected) { Disconnect(); } } catch (Exception ex) { } if (m_stream != null) { try { m_stream.Dispose(); } catch (Exception ex) { } m_stream = null; } try { m_credentials = null; m_textEncoding = null; m_host = null; m_asyncmethods.Clear(); } catch (Exception ex) { } IsDisposed = true; GC.SuppressFinalize(this); #if !CORE14 } #endif } /// <summary> /// Finalizer /// </summary> ~FtpClient() { Dispose(); } #endregion #region Clone /// <summary> /// Clones the control connection for opening multiple data streams /// </summary> /// <returns>A new control connection with the same property settings as this one</returns> protected FtpClient CloneConnection() { var conn = Create(); conn.m_isClone = true; // configure new connection as clone of self conn.InternetProtocolVersions = InternetProtocolVersions; conn.SocketPollInterval = SocketPollInterval; conn.StaleDataCheck = StaleDataCheck; conn.EnableThreadSafeDataConnections = EnableThreadSafeDataConnections; conn.NoopInterval = NoopInterval; conn.Encoding = Encoding; conn.Host = Host; conn.Port = Port; conn.Credentials = Credentials; conn.MaximumDereferenceCount = MaximumDereferenceCount; conn.ClientCertificates = ClientCertificates; conn.DataConnectionType = DataConnectionType; conn.UngracefullDisconnection = UngracefullDisconnection; conn.ConnectTimeout = ConnectTimeout; conn.ReadTimeout = ReadTimeout; conn.DataConnectionConnectTimeout = DataConnectionConnectTimeout; conn.DataConnectionReadTimeout = DataConnectionReadTimeout; conn.SocketKeepAlive = SocketKeepAlive; conn.m_capabilities = m_capabilities; conn.EncryptionMode = EncryptionMode; conn.DataConnectionEncryption = DataConnectionEncryption; conn.SslProtocols = SslProtocols; conn.SslBuffering = SslBuffering; conn.TransferChunkSize = TransferChunkSize; conn.LocalFileBufferSize = LocalFileBufferSize; conn.ListingDataType = ListingDataType; conn.ListingParser = ListingParser; conn.ListingCulture = ListingCulture; conn.ListingCustomParser = ListingCustomParser; conn.TimeZone = TimeZone; conn.TimeConversion = TimeConversion; conn.RetryAttempts = RetryAttempts; conn.UploadRateLimit = UploadRateLimit; conn.DownloadZeroByteFiles = DownloadZeroByteFiles; conn.DownloadRateLimit = DownloadRateLimit; conn.DownloadDataType = DownloadDataType; conn.UploadDataType = UploadDataType; conn.ActivePorts = ActivePorts; conn.PassiveBlockedPorts = PassiveBlockedPorts; conn.PassiveMaxAttempts = PassiveMaxAttempts; conn.SendHost = SendHost; conn.SendHostDomain = SendHostDomain; conn.FXPDataType = FXPDataType; conn.FXPProgressInterval = FXPProgressInterval; conn.ServerHandler = ServerHandler; conn.UploadDirectoryDeleteExcluded = UploadDirectoryDeleteExcluded; conn.DownloadDirectoryDeleteExcluded = DownloadDirectoryDeleteExcluded; // configure new connection as clone of self (newer version .NET only) #if ASYNC && !CORE14 && !CORE16 conn.SocketLocalIp = SocketLocalIp; #endif // configure new connection as clone of self (.NET core props only) #if CORE conn.LocalTimeZone = LocalTimeZone; #endif // fix for #428: OpenRead with EnableThreadSafeDataConnections always uses ASCII conn.CurrentDataType = CurrentDataType; conn.ForceSetDataType = true; // configure new connection as clone of self (.NET framework props only) #if !CORE conn.PlainTextEncryption = PlainTextEncryption; #endif // always accept certificate no matter what because if code execution ever // gets here it means the certificate on the control connection object being // cloned was already accepted. conn.ValidateCertificate += new FtpSslValidation( delegate (FtpClient obj, FtpSslValidationEventArgs e) { e.Accept = true; }); return conn; } #endregion #region Connect private FtpListParser m_listParser; /// <summary> /// Connect to the server /// </summary> /// <exception cref="ObjectDisposedException">Thrown if this object has been disposed.</exception> public virtual void Connect() { FtpReply reply; #if !CORE14 lock (m_lock) { #endif LogFunc(nameof(Connect)); if (IsDisposed) { throw new ObjectDisposedException("This FtpClient object has been disposed. It is no longer accessible."); } if (m_stream == null) { m_stream = new FtpSocketStream(this); m_stream.ValidateCertificate += new FtpSocketStreamSslValidation(FireValidateCertficate); } else { if (IsConnected) { Disconnect(); } } if (Host == null) { throw new FtpException("No host has been specified"); } if (m_capabilities == null) { m_capabilities = new List<FtpCapability>(); } ResetStateFlags(); m_hashAlgorithms = FtpHashAlgorithm.NONE; m_stream.ConnectTimeout = m_connectTimeout; m_stream.SocketPollInterval = m_socketPollInterval; Connect(m_stream); m_stream.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_keepAlive); #if !NO_SSL if (EncryptionMode == FtpEncryptionMode.Implicit) { m_stream.ActivateEncryption(Host, m_clientCerts.Count > 0 ? m_clientCerts : null, m_SslProtocols); } #endif Handshake(); m_serverType = FtpServerSpecificHandler.DetectFtpServer(this, HandshakeReply); if (SendHost) { if (!(reply = Execute("HOST " + (SendHostDomain != null ? SendHostDomain : Host))).Success) { throw new FtpException("HOST command failed."); } } #if !NO_SSL // try to upgrade this connection to SSL if supported by the server if (EncryptionMode == FtpEncryptionMode.Explicit || EncryptionMode == FtpEncryptionMode.Auto) { reply = Execute("AUTH TLS"); if (!reply.Success){ _ConnectionFTPSFailure = true; if (EncryptionMode == FtpEncryptionMode.Explicit) { throw new FtpSecurityNotAvailableException("AUTH TLS command failed."); } } else if (reply.Success) { m_stream.ActivateEncryption(Host, m_clientCerts.Count > 0 ? m_clientCerts : null, m_SslProtocols); } } #endif if (m_credentials != null) { Authenticate(); } // configure the default FTPS settings if (IsEncrypted && DataConnectionEncryption) { if (!(reply = Execute("PBSZ 0")).Success) { throw new FtpCommandException(reply); } if (!(reply = Execute("PROT P")).Success) { throw new FtpCommandException(reply); } } // if this is a clone these values should have already been loaded // so save some bandwidth and CPU time and skip executing this again. // otherwise clear the capabilities in case connection is reused to // a different server if (!m_isClone && m_checkCapabilities) { m_capabilities.Clear(); } bool assumeCaps = false; if (m_capabilities.IsBlank() && m_checkCapabilities) { if ((reply = Execute("FEAT")).Success && reply.InfoMessages != null) { GetFeatures(reply); } else { assumeCaps = true; } } // Enable UTF8 if the encoding is ASCII and UTF8 is supported if (m_textEncodingAutoUTF && m_textEncoding == Encoding.ASCII && HasFeature(FtpCapability.UTF8)) { m_textEncoding = Encoding.UTF8; } LogStatus(FtpTraceLevel.Info, "Text encoding: " + m_textEncoding.ToString()); if (m_textEncoding == Encoding.UTF8) { // If the server supports UTF8 it should already be enabled and this // command should not matter however there are conflicting drafts // about this so we'll just execute it to be safe. if ((reply = Execute("OPTS UTF8 ON")).Success) { _ConnectionUTF8Success = true; } } // Get the system type - Needed to auto-detect file listing parser if ((reply = Execute("SYST")).Success) { m_systemType = reply.Message; m_serverType = FtpServerSpecificHandler.DetectFtpServerBySyst(this); m_serverOS = FtpServerSpecificHandler.DetectFtpOSBySyst(this); } // Set a FTP server handler if a custom handler has not already been set if (ServerHandler == null) { ServerHandler = FtpServerSpecificHandler.GetServerHandler(m_serverType); } // Assume the system's capabilities if FEAT command not supported by the server if (assumeCaps) { FtpServerSpecificHandler.AssumeCapabilities(this, ServerHandler, m_capabilities, ref m_hashAlgorithms); } #if !NO_SSL && !CORE if (IsEncrypted && PlainTextEncryption) { if (!(reply = Execute("CCC")).Success) { throw new FtpSecurityNotAvailableException("Failed to disable encryption with CCC command. Perhaps your server does not support it or is not configured to allow it."); } else { // close the SslStream and send close_notify command to server m_stream.DeactivateEncryption(); // read stale data (server's reply?) ReadStaleData(false, true, false); } } #endif // Unless a custom list parser has been set, // Detect the listing parser and prefer machine listings over any other type // FIX : #739 prefer using machine listings to fix issues with GetListing and DeleteDirectory if (ListingParser != FtpParser.Custom) { ListingParser = ServerHandler != null ? ServerHandler.GetParser() : FtpParser.Auto; if (HasFeature(FtpCapability.MLSD)) { ListingParser = FtpParser.Machine; } } // Create the parser even if the auto-OS detection failed m_listParser.Init(m_serverOS, ListingParser); // FIX : #318 always set the type when we create a new connection ForceSetDataType = true; // Execute server-specific post-connection event if (ServerHandler != null) { ServerHandler.AfterConnected(this); } #if !CORE14 } #endif } #if ASYNC // TODO: add example /// <summary> /// Connect to the server /// </summary> /// <exception cref="ObjectDisposedException">Thrown if this object has been disposed.</exception> public virtual async Task ConnectAsync(CancellationToken token = default(CancellationToken)) { FtpReply reply; LogFunc(nameof(ConnectAsync)); if (IsDisposed) { throw new ObjectDisposedException("This FtpClient object has been disposed. It is no longer accessible."); } if (m_stream == null) { m_stream = new FtpSocketStream(this); m_stream.ValidateCertificate += new FtpSocketStreamSslValidation(FireValidateCertficate); } else { if (IsConnected) { Disconnect(); } } if (Host == null) { throw new FtpException("No host has been specified"); } if (m_capabilities == null) { m_capabilities = new List<FtpCapability>(); } ResetStateFlags(); m_hashAlgorithms = FtpHashAlgorithm.NONE; m_stream.ConnectTimeout = m_connectTimeout; m_stream.SocketPollInterval = m_socketPollInterval; await ConnectAsync(m_stream, token); m_stream.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_keepAlive); #if !NO_SSL if (EncryptionMode == FtpEncryptionMode.Implicit) { await m_stream.ActivateEncryptionAsync(Host, m_clientCerts.Count > 0 ? m_clientCerts : null, m_SslProtocols); } #endif await HandshakeAsync(token); m_serverType = FtpServerSpecificHandler.DetectFtpServer(this, HandshakeReply); if (SendHost) { if (!(reply = await ExecuteAsync("HOST " + (SendHostDomain != null ? SendHostDomain : Host), token)).Success) { throw new FtpException("HOST command failed."); } } #if !NO_SSL // try to upgrade this connection to SSL if supported by the server if (EncryptionMode == FtpEncryptionMode.Explicit || EncryptionMode == FtpEncryptionMode.Auto) { reply = await ExecuteAsync("AUTH TLS", token); if (!reply.Success) { _ConnectionFTPSFailure = true; if (EncryptionMode == FtpEncryptionMode.Explicit) { throw new FtpSecurityNotAvailableException("AUTH TLS command failed."); } } else if (reply.Success) { await m_stream.ActivateEncryptionAsync(Host, m_clientCerts.Count > 0 ? m_clientCerts : null, m_SslProtocols); } } #endif if (m_credentials != null) { await AuthenticateAsync(token); } // configure the default FTPS settings if (IsEncrypted && DataConnectionEncryption) { if (!(reply = await ExecuteAsync("PBSZ 0", token)).Success) { throw new FtpCommandException(reply); } if (!(reply = await ExecuteAsync("PROT P", token)).Success) { throw new FtpCommandException(reply); } } // if this is a clone these values should have already been loaded // so save some bandwidth and CPU time and skip executing this again. // otherwise clear the capabilities in case connection is reused to // a different server if (!m_isClone && m_checkCapabilities) { m_capabilities.Clear(); } bool assumeCaps = false; if (m_capabilities.IsBlank() && m_checkCapabilities) { if ((reply = await ExecuteAsync("FEAT", token)).Success && reply.InfoMessages != null) { GetFeatures(reply); } else { assumeCaps = true; } } // Enable UTF8 if the encoding is ASCII and UTF8 is supported if (m_textEncodingAutoUTF && m_textEncoding == Encoding.ASCII && HasFeature(FtpCapability.UTF8)) { m_textEncoding = Encoding.UTF8; } LogStatus(FtpTraceLevel.Info, "Text encoding: " + m_textEncoding.ToString()); if (m_textEncoding == Encoding.UTF8) { // If the server supports UTF8 it should already be enabled and this // command should not matter however there are conflicting drafts // about this so we'll just execute it to be safe. if ((reply = await ExecuteAsync("OPTS UTF8 ON", token)).Success) { _ConnectionUTF8Success = true; } } // Get the system type - Needed to auto-detect file listing parser if ((reply = await ExecuteAsync("SYST", token)).Success) { m_systemType = reply.Message; m_serverType = FtpServerSpecificHandler.DetectFtpServerBySyst(this); m_serverOS = FtpServerSpecificHandler.DetectFtpOSBySyst(this); } // Set a FTP server handler if a custom handler has not already been set if (ServerHandler == null) { ServerHandler = FtpServerSpecificHandler.GetServerHandler(m_serverType); } // Assume the system's capabilities if FEAT command not supported by the server if (assumeCaps) { FtpServerSpecificHandler.AssumeCapabilities(this, ServerHandler, m_capabilities, ref m_hashAlgorithms); } #if !NO_SSL && !CORE if (IsEncrypted && PlainTextEncryption) { if (!(reply = await ExecuteAsync("CCC", token)).Success) { throw new FtpSecurityNotAvailableException("Failed to disable encryption with CCC command. Perhaps your server does not support it or is not configured to allow it."); } else { // close the SslStream and send close_notify command to server m_stream.DeactivateEncryption(); // read stale data (server's reply?) await ReadStaleDataAsync(false, true, false, token); } } #endif // Unless a custom list parser has been set, // Detect the listing parser and prefer machine listings over any other type // FIX : #739 prefer using machine listings to fix issues with GetListing and DeleteDirectory if (ListingParser != FtpParser.Custom) { ListingParser = ServerHandler != null ? ServerHandler.GetParser() : FtpParser.Auto; if (HasFeature(FtpCapability.MLSD)) { ListingParser = FtpParser.Machine; } } // Create the parser even if the auto-OS detection failed m_listParser.Init(m_serverOS, ListingParser); // FIX : #318 always set the type when we create a new connection ForceSetDataType = true; // Execute server-specific post-connection event if (ServerHandler != null) { await ServerHandler.AfterConnectedAsync(this, token); } } #endif /// <summary> /// Connect to the FTP server. Overridden in proxy classes. /// </summary> /// <param name="stream"></param> protected virtual void Connect(FtpSocketStream stream) { stream.Connect(Host, Port, InternetProtocolVersions); } #if ASYNC /// <summary> /// Connect to the FTP server. Overridden in proxy classes. /// </summary> /// <param name="stream"></param> /// <param name="token"></param> protected virtual async Task ConnectAsync(FtpSocketStream stream, CancellationToken token) { await stream.ConnectAsync(Host, Port, InternetProtocolVersions, token); } #endif /// <summary> /// Connect to the FTP server. Overridden in proxy classes. /// </summary> protected virtual void Connect(FtpSocketStream stream, string host, int port, FtpIpVersion ipVersions) { stream.Connect(host, port, ipVersions); } #if ASYNC /// <summary> /// Connect to the FTP server. Overridden in proxy classes. /// </summary> protected virtual Task ConnectAsync(FtpSocketStream stream, string host, int port, FtpIpVersion ipVersions, CancellationToken token) { return stream.ConnectAsync(host, port, ipVersions, token); } #endif protected FtpReply HandshakeReply; /// <summary> /// Called during Connect(). Typically extended by FTP proxies. /// </summary> protected virtual void Handshake() { FtpReply reply; if (!(reply = GetReply()).Success) { if (reply.Code == null) { throw new IOException("The connection was terminated before a greeting could be read."); } else { throw new FtpCommandException(reply); } } HandshakeReply = reply; } #if ASYNC /// <summary> /// Called during <see cref="ConnectAsync()"/>. Typically extended by FTP proxies. /// </summary> protected virtual async Task HandshakeAsync(CancellationToken token = default(CancellationToken)) { FtpReply reply; if (!(reply = await GetReplyAsync(token)).Success) { if (reply.Code == null) { throw new IOException("The connection was terminated before a greeting could be read."); } else { throw new FtpCommandException(reply); } } HandshakeReply = reply; } #endif /// <summary> /// Populates the capabilities flags based on capabilities /// supported by this server. This method is overridable /// so that new features can be supported /// </summary> /// <param name="reply">The reply object from the FEAT command. The InfoMessages property will /// contain a list of the features the server supported delimited by a new line '\n' character.</param> protected virtual void GetFeatures(FtpReply reply) { FtpServerSpecificHandler.GetFeatures(this, m_capabilities, ref m_hashAlgorithms, reply.InfoMessages.Split('\n')); } #if !ASYNC private delegate void AsyncConnect(); /// <summary> /// Initiates a connection to the server /// </summary> /// <param name="callback">AsyncCallback method</param> /// <param name="state">State object</param> /// <returns>IAsyncResult</returns> public IAsyncResult BeginConnect(AsyncCallback callback, object state) { AsyncConnect func; IAsyncResult ar; lock (m_asyncmethods) { ar = (func = Connect).BeginInvoke(callback, state); m_asyncmethods.Add(ar, func); } return ar; } /// <summary> /// Ends an asynchronous connection attempt to the server from <see cref="BeginConnect"/> /// </summary> /// <param name="ar"><see cref="IAsyncResult"/> returned from <see cref="BeginConnect"/></param> public void EndConnect(IAsyncResult ar) { GetAsyncDelegate<AsyncConnect>(ar).EndInvoke(ar); } #endif #endregion #region Login /// <summary> /// Performs a login on the server. This method is overridable so /// that the login procedure can be changed to support, for example, /// a FTP proxy. /// </summary> protected virtual void Authenticate() { Authenticate(Credentials.UserName, Credentials.Password, Credentials.Domain); } #if ASYNC /// <summary> /// Performs a login on the server. This method is overridable so /// that the login procedure can be changed to support, for example, /// a FTP proxy. /// </summary> protected virtual async Task AuthenticateAsync(CancellationToken token) { await AuthenticateAsync(Credentials.UserName, Credentials.Password, Credentials.Domain, token); } #endif /// <summary> /// Performs a login on the server. This method is overridable so /// that the login procedure can be changed to support, for example, /// a FTP proxy. /// </summary> /// <exception cref="FtpAuthenticationException">On authentication failures</exception> /// <remarks> /// To handle authentication failures without retries, catch FtpAuthenticationException. /// </remarks> protected virtual void Authenticate(string userName, string password, string account) { // mark that we are not authenticated m_IsAuthenticated = false; // send the USER command along with the FTP username FtpReply reply = Execute("USER " + userName); // check the reply to the USER command if (!reply.Success) { throw new FtpAuthenticationException(reply); } // if it was accepted else if (reply.Type == FtpResponseType.PositiveIntermediate) { // send the PASS command along with the FTP password reply = Execute("PASS " + password); // fix for #620: some servers send multiple responses that must be read and decoded, // otherwise the connection is aborted and remade and it goes into an infinite loop var staleData = ReadStaleData(false, true, true); if (staleData != null) { var staleReply = new FtpReply(); if (DecodeStringToReply(staleData, ref staleReply) && !staleReply.Success) { throw new FtpAuthenticationException(staleReply); } } // check the first reply to the PASS command if (!reply.Success) { throw new FtpAuthenticationException(reply); } // only possible 3** here is `332 Need account for login` if (reply.Type == FtpResponseType.PositiveIntermediate) { reply = Execute("ACCT " + account); if (!reply.Success) { throw new FtpAuthenticationException(reply); } } // mark that we are authenticated m_IsAuthenticated = true; } } #if ASYNC /// <summary> /// Performs a login on the server. This method is overridable so /// that the login procedure can be changed to support, for example, /// a FTP proxy. /// </summary> /// <exception cref="FtpAuthenticationException">On authentication failures</exception> /// <remarks> /// To handle authentication failures without retries, catch FtpAuthenticationException. /// </remarks> protected virtual async Task AuthenticateAsync(string userName, string password, string account, CancellationToken token) { // send the USER command along with the FTP username FtpReply reply = await ExecuteAsync("USER " + userName, token); // check the reply to the USER command if (!reply.Success) { throw new FtpAuthenticationException(reply); } // if it was accepted else if (reply.Type == FtpResponseType.PositiveIntermediate) { // send the PASS command along with the FTP password reply = await ExecuteAsync("PASS " + password, token); // fix for #620: some servers send multiple responses that must be read and decoded, // otherwise the connection is aborted and remade and it goes into an infinite loop var staleData = await ReadStaleDataAsync(false, true, true, token); if (staleData != null) { var staleReply = new FtpReply(); if (DecodeStringToReply(staleData, ref staleReply) && !staleReply.Success) { throw new FtpAuthenticationException(staleReply); } } // check the first reply to the PASS command if (!reply.Success) { throw new FtpAuthenticationException(reply); } // only possible 3** here is `332 Need account for login` if (reply.Type == FtpResponseType.PositiveIntermediate) { reply = await ExecuteAsync("ACCT " + account, token); if (!reply.Success) { throw new FtpAuthenticationException(reply); } else { m_IsAuthenticated = true; } } else if (reply.Type == FtpResponseType.PositiveCompletion) { m_IsAuthenticated = true; } } } #endif #endregion #region Disconnect /// <summary> /// Disconnects from the server /// </summary> public virtual void Disconnect() { #if !CORE14 lock (m_lock) { #endif if (m_stream != null && m_stream.IsConnected) { try { if (!UngracefullDisconnection) { Execute("QUIT"); } } catch (Exception ex) { LogStatus(FtpTraceLevel.Warn, "FtpClient.Disconnect(): Exception caught and discarded while closing control connection: " + ex.ToString()); } finally { m_stream.Close(); } } #if !CORE14 } #endif } #if !ASYNC private delegate void AsyncDisconnect(); /// <summary> /// Initiates a disconnection on the server /// </summary> /// <param name="callback"><see cref="AsyncCallback"/> method</param> /// <param name="state">State object</param> /// <returns>IAsyncResult</returns> public IAsyncResult BeginDisconnect(AsyncCallback callback, object state) { IAsyncResult ar; AsyncDisconnect func; lock (m_asyncmethods) { ar = (func = Disconnect).BeginInvoke(callback, state); m_asyncmethods.Add(ar, func); } return ar; } /// <summary> /// Ends a call to <see cref="BeginDisconnect"/> /// </summary> /// <param name="ar"><see cref="IAsyncResult"/> returned from <see cref="BeginDisconnect"/></param> public void EndDisconnect(IAsyncResult ar) { GetAsyncDelegate<AsyncDisconnect>(ar).EndInvoke(ar); } #endif #if ASYNC /// <summary> /// Disconnects from the server asynchronously /// </summary> public async Task DisconnectAsync(CancellationToken token = default(CancellationToken)) { if (m_stream != null && m_stream.IsConnected) { try { if (!UngracefullDisconnection) { await ExecuteAsync("QUIT", token); } } catch (Exception ex) { LogStatus(FtpTraceLevel.Warn, "FtpClient.Disconnect(): Exception caught and discarded while closing control connection: " + ex.ToString()); } finally { m_stream.Close(); } } } #endif #endregion #region FTPS /// <summary> /// Catches the socket stream ssl validation event and fires the event handlers /// attached to this object for validating SSL certificates /// </summary> /// <param name="stream">The stream that fired the event</param> /// <param name="e">The event args used to validate the certificate</param> private void FireValidateCertficate(FtpSocketStream stream, FtpSslValidationEventArgs e) { OnValidateCertficate(e); } /// <summary> /// Fires the SSL validation event /// </summary> /// <param name="e">Event Args</param> private void OnValidateCertficate(FtpSslValidationEventArgs e) { // automatically validate if ValidateAnyCertificate is set if (ValidateAnyCertificate) { e.Accept = true; return; } // fallback to manual validation using the ValidateCertificate event m_ValidateCertificate?.Invoke(this, e); } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Iap.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedIdentityAwareProxyOAuthServiceClientSnippets { /// <summary>Snippet for ListBrands</summary> public void ListBrandsRequestObject() { // Snippet: ListBrands(ListBrandsRequest, CallSettings) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = IdentityAwareProxyOAuthServiceClient.Create(); // Initialize request argument(s) ListBrandsRequest request = new ListBrandsRequest { Parent = "", }; // Make the request ListBrandsResponse response = identityAwareProxyOAuthServiceClient.ListBrands(request); // End snippet } /// <summary>Snippet for ListBrandsAsync</summary> public async Task ListBrandsRequestObjectAsync() { // Snippet: ListBrandsAsync(ListBrandsRequest, CallSettings) // Additional: ListBrandsAsync(ListBrandsRequest, CancellationToken) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = await IdentityAwareProxyOAuthServiceClient.CreateAsync(); // Initialize request argument(s) ListBrandsRequest request = new ListBrandsRequest { Parent = "", }; // Make the request ListBrandsResponse response = await identityAwareProxyOAuthServiceClient.ListBrandsAsync(request); // End snippet } /// <summary>Snippet for CreateBrand</summary> public void CreateBrandRequestObject() { // Snippet: CreateBrand(CreateBrandRequest, CallSettings) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = IdentityAwareProxyOAuthServiceClient.Create(); // Initialize request argument(s) CreateBrandRequest request = new CreateBrandRequest { Parent = "", Brand = new Brand(), }; // Make the request Brand response = identityAwareProxyOAuthServiceClient.CreateBrand(request); // End snippet } /// <summary>Snippet for CreateBrandAsync</summary> public async Task CreateBrandRequestObjectAsync() { // Snippet: CreateBrandAsync(CreateBrandRequest, CallSettings) // Additional: CreateBrandAsync(CreateBrandRequest, CancellationToken) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = await IdentityAwareProxyOAuthServiceClient.CreateAsync(); // Initialize request argument(s) CreateBrandRequest request = new CreateBrandRequest { Parent = "", Brand = new Brand(), }; // Make the request Brand response = await identityAwareProxyOAuthServiceClient.CreateBrandAsync(request); // End snippet } /// <summary>Snippet for GetBrand</summary> public void GetBrandRequestObject() { // Snippet: GetBrand(GetBrandRequest, CallSettings) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = IdentityAwareProxyOAuthServiceClient.Create(); // Initialize request argument(s) GetBrandRequest request = new GetBrandRequest { Name = "", }; // Make the request Brand response = identityAwareProxyOAuthServiceClient.GetBrand(request); // End snippet } /// <summary>Snippet for GetBrandAsync</summary> public async Task GetBrandRequestObjectAsync() { // Snippet: GetBrandAsync(GetBrandRequest, CallSettings) // Additional: GetBrandAsync(GetBrandRequest, CancellationToken) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = await IdentityAwareProxyOAuthServiceClient.CreateAsync(); // Initialize request argument(s) GetBrandRequest request = new GetBrandRequest { Name = "", }; // Make the request Brand response = await identityAwareProxyOAuthServiceClient.GetBrandAsync(request); // End snippet } /// <summary>Snippet for CreateIdentityAwareProxyClient</summary> public void CreateIdentityAwareProxyClientRequestObject() { // Snippet: CreateIdentityAwareProxyClient(CreateIdentityAwareProxyClientRequest, CallSettings) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = IdentityAwareProxyOAuthServiceClient.Create(); // Initialize request argument(s) CreateIdentityAwareProxyClientRequest request = new CreateIdentityAwareProxyClientRequest { Parent = "", IdentityAwareProxyClient = new IdentityAwareProxyClient(), }; // Make the request IdentityAwareProxyClient response = identityAwareProxyOAuthServiceClient.CreateIdentityAwareProxyClient(request); // End snippet } /// <summary>Snippet for CreateIdentityAwareProxyClientAsync</summary> public async Task CreateIdentityAwareProxyClientRequestObjectAsync() { // Snippet: CreateIdentityAwareProxyClientAsync(CreateIdentityAwareProxyClientRequest, CallSettings) // Additional: CreateIdentityAwareProxyClientAsync(CreateIdentityAwareProxyClientRequest, CancellationToken) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = await IdentityAwareProxyOAuthServiceClient.CreateAsync(); // Initialize request argument(s) CreateIdentityAwareProxyClientRequest request = new CreateIdentityAwareProxyClientRequest { Parent = "", IdentityAwareProxyClient = new IdentityAwareProxyClient(), }; // Make the request IdentityAwareProxyClient response = await identityAwareProxyOAuthServiceClient.CreateIdentityAwareProxyClientAsync(request); // End snippet } /// <summary>Snippet for ListIdentityAwareProxyClients</summary> public void ListIdentityAwareProxyClientsRequestObject() { // Snippet: ListIdentityAwareProxyClients(ListIdentityAwareProxyClientsRequest, CallSettings) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = IdentityAwareProxyOAuthServiceClient.Create(); // Initialize request argument(s) ListIdentityAwareProxyClientsRequest request = new ListIdentityAwareProxyClientsRequest { Parent = "", }; // Make the request PagedEnumerable<ListIdentityAwareProxyClientsResponse, IdentityAwareProxyClient> response = identityAwareProxyOAuthServiceClient.ListIdentityAwareProxyClients(request); // Iterate over all response items, lazily performing RPCs as required foreach (IdentityAwareProxyClient item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListIdentityAwareProxyClientsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (IdentityAwareProxyClient item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<IdentityAwareProxyClient> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (IdentityAwareProxyClient item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListIdentityAwareProxyClientsAsync</summary> public async Task ListIdentityAwareProxyClientsRequestObjectAsync() { // Snippet: ListIdentityAwareProxyClientsAsync(ListIdentityAwareProxyClientsRequest, CallSettings) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = await IdentityAwareProxyOAuthServiceClient.CreateAsync(); // Initialize request argument(s) ListIdentityAwareProxyClientsRequest request = new ListIdentityAwareProxyClientsRequest { Parent = "", }; // Make the request PagedAsyncEnumerable<ListIdentityAwareProxyClientsResponse, IdentityAwareProxyClient> response = identityAwareProxyOAuthServiceClient.ListIdentityAwareProxyClientsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((IdentityAwareProxyClient item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListIdentityAwareProxyClientsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (IdentityAwareProxyClient item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<IdentityAwareProxyClient> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (IdentityAwareProxyClient item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetIdentityAwareProxyClient</summary> public void GetIdentityAwareProxyClientRequestObject() { // Snippet: GetIdentityAwareProxyClient(GetIdentityAwareProxyClientRequest, CallSettings) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = IdentityAwareProxyOAuthServiceClient.Create(); // Initialize request argument(s) GetIdentityAwareProxyClientRequest request = new GetIdentityAwareProxyClientRequest { Name = "", }; // Make the request IdentityAwareProxyClient response = identityAwareProxyOAuthServiceClient.GetIdentityAwareProxyClient(request); // End snippet } /// <summary>Snippet for GetIdentityAwareProxyClientAsync</summary> public async Task GetIdentityAwareProxyClientRequestObjectAsync() { // Snippet: GetIdentityAwareProxyClientAsync(GetIdentityAwareProxyClientRequest, CallSettings) // Additional: GetIdentityAwareProxyClientAsync(GetIdentityAwareProxyClientRequest, CancellationToken) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = await IdentityAwareProxyOAuthServiceClient.CreateAsync(); // Initialize request argument(s) GetIdentityAwareProxyClientRequest request = new GetIdentityAwareProxyClientRequest { Name = "", }; // Make the request IdentityAwareProxyClient response = await identityAwareProxyOAuthServiceClient.GetIdentityAwareProxyClientAsync(request); // End snippet } /// <summary>Snippet for ResetIdentityAwareProxyClientSecret</summary> public void ResetIdentityAwareProxyClientSecretRequestObject() { // Snippet: ResetIdentityAwareProxyClientSecret(ResetIdentityAwareProxyClientSecretRequest, CallSettings) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = IdentityAwareProxyOAuthServiceClient.Create(); // Initialize request argument(s) ResetIdentityAwareProxyClientSecretRequest request = new ResetIdentityAwareProxyClientSecretRequest { Name = "", }; // Make the request IdentityAwareProxyClient response = identityAwareProxyOAuthServiceClient.ResetIdentityAwareProxyClientSecret(request); // End snippet } /// <summary>Snippet for ResetIdentityAwareProxyClientSecretAsync</summary> public async Task ResetIdentityAwareProxyClientSecretRequestObjectAsync() { // Snippet: ResetIdentityAwareProxyClientSecretAsync(ResetIdentityAwareProxyClientSecretRequest, CallSettings) // Additional: ResetIdentityAwareProxyClientSecretAsync(ResetIdentityAwareProxyClientSecretRequest, CancellationToken) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = await IdentityAwareProxyOAuthServiceClient.CreateAsync(); // Initialize request argument(s) ResetIdentityAwareProxyClientSecretRequest request = new ResetIdentityAwareProxyClientSecretRequest { Name = "", }; // Make the request IdentityAwareProxyClient response = await identityAwareProxyOAuthServiceClient.ResetIdentityAwareProxyClientSecretAsync(request); // End snippet } /// <summary>Snippet for DeleteIdentityAwareProxyClient</summary> public void DeleteIdentityAwareProxyClientRequestObject() { // Snippet: DeleteIdentityAwareProxyClient(DeleteIdentityAwareProxyClientRequest, CallSettings) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = IdentityAwareProxyOAuthServiceClient.Create(); // Initialize request argument(s) DeleteIdentityAwareProxyClientRequest request = new DeleteIdentityAwareProxyClientRequest { Name = "", }; // Make the request identityAwareProxyOAuthServiceClient.DeleteIdentityAwareProxyClient(request); // End snippet } /// <summary>Snippet for DeleteIdentityAwareProxyClientAsync</summary> public async Task DeleteIdentityAwareProxyClientRequestObjectAsync() { // Snippet: DeleteIdentityAwareProxyClientAsync(DeleteIdentityAwareProxyClientRequest, CallSettings) // Additional: DeleteIdentityAwareProxyClientAsync(DeleteIdentityAwareProxyClientRequest, CancellationToken) // Create client IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = await IdentityAwareProxyOAuthServiceClient.CreateAsync(); // Initialize request argument(s) DeleteIdentityAwareProxyClientRequest request = new DeleteIdentityAwareProxyClientRequest { Name = "", }; // Make the request await identityAwareProxyOAuthServiceClient.DeleteIdentityAwareProxyClientAsync(request); // End snippet } } }
// Author: Ghalib Ghniem ghalib@ItInfoPlus.com // Created: 2015-03-25 // Last Modified: 2015-04-14 // using System; using System.Collections.ObjectModel; using System.Web.UI.WebControls; using System.Collections.Generic; using log4net; using mojoPortal.Business; using mojoPortal.Business.WebHelpers; using mojoPortal.Web.Framework; using mojoPortal.Web.AdminUI; using mojoPortal.Web; using iQuran.Business; using iQuran.Web.Helper; using Resources; using mojoPortal.Web.Editor; namespace iQuran.Web.UI.AdminUI { public partial class iQuranManager : NonCmsBasePage { private static readonly ILog log = LogManager.GetLogger(typeof(iQuranManager)); protected string EditPropertiesImage = "~/Data/SiteImages/" + WebConfigSettings.EditPropertiesImage; protected string DeleteLinkImage = "~/Data/SiteImages/" + WebConfigSettings.DeleteLinkImage; private bool canAdministrate = false; protected bool IsUserAdmin = false; private SiteUser currentUser = null; #region Pager Properties private string BindByWhat = "all"; private string sortParam = string.Empty; private string sort = "Title"; private string searchParam = string.Empty; private string search = string.Empty; private string searchTitleParam = string.Empty; private string searchTitle = string.Empty; private bool searchIsActive = false; private int pageNumber = 1; private int pageSize = 0; private int totalPages = 0; #endregion protected void Page_Load(object sender, EventArgs e) { LoadSettings(); if (!this.canAdministrate) { SiteUtils.RedirectToAccessDeniedPage(this); return; } pageSize = int.Parse(ConfigHelper.GetStringProperty("PagerPageSize", "20")); LoadPager(); PopulateLabels(); PopulateControls(); } private void LoadSettings() { if ((WebUser.IsInRole("iQuranManagers")) || (WebUser.IsInRole("iQuranContentsAdmins")) || (WebUser.IsAdmin)) this.canAdministrate = true; else this.canAdministrate = false; if (WebUser.IsAdmin) IsUserAdmin = true; SecurityHelper.DisableBrowserCache(); lnkAdminMenu.Visible = (WebUser.IsAdmin); AddClassToBody("administration"); AddClassToBody("rolemanager"); } private void LoadPager() { pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", 1); if (Page.Request.Params["sort"] != null) { sort = Page.Request.Params["sort"]; } searchTitleParam = "searchtitle"; if ((Page.Request.Params[searchTitleParam] != null) && (Page.Request.Params[searchTitleParam].Length > 0)) { searchTitle = Page.Request.Params[searchTitleParam]; BindByWhat = "title"; search = "0"; } else { searchTitle = string.Empty; searchParam = "search"; if (Page.Request.Params[searchParam] != null) { search = Page.Request.Params[searchParam]; switch (search) { //0: all , 1.active , 2.notactive case "0": default: BindByWhat = "all"; break; case "1": searchIsActive = true; BindByWhat = "active"; break; case "2": searchIsActive = false; BindByWhat = "notactive"; break; } } else { search = "0"; BindByWhat = "all"; } } sortParam = "sort"; if (Page.Request.Params[sortParam] != null) sort = Page.Request.Params[sortParam]; else sort = "Title"; } private void PopulateLabels() { Title = SiteUtils.FormatPageTitle(siteSettings, Resources.iQuranResources.AdminMenuiQuranManagerAdminLink); spnTitle.InnerText = Title; lnkAdminMenu.Text = Resource.AdminMenuLink; lnkAdminMenu.ToolTip = Resource.AdminMenuLink; lnkAdminMenu.NavigateUrl = SiteRoot + "/Admin/AdminMenu.aspx"; lnkAdvanced.Text = Resources.iQuranResources.AdvancedLink; lnkAdvanced.ToolTip = Resources.iQuranResources.AdvancedToolsHeading; lnkAdvanced.NavigateUrl = SiteRoot + "/Admin/AccessQuran/iQuranAdvanced.aspx"; lnkiQuranManagerAdmin.Text = Resources.iQuranResources.AdminMenuiQuranManagerAdminLink; lnkiQuranManagerAdmin.ToolTip = Resources.iQuranResources.AdminMenuiQuranManagerAdminLink; lnkiQuranManagerAdmin.NavigateUrl = SiteRoot + "/Admin/AccessQuran/iQuran/iQuranManager.aspx"; lnkAddNew.Text = Resources.iQuranResources.AddNewiQuranHeader; lnkAddNew.ToolTip = Resources.iQuranResources.AddNewiQuranHeader; lnkAddNew.NavigateUrl = SiteRoot + "/Admin/AccessQuran/iQuran/iQuranEdit.aspx"; lnkAddNew.Visible = (WebUser.IsInRole("iQuranManagers")) || (WebUser.IsAdmin); btnSearchTitle.AlternateText = Resources.iQuranResources.SearchByTitleHeader; btnSearchTitle.ToolTip = Resources.iQuranResources.SearchByTitleHeader; lblmessage.Visible = false; divMsg.Visible = false; } private void PopulateControls() { if (Page.IsPostBack) return; BindGrid(); ddStatus.ClearSelection(); ddStatus.Items.FindByValue(search.ToString()).Selected = true; } private void BindGrid() { bool isAdmin = ((WebUser.IsInRole("iQuranManagers")) || (WebUser.IsInRole("iQuranContentsAdmins")) || (WebUser.IsAdmin)); // Get the Current Loged on UserID SiteUser siteUser = SiteUtils.GetCurrentSiteUser(); int userID = siteUser.UserId; List<Quran> dataList = new List<Quran>(); //0: all , 1.active , 2.notactive , if (this.BindByWhat == "all") dataList = Quran.GetPage_iQuran_All(false, siteSettings.SiteId, isAdmin, pageNumber, pageSize, out totalPages); //Search For Title if (this.BindByWhat == "title") dataList = Quran.GetPage_iQuran_ByTitle(false, siteSettings.SiteId, isAdmin, this.searchTitle, pageNumber, pageSize, out totalPages); if ((this.BindByWhat == "active") || (this.BindByWhat == "notactive")) dataList = Quran.GetPage_iQuran_ByActive(false, siteSettings.SiteId, searchIsActive, pageNumber, pageSize, out totalPages); string pageUrl = string.Empty; pageUrl = SiteRoot + "/Admin/AccessQuran/iQuran/iQuranManager.aspx?" + "sort=" + this.sort + "&amp;search=" + this.search + "&amp;searchtitle=" + Server.UrlEncode(this.searchTitle) + "&amp;pagenumber={0}"; amsPager.PageURLFormat = pageUrl; amsPager.ShowFirstLast = true; amsPager.CurrentIndex = pageNumber; amsPager.PageSize = pageSize; amsPager.PageCount = totalPages; amsPager.Visible = (totalPages > 1); iQGrid.DataSource = dataList; iQGrid.PageIndex = pageNumber; iQGrid.PageSize = pageSize; iQGrid.DataBind(); if (iQGrid.Rows.Count == 0) { lblmessage.Visible = true; divMsg.Visible = true; lblmessage.Text = Resources.iQuranMessagesResources.NoDataYet; } } private void SetRedirectString() { string redirectUrl = string.Empty; redirectUrl = SiteRoot + "/Admin/AccessQuran/iQuran/iQuranManager.aspx?" + "pagenumber=" + pageNumber.ToInvariantString() + "&sort=" + this.sort + "&search=" + this.search + "&searchtitle=" + Server.UrlEncode(this.searchTitle); WebUtils.SetupRedirect(this, redirectUrl); } #region GRID EVENTS void iQGrid_Sorting(object sender, GridViewSortEventArgs e) { this.sort = e.SortExpression; SetRedirectString(); } protected void iQGrid_RowDeleting(object sender, GridViewDeleteEventArgs e) { //DO Nothing; } void iQGrid_RowCommand(object sender, GridViewCommandEventArgs e) { if (log.IsDebugEnabled) { log.Debug(this.PageTitle + " fired event iQGrid_RowCommand"); } int iquranID = int.Parse(e.CommandArgument.ToString()); int siteid = siteSettings.SiteId; string dleteDate = String.Format(DateTime.Now.ToString(), "mm dd yyyy"); currentUser = SiteUtils.GetCurrentSiteUser(); Quran iquran = new Quran(siteid, iquranID); switch (e.CommandName) { case "delete": default: Quran.Delete(siteid, iquranID); //iQGrid.EditIndex = +1; //log it: log.Info("user " + currentUser.Name + " deleted Quran Version : " + iquran.Title + " at: " + dleteDate); BindGrid(); lblmessage.Text = iQuranMessagesResources.DeletedMsg + "<br />"; lblmessage.Visible = true; divMsg.Visible = true; break; } } #endregion #region SEARCH private void CheckSearchWhat() { if (txtSearchByTitle.Text.Trim() == string.Empty) this.searchTitle = string.Empty; else this.searchTitle = SecurityHelper.RemoveMarkup(txtSearchByTitle.Text); search = ddStatus.SelectedValue.ToString(); //0: all , 1.active , 2.notactive } protected void btnSearchTitle_Click(Object sender, EventArgs e) { if (txtSearchByTitle.Text.Trim() == string.Empty) return; this.searchTitle = SecurityHelper.RemoveMarkup(txtSearchByTitle.Text); this.search = "title"; SetRedirectString(); } protected void ddStatus_SelectedIndexChanged(object sender, EventArgs e) { CheckSearchWhat(); SetRedirectString(); } #endregion #region OnInit override protected void OnInit(EventArgs e) { base.OnInit(e); this.Load += new EventHandler(this.Page_Load); this.iQGrid.Sorting += new GridViewSortEventHandler(iQGrid_Sorting); this.iQGrid.RowCommand += new GridViewCommandEventHandler(iQGrid_RowCommand); this.iQGrid.RowDeleting += new GridViewDeleteEventHandler(iQGrid_RowDeleting); SuppressMenuSelection(); SuppressPageMenu(); } protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); } #endregion } }
/* * Munger - An Interface pattern on getting and setting values from object through Reflection * * Author: Phillip Piper * Date: 28/11/2008 17:15 * * Change log: * v2.5.1 * 2012-05-01 JPP - Added IgnoreMissingAspects property * v2.5 * 2011-05-20 JPP - Accessing through an indexer when the target had both a integer and * a string indexer didn't work reliably. * v2.4.1 * 2010-08-10 JPP - Refactored into Munger/SimpleMunger. 3x faster! * v2.3 * 2009-02-15 JPP - Made Munger a public class * 2009-01-20 JPP - Made the Munger capable of handling indexed access. * Incidentally, this removed the ugliness that the last change introduced. * 2009-01-18 JPP - Handle target objects from a DataListView (normally DataRowViews) * v2.0 * 2008-11-28 JPP Initial version * * TO DO: * * Copyright (C) 2006-2014 Phillip Piper * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. */ using System; using System.Collections.Generic; using System.Reflection; namespace BrightIdeasSoftware { /// <summary> /// An instance of Munger gets a value from or puts a value into a target object. The property /// to be peeked (or poked) is determined from a string. The peeking or poking is done using reflection. /// </summary> /// <remarks> /// Name of the aspect to be peeked can be a field, property or parameterless method. The name of an /// aspect to poke can be a field, writable property or single parameter method. /// <para> /// Aspect names can be dotted to chain a series of references. /// </para> /// <example>Order.Customer.HomeAddress.State</example> /// </remarks> public class Munger { #region Life and death /// <summary> /// Create a do nothing Munger /// </summary> public Munger() { } /// <summary> /// Create a Munger that works on the given aspect name /// </summary> /// <param name="aspectName">The name of the </param> public Munger(String aspectName) { this.AspectName = aspectName; } #endregion #region Static utility methods /// <summary> /// A helper method to put the given value into the given aspect of the given object. /// </summary> /// <remarks>This method catches and silently ignores any errors that occur /// while modifying the target object</remarks> /// <param name="target">The object to be modified</param> /// <param name="propertyName">The name of the property/field to be modified</param> /// <param name="value">The value to be assigned</param> /// <returns>Did the modification work?</returns> public static bool PutProperty(object target, string propertyName, object value) { try { Munger munger = new Munger(propertyName); return munger.PutValue(target, value); } catch (MungerException) { // Not a lot we can do about this. Something went wrong in the bowels // of the property. Let's take the ostrich approach and just ignore it :-) // Normally, we would never just silently ignore an exception. // However, in this case, this is a utility method that explicitly // contracts to catch and ignore errors. If this is not acceptible, // the programmer should not use this method. } return false; } /// <summary> /// Gets or sets whether Mungers will silently ignore missing aspect errors. /// </summary> /// <remarks> /// <para> /// By default, if a Munger is asked to fetch a field/property/method /// that does not exist from a model, it returns an error message, since that /// condition is normally a programming error. There are some use cases where /// this is not an error, and the munger should simply keep quiet. /// </para> /// <para>By default this is true during release builds.</para> /// </remarks> public static bool IgnoreMissingAspects { get { return ignoreMissingAspects; } set { ignoreMissingAspects = value; } } private static bool ignoreMissingAspects #if !DEBUG = true #endif ; #endregion #region Public properties /// <summary> /// The name of the aspect that is to be peeked or poked. /// </summary> /// <remarks> /// <para> /// This name can be a field, property or parameter-less method. /// </para> /// <para> /// The name can be dotted, which chains references. If any link in the chain returns /// null, the entire chain is considered to return null. /// </para> /// </remarks> /// <example>"DateOfBirth"</example> /// <example>"Owner.HomeAddress.Postcode"</example> public string AspectName { get { return aspectName; } set { aspectName = value; // Clear any cache aspectParts = null; } } private string aspectName; #endregion #region Public interface /// <summary> /// Extract the value indicated by our AspectName from the given target. /// </summary> /// <remarks>If the aspect name is null or empty, this will return null.</remarks> /// <param name="target">The object that will be peeked</param> /// <returns>The value read from the target</returns> public Object GetValue(Object target) { if (this.Parts.Count == 0) return null; try { return this.EvaluateParts(target, this.Parts); } catch (MungerException ex) { if (Munger.IgnoreMissingAspects) return null; return String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", ex.Munger.AspectName, ex.Target.GetType()); } } /// <summary> /// Extract the value indicated by our AspectName from the given target, raising exceptions /// if the munger fails. /// </summary> /// <remarks>If the aspect name is null or empty, this will return null.</remarks> /// <param name="target">The object that will be peeked</param> /// <returns>The value read from the target</returns> public Object GetValueEx(Object target) { if (this.Parts.Count == 0) return null; return this.EvaluateParts(target, this.Parts); } /// <summary> /// Poke the given value into the given target indicated by our AspectName. /// </summary> /// <remarks> /// <para> /// If the AspectName is a dotted path, all the selectors bar the last /// are used to find the object that should be updated, and the last /// selector is used as the property to update on that object. /// </para> /// <para> /// So, if 'target' is a Person and the AspectName is "HomeAddress.Postcode", /// this method will first fetch "HomeAddress" property, and then try to set the /// "Postcode" property on the home address object. /// </para> /// </remarks> /// <param name="target">The object that will be poked</param> /// <param name="value">The value that will be poked into the target</param> /// <returns>bool indicating whether the put worked</returns> public bool PutValue(Object target, Object value) { if (this.Parts.Count == 0) return false; SimpleMunger lastPart = this.Parts[this.Parts.Count - 1]; if (this.Parts.Count > 1) { List<SimpleMunger> parts = new List<SimpleMunger>(this.Parts); parts.RemoveAt(parts.Count - 1); try { target = this.EvaluateParts(target, parts); } catch (MungerException ex) { this.ReportPutValueException(ex); return false; } } if (target != null) { try { return lastPart.PutValue(target, value); } catch (MungerException ex) { this.ReportPutValueException(ex); } } return false; } #endregion #region Implementation /// <summary> /// Gets the list of SimpleMungers that match our AspectName /// </summary> private IList<SimpleMunger> Parts { get { if (aspectParts == null) aspectParts = BuildParts(this.AspectName); return aspectParts; } } private IList<SimpleMunger> aspectParts; /// <summary> /// Convert a possibly dotted AspectName into a list of SimpleMungers /// </summary> /// <param name="aspect"></param> /// <returns></returns> private IList<SimpleMunger> BuildParts(string aspect) { List<SimpleMunger> parts = new List<SimpleMunger>(); if (!String.IsNullOrEmpty(aspect)) { foreach (string part in aspect.Split('.')) { parts.Add(new SimpleMunger(part.Trim())); } } return parts; } /// <summary> /// Evaluate the given chain of SimpleMungers against an initial target. /// </summary> /// <param name="target"></param> /// <param name="parts"></param> /// <returns></returns> private object EvaluateParts(object target, IList<SimpleMunger> parts) { foreach (SimpleMunger part in parts) { if (target == null) break; target = part.GetValue(target); } return target; } private void ReportPutValueException(MungerException ex) { //TODO: How should we report this error? System.Diagnostics.Debug.WriteLine("PutValue failed"); System.Diagnostics.Debug.WriteLine(String.Format("- Culprit aspect: {0}", ex.Munger.AspectName)); System.Diagnostics.Debug.WriteLine(String.Format("- Target: {0} of type {1}", ex.Target, ex.Target.GetType())); System.Diagnostics.Debug.WriteLine(String.Format("- Inner exception: {0}", ex.InnerException)); } #endregion } /// <summary> /// A SimpleMunger deals with a single property/field/method on its target. /// </summary> /// <remarks> /// Munger uses a chain of these resolve a dotted aspect name. /// </remarks> public class SimpleMunger { #region Life and death /// <summary> /// Create a SimpleMunger /// </summary> /// <param name="aspectName"></param> public SimpleMunger(String aspectName) { this.aspectName = aspectName; } #endregion #region Public properties /// <summary> /// The name of the aspect that is to be peeked or poked. /// </summary> /// <remarks> /// <para> /// This name can be a field, property or method. /// When using a method to get a value, the method must be parameter-less. /// When using a method to set a value, the method must accept 1 parameter. /// </para> /// <para> /// It cannot be a dotted name. /// </para> /// </remarks> public string AspectName { get { return aspectName; } } private readonly string aspectName; #endregion #region Public interface /// <summary> /// Get a value from the given target /// </summary> /// <param name="target"></param> /// <returns></returns> public Object GetValue(Object target) { if (target == null) return null; this.ResolveName(target, this.AspectName, 0); try { if (this.resolvedPropertyInfo != null) return this.resolvedPropertyInfo.GetValue(target, null); if (this.resolvedMethodInfo != null) return this.resolvedMethodInfo.Invoke(target, null); if (this.resolvedFieldInfo != null) return this.resolvedFieldInfo.GetValue(target); // If that didn't work, try to use the indexer property. // This covers things like dictionaries and DataRows. if (this.indexerPropertyInfo != null) return this.indexerPropertyInfo.GetValue(target, new object[] { this.AspectName }); } catch (Exception ex) { // Lots of things can do wrong in these invocations throw new MungerException(this, target, ex); } // If we get to here, we couldn't find a match for the aspect throw new MungerException(this, target, new MissingMethodException()); } /// <summary> /// Poke the given value into the given target indicated by our AspectName. /// </summary> /// <param name="target">The object that will be poked</param> /// <param name="value">The value that will be poked into the target</param> /// <returns>bool indicating if the put worked</returns> public bool PutValue(object target, object value) { if (target == null) return false; this.ResolveName(target, this.AspectName, 1); try { if (this.resolvedPropertyInfo != null) { this.resolvedPropertyInfo.SetValue(target, value, null); return true; } if (this.resolvedMethodInfo != null) { this.resolvedMethodInfo.Invoke(target, new object[] { value }); return true; } if (this.resolvedFieldInfo != null) { this.resolvedFieldInfo.SetValue(target, value); return true; } // If that didn't work, try to use the indexer property. // This covers things like dictionaries and DataRows. if (this.indexerPropertyInfo != null) { this.indexerPropertyInfo.SetValue(target, value, new object[] { this.AspectName }); return true; } } catch (Exception ex) { // Lots of things can do wrong in these invocations throw new MungerException(this, target, ex); } return false; } #endregion #region Implementation private void ResolveName(object target, string name, int numberMethodParameters) { if (cachedTargetType == target.GetType() && cachedName == name && cachedNumberParameters == numberMethodParameters) return; cachedTargetType = target.GetType(); cachedName = name; cachedNumberParameters = numberMethodParameters; resolvedFieldInfo = null; resolvedPropertyInfo = null; resolvedMethodInfo = null; indexerPropertyInfo = null; const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance /*| BindingFlags.NonPublic*/; foreach (PropertyInfo pinfo in target.GetType().GetProperties(flags)) { if (pinfo.Name == name) { resolvedPropertyInfo = pinfo; return; } // See if we can find an string indexer property while we are here. // We also need to allow for old style <object> keyed collections. if (indexerPropertyInfo == null && pinfo.Name == "Item") { ParameterInfo[] par = pinfo.GetGetMethod().GetParameters(); if (par.Length > 0) { Type parameterType = par[0].ParameterType; if (parameterType == typeof(string) || parameterType == typeof(object)) indexerPropertyInfo = pinfo; } } } foreach (FieldInfo info in target.GetType().GetFields(flags)) { if (info.Name == name) { resolvedFieldInfo = info; return; } } foreach (MethodInfo info in target.GetType().GetMethods(flags)) { if (info.Name == name && info.GetParameters().Length == numberMethodParameters) { resolvedMethodInfo = info; return; } } } private Type cachedTargetType; private string cachedName; private int cachedNumberParameters; private FieldInfo resolvedFieldInfo; private PropertyInfo resolvedPropertyInfo; private MethodInfo resolvedMethodInfo; private PropertyInfo indexerPropertyInfo; #endregion } /// <summary> /// These exceptions are raised when a munger finds something it cannot process /// </summary> public class MungerException : ApplicationException { /// <summary> /// Create a MungerException /// </summary> /// <param name="munger"></param> /// <param name="target"></param> /// <param name="ex"></param> public MungerException(SimpleMunger munger, object target, Exception ex) : base("Munger failed", ex) { this.munger = munger; this.target = target; } /// <summary> /// Get the munger that raised the exception /// </summary> public SimpleMunger Munger { get { return munger; } } private readonly SimpleMunger munger; /// <summary> /// Gets the target that threw the exception /// </summary> public object Target { get { return target; } } private readonly object target; } /* * We don't currently need this * 2010-08-06 * internal class SimpleBinder : Binder { public override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, System.Globalization.CultureInfo culture) { //return Type.DefaultBinder.BindToField( throw new NotImplementedException(); } public override object ChangeType(object value, Type type, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } public override MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] names, out object state) { throw new NotImplementedException(); } public override void ReorderArgumentArray(ref object[] args, object state) { throw new NotImplementedException(); } public override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } public override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers) { if (match == null) throw new ArgumentNullException("match"); if (match.Length == 0) return null; return match[0]; } } */ }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using java.lang; using org.junit; namespace cnatural.compiler.test { public class ObjectModelTest : ExecutionTest { protected override String ResourcesPath { get { return "ObjectModelTest"; } } [Test] public void staticIntField() { doTest("StaticIntField", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void intField() { doTest("IntField", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void staticMethod() { doTest("StaticMethod", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void qualifiedStaticCall() { doTest("QualifiedStaticCall", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void instanceMethod() { doTest("InstanceMethod", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void thisMethodCall() { doTest("ThisMethodCall", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void thisFieldAccess() { doTest("ThisFieldAccess", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void inheritance() { doTest("Inheritance", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void superCall() { doTest("SuperCall", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void shadowing() { doTest("Shadowing", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void interfaceCall() { doTest("InterfaceCall", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void propertyGet() { doTest("PropertyGet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void staticPropertyGet() { doTest("StaticPropertyGet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void propertySet() { doTest("PropertySet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void staticPropertySet() { doTest("StaticPropertySet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void propertyGetSet() { doTest("PropertyGetSet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void staticPropertyGetSet() { doTest("StaticPropertyGetSet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void AutomaticProperty() { doTest("AutomaticProperty", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void staticAutomaticProperty() { doTest("StaticAutomaticProperty", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void indexerGet() { doTest("IndexerGet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void staticIndexerGet() { doTest("StaticIndexerGet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void indexerSet() { doTest("IndexerSet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void staticIndexerSet() { doTest("StaticIndexerSet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void indexerGetSet() { doTest("IndexerGetSet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void staticIndexerGetSet() { doTest("StaticIndexerGetSet", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void constructor() { doTest("Constructor", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void constructorArgument() { doTest("ConstructorArgument", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void constantMethodOverload() { doTest("ConstantMethodOverload", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void constantMethodOverload2() { doTest("ConstantMethodOverload2", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void derivedOverload() { doTest("DerivedOverload", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void intVarargs() { doTest("IntVarargs", new Class<?>[] {}, new Object[] {}, 6); } [Test] public void intVarargsNoArg() { doTest("IntVarargsNoArg", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void interfaceCall2() { doTest("InterfaceCall2", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void genericClass() { doTest("GenericClass", new Class<?>[] { typeof(String) }, new Object[] { "STR" }, "STR"); } [Test] public void delegate_0() { doTest("Delegate", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void delegate2() { doTest("Delegate2", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void delegateField() { doTest("DelegateField", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void delegateStatic() { doTest("DelegateStatic", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void delegateLambda() { doTest("DelegateLambda", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void delegateLambdaLocal() { doTest("DelegateLambdaLocal", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void delegateLambdaArgument() { doTest("DelegateLambdaArgument", new Class<?>[] { typeof(int) }, new Object[] { 3 }, 5); } [Test] public void delegateLambdaField() { doTest("DelegateLambdaField", new Class<?>[] {}, new Object[] {}, 5); } [Test] public void delegateLambdaBlock() { doTest("DelegateLambdaBlock", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void delegateLambdas() { doTest("DelegateLambdas", new Class<?>[] { typeof(int) }, new Object[] { 3 }, 7); } [Test] public void delegateNestedLambdas() { doTest("DelegateNestedLambdas", new Class<?>[] { typeof(int) }, new Object[] { 3 }, 7); } [Test] public void delegateNestedLambdas2() { doTest("DelegateNestedLambdas2", new Class<?>[] { typeof(int) }, new Object[] { 3 }, 5); } [Test] public void delegateNestedLambdas3() { doTest("DelegateNestedLambdas3", new Class<?>[] { typeof(int) }, new Object[] { 3 }, 5); } [Test] public void delegateNestedNestedLambdas() { doTest("DelegateNestedNestedLambdas", new Class<?>[] { typeof(int) }, new Object[] { 3 }, 11); } [Test] public void delegateNestedNestedLambdas2() { doTest("DelegateNestedNestedLambdas2", new Class<?>[] { typeof(int) }, new Object[] { 3 }, 7); } [Test] public void delegateLambdaSideEffect() { doTest("DelegateLambdaSideEffect", new Class<?>[] {}, new Object[] {}, 5); } [Test] public void using_0() { doTest("Using", new Class<?>[] { typeof(char) }, new Object[] { 'a' }, 'a'); } [Test] public void usingAlias() { doTest("UsingAlias", new Class<?>[] { typeof(String), typeof(String) }, new Object[] { "STR1", "STR2" }, "STR1STR2"); } [Test] public void usingAlias2() { doTest("p2.UsingAlias2", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void usingAliasGenerics() { doTest("UsingAliasGenerics", new Class<?>[] { typeof(String), typeof(String) }, new Object[] { "STR1", "STR2" }, "STR2"); } [Test] public void packages() { doTest("p.Packages", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void fieldInit() { doTest("FieldInit", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void genericClassField() { doTest("p.GenericClassField", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void genericConstraint() { doTest("p.GenericConstraint", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void genericConstraints() { doTest("p.GenericConstraints", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void genericClass2() { doTest("GenericClass2", new Class<?>[] { typeof(String) }, new Object[] { "STR" }, "STR"); } [Test] public void genericMethod() { doTest("GenericMethod", new Class<?>[] { typeof(String) }, new Object[] { "STR" }, "STR"); } [Test] public void staticInitializer() { doTest("StaticInitializer", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void staticInitializer2() { doTest("StaticInitializer2", new Class<?>[] {}, new Object[] {}, 6); } [Test] public void nestedInterface() { doTest("NestedInterface", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void constructor2() { doTest("Constructor2", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void nestedClass() { doTest("NestedClass", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void nestedClass2() { doTest("NestedClass2", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void nestedClassAccess() { doTest("NestedClassAccess", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void nestedClassAccess2() { doTest("NestedClassAccess2", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void nestedClassMethodAccess() { doTest("NestedClassMethodAccess", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void nestedClassMethodAccess2() { doTest("NestedClassMethodAccess2", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void nestedClassConstructorAccess() { doTest("NestedClassConstructorAccess", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void varargs() { doTest("Varargs", new Class<?>[] {}, new Object[] {}, ""); } [Test] public void interfaceImplementation() { doTest("InterfaceImplementation", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void methodOverload() { doTest("MethodOverload", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void methodOverload2() { doTest("MethodOverload2", new Class<?>[] {}, new Object[] {}, 201); } [Test] public void nestedClassBase() { doTest("NestedClassBase", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void nestedClassBase2() { doTest("NestedClassBase2", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void interfaceBase() { doTest("p.InterfaceBase", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void varargsOverload() { doTest("VarargsOverload", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void varargsOverride() { doTest("VarargsOverride", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void nestedClassSiblings() { doTest("NestedClassSiblings", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void nestedClassSiblings2() { doTest("NestedClassSiblings2", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void varargsNull() { doTest("VarargsNull", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void constructorThis() { doTest("ConstructorThis", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void genericBase() { doTest("GenericBase", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void genericBase2() { doTest("GenericBase2", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void genericArray() { doTest("GenericArray", new Class<?>[] { typeof(String) }, new Object[] { "STR" }, "STR"); } [Test] public void genericArrayConstraint() { doTest("GenericArrayConstraint", new Class<?>[] { typeof(String) }, new Object[] { "STR" }, "STR"); } [Test] public void genericNestedClass() { doTest("GenericNestedClass", new Class<?>[] { typeof(String) }, new Object[] { "STR" }, "STR"); } [Test] public void genericStaticField() { doTest("GenericStaticField", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void shortByteOverload() { doTest("ShortByteOverload", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void varargsOverload2() { doTest("VarargsOverload2", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void nestedClassOverload() { doTest("NestedClassOverload", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void nestedClassOverload2() { doTest("NestedClassOverload2", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void genericOverload() { doTest("GenericOverload", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void packages2() { doTest("Packages2", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void nestedClassModification() { doTest("NestedClassModification", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void nestedClassModification2() { doTest("NestedClassModification2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void varargsArray() { doTest("VarargsArray", new Class<?>[] {}, new Object[] {}, "abc"); } [Test] public void destructor() { doTest("Destructor", new Class<?>[] {}, new Object[] {}, null); } [Test] public void arrayProperty() { doTest("ArrayProperty", new Class<?>[] {}, new Object[] {}, 9); } [Test] public void staticShortField() { doTest("StaticShortField", new Class<?>[] {}, new Object[] {}, (short)1); } [Test] public void staticLongField() { doTest("StaticLongField", new Class<?>[] {}, new Object[] {}, 1L); } [Test] public void longField() { doTest("LongField", new Class<?>[] {}, new Object[] {}, 1L); } [Test] public void superField() { doTest("SuperField", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void virtualCall() { doTest("VirtualCall", new Class<?>[] {}, new Object[] {}, true); } [Test] public void packageAliasing() { doTest("PackageAliasing", new Class<?>[] {}, new Object[] {}, "OK"); } [Test] public void extensionMethod() { doTest("ExtensionMethod", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void indexer() { doTest("Indexer", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void indexerStatic() { doTest("IndexerStatic", new Class<?>[] {}, new Object[] {}, 5); } [Test] public void indexerKeys() { doTest("IndexerKeys", new Class<?>[] {}, new Object[] {}, "ab2.0c"); } [Test] public void bridge() { doTest("Bridge", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void indexerInterface() { doTest("IndexerInterface", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void PropertyInterface() { doTest("PropertyInterface", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void fields() { doTest("Fields", new Class<?>[] {}, new Object[] {}, 6); } [Test] public void covariance() { doTest("Covariance", new Class<?>[] {}, new Object[] {}, true); } [Test] public void genericConstraints2() { doTest("GenericConstraints2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void staticAccess() { doTest("StaticAccess", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void genericNestedInterface() { doTest("GenericNestedInterface", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void inheritedMethodCall() { doTest("InheritedMethodCall", new Class<?>[] {}, new Object[] {}, "AB"); } [Test] public void abstractProperty() { doTest("AbstractProperty", new Class<?>[] {}, new Object[] {}, "STR"); } [Test] public void packageProtectedAccess() { doTest("PackageProtectedAccess", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void classAnnotation() { doTest("ClassAnnotation", new Class<?>[] {}, new Object[] {}, true); } [Test] public void methodAnnotation() { doTest("MethodAnnotation", new Class<?>[] {}, new Object[] {}, true); } [Test] public void fieldAnnotation() { doTest("FieldAnnotation", new Class<?>[] {}, new Object[] {}, true); } [Test] public void methodAnnotation2() { doTest("MethodAnnotation2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void annotationType() { doTest("AnnotationType", new Class<?>[] {}, new Object[] {}, true); } [Test] public void annotationArray() { doTest("AnnotationArray", new Class<?>[] {}, new Object[] {}, true); } [Test] public void annotationEnum() { doTest("AnnotationEnum", new Class<?>[] {}, new Object[] {}, true); } [Test] public void annotationArray2() { doTest("AnnotationArray2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void indexerVarargs() { doTest("IndexerVarargs", new Class<?>[] {}, new Object[] {}, 6); } [Test] public void longConstField() { doTest("LongConstField", new Class<?>[] {}, new Object[] {}, 2L); } [Test] public void floatConstField() { doTest("FloatConstField", new Class<?>[] {}, new Object[] {}, 2f); } [Test] public void doubleConstField() { doTest("DoubleConstField", new Class<?>[] {}, new Object[] {}, 2d); } [Test] public void byteConstField() { doTest("ByteConstField", new Class<?>[] {}, new Object[] {}, (byte)2); } [Test] public void parameterAnnotation() { doTest("ParameterAnnotation", new Class<?>[] {}, new Object[] {}, true); } [Test] public void parameterAnnotations() { doTest("ParameterAnnotations", new Class<?>[] {}, new Object[] {}, true); } [Test] public void parameterAnnotationConstructor() { doTest("ParameterAnnotationConstructor", new Class<?>[] {}, new Object[] {}, true); } [Test] public void genericNestedClass2() { doTest("GenericNestedClass2", new Class<?>[] {}, new Object[] {}, "OK"); } [Test] public void genericField() { doTest("GenericField", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void genericProperty() { doTest("GenericProperty", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void genericMethod2() { doTest("GenericMethod2", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void staticFinalLongField() { doTest("StaticFinalLongField", new Class<?>[] {}, new Object[] {}, 0L); } [Test] public void genericAssignment() { doTest("GenericAssignment", new Class<?>[] {}, new Object[] {}, true); } [Test] public void wildcardArgument() { doTest("WildcardArgument", new Class<?>[] {}, new Object[] {}, true); } [Test] public void wildcardArrayArgument() { doTest("WildcardArrayArgument", new Class<?>[] {}, new Object[] {}, true); } [Test] public void wildcardConstraintArgument() { doTest("WildcardConstraintArgument", new Class<?>[] {}, new Object[] {}, true); } [Test] public void wildcardLowerConstraintArgument() { doTest("WildcardLowerConstraintArgument", new Class<?>[] {}, new Object[] {}, true); } [Test] public void enumDeclaration() { doTest("EnumDeclaration", new Class<?>[] {}, new Object[] {}, true); } [Test] public void autoPropertyNestedAccess() { doTest("AutoPropertyNestedAccess", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void wildcardBoundInheritance() { doTest("WildcardBoundInheritance", new Class<?>[] {}, new Object[] {}, true); } [Test] public void wildcardBoundInheritance2() { doTest("WildcardBoundInheritance2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void genericConstraintInheritance() { doTest("GenericConstraintInheritance", new Class<?>[] {}, new Object[] {}, true); } [Test] public void genericMethodImplementation() { doTest("GenericMethodImplementation", new Class<?>[] {}, new Object[] {}, true); } [Test] public void genericMethodImplementation2() { doTest("GenericMethodImplementation2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void genericBridgeBoxing() { doTest("GenericBridgeBoxing", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void privateOuterField() { doTest("p.q.PrivateOuterField", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void wildcardBoundParameter() { doTest("WildcardBoundParameter", new Class<?>[] {}, new Object[] {}, true); } [Test] public void delegateLambdaAnonymous() { doTest("DelegateLambdaAnonymous", new Class<?>[] {}, new Object[] {}, 7); } [Test] public void lambdaCatchVariable() { doTest("LambdaCatchVariable", new Class<?>[] {}, new Object[] {}, "Message"); } [Test] public void lambdaForeachVariable() { doTest("LambdaForeachVariable", new Class<?>[] {}, new Object[] {}, "abc"); } [Test] public void lambdaStatic() { doTest("LambdaStatic", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void lambdaInConstructor() { doTest("LambdaInConstructor", new Class<?>[] {}, new Object[] {}, 3); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal enum CorElementType { ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_I4, ELEMENT_TYPE_I8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_I1, ELEMENT_TYPE_U2, ELEMENT_TYPE_U4, ELEMENT_TYPE_U8, ELEMENT_TYPE_I, ELEMENT_TYPE_U, ELEMENT_TYPE_OBJECT, ELEMENT_TYPE_STRING, ELEMENT_TYPE_TYPEDBYREF, ELEMENT_TYPE_CLASS, ELEMENT_TYPE_VALUETYPE, ELEMENT_TYPE_END } internal class PredefinedTypes { private SymbolTable _runtimeBinderSymbolTable; private BSYMMGR _pBSymmgr; private AggregateSymbol[] _predefSyms; // array of predefined symbol types. private KAID _aidMsCorLib; // The assembly ID for all predefined types. public PredefinedTypes(BSYMMGR pBSymmgr) { _pBSymmgr = pBSymmgr; _aidMsCorLib = KAID.kaidNil; _runtimeBinderSymbolTable = null; } // We want to delay load the predef syms as needed. private AggregateSymbol DelayLoadPredefSym(PredefinedType pt) { CType type = _runtimeBinderSymbolTable.GetCTypeFromType(PredefinedTypeFacts.GetAssociatedSystemType(pt)); AggregateSymbol sym = type.getAggregate(); // If we failed to load this thing, we have problems. if (sym == null) { return null; } return PredefinedTypes.InitializePredefinedType(sym, pt); } internal static AggregateSymbol InitializePredefinedType(AggregateSymbol sym, PredefinedType pt) { sym.SetPredefined(true); sym.SetPredefType(pt); sym.SetSkipUDOps(pt <= PredefinedType.PT_ENUM && pt != PredefinedType.PT_INTPTR && pt != PredefinedType.PT_UINTPTR && pt != PredefinedType.PT_TYPE); return sym; } public bool Init(ErrorHandling errorContext, SymbolTable symtable) { _runtimeBinderSymbolTable = symtable; Debug.Assert(_pBSymmgr != null); #if !CSEE Debug.Assert(_predefSyms == null); #else // CSEE Debug.Assert(predefSyms == null || aidMsCorLib != KAID.kaidNil); #endif // CSEE if (_aidMsCorLib == KAID.kaidNil) { // If we haven't found mscorlib yet, first look for System.Object. Then use its assembly as // the location for all other pre-defined types. AggregateSymbol aggObj = FindPredefinedType(errorContext, PredefinedTypeFacts.GetName(PredefinedType.PT_OBJECT), KAID.kaidGlobal, AggKindEnum.Class, 0, true); if (aggObj == null) return false; _aidMsCorLib = aggObj.GetAssemblyID(); } _predefSyms = new AggregateSymbol[(int)PredefinedType.PT_COUNT]; Debug.Assert(_predefSyms != null); return true; } //////////////////////////////////////////////////////////////////////////////// // finds an existing declaration for a predefined type. // returns null on failure. If isRequired is true, an error message is also // given. private static readonly char[] s_nameSeparators = new char[] { '.' }; private AggregateSymbol FindPredefinedType(ErrorHandling errorContext, string pszType, KAID aid, AggKindEnum aggKind, int arity, bool isRequired) { Debug.Assert(!string.IsNullOrEmpty(pszType)); // Shouldn't be the empty string! NamespaceOrAggregateSymbol bagCur = _pBSymmgr.GetRootNS(); Name name = null; string[] nameParts = pszType.Split(s_nameSeparators); for (int i = 0, n = nameParts.Length; i < n; i++) { name = _pBSymmgr.GetNameManager().Add(nameParts[i]); if (i == n - 1) { // This is the last component. Handle it special below. break; } // first search for an outer type which is also predefined // this must be first because we always create a namespace for // outer names, even for nested types AggregateSymbol aggNext = _pBSymmgr.LookupGlobalSymCore(name, bagCur, symbmask_t.MASK_AggregateSymbol).AsAggregateSymbol(); if (aggNext != null && aggNext.InAlias(aid) && aggNext.IsPredefined()) { bagCur = aggNext; } else { // ... if no outer type, then search for namespaces NamespaceSymbol nsNext = _pBSymmgr.LookupGlobalSymCore(name, bagCur, symbmask_t.MASK_NamespaceSymbol).AsNamespaceSymbol(); bool bIsInAlias = true; if (nsNext == null) { bIsInAlias = false; } else { bIsInAlias = nsNext.InAlias(aid); } if (!bIsInAlias) { // Didn't find the namespace in this aid. if (isRequired) { errorContext.Error(ErrorCode.ERR_PredefinedTypeNotFound, pszType); } return null; } bagCur = nsNext; } } AggregateSymbol aggAmbig; AggregateSymbol aggBad; AggregateSymbol aggFound = FindPredefinedTypeCore(name, bagCur, aid, aggKind, arity, out aggAmbig, out aggBad); if (aggFound == null) { // Didn't find the AggregateSymbol. if (aggBad != null && (isRequired || aid == KAID.kaidGlobal && aggBad.IsSource())) errorContext.ErrorRef(ErrorCode.ERR_PredefinedTypeBadType, aggBad); else if (isRequired) errorContext.Error(ErrorCode.ERR_PredefinedTypeNotFound, pszType); return null; } if (aggAmbig == null && aid != KAID.kaidGlobal) { // Look in kaidGlobal to make sure there isn't a conflicting one. AggregateSymbol tmp; AggregateSymbol agg2 = FindPredefinedTypeCore(name, bagCur, KAID.kaidGlobal, aggKind, arity, out aggAmbig, out tmp); Debug.Assert(agg2 != null); if (agg2 != aggFound) aggAmbig = agg2; } return aggFound; } private AggregateSymbol FindPredefinedTypeCore(Name name, NamespaceOrAggregateSymbol bag, KAID aid, AggKindEnum aggKind, int arity, out AggregateSymbol paggAmbig, out AggregateSymbol paggBad) { AggregateSymbol aggFound = null; paggAmbig = null; paggBad = null; for (AggregateSymbol aggCur = _pBSymmgr.LookupGlobalSymCore(name, bag, symbmask_t.MASK_AggregateSymbol).AsAggregateSymbol(); aggCur != null; aggCur = BSYMMGR.LookupNextSym(aggCur, bag, symbmask_t.MASK_AggregateSymbol).AsAggregateSymbol()) { if (!aggCur.InAlias(aid) || aggCur.GetTypeVarsAll().size != arity) { continue; } if (aggCur.AggKind() != aggKind) { if (paggBad == null) { paggBad = aggCur; } continue; } if (aggFound != null) { Debug.Assert(paggAmbig == null); paggAmbig = aggCur; break; } aggFound = aggCur; if (paggAmbig == null) { break; } } return aggFound; } public void ReportMissingPredefTypeError(ErrorHandling errorContext, PredefinedType pt) { Debug.Assert(_pBSymmgr != null); Debug.Assert(_predefSyms != null); Debug.Assert((PredefinedType)0 <= pt && pt < PredefinedType.PT_COUNT && _predefSyms[(int)pt] == null); // We do not assert that !predefTypeInfo[pt].isRequired because if the user is defining // their own MSCorLib and is defining a required PredefType, they'll run into this error // and we need to allow it to go through. errorContext.Error(ErrorCode.ERR_PredefinedTypeNotFound, PredefinedTypeFacts.GetName(pt)); } public AggregateSymbol GetReqPredefAgg(PredefinedType pt) { if (!PredefinedTypeFacts.IsRequired(pt)) throw Error.InternalCompilerError(); if (_predefSyms[(int)pt] == null) { // Delay load this thing. _predefSyms[(int)pt] = DelayLoadPredefSym(pt); } return _predefSyms[(int)pt]; } public AggregateSymbol GetOptPredefAgg(PredefinedType pt) { if (_predefSyms[(int)pt] == null) { // Delay load this thing. _predefSyms[(int)pt] = DelayLoadPredefSym(pt); } Debug.Assert(_predefSyms != null); return _predefSyms[(int)pt]; } //////////////////////////////////////////////////////////////////////////////// // Some of the predefined types have built-in names, like "int" or "string" or // "object". This return the nice name if one exists; otherwise null is // returned. public static string GetNiceName(PredefinedType pt) { return PredefinedTypeFacts.GetNiceName(pt); } public static string GetNiceName(AggregateSymbol type) { if (type.IsPredefined()) return GetNiceName(type.GetPredefType()); else return null; } public static string GetFullName(PredefinedType pt) { return PredefinedTypeFacts.GetName(pt); } public static bool isRequired(PredefinedType pt) { return PredefinedTypeFacts.IsRequired(pt); } } internal static class PredefinedTypeFacts { internal static string GetName(PredefinedType type) { return s_pdTypes[(int)type].name; } internal static bool IsRequired(PredefinedType type) { return s_pdTypes[(int)type].required; } internal static FUNDTYPE GetFundType(PredefinedType type) { return s_pdTypes[(int)type].fundType; } internal static Type GetAssociatedSystemType(PredefinedType type) { return s_pdTypes[(int)type].AssociatedSystemType; } internal static bool IsSimpleType(PredefinedType type) { switch (type) { case PredefinedType.PT_BYTE: case PredefinedType.PT_SHORT: case PredefinedType.PT_INT: case PredefinedType.PT_LONG: case PredefinedType.PT_FLOAT: case PredefinedType.PT_DOUBLE: case PredefinedType.PT_DECIMAL: case PredefinedType.PT_CHAR: case PredefinedType.PT_BOOL: case PredefinedType.PT_SBYTE: case PredefinedType.PT_USHORT: case PredefinedType.PT_UINT: case PredefinedType.PT_ULONG: return true; default: return false; } } internal static bool IsNumericType(PredefinedType type) { switch (type) { case PredefinedType.PT_BYTE: case PredefinedType.PT_SHORT: case PredefinedType.PT_INT: case PredefinedType.PT_LONG: case PredefinedType.PT_FLOAT: case PredefinedType.PT_DOUBLE: case PredefinedType.PT_DECIMAL: case PredefinedType.PT_SBYTE: case PredefinedType.PT_USHORT: case PredefinedType.PT_UINT: case PredefinedType.PT_ULONG: return true; default: return false; } } internal static string GetNiceName(PredefinedType type) { switch (type) { case PredefinedType.PT_BYTE: return "byte"; case PredefinedType.PT_SHORT: return "short"; case PredefinedType.PT_INT: return "int"; case PredefinedType.PT_LONG: return "long"; case PredefinedType.PT_FLOAT: return "float"; case PredefinedType.PT_DOUBLE: return "double"; case PredefinedType.PT_DECIMAL: return "decimal"; case PredefinedType.PT_CHAR: return "char"; case PredefinedType.PT_BOOL: return "bool"; case PredefinedType.PT_SBYTE: return "sbyte"; case PredefinedType.PT_USHORT: return "ushort"; case PredefinedType.PT_UINT: return "uint"; case PredefinedType.PT_ULONG: return "ulong"; case PredefinedType.PT_OBJECT: return "object"; case PredefinedType.PT_STRING: return "string"; default: return null; } } internal static bool IsPredefinedType(string name) { return s_pdTypeNames.ContainsKey(name); } internal static PredefinedType GetPredefTypeIndex(string name) { return s_pdTypeNames[name]; } private class PredefinedTypeInfo { internal PredefinedType type; internal string name; internal bool required; internal FUNDTYPE fundType; internal Type AssociatedSystemType; internal PredefinedTypeInfo(PredefinedType type, Type associatedSystemType, string name, bool required, int arity, AggKindEnum aggKind, FUNDTYPE fundType, bool inMscorlib) { this.type = type; this.name = name; this.required = required; this.fundType = fundType; this.AssociatedSystemType = associatedSystemType; } internal PredefinedTypeInfo(PredefinedType type, Type associatedSystemType, string name, bool required, int arity, bool inMscorlib) : this(type, associatedSystemType, name, required, arity, AggKindEnum.Class, FUNDTYPE.FT_REF, inMscorlib) { } } private static readonly PredefinedTypeInfo[] s_pdTypes = new PredefinedTypeInfo[] { new PredefinedTypeInfo(PredefinedType.PT_BYTE, typeof(System.Byte), "System.Byte", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U1, true), new PredefinedTypeInfo(PredefinedType.PT_SHORT, typeof(System.Int16), "System.Int16", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I2, true), new PredefinedTypeInfo(PredefinedType.PT_INT, typeof(System.Int32), "System.Int32", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I4, true), new PredefinedTypeInfo(PredefinedType.PT_LONG, typeof(System.Int64), "System.Int64", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I8, true), new PredefinedTypeInfo(PredefinedType.PT_FLOAT, typeof(System.Single), "System.Single", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_R4, true), new PredefinedTypeInfo(PredefinedType.PT_DOUBLE, typeof(System.Double), "System.Double", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_R8, true), new PredefinedTypeInfo(PredefinedType.PT_DECIMAL, typeof(System.Decimal), "System.Decimal", false, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_CHAR, typeof(System.Char), "System.Char", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U2, true), new PredefinedTypeInfo(PredefinedType.PT_BOOL, typeof(System.Boolean), "System.Boolean", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I1, true), new PredefinedTypeInfo(PredefinedType.PT_SBYTE, typeof(System.SByte), "System.SByte", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I1, true), new PredefinedTypeInfo(PredefinedType.PT_USHORT, typeof(System.UInt16), "System.UInt16", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U2, true), new PredefinedTypeInfo(PredefinedType.PT_UINT, typeof(System.UInt32), "System.UInt32", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U4, true), new PredefinedTypeInfo(PredefinedType.PT_ULONG, typeof(System.UInt64), "System.UInt64", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U8, true), new PredefinedTypeInfo(PredefinedType.PT_INTPTR, typeof(System.IntPtr), "System.IntPtr", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_UINTPTR, typeof(System.UIntPtr), "System.UIntPtr", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_OBJECT, typeof(System.Object), "System.Object", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_STRING, typeof(System.String), "System.String", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DELEGATE, typeof(System.Delegate), "System.Delegate", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_MULTIDEL, typeof(System.MulticastDelegate), "System.MulticastDelegate", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ARRAY, typeof(System.Array), "System.Array", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_EXCEPTION, typeof(System.Exception), "System.Exception", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_TYPE, typeof(System.Type), "System.Type", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_MONITOR, typeof(System.Threading.Monitor), "System.Threading.Monitor", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_VALUE, typeof(System.ValueType), "System.ValueType", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ENUM, typeof(System.Enum), "System.Enum", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DATETIME, typeof(System.DateTime), "System.DateTime", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGABLEATTRIBUTE, typeof(System.Diagnostics.DebuggableAttribute), "System.Diagnostics.DebuggableAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGABLEATTRIBUTE_DEBUGGINGMODES, typeof(System.Diagnostics.DebuggableAttribute.DebuggingModes), "System.Diagnostics.DebuggableAttribute.DebuggingModes", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_IN, typeof(System.Runtime.InteropServices.InAttribute), "System.Runtime.InteropServices.InAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_OUT, typeof(System.Runtime.InteropServices.OutAttribute), "System.Runtime.InteropServices.OutAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ATTRIBUTE, typeof(System.Attribute), "System.Attribute", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ATTRIBUTEUSAGE, typeof(System.AttributeUsageAttribute), "System.AttributeUsageAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ATTRIBUTETARGETS, typeof(System.AttributeTargets), "System.AttributeTargets", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_OBSOLETE, typeof(System.ObsoleteAttribute), "System.ObsoleteAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_CONDITIONAL, typeof(System.Diagnostics.ConditionalAttribute), "System.Diagnostics.ConditionalAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_CLSCOMPLIANT, typeof(System.CLSCompliantAttribute), "System.CLSCompliantAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_GUID, typeof(System.Runtime.InteropServices.GuidAttribute), "System.Runtime.InteropServices.GuidAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEFAULTMEMBER, typeof(System.Reflection.DefaultMemberAttribute), "System.Reflection.DefaultMemberAttribute", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_PARAMS, typeof(System.ParamArrayAttribute), "System.ParamArrayAttribute", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_COMIMPORT, typeof(System.Runtime.InteropServices.ComImportAttribute), "System.Runtime.InteropServices.ComImportAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_FIELDOFFSET, typeof(System.Runtime.InteropServices.FieldOffsetAttribute), "System.Runtime.InteropServices.FieldOffsetAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_STRUCTLAYOUT, typeof(System.Runtime.InteropServices.StructLayoutAttribute), "System.Runtime.InteropServices.StructLayoutAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_LAYOUTKIND, typeof(System.Runtime.InteropServices.LayoutKind), "System.Runtime.InteropServices.LayoutKind", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_MARSHALAS, typeof(System.Runtime.InteropServices.MarshalAsAttribute), "System.Runtime.InteropServices.MarshalAsAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DLLIMPORT, typeof(System.Runtime.InteropServices.DllImportAttribute), "System.Runtime.InteropServices.DllImportAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_INDEXERNAME, typeof(System.Runtime.CompilerServices.IndexerNameAttribute), "System.Runtime.CompilerServices.IndexerNameAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DECIMALCONSTANT, typeof(System.Runtime.CompilerServices.DecimalConstantAttribute), "System.Runtime.CompilerServices.DecimalConstantAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEFAULTVALUE, typeof(System.Runtime.InteropServices.DefaultParameterValueAttribute), "System.Runtime.InteropServices.DefaultParameterValueAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_UNMANAGEDFUNCTIONPOINTER, typeof(System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute), "System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_CALLINGCONVENTION, typeof(System.Runtime.InteropServices.CallingConvention), "System.Runtime.InteropServices.CallingConvention", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_I4, true), new PredefinedTypeInfo(PredefinedType.PT_CHARSET, typeof(System.Runtime.InteropServices.CharSet), "System.Runtime.InteropServices.CharSet", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_TYPEHANDLE, typeof(System.RuntimeTypeHandle), "System.RuntimeTypeHandle", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_FIELDHANDLE, typeof(System.RuntimeFieldHandle), "System.RuntimeFieldHandle", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_METHODHANDLE, typeof(System.RuntimeMethodHandle), "System.RuntimeMethodHandle", false, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_G_DICTIONARY, typeof(System.Collections.Generic.Dictionary<,>), "System.Collections.Generic.Dictionary`2", false, 2, true), new PredefinedTypeInfo(PredefinedType.PT_IASYNCRESULT, typeof(System.IAsyncResult), "System.IAsyncResult", false, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_ASYNCCBDEL, typeof(System.AsyncCallback), "System.AsyncCallback", false, 0, AggKindEnum.Delegate, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_IDISPOSABLE, typeof(System.IDisposable), "System.IDisposable", true, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_IENUMERABLE, typeof(System.Collections.IEnumerable), "System.Collections.IEnumerable", true, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_IENUMERATOR, typeof(System.Collections.IEnumerator), "System.Collections.IEnumerator", true, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_SYSTEMVOID, typeof(void), "System.Void", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_RUNTIMEHELPERS, typeof(System.Runtime.CompilerServices.RuntimeHelpers), "System.Runtime.CompilerServices.RuntimeHelpers", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_VOLATILEMOD, typeof(System.Runtime.CompilerServices.IsVolatile), "System.Runtime.CompilerServices.IsVolatile", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_COCLASS, typeof(System.Runtime.InteropServices.CoClassAttribute), "System.Runtime.InteropServices.CoClassAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ACTIVATOR, typeof(System.Activator), "System.Activator", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_G_IENUMERABLE, typeof(System.Collections.Generic.IEnumerable<>), "System.Collections.Generic.IEnumerable`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_G_IENUMERATOR, typeof(System.Collections.Generic.IEnumerator<>), "System.Collections.Generic.IEnumerator`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_G_OPTIONAL, typeof(System.Nullable<>), "System.Nullable`1", false, 1, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_FIXEDBUFFER, typeof(System.Runtime.CompilerServices.FixedBufferAttribute), "System.Runtime.CompilerServices.FixedBufferAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEFAULTCHARSET, typeof(System.Runtime.InteropServices.DefaultCharSetAttribute), "System.Runtime.InteropServices.DefaultCharSetAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_COMPILATIONRELAXATIONS, typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute), "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_RUNTIMECOMPATIBILITY, typeof(System.Runtime.CompilerServices.RuntimeCompatibilityAttribute), "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_FRIENDASSEMBLY, typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute), "System.Runtime.CompilerServices.InternalsVisibleToAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERHIDDEN, typeof(System.Diagnostics.DebuggerHiddenAttribute), "System.Diagnostics.DebuggerHiddenAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_TYPEFORWARDER, typeof(System.Runtime.CompilerServices.TypeForwardedToAttribute), "System.Runtime.CompilerServices.TypeForwardedToAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_KEYFILE, typeof(System.Reflection.AssemblyKeyFileAttribute), "System.Reflection.AssemblyKeyFileAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_KEYNAME, typeof(System.Reflection.AssemblyKeyNameAttribute), "System.Reflection.AssemblyKeyNameAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DELAYSIGN, typeof(System.Reflection.AssemblyDelaySignAttribute), "System.Reflection.AssemblyDelaySignAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_NOTSUPPORTEDEXCEPTION, typeof(System.NotSupportedException), "System.NotSupportedException", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_COMPILERGENERATED, typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), "System.Runtime.CompilerServices.CompilerGeneratedAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_UNSAFEVALUETYPE, typeof(System.Runtime.CompilerServices.UnsafeValueTypeAttribute), "System.Runtime.CompilerServices.UnsafeValueTypeAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ASSEMBLYFLAGS, typeof(System.Reflection.AssemblyFlagsAttribute), "System.Reflection.AssemblyFlagsAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ASSEMBLYVERSION, typeof(System.Reflection.AssemblyVersionAttribute), "System.Reflection.AssemblyVersionAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ASSEMBLYCULTURE, typeof(System.Reflection.AssemblyCultureAttribute), "System.Reflection.AssemblyCultureAttribute", false, 0, true), // LINQ new PredefinedTypeInfo(PredefinedType.PT_G_IQUERYABLE, typeof(System.Linq.IQueryable<>), "System.Linq.IQueryable`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, false), new PredefinedTypeInfo(PredefinedType.PT_IQUERYABLE, typeof(System.Linq.IQueryable), "System.Linq.IQueryable", false, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, false), new PredefinedTypeInfo(PredefinedType.PT_STRINGBUILDER, typeof(System.Text.StringBuilder), "System.Text.StringBuilder", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_G_ICOLLECTION, typeof(System.Collections.Generic.ICollection<>), "System.Collections.Generic.ICollection`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_G_ILIST, typeof(System.Collections.Generic.IList<>), "System.Collections.Generic.IList`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_EXTENSION, typeof(System.Runtime.CompilerServices.ExtensionAttribute), "System.Runtime.CompilerServices.ExtensionAttribute", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_G_EXPRESSION, typeof(System.Linq.Expressions.Expression<>), "System.Linq.Expressions.Expression`1", false, 1, false), new PredefinedTypeInfo(PredefinedType.PT_EXPRESSION, typeof(System.Linq.Expressions.Expression), "System.Linq.Expressions.Expression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_LAMBDAEXPRESSION, typeof(System.Linq.Expressions.LambdaExpression), "System.Linq.Expressions.LambdaExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_BINARYEXPRESSION, typeof(System.Linq.Expressions.BinaryExpression), "System.Linq.Expressions.BinaryExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_UNARYEXPRESSION, typeof(System.Linq.Expressions.UnaryExpression), "System.Linq.Expressions.UnaryExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_CONDITIONALEXPRESSION, typeof(System.Linq.Expressions.ConditionalExpression), "System.Linq.Expressions.ConditionalExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_CONSTANTEXPRESSION, typeof(System.Linq.Expressions.ConstantExpression), "System.Linq.Expressions.ConstantExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_PARAMETEREXPRESSION, typeof(System.Linq.Expressions.ParameterExpression), "System.Linq.Expressions.ParameterExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MEMBEREXPRESSION, typeof(System.Linq.Expressions.MemberExpression), "System.Linq.Expressions.MemberExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_METHODCALLEXPRESSION, typeof(System.Linq.Expressions.MethodCallExpression), "System.Linq.Expressions.MethodCallExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_NEWEXPRESSION, typeof(System.Linq.Expressions.NewExpression), "System.Linq.Expressions.NewExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_BINDING, typeof(System.Linq.Expressions.MemberBinding), "System.Linq.Expressions.MemberBinding", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MEMBERINITEXPRESSION, typeof(System.Linq.Expressions.MemberInitExpression), "System.Linq.Expressions.MemberInitExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_LISTINITEXPRESSION, typeof(System.Linq.Expressions.ListInitExpression), "System.Linq.Expressions.ListInitExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_TYPEBINARYEXPRESSION, typeof(System.Linq.Expressions.TypeBinaryExpression), "System.Linq.Expressions.TypeBinaryExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_NEWARRAYEXPRESSION, typeof(System.Linq.Expressions.NewArrayExpression), "System.Linq.Expressions.NewArrayExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MEMBERASSIGNMENT, typeof(System.Linq.Expressions.MemberAssignment), "System.Linq.Expressions.MemberAssignment", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MEMBERLISTBINDING, typeof(System.Linq.Expressions.MemberListBinding), "System.Linq.Expressions.MemberListBinding", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MEMBERMEMBERBINDING, typeof(System.Linq.Expressions.MemberMemberBinding), "System.Linq.Expressions.MemberMemberBinding", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_INVOCATIONEXPRESSION, typeof(System.Linq.Expressions.InvocationExpression), "System.Linq.Expressions.InvocationExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_FIELDINFO, typeof(System.Reflection.FieldInfo), "System.Reflection.FieldInfo", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_METHODINFO, typeof(System.Reflection.MethodInfo), "System.Reflection.MethodInfo", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_CONSTRUCTORINFO, typeof(System.Reflection.ConstructorInfo), "System.Reflection.ConstructorInfo", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_PROPERTYINFO, typeof(System.Reflection.PropertyInfo), "System.Reflection.PropertyInfo", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_METHODBASE, typeof(System.Reflection.MethodBase), "System.Reflection.MethodBase", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_MEMBERINFO, typeof(System.Reflection.MemberInfo), "System.Reflection.MemberInfo", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERDISPLAY, typeof(System.Diagnostics.DebuggerDisplayAttribute), "System.Diagnostics.DebuggerDisplayAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERBROWSABLE, typeof(System.Diagnostics.DebuggerBrowsableAttribute), "System.Diagnostics.DebuggerBrowsableAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERBROWSABLESTATE, typeof(System.Diagnostics.DebuggerBrowsableState), "System.Diagnostics.DebuggerBrowsableState", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_I4, true), new PredefinedTypeInfo(PredefinedType.PT_G_EQUALITYCOMPARER, typeof(System.Collections.Generic.EqualityComparer<>), "System.Collections.Generic.EqualityComparer`1", false, 1, true), new PredefinedTypeInfo(PredefinedType.PT_ELEMENTINITIALIZER, typeof(System.Linq.Expressions.ElementInit), "System.Linq.Expressions.ElementInit", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MISSING, typeof(System.Reflection.Missing), "System.Reflection.Missing", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_G_IREADONLYLIST, typeof(System.Collections.Generic.IReadOnlyList<>), "System.Collections.Generic.IReadOnlyList`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, false), new PredefinedTypeInfo(PredefinedType.PT_G_IREADONLYCOLLECTION, typeof(System.Collections.Generic.IReadOnlyCollection<>), "System.Collections.Generic.IReadOnlyCollection`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, false), }; private static readonly Dictionary<string, PredefinedType> s_pdTypeNames = CreatePredefinedTypeFacts(); private static Dictionary<string, PredefinedType> CreatePredefinedTypeFacts() { var pdTypeNames = new Dictionary<string, PredefinedType>((int)PredefinedType.PT_COUNT); #if DEBUG for (int i = 0; i < (int)PredefinedType.PT_COUNT; i++) { System.Diagnostics.Debug.Assert(s_pdTypes[i].type == (PredefinedType)i); } #endif for (int i = 0; i < (int)PredefinedType.PT_COUNT; i++) { pdTypeNames.Add(s_pdTypes[i].name, (PredefinedType)i); } return pdTypeNames; } } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.IO; namespace UnrealBuildTool { class WinRTPlatform : UEBuildPlatform { /// <summary> /// Should the app be compiled as WinRT /// </summary> [XmlConfig] public static bool bCompileWinRT = false; public static bool IsVisualStudioInstalled() { string BaseVSToolPath = WindowsPlatform.GetVSComnToolsPath(); if (string.IsNullOrEmpty(BaseVSToolPath) == false) { return true; } return false; } public static bool IsWindows8() { // Are we a Windows8 machine? if ((Environment.OSVersion.Version.Major == 6) && (Environment.OSVersion.Version.Minor == 2)) { return true; } return false; } public override bool CanUseXGE() { return false; } /** * Whether the required external SDKs are installed for this platform */ protected override SDKStatus HasRequiredManualSDKInternal() { return !Utils.IsRunningOnMono && IsVisualStudioInstalled() ? SDKStatus.Valid : SDKStatus.Invalid; } /** * Register the platform with the UEBuildPlatform class */ protected override void RegisterBuildPlatformInternal() { //@todo.Rocket: Add platform support if (UnrealBuildTool.RunningRocket() || Utils.IsRunningOnMono) { return; } if ((ProjectFileGenerator.bGenerateProjectFiles == true) || (IsVisualStudioInstalled() == true)) { bool bRegisterBuildPlatform = true; // We also need to check for the generated projects... to handle the case where someone generates projects w/out WinRT. // Hardcoding this for now - but ideally it would be dynamically discovered. string EngineSourcePath = Path.Combine(ProjectFileGenerator.EngineRelativePath, "Source"); string WinRTRHIFile = Path.Combine(EngineSourcePath, "Runtime", "Windows", "D3D11RHI", "D3D11RHI.build.cs"); if (File.Exists(WinRTRHIFile) == false) { bRegisterBuildPlatform = false; } if (bRegisterBuildPlatform == true) { // Register this build platform for WinRT Log.TraceVerbose(" Registering for {0}", UnrealTargetPlatform.WinRT.ToString()); UEBuildPlatform.RegisterBuildPlatform(UnrealTargetPlatform.WinRT, this); UEBuildPlatform.RegisterPlatformWithGroup(UnrealTargetPlatform.WinRT, UnrealPlatformGroup.Microsoft); // For now only register WinRT_ARM is truly a Windows 8 machine. // This will prevent people who do all platform builds from running into the compiler issue. if (WinRTPlatform.IsWindows8() == true) { Log.TraceVerbose(" Registering for {0}", UnrealTargetPlatform.WinRT_ARM.ToString()); UEBuildPlatform.RegisterBuildPlatform(UnrealTargetPlatform.WinRT_ARM, this); UEBuildPlatform.RegisterPlatformWithGroup(UnrealTargetPlatform.WinRT_ARM, UnrealPlatformGroup.Microsoft); } } } } /** * Retrieve the CPPTargetPlatform for the given UnrealTargetPlatform * * @param InUnrealTargetPlatform The UnrealTargetPlatform being build * * @return CPPTargetPlatform The CPPTargetPlatform to compile for */ public override CPPTargetPlatform GetCPPTargetPlatform(UnrealTargetPlatform InUnrealTargetPlatform) { switch (InUnrealTargetPlatform) { case UnrealTargetPlatform.WinRT: return CPPTargetPlatform.WinRT; case UnrealTargetPlatform.WinRT_ARM: return CPPTargetPlatform.WinRT_ARM; } throw new BuildException("WinRTPlatform::GetCPPTargetPlatform: Invalid request for {0}", InUnrealTargetPlatform.ToString()); } /** * Get the extension to use for the given binary type * * @param InBinaryType The binary type being built * * @return string The binary extension (i.e. 'exe' or 'dll') */ public override string GetBinaryExtension(UEBuildBinaryType InBinaryType) { switch (InBinaryType) { case UEBuildBinaryType.DynamicLinkLibrary: return ".dll"; case UEBuildBinaryType.Executable: return ".exe"; case UEBuildBinaryType.StaticLibrary: return ".lib"; case UEBuildBinaryType.Object: return ".obj"; case UEBuildBinaryType.PrecompiledHeader: return ".pch"; } return base.GetBinaryExtension(InBinaryType); } /** * Get the extension to use for debug info for the given binary type * * @param InBinaryType The binary type being built * * @return string The debug info extension (i.e. 'pdb') */ public override string GetDebugInfoExtension(UEBuildBinaryType InBinaryType) { return ".pdb"; } /** * Gives the platform a chance to 'override' the configuration settings * that are overridden on calls to RunUBT. * * @param InPlatform The UnrealTargetPlatform being built * @param InConfiguration The UnrealTargetConfiguration being built * * @return bool true if debug info should be generated, false if not */ public override void ResetBuildConfiguration(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration) { ValidateUEBuildConfiguration(); } /** * Validate the UEBuildConfiguration for this platform * This is called BEFORE calling UEBuildConfiguration to allow setting * various fields used in that function such as CompileLeanAndMean... */ public override void ValidateUEBuildConfiguration() { UEBuildConfiguration.bCompileLeanAndMeanUE = true; UEBuildConfiguration.bCompilePhysX = false; UEBuildConfiguration.bCompileAPEX = false; UEBuildConfiguration.bRuntimePhysicsCooking = false; BuildConfiguration.bUseUnityBuild = false; // Don't stop compilation at first error... BuildConfiguration.bStopXGECompilationAfterErrors = false; } /** * Whether this platform should build a monolithic binary */ public override bool ShouldCompileMonolithicBinary(UnrealTargetPlatform InPlatform) { return true; } /** * Whether PDB files should be used * * @param InPlatform The CPPTargetPlatform being built * @param InConfiguration The CPPTargetConfiguration being built * @param bInCreateDebugInfo true if debug info is getting create, false if not * * @return bool true if PDB files should be used, false if not */ public override bool ShouldUsePDBFiles(CPPTargetPlatform Platform, CPPTargetConfiguration Configuration, bool bCreateDebugInfo) { return true; } /** * Whether the editor should be built for this platform or not * * @param InPlatform The UnrealTargetPlatform being built * @param InConfiguration The UnrealTargetConfiguration being built * @return bool true if the editor should be built, false if not */ public override bool ShouldNotBuildEditor(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration) { return true; } /** * Whether the platform requires cooked data * * @param InPlatform The UnrealTargetPlatform being built * @param InConfiguration The UnrealTargetConfiguration being built * @return bool true if the platform requires cooked data, false if not */ public override bool BuildRequiresCookedData(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration) { return true; } /** * Get a list of extra modules the platform requires. * This is to allow undisclosed platforms to add modules they need without exposing information about the platfomr. * * @param Target The target being build * @param BuildTarget The UEBuildTarget getting build * @param PlatformExtraModules OUTPUT the list of extra modules the platform needs to add to the target */ public override void GetExtraModules(TargetInfo Target, UEBuildTarget BuildTarget, ref List<string> PlatformExtraModules) { if (Target.Platform == UnrealTargetPlatform.WinRT) { PlatformExtraModules.Add("XAudio2"); } } /** * Modify the newly created module passed in for this platform. * This is not required - but allows for hiding details of a * particular platform. * * @param InModule The newly loaded module * @param Target The target being build */ public override void ModifyNewlyLoadedModule(UEBuildModule InModule, TargetInfo Target) { if ((Target.Platform == UnrealTargetPlatform.WinRT) || (Target.Platform == UnrealTargetPlatform.WinRT_ARM)) { if (InModule.ToString() == "Core") { InModule.AddPublicIncludePath("Runtime/Core/Public/WinRT"); InModule.AddPublicDependencyModule("zlib"); } else if (InModule.ToString() == "Engine") { InModule.AddPrivateDependencyModule("zlib"); InModule.AddPrivateDependencyModule("UElibPNG"); InModule.AddPublicDependencyModule("UEOgg"); InModule.AddPublicDependencyModule("Vorbis"); } else if (InModule.ToString() == "Launch") { } else if (InModule.ToString() == "D3D11RHI") { InModule.AddPublicDefinition("D3D11_CUSTOM_VIEWPORT_CONSTRUCTOR=1"); // To enable platform specific D3D11 RHI Types InModule.AddPrivateIncludePath("Runtime/Windows/D3D11RHI/Private/WinRT"); // Hack to enable AllowWindowsPlatformTypes.h/HideWindowsPlatformTypes.h InModule.AddPublicIncludePath("Runtime/Core/Public/Windows"); } else if (InModule.ToString() == "Sockets") { // Hack to enable AllowWindowsPlatformTypes.h/HideWindowsPlatformTypes.h InModule.AddPublicIncludePath("Runtime/Core/Public/Windows"); } else if (InModule.ToString() == "PhysX") { string PhysXDir = UEBuildConfiguration.UEThirdPartySourceDirectory + "PhysX/PhysX-3.3/"; InModule.AddPublicIncludePath("include/foundation/WinRT"); if (Target.Platform == UnrealTargetPlatform.WinRT) { InModule.AddPublicLibraryPath(PhysXDir + "Lib/WinRT"); } else { InModule.AddPublicLibraryPath(PhysXDir + "Lib/WinRT/ARM"); } if (Target.Configuration == UnrealTargetConfiguration.Debug) { InModule.AddPublicAdditionalLibrary("PhysX3DEBUG.lib"); InModule.AddPublicAdditionalLibrary("PhysX3ExtensionsDEBUG.lib"); InModule.AddPublicAdditionalLibrary("PhysX3CookingDEBUG.lib"); InModule.AddPublicAdditionalLibrary("PhysX3CommonDEBUG.lib"); InModule.AddPublicAdditionalLibrary("PhysX3VehicleDEBUG.lib"); InModule.AddPublicAdditionalLibrary("PxTaskDEBUG.lib"); InModule.AddPublicAdditionalLibrary("PhysXVisualDebuggerSDKDEBUG.lib"); InModule.AddPublicAdditionalLibrary("PhysXProfileSDKDEBUG.lib"); } else if (Target.Configuration == UnrealTargetConfiguration.Development) { InModule.AddPublicAdditionalLibrary("PhysX3PROFILE.lib"); InModule.AddPublicAdditionalLibrary("PhysX3ExtensionsPROFILE.lib"); InModule.AddPublicAdditionalLibrary("PhysX3CookingPROFILE.lib"); InModule.AddPublicAdditionalLibrary("PhysX3CommonPROFILE.lib"); InModule.AddPublicAdditionalLibrary("PhysX3VehiclePROFILE.lib"); InModule.AddPublicAdditionalLibrary("PxTaskPROFILE.lib"); InModule.AddPublicAdditionalLibrary("PhysXVisualDebuggerSDKPROFILE.lib"); InModule.AddPublicAdditionalLibrary("PhysXProfileSDKPROFILE.lib"); } else // Test or Shipping { InModule.AddPublicAdditionalLibrary("PhysX3.lib"); InModule.AddPublicAdditionalLibrary("PhysX3Extensions.lib"); InModule.AddPublicAdditionalLibrary("PhysX3Cooking.lib"); InModule.AddPublicAdditionalLibrary("PhysX3Common.lib"); InModule.AddPublicAdditionalLibrary("PhysX3Vehicle.lib"); InModule.AddPublicAdditionalLibrary("PxTask.lib"); InModule.AddPublicAdditionalLibrary("PhysXVisualDebuggerSDK.lib"); InModule.AddPublicAdditionalLibrary("PhysXProfileSDK.lib"); } } else if (InModule.ToString() == "APEX") { InModule.RemovePublicDefinition("APEX_STATICALLY_LINKED=0"); InModule.AddPublicDefinition("APEX_STATICALLY_LINKED=1"); string APEXDir = UEBuildConfiguration.UEThirdPartySourceDirectory + "PhysX/APEX-1.3/"; if (Target.Platform == UnrealTargetPlatform.WinRT) { InModule.AddPublicLibraryPath(APEXDir + "lib/WinRT"); } else { InModule.AddPublicLibraryPath(APEXDir + "lib/WinRT/ARM"); } if (Target.Configuration == UnrealTargetConfiguration.Debug) { InModule.AddPublicAdditionalLibrary("ApexCommonDEBUG.lib"); InModule.AddPublicAdditionalLibrary("ApexFrameworkDEBUG.lib"); InModule.AddPublicAdditionalLibrary("ApexSharedDEBUG.lib"); InModule.AddPublicAdditionalLibrary("APEX_DestructibleDEBUG.lib"); } else if (Target.Configuration == UnrealTargetConfiguration.Development) { InModule.AddPublicAdditionalLibrary("ApexCommonPROFILE.lib"); InModule.AddPublicAdditionalLibrary("ApexFrameworkPROFILE.lib"); InModule.AddPublicAdditionalLibrary("ApexSharedPROFILE.lib"); InModule.AddPublicAdditionalLibrary("APEX_DestructiblePROFILE.lib"); } else // Test or Shipping { InModule.AddPublicAdditionalLibrary("ApexCommon.lib"); InModule.AddPublicAdditionalLibrary("ApexFramework.lib"); InModule.AddPublicAdditionalLibrary("ApexShared.lib"); InModule.AddPublicAdditionalLibrary("APEX_Destructible.lib"); } } else if (InModule.ToString() == "FreeType2") { string FreeType2Path = UEBuildConfiguration.UEThirdPartySourceDirectory + "FreeType2/FreeType2-2.4.12/"; if (Target.Platform == UnrealTargetPlatform.WinRT) { InModule.AddPublicLibraryPath(FreeType2Path + "Lib/WinRT/Win64"); } else { InModule.AddPublicLibraryPath(FreeType2Path + "Lib/WinRT/ARM"); } InModule.AddPublicAdditionalLibrary("freetype2412MT.lib"); } else if (InModule.ToString() == "UElibPNG") { string libPNGPath = UEBuildConfiguration.UEThirdPartySourceDirectory + "libPNG/libPNG-1.5.2"; if (Target.Platform == UnrealTargetPlatform.WinRT) { InModule.AddPublicLibraryPath(libPNGPath + "/lib/WinRT/Win64"); } else { InModule.AddPublicLibraryPath(libPNGPath + "/lib/WinRT/ARM"); } InModule.AddPublicAdditionalLibrary("libpng125.lib"); } else if (InModule.ToString() == "DX11") { // Clear out all the Windows include paths and libraries... // The WinRTSDK module handles proper paths and libs for WinRT. // However, the D3D11RHI module will include the DX11 module. InModule.ClearPublicIncludePaths(); InModule.ClearPublicLibraryPaths(); InModule.ClearPublicAdditionalLibraries(); InModule.RemovePublicDefinition("WITH_D3DX_LIBS=1"); InModule.AddPublicDefinition("D3D11_WITH_DWMAPI=0"); InModule.AddPublicDefinition("WITH_D3DX_LIBS=0"); InModule.AddPublicDefinition("WITH_DX_PERF=0"); InModule.RemovePublicAdditionalLibrary("X3DAudio.lib"); InModule.RemovePublicAdditionalLibrary("XAPOFX.lib"); } else if (InModule.ToString() == "XInput") { InModule.AddPublicAdditionalLibrary("XInput.lib"); } else if (InModule.ToString() == "XAudio2") { InModule.AddPublicDefinition("XAUDIO_SUPPORTS_XMA2WAVEFORMATEX=0"); InModule.AddPublicDefinition("XAUDIO_SUPPORTS_DEVICE_DETAILS=0"); InModule.AddPublicDefinition("XAUDIO2_SUPPORTS_MUSIC=0"); InModule.AddPublicDefinition("XAUDIO2_SUPPORTS_SENDLIST=0"); InModule.AddPublicAdditionalLibrary("XAudio2.lib"); // Hack to enable AllowWindowsPlatformTypes.h/HideWindowsPlatformTypes.h InModule.AddPublicIncludePath("Runtime/Core/Public/Windows"); } else if (InModule.ToString() == "UEOgg") { string OggPath = UEBuildConfiguration.UEThirdPartySourceDirectory + "Ogg/libogg-1.2.2/"; if (Target.Platform == UnrealTargetPlatform.WinRT) { InModule.AddPublicLibraryPath(OggPath + "WinRT/VS2012/WinRT/x64/Release"); } else { InModule.AddPublicLibraryPath(OggPath + "WinRT/VS2012/WinRT/ARM/Release"); } InModule.AddPublicAdditionalLibrary("libogg_static.lib"); } else if (InModule.ToString() == "Vorbis") { string VorbisPath = UEBuildConfiguration.UEThirdPartySourceDirectory + "Vorbis/libvorbis-1.3.2/"; if (Target.Platform == UnrealTargetPlatform.WinRT) { InModule.AddPublicLibraryPath(VorbisPath + "WinRT/VS2012/WinRT/x64/Release"); } else { InModule.AddPublicLibraryPath(VorbisPath + "WinRT/VS2012/WinRT/ARM/Release"); } InModule.AddPublicAdditionalLibrary("libvorbis_static.lib"); } else if (InModule.ToString() == "VorbisFile") { string VorbisPath = UEBuildConfiguration.UEThirdPartySourceDirectory + "Vorbis/libvorbis-1.3.2/"; if (Target.Platform == UnrealTargetPlatform.WinRT) { InModule.AddPublicLibraryPath(VorbisPath + "WinRT/VS2012/WinRT/x64/Release"); } else { InModule.AddPublicLibraryPath(VorbisPath + "WinRT/VS2012/WinRT/ARM/Release"); } InModule.AddPublicAdditionalLibrary("libvorbisfile_static.lib"); } else if (InModule.ToString() == "DX11Audio") { InModule.RemovePublicAdditionalLibrary("X3DAudio.lib"); InModule.RemovePublicAdditionalLibrary("XAPOFX.lib"); } else if (InModule.ToString() == "zlib") { if (Target.Platform == UnrealTargetPlatform.WinRT) { InModule.AddPublicLibraryPath(UEBuildConfiguration.UEThirdPartySourceDirectory + "zlib/zlib-1.2.5/Lib/WinRT/Win64"); } else { InModule.AddPublicLibraryPath(UEBuildConfiguration.UEThirdPartySourceDirectory + "zlib/zlib-1.2.5/Lib/WinRT/ARM"); } InModule.AddPublicAdditionalLibrary("zlib125.lib"); } } else if ((Target.Platform == UnrealTargetPlatform.Win32) || (Target.Platform == UnrealTargetPlatform.Win64)) { // bool bBuildShaderFormats = UEBuildConfiguration.bForceBuildShaderFormats; // if (!UEBuildConfiguration.bBuildRequiresCookedData) // { // if (InModule.ToString() == "Engine") // { // if (UEBuildConfiguration.bBuildDeveloperTools) // { // InModule.AddPlatformSpecificDynamicallyLoadedModule("WinRTTargetPlatform"); // } // } // else if (InModule.ToString() == "TargetPlatform") // { // bBuildShaderFormats = true; // } // } // // allow standalone tools to use targetplatform modules, without needing Engine // if (UEBuildConfiguration.bForceBuildTargetPlatforms) // { // InModule.AddPlatformSpecificDynamicallyLoadedModule("WinRTTargetPlatform"); // } // if (bBuildShaderFormats) // { // InModule.AddPlatformSpecificDynamicallyLoadedModule("ShaderFormatWinRT"); // } } } /** * Setup the target environment for building * * @param InBuildTarget The target being built */ public override void SetUpEnvironment(UEBuildTarget InBuildTarget) { InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_DESKTOP=0"); if (InBuildTarget.Platform == UnrealTargetPlatform.WinRT) { InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_64BITS=1"); } else { //WinRT_ARM InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_64BITS=0"); } InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("EXCEPTIONS_DISABLED=0"); InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WITH_OGGVORBIS=1"); InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_CAN_SUPPORT_EDITORONLY_DATA=0"); //@todo.WINRT: REMOVE THIS // Temporary disabling of automation... to get things working InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WITH_AUTOMATION_WORKER=0"); //@todo.WinRT: Add support for version enforcement //InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("MIN_EXPECTED_XDK_VER=1070"); //InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("MAX_EXPECTED_XDK_VER=1070"); InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("UNICODE"); InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("_UNICODE"); //InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WIN32_LEAN_AND_MEAN"); InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WINAPI_FAMILY=WINAPI_FAMILY_APP"); if (InBuildTarget.Platform == UnrealTargetPlatform.WinRT) { InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WINRT=1"); InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_WINRT=1"); } else { //WinRT_ARM InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WINRT=1"); InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_WINRT_ARM=1"); InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_WINRT=1"); // InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WinRT_ARM=1"); } // No D3DX on WinRT! InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("NO_D3DX_LIBS=1"); // Explicitly exclude the MS C++ runtime libraries we're not using, to ensure other libraries we link with use the same // runtime library as the engine. if (InBuildTarget.Configuration == UnrealTargetConfiguration.Debug) { InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("MSVCRT"); InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("MSVCPRT"); } else { InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("MSVCRTD"); InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("MSVCPRTD"); } InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("LIBC"); InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("LIBCMT"); InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("LIBCPMT"); InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("LIBCP"); InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("LIBCD"); InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("LIBCMTD"); InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("LIBCPMTD"); InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("LIBCPD"); // Compile and link with Win32 API libraries. // d2d1.lib // d3d11.lib // dxgi.lib // ole32.lib // windowscodecs.lib // dwrite.lib InBuildTarget.GlobalLinkEnvironment.Config.AdditionalLibraries.Add("runtimeobject.lib"); InBuildTarget.GlobalLinkEnvironment.Config.AdditionalLibraries.Add("mincore.lib"); //InBuildTarget.GlobalLinkEnvironment.Config.AdditionalLibraries.Add("mincore_legacy.lib"); //InBuildTarget.GlobalLinkEnvironment.Config.AdditionalLibraries.Add("mincore_obsolete.lib"); InBuildTarget.GlobalLinkEnvironment.Config.AdditionalLibraries.Add("user32.lib"); // Windows Vista/7 Desktop Windows Manager API for Slate Windows Compliance //InBuildTarget.GlobalLinkEnvironment.Config.AdditionalLibraries.Add("dwmapi.lib"); UEBuildConfiguration.bCompileSimplygon = false; // For 64-bit builds, we'll forcibly ignore a linker warning with DirectInput. This is // Microsoft's recommended solution as they don't have a fixed .lib for us. InBuildTarget.GlobalLinkEnvironment.Config.AdditionalArguments += " /ignore:4078"; // WinRT assemblies //InBuildTarget.GlobalCompileEnvironment.Config.SystemDotNetAssemblyPaths.Add("$(DurangoXDK)\\console\\Metadata"); //InBuildTarget.GlobalCompileEnvironment.Config.FrameworkAssemblyDependencies.Add("Windows.Foundation.winmd"); //InBuildTarget.GlobalCompileEnvironment.Config.FrameworkAssemblyDependencies.Add("Windows.winmd"); } /** * Whether this platform should create debug information or not * * @param InPlatform The UnrealTargetPlatform being built * @param InConfiguration The UnrealTargetConfiguration being built * * @return bool true if debug info should be generated, false if not */ public override bool ShouldCreateDebugInfo(UnrealTargetPlatform Platform, UnrealTargetConfiguration Configuration) { switch (Configuration) { case UnrealTargetConfiguration.Development: case UnrealTargetConfiguration.Shipping: case UnrealTargetConfiguration.Test: case UnrealTargetConfiguration.Debug: default: return true; }; } /** * Setup the binaries for this specific platform. * * @param InBuildTarget The target being built */ public override void SetupBinaries(UEBuildTarget InBuildTarget) { InBuildTarget.ExtraModuleNames.Add("XInput"); } // // WinRT specific functions // /** * Should the app be compiled as WinRT */ public static bool ShouldCompileWinRT() { return WinRTPlatform.bCompileWinRT; } } }
using System.Collections.Generic; using System.Linq; namespace Entitas { public enum GroupEventType : byte { OnEntityAdded, OnEntityRemoved, OnEntityAddedOrRemoved } /// Use pool.GetGroup(matcher) to get a group of entities which match /// the specified matcher. Calling pool.GetGroup(matcher) with the /// same matcher will always return the same instance of the group. /// The created group is managed by the pool and will always be up to date. /// It will automatically add entities that match the matcher or /// remove entities as soon as they don't match the matcher anymore. public class Group { /// Occurs when an entity gets added. public event GroupChanged OnEntityAdded; /// Occurs when an entity gets removed. public event GroupChanged OnEntityRemoved; /// Occurs when a component of an entity in the group gets replaced. public event GroupUpdated OnEntityUpdated; public delegate void GroupChanged( Group group, Entity entity, int index, IComponent component ); public delegate void GroupUpdated( Group group, Entity entity, int index, IComponent previousComponent, IComponent newComponent ); /// Returns the number of entities in the group. public int count { get { return _entities.Count; } } /// Returns the matcher which was used to create this group. public IMatcher matcher { get { return _matcher; } } readonly IMatcher _matcher; readonly HashSet<Entity> _entities = new HashSet<Entity>( EntityEqualityComparer.comparer ); Entity[] _entitiesCache; Entity _singleEntityCache; string _toStringCache; /// Use pool.GetGroup(matcher) to get a group of entities which match /// the specified matcher. public Group(IMatcher matcher) { _matcher = matcher; } /// This is used by the pool to manage the group. public void HandleEntitySilently(Entity entity) { if(_matcher.Matches(entity)) { addEntitySilently(entity); } else { removeEntitySilently(entity); } } /// This is used by the pool to manage the group. public void HandleEntity( Entity entity, int index, IComponent component) { if(_matcher.Matches(entity)) { addEntity(entity, index, component); } else { removeEntity(entity, index, component); } } /// This is used by the pool to manage the group. public void UpdateEntity( Entity entity, int index, IComponent previousComponent, IComponent newComponent) { if(_entities.Contains(entity)) { if(OnEntityRemoved != null) { OnEntityRemoved(this, entity, index, previousComponent); } if(OnEntityAdded != null) { OnEntityAdded(this, entity, index, newComponent); } if(OnEntityUpdated != null) { OnEntityUpdated( this, entity, index, previousComponent, newComponent ); } } } /// This is called by pool.Reset() and pool.ClearGroups() to remove /// all event handlers. /// This is useful when you want to soft-restart your application. public void RemoveAllEventHandlers() { OnEntityAdded = null; OnEntityRemoved = null; OnEntityUpdated = null; } internal GroupChanged handleEntity(Entity entity) { return _matcher.Matches(entity) ? (addEntitySilently(entity) ? OnEntityAdded : null) : (removeEntitySilently(entity) ? OnEntityRemoved : null); } bool addEntitySilently(Entity entity) { if(entity.isEnabled) { var added = _entities.Add(entity); if(added) { _entitiesCache = null; _singleEntityCache = null; entity.Retain(this); } return added; } return false; } void addEntity(Entity entity, int index, IComponent component) { if(addEntitySilently(entity) && OnEntityAdded != null) { OnEntityAdded(this, entity, index, component); } } bool removeEntitySilently(Entity entity) { var removed = _entities.Remove(entity); if(removed) { _entitiesCache = null; _singleEntityCache = null; entity.Release(this); } return removed; } void removeEntity(Entity entity, int index, IComponent component) { var removed = _entities.Remove(entity); if(removed) { _entitiesCache = null; _singleEntityCache = null; if(OnEntityRemoved != null) { OnEntityRemoved(this, entity, index, component); } entity.Release(this); } } /// Determines whether this group has the specified entity. public bool ContainsEntity(Entity entity) { return _entities.Contains(entity); } /// Returns all entities which are currently in this group. public Entity[] GetEntities() { if(_entitiesCache == null) { _entitiesCache = new Entity[_entities.Count]; _entities.CopyTo(_entitiesCache); } return _entitiesCache; } /// Returns the only entity in this group. It will return null /// if the group is empty. It will throw an exception if the group /// has more than one entity. public Entity GetSingleEntity() { if(_singleEntityCache == null) { var c = _entities.Count; if(c == 1) { using (var enumerator = _entities.GetEnumerator()) { enumerator.MoveNext(); _singleEntityCache = enumerator.Current; } } else if(c == 0) { return null; } else { throw new GroupSingleEntityException(this); } } return _singleEntityCache; } public override string ToString() { if(_toStringCache == null) { _toStringCache = "Group(" + _matcher + ")"; } return _toStringCache; } } public class GroupSingleEntityException : EntitasException { public GroupSingleEntityException(Group group) : base( "Cannot get the single entity from " + group + "!\nGroup contains " + group.count + " entities:", string.Join("\n", group.GetEntities().Select(e => e.ToString()).ToArray() ) ) { } } }
namespace Humidifier.GameLift { using System.Collections.Generic; using FleetTypes; public class Fleet : Humidifier.Resource { public override string AWSTypeName { get { return @"AWS::GameLift::Fleet"; } } /// <summary> /// BuildId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-buildid /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic BuildId { get; set; } /// <summary> /// CertificateConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-certificateconfiguration /// Required: False /// UpdateType: Immutable /// Type: CertificateConfiguration /// </summary> public CertificateConfiguration CertificateConfiguration { get; set; } /// <summary> /// Description /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-description /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Description { get; set; } /// <summary> /// DesiredEC2Instances /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-desiredec2instances /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic DesiredEC2Instances { get; set; } /// <summary> /// EC2InboundPermissions /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-ec2inboundpermissions /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: IpPermission /// </summary> public List<IpPermission> EC2InboundPermissions { get; set; } /// <summary> /// EC2InstanceType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-ec2instancetype /// Required: True /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic EC2InstanceType { get; set; } /// <summary> /// FleetType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-fleettype /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic FleetType { get; set; } /// <summary> /// InstanceRoleARN /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-instancerolearn /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic InstanceRoleARN { get; set; } /// <summary> /// LogPaths /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-logpaths /// Required: False /// UpdateType: Immutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic LogPaths { get; set; } /// <summary> /// MaxSize /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-maxsize /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic MaxSize { get; set; } /// <summary> /// MetricGroups /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-metricgroups /// Required: False /// UpdateType: Mutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic MetricGroups { get; set; } /// <summary> /// MinSize /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-minsize /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic MinSize { get; set; } /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-name /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } /// <summary> /// NewGameSessionProtectionPolicy /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-newgamesessionprotectionpolicy /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic NewGameSessionProtectionPolicy { get; set; } /// <summary> /// PeerVpcAwsAccountId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-peervpcawsaccountid /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic PeerVpcAwsAccountId { get; set; } /// <summary> /// PeerVpcId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-peervpcid /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic PeerVpcId { get; set; } /// <summary> /// ResourceCreationLimitPolicy /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-resourcecreationlimitpolicy /// Required: False /// UpdateType: Mutable /// Type: ResourceCreationLimitPolicy /// </summary> public ResourceCreationLimitPolicy ResourceCreationLimitPolicy { get; set; } /// <summary> /// RuntimeConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-runtimeconfiguration /// Required: False /// UpdateType: Mutable /// Type: RuntimeConfiguration /// </summary> public RuntimeConfiguration RuntimeConfiguration { get; set; } /// <summary> /// ScriptId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-scriptid /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic ScriptId { get; set; } /// <summary> /// ServerLaunchParameters /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-serverlaunchparameters /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic ServerLaunchParameters { get; set; } /// <summary> /// ServerLaunchPath /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-serverlaunchpath /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic ServerLaunchPath { get; set; } } namespace FleetTypes { public class IpPermission { /// <summary> /// FromPort /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-ec2inboundpermission.html#cfn-gamelift-fleet-ec2inboundpermissions-fromport /// Required: True /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic FromPort { get; set; } /// <summary> /// IpRange /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-ec2inboundpermission.html#cfn-gamelift-fleet-ec2inboundpermissions-iprange /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic IpRange { get; set; } /// <summary> /// Protocol /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-ec2inboundpermission.html#cfn-gamelift-fleet-ec2inboundpermissions-protocol /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Protocol { get; set; } /// <summary> /// ToPort /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-ec2inboundpermission.html#cfn-gamelift-fleet-ec2inboundpermissions-toport /// Required: True /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic ToPort { get; set; } } public class ServerProcess { /// <summary> /// ConcurrentExecutions /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-serverprocess.html#cfn-gamelift-fleet-serverprocess-concurrentexecutions /// Required: True /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic ConcurrentExecutions { get; set; } /// <summary> /// LaunchPath /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-serverprocess.html#cfn-gamelift-fleet-serverprocess-launchpath /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic LaunchPath { get; set; } /// <summary> /// Parameters /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-serverprocess.html#cfn-gamelift-fleet-serverprocess-parameters /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Parameters { get; set; } } public class ResourceCreationLimitPolicy { /// <summary> /// NewGameSessionsPerCreator /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-resourcecreationlimitpolicy.html#cfn-gamelift-fleet-resourcecreationlimitpolicy-newgamesessionspercreator /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic NewGameSessionsPerCreator { get; set; } /// <summary> /// PolicyPeriodInMinutes /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-resourcecreationlimitpolicy.html#cfn-gamelift-fleet-resourcecreationlimitpolicy-policyperiodinminutes /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic PolicyPeriodInMinutes { get; set; } } public class CertificateConfiguration { /// <summary> /// CertificateType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-certificateconfiguration.html#cfn-gamelift-fleet-certificateconfiguration-certificatetype /// Required: True /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic CertificateType { get; set; } } public class RuntimeConfiguration { /// <summary> /// GameSessionActivationTimeoutSeconds /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-runtimeconfiguration.html#cfn-gamelift-fleet-runtimeconfiguration-gamesessionactivationtimeoutseconds /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic GameSessionActivationTimeoutSeconds { get; set; } /// <summary> /// MaxConcurrentGameSessionActivations /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-runtimeconfiguration.html#cfn-gamelift-fleet-runtimeconfiguration-maxconcurrentgamesessionactivations /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic MaxConcurrentGameSessionActivations { get; set; } /// <summary> /// ServerProcesses /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-runtimeconfiguration.html#cfn-gamelift-fleet-runtimeconfiguration-serverprocesses /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: ServerProcess /// </summary> public List<ServerProcess> ServerProcesses { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Convenient wrapper for an array, an offset, and ** a count. Ideally used in streams & collections. ** Net Classes will consume an array of these. ** ** ===========================================================*/ using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System { // Note: users should make sure they copy the fields out of an ArraySegment onto their stack // then validate that the fields describe valid bounds within the array. This must be done // because assignments to value types are not atomic, and also because one thread reading // three fields from an ArraySegment may not see the same ArraySegment from one call to another // (ie, users could assign a new value to the old location). [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct ArraySegment<T> : IList<T>, IReadOnlyList<T> { // Do not replace the array allocation with Array.Empty. We don't want to have the overhead of // instantiating another generic type in addition to ArraySegment<T> for new type parameters. public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]); private readonly T[] _array; // Do not rename (binary serialization) private readonly int _offset; // Do not rename (binary serialization) private readonly int _count; // Do not rename (binary serialization) public ArraySegment(T[] array) { if (array == null) throw new ArgumentNullException(nameof(array)); Contract.EndContractBlock(); _array = array; _offset = 0; _count = array.Length; } public ArraySegment(T[] array, int offset, int count) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); _array = array; _offset = offset; _count = count; } public T[] Array => _array; public int Offset => _offset; public int Count => _count; public T this[int index] { get { if ((uint)index >= (uint)_count) { throw new ArgumentOutOfRangeException(nameof(index)); } return _array[_offset + index]; } set { if ((uint)index >= (uint)_count) { throw new ArgumentOutOfRangeException(nameof(index)); } _array[_offset + index] = value; } } public Enumerator GetEnumerator() { ThrowInvalidOperationIfDefault(); return new Enumerator(this); } public override int GetHashCode() { if (_array == null) { return 0; } int hash = 5381; hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset); hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count); // The array hash is expected to be an evenly-distributed mixture of bits, // so rather than adding the cost of another rotation we just xor it. hash ^= _array.GetHashCode(); return hash; } public void CopyTo(T[] destination) => CopyTo(destination, 0); public void CopyTo(T[] destination, int destinationIndex) { ThrowInvalidOperationIfDefault(); System.Array.Copy(_array, _offset, destination, destinationIndex, _count); } public void CopyTo(ArraySegment<T> destination) { ThrowInvalidOperationIfDefault(); destination.ThrowInvalidOperationIfDefault(); if (_count > destination._count) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } System.Array.Copy(_array, _offset, destination._array, destination._offset, _count); } public override bool Equals(Object obj) { if (obj is ArraySegment<T>) return Equals((ArraySegment<T>)obj); else return false; } public bool Equals(ArraySegment<T> obj) { return obj._array == _array && obj._offset == _offset && obj._count == _count; } public ArraySegment<T> Slice(int index) { ThrowInvalidOperationIfDefault(); if ((uint)index > (uint)_count) { throw new ArgumentOutOfRangeException(nameof(index)); } return new ArraySegment<T>(_array, _offset + index, _count - index); } public ArraySegment<T> Slice(int index, int count) { ThrowInvalidOperationIfDefault(); if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index)) { throw new ArgumentOutOfRangeException(nameof(index)); } return new ArraySegment<T>(_array, _offset + index, count); } public T[] ToArray() { ThrowInvalidOperationIfDefault(); if (_count == 0) { return Empty._array; } var array = new T[_count]; System.Array.Copy(_array, _offset, array, 0, _count); return array; } public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b) { return a.Equals(b); } public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b) { return !(a == b); } public static implicit operator ArraySegment<T>(T[] array) => new ArraySegment<T>(array); #region IList<T> T IList<T>.this[int index] { get { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException(nameof(index)); Contract.EndContractBlock(); return _array[_offset + index]; } set { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException(nameof(index)); Contract.EndContractBlock(); _array[_offset + index] = value; } } int IList<T>.IndexOf(T item) { ThrowInvalidOperationIfDefault(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); Debug.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0 ? index - _offset : -1; } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } #endregion #region IReadOnlyList<T> T IReadOnlyList<T>.this[int index] { get { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException(nameof(index)); Contract.EndContractBlock(); return _array[_offset + index]; } } #endregion IReadOnlyList<T> #region ICollection<T> bool ICollection<T>.IsReadOnly { get { // the indexer setter does not throw an exception although IsReadOnly is true. // This is to match the behavior of arrays. return true; } } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { ThrowInvalidOperationIfDefault(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); Debug.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0; } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { ThrowInvalidOperationIfDefault(); System.Array.Copy(_array, _offset, array, arrayIndex, _count); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } #endregion #region IEnumerable<T> IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion private void ThrowInvalidOperationIfDefault() { if (_array == null) { throw new InvalidOperationException(SR.InvalidOperation_NullArray); } } public struct Enumerator : IEnumerator<T> { private readonly T[] _array; private readonly int _start; private readonly int _end; // cache Offset + Count, since it's a little slow private int _current; internal Enumerator(ArraySegment<T> arraySegment) { Debug.Assert(arraySegment.Array != null); Debug.Assert(arraySegment.Offset >= 0); Debug.Assert(arraySegment.Count >= 0); Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length); _array = arraySegment._array; _start = arraySegment._offset; _end = _start + arraySegment._count; _current = _start - 1; } public bool MoveNext() { if (_current < _end) { _current++; return (_current < _end); } return false; } public T Current { get { if (_current < _start) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); if (_current >= _end) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); return _array[_current]; } } object IEnumerator.Current => Current; void IEnumerator.Reset() { _current = _start - 1; } public void Dispose() { } } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Core.QueueWebJobUsageWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Common.Git; using Microsoft.DocAsCode.DataContracts.Common; using Microsoft.DocAsCode.DataContracts.ManagedReference; using Microsoft.DocAsCode.Plugins; public static class VisitorHelper { public static string GlobalNamespaceId { get; set; } private static readonly Regex GenericMethodPostFix = new Regex(@"``\d+$", RegexOptions.Compiled); public static void FeedComments(MetadataItem item, ITripleSlashCommentParserContext context) { if (!string.IsNullOrEmpty(item.RawComment)) { var commentModel = TripleSlashCommentModel.CreateModel(item.RawComment, item.Language, context); if (commentModel == null) return; item.Summary = commentModel.Summary; item.Remarks = commentModel.Remarks; item.Exceptions = commentModel.Exceptions; item.Sees = commentModel.Sees; item.SeeAlsos = commentModel.SeeAlsos; item.Examples = commentModel.Examples; item.InheritDoc = commentModel.InheritDoc; item.CommentModel = commentModel; } } public static string GetId(ISymbol symbol) { if (symbol == null) { return null; } if (symbol is INamespaceSymbol namespaceSymbol && namespaceSymbol.IsGlobalNamespace) { return GlobalNamespaceId; } if (symbol is IAssemblySymbol assemblySymbol) { return assemblySymbol.MetadataName; } if (symbol is IDynamicTypeSymbol dynamicSymbol) { return typeof(object).FullName; } return GetDocumentationCommentId(symbol)?.Substring(2); } private static string GetDocumentationCommentId(ISymbol symbol) { string str = symbol.GetDocumentationCommentId(); if (string.IsNullOrEmpty(str)) { return null; } if (InGlobalNamespace(symbol) && !string.IsNullOrEmpty(GlobalNamespaceId)) { bool isNamespace = (symbol is INamespaceSymbol); bool isTypeParameter = (symbol is ITypeParameterSymbol); if (!isNamespace && !isTypeParameter) { str = str.Insert(2, GlobalNamespaceId + "."); } } return str; } public static string GetCommentId(ISymbol symbol) { if (symbol == null || symbol is IAssemblySymbol) { return null; } if (symbol is IDynamicTypeSymbol) { return "T:" + typeof(object).FullName; } return GetDocumentationCommentId(symbol); } public static string GetOverloadId(ISymbol symbol) { return GetOverloadIdBody(symbol) + "*"; } public static string GetOverloadIdBody(ISymbol symbol) { var id = GetId(symbol); var uidBody = id; { var index = uidBody.IndexOf('('); if (index != -1) { uidBody = uidBody.Remove(index); } } uidBody = GenericMethodPostFix.Replace(uidBody, string.Empty); return uidBody; } public static ApiParameter GetParameterDescription(ISymbol symbol, MetadataItem item, string id, bool isReturn, ITripleSlashCommentParserContext context) { string comment = isReturn ? item.CommentModel?.Returns : item.CommentModel?.GetParameter(symbol.Name); return new ApiParameter { Name = isReturn ? null : symbol.Name, Type = id, Description = comment, }; } public static ApiParameter GetTypeParameterDescription(ITypeParameterSymbol symbol, MetadataItem item, ITripleSlashCommentParserContext context) { string comment = item.CommentModel?.GetTypeParameter(symbol.Name); return new ApiParameter { Name = symbol.Name, Description = comment, }; } public static SourceDetail GetSourceDetail(ISymbol symbol) { // For namespace, definition is meaningless if (symbol == null || symbol.Kind == SymbolKind.Namespace) { return null; } var syntaxRef = symbol.DeclaringSyntaxReferences.LastOrDefault(); if (symbol.IsExtern || syntaxRef == null) { return new SourceDetail { IsExternalPath = true, Path = symbol.ContainingAssembly?.Name, }; } var syntaxNode = syntaxRef.GetSyntax(); Debug.Assert(syntaxNode != null); if (syntaxNode != null) { var source = new SourceDetail { StartLine = syntaxNode.SyntaxTree.GetLineSpan(syntaxNode.Span).StartLinePosition.Line, Path = syntaxNode.SyntaxTree.FilePath, Name = symbol.Name }; source.Remote = GitUtility.TryGetFileDetail(source.Path); if (source.Remote != null) { source.Path = PathUtility.FormatPath(source.Path, UriKind.Relative, EnvironmentContext.BaseDirectory); } return source; } return null; } public static MemberType GetMemberTypeFromTypeKind(TypeKind typeKind) { switch (typeKind) { case TypeKind.Module: case TypeKind.Class: return MemberType.Class; case TypeKind.Enum: return MemberType.Enum; case TypeKind.Interface: return MemberType.Interface; case TypeKind.Struct: return MemberType.Struct; case TypeKind.Delegate: return MemberType.Delegate; default: return MemberType.Default; } } public static bool InGlobalNamespace(ISymbol symbol) { Debug.Assert(symbol != null); return symbol.ContainingNamespace == null || symbol.ContainingNamespace.IsGlobalNamespace; } } }
// 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; using System.Collections.Generic; using System.Data; using System.Linq; using DotSpatial.Data; using DotSpatial.NTSExtension; using NetTopologySuite.Geometries; namespace DotSpatial.Symbology { /// <summary> /// A selection that uses indices instead of features. /// </summary> public class IndexSelection : Changeable, IIndexSelection { #region Fields private readonly IFeatureLayer _layer; private readonly List<ShapeRange> _shapes; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="IndexSelection"/> class. /// </summary> /// <param name="layer">Layer the selected items belong to.</param> public IndexSelection(IFeatureLayer layer) { _layer = layer; _shapes = layer.DataSet.ShapeIndices; SelectionMode = SelectionMode.IntersectsExtent; SelectionState = true; } #endregion #region Properties /// <inheritdoc /> public int Count { get { return _layer.DrawnStates?.Count(_ => _.Selected == SelectionState) ?? 0; } } /// <summary> /// Gets the envelope of this collection. /// </summary> public Envelope Envelope { get { if (!_layer.DrawnStatesNeeded) return new Envelope(); Extent ext = new Extent(); FastDrawnState[] drawnStates = _layer.DrawnStates; for (int shp = 0; shp < drawnStates.Length; shp++) { if (drawnStates[shp].Selected == SelectionState) { ext.ExpandToInclude(_shapes[shp].Extent); } } return ext.ToEnvelope(); } } /// <inheritdoc /> public bool IsReadOnly => false; /// <summary> /// Gets or sets the handler to use for progress messages during selection. /// </summary> public IProgressHandler ProgressHandler { get; set; } /// <summary> /// Gets or sets the region category. Setting this to a specific category will only allow selection by /// region to affect the features that are within the specified category. /// </summary> public IFeatureCategory RegionCategory { get; set; } /// <summary> /// Gets or sets the selection mode. The selection mode controls how envelopes are treated when working with geometries. /// </summary> public SelectionMode SelectionMode { get; set; } /// <summary> /// Gets or sets a value indicating whether this should work as "Selected" indices (true) or /// "UnSelected" indices (false). /// </summary> public bool SelectionState { get; set; } #endregion #region Methods /// <inheritdoc /> public void Add(int index) { if (index < 0 || index >= _layer.DrawnStates.Length) return; if (_layer.DrawnStates[index].Selected == SelectionState) return; _layer.DrawnStates[index].Selected = SelectionState; OnChanged(); } /// <summary> /// Adds all of the specified index values to the selection. /// </summary> /// <param name="indices">The indices to add.</param> public void AddRange(IEnumerable<int> indices) { foreach (int index in indices) { _layer.DrawnStates[index].Selected = SelectionState; } OnChanged(); } /// <summary> /// This uses extent checking (rather than full polygon intersection checking). It will add /// any members that are either contained by or intersect with the specified region /// depending on the SelectionMode property. The order of operation is the region /// acting on the feature, so Contains, for instance, would work with points. /// </summary> /// <param name="region">The region that contains the features that get added.</param> /// <param name="affectedArea">The affected area of this addition.</param> /// <returns>True if any item was actually added to the collection.</returns> public bool AddRegion(Envelope region, out Envelope affectedArea) { Action<FastDrawnState> addToSelection = state => state.Selected = SelectionState; return DoAction(addToSelection, region, out affectedArea); } /// <inheritdoc /> public void AddRow(Dictionary<string, object> values) { // Don't worry about the index in this case. _layer.DataSet.AddRow(values); } /// <inheritdoc /> public void AddRow(DataRow values) { // Don't worry about the index in this case. _layer.DataSet.AddRow(values); } /// <inheritdoc /> public void Clear() { foreach (FastDrawnState state in _layer.DrawnStates) { state.Selected = !SelectionState; } OnChanged(); } /// <inheritdoc /> public bool Contains(int index) { return _layer.DrawnStates[index].Selected == SelectionState; } /// <inheritdoc /> public void CopyTo(int[] array, int arrayIndex) { int index = arrayIndex; foreach (int i in this) { array[index] = i; index++; } } /// <inheritdoc /> public void Edit(int index, Dictionary<string, object> values) { int sourceIndex = GetSourceIndex(index); _layer.DataSet.Edit(sourceIndex, values); } /// <inheritdoc /> public void Edit(int index, DataRow values) { int sourceIndex = GetSourceIndex(index); _layer.DataSet.Edit(sourceIndex, values); } /// <inheritdoc /> public DataTable GetAttributes(int startIndex, int numRows) { return GetAttributes(startIndex, numRows, _layer.DataSet.GetColumns().Select(d => d.ColumnName)); } /// <inheritdoc /> public DataTable GetAttributes(int startIndex, int numRows, IEnumerable<string> fieldNames) { var c = new AttributeCache(_layer.DataSet, numRows); var fn = new HashSet<string>(fieldNames); var result = new DataTable(); foreach (DataColumn col in _layer.DataSet.GetColumns()) { if (fn.Contains(col.ColumnName)) { result.Columns.Add(col); } } int i = 0; FastDrawnState[] drawnStates = _layer.DrawnStates; for (int fid = 0; fid < drawnStates.Length; fid++) { if (drawnStates[fid].Selected) { i++; if (i < startIndex) continue; DataRow dr = result.NewRow(); Dictionary<string, object> vals = c.RetrieveElement(fid); foreach (KeyValuePair<string, object> pair in vals) { if (fn.Contains(pair.Key)) dr[pair.Key] = pair.Value; } result.Rows.Add(dr); if (i > startIndex + numRows) break; } } return result; } /// <inheritdoc /> public DataColumn GetColumn(string name) { return _layer.DataSet.GetColumn(name); } /// <inheritdoc /> public DataColumn[] GetColumns() { { return _layer.DataSet.GetColumns(); } } /// <inheritdoc /> public int[] GetCounts(string[] expressions, ICancelProgressHandler progressHandler, int maxSampleSize) { int numSelected = Count; int[] counts = new int[expressions.Length]; bool requiresRun = false; for (int ie = 0; ie < expressions.Length; ie++) { if (string.IsNullOrEmpty(expressions[ie])) { counts[ie] = numSelected; } else { requiresRun = true; } } if (!requiresRun) return counts; AttributePager ap = new AttributePager(_layer.DataSet, 100000); int numinTable = 0; DataTable result = new DataTable(); result.Columns.AddRange(_layer.DataSet.GetColumns()); FastDrawnState[] drawnStates = _layer.DrawnStates; for (int shp = 0; shp < drawnStates.Length; shp++) { if (drawnStates[shp].Selected) { result.Rows.Add(ap.Row(shp).ItemArray); numinTable++; if (numinTable > 100000) { for (int ie = 0; ie < expressions.Length; ie++) { if (string.IsNullOrEmpty(expressions[ie])) continue; counts[ie] += result.Select(expressions[ie]).Length; } result.Clear(); } } } for (int ie = 0; ie < expressions.Length; ie++) { if (string.IsNullOrEmpty(expressions[ie])) continue; counts[ie] += result.Select(expressions[ie]).Length; } result.Clear(); return counts; } /// <inheritdoc /> public IEnumerator<int> GetEnumerator() { return new IndexSelectionEnumerator(_layer.DrawnStates, SelectionState); } /// <summary> /// Inverts the selection based on the current SelectionMode. /// </summary> /// <param name="region">The geographic region to reverse the selected state.</param> /// <param name="affectedArea">The affected area to invert.</param> /// <returns>True, if the selection was changed.</returns> public bool InvertSelection(Envelope region, out Envelope affectedArea) { Action<FastDrawnState> invertSelection = state => state.Selected = !state.Selected; return DoAction(invertSelection, region, out affectedArea); } /// <inheritdoc /> public int NumRows() { return Count; } /// <inheritdoc /> public bool Remove(int index) { if (index < 0 || index >= _layer.DrawnStates.Length) return false; if (_layer.DrawnStates[index].Selected != SelectionState) return false; _layer.DrawnStates[index].Selected = !SelectionState; OnChanged(); return true; } /// <summary> /// Attempts to remove all the members from the collection. If /// one of the specified indices is outside the range of possible /// values, this returns false, even if others were successfully removed. /// This will also return false if none of the states were changed. /// </summary> /// <param name="indices">The indices to remove.</param> /// <returns>True if the selection was changed.</returns> public bool RemoveRange(IEnumerable<int> indices) { bool problem = false; bool changed = false; FastDrawnState[] drawnStates = _layer.DrawnStates; foreach (int index in indices) { if (index < 0 || index > drawnStates.Length) { problem = true; } else { if (drawnStates[index].Selected != !SelectionState) changed = true; drawnStates[index].Selected = !SelectionState; } } return !problem && changed; } /// <summary> /// Tests each member currently in the selected features based on /// the SelectionMode. If it passes, it will remove the feature from /// the selection. /// </summary> /// <param name="region">The geographic region to remove.</param> /// <param name="affectedArea">A geographic area that was affected by this change.</param> /// <returns>Boolean, true if the collection was changed.</returns> public bool RemoveRegion(Envelope region, out Envelope affectedArea) { Action<FastDrawnState> removeFromSelection = state => state.Selected = !SelectionState; return DoAction(removeFromSelection, region, out affectedArea); } /// <inheritdoc /> public void SetAttributes(int startIndex, DataTable values) { FastDrawnState[] drawnStates = _layer.DrawnStates; int sind = -1; for (int fid = 0; fid < drawnStates.Length; fid++) { if (drawnStates[fid].Selected) { sind++; if (sind > startIndex + values.Rows.Count) { break; } if (sind >= startIndex) { _layer.DataSet.Edit(fid, values.Rows[sind]); } } } } /// <summary> /// Exports the members of this collection as a list of IFeature. /// </summary> /// <returns>A List of IFeature.</returns> public List<IFeature> ToFeatureList() { List<IFeature> result = new List<IFeature>(); FastDrawnState[] drawnStates = _layer.DrawnStates; for (int shp = 0; shp < drawnStates.Length; shp++) { if (drawnStates[shp].Selected == SelectionState) { result.Add(_layer.DataSet.GetFeature(shp)); } } return result; } /// <summary> /// Returns a new featureset based on the features in this collection. /// </summary> /// <returns>An in memory featureset that has not yet been saved to a file in any way.</returns> public FeatureSet ToFeatureSet() { return new FeatureSet(ToFeatureList()) { Projection = _layer.DataSet.Projection }; } /// <summary> /// Gets the enumerator. /// </summary> /// <returns>The enumerator.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Runs the given action for all the shapes that are affected by the current SelectionMode and the given region. /// </summary> /// <param name="action">Action that is run on the affected shapes.</param> /// <param name="region">Region that is used to determine the affected shapes.</param> /// <param name="affectedArea">Area that results from the affected shapes.</param> /// <returns>True, if at least one shape was affected.</returns> private bool DoAction(Action<FastDrawnState> action, Envelope region, out Envelope affectedArea) { bool somethingChanged = false; SuspendChanges(); Extent affected = new Extent(); Polygon reg = region.ToPolygon(); ShapeRange env = new ShapeRange(region); for (int shp = 0; shp < _layer.DrawnStates.Length; shp++) { if (RegionCategory != null && _layer.DrawnStates[shp].Category != RegionCategory) continue; bool doAction = false; ShapeRange shape = _shapes[shp]; switch (SelectionMode) { case SelectionMode.Intersects: // Prevent geometry creation (which is slow) and use ShapeRange instead doAction = env.Intersects(shape); break; case SelectionMode.IntersectsExtent: doAction = shape.Extent.Intersects(region); break; case SelectionMode.ContainsExtent: doAction = shape.Extent.Within(region); break; case SelectionMode.Disjoint: if (!shape.Extent.Intersects(region)) { doAction = true; } else { Geometry g = _layer.DataSet.GetFeature(shp).Geometry; doAction = reg.Disjoint(g); } break; } if (shape.Extent.Intersects(region)) { Geometry geom = _layer.DataSet.GetFeature(shp).Geometry; switch (SelectionMode) { case SelectionMode.Contains: doAction = shape.Extent.Within(region) || reg.Contains(geom); break; case SelectionMode.CoveredBy: doAction = reg.CoveredBy(geom); break; case SelectionMode.Covers: doAction = reg.Covers(geom); break; case SelectionMode.Overlaps: doAction = reg.Overlaps(geom); break; case SelectionMode.Touches: doAction = reg.Touches(geom); break; case SelectionMode.Within: doAction = reg.Within(geom); break; } } if (doAction) { action(_layer.DrawnStates[shp]); affected.ExpandToInclude(shape.Extent); somethingChanged = true; OnChanged(); } } ResumeChanges(); affectedArea = affected.ToEnvelope(); return somethingChanged; } private int GetSourceIndex(int selectedIndex) { // For instance, the 0 index member of the selection might in fact // be the 10th member of the featureset. But we want to edit the 10th member // and not the 0 member. int count = 0; foreach (int i in this) { if (count == selectedIndex) return i; count++; } throw new IndexOutOfRangeException("Index requested was: " + selectedIndex + " but the selection only has " + count + " members"); } #endregion #region Classes /// <summary> /// This class cycles through the members. /// </summary> private class IndexSelectionEnumerator : IEnumerator<int> { #region Fields private readonly bool _selectionState; private readonly FastDrawnState[] _states; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="IndexSelectionEnumerator"/> class. /// </summary> /// <param name="states">The states.</param> /// <param name="selectionState">The selection state.</param> public IndexSelectionEnumerator(FastDrawnState[] states, bool selectionState) { _states = states; _selectionState = selectionState; Current = -1; } #endregion #region Properties /// <inheritdoc /> public int Current { get; private set; } object IEnumerator.Current => Current; #endregion #region Methods /// <inheritdoc /> public void Dispose() { } /// <inheritdoc /> public bool MoveNext() { do { Current++; } while (Current < _states.Length && _states[Current].Selected != _selectionState); return Current != _states.Length; } /// <inheritdoc /> public void Reset() { Current = -1; } #endregion } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using System.Drawing.Drawing2D; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { partial class DockPanel { private sealed class DockDragHandler : DragHandler { private class DockIndicator : DragForm { #region IHitTest private interface IHitTest { DockStyle HitTest(Point pt); DockStyle Status { get; set; } } #endregion #region PanelIndicator private class PanelIndicator : PictureBox, IHitTest { private static Image _imagePanelLeft = Resources.DockIndicator_PanelLeft; private static Image _imagePanelRight = Resources.DockIndicator_PanelRight; private static Image _imagePanelTop = Resources.DockIndicator_PanelTop; private static Image _imagePanelBottom = Resources.DockIndicator_PanelBottom; private static Image _imagePanelFill = Resources.DockIndicator_PanelFill; private static Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft_Active; private static Image _imagePanelRightActive = Resources.DockIndicator_PanelRight_Active; private static Image _imagePanelTopActive = Resources.DockIndicator_PanelTop_Active; private static Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom_Active; private static Image _imagePanelFillActive = Resources.DockIndicator_PanelFill_Active; public PanelIndicator(DockStyle dockStyle) { m_dockStyle = dockStyle; SizeMode = PictureBoxSizeMode.AutoSize; Image = ImageInactive; } private DockStyle m_dockStyle; private DockStyle DockStyle { get { return m_dockStyle; } } private DockStyle m_status; public DockStyle Status { get { return m_status; } set { if (value != DockStyle && value != DockStyle.None) throw new InvalidEnumArgumentException(); if (m_status == value) return; m_status = value; IsActivated = (m_status != DockStyle.None); } } private Image ImageInactive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeft; else if (DockStyle == DockStyle.Right) return _imagePanelRight; else if (DockStyle == DockStyle.Top) return _imagePanelTop; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottom; else if (DockStyle == DockStyle.Fill) return _imagePanelFill; else return null; } } private Image ImageActive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeftActive; else if (DockStyle == DockStyle.Right) return _imagePanelRightActive; else if (DockStyle == DockStyle.Top) return _imagePanelTopActive; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottomActive; else if (DockStyle == DockStyle.Fill) return _imagePanelFillActive; else return null; } } private bool m_isActivated = false; private bool IsActivated { get { return m_isActivated; } set { m_isActivated = value; Image = IsActivated ? ImageActive : ImageInactive; } } public DockStyle HitTest(Point pt) { return ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None; } } #endregion PanelIndicator #region PaneIndicator private class PaneIndicator : PictureBox, IHitTest { private struct HotSpotIndex { public HotSpotIndex(int x, int y, DockStyle dockStyle) { m_x = x; m_y = y; m_dockStyle = dockStyle; } private int m_x; public int X { get { return m_x; } } private int m_y; public int Y { get { return m_y; } } private DockStyle m_dockStyle; public DockStyle DockStyle { get { return m_dockStyle; } } } private static Bitmap _bitmapPaneDiamond = Resources.DockIndicator_PaneDiamond; private static Bitmap _bitmapPaneDiamondLeft = Resources.DockIndicator_PaneDiamond_Left; private static Bitmap _bitmapPaneDiamondRight = Resources.DockIndicator_PaneDiamond_Right; private static Bitmap _bitmapPaneDiamondTop = Resources.DockIndicator_PaneDiamond_Top; private static Bitmap _bitmapPaneDiamondBottom = Resources.DockIndicator_PaneDiamond_Bottom; private static Bitmap _bitmapPaneDiamondFill = Resources.DockIndicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondHotSpot = Resources.DockIndicator_PaneDiamond_HotSpot; private static Bitmap _bitmapPaneDiamondHotSpotIndex = Resources.DockIndicator_PaneDiamond_HotSpotIndex; private static HotSpotIndex[] _hotSpots = new HotSpotIndex[] { new HotSpotIndex(1, 0, DockStyle.Top), new HotSpotIndex(0, 1, DockStyle.Left), new HotSpotIndex(1, 1, DockStyle.Fill), new HotSpotIndex(2, 1, DockStyle.Right), new HotSpotIndex(1, 2, DockStyle.Bottom) }; private static GraphicsPath _displayingGraphicsPath = DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond); public PaneIndicator() { SizeMode = PictureBoxSizeMode.AutoSize; Image = _bitmapPaneDiamond; Region = new Region(DisplayingGraphicsPath); } public static GraphicsPath DisplayingGraphicsPath { get { return _displayingGraphicsPath; } } public DockStyle HitTest(Point pt) { if (!Visible) return DockStyle.None; pt = PointToClient(pt); if (!ClientRectangle.Contains(pt)) return DockStyle.None; for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++) { if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y)) return _hotSpots[i].DockStyle; } return DockStyle.None; } private DockStyle m_status = DockStyle.None; public DockStyle Status { get { return m_status; } set { m_status = value; if (m_status == DockStyle.None) Image = _bitmapPaneDiamond; else if (m_status == DockStyle.Left) Image = _bitmapPaneDiamondLeft; else if (m_status == DockStyle.Right) Image = _bitmapPaneDiamondRight; else if (m_status == DockStyle.Top) Image = _bitmapPaneDiamondTop; else if (m_status == DockStyle.Bottom) Image = _bitmapPaneDiamondBottom; else if (m_status == DockStyle.Fill) Image = _bitmapPaneDiamondFill; } } } #endregion PaneIndicator #region consts private int _PanelIndicatorMargin = 10; #endregion private DockDragHandler m_dragHandler; public DockIndicator(DockDragHandler dragHandler) { m_dragHandler = dragHandler; Controls.AddRange(new Control[] { PaneDiamond, PanelLeft, PanelRight, PanelTop, PanelBottom, PanelFill }); Region = new Region(Rectangle.Empty); } private PaneIndicator m_paneDiamond = null; private PaneIndicator PaneDiamond { get { if (m_paneDiamond == null) m_paneDiamond = new PaneIndicator(); return m_paneDiamond; } } private PanelIndicator m_panelLeft = null; private PanelIndicator PanelLeft { get { if (m_panelLeft == null) m_panelLeft = new PanelIndicator(DockStyle.Left); return m_panelLeft; } } private PanelIndicator m_panelRight = null; private PanelIndicator PanelRight { get { if (m_panelRight == null) m_panelRight = new PanelIndicator(DockStyle.Right); return m_panelRight; } } private PanelIndicator m_panelTop = null; private PanelIndicator PanelTop { get { if (m_panelTop == null) m_panelTop = new PanelIndicator(DockStyle.Top); return m_panelTop; } } private PanelIndicator m_panelBottom = null; private PanelIndicator PanelBottom { get { if (m_panelBottom == null) m_panelBottom = new PanelIndicator(DockStyle.Bottom); return m_panelBottom; } } private PanelIndicator m_panelFill = null; private PanelIndicator PanelFill { get { if (m_panelFill == null) m_panelFill = new PanelIndicator(DockStyle.Fill); return m_panelFill; } } private bool m_fullPanelEdge = false; public bool FullPanelEdge { get { return m_fullPanelEdge; } set { if (m_fullPanelEdge == value) return; m_fullPanelEdge = value; RefreshChanges(); } } public DockDragHandler DragHandler { get { return m_dragHandler; } } public DockPanel DockPanel { get { return DragHandler.DockPanel; } } private DockPane m_dockPane = null; public DockPane DockPane { get { return m_dockPane; } internal set { if (m_dockPane == value) return; DockPane oldDisplayingPane = DisplayingPane; m_dockPane = value; if (oldDisplayingPane != DisplayingPane) RefreshChanges(); } } private IHitTest m_hitTest = null; private IHitTest HitTestResult { get { return m_hitTest; } set { if (m_hitTest == value) return; if (m_hitTest != null) m_hitTest.Status = DockStyle.None; m_hitTest = value; } } private DockPane DisplayingPane { get { return ShouldPaneDiamondVisible() ? DockPane : null; } } private void RefreshChanges() { Region region = new Region(Rectangle.Empty); Rectangle rectDockArea = FullPanelEdge ? DockPanel.DockArea : DockPanel.DocumentWindowBounds; rectDockArea = RectangleToClient(DockPanel.RectangleToScreen(rectDockArea)); if (ShouldPanelIndicatorVisible(DockState.DockLeft)) { PanelLeft.Location = new Point(rectDockArea.X + _PanelIndicatorMargin, rectDockArea.Y + (rectDockArea.Height - PanelRight.Height) / 2); PanelLeft.Visible = true; region.Union(PanelLeft.Bounds); } else PanelLeft.Visible = false; if (ShouldPanelIndicatorVisible(DockState.DockRight)) { PanelRight.Location = new Point(rectDockArea.X + rectDockArea.Width - PanelRight.Width - _PanelIndicatorMargin, rectDockArea.Y + (rectDockArea.Height - PanelRight.Height) / 2); PanelRight.Visible = true; region.Union(PanelRight.Bounds); } else PanelRight.Visible = false; if (ShouldPanelIndicatorVisible(DockState.DockTop)) { PanelTop.Location = new Point(rectDockArea.X + (rectDockArea.Width - PanelTop.Width) / 2, rectDockArea.Y + _PanelIndicatorMargin); PanelTop.Visible = true; region.Union(PanelTop.Bounds); } else PanelTop.Visible = false; if (ShouldPanelIndicatorVisible(DockState.DockBottom)) { PanelBottom.Location = new Point(rectDockArea.X + (rectDockArea.Width - PanelBottom.Width) / 2, rectDockArea.Y + rectDockArea.Height - PanelBottom.Height - _PanelIndicatorMargin); PanelBottom.Visible = true; region.Union(PanelBottom.Bounds); } else PanelBottom.Visible = false; if (ShouldPanelIndicatorVisible(DockState.Document)) { Rectangle rectDocumentWindow = RectangleToClient(DockPanel.RectangleToScreen(DockPanel.DocumentWindowBounds)); PanelFill.Location = new Point(rectDocumentWindow.X + (rectDocumentWindow.Width - PanelFill.Width) / 2, rectDocumentWindow.Y + (rectDocumentWindow.Height - PanelFill.Height) / 2); PanelFill.Visible = true; region.Union(PanelFill.Bounds); } else PanelFill.Visible = false; if (ShouldPaneDiamondVisible()) { Rectangle rect = RectangleToClient(DockPane.RectangleToScreen(DockPane.ClientRectangle)); PaneDiamond.Location = new Point(rect.Left + (rect.Width - PaneDiamond.Width) / 2, rect.Top + (rect.Height - PaneDiamond.Height) / 2); PaneDiamond.Visible = true; using (GraphicsPath graphicsPath = PaneIndicator.DisplayingGraphicsPath.Clone() as GraphicsPath) { Point[] pts = new Point[] { new Point(PaneDiamond.Left, PaneDiamond.Top), new Point(PaneDiamond.Right, PaneDiamond.Top), new Point(PaneDiamond.Left, PaneDiamond.Bottom) }; using (Matrix matrix = new Matrix(PaneDiamond.ClientRectangle, pts)) { graphicsPath.Transform(matrix); } region.Union(graphicsPath); } } else PaneDiamond.Visible = false; Region = region; } private bool ShouldPanelIndicatorVisible(DockState dockState) { if (!Visible) return false; if (DockPanel.DockWindows[dockState].Visible) return false; return DragHandler.DragSource.IsDockStateValid(dockState); } private bool ShouldPaneDiamondVisible() { if (DockPane == null) return false; if (!DockPanel.AllowEndUserNestedDocking) return false; return DragHandler.DragSource.CanDockTo(DockPane); } public override void Show(bool bActivate) { Bounds = GetAllScreenBounds(); base.Show(bActivate); RefreshChanges(); } public void TestDrop() { Point pt = Control.MousePosition; DockPane = DockHelper.PaneAtPoint(pt, DockPanel); if (TestDrop(PanelLeft, pt) != DockStyle.None) HitTestResult = PanelLeft; else if (TestDrop(PanelRight, pt) != DockStyle.None) HitTestResult = PanelRight; else if (TestDrop(PanelTop, pt) != DockStyle.None) HitTestResult = PanelTop; else if (TestDrop(PanelBottom, pt) != DockStyle.None) HitTestResult = PanelBottom; else if (TestDrop(PanelFill, pt) != DockStyle.None) HitTestResult = PanelFill; else if (TestDrop(PaneDiamond, pt) != DockStyle.None) HitTestResult = PaneDiamond; else HitTestResult = null; if (HitTestResult != null) { if (HitTestResult is PaneIndicator) DragHandler.Outline.Show(DockPane, HitTestResult.Status); else DragHandler.Outline.Show(DockPanel, HitTestResult.Status, FullPanelEdge); } } private static DockStyle TestDrop(IHitTest hitTest, Point pt) { return hitTest.Status = hitTest.HitTest(pt); } private static Rectangle GetAllScreenBounds() { Rectangle rect = new Rectangle(0, 0, 0, 0); foreach (Screen screen in Screen.AllScreens) { Rectangle rectScreen = screen.Bounds; if (rectScreen.Left < rect.Left) { rect.Width += (rect.Left - rectScreen.Left); rect.X = rectScreen.X; } if (rectScreen.Right > rect.Right) rect.Width += (rectScreen.Right - rect.Right); if (rectScreen.Top < rect.Top) { rect.Height += (rect.Top - rectScreen.Top); rect.Y = rectScreen.Y; } if (rectScreen.Bottom > rect.Bottom) rect.Height += (rectScreen.Bottom - rect.Bottom); } return rect; } } private class DockOutline : DockOutlineBase { public DockOutline() { m_dragForm = new DragForm(); SetDragForm(Rectangle.Empty); DragForm.BackColor = SystemColors.ActiveCaption; DragForm.Opacity = 0.5; DragForm.Show(false); } DragForm m_dragForm; private DragForm DragForm { get { return m_dragForm; } } protected override void OnShow() { CalculateRegion(); } protected override void OnClose() { DragForm.Close(); } private void CalculateRegion() { if (SameAsOldValue) return; if (!FloatWindowBounds.IsEmpty) SetOutline(FloatWindowBounds); else if (DockTo is DockPanel) SetOutline(DockTo as DockPanel, Dock, (ContentIndex != 0)); else if (DockTo is DockPane) SetOutline(DockTo as DockPane, Dock, ContentIndex); else SetOutline(); } private void SetOutline() { SetDragForm(Rectangle.Empty); } private void SetOutline(Rectangle floatWindowBounds) { SetDragForm(floatWindowBounds); } private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge) { Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); if (dock == DockStyle.Top) { int height = dockPanel.GetDockWindowSize(DockState.DockTop); rect = new Rectangle(rect.X, rect.Y, rect.Width, height); } else if (dock == DockStyle.Bottom) { int height = dockPanel.GetDockWindowSize(DockState.DockBottom); rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height); } else if (dock == DockStyle.Left) { int width = dockPanel.GetDockWindowSize(DockState.DockLeft); rect = new Rectangle(rect.X, rect.Y, width, rect.Height); } else if (dock == DockStyle.Right) { int width = dockPanel.GetDockWindowSize(DockState.DockRight); rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height); } else if (dock == DockStyle.Fill) { rect = dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); } SetDragForm(rect); } private void SetOutline(DockPane pane, DockStyle dock, int contentIndex) { if (dock != DockStyle.Fill) { Rectangle rect = pane.DisplayingRectangle; if (dock == DockStyle.Right) rect.X += rect.Width / 2; if (dock == DockStyle.Bottom) rect.Y += rect.Height / 2; if (dock == DockStyle.Left || dock == DockStyle.Right) rect.Width -= rect.Width / 2; if (dock == DockStyle.Top || dock == DockStyle.Bottom) rect.Height -= rect.Height / 2; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else if (contentIndex == -1) { Rectangle rect = pane.DisplayingRectangle; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else { using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex)) { RectangleF rectF = path.GetBounds(); Rectangle rect = new Rectangle((int)rectF.X, (int)rectF.Y, (int)rectF.Width, (int)rectF.Height); using (Matrix matrix = new Matrix(rect, new Point[] { new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height) })) { path.Transform(matrix); } Region region = new Region(path); SetDragForm(rect, region); } } } private void SetDragForm(Rectangle rect) { DragForm.Bounds = rect; if (rect == Rectangle.Empty) DragForm.Region = new Region(Rectangle.Empty); else if (DragForm.Region != null) DragForm.Region = null; } private void SetDragForm(Rectangle rect, Region region) { DragForm.Bounds = rect; DragForm.Region = region; } } public DockDragHandler(DockPanel panel) : base(panel) { } public new IDockDragSource DragSource { get { return base.DragSource as IDockDragSource; } set { base.DragSource = value; } } private DockOutlineBase m_outline; public DockOutlineBase Outline { get { return m_outline; } private set { m_outline = value; } } private DockIndicator m_indicator; private DockIndicator Indicator { get { return m_indicator; } set { m_indicator = value; } } private Rectangle m_floatOutlineBounds; private Rectangle FloatOutlineBounds { get { return m_floatOutlineBounds; } set { m_floatOutlineBounds = value; } } public void BeginDrag(IDockDragSource dragSource) { DragSource = dragSource; if (!BeginDrag()) { DragSource = null; return; } Outline = new DockOutline(); Indicator = new DockIndicator(this); Indicator.Show(false); FloatOutlineBounds = DragSource.BeginDrag(StartMousePosition); } protected override void OnDragging() { TestDrop(); } protected override void OnEndDrag(bool abort) { DockPanel.SuspendLayout(true); Outline.Close(); Indicator.Close(); EndDrag(abort); DockPanel.ResumeLayout(true, true); DragSource = null; } private void TestDrop() { Outline.FlagTestDrop = false; Indicator.FullPanelEdge = ((Control.ModifierKeys & Keys.Shift) != 0); if ((Control.ModifierKeys & Keys.Control) == 0) { Indicator.TestDrop(); if (!Outline.FlagTestDrop) { DockPane pane = DockHelper.PaneAtPoint(Control.MousePosition, DockPanel); if (pane != null && DragSource.IsDockStateValid(pane.DockState)) pane.TestDrop(DragSource, Outline); } if (!Outline.FlagTestDrop && DragSource.IsDockStateValid(DockState.Float)) { FloatWindow floatWindow = DockHelper.FloatWindowAtPoint(Control.MousePosition, DockPanel); if (floatWindow != null) floatWindow.TestDrop(DragSource, Outline); } } else Indicator.DockPane = DockHelper.PaneAtPoint(Control.MousePosition, DockPanel); if (!Outline.FlagTestDrop) { if (DragSource.IsDockStateValid(DockState.Float)) { Rectangle rect = FloatOutlineBounds; rect.Offset(Control.MousePosition.X - StartMousePosition.X, Control.MousePosition.Y - StartMousePosition.Y); Outline.Show(rect); } } if (!Outline.FlagTestDrop) { Cursor.Current = Cursors.No; Outline.Show(); } else Cursor.Current = DragControl.Cursor; } private void EndDrag(bool abort) { if (abort) return; if (!Outline.FloatWindowBounds.IsEmpty) DragSource.FloatAt(Outline.FloatWindowBounds); else if (Outline.DockTo is DockPane) { DockPane pane = Outline.DockTo as DockPane; DragSource.DockTo(pane, Outline.Dock, Outline.ContentIndex); } else if (Outline.DockTo is DockPanel) { DockPanel panel = Outline.DockTo as DockPanel; panel.UpdateDockWindowZOrder(Outline.Dock, Outline.FlagFullEdge); DragSource.DockTo(panel, Outline.Dock); } } } private DockDragHandler m_dockDragHandler = null; private DockDragHandler GetDockDragHandler() { if (m_dockDragHandler == null) m_dockDragHandler = new DockDragHandler(this); return m_dockDragHandler; } internal void BeginDrag(IDockDragSource dragSource) { GetDockDragHandler().BeginDrag(dragSource); } } }
namespace BooCompiler.Tests { using NUnit.Framework; [TestFixture] public class MacrosTestFixture : AbstractCompilerTestCase { [Test] public void assert_1() { RunCompilerTestCase(@"assert-1.boo"); } [Test] public void custom_class_macro_as_generic_argument() { RunCompilerTestCase(@"custom-class-macro-as-generic-argument.boo"); } [Test] public void custom_class_macro_with_internal_field() { RunCompilerTestCase(@"custom-class-macro-with-internal-field.boo"); } [Test] public void custom_class_macro_with_internal_property() { RunCompilerTestCase(@"custom-class-macro-with-internal-property.boo"); } [Test] public void custom_class_macro_with_method_override() { RunCompilerTestCase(@"custom-class-macro-with-method-override.boo"); } [Test] public void custom_class_macro_with_properties_and_field() { RunCompilerTestCase(@"custom-class-macro-with-properties-and-field.boo"); } [Test] public void custom_class_macro_with_properties() { RunCompilerTestCase(@"custom-class-macro-with-properties.boo"); } [Test] public void custom_class_macro_with_property_macro() { RunCompilerTestCase(@"custom-class-macro-with-property-macro.boo"); } [Test] public void custom_class_macro_with_simple_method_and_field() { RunCompilerTestCase(@"custom-class-macro-with-simple-method-and-field.boo"); } [Test] public void custom_class_macro_with_simple_method() { RunCompilerTestCase(@"custom-class-macro-with-simple-method.boo"); } [Test] public void debug_1() { RunCompilerTestCase(@"debug-1.boo"); } [Test] public void generator_macro_1() { RunCompilerTestCase(@"generator-macro-1.boo"); } [Test] public void generator_macro_2() { RunCompilerTestCase(@"generator-macro-2.boo"); } [Test] public void generator_macro_3() { RunCompilerTestCase(@"generator-macro-3.boo"); } [Test] public void generator_macro_4() { RunCompilerTestCase(@"generator-macro-4.boo"); } [Test] public void generator_macro_5() { RunCompilerTestCase(@"generator-macro-5.boo"); } [Test] public void ifdef_1() { RunCompilerTestCase(@"ifdef-1.boo"); } [Test] public void internal_macro_is_preferred() { RunCompilerTestCase(@"internal-macro-is-preferred.boo"); } [Test] public void macro_1() { RunCompilerTestCase(@"macro-1.boo"); } [Test] public void macro_2() { RunCompilerTestCase(@"macro-2.boo"); } [Test] public void macro_3() { RunCompilerTestCase(@"macro-3.boo"); } [Test] public void macro_4() { RunCompilerTestCase(@"macro-4.boo"); } [Test] public void macro_5() { RunCompilerTestCase(@"macro-5.boo"); } [Test] public void macro_arguments_1() { RunCompilerTestCase(@"macro-arguments-1.boo"); } [Test] public void macro_arguments_2() { RunCompilerTestCase(@"macro-arguments-2.boo"); } [Test] public void macro_attribute_fpa() { RunCompilerTestCase(@"macro-attribute-fpa.boo"); } [Test] public void macro_case_1() { RunCompilerTestCase(@"macro-case-1.boo"); } [Test] public void macro_case_otherwise_2() { RunCompilerTestCase(@"macro-case-otherwise-2.boo"); } [Test] public void macro_case_otherwise() { RunCompilerTestCase(@"macro-case-otherwise.boo"); } [Test] public void macro_expansion_order_1() { RunCompilerTestCase(@"macro-expansion-order-1.boo"); } [Test] public void macro_imports_1() { RunCompilerTestCase(@"macro-imports-1.boo"); } [Test] public void macro_should_be_able_to_reach_module() { RunCompilerTestCase(@"macro-should-be-able-to-reach-module.boo"); } [Test] public void macro_yielding_generic_class() { RunCompilerTestCase(@"macro-yielding-generic-class.boo"); } [Test] public void macro_yielding_generic_method_1() { RunCompilerTestCase(@"macro-yielding-generic-method-1.boo"); } [Test] public void macro_yielding_partial_enum_with_existing_partial_definition() { RunCompilerTestCase(@"macro-yielding-partial-enum-with-existing-partial-definition.boo"); } [Test] public void macro_yielding_partial_enums() { RunCompilerTestCase(@"macro-yielding-partial-enums.boo"); } [Test] public void member_macro_changing_all_sibling_method_bodies() { RunCompilerTestCase(@"member-macro-changing-all-sibling-method-bodies.boo"); } [Test] public void member_macro_contributing_initialization_code() { RunCompilerTestCase(@"member-macro-contributing-initialization-code.boo"); } [Test] public void member_macro_initialization_order() { RunCompilerTestCase(@"member-macro-initialization-order.boo"); } [Test] public void member_macro_nodes_inherit_visibility_and_attributes() { RunCompilerTestCase(@"member-macro-nodes-inherit-visibility-and-attributes.boo"); } [Test] public void member_macro_nodes_inherit_visibility_only_when_not_set() { RunCompilerTestCase(@"member-macro-nodes-inherit-visibility-only-when-not-set.boo"); } [Test] public void member_macro_producing_field_and_constructor() { RunCompilerTestCase(@"member-macro-producing-field-and-constructor.boo"); } [Test] public void member_macro_producing_field_and_property() { RunCompilerTestCase(@"member-macro-producing-field-and-property.boo"); } [Test] public void nested_macros_1() { RunCompilerTestCase(@"nested-macros-1.boo"); } [Test] public void nested_macros_2() { RunCompilerTestCase(@"nested-macros-2.boo"); } [Test] public void nested_macros_3() { RunCompilerTestCase(@"nested-macros-3.boo"); } [Test] public void nested_macros_4() { RunCompilerTestCase(@"nested-macros-4.boo"); } [Test] public void nested_macros_5() { RunCompilerTestCase(@"nested-macros-5.boo"); } [Test] public void nested_macros_6() { RunCompilerTestCase(@"nested-macros-6.boo"); } [Ignore("Use of external extension within another external extension does not work yet")][Test] public void nested_macros_7() { RunCompilerTestCase(@"nested-macros-7.boo"); } [Test] public void nested_macros_8() { RunCompilerTestCase(@"nested-macros-8.boo"); } [Test] public void nested_macros() { RunCompilerTestCase(@"nested-macros.boo"); } [Test] public void preserving_1() { RunCompilerTestCase(@"preserving-1.boo"); } [Test] public void print_1() { RunCompilerTestCase(@"print-1.boo"); } [Test] public void print_2() { RunCompilerTestCase(@"print-2.boo"); } [Test] public void then_can_be_used_as_macro_name() { RunCompilerTestCase(@"then-can-be-used-as-macro-name.boo"); } [Test] public void type_member_macro_yielding_member_with_member_generating_attribute() { RunCompilerTestCase(@"type-member-macro-yielding-member-with-member-generating-attribute.boo"); } [Test] public void using_1() { RunCompilerTestCase(@"using-1.boo"); } [Test] public void using_2() { RunCompilerTestCase(@"using-2.boo"); } [Test] public void using_3() { RunCompilerTestCase(@"using-3.boo"); } [Test] public void using_4() { RunCompilerTestCase(@"using-4.boo"); } [Test] public void using_5() { RunCompilerTestCase(@"using-5.boo"); } [Test] public void yieldAll_1() { RunCompilerTestCase(@"yieldAll-1.boo"); } [Test] public void yieldAll_2() { RunCompilerTestCase(@"yieldAll-2.boo"); } override protected string GetRelativeTestCasesPath() { return "macros"; } } }
#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 { // Define our necessary event types (EventArgs and the delegate) public delegate void MesgEventHandler(object sender, MesgEventArgs e); public delegate void MesgDefinitionEventHandler(object sender, MesgDefinitionEventArgs e); public class MesgEventArgs : EventArgs { public Mesg mesg = null; public MesgEventArgs() { } public MesgEventArgs(Mesg newMesg) { mesg = new Mesg(newMesg); } } public class MesgDefinitionEventArgs : EventArgs { public MesgDefinition mesgDef = null; public MesgDefinitionEventArgs() { } public MesgDefinitionEventArgs(MesgDefinition newDefn) { mesgDef = new MesgDefinition(newDefn); } } /// <summary> /// The MesgBroadcaster manages Mesg and MesgDefinition events. Its /// handlers should be connected to the source of Mesg and MesgDef events /// (such as a file decoder). /// Clients may subscribe to the Broadcasters events (Mesg, Mesg Def /// or specofic Profile Mesg) /// </summary> public class MesgBroadcaster { #region Methods & Events public event MesgDefinitionEventHandler MesgDefinitionEvent; public event MesgEventHandler MesgEvent; // One event for every Profile Mesg public event MesgEventHandler FileIdMesgEvent; public event MesgEventHandler FileCreatorMesgEvent; public event MesgEventHandler TimestampCorrelationMesgEvent; public event MesgEventHandler SoftwareMesgEvent; public event MesgEventHandler SlaveDeviceMesgEvent; public event MesgEventHandler CapabilitiesMesgEvent; public event MesgEventHandler FileCapabilitiesMesgEvent; public event MesgEventHandler MesgCapabilitiesMesgEvent; public event MesgEventHandler FieldCapabilitiesMesgEvent; public event MesgEventHandler DeviceSettingsMesgEvent; public event MesgEventHandler UserProfileMesgEvent; public event MesgEventHandler HrmProfileMesgEvent; public event MesgEventHandler SdmProfileMesgEvent; public event MesgEventHandler BikeProfileMesgEvent; public event MesgEventHandler ZonesTargetMesgEvent; public event MesgEventHandler SportMesgEvent; public event MesgEventHandler HrZoneMesgEvent; public event MesgEventHandler SpeedZoneMesgEvent; public event MesgEventHandler CadenceZoneMesgEvent; public event MesgEventHandler PowerZoneMesgEvent; public event MesgEventHandler MetZoneMesgEvent; public event MesgEventHandler GoalMesgEvent; public event MesgEventHandler ActivityMesgEvent; public event MesgEventHandler SessionMesgEvent; public event MesgEventHandler LapMesgEvent; public event MesgEventHandler LengthMesgEvent; public event MesgEventHandler RecordMesgEvent; public event MesgEventHandler EventMesgEvent; public event MesgEventHandler DeviceInfoMesgEvent; public event MesgEventHandler TrainingFileMesgEvent; public event MesgEventHandler HrvMesgEvent; public event MesgEventHandler CameraEventMesgEvent; public event MesgEventHandler GyroscopeDataMesgEvent; public event MesgEventHandler AccelerometerDataMesgEvent; public event MesgEventHandler ThreeDSensorCalibrationMesgEvent; public event MesgEventHandler VideoFrameMesgEvent; public event MesgEventHandler ObdiiDataMesgEvent; public event MesgEventHandler NmeaSentenceMesgEvent; public event MesgEventHandler AviationAttitudeMesgEvent; public event MesgEventHandler VideoMesgEvent; public event MesgEventHandler VideoTitleMesgEvent; public event MesgEventHandler VideoDescriptionMesgEvent; public event MesgEventHandler VideoClipMesgEvent; public event MesgEventHandler CourseMesgEvent; public event MesgEventHandler CoursePointMesgEvent; public event MesgEventHandler SegmentIdMesgEvent; public event MesgEventHandler SegmentLeaderboardEntryMesgEvent; public event MesgEventHandler SegmentPointMesgEvent; public event MesgEventHandler SegmentLapMesgEvent; public event MesgEventHandler SegmentFileMesgEvent; public event MesgEventHandler WorkoutMesgEvent; public event MesgEventHandler WorkoutStepMesgEvent; public event MesgEventHandler ScheduleMesgEvent; public event MesgEventHandler TotalsMesgEvent; public event MesgEventHandler WeightScaleMesgEvent; public event MesgEventHandler BloodPressureMesgEvent; public event MesgEventHandler MonitoringInfoMesgEvent; public event MesgEventHandler MonitoringMesgEvent; public event MesgEventHandler MemoGlobMesgEvent; public event MesgEventHandler PadMesgEvent; public void OnMesg(object sender, MesgEventArgs e) { // Notify any subscribers of either our general mesg event or specific profile mesg event if (MesgEvent != null) { MesgEvent(sender, e); } switch (e.mesg.Num) { case (ushort)MesgNum.FileId: if (FileIdMesgEvent != null) { FileIdMesg fileIdMesg = new FileIdMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = fileIdMesg; FileIdMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.FileCreator: if (FileCreatorMesgEvent != null) { FileCreatorMesg fileCreatorMesg = new FileCreatorMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = fileCreatorMesg; FileCreatorMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.TimestampCorrelation: if (TimestampCorrelationMesgEvent != null) { TimestampCorrelationMesg timestampCorrelationMesg = new TimestampCorrelationMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = timestampCorrelationMesg; TimestampCorrelationMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Software: if (SoftwareMesgEvent != null) { SoftwareMesg softwareMesg = new SoftwareMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = softwareMesg; SoftwareMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.SlaveDevice: if (SlaveDeviceMesgEvent != null) { SlaveDeviceMesg slaveDeviceMesg = new SlaveDeviceMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = slaveDeviceMesg; SlaveDeviceMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Capabilities: if (CapabilitiesMesgEvent != null) { CapabilitiesMesg capabilitiesMesg = new CapabilitiesMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = capabilitiesMesg; CapabilitiesMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.FileCapabilities: if (FileCapabilitiesMesgEvent != null) { FileCapabilitiesMesg fileCapabilitiesMesg = new FileCapabilitiesMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = fileCapabilitiesMesg; FileCapabilitiesMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.MesgCapabilities: if (MesgCapabilitiesMesgEvent != null) { MesgCapabilitiesMesg mesgCapabilitiesMesg = new MesgCapabilitiesMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = mesgCapabilitiesMesg; MesgCapabilitiesMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.FieldCapabilities: if (FieldCapabilitiesMesgEvent != null) { FieldCapabilitiesMesg fieldCapabilitiesMesg = new FieldCapabilitiesMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = fieldCapabilitiesMesg; FieldCapabilitiesMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.DeviceSettings: if (DeviceSettingsMesgEvent != null) { DeviceSettingsMesg deviceSettingsMesg = new DeviceSettingsMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = deviceSettingsMesg; DeviceSettingsMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.UserProfile: if (UserProfileMesgEvent != null) { UserProfileMesg userProfileMesg = new UserProfileMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = userProfileMesg; UserProfileMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.HrmProfile: if (HrmProfileMesgEvent != null) { HrmProfileMesg hrmProfileMesg = new HrmProfileMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = hrmProfileMesg; HrmProfileMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.SdmProfile: if (SdmProfileMesgEvent != null) { SdmProfileMesg sdmProfileMesg = new SdmProfileMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = sdmProfileMesg; SdmProfileMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.BikeProfile: if (BikeProfileMesgEvent != null) { BikeProfileMesg bikeProfileMesg = new BikeProfileMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = bikeProfileMesg; BikeProfileMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.ZonesTarget: if (ZonesTargetMesgEvent != null) { ZonesTargetMesg zonesTargetMesg = new ZonesTargetMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = zonesTargetMesg; ZonesTargetMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Sport: if (SportMesgEvent != null) { SportMesg sportMesg = new SportMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = sportMesg; SportMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.HrZone: if (HrZoneMesgEvent != null) { HrZoneMesg hrZoneMesg = new HrZoneMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = hrZoneMesg; HrZoneMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.SpeedZone: if (SpeedZoneMesgEvent != null) { SpeedZoneMesg speedZoneMesg = new SpeedZoneMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = speedZoneMesg; SpeedZoneMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.CadenceZone: if (CadenceZoneMesgEvent != null) { CadenceZoneMesg cadenceZoneMesg = new CadenceZoneMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = cadenceZoneMesg; CadenceZoneMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.PowerZone: if (PowerZoneMesgEvent != null) { PowerZoneMesg powerZoneMesg = new PowerZoneMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = powerZoneMesg; PowerZoneMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.MetZone: if (MetZoneMesgEvent != null) { MetZoneMesg metZoneMesg = new MetZoneMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = metZoneMesg; MetZoneMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Goal: if (GoalMesgEvent != null) { GoalMesg goalMesg = new GoalMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = goalMesg; GoalMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Activity: if (ActivityMesgEvent != null) { ActivityMesg activityMesg = new ActivityMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = activityMesg; ActivityMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Session: if (SessionMesgEvent != null) { SessionMesg sessionMesg = new SessionMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = sessionMesg; SessionMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Lap: if (LapMesgEvent != null) { LapMesg lapMesg = new LapMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = lapMesg; LapMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Length: if (LengthMesgEvent != null) { LengthMesg lengthMesg = new LengthMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = lengthMesg; LengthMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Record: if (RecordMesgEvent != null) { RecordMesg recordMesg = new RecordMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = recordMesg; RecordMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Event: if (EventMesgEvent != null) { EventMesg eventMesg = new EventMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = eventMesg; EventMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.DeviceInfo: if (DeviceInfoMesgEvent != null) { DeviceInfoMesg deviceInfoMesg = new DeviceInfoMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = deviceInfoMesg; DeviceInfoMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.TrainingFile: if (TrainingFileMesgEvent != null) { TrainingFileMesg trainingFileMesg = new TrainingFileMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = trainingFileMesg; TrainingFileMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Hrv: if (HrvMesgEvent != null) { HrvMesg hrvMesg = new HrvMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = hrvMesg; HrvMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.CameraEvent: if (CameraEventMesgEvent != null) { CameraEventMesg cameraEventMesg = new CameraEventMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = cameraEventMesg; CameraEventMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.GyroscopeData: if (GyroscopeDataMesgEvent != null) { GyroscopeDataMesg gyroscopeDataMesg = new GyroscopeDataMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = gyroscopeDataMesg; GyroscopeDataMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.AccelerometerData: if (AccelerometerDataMesgEvent != null) { AccelerometerDataMesg accelerometerDataMesg = new AccelerometerDataMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = accelerometerDataMesg; AccelerometerDataMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.ThreeDSensorCalibration: if (ThreeDSensorCalibrationMesgEvent != null) { ThreeDSensorCalibrationMesg threeDSensorCalibrationMesg = new ThreeDSensorCalibrationMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = threeDSensorCalibrationMesg; ThreeDSensorCalibrationMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.VideoFrame: if (VideoFrameMesgEvent != null) { VideoFrameMesg videoFrameMesg = new VideoFrameMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = videoFrameMesg; VideoFrameMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.ObdiiData: if (ObdiiDataMesgEvent != null) { ObdiiDataMesg obdiiDataMesg = new ObdiiDataMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = obdiiDataMesg; ObdiiDataMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.NmeaSentence: if (NmeaSentenceMesgEvent != null) { NmeaSentenceMesg nmeaSentenceMesg = new NmeaSentenceMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = nmeaSentenceMesg; NmeaSentenceMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.AviationAttitude: if (AviationAttitudeMesgEvent != null) { AviationAttitudeMesg aviationAttitudeMesg = new AviationAttitudeMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = aviationAttitudeMesg; AviationAttitudeMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Video: if (VideoMesgEvent != null) { VideoMesg videoMesg = new VideoMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = videoMesg; VideoMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.VideoTitle: if (VideoTitleMesgEvent != null) { VideoTitleMesg videoTitleMesg = new VideoTitleMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = videoTitleMesg; VideoTitleMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.VideoDescription: if (VideoDescriptionMesgEvent != null) { VideoDescriptionMesg videoDescriptionMesg = new VideoDescriptionMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = videoDescriptionMesg; VideoDescriptionMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.VideoClip: if (VideoClipMesgEvent != null) { VideoClipMesg videoClipMesg = new VideoClipMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = videoClipMesg; VideoClipMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Course: if (CourseMesgEvent != null) { CourseMesg courseMesg = new CourseMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = courseMesg; CourseMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.CoursePoint: if (CoursePointMesgEvent != null) { CoursePointMesg coursePointMesg = new CoursePointMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = coursePointMesg; CoursePointMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.SegmentId: if (SegmentIdMesgEvent != null) { SegmentIdMesg segmentIdMesg = new SegmentIdMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = segmentIdMesg; SegmentIdMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.SegmentLeaderboardEntry: if (SegmentLeaderboardEntryMesgEvent != null) { SegmentLeaderboardEntryMesg segmentLeaderboardEntryMesg = new SegmentLeaderboardEntryMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = segmentLeaderboardEntryMesg; SegmentLeaderboardEntryMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.SegmentPoint: if (SegmentPointMesgEvent != null) { SegmentPointMesg segmentPointMesg = new SegmentPointMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = segmentPointMesg; SegmentPointMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.SegmentLap: if (SegmentLapMesgEvent != null) { SegmentLapMesg segmentLapMesg = new SegmentLapMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = segmentLapMesg; SegmentLapMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.SegmentFile: if (SegmentFileMesgEvent != null) { SegmentFileMesg segmentFileMesg = new SegmentFileMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = segmentFileMesg; SegmentFileMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Workout: if (WorkoutMesgEvent != null) { WorkoutMesg workoutMesg = new WorkoutMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = workoutMesg; WorkoutMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.WorkoutStep: if (WorkoutStepMesgEvent != null) { WorkoutStepMesg workoutStepMesg = new WorkoutStepMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = workoutStepMesg; WorkoutStepMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Schedule: if (ScheduleMesgEvent != null) { ScheduleMesg scheduleMesg = new ScheduleMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = scheduleMesg; ScheduleMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Totals: if (TotalsMesgEvent != null) { TotalsMesg totalsMesg = new TotalsMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = totalsMesg; TotalsMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.WeightScale: if (WeightScaleMesgEvent != null) { WeightScaleMesg weightScaleMesg = new WeightScaleMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = weightScaleMesg; WeightScaleMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.BloodPressure: if (BloodPressureMesgEvent != null) { BloodPressureMesg bloodPressureMesg = new BloodPressureMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = bloodPressureMesg; BloodPressureMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.MonitoringInfo: if (MonitoringInfoMesgEvent != null) { MonitoringInfoMesg monitoringInfoMesg = new MonitoringInfoMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = monitoringInfoMesg; MonitoringInfoMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Monitoring: if (MonitoringMesgEvent != null) { MonitoringMesg monitoringMesg = new MonitoringMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = monitoringMesg; MonitoringMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.MemoGlob: if (MemoGlobMesgEvent != null) { MemoGlobMesg memoGlobMesg = new MemoGlobMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = memoGlobMesg; MemoGlobMesgEvent(sender, mesgEventArgs); } break; case (ushort)MesgNum.Pad: if (PadMesgEvent != null) { PadMesg padMesg = new PadMesg(e.mesg); MesgEventArgs mesgEventArgs = new MesgEventArgs(); mesgEventArgs.mesg = padMesg; PadMesgEvent(sender, mesgEventArgs); } break; } } public void OnMesgDefinition(object sender, MesgDefinitionEventArgs e) { // Notify any subscribers if (MesgDefinitionEvent != null) { MesgDefinitionEvent(sender, e); } } #endregion // Methods } // Class } // namespace
using System; using System.IO; using System.Security.Cryptography; using System.Text; using Contrive.Common.Extensions; namespace Contrive.Common { public class Cryptographer<ENCRYPTION_ALGORITHM, HASH_ALGORITM> : CryptographerBase where ENCRYPTION_ALGORITHM : SymmetricAlgorithm, new() where HASH_ALGORITM : HashAlgorithm, new() { public Cryptographer(byte[] encryptionKey, byte[] hmacKey) { Verify.NotEmpty(encryptionKey, "encryptionKey"); Verify.NotEmpty(hmacKey, "hmacKey"); _hmacKey = hmacKey; _encryptionKey = encryptionKey; } readonly byte[] _encryptionKey; readonly byte[] _hmacKey; int _hashSize; int HashSize { get { if (_hashSize == 0) { using (var hashAlgorithm = new HASH_ALGORITM()) { _hashSize = hashAlgorithm.HashSize; } } return _hashSize; } } protected override string Protect(string input, Protection protectionOption) { var data = Encoding.Unicode.GetBytes(input); Verify.NotNull(data, "data"); if (protectionOption == Protection.All || protectionOption == Protection.Validation) { var hashData = Hash(data); var validationData = new byte[hashData.Length + data.Length]; Buffer.BlockCopy(data, 0, validationData, 0, data.Length); Buffer.BlockCopy(hashData, 0, validationData, data.Length, hashData.Length); data = validationData; } if (protectionOption == Protection.All || protectionOption == Protection.Encryption) data = Encode(data); return data.ToHex(); } protected override string Unprotect(string encodedData, Protection protectionOption) { Verify.NotNull(encodedData, "encodedData"); if (encodedData.Length%2 != 0) throw new ArgumentException(null, "encodedData"); byte[] buffer; try { buffer = encodedData.HexToBinary(); } catch { throw new ArgumentException(null, "encodedData"); } if (buffer == null || buffer.Length < 1) throw new ArgumentException(null, "encodedData"); if (protectionOption == Protection.All || protectionOption == Protection.Encryption) { buffer = Decode(buffer); if (buffer == null) return null; } if (protectionOption == Protection.All || protectionOption == Protection.Validation) { if (buffer.Length < HashSize) return null; var bufferCopy = buffer; buffer = new byte[bufferCopy.Length - HashSize]; Buffer.BlockCopy(bufferCopy, 0, buffer, 0, buffer.Length); var hashValue = Hash(buffer); if (hashValue == null || hashValue.Length != HashSize) return null; for (var index = 0; index < hashValue.Length; ++index) { if (hashValue[index] != bufferCopy[buffer.Length + index]) return null; } } return Encoding.UTF8.GetString(buffer); } byte[] Encode(byte[] buffer) { Verify.NotEmpty(buffer, "buffer"); byte[] outputBuffer; using (var algorithm = new ENCRYPTION_ALGORITHM()) { using (var ms = new MemoryStream()) { algorithm.GenerateIV(); algorithm.Key = _encryptionKey; ms.Write(algorithm.IV, 0, algorithm.IV.Length); using (var encryptor = algorithm.CreateEncryptor()) { using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { cs.Write(buffer, 0, buffer.Length); cs.FlushFinalBlock(); } } outputBuffer = ms.ToArray(); } } return outputBuffer; } byte[] Decode(byte[] inputBuffer) { Verify.NotEmpty(inputBuffer, "inputBuffer"); byte[] outputBuffer; using (var algorithm = new ENCRYPTION_ALGORITHM()) { try { var inputVectorBuffer = new byte[algorithm.IV.Length]; Array.Copy(inputBuffer, inputVectorBuffer, inputVectorBuffer.Length); Buffer.BlockCopy(inputVectorBuffer, 0, algorithm.IV, 0, inputVectorBuffer.Length); algorithm.Key = _encryptionKey; using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputBuffer, inputVectorBuffer.Length, inputBuffer.Length - inputVectorBuffer.Length); cs.FlushFinalBlock(); } outputBuffer = ms.ToArray(); } } catch (FormatException ex) { this.LogException(ex); throw new CryptographicException("The value could not be decoded.", ex); } } return outputBuffer; } byte[] Hash(byte[] buffer) { byte[] hash; using (var hashAlgorithm = new HASH_ALGORITM()) { if (hashAlgorithm.Is<KeyedHashAlgorithm>()) hash = HashKeyed(hashAlgorithm.As<KeyedHashAlgorithm>(), buffer, _hmacKey); else hash = HashNonKeyed(hashAlgorithm, buffer, _hmacKey); } return hash; } static byte[] HashNonKeyed(HashAlgorithm algorithm, byte[] buffer, byte[] validationKey) { var length = buffer.Length + validationKey.Length; var newBuffer = new byte[length]; Buffer.BlockCopy(buffer, 0, newBuffer, 0, buffer.Length); Buffer.BlockCopy(validationKey, 0, newBuffer, buffer.Length, validationKey.Length); return algorithm.ComputeHash(newBuffer); } static byte[] HashKeyed(KeyedHashAlgorithm algorithm, byte[] buffer, byte[] validationKey) { algorithm.Key = validationKey; return algorithm.ComputeHash(buffer); } } }
#region License /* Copyright (c) 2010-2014 Danko Kozar 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 License using System.Collections.Generic; using eDriven.Core.Events; using UnityEngine; using EventHandler=eDriven.Core.Events.EventHandler; using MulticastDelegate=eDriven.Core.Events.MulticastDelegate; namespace eDriven.Core.Managers { /// <summary> /// Connects to SystemManager signals /// Dispatches touch events to interested parties /// </summary> public sealed class TouchEventDispatcher : EventDispatcher { #if DEBUG /// <summary> /// Debug mode /// </summary> public new static bool DebugMode; #endif #region Singleton private static TouchEventDispatcher _instance; private TouchEventDispatcher() { // Constructor is protected! } /// <summary> /// Singleton instance /// </summary> public static TouchEventDispatcher Instance { get { if (_instance == null) { #if DEBUG if (DebugMode) Debug.Log(string.Format("Instantiating TouchEventDispatcher instance")); #endif _instance = new TouchEventDispatcher(); _instance.Initialize(); } return _instance; } } #endregion /// <summary> /// A list of plugins /// </summary> private readonly List<ITouchEventDispatcherPlugin> _plugins = new List<ITouchEventDispatcherPlugin>(); #region Initialization /// <summary> /// Initialization routine /// </summary> private void Initialize() { #if DEBUG if (DebugMode) Debug.Log(string.Format("Initializing TouchEventDispatcher")); #endif } #endregion #region Methods /// <summary> /// Adds the plugin /// </summary> /// <param name="plugin"></param> public void AddPlugin(ITouchEventDispatcherPlugin plugin) { _plugins.Add(plugin); plugin.Initialize(this); } /// <summary> /// Removes the plugin /// </summary> /// <param name="plugin"></param> public void RemovePlugin(ITouchEventDispatcherPlugin plugin) { _plugins.Remove(plugin); plugin.Dispose(); } #endregion #region Multicast delegates private MulticastDelegate _singleTouch; /// <summary> /// Fires resize events /// </summary> public MulticastDelegate SingleTouch { get { if (null == _singleTouch) _singleTouch = new MulticastDelegate(this, TouchEvent.SINGLE_TOUCH); return _singleTouch; } set { _singleTouch = value; } } private MulticastDelegate _doubleTouch; /// <summary> /// Fires resize events /// </summary> public MulticastDelegate DoubleTouch { get { if (null == _doubleTouch) _doubleTouch = new MulticastDelegate(this, TouchEvent.DOUBLE_TOUCH); return _doubleTouch; } set { _doubleTouch = value; } } private MulticastDelegate _trippleTouch; /// <summary> /// Fires resize events /// </summary> public MulticastDelegate TrippleTouch { get { if (null == _trippleTouch) _trippleTouch = new MulticastDelegate(this, TouchEvent.TRIPPLE_TOUCH); return _trippleTouch; } set { _trippleTouch = value; } } private MulticastDelegate _quadrupleTouch; /// <summary> /// Fires resize events /// </summary> public MulticastDelegate QuadrupleTouch { get { if (null == _quadrupleTouch) _quadrupleTouch = new MulticastDelegate(this, TouchEvent.QUADRUPLE_TOUCH); return _quadrupleTouch; } set { _quadrupleTouch = value; } } private MulticastDelegate _quintupleTouch; /// <summary> /// Fires resize events /// </summary> public MulticastDelegate QuintupleTouch { get { if (null == _quintupleTouch) _quintupleTouch = new MulticastDelegate(this, TouchEvent.QUINTUPLE_TOUCH); return _quintupleTouch; } set { _quintupleTouch = value; } } #endregion #region Handlers private int _touchCount; public override void AddEventListener(string eventType, EventHandler handler, EventPhase phases) { base.AddEventListener(eventType, handler, phases); _touchCount++; SystemManager.Instance.TouchSignal.Connect(TouchSlot); } public override void RemoveEventListener(string eventType, EventHandler handler, EventPhase phases) { base.RemoveEventListener(eventType, handler, phases); _touchCount--; if (_touchCount <= 0) { SystemManager.Instance.TouchSignal.Disconnect(TouchSlot); } } #endregion #region Slots private void TouchSlot(params object[] parameters) { if (_touchCount <= 0) return; Touch[] touches = (Touch[])parameters[0]; #if DEBUG if (DebugMode) { Debug.Log("Touch with " + touches.Length + " fingers"); } #endif TouchEvent touchEvent = new TouchEvent(TouchEvent.TOUCH); DispatchEvent(touchEvent); if (touchEvent.Canceled) return; switch (touches.Length) { case 1: touchEvent = new TouchEvent(TouchEvent.SINGLE_TOUCH); DispatchEvent(touchEvent); break; case 2: touchEvent = new TouchEvent(TouchEvent.DOUBLE_TOUCH); DispatchEvent(touchEvent); break; case 3: touchEvent = new TouchEvent(TouchEvent.TRIPPLE_TOUCH); DispatchEvent(touchEvent); break; case 4: touchEvent = new TouchEvent(TouchEvent.QUADRUPLE_TOUCH); DispatchEvent(touchEvent); break; case 5: touchEvent = new TouchEvent(TouchEvent.QUINTUPLE_TOUCH); DispatchEvent(touchEvent); break; default: break; } // process custom gestures foreach (ITouchEventDispatcherPlugin plugin in _plugins) { plugin.Process(touches); } } #endregion #region IDisposable public override void Dispose() { base.Dispose(); foreach (ITouchEventDispatcherPlugin plugin in _plugins) { plugin.Dispose(); } _plugins.Clear(); } #endregion } }
/****************************************************************************************** * The MIT License (MIT) * * Copyright (c) 2014 oxage.net * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************************/ using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; namespace Oxage { /// <summary> /// Wake-on-LAN (WOL) utility /// </summary> public class Program { private static string ip; //"192.168.1.6" private static string mac; //"00:1A:A0:48:F1:9B" private static int interval = 5; private static bool ping = false; public static void Main(string[] args) { if (args == null || args.Length == 0 || args[0] == "--help") { Console.WriteLine("Usage:"); Console.WriteLine(" wol [options]"); Console.WriteLine(""); Console.WriteLine("Options:"); Console.WriteLine(" -mac [xx:xx:xx:xx:xx:xx] MAC address of a device to wake up"); Console.WriteLine(" -ip [a.b.c.d] IP address of a device to ping"); Console.WriteLine(" -f [host] Find MAC address by IP or hostname"); Console.WriteLine(" -t [sec] Time to wait between pings"); Console.WriteLine(" -p Send wake up and ping until alive"); Console.WriteLine(""); Console.WriteLine("Examples:"); Console.WriteLine(" wol -f 192.168.1.1"); Console.WriteLine(" wol -mac 00:1A:A0:48:F1:9B"); Console.WriteLine(" wol -mac 00:1A:A0:48:F1:9B -ip 192.168.1.1 -p -t 5"); return; } //Handle global exception AppDomain.CurrentDomain.UnhandledException += (sender, e) => { var error = e.ExceptionObject as Exception; var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(error.Message); Console.ForegroundColor = color; Environment.Exit(-1); }; for (int i = 0; i < args.Length; i++) { string arg = args[i]; switch (arg) { case "-ip": ip = args[++i]; break; case "-mac": mac = args[++i]; Wol.Wake(mac); return; case "-p": ping = true; break; case "-t": interval = int.Parse(args[++i]); break; case "-f": var arp = new Arp(); Console.WriteLine(arp.GetMACAddress(args[++i])); return; default: throw new Exception("Unknown argument: " + arg); } } if (string.IsNullOrEmpty(mac)) { throw new Exception("MAC address is missing!"); } var array = GetMacArray(mac); if (ping) { if (string.IsNullOrEmpty(ip)) { throw new Exception("IP address is missing!"); } //Send wake up signals until the target device responds while (!Ping(ip)) { WakeUp(array); Thread.Sleep(interval * 1000); } } else { //Just send a WOL wake up signal WakeUp(array); } } /// <summary> /// Sends a ping signal to an IP address. /// </summary> /// <param name="ip"></param> /// <returns></returns> /// <remarks> /// Reference: /// http://msdn.microsoft.com/en-us/library/system.net.networkinformation.pingreply.buffer%28v=vs.110%29.aspx /// </remarks> public static bool Ping(string ip) { var ping = new Ping(); //Create a buffer of 32 bytes of data to be transmitted. byte[] data = Encoding.ASCII.GetBytes("................................"); //Jump though 64 routing nodes tops, and don't fragment the packet var options = new PingOptions(64, true); //Send the ping var reply = ping.Send(ip, 3000, data, options); return reply.Status == IPStatus.Success; } /// <summary> /// Sends a Wake-on-LAN packet to the specified MAC address. /// </summary> /// <param name="mac">Physical MAC address to send WOL packet to.</param> public static void WakeUp(byte[] mac) { //WOL packet is sent over UDP 255.255.255.0:40000. var client = new UdpClient(); client.Connect(IPAddress.Broadcast, 40000); //WOL packet contains a 6-bytes trailer and 16 times a 6-bytes sequence containing the MAC address. byte[] packet = new byte[17 * 6]; //Trailer of 6 times 0xFF. for (int i = 0; i < 6; i++) { packet[i] = 0xFF; } //Body of magic packet contains 16 times the MAC address. for (int i = 1; i <= 16; i++) { for (int j = 0; j < 6; j++) { packet[i * 6 + j] = mac[j]; } } //Send the WOL packet client.Send(packet, packet.Length); } /// <summary> /// Converts MAC string to byte array. /// </summary> public static byte[] GetMacArray(string mac) { if (string.IsNullOrEmpty(mac)) { throw new ArgumentNullException("mac"); } mac = mac.Replace("-", ""); byte[] result = new byte[6]; try { string[] tmp = mac.Split(':', '-'); if (tmp.Length != 6) { tmp = mac.Split('.'); if (tmp.Length == 3) { for (int i = 0; i < 3; i++) { result[i * 2] = byte.Parse(tmp[i].Substring(0, 2), NumberStyles.HexNumber); result[i * 2 + 1] = byte.Parse(tmp[i].Substring(2, 2), NumberStyles.HexNumber); } } else { for (int i = 0; i < 12; i += 2) { result[i / 2] = byte.Parse(mac.Substring(i, 2), NumberStyles.HexNumber); } } } else { for (int i = 0; i < 6; i++) { result[i] = byte.Parse(tmp[i], NumberStyles.HexNumber); } } } catch { throw new ArgumentException("Argument doesn't have the correct format: " + mac, "mac"); } return result; } } internal static class Win32 { [DllImport("iphlpapi.dll", ExactSpelling = true)] internal static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen); } public class Arp { public string GetMACAddress(IPAddress ipAddress) { byte[] addressBytes = ipAddress.GetAddressBytes(); int address = BitConverter.ToInt32(addressBytes, 0); byte[] macAddr = new byte[6]; uint macAddrLen = (uint)macAddr.Length; if (Win32.SendARP(address, 0, macAddr, ref macAddrLen) != 0) { return null; } StringBuilder macAddressString = new StringBuilder(); for (int i = 0; i < macAddr.Length; i++) { if (macAddressString.Length > 0) macAddressString.Append(":"); macAddressString.AppendFormat("{0:x2}", macAddr[i]); } return macAddressString.ToString(); } public string GetMACAddress(string hostName) { IPHostEntry hostEntry = null; try { hostEntry = Dns.GetHostEntry(hostName); } catch { return null; } if (hostEntry.AddressList.Length == 0) { return null; } // Find the first address IPV4 address for that host IPAddress ipAddress = null; foreach (IPAddress ip in hostEntry.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { ipAddress = ip; break; } } // If running on .net 3.5 you can do it with LINQ :) //IPAddress ipAddress = hostEntry.AddressList.First<IPAddress>(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); return GetMACAddress(ipAddress); } } /// <summary> /// Class for sending Wake-on-LAN Magic Packets /// </summary> public static class Wol { /// <summary> /// Wake up the device by sending a 'magic' packet /// </summary> /// <param name="macAddress"></param> public static void Wake(string macAddress) { string[] byteStrings = macAddress.Split(':'); byte[] bytes = new byte[6]; for (int i = 0; i < 6; i++) bytes[i] = (byte)Int32.Parse(byteStrings[i], System.Globalization.NumberStyles.HexNumber); Wake(bytes); } /// <summary> /// Send a magic packet /// </summary> /// <param name="macAddress"></param> public static void Wake(byte[] macAddress) { if (macAddress == null) { throw new ArgumentNullException("macAddress", "MAC Address must be provided"); } if (macAddress.Length != 6) { throw new ArgumentOutOfRangeException("macAddress", "MAC Address must have 6 bytes"); } // A Wake on LAN magic packet contains a 6 byte header and // the MAC address of the target MAC address (6 bytes) 16 times byte[] wolPacket = new byte[17 * 6]; MemoryStream ms = new MemoryStream(wolPacket, true); // Write the 6 byte 0xFF header for (int i = 0; i < 6; i++) { ms.WriteByte(0xFF); } // Write the MAC Address 16 times for (int i = 0; i < 16; i++) { ms.Write(macAddress, 0, macAddress.Length); } // Broadcast the magic packet UdpClient udp = new UdpClient(); udp.Connect(IPAddress.Broadcast, 0); udp.Send(wolPacket, wolPacket.Length); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class VineDragComponent : MonoBehaviour { static VineComponent vine; public GameObject linePrefab; static LineRenderer line1; static VineDragComponent instance; private static bool dragging = false; private static List<Vector3> startDragPositions = new List<Vector3> (); private static List<float> vinePercentagePositions = new List<float> (); private static List<Vector3> releasePositions = new List<Vector3>(); private static Vector3 clickStartPosition; //private static Vector3 clickStopPosition; private static float clickStartPercentage; public static bool vineCut = false; //private static GameObject debugSphere1; //private static GameObject debugSphere2; // Use this for initialization void Start () { instance = this; //debugSphere1 = GameObject.CreatePrimitive (PrimitiveType.Sphere); //debugSphere2 = GameObject.CreatePrimitive (PrimitiveType.Sphere); } // Update is called once per frame void Update () { if (vine != null) { line1.transform.position = gameObject.transform.position; line1.SetPosition(0, vine.ends[0].gameObject.transform.position); line1.SetPosition(2, vine.ends[1].gameObject.transform.position); var temp = Camera.main.ScreenToWorldPoint(Input.mousePosition); temp.z = 1f; line1.SetPosition(1, temp); } if (Input.GetMouseButtonUp(0)) { if (vine != null) { CameraPanningScript.Enable(); //show the vine vine.gameObject.GetComponent<SpriteRenderer>().enabled = true; //turn collisions on again vine.colliderOnAgainTime = Time.time + .5f; //destroy the lines GameObject.Destroy(line1); line1 = null; Vector3 dir = vine.gameObject.transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition); OnDragRelease(dir); //Debug.Log ("Releasing vine: " + vine.gameObject.name + " at dir: " + dir); vine = null; } } if (dragging && vine != null) { var mP = ClickToDrag.GetCursorWorldLocation(); var pp1 = vine.ends[0].gameObject.transform.position; var pp2 = vine.ends[1].gameObject.transform.position; for (int i = 0; i < vine.seedizens.Count; ++i) { var seedizen = vine.seedizens[i]; if (seedizen == null || seedizen.gameObject == null) { continue; } if (i >= vinePercentagePositions.Count) { Debug.Log("The system of coordinating positions on lists stored on multiple classes has failed!!! Consider storing this data on the seedizens"); continue; } var perc = vinePercentagePositions[i]; if (perc < clickStartPercentage) { var halfPer = perc / clickStartPercentage; //Debug.Log ("proportional percentage: "+halfPer); seedizen.transform.position = halfPer * (mP - pp1) + pp1; } else { var halfPer = (perc - clickStartPercentage) / (1 - clickStartPercentage); //Debug.Log ("proportional percentage past cursor: "+halfPer); seedizen.transform.position = halfPer * (pp2 - mP) + mP; } } UpdateFlingArrow(); } } public static void StartVineDrag(VineComponent vc) { CameraPanningScript.Disable(); vine = vc; dragging = true; clickStartPosition = ClickToDrag.GetCursorWorldLocation(); //var sph = GameObject.CreatePrimitive (PrimitiveType.Sphere); //sph.transform.position = clickStartPosition; startDragPositions.Clear(); vinePercentagePositions.Clear(); releasePositions.Clear(); var vineVector = vine.ends[1].gameObject.transform.position - vine.ends[0].gameObject.transform.position; clickStartPercentage = (clickStartPosition - vine.ends[0].gameObject.transform.position).magnitude / vineVector.magnitude; //Debug.Log ("click percentage: " + clickStartPercentage); foreach (var seedizen in vine.seedizens) { if (seedizen == null || seedizen.gameObject == null) { Debug.Log("null seedizen"); continue; } seedizen.inTransit = false; startDragPositions.Add(seedizen.transform.position); vinePercentagePositions.Add((seedizen.transform.position - vine.ends[0].gameObject.transform.position).magnitude / vineVector.magnitude); } //create some lines var l1 = GameObject.Instantiate(instance.linePrefab) as GameObject; line1 = l1.GetComponent<LineRenderer>(); //hide the vine vc.gameObject.GetComponent<SpriteRenderer>().enabled = false; //turn off collisions vc.gameObject.GetComponent<Collider2D>().enabled = false; MakeFlingArrow(); } void OnDragRelease(Vector3 dir) { releasePositions.Clear(); // clickStopPosition = ClickToDrag.GetCursorWorldLocation(); List<SeedizenComponent> seedizensCopy = new List<SeedizenComponent>(vine.seedizens); for (int i = 0; i < seedizensCopy.Count; i++) { var seedizen = seedizensCopy[i]; if (seedizen == null || seedizen.gameObject == null) { Debug.Log("Null seedizen"); continue; } releasePositions.Add(seedizen.transform.position); //debugSphere1.transform.position=releasePositions[i]; //debugSphere2.transform.position=startDragPositions[i]; seedizen.temporarilyDisableCollider(1.0f); if (i >= startDragPositions.Count || i >= releasePositions.Count) { Debug.Log("The system of coordinating positions on lists stored on multiple classes has failed!!! Consider storing this data on the seedizens"); continue; } seedizen.StartFlight((startDragPositions[i] - releasePositions[i]));//still need to make the falloff for this greater than linear } vine.seedizens.Clear(); dragging = false; DestroyFlingArrow(); } static GameObject flingArrow; static void MakeFlingArrow() { flingArrow = GameObject.Instantiate(Resources.Load<GameObject>("FlingArrow")) as GameObject; flingArrow.transform.position = clickStartPosition; UpdateFlingArrow(); } static void UpdateFlingArrow() { if (flingArrow == null) { Debug.Log("Fling arrow is null"); return; } //also clickStartPosition Vector3 pos = ClickToDrag.GetCursorWorldLocation(); Vector3 differenceVector = clickStartPosition - pos; float angle = Mathf.Atan2(differenceVector.y, differenceVector.x) * Mathf.Rad2Deg - 90f; flingArrow.transform.rotation = Quaternion.Euler(0, 0, angle); flingArrow.transform.localScale = Vector3.one * (differenceVector.magnitude / 4f); } static void DestroyFlingArrow() { GameObject.Destroy(flingArrow); } public void VineCut() { if (vineCut == true) { vineCut = false; } else { vineCut = true; } } }