context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.Text; using NLog.Config; using NLog.Internal; /// <summary> /// A specialized layout that renders XML-formatted events. /// </summary> [ThreadAgnostic] public abstract class XmlElementBase : Layout { private const string DefaultPropertyName = "property"; private const string DefaultPropertyKeyAttribute = "key"; private const string DefaultCollectionItemName = "item"; /// <summary> /// Initializes a new instance of the <see cref="XmlElementBase"/> class. /// </summary> /// <param name="elementName">The name of the top XML node</param> /// <param name="elementValue">The value of the top XML node</param> protected XmlElementBase(string elementName, Layout elementValue) { ElementNameInternal = elementName; LayoutWrapper.Inner = elementValue; Attributes = new List<XmlAttribute>(); Elements = new List<XmlElement>(); ExcludeProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Name of the XML element /// </summary> /// <remarks>Upgrade to private protected when using C# 7.2 </remarks> /// <docgen category='XML Options' order='10' /> internal string ElementNameInternal { get => _elementName; set => _elementName = XmlHelper.XmlConvertToElementName(value?.Trim()); } private string _elementName; /// <summary> /// Value inside the XML element /// </summary> /// <remarks>Upgrade to private protected when using C# 7.2 </remarks> /// <docgen category='XML Options' order='10' /> internal readonly LayoutRenderers.Wrappers.XmlEncodeLayoutRendererWrapper LayoutWrapper = new LayoutRenderers.Wrappers.XmlEncodeLayoutRendererWrapper(); /// <summary> /// Auto indent and create new lines /// </summary> /// <docgen category='XML Options' order='10' /> public bool IndentXml { get; set; } /// <summary> /// Gets the array of xml 'elements' configurations. /// </summary> /// <docgen category='XML Options' order='10' /> [ArrayParameter(typeof(XmlElement), "element")] public IList<XmlElement> Elements { get; private set; } /// <summary> /// Gets the array of 'attributes' configurations for the element /// </summary> /// <docgen category='XML Options' order='10' /> [ArrayParameter(typeof(XmlAttribute), "attribute")] public IList<XmlAttribute> Attributes { get; private set; } /// <summary> /// Gets or sets whether a ElementValue with empty value should be included in the output /// </summary> /// <docgen category='XML Options' order='10' /> public bool IncludeEmptyValue { get; set; } /// <summary> /// Gets or sets the option to include all properties from the log event (as XML) /// </summary> /// <docgen category='JSON Output' order='10' /> public bool IncludeEventProperties { get; set; } /// <summary> /// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeScopeProperties { get => _includeScopeProperties ?? (_includeMdlc == true || _includeMdc == true); set => _includeScopeProperties = value; } private bool? _includeScopeProperties; /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='LogEvent Properties XML Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdc { get => _includeMdc ?? false; set => _includeMdc = value; } private bool? _includeMdc; /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary. /// </summary> /// <docgen category='LogEvent Properties XML Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdlc { get => _includeMdlc ?? false; set => _includeMdlc = value; } private bool? _includeMdlc; /// <summary> /// Gets or sets the option to include all properties from the log event (as XML) /// </summary> /// <docgen category='LogEvent Properties XML Options' order='10' /> [Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")] public bool IncludeAllProperties { get => IncludeEventProperties; set => IncludeEventProperties = value; } /// <summary> /// List of property names to exclude when <see cref="IncludeAllProperties"/> is true /// </summary> /// <docgen category='LogEvent Properties XML Options' order='10' /> #if !NET35 public ISet<string> ExcludeProperties { get; set; } #else public HashSet<string> ExcludeProperties { get; set; } #endif /// <summary> /// XML element name to use when rendering properties /// </summary> /// <remarks> /// Support string-format where {0} means property-key-name /// /// Skips closing element tag when having configured <see cref="PropertiesElementValueAttribute"/> /// </remarks> /// <docgen category='LogEvent Properties XML Options' order='10' /> public string PropertiesElementName { get => _propertiesElementName; set { _propertiesElementName = value; _propertiesElementNameHasFormat = value?.IndexOf('{') >= 0; if (!_propertiesElementNameHasFormat) _propertiesElementName = XmlHelper.XmlConvertToElementName(value?.Trim()); } } private string _propertiesElementName = DefaultPropertyName; private bool _propertiesElementNameHasFormat; /// <summary> /// XML attribute name to use when rendering property-key /// /// When null (or empty) then key-attribute is not included /// </summary> /// <remarks> /// Will replace newlines in attribute-value with &#13;&#10; /// </remarks> /// <docgen category='LogEvent Properties XML Options' order='10' /> public string PropertiesElementKeyAttribute { get; set; } = DefaultPropertyKeyAttribute; /// <summary> /// XML attribute name to use when rendering property-value /// /// When null (or empty) then value-attribute is not included and /// value is formatted as XML-element-value /// </summary> /// <remarks> /// Skips closing element tag when using attribute for value /// /// Will replace newlines in attribute-value with &#13;&#10; /// </remarks> /// <docgen category='LogEvent Properties XML Options' order='10' /> public string PropertiesElementValueAttribute { get; set; } /// <summary> /// XML element name to use for rendering IList-collections items /// </summary> /// <docgen category='LogEvent Properties XML Options' order='10' /> public string PropertiesCollectionItemName { get; set; } = DefaultCollectionItemName; /// <summary> /// How far should the XML serializer follow object references before backing off /// </summary> /// <docgen category='LogEvent Properties XML Options' order='10' /> public int MaxRecursionLimit { get; set; } = 1; private ObjectReflectionCache ObjectReflectionCache => _objectReflectionCache ?? (_objectReflectionCache = new ObjectReflectionCache(LoggingConfiguration.GetServiceProvider())); private ObjectReflectionCache _objectReflectionCache; private static readonly IEqualityComparer<object> _referenceEqualsComparer = SingleItemOptimizedHashSet<object>.ReferenceEqualityComparer.Default; private const int MaxXmlLength = 512 * 1024; /// <inheritdoc/> protected override void InitializeLayout() { base.InitializeLayout(); if (IncludeScopeProperties) ThreadAgnostic = false; if (IncludeEventProperties) MutableUnsafe = true; if (Attributes.Count > 1) { HashSet<string> attributeValidator = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var attribute in Attributes) { if (string.IsNullOrEmpty(attribute.Name)) { Common.InternalLogger.Warn("XmlElement(ElementName={0}): Contains attribute with missing name (Ignored)"); } else if (attributeValidator.Contains(attribute.Name)) { Common.InternalLogger.Warn("XmlElement(ElementName={0}): Contains duplicate attribute name: {1} (Invalid xml)", ElementNameInternal, attribute.Name); } else { attributeValidator.Add(attribute.Name); } } } } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target); } /// <inheritdoc/> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { int orgLength = target.Length; RenderXmlFormattedMessage(logEvent, target); if (target.Length == orgLength && IncludeEmptyValue && !string.IsNullOrEmpty(ElementNameInternal)) { RenderSelfClosingElement(target, ElementNameInternal); } } /// <inheritdoc/> protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } private void RenderXmlFormattedMessage(LogEventInfo logEvent, StringBuilder sb) { int orgLength = sb.Length; // Attributes without element-names should be added to the top XML element if (!string.IsNullOrEmpty(ElementNameInternal)) { for (int i = 0; i < Attributes.Count; i++) { var attribute = Attributes[i]; int beforeAttributeLength = sb.Length; if (!RenderAppendXmlAttributeValue(attribute, logEvent, sb, sb.Length == orgLength)) { sb.Length = beforeAttributeLength; } } if (sb.Length != orgLength) { bool hasElements = HasNestedXmlElements(logEvent); if (!hasElements) { sb.Append("/>"); return; } else { sb.Append('>'); } } if (LayoutWrapper.Inner != null) { int beforeElementLength = sb.Length; if (sb.Length == orgLength) { RenderStartElement(sb, ElementNameInternal); } int beforeValueLength = sb.Length; LayoutWrapper.RenderAppendBuilder(logEvent, sb); if (beforeValueLength == sb.Length && !IncludeEmptyValue) { sb.Length = beforeElementLength; } } if (IndentXml && sb.Length != orgLength) sb.AppendLine(); } //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < Elements.Count; i++) { var element = Elements[i]; int beforeAttributeLength = sb.Length; if (!RenderAppendXmlElementValue(element, logEvent, sb, sb.Length == orgLength)) { sb.Length = beforeAttributeLength; } } AppendLogEventXmlProperties(logEvent, sb, orgLength); if (sb.Length > orgLength && !string.IsNullOrEmpty(ElementNameInternal)) { EndXmlDocument(sb, ElementNameInternal); } } private bool HasNestedXmlElements(LogEventInfo logEvent) { if (LayoutWrapper.Inner != null) return true; if (Elements.Count > 0) return true; if (IncludeScopeProperties) return true; if (IncludeEventProperties && logEvent.HasProperties) return true; return false; } private void AppendLogEventXmlProperties(LogEventInfo logEventInfo, StringBuilder sb, int orgLength) { if (IncludeScopeProperties) { using (var scopeEnumerator = ScopeContext.GetAllPropertiesEnumerator()) { while (scopeEnumerator.MoveNext()) { var scopeProperty = scopeEnumerator.Current; if (string.IsNullOrEmpty(scopeProperty.Key)) continue; if (ExcludeProperties.Contains(scopeProperty.Key)) continue; AppendXmlPropertyValue(scopeProperty.Key, scopeProperty.Value, sb, orgLength); } } } if (IncludeEventProperties && logEventInfo.HasProperties) { AppendLogEventProperties(logEventInfo, sb, orgLength); } } private void AppendLogEventProperties(LogEventInfo logEventInfo, StringBuilder sb, int orgLength) { IEnumerable<MessageTemplates.MessageTemplateParameter> propertiesList = logEventInfo.CreateOrUpdatePropertiesInternal(true); foreach (var prop in propertiesList) { if (string.IsNullOrEmpty(prop.Name)) continue; if (ExcludeProperties.Contains(prop.Name)) continue; var propertyValue = prop.Value; if (!string.IsNullOrEmpty(prop.Format) && propertyValue is IFormattable formattedProperty) propertyValue = formattedProperty.ToString(prop.Format, logEventInfo.FormatProvider ?? LoggingConfiguration?.DefaultCultureInfo); else if (prop.CaptureType == MessageTemplates.CaptureType.Stringify) propertyValue = Convert.ToString(prop.Value ?? string.Empty, logEventInfo.FormatProvider ?? LoggingConfiguration?.DefaultCultureInfo); AppendXmlPropertyObjectValue(prop.Name, propertyValue, sb, orgLength, default(SingleItemOptimizedHashSet<object>), 0); } } private bool AppendXmlPropertyObjectValue(string propName, object propertyValue, StringBuilder sb, int orgLength, SingleItemOptimizedHashSet<object> objectsInPath, int depth, bool ignorePropertiesElementName = false) { var convertibleValue = propertyValue as IConvertible; var objTypeCode = convertibleValue?.GetTypeCode() ?? (propertyValue is null ? TypeCode.Empty : TypeCode.Object); if (objTypeCode != TypeCode.Object) { string xmlValueString = XmlHelper.XmlConvertToString(convertibleValue, objTypeCode, true); AppendXmlPropertyStringValue(propName, xmlValueString, sb, orgLength, false, ignorePropertiesElementName); } else { int beforeValueLength = sb.Length; if (beforeValueLength > MaxXmlLength) { return false; } int nextDepth = objectsInPath.Count == 0 ? depth : (depth + 1); // Allow serialization of list-items if (nextDepth > MaxRecursionLimit) { return false; } if (objectsInPath.Contains(propertyValue)) { return false; } if (propertyValue is System.Collections.IDictionary dict) { using (StartCollectionScope(ref objectsInPath, dict)) { AppendXmlDictionaryObject(propName, dict, sb, orgLength, objectsInPath, nextDepth, ignorePropertiesElementName); } } else if (propertyValue is System.Collections.IEnumerable collection) { if (ObjectReflectionCache.TryLookupExpandoObject(propertyValue, out var propertyValues)) { using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(propertyValue, ref objectsInPath, false, _referenceEqualsComparer)) { AppendXmlObjectPropertyValues(propName, ref propertyValues, sb, orgLength, ref objectsInPath, nextDepth, ignorePropertiesElementName); } } else { using (StartCollectionScope(ref objectsInPath, collection)) { AppendXmlCollectionObject(propName, collection, sb, orgLength, objectsInPath, nextDepth, ignorePropertiesElementName); } } } else { using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(propertyValue, ref objectsInPath, false, _referenceEqualsComparer)) { var propertyValues = ObjectReflectionCache.LookupObjectProperties(propertyValue); AppendXmlObjectPropertyValues(propName, ref propertyValues, sb, orgLength, ref objectsInPath, nextDepth, ignorePropertiesElementName); } } } return true; } private static SingleItemOptimizedHashSet<object>.SingleItemScopedInsert StartCollectionScope(ref SingleItemOptimizedHashSet<object> objectsInPath, object value) { return new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(value, ref objectsInPath, true, _referenceEqualsComparer); } private void AppendXmlCollectionObject(string propName, System.Collections.IEnumerable collection, StringBuilder sb, int orgLength, SingleItemOptimizedHashSet<object> objectsInPath, int depth, bool ignorePropertiesElementName) { string propNameElement = AppendXmlPropertyValue(propName, string.Empty, sb, orgLength, true); if (!string.IsNullOrEmpty(propNameElement)) { foreach (var item in collection) { int beforeValueLength = sb.Length; if (beforeValueLength > MaxXmlLength) break; if (!AppendXmlPropertyObjectValue(PropertiesCollectionItemName, item, sb, orgLength, objectsInPath, depth, true)) { sb.Length = beforeValueLength; } } AppendClosingPropertyTag(propNameElement, sb, ignorePropertiesElementName); } } private void AppendXmlDictionaryObject(string propName, System.Collections.IDictionary dictionary, StringBuilder sb, int orgLength, SingleItemOptimizedHashSet<object> objectsInPath, int depth, bool ignorePropertiesElementName) { string propNameElement = AppendXmlPropertyValue(propName, string.Empty, sb, orgLength, true, ignorePropertiesElementName); if (!string.IsNullOrEmpty(propNameElement)) { foreach (var item in new DictionaryEntryEnumerable(dictionary)) { int beforeValueLength = sb.Length; if (beforeValueLength > MaxXmlLength) break; if (!AppendXmlPropertyObjectValue(item.Key?.ToString(), item.Value, sb, orgLength, objectsInPath, depth)) { sb.Length = beforeValueLength; } } AppendClosingPropertyTag(propNameElement, sb, ignorePropertiesElementName); } } private void AppendXmlObjectPropertyValues(string propName, ref ObjectReflectionCache.ObjectPropertyList propertyValues, StringBuilder sb, int orgLength, ref SingleItemOptimizedHashSet<object> objectsInPath, int depth, bool ignorePropertiesElementName = false) { if (propertyValues.IsSimpleValue) { AppendXmlPropertyValue(propName, propertyValues.ObjectValue, sb, orgLength, false, ignorePropertiesElementName); } else { string propNameElement = AppendXmlPropertyValue(propName, string.Empty, sb, orgLength, true, ignorePropertiesElementName); if (!string.IsNullOrEmpty(propNameElement)) { foreach (var property in propertyValues) { int beforeValueLength = sb.Length; if (beforeValueLength > MaxXmlLength) break; if (!property.HasNameAndValue) continue; var propertyTypeCode = property.TypeCode; if (propertyTypeCode != TypeCode.Object) { string xmlValueString = XmlHelper.XmlConvertToString((IConvertible)property.Value, propertyTypeCode, true); AppendXmlPropertyStringValue(property.Name, xmlValueString, sb, orgLength, false, ignorePropertiesElementName); } else { if (!AppendXmlPropertyObjectValue(property.Name, property.Value, sb, orgLength, objectsInPath, depth)) { sb.Length = beforeValueLength; } } } AppendClosingPropertyTag(propNameElement, sb, ignorePropertiesElementName); } } } private string AppendXmlPropertyValue(string propName, object propertyValue, StringBuilder sb, int orgLength, bool ignoreValue = false, bool ignorePropertiesElementName = false) { string xmlValueString = ignoreValue ? string.Empty : XmlHelper.XmlConvertToStringSafe(propertyValue); return AppendXmlPropertyStringValue(propName, xmlValueString, sb, orgLength, ignoreValue, ignorePropertiesElementName); } private string AppendXmlPropertyStringValue(string propName, string xmlValueString, StringBuilder sb, int orgLength, bool ignoreValue = false, bool ignorePropertiesElementName = false) { if (string.IsNullOrEmpty(PropertiesElementName)) return string.Empty; // Not supported propName = propName?.Trim(); if (string.IsNullOrEmpty(propName)) return string.Empty; // Not supported if (sb.Length == orgLength && !string.IsNullOrEmpty(ElementNameInternal)) { BeginXmlDocument(sb, ElementNameInternal); } if (IndentXml && !string.IsNullOrEmpty(ElementNameInternal)) sb.Append(" "); sb.Append('<'); string propNameElement; if (ignorePropertiesElementName) { propNameElement = XmlHelper.XmlConvertToElementName(propName); sb.Append(propNameElement); } else { if (_propertiesElementNameHasFormat) { propNameElement = XmlHelper.XmlConvertToElementName(propName); sb.AppendFormat(PropertiesElementName, propNameElement); } else { propNameElement = PropertiesElementName; sb.Append(PropertiesElementName); } RenderAttribute(sb, PropertiesElementKeyAttribute, propName); } if (!ignoreValue) { if (RenderAttribute(sb, PropertiesElementValueAttribute, xmlValueString)) { sb.Append("/>"); if (IndentXml) sb.AppendLine(); } else { sb.Append('>'); XmlHelper.EscapeXmlString(xmlValueString, false, sb); AppendClosingPropertyTag(propNameElement, sb, ignorePropertiesElementName); } } else { sb.Append('>'); if (IndentXml) sb.AppendLine(); } return propNameElement; } private void AppendClosingPropertyTag(string propNameElement, StringBuilder sb, bool ignorePropertiesElementName = false) { sb.Append("</"); if (ignorePropertiesElementName) sb.Append(propNameElement); else sb.AppendFormat(PropertiesElementName, propNameElement); sb.Append('>'); if (IndentXml) sb.AppendLine(); } /// <summary> /// write attribute, only if <paramref name="attributeName"/> is not empty /// </summary> /// <param name="sb"></param> /// <param name="attributeName"></param> /// <param name="value"></param> /// <returns>rendered</returns> private static bool RenderAttribute(StringBuilder sb, string attributeName, string value) { if (!string.IsNullOrEmpty(attributeName)) { sb.Append(' '); sb.Append(attributeName); sb.Append("=\""); XmlHelper.EscapeXmlString(value, true, sb); sb.Append('\"'); return true; } return false; } private bool RenderAppendXmlElementValue(XmlElementBase xmlElement, LogEventInfo logEvent, StringBuilder sb, bool beginXmlDocument) { string xmlElementName = xmlElement.ElementNameInternal; if (string.IsNullOrEmpty(xmlElementName)) return false; if (beginXmlDocument && !string.IsNullOrEmpty(ElementNameInternal)) { BeginXmlDocument(sb, ElementNameInternal); } if (IndentXml && !string.IsNullOrEmpty(ElementNameInternal)) sb.Append(" "); int beforeValueLength = sb.Length; xmlElement.Render(logEvent, sb); if (sb.Length == beforeValueLength && !xmlElement.IncludeEmptyValue) return false; if (IndentXml) sb.AppendLine(); return true; } private bool RenderAppendXmlAttributeValue(XmlAttribute xmlAttribute, LogEventInfo logEvent, StringBuilder sb, bool beginXmlDocument) { string xmlKeyString = xmlAttribute.Name; if (string.IsNullOrEmpty(xmlKeyString)) return false; if (beginXmlDocument) { sb.Append('<'); sb.Append(ElementNameInternal); } sb.Append(' '); sb.Append(xmlKeyString); sb.Append("=\""); if (!xmlAttribute.RenderAppendXmlValue(logEvent, sb)) return false; sb.Append('\"'); return true; } private void BeginXmlDocument(StringBuilder sb, string elementName) { RenderStartElement(sb, elementName); if (IndentXml) sb.AppendLine(); } private void EndXmlDocument(StringBuilder sb, string elementName) { RenderEndElement(sb, elementName); } /// <inheritdoc/> public override string ToString() { if (Elements.Count > 0) return ToStringWithNestedItems(Elements, l => l.ToString()); else if (Attributes.Count > 0) return ToStringWithNestedItems(Attributes, a => "Attributes:" + a.Name); else if (ElementNameInternal != null) return ToStringWithNestedItems(new[] { this }, n => "Element:" + n.ElementNameInternal); else return GetType().Name; } private static void RenderSelfClosingElement(StringBuilder target, string elementName) { target.Append('<'); target.Append(elementName); target.Append("/>"); } private static void RenderStartElement(StringBuilder sb, string elementName) { sb.Append('<'); sb.Append(elementName); sb.Append('>'); } private static void RenderEndElement(StringBuilder sb, string elementName) { sb.Append("</"); sb.Append(elementName); sb.Append('>'); } } }
/* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using UnityEngine.SocialPlatforms; using System.Collections; using System.Collections.Generic; using UnityEngine; using GooglePlayGames.BasicApi; using GooglePlayGames.OurUtils; using GooglePlayGames.BasicApi.Multiplayer; using GooglePlayGames.BasicApi.SavedGame; namespace GooglePlayGames { /// <summary> /// Provides access to the Google Play Games platform. This is an implementation of /// UnityEngine.SocialPlatforms.ISocialPlatform. Activate this platform by calling /// the <see cref="Activate" /> method, then authenticate by calling /// the <see cref="Authenticate" /> method. After authentication /// completes, you may call the other methods of this class. This is not a complete /// implementation of the ISocialPlatform interface. Methods lacking an implementation /// or whose behavior is at variance with the standard are noted as such. /// </summary> public class PlayGamesPlatform : ISocialPlatform { private static volatile PlayGamesPlatform sInstance = null; private readonly PlayGamesClientConfiguration mConfiguration; private PlayGamesLocalUser mLocalUser = null; private IPlayGamesClient mClient = null; // the default leaderboard we show on ShowLeaderboardUI private string mDefaultLbUi = null; // achievement/leaderboard ID mapping table private Dictionary<string, string> mIdMap = new Dictionary<string, string>(); private PlayGamesPlatform(PlayGamesClientConfiguration configuration) { this.mLocalUser = new PlayGamesLocalUser(this); this.mConfiguration = configuration; } internal PlayGamesPlatform(IPlayGamesClient client) { this.mClient = Misc.CheckNotNull(client); this.mLocalUser = new PlayGamesLocalUser(this); this.mConfiguration = PlayGamesClientConfiguration.DefaultConfiguration; } public static void InitializeInstance(PlayGamesClientConfiguration configuration) { if (sInstance != null) { Logger.w("PlayGamesPlatform already initialized. Ignoring this call."); return; } sInstance = new PlayGamesPlatform(configuration); } /// <summary> /// Gets the singleton instance of the Play Games platform. /// </summary> /// <returns> /// The instance. /// </returns> public static PlayGamesPlatform Instance { get { if (sInstance == null) { Logger.d("Instance was not initialized, using default configuration."); InitializeInstance(PlayGamesClientConfiguration.DefaultConfiguration); } return sInstance; } } /// <summary> /// Gets or sets a value indicating whether debug logs are enabled. This property /// may be set before calling <see cref="Activate" /> method. /// </summary> /// <returns> /// <c>true</c> if debug log enabled; otherwise, <c>false</c>. /// </returns> public static bool DebugLogEnabled { get { return Logger.DebugLogEnabled; } set { Logger.DebugLogEnabled = value; } } /// Gets the real time multiplayer API object public IRealTimeMultiplayerClient RealTime { get { return mClient.GetRtmpClient(); } } /// Gets the turn based multiplayer API object public ITurnBasedMultiplayerClient TurnBased { get { return mClient.GetTbmpClient(); } } public ISavedGameClient SavedGame { get { return mClient.GetSavedGameClient(); } } /// <summary> /// Activates the Play Games platform as the implementation of Social.Active. /// After calling this method, you can call methods on Social.Active. For /// example, <c>Social.Active.Authenticate()</c>. /// </summary> /// <returns>The singleton <see cref="PlayGamesPlatform" /> instance.</returns> public static PlayGamesPlatform Activate() { Logger.d("Activating PlayGamesPlatform."); Social.Active = PlayGamesPlatform.Instance; Logger.d("PlayGamesPlatform activated: " + Social.Active); return PlayGamesPlatform.Instance; } /// <summary> /// Specifies that the ID <c>fromId</c> should be implicitly replaced by <c>toId</c> /// on any calls that take a leaderboard or achievement ID. After a mapping is /// registered, you can use <c>fromId</c> instead of <c>toId</c> when making a call. /// For example, the following two snippets are equivalent: /// /// <code> /// ReportProgress("Cfiwjew894_AQ", 100.0, callback); /// </code> /// ...is equivalent to: /// <code> /// AddIdMapping("super-combo", "Cfiwjew894_AQ"); /// ReportProgress("super-combo", 100.0, callback); /// </code> /// /// </summary> /// <param name='fromId'> /// The identifier to map. /// </param> /// <param name='toId'> /// The identifier that <c>fromId</c> will be mapped to. /// </param> public void AddIdMapping(string fromId, string toId) { mIdMap[fromId] = toId; } /// <summary> /// Authenticate the local user with the Google Play Games service. /// </summary> /// <param name='callback'> /// The callback to call when authentication finishes. It will be called /// with <c>true</c> if authentication was successful, <c>false</c> /// otherwise. /// </param> public void Authenticate(Action<bool> callback) { Authenticate(callback, false); } /// <summary> /// Authenticate the local user with the Google Play Games service. /// </summary> /// <param name='callback'> /// The callback to call when authentication finishes. It will be called /// with <c>true</c> if authentication was successful, <c>false</c> /// otherwise. /// </param> /// <param name='silent'> /// Indicates whether authentication should be silent. If <c>false</c>, /// authentication may show popups and interact with the user to obtain /// authorization. If <c>true</c>, there will be no popups or interaction with /// the user, and the authentication will fail instead if such interaction /// is required. A typical pattern is to try silent authentication on startup /// and, if that fails, present the user with a "Sign in" button that then /// triggers normal (not silent) authentication. /// </param> public void Authenticate(Action<bool> callback, bool silent) { // make a platform-specific Play Games client if (mClient == null) { Logger.d("Creating platform-specific Play Games client."); mClient = PlayGamesClientFactory.GetPlatformPlayGamesClient(mConfiguration); } // authenticate! mClient.Authenticate(callback, silent); } /// <summary> /// Same as <see cref="Authenticate(Action<bool>,bool)"/>. Provided for compatibility /// with ISocialPlatform. /// </summary> /// <param name="unused">Unused.</param> /// <param name="callback">Callback.</param> public void Authenticate(ILocalUser unused, Action<bool> callback) { Authenticate(callback, false); } /// <summary> /// Determines whether the user is authenticated. /// </summary> /// <returns> /// <c>true</c> if the user is authenticated; otherwise, <c>false</c>. /// </returns> public bool IsAuthenticated() { return mClient != null && mClient.IsAuthenticated(); } /// Sign out. After signing out, Authenticate must be called again to sign back in. public void SignOut() { if (mClient != null) { mClient.SignOut(); } } /// <summary> /// Not implemented yet. Calls the callback with an empty list. /// </summary> public void LoadUsers(string[] userIDs, Action<IUserProfile[]> callback) { Logger.w("PlayGamesPlatform.LoadUsers is not implemented."); if (callback != null) { callback.Invoke(new IUserProfile[0]); } } /// <summary> /// Returns the user's Google ID. /// </summary> /// <returns> /// The user's Google ID. No guarantees are made as to the meaning or format of /// this identifier except that it is unique to the user who is signed in. /// </returns> public string GetUserId() { if (!IsAuthenticated()) { Logger.e("GetUserId() can only be called after authentication."); return "0"; } return mClient.GetUserId(); } /// <summary> /// Returns the user's display name. /// </summary> /// <returns> /// The user display name (e.g. "Bruno Oliveira") /// </returns> public string GetUserDisplayName() { if (!IsAuthenticated()) { Logger.e("GetUserDisplayName can only be called after authentication."); return ""; } return mClient.GetUserDisplayName(); } /// <summary> /// Returns the user's avatar URL if they have one. /// </summary> /// <returns> /// The URL, or <code>null</code> if the user is not authenticated or does not have /// an avatar. /// </returns> public string GetUserImageUrl() { if (!IsAuthenticated()) { Logger.e("GetUserImageUrl can only be called after authentication."); return null; } return mClient.GetUserImageUrl(); } /// <summary> /// Reports the progress of an achievement (reveal, unlock or increment). This method attempts /// to implement the expected behavior of ISocialPlatform.ReportProgress as closely as possible, /// as described below. Although this method works with incremental achievements for compatibility /// purposes, calling this method for incremental achievements is not recommended, /// since the Play Games API exposes incremental achievements in a very different way /// than the interface presented by ISocialPlatform.ReportProgress. The implementation of this /// method for incremental achievements attempts to produce the correct result, but may be /// imprecise. If possible, call <see cref="IncrementAchievement" /> instead. /// </summary> /// <param name='achievementID'> /// The ID of the achievement to unlock, reveal or increment. This can be a raw Google Play /// Games achievement ID (alphanumeric string), or an alias that was previously configured /// by a call to <see cref="AddIdMapping" />. /// </param> /// <param name='progress'> /// Progress of the achievement. If the achievement is standard (not incremental), then /// a progress of 0.0 will reveal the achievement and 100.0 will unlock it. Behavior of other /// values is undefined. If the achievement is incremental, then this value is interpreted /// as the total percentage of the achievement's progress that the player should have /// as a result of this call (regardless of the progress they had before). So if the /// player's previous progress was 30% and this call specifies 50.0, the new progress will /// be 50% (not 80%). /// </param> /// <param name='callback'> /// Callback that will be called to report the result of the operation: <c>true</c> on /// success, <c>false</c> otherwise. /// </param> public void ReportProgress(string achievementID, double progress, Action<bool> callback) { if (!IsAuthenticated()) { Logger.e("ReportProgress can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } // map ID, if it's in the dictionary Logger.d("ReportProgress, " + achievementID + ", " + progress); achievementID = MapId(achievementID); // if progress is 0.0, we just want to reveal it if (progress < 0.000001) { Logger.d("Progress 0.00 interpreted as request to reveal."); mClient.RevealAchievement(achievementID, callback); return; } // figure out if it's a standard or incremental achievement bool isIncremental = false; int curSteps = 0, totalSteps = 0; Achievement ach = mClient.GetAchievement(achievementID); if (ach == null) { Logger.w("Unable to locate achievement " + achievementID); Logger.w("As a quick fix, assuming it's standard."); isIncremental = false; } else { isIncremental = ach.IsIncremental; curSteps = ach.CurrentSteps; totalSteps = ach.TotalSteps; Logger.d("Achievement is " + (isIncremental ? "INCREMENTAL" : "STANDARD")); if (isIncremental) { Logger.d("Current steps: " + curSteps + "/" + totalSteps); } } // do the right thing depending on the achievement type if (isIncremental) { // increment it to the target percentage (approximate) Logger.d("Progress " + progress + " interpreted as incremental target (approximate)."); if (progress >= 0.0 && progress <= 1.0) { // in a previous version, incremental progress was reported by using the range [0-1] Logger.w("Progress " + progress + " is less than or equal to 1. You might be trying to use values in the range of [0,1], while values are expected to be within the range [0,100]. If you are using the latter, you can safely ignore this message."); } int targetSteps = (int)((progress / 100) * totalSteps); int numSteps = targetSteps - curSteps; Logger.d("Target steps: " + targetSteps + ", cur steps:" + curSteps); Logger.d("Steps to increment: " + numSteps); if (numSteps > 0) { mClient.IncrementAchievement(achievementID, numSteps, callback); } } else if (progress >= 100) { // unlock it! Logger.d("Progress " + progress + " interpreted as UNLOCK."); mClient.UnlockAchievement(achievementID, callback); } else { // not enough to unlock Logger.d("Progress " + progress + " not enough to unlock non-incremental achievement."); } } /// <summary> /// Increments an achievement. This is a Play Games extension of the ISocialPlatform API. /// </summary> /// <param name='achievementID'> /// The ID of the achievement to increment. This can be a raw Google Play /// Games achievement ID (alphanumeric string), or an alias that was previously configured /// by a call to <see cref="AddIdMapping" />. /// </param> /// <param name='steps'> /// The number of steps to increment the achievement by. /// </param> /// <param name='callback'> /// The callback to call to report the success or failure of the operation. The callback /// will be called with <c>true</c> to indicate success or <c>false</c> for failure. /// </param> public void IncrementAchievement(string achievementID, int steps, Action<bool> callback) { if (!IsAuthenticated()) { Logger.e("IncrementAchievement can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } // map ID, if it's in the dictionary Logger.d("IncrementAchievement: " + achievementID + ", steps " + steps); achievementID = MapId(achievementID); mClient.IncrementAchievement(achievementID, steps, callback); } /// <summary> /// Not implemented yet. Calls the callback with an empty list. /// </summary> public void LoadAchievementDescriptions(Action<IAchievementDescription[]> callback) { Logger.w("PlayGamesPlatform.LoadAchievementDescriptions is not implemented."); if (callback != null) { callback.Invoke(new IAchievementDescription[0]); } } /// <summary> /// Not implemented yet. Calls the callback with an empty list. /// </summary> public void LoadAchievements(Action<IAchievement[]> callback) { Logger.w("PlayGamesPlatform.LoadAchievements is not implemented."); if (callback != null) { callback.Invoke(new IAchievement[0]); } } /// <summary> /// Creates an achievement object which may be subsequently used to report an /// achievement. /// </summary> /// <returns> /// The achievement object. /// </returns> public IAchievement CreateAchievement() { return new PlayGamesAchievement(); } /// <summary> /// Reports a score to a leaderboard. /// </summary> /// <param name='score'> /// The score to report. /// </param> /// <param name='board'> /// The ID of the leaderboard on which the score is to be posted. This may be a raw /// Google Play Games leaderboard ID or an alias configured through a call to /// <see cref="AddIdMapping" />. /// </param> /// <param name='callback'> /// The callback to call to report the success or failure of the operation. The callback /// will be called with <c>true</c> to indicate success or <c>false</c> for failure. /// </param> public void ReportScore(long score, string board, Action<bool> callback) { if (!IsAuthenticated()) { Logger.e("ReportScore can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } Logger.d("ReportScore: score=" + score + ", board=" + board); string lbId = MapId(board); mClient.SubmitScore(lbId, score, callback); } /// <summary> /// Not implemented yet. Calls the callback with an empty list. /// </summary> public void LoadScores(string leaderboardID, Action<IScore[]> callback) { Logger.w("PlayGamesPlatform.LoadScores not implemented."); if (callback != null) { callback.Invoke(new IScore[0]); } } /// <summary> /// Not implemented yet. Returns null; /// </summary> public ILeaderboard CreateLeaderboard() { Logger.w("PlayGamesPlatform.CreateLeaderboard not implemented. Returning null."); return null; } /// <summary> /// Shows the standard Google Play Games achievements user interface, /// which allows the player to browse their achievements. /// </summary> public void ShowAchievementsUI() { if (!IsAuthenticated()) { Logger.e("ShowAchievementsUI can only be called after authentication."); return; } Logger.d("ShowAchievementsUI"); mClient.ShowAchievementsUI(); } /// <summary> /// Shows the standard Google Play Games leaderboards user interface, /// which allows the player to browse their leaderboards. If you have /// configured a specific leaderboard as the default through a call to /// <see cref="SetDefaultLeaderboardForUi" />, the UI will show that /// specific leaderboard only. Otherwise, a list of all the leaderboards /// will be shown. /// </summary> public void ShowLeaderboardUI() { if (!IsAuthenticated()) { Logger.e("ShowLeaderboardUI can only be called after authentication."); return; } Logger.d("ShowLeaderboardUI"); mClient.ShowLeaderboardUI(MapId(mDefaultLbUi)); } /// <summary> /// Shows the standard Google Play Games leaderboard UI for the given /// leaderboard. /// </summary> /// <param name='lbId'> /// The ID of the leaderboard to display. This may be a raw /// Google Play Games leaderboard ID or an alias configured through a call to /// <see cref="AddIdMapping" />. /// </param> public void ShowLeaderboardUI(string lbId) { if (!IsAuthenticated()) { Logger.e("ShowLeaderboardUI can only be called after authentication."); return; } Logger.d("ShowLeaderboardUI, lbId=" + lbId); if (lbId != null) { lbId = MapId(lbId); } mClient.ShowLeaderboardUI(lbId); } /// <summary> /// Sets the default leaderboard for the leaderboard UI. After calling this /// method, a call to <see cref="ShowLeaderboardUI" /> will show only the specified /// leaderboard instead of showing the list of all leaderboards. /// </summary> /// <param name='lbid'> /// The ID of the leaderboard to display on the default UI. This may be a raw /// Google Play Games leaderboard ID or an alias configured through a call to /// <see cref="AddIdMapping" />. /// </param> public void SetDefaultLeaderboardForUI(string lbid) { Logger.d("SetDefaultLeaderboardForUI: " + lbid); if (lbid != null) { lbid = MapId(lbid); } mDefaultLbUi = lbid; } /// <summary> /// Not implemented yet. Calls the callback with <c>false</c>. /// </summary> public void LoadFriends(ILocalUser user, Action<bool> callback) { Logger.w("PlayGamesPlatform.LoadFriends not implemented."); if (callback != null) { callback.Invoke(false); } } /// <summary> /// Not implemented yet. Calls the callback with <c>false</c>. /// </summary> public void LoadScores(ILeaderboard board, Action<bool> callback) { Logger.w("PlayGamesPlatform.LoadScores not implemented."); if (callback != null) { callback.Invoke(false); } } /// <summary> /// Not implemented yet. Returns false. /// </summary> public bool GetLoading(ILeaderboard board) { return false; } /// <summary> /// Loads app state (cloud save) data from the server. /// </summary> /// <param name='slot'> /// The app state slot number. The exact number of slots and their size can be seen /// in the Google Play Games documentation. Slot 0 is always available, and is at /// least 128K long. /// </param> /// <param name='callbacks'> /// The callbacks to call when the state is loaded, or when a conflict occurs. /// </param> public void LoadState(int slot, OnStateLoadedListener listener) { if (!IsAuthenticated()) { Logger.e("LoadState can only be called after authentication."); if (listener != null) { listener.OnStateLoaded(false, slot, null); } return; } mClient.LoadState(slot, listener); } /// <summary> /// Writes app state (cloud save) data to the server. /// </summary> /// <param name='slot'> /// The app state slot number. The exact number of slots and their size can be seen /// in the Google Play Games documentation. Slot 0 is always available, and is at /// least 128K long. /// </param> /// <param name='data'> /// The data to write. /// </param> public void UpdateState(int slot, byte[] data, OnStateLoadedListener listener) { if (!IsAuthenticated()) { Logger.e("UpdateState can only be called after authentication."); if (listener != null) { listener.OnStateSaved(false, slot); } return; } mClient.UpdateState(slot, data, listener); } /// <summary> /// Gets the local user. /// </summary> /// <returns> /// The local user. /// </returns> public ILocalUser localUser { get { return mLocalUser; } } /// Register an invitation delegate to be notified when a multiplayer invitation arrives public void RegisterInvitationDelegate(BasicApi.InvitationReceivedDelegate deleg) { mClient.RegisterInvitationDelegate(deleg); } private string MapId(string id) { if (id == null) { return null; } if (mIdMap.ContainsKey(id)) { string result = mIdMap[id]; Logger.d("Mapping alias " + id + " to ID " + result); return result; } return id; } } }
#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 namespace PdfSharp.Charting { /// <summary> /// Represents charts with different types. /// </summary> public class Chart : DocumentObject { /// <summary> /// Initializes a new instance of the Chart class. /// </summary> public Chart() { } /// <summary> /// Initializes a new instance of the Chart class with the specified parent. /// </summary> internal Chart(DocumentObject parent) : base(parent) { } /// <summary> /// Initializes a new instance of the Chart class with the specified chart type. /// </summary> public Chart(ChartType type) : this() { Type = type; } #region Methods /// <summary> /// Creates a deep copy of this object. /// </summary> public new Chart Clone() { return (Chart)DeepCopy(); } /// <summary> /// Implements the deep copy of the object. /// </summary> protected override object DeepCopy() { Chart chart = (Chart)base.DeepCopy(); if (chart._xAxis != null) { chart._xAxis = chart._xAxis.Clone(); chart._xAxis._parent = chart; } if (chart._yAxis != null) { chart._yAxis = chart._yAxis.Clone(); chart._yAxis._parent = chart; } if (chart._zAxis != null) { chart._zAxis = chart._zAxis.Clone(); chart._zAxis._parent = chart; } if (chart._seriesCollection != null) { chart._seriesCollection = chart._seriesCollection.Clone(); chart._seriesCollection._parent = chart; } if (chart._xValues != null) { chart._xValues = chart._xValues.Clone(); chart._xValues._parent = chart; } if (chart._plotArea != null) { chart._plotArea = chart._plotArea.Clone(); chart._plotArea._parent = chart; } if (chart._dataLabel != null) { chart._dataLabel = chart._dataLabel.Clone(); chart._dataLabel._parent = chart; } return chart; } /// <summary> /// Determines the type of the given axis. /// </summary> internal string CheckAxis(Axis axis) { if ((_xAxis != null) && (axis == _xAxis)) return "xaxis"; if ((_yAxis != null) && (axis == _yAxis)) return "yaxis"; if ((_zAxis != null) && (axis == _zAxis)) return "zaxis"; return ""; } #endregion #region Properties /// <summary> /// Gets or sets the base type of the chart. /// ChartType of the series can be overwritten. /// </summary> public ChartType Type { get { return _type; } set { _type = value; } } internal ChartType _type; /// <summary> /// Gets or sets the font for the chart. This will be the default font for all objects which are /// part of the chart. /// </summary> public Font Font { get { return _font ?? (_font = new Font(this)); } } internal Font _font; /// <summary> /// Gets the legend of the chart. /// </summary> public Legend Legend { get { return _legend ?? (_legend = new Legend(this)); } } internal Legend _legend; /// <summary> /// Gets the X-Axis of the Chart. /// </summary> public Axis XAxis { get { return _xAxis ?? (_xAxis = new Axis(this)); } } internal Axis _xAxis; /// <summary> /// Gets the Y-Axis of the Chart. /// </summary> public Axis YAxis { get { return _yAxis ?? (_yAxis = new Axis(this)); } } internal Axis _yAxis; /// <summary> /// Gets the Z-Axis of the Chart. /// </summary> public Axis ZAxis { get { return _zAxis ?? (_zAxis = new Axis(this)); } } internal Axis _zAxis; /// <summary> /// Gets the collection of the data series. /// </summary> public SeriesCollection SeriesCollection { get { return _seriesCollection ?? (_seriesCollection = new SeriesCollection(this)); } } internal SeriesCollection _seriesCollection; /// <summary> /// Gets the collection of the values written on the X-Axis. /// </summary> public XValues XValues { get { return _xValues ?? (_xValues = new XValues(this)); } } internal XValues _xValues; /// <summary> /// Gets the plot (drawing) area of the chart. /// </summary> public PlotArea PlotArea { get { return _plotArea ?? (_plotArea = new PlotArea(this)); } } internal PlotArea _plotArea; /// <summary> /// Gets or sets a value defining how blanks in the data series should be shown. /// </summary> public BlankType DisplayBlanksAs { get { return _displayBlanksAs; } set { _displayBlanksAs = value; } } internal BlankType _displayBlanksAs; /// <summary> /// Gets the DataLabel of the chart. /// </summary> public DataLabel DataLabel { get { return _dataLabel ?? (_dataLabel = new DataLabel(this)); } } internal DataLabel _dataLabel; /// <summary> /// Gets or sets whether the chart has a DataLabel. /// </summary> public bool HasDataLabel { get { return _hasDataLabel; } set { _hasDataLabel = value; } } internal bool _hasDataLabel; #endregion } }
// // PlaybackRepeatActions.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using Mono.Unix; using Gtk; using Hyena; using Hyena.Gui; using Banshee.Configuration; using Banshee.ServiceStack; using Banshee.PlaybackController; namespace Banshee.Gui { public class PlaybackRepeatActions : BansheeActionGroup, IEnumerable<RadioAction> { private RadioAction active_action; private RadioAction saved_action; public RadioAction Active { get { return active_action; } set { active_action = value; ServiceManager.PlaybackController.RepeatMode = (PlaybackRepeatMode)active_action.Value; } } public new bool Sensitive { get { return base.Sensitive; } set { base.Sensitive = value; OnChanged (); } } public event EventHandler Changed; public PlaybackRepeatActions (InterfaceActionService actionService) : base (actionService, "PlaybackRepeat") { actionService.AddActionGroup (this); Add (new ActionEntry [] { new ActionEntry ("RepeatMenuAction", null, Catalog.GetString ("Repeat"), null, Catalog.GetString ("Repeat"), null) }); Add (new RadioActionEntry [] { new RadioActionEntry ("RepeatNoneAction", null, Catalog.GetString ("Repeat _Off"), null, Catalog.GetString ("Do not repeat playlist"), (int)PlaybackRepeatMode.None), new RadioActionEntry ("RepeatAllAction", null, Catalog.GetString ("Repeat _All"), null, Catalog.GetString ("Play all songs before repeating playlist"), (int)PlaybackRepeatMode.RepeatAll), new RadioActionEntry ("RepeatSingleAction", null, Catalog.GetString ("Repeat Singl_e"), null, Catalog.GetString ("Repeat the current playing song"), (int)PlaybackRepeatMode.RepeatSingle) }, 0, OnActionChanged); this["RepeatNoneAction"].IconName = "media-repeat-none"; this["RepeatAllAction"].IconName = "media-repeat-all"; this["RepeatSingleAction"].IconName = "media-repeat-single"; ServiceManager.PlaybackController.RepeatModeChanged += OnRepeatModeChanged; ServiceManager.PlaybackController.SourceChanged += OnPlaybackSourceChanged; Gtk.Action action = this[ConfigIdToActionName (RepeatMode.Get ())]; if (action is RadioAction) { active_action = (RadioAction)action; } else { Active = (RadioAction)this["RepeatNoneAction"]; } Active.Activate (); } private void OnRepeatModeChanged (object o, EventArgs<PlaybackRepeatMode> args) { if (active_action.Value != (int)args.Value) { // This happens only when changing the mode using DBus. // In this case we need to locate the action by its value. foreach (RadioAction action in this) { if (action.Value == (int)args.Value) { active_action = action; break; } } } if (saved_action == null) { RepeatMode.Set (ActionNameToConfigId (active_action.Name)); } OnChanged(); } private void OnPlaybackSourceChanged (object o, EventArgs args) { var source = ServiceManager.PlaybackController.Source; if (saved_action == null && !source.CanRepeat) { saved_action = Active; Active = this["RepeatNoneAction"] as RadioAction; Sensitive = false; } else if (saved_action != null && source.CanRepeat) { Active = saved_action; saved_action = null; Sensitive = true; } } private void OnActionChanged (object o, ChangedArgs args) { Active = args.Current; } private void OnChanged () { EventHandler handler = Changed; if (handler != null) { handler (this, EventArgs.Empty); } } public void AttachSubmenu (string menuItemPath) { MenuItem parent = Actions.UIManager.GetWidget (menuItemPath) as MenuItem; parent.Submenu = CreateMenu (); } public MenuItem CreateSubmenu () { MenuItem parent = (MenuItem)this["RepeatMenuAction"].CreateMenuItem (); parent.Submenu = CreateMenu (); return parent; } public Menu CreateMenu () { Menu menu = new Gtk.Menu (); bool separator = false; foreach (RadioAction action in this) { menu.Append (action.CreateMenuItem ()); if (!separator) { separator = true; menu.Append (new SeparatorMenuItem ()); } } menu.ShowAll (); return menu; } public IEnumerator<RadioAction> GetEnumerator () { yield return (RadioAction)this["RepeatNoneAction"]; yield return (RadioAction)this["RepeatAllAction"]; yield return (RadioAction)this["RepeatSingleAction"]; } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } private static string ConfigIdToActionName (string configuration) { return String.Format ("{0}Action", StringUtil.UnderCaseToCamelCase (configuration)); } private static string ActionNameToConfigId (string actionName) { return StringUtil.CamelCaseToUnderCase (actionName.Substring (0, actionName.Length - (actionName.EndsWith ("Action") ? 6 : 0))); } public static readonly SchemaEntry<string> RepeatMode = new SchemaEntry<string> ( "playback", "repeat_mode", "none", "Repeat playback", "Repeat mode (repeat_none, repeat_all, repeat_single)" ); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq.Expressions; using System.Reflection; using ALinq.Mapping; namespace ALinq.SqlClient { internal class SqlFactory { // Fields private readonly MetaModel model; private readonly ITypeSystemProvider typeProvider; // Methods internal SqlFactory(ITypeSystemProvider typeProvider, MetaModel model) { this.typeProvider = typeProvider; this.model = model; } internal SqlExpression Add(params SqlExpression[] expressions) { SqlExpression right = expressions[expressions.Length - 1]; for (int i = expressions.Length - 2; i >= 0; i--) { right = this.Binary(SqlNodeType.Add, expressions[i], right); } return right; } internal SqlExpression Add(SqlExpression expr, int second) { return this.Binary(SqlNodeType.Add, expr, this.ValueFromObject(second, false, expr.SourceExpression)); } internal SqlExpression AndAccumulate(SqlExpression left, SqlExpression right) { if (left == null) { return right; } if (right == null) { return left; } return this.Binary(SqlNodeType.And, left, right); } internal SqlBetween Between(SqlExpression expr, SqlExpression start, SqlExpression end, Expression source) { return new SqlBetween(typeof(bool), this.typeProvider.From(typeof(bool)), expr, start, end, source); } internal SqlBinary Binary(SqlNodeType nodeType, SqlExpression left, SqlExpression right) { return this.Binary(nodeType, left, right, null, null); } internal SqlBinary Binary(SqlNodeType nodeType, SqlExpression left, SqlExpression right, MethodInfo method) { return this.Binary(nodeType, left, right, method, null); } internal SqlBinary Binary(SqlNodeType nodeType, SqlExpression left, SqlExpression right, Type clrType) { return this.Binary(nodeType, left, right, null, clrType); } internal SqlBinary Binary(SqlNodeType nodeType, SqlExpression left, SqlExpression right, MethodInfo method, Type clrType) { IProviderType sqlType = null; if (nodeType.IsPredicateBinaryOperator()) { if (clrType == null) { clrType = typeof(bool); } sqlType = this.typeProvider.From(clrType); } else { IProviderType type2 = this.typeProvider.PredictTypeForBinary(nodeType, left.SqlType, right.SqlType); if (type2 == right.SqlType) { if (clrType == null) { clrType = right.ClrType; } sqlType = right.SqlType; } else if (type2 == left.SqlType) { if (clrType == null) { clrType = left.ClrType; } sqlType = left.SqlType; } else { sqlType = type2; if (clrType == null) { clrType = type2.GetClosestRuntimeType(); } } } return new SqlBinary(nodeType, clrType, sqlType, left, right, method); } internal SqlExpression Case(Type clrType, SqlExpression discriminator, List<SqlExpression> matches, List<SqlExpression> values, Expression sourceExpression) { if (values.Count == 0) { throw Error.EmptyCaseNotSupported(); } bool flag = false; foreach (var expression in values) { flag |= expression.IsClientAidedExpression(); } if (flag) { var list = new List<SqlClientWhen>(); int num = 0; int num2 = matches.Count; while (num < num2) { list.Add(new SqlClientWhen(matches[num], values[num])); num++; } return new SqlClientCase(clrType, discriminator, list, sourceExpression); } var whens = new List<SqlWhen>(); int num3 = 0; int count = matches.Count; while (num3 < count) { whens.Add(new SqlWhen(matches[num3], values[num3])); num3++; } return new SqlSimpleCase(clrType, discriminator, whens, sourceExpression); } internal SqlExpression CastTo(Type clrType, SqlExpression expr) { return this.UnaryCast(clrType, this.typeProvider.From(clrType), expr, expr.SourceExpression); } internal SqlExpression CLRLENGTH(SqlExpression expr) { return Unary(SqlNodeType.ClrLength, expr); } internal virtual SqlExpression Concat(SqlExpression[] expressions, Expression sourceExpression) { SqlExpression right = expressions[expressions.Length - 1]; Debug.Assert(right.SqlType.IsString || right.SqlType.IsChar); for (int i = expressions.Length - 2; i >= 0; i--) { Debug.Assert(expressions[i].SqlType.IsString || expressions[i].SqlType.IsChar); right = this.Binary(SqlNodeType.Concat, expressions[i], right); } return right; } internal SqlExpression ConvertTo(Type clrType, SqlExpression expr) { return UnaryConvert(clrType, typeProvider.From(clrType), expr, expr.SourceExpression); } internal SqlExpression ConvertTo(Type clrType, IProviderType sqlType, SqlExpression expr) { return UnaryConvert(clrType, sqlType, expr, expr.SourceExpression); } internal SqlExpression ConvertToBigint(SqlExpression expr) { return this.ConvertTo(typeof(long), expr); } internal SqlExpression ConvertToBool(SqlExpression expr) { return this.ConvertTo(typeof(bool), expr); } internal SqlExpression ConvertToDouble(SqlExpression expr) { return this.ConvertTo(typeof(double), expr); } internal SqlExpression ConvertToInt(SqlExpression expr) { return this.ConvertTo(typeof(int), expr); } internal virtual SqlExpression DATALENGTH(SqlExpression expr) { return FunctionCall(typeof(int), "DATALENGTH", new[] { expr }, expr.SourceExpression); } internal SqlExpression DATEADD(string partName, SqlExpression value, SqlExpression expr) { return DATEADD(partName, value, expr, expr.SourceExpression, false); } internal SqlExpression DATEADD(string partName, SqlExpression value, SqlExpression expr, Expression sourceExpression, bool asNullable) { Type clrType = asNullable ? typeof(DateTime?) : typeof(DateTime); return this.FunctionCall(clrType, "DATEADD", new[] { new SqlVariable(typeof(void), null, partName, sourceExpression), value, expr }, sourceExpression); } internal virtual SqlExpression DATEPART(string partName, SqlExpression expr) { return FunctionCall(typeof(int), "DATEPART", new[] { new SqlVariable(typeof(void), null, partName, expr.SourceExpression), expr }, expr.SourceExpression); } internal IProviderType Default(MetaDataMember member) { if (member == null) { throw Error.ArgumentNull("member"); } if (!string.IsNullOrEmpty(member.DbType)) { return this.typeProvider.Parse(member.DbType); } return this.typeProvider.From(member.Type); } [System.Diagnostics.DebuggerStepThrough] internal IProviderType Default(Type clrType) { return this.typeProvider.From(clrType); } internal SqlExpression DiscriminatedType(SqlExpression discriminator, MetaType targetType) { return new SqlDiscriminatedType(this.typeProvider.From(typeof(Type)), discriminator, targetType, discriminator.SourceExpression); } internal SqlExpression Divide(SqlExpression first, SqlExpression second) { return this.Binary(SqlNodeType.Div, first, second); } internal SqlExpression Divide(SqlExpression expr, long second) { return this.Binary(SqlNodeType.Div, expr, this.ValueFromObject(second, false, expr.SourceExpression)); } internal SqlDoNotVisitExpression DoNotVisitExpression(SqlExpression expr) { return new SqlDoNotVisitExpression(expr); } internal SqlExprSet ExprSet(SqlExpression[] exprs, Expression sourceExpression) { return new SqlExprSet(exprs[0].ClrType, exprs, sourceExpression); } internal SqlFunctionCall FunctionCall(Type clrType, string name, IEnumerable<SqlExpression> args, Expression source) { return new SqlFunctionCall(clrType, Default(clrType), name, args, source); } internal SqlFunctionCall FunctionCall(Type clrType, IProviderType sqlType, string name, IEnumerable<SqlExpression> args, Expression source) { return new SqlFunctionCall(clrType, sqlType, name, args, source); } internal SqlIn In(SqlExpression expr, IEnumerable<SqlExpression> values, Expression source) { return new SqlIn(typeof(bool), this.typeProvider.From(typeof(bool)), expr, values, source); } internal virtual SqlExpression String_Length(SqlExpression expr) { return this.FunctionCall(typeof(int), "LEN", new[] { expr }, expr.SourceExpression); } internal SqlLike Like(SqlExpression expr, SqlExpression pattern, SqlExpression escape, Expression source) { return new SqlLike(typeof(bool), this.typeProvider.From(typeof(bool)), expr, pattern, escape, source); } internal SqlMember Member(SqlExpression expr, MetaDataMember member) { return new SqlMember(member.Type, this.Default(member), expr, member.Member); } internal SqlMember Member(SqlExpression expr, MemberInfo member) { //if (member is IndexMemberInfo) //{ // Type memberType = TypeSystem.GetMemberType(member); // MetaType metaType = this.model.GetMetaType(member.DeclaringType); // //MetaDataMember dataMember = metaType.GetDataMember(member); // var dataMember = new IndexPropertyDataMember(metaType, (IndexMemberInfo) member); // //if ((metaType == null)) // //{ // // return new MySqlMember(memberType, this.Default(memberType), expr, member, dataMember); // //} // return new MySqlMember(memberType, this.Default(dataMember), expr, member, dataMember); //} //else //{ Type memberType = TypeSystem.GetMemberType(member); MetaType metaType = this.model.GetMetaType(member.DeclaringType); MetaDataMember dataMember = metaType.GetDataMember(member); if (dataMember != null) { return new SqlMember(memberType, this.Default(dataMember), expr, member); } return new SqlMember(memberType, this.Default(memberType), expr, member); //} } [System.Diagnostics.DebuggerStepThrough] internal SqlMethodCall MethodCall(MethodInfo method, SqlExpression obj, SqlExpression[] args, Expression sourceExpression) { return new SqlMethodCall(method.ReturnType, this.Default(method.ReturnType), method, obj, args, sourceExpression); } internal SqlMethodCall MethodCall(Type returnType, MethodInfo method, SqlExpression obj, SqlExpression[] args, Expression sourceExpression) { return new SqlMethodCall(returnType, this.Default(returnType), method, obj, args, sourceExpression); } internal SqlExpression Mod(SqlExpression expr, long second) { return this.Binary(SqlNodeType.Mod, expr, this.ValueFromObject(second, false, expr.SourceExpression)); } internal SqlExpression Multiply(params SqlExpression[] expressions) { SqlExpression right = expressions[expressions.Length - 1]; for (int i = expressions.Length - 2; i >= 0; i--) { right = this.Binary(SqlNodeType.Mul, expressions[i], right); } return right; } internal SqlExpression Multiply(SqlExpression expr, long second) { return this.Binary(SqlNodeType.Mul, expr, this.ValueFromObject(second, false, expr.SourceExpression)); } internal SqlNew New(MetaType type, ConstructorInfo cons, IEnumerable<SqlExpression> args, IEnumerable<MemberInfo> argMembers, IEnumerable<SqlMemberAssign> bindings, Expression sourceExpression) { return new SqlNew(type, this.typeProvider.From(type.Type), cons, args, argMembers, bindings, sourceExpression); } internal SqlExpression ObjectType(SqlExpression obj, Expression sourceExpression) { return new SqlObjectType(obj, this.typeProvider.From(typeof(Type)), sourceExpression); } internal SqlExpression OrAccumulate(SqlExpression left, SqlExpression right) { if (left == null) { return right; } if (right == null) { return left; } return this.Binary(SqlNodeType.Or, left, right); } internal SqlExpression Parameter(object value, Expression source) { Type clrType = value.GetType(); return this.Value(clrType, this.typeProvider.From(value), value, true, source); } internal SqlRowNumber RowNumber(List<SqlOrderExpression> orderBy, Expression sourceExpression) { return new SqlRowNumber(typeof(long), this.typeProvider.From(typeof(long)), orderBy, sourceExpression); } internal virtual SqlSearchedCase SearchedCase(SqlWhen[] whens, SqlExpression @else, Expression sourceExpression) { return new SqlSearchedCase(whens[0].Value.ClrType, whens, @else, sourceExpression); } internal SqlExpression StaticType(MetaType typeOf, Expression sourceExpression) { if (typeOf == null) { throw Error.ArgumentNull("typeOf"); } if (typeOf.InheritanceCode == null) { return new SqlValue(typeof(Type), this.typeProvider.From(typeof(Type)), typeOf.Type, false, sourceExpression); } Type clrType = typeOf.InheritanceCode.GetType(); SqlValue discriminator = new SqlValue(clrType, this.typeProvider.From(clrType), typeOf.InheritanceCode, true, sourceExpression); return this.DiscriminatedType(discriminator, typeOf); } internal SqlSubSelect SubSelect(SqlNodeType nt, SqlSelect select) { return this.SubSelect(nt, select, null); } internal SqlSubSelect SubSelect(SqlNodeType nt, SqlSelect select, Type clrType) { IProviderType sqlType = null; SqlNodeType type2 = nt; if (type2 <= SqlNodeType.Exists) { switch (type2) { case SqlNodeType.Element: goto Label_0022; case SqlNodeType.Exists: clrType = typeof(bool); sqlType = this.typeProvider.From(typeof(bool)); goto Label_0098; } goto Label_0098; } if (type2 == SqlNodeType.Multiset) { if (clrType == null) { clrType = typeof(List<>).MakeGenericType(new Type[] { select.Selection.ClrType }); } sqlType = this.typeProvider.GetApplicationType(1); goto Label_0098; } if (type2 != SqlNodeType.ScalarSubSelect) { goto Label_0098; } Label_0022: clrType = select.Selection.ClrType; sqlType = select.Selection.SqlType; Label_0098: return new SqlSubSelect(nt, clrType, sqlType, select); } internal SqlExpression Subtract(SqlExpression first, SqlExpression second) { return this.Binary(SqlNodeType.Sub, first, second); } internal SqlExpression Subtract(SqlExpression expr, int second) { return this.Binary(SqlNodeType.Sub, expr, this.ValueFromObject(second, false, expr.SourceExpression)); } internal SqlTable Table(MetaTable table, MetaType rowType, Expression sourceExpression) { return new SqlTable(table, rowType, this.typeProvider.GetApplicationType(0), sourceExpression); } internal SqlTableValuedFunctionCall TableValuedFunctionCall(MetaType rowType, Type clrType, string name, IEnumerable<SqlExpression> args, Expression source) { return new SqlTableValuedFunctionCall(rowType, clrType, this.Default(clrType), name, args, source); } internal SqlExpression TypeCase(Type clrType, MetaType rowType, SqlExpression discriminator, IEnumerable<SqlTypeCaseWhen> whens, Expression sourceExpression) { return new SqlTypeCase(clrType, this.typeProvider.From(clrType), rowType, discriminator, whens, sourceExpression); } public SqlExpression TypedLiteralNull(Type type, Expression sourceExpression) { return this.ValueFromObject(null, type, false, sourceExpression); } internal SqlUnary Unary(SqlNodeType nodeType, SqlExpression expression) { return this.Unary(nodeType, expression, expression.SourceExpression); } internal SqlUnary Unary(SqlNodeType nodeType, SqlExpression expression, Expression sourceExpression) { return this.Unary(nodeType, expression, null, sourceExpression); } internal SqlUnary Unary(SqlNodeType nodeType, SqlExpression expression, MethodInfo method, Expression sourceExpression) { Type clrType = null; IProviderType sqlType = null; if (nodeType == SqlNodeType.Count) { clrType = typeof(int); sqlType = this.typeProvider.From(typeof(int)); } else if (nodeType == SqlNodeType.LongCount) { clrType = typeof(long); sqlType = this.typeProvider.From(typeof(long)); } else if (nodeType == SqlNodeType.ClrLength) { clrType = typeof(int); sqlType = this.typeProvider.From(typeof(int)); } else { if (nodeType.IsPredicateUnaryOperator()) { clrType = typeof(bool); } else { clrType = expression.ClrType; } sqlType = this.typeProvider.PredictTypeForUnary(nodeType, expression.SqlType); } return new SqlUnary(nodeType, clrType, sqlType, expression, method, sourceExpression); } internal SqlUnary UnaryCast(Type targetClrType, IProviderType targetSqlType, SqlExpression expression, Expression sourceExpression) { return new SqlUnary(SqlNodeType.Cast, targetClrType, targetSqlType, expression, null, sourceExpression); } internal static SqlUnary UnaryConvert(Type targetClrType, IProviderType targetSqlType, SqlExpression expression, Expression sourceExpression) { return new SqlUnary(SqlNodeType.Convert, targetClrType, targetSqlType, expression, null, sourceExpression); } internal SqlUnary UnaryValueOf(SqlExpression expression, Expression sourceExpression) { return new SqlUnary(SqlNodeType.ValueOf, TypeSystem.GetNonNullableType(expression.ClrType), expression.SqlType, expression, null, sourceExpression); } internal SqlExpression Value(Type clrType, IProviderType sqlType, object value, bool isClientSpecified, Expression sourceExpression) { if (typeof(Type).IsAssignableFrom(clrType)) { MetaType metaType = this.model.GetMetaType((Type)value); return this.StaticType(metaType, sourceExpression); } return new SqlValue(clrType, sqlType, value, isClientSpecified, sourceExpression); } internal SqlExpression ValueFromObject(object value, Expression sourceExpression) { return this.ValueFromObject(value, false, sourceExpression); } internal SqlExpression ValueFromObject(object value, bool isClientSpecified, Expression sourceExpression) { if (value == null) { throw Error.ArgumentNull("value"); } Type clrType = value.GetType(); return this.ValueFromObject(value, clrType, isClientSpecified, sourceExpression); } internal SqlExpression ValueFromObject(object value, Type clrType, bool isClientSpecified, Expression sourceExpression) { if (clrType == null) { throw Error.ArgumentNull("clrType"); } IProviderType sqlType; if (value == null || clrType.IsValueType == false) sqlType = this.typeProvider.From(clrType); else sqlType = this.typeProvider.From(value); return this.Value(clrType, sqlType, value, isClientSpecified, sourceExpression); } // Properties internal ITypeSystemProvider TypeProvider { get { return this.typeProvider; } } private SqlExpression CreateDateTimeFromDateAndMs(SqlExpression sqlDate, SqlExpression ms, Expression source, bool asNullable) { SqlExpression expr = ConvertToBigint(ms); SqlExpression expression2 = DATEADD("day", Divide(expr, (long)0x5265c00L), sqlDate, source, asNullable); return DATEADD("ms", Mod(expr, 0x5265c00L), expression2, source, asNullable); } private SqlExpression CreateDateTimeFromDateAndMs(SqlExpression sqlDate, SqlExpression ms, Expression source) { return CreateDateTimeFromDateAndMs(sqlDate, ms, source, false); } internal virtual SqlExpression DateTime_AddDays(SqlMethodCall mc) { SqlExpression expression6 = Multiply(mc.Arguments[0], 0x5265c00L); var expression = this.CreateDateTimeFromDateAndMs(mc.Object, expression6, mc.SourceExpression, false); return expression; } internal virtual SqlExpression DateTime_AddHours(SqlMethodCall mc) { SqlExpression expression5 = Multiply(mc.Arguments[0], 0x36ee80L); return CreateDateTimeFromDateAndMs(mc.Object, expression5, mc.SourceExpression); } internal virtual SqlExpression DateTime_AddMinutes(SqlMethodCall mc) { SqlExpression expression4 = Multiply(mc.Arguments[0], 0xea60L); return this.CreateDateTimeFromDateAndMs(mc.Object, expression4, mc.SourceExpression); } internal virtual SqlExpression DateTime_AddSeconds(SqlMethodCall mc) { SqlExpression ms = Multiply(mc.Arguments[0], 0x3e8L); return this.CreateDateTimeFromDateAndMs(mc.Object, ms, mc.SourceExpression); } internal virtual SqlExpression DateTime_AddYears(SqlMethodCall mc) { return DATEADD("YEAR", mc.Arguments[0], mc.Object); } internal virtual SqlExpression DateTime_AddMonths(SqlMethodCall mc) { return DATEADD("MONTH", mc.Arguments[0], mc.Object); ; } internal virtual SqlExpression DateTime_ToString(SqlMethodCall mc) { throw new NotImplementedException(); } internal virtual SqlExpression DateTime_Add(SqlMethodCall mc) { return CreateDateTimeFromDateAndTicks(mc.Object, mc.Arguments[0], mc.SourceExpression); } private SqlExpression CreateDateTimeFromDateAndTicks(SqlExpression sqlDate, SqlExpression sqlTicks, Expression source) { return this.CreateDateTimeFromDateAndTicks(sqlDate, sqlTicks, source, false); } private SqlExpression CreateDateTimeFromDateAndTicks(SqlExpression sqlDate, SqlExpression sqlTicks, Expression source, bool asNullable) { SqlExpression expr = DATEADD("day", Divide(sqlTicks, (long)0xc92a69c000L), sqlDate, source, asNullable); return DATEADD("ms", Mod(Divide(sqlTicks, (long)0x2710L), 0x5265c00L), expr, source, asNullable); } internal virtual SqlExpression Math_Truncate(SqlMethodCall mc) { var args = new[] { mc.Arguments[0], ValueFromObject(0, false, mc.SourceExpression), ValueFromObject(1, false, mc.SourceExpression) }; return FunctionCall(mc.Method.ReturnType, "ROUND", args, mc.SourceExpression); } internal virtual SqlExpression Math_Round(SqlMethodCall mc) { var expr = mc.Arguments[0]; Type clrType = expr.ClrType; var sourceExpression = mc.SourceExpression; //if (mc.Arguments.Count == 1) // return FunctionCall(clrType, "round", new[] { expr }, sourceExpression); int count = mc.Arguments.Count; if (mc.Arguments[count - 1].ClrType != typeof(MidpointRounding)) { throw Error.MathRoundNotSupported(); } SqlExpression expression15; if (count == 2) { expression15 = ValueFromObject(0, false, sourceExpression); } else { expression15 = mc.Arguments[1]; } SqlExpression expression16 = mc.Arguments[count - 1]; if (expression16.NodeType != SqlNodeType.Value) { throw Error.NonConstantExpressionsNotSupportedForRounding(); } if (((MidpointRounding)SqlVisitor.Eval(expression16)) == MidpointRounding.AwayFromZero) { return FunctionCall(expr.ClrType, "round", new[] { expr, expression15 }, sourceExpression); } SqlExpression expression17 = this.FunctionCall(clrType, "round", new[] { expr, expression15 }, sourceExpression); SqlExpression expression18 = this.Multiply(expr, 2L); SqlExpression expression19 = this.FunctionCall(clrType, "round", new[] { expression18, expression15 }, sourceExpression); SqlExpression expression20 = this.AndAccumulate(this.Binary(SqlNodeType.EQ, expression18, expression19), this.Binary(SqlNodeType.NE, expr, expression17)); SqlExpression expression21 = this.Multiply(this.FunctionCall(clrType, "round", new[] { this.Divide(expr, 2L), expression15 }, sourceExpression), 2L); return this.SearchedCase(new[] { new SqlWhen(expression20, expression21) }, expression17, sourceExpression); } internal virtual SqlExpression String_Substring(SqlMethodCall mc) { SqlExpression[] args; if (mc.Arguments.Count != 1) { if (mc.Arguments.Count == 2) { args = new[] { mc.Object, Add(mc.Arguments[0], 1), mc.Arguments[1] }; return FunctionCall(typeof(string), "SUBSTRING", args, mc.SourceExpression); } throw Error.MethodHasNoSupportConversionToSql(mc.Method);//GetMethodSupportException(mc); } args = new[] { mc.Object, Add(mc.Arguments[0], 1), CLRLENGTH(mc.Object) }; return FunctionCall(typeof(string), "SUBSTRING", args, mc.SourceExpression); } internal virtual SqlExpression String_Insert(SqlMethodCall mc) { return null; } internal virtual SqlExpression Math_Max(SqlMethodCall mc) { SqlExpression left = mc.Arguments[0]; SqlExpression right = mc.Arguments[1]; SqlExpression match = Binary(SqlNodeType.LT, left, right); return new SqlSearchedCase(mc.Method.ReturnType, new[] { new SqlWhen(match, right) }, left, mc.SourceExpression); } internal virtual SqlExpression Math_Min(SqlMethodCall mc) { SqlExpression expression11 = mc.Arguments[0]; SqlExpression expression12 = mc.Arguments[1]; SqlExpression expression13 = this.Binary(SqlNodeType.LT, expression11, expression12); return this.SearchedCase(new[] { new SqlWhen(expression13, expression11) }, expression12, mc.SourceExpression); } internal virtual SqlExpression String_Trim(SqlMethodCall mc) { var args = new[] { FunctionCall(typeof(string), "RTRIM", new[] { mc.Object }, mc.SourceExpression) }; return FunctionCall(typeof(string), "LTRIM", args, mc.SourceExpression); } internal virtual SqlExpression String_TrimEnd(SqlMethodCall mc) { throw Error.MethodHasNoSupportConversionToSql(mc); } internal virtual SqlExpression String_TrimStart(SqlMethodCall mc) { return FunctionCall(typeof(string), "LTRIM", new[] { mc.Object }, mc.SourceExpression); } internal SqlVariable VariableFromName(string name, Expression sourceExpression) { return new SqlVariable(typeof(void), null, name, sourceExpression); } internal virtual SqlExpression UNICODE(Type clrType, SqlUnary uo) { return FunctionCall(clrType, TypeProvider.From(typeof(int)), "UNICODE", new[] { uo.Operand }, uo.SourceExpression); } internal virtual MethodSupport GetConvertMethodSupport(SqlMethodCall mc) { //return MethodSupport.None; if ((mc.Method.IsStatic && (mc.Method.DeclaringType == typeof(Convert))) && (mc.Arguments.Count == 1)) { switch (mc.Method.Name) { case "ToBoolean": case "ToDecimal": case "ToByte": case "ToChar": case "ToDouble": case "ToInt16": case "ToInt32": case "ToInt64": case "ToSingle": case "ToString": return MethodSupport.Method; case "ToDateTime": if ((mc.Arguments[0].ClrType != typeof(string)) && (mc.Arguments[0].ClrType != typeof(DateTime))) { return MethodSupport.MethodGroup; } return MethodSupport.Method; } } return MethodSupport.None; } internal virtual SqlExpression String_Remove(SqlMethodCall mc) { var sourceExpression = mc.SourceExpression; if (mc.Arguments.Count != 1) { if (mc.Arguments.Count == 2) { return this.FunctionCall(typeof(string), "STUFF", new SqlExpression[] { mc.Object, this.Add(mc.Arguments[0], 1), mc.Arguments[1], this.ValueFromObject("", false, sourceExpression) }, sourceExpression); } throw Error.MethodHasNoSupportConversionToSql(mc.Method); } return FunctionCall(typeof(string), "STUFF", new[] { mc.Object, this.Add(mc.Arguments[0], 1), this.CLRLENGTH(mc.Object), this.ValueFromObject("", false, sourceExpression) }, sourceExpression); } internal virtual SqlExpression DateTime_Date(SqlMember m, SqlExpression expr) { var expression = DATEPART("MILLISECOND", expr); var expression4 = DATEPART("SECOND", expr); var expression5 = DATEPART("MINUTE", expr); var expression6 = DATEPART("HOUR", expr); var expression7 = expr; expression7 = DATEADD("MILLISECOND", Unary(SqlNodeType.Negate, expression), expression7); expression7 = DATEADD("SECOND", Unary(SqlNodeType.Negate, expression4), expression7); expression7 = DATEADD("MINUTE", Unary(SqlNodeType.Negate, expression5), expression7); return DATEADD("HOUR", Unary(SqlNodeType.Negate, expression6), expression7); } internal virtual SqlExpression DateTime_Day(SqlMember m, SqlExpression expr) { string datePart = GetDatePart(m.Member.Name); return DATEPART(datePart, expr); } internal virtual SqlExpression DateTime_DayOfYear(SqlMember m, SqlExpression expr) { string datePart = GetDatePart(m.Member.Name); return DATEPART(datePart, expr); } internal virtual SqlNode DateTime_TimeOfDay(SqlMember member, SqlExpression expr) { SqlExpression expression8 = this.DATEPART("HOUR", expr); SqlExpression expression9 = this.DATEPART("MINUTE", expr); SqlExpression expression10 = this.DATEPART("SECOND", expr); SqlExpression expression11 = this.DATEPART("MILLISECOND", expr); SqlExpression expression12 = this.Multiply(this.ConvertToBigint(expression8), 0x861c46800L); SqlExpression expression13 = this.Multiply(this.ConvertToBigint(expression9), 0x23c34600L); SqlExpression expression14 = this.Multiply(this.ConvertToBigint(expression10), 0x989680L); SqlExpression expression15 = this.Multiply(this.ConvertToBigint(expression11), 0x2710L); return this.ConvertTo(typeof(TimeSpan), this.Add(new SqlExpression[] { expression12, expression13, expression14, expression15 })); } internal virtual SqlExpression String_IndexOf(SqlMethodCall mc, Expression sourceExpression) { if (mc.Arguments.Count == 1) { if ((mc.Arguments[0] is SqlValue) && (((SqlValue)mc.Arguments[0]).Value == null)) { throw Error.ArgumentNull("value"); } var when = new SqlWhen(Binary(SqlNodeType.EQ, CLRLENGTH(mc.Arguments[0]), ValueFromObject(0, sourceExpression)), ValueFromObject(0, sourceExpression)); SqlExpression expression9 = Subtract(FunctionCall(typeof(int), "CHARINDEX", new[] { mc.Arguments[0], mc.Object }, sourceExpression), 1); return SearchedCase(new SqlWhen[] { when }, expression9, sourceExpression); } if (mc.Arguments.Count == 2) { if ((mc.Arguments[0] is SqlValue) && (((SqlValue)mc.Arguments[0]).Value == null)) { throw Error.ArgumentNull("value"); } if (mc.Arguments[1].ClrType == typeof(StringComparison)) { throw Error.IndexOfWithStringComparisonArgNotSupported(); } SqlExpression expression10 = Binary(SqlNodeType.EQ, CLRLENGTH(mc.Arguments[0]), ValueFromObject(0, sourceExpression)); SqlWhen when2 = new SqlWhen(AndAccumulate(expression10, Binary(SqlNodeType.LE, Add(mc.Arguments[1], 1), CLRLENGTH(mc.Object))), mc.Arguments[1]); SqlExpression expression11 = Subtract(FunctionCall(typeof(int), "CHARINDEX", new SqlExpression[] { mc.Arguments[0], mc.Object, Add(mc.Arguments[1], 1) }, sourceExpression), 1); return SearchedCase(new SqlWhen[] { when2 }, expression11, sourceExpression); } if (mc.Arguments.Count != 3) { //throw GetMethodSupportException(mc); Error.MethodHasNoSupportConversionToSql(mc); //goto Label_1B30; } if ((mc.Arguments[0] is SqlValue) && (((SqlValue)mc.Arguments[0]).Value == null)) { throw Error.ArgumentNull("value"); } if (mc.Arguments[2].ClrType == typeof(StringComparison)) { throw Error.IndexOfWithStringComparisonArgNotSupported(); } SqlExpression left = Binary(SqlNodeType.EQ, CLRLENGTH(mc.Arguments[0]), ValueFromObject(0, sourceExpression)); SqlWhen when3 = new SqlWhen(AndAccumulate(left, Binary(SqlNodeType.LE, Add(mc.Arguments[1], 1), CLRLENGTH(mc.Object))), mc.Arguments[1]); SqlExpression expression13 = FunctionCall(typeof(string), "SUBSTRING", new SqlExpression[] { mc.Object, ValueFromObject(1, false, sourceExpression), Add(new SqlExpression[] { mc.Arguments[1], mc.Arguments[2] }) }, sourceExpression); SqlExpression @else = Subtract(FunctionCall(typeof(int), "CHARINDEX", new SqlExpression[] { mc.Arguments[0], expression13, Add(mc.Arguments[1], 1) }, sourceExpression), 1); return SearchedCase(new SqlWhen[] { when3 }, @else, sourceExpression); } internal virtual SqlExpression Math_Floor(SqlMethodCall mc) { return CreateFunctionCallStatic1(mc.Arguments[0].ClrType, "FLOOR", mc.Arguments, mc.SourceExpression); } protected SqlExpression CreateFunctionCallStatic2(Type type, string functionName, List<SqlExpression> arguments, Expression source) { return FunctionCall(type, functionName, new[] { arguments[0], arguments[1] }, source); } protected SqlExpression CreateFunctionCallStatic1(Type type, string functionName, List<SqlExpression> arguments, Expression source) { return FunctionCall(type, functionName, new[] { arguments[0] }, source); } internal virtual SqlExpression DateTime_DayOfWeek(SqlMember m, SqlExpression expr) { SqlExpression expression16 = DATEPART("dw", expr); var fun = Add(new SqlVariable(typeof(int), Default(typeof(int)), "@@DATEFIRST", expr.SourceExpression), 6); return ConvertTo(typeof(DayOfWeek), Mod(Add(new[] { expression16, fun }), 7L)); } internal virtual bool IsSupportedDateTimeMember(SqlMember m) { if (m.Expression.ClrType == typeof(DateTime)) { string str2; if (GetDatePart(m.Member.Name) != null) { return true; } if (((str2 = m.Member.Name) != null) && (((str2 == "Date") || (str2 == "TimeOfDay")) || (str2 == "DayOfWeek"))) { return true; } } return false; } private static string GetDatePart(string memberName) { switch (memberName) { case "Year": case "Month": case "Day": case "DayOfYear": //case "DayOfWeek": case "Hour": case "Minute": case "Second": case "Millisecond": return memberName; } return null; } internal virtual MethodSupport GetStringMethodSupport(SqlMethodCall mc) { if (mc.Method.DeclaringType == typeof(string)) { if (mc.Method.IsStatic) { if (mc.Method.Name == "Concat") { return MethodSupport.Method; } } else { switch (mc.Method.Name) { case "Contains": case "StartsWith": case "EndsWith": if (mc.Arguments.Count != 1) { return MethodSupport.MethodGroup; } return MethodSupport.Method; case "IndexOf": case "LastIndexOf": if (mc.Arguments[mc.Arguments.Count - 1].ClrType == typeof(StringComparison)) return MethodSupport.None; if (((mc.Arguments.Count != 1) && (mc.Arguments.Count != 2)) && (mc.Arguments.Count != 3)) { return MethodSupport.MethodGroup; } return MethodSupport.Method; case "Insert": if (mc.Arguments.Count != 2) { return MethodSupport.MethodGroup; } return MethodSupport.Method; case "PadLeft": case "PadRight": case "Remove": case "Substring": if ((mc.Arguments.Count != 1) && (mc.Arguments.Count != 2)) { return MethodSupport.MethodGroup; } return MethodSupport.Method; case "Replace": return MethodSupport.Method; case "Trim": case "TrimEnd": case "ToLower": case "ToUpper": if (mc.Arguments.Count == 0) { return MethodSupport.Method; } return MethodSupport.MethodGroup; case "get_Chars": case "CompareTo": if (mc.Arguments.Count != 1) { return MethodSupport.MethodGroup; } return MethodSupport.Method; } } } return MethodSupport.None; } internal virtual SqlExpression TranslateConvertStaticMethod(SqlMethodCall mc) { //SqlExpression expression = null; if (mc.Arguments.Count != 1) { return null; } var expr = mc.Arguments[0]; Type type; switch (mc.Method.Name) { case "ToBoolean": type = typeof(bool); break; case "ToDecimal": type = typeof(decimal); break; case "ToByte": type = typeof(byte); break; case "ToChar": type = typeof(char); if (expr.SqlType.IsChar) { TypeProvider.From(type, 1); } break; case "ToDateTime": { var nonNullableType = TypeSystem.GetNonNullableType(expr.ClrType); if ((nonNullableType != typeof(string)) && (nonNullableType != typeof(DateTime))) { throw Error.ConvertToDateTimeOnlyForDateTimeOrString(); } type = typeof(DateTime); break; } case "ToDouble": type = typeof(double); break; case "ToInt16": type = typeof(short); break; case "ToInt32": type = typeof(int); break; case "ToInt64": type = typeof(long); break; case "ToSingle": type = typeof(float); break; case "ToString": type = typeof(string); break; case "ToSByte": type = typeof(sbyte); break; default: throw Error.MethodHasNoSupportConversionToSql(mc); } if ((this.TypeProvider.From(type) != expr.SqlType) || ((expr.ClrType == typeof(bool)) && (type == typeof(int)))) { return this.ConvertTo(type, expr); } if (this.TypeProvider.From(type) != expr.SqlType) { return this.ConvertTo(type, expr); } if ((type != expr.ClrType) && (TypeSystem.GetNonNullableType(type) == TypeSystem.GetNonNullableType(expr.ClrType))) { return new SqlLift(type, expr, expr.SourceExpression); } return expr; } internal virtual SqlExpression String_GetChar(SqlMethodCall mc, Expression sourceExpression) { if (mc.Arguments.Count != 1) { //throw GetMethodSupportException(mc); Error.MethodHasNoSupportConversionToSql(mc); } var args = new[] { mc.Object, Add(mc.Arguments[0], 1), ValueFromObject(1, false, sourceExpression) }; return FunctionCall(typeof(char), "SUBSTRING", args, sourceExpression); } internal virtual SqlExpression String_Replace(SqlMethodCall mc) { if ((mc.Arguments[0] is SqlValue) && (((SqlValue)mc.Arguments[0]).Value == null)) { throw Error.ArgumentNull("old"); } if ((mc.Arguments[1] is SqlValue) && (((SqlValue)mc.Arguments[1]).Value == null)) { throw Error.ArgumentNull("new"); } return FunctionCall(typeof(string), "REPLACE", new[] { mc.Object, mc.Arguments[0], mc.Arguments[1] }, mc.SourceExpression); } internal virtual SqlExpression Math_Atan(SqlMethodCall mc, Expression sourceExpression) { return CreateFunctionCallStatic1(typeof(double), "ATAN", mc.Arguments, sourceExpression); } internal virtual SqlExpression Math_Atan2(SqlMethodCall mc, Expression sourceExpression) { Debug.Assert(mc.Method.Name == "Atan2"); return this.CreateFunctionCallStatic2(typeof(double), "ATN2", mc.Arguments, sourceExpression); } internal virtual SqlExpression Math_Cosh(SqlMethodCall mc, Expression sourceExpression) { SqlExpression expression = mc.Arguments[0]; SqlExpression expression3 = FunctionCall(typeof(double), "EXP", new[] { expression }, sourceExpression); SqlExpression expression4 = Unary(SqlNodeType.Negate, expression, sourceExpression); SqlExpression expression5 = FunctionCall(typeof(double), "EXP", new[] { expression4 }, sourceExpression); return Divide(Add(new[] { expression3, expression5 }), 2L); } internal virtual SqlExpression Math_Sinh(SqlMethodCall mc, Expression sourceExpression) { SqlExpression expression22 = mc.Arguments[0]; SqlExpression expression23 = FunctionCall(typeof(double), "EXP", new SqlExpression[] { expression22 }, sourceExpression); SqlExpression expression24 = Unary(SqlNodeType.Negate, expression22, sourceExpression); SqlExpression expression25 = FunctionCall(typeof(double), "EXP", new SqlExpression[] { expression24 }, sourceExpression); return Divide(Subtract(expression23, expression25), (long)2L); } internal virtual SqlExpression MakeCoalesce(SqlExpression left, SqlExpression right, Type type, Expression sourceExpression) { return FunctionCall(type, "ISNULL", new[] { left, right }, sourceExpression); } internal virtual SqlExpression DateTime_Hour(SqlMember m, SqlExpression expr) { string datePart = GetDatePart(m.Member.Name); return DATEPART(datePart, expr); } internal virtual SqlExpression DateTime_Minute(SqlMember m, SqlExpression expr) { string datePart = GetDatePart(m.Member.Name); return DATEPART(datePart, expr); } internal virtual SqlExpression DateTime_Month(SqlMember m, SqlExpression expr) { string datePart = GetDatePart(m.Member.Name); return DATEPART(datePart, expr); } internal virtual SqlExpression DateTime_Second(SqlMember m, SqlExpression expr) { string datePart = GetDatePart(m.Member.Name); return DATEPART(datePart, expr); } internal virtual SqlNode DateTime_Year(SqlMember m, SqlExpression expr) { string datePart = GetDatePart(m.Member.Name); return DATEPART(datePart, expr); } internal virtual SqlExpression Math_Log10(SqlMethodCall mc) { Debug.Assert(mc.Method.Name == "Log10"); return CreateFunctionCallStatic1(typeof(double), "LOG10", mc.Arguments, mc.SourceExpression); } internal virtual SqlExpression Math_Log(SqlMethodCall mc) { //Debug.Assert(mc.Method.Name == "Log10"); return CreateFunctionCallStatic1(typeof(double), "ln", mc.Arguments, mc.SourceExpression); } // Fields private static readonly string[] dateParts = new[] { "Year", "Month", "Day", "Hour", "Minute", "Second", "Millisecond" }; internal virtual MethodSupport GetSqlMethodsMethodSupport(SqlMethodCall mc) { //MY CODE if (Attribute.IsDefined(mc.Method, typeof(FunctionAttribute))) return MethodSupport.Method; //================================ if (mc.Method.IsStatic && (mc.Method.DeclaringType == typeof(SqlMethods))) { if (mc.Method.Name.StartsWith("DateDiff", StringComparison.Ordinal) && (mc.Arguments.Count == 2)) { foreach (string str in dateParts) { if (mc.Method.Name == ("DateDiff" + str)) { if (mc.Arguments.Count == 2) { return MethodSupport.Method; } return MethodSupport.MethodGroup; } } } else { if (mc.Method.Name == "Like") { if (mc.Arguments.Count == 2) { return MethodSupport.Method; } if (mc.Arguments.Count == 3) { return MethodSupport.Method; } return MethodSupport.MethodGroup; } if (mc.Method.Name == "RawLength") { return MethodSupport.Method; } if(mc.Method.Name == "Identity") { return MethodSupport.Method; } } } return MethodSupport.None; } internal virtual SqlExpression TranslateSqlMethodsMethod(SqlMethodCall mc) { Expression sourceExpression = mc.SourceExpression; const SqlExpression expression2 = null; string name = mc.Method.Name; if (name.StartsWith("DateDiff", StringComparison.Ordinal) && (mc.Arguments.Count == 2)) { foreach (string str2 in dateParts) { if (mc.Method.Name == ("DateDiff" + str2)) { SqlExpression expression3 = mc.Arguments[0]; SqlExpression expression4 = mc.Arguments[1]; SqlExpression expression5 = new SqlVariable(typeof(void), null, str2, sourceExpression); return this.FunctionCall(typeof(int), "DATEDIFF", new[] { expression5, expression3, expression4 }, sourceExpression); } } return expression2; } if (name == "Like") { if (mc.Arguments.Count == 2) { return this.Like(mc.Arguments[0], mc.Arguments[1], null, sourceExpression); } if (mc.Arguments.Count != 3) { return expression2; } return this.Like(mc.Arguments[0], mc.Arguments[1], this.ConvertTo(typeof(string), mc.Arguments[2]), sourceExpression); } if (name == "RawLength") { return this.DATALENGTH(mc.Arguments[0]); } return expression2; } internal virtual MethodSupport GetDateTimeMethodSupport(SqlMethodCall mc) { if (!mc.Method.IsStatic && (mc.Method.DeclaringType == typeof(DateTime))) { switch (mc.Method.Name) { case "CompareTo": case "AddTicks": case "AddMonths": case "AddYears": case "AddMilliseconds": case "AddSeconds": case "AddMinutes": case "AddHours": case "AddDays": return MethodSupport.Method; case "Add": if ((mc.Arguments.Count == 1) && (mc.Arguments[0].ClrType == typeof(TimeSpan))) { return MethodSupport.Method; } return MethodSupport.MethodGroup; } } return MethodSupport.None; } internal virtual SqlExpression DateTime_Subtract(SqlMethodCall mc) { throw new NotImplementedException(); } internal virtual SqlExpression DateTime_SubtractDays(SqlMethodCall mc) { throw new NotImplementedException(); } } }
// <copyright file="Startup.cs" company="Microsoft Open Technologies, Inc."> // Copyright 2011-2013 Microsoft Open Technologies, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Threading.Tasks; using Katana.Sandbox.WebServer; using Microsoft.Owin; using Microsoft.Owin.Logging; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Facebook; using Microsoft.Owin.Security.Infrastructure; using Microsoft.Owin.Security.OAuth; using Owin; [assembly: OwinStartup(typeof(Startup))] namespace Katana.Sandbox.WebServer { public class Startup { private readonly ConcurrentDictionary<string, string> _authenticationCodes = new ConcurrentDictionary<string, string>(StringComparer.Ordinal); public void Configuration(IAppBuilder app) { var logger = app.CreateLogger("Katana.Sandbox.WebServer"); logger.WriteInformation("Application Started"); app.Use(async (context, next) => { context.Get<TextWriter>("host.TraceOutput").WriteLine("{0} {1}{2}", context.Request.Method, context.Request.PathBase, context.Request.Path); await next(); context.Get<TextWriter>("host.TraceOutput").WriteLine("{0} {1}{2}", context.Response.StatusCode, context.Request.PathBase, context.Request.Path); }); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Application", AuthenticationMode = AuthenticationMode.Passive, LoginPath = new PathString("/Login"), LogoutPath = new PathString("/Logout"), }); app.SetDefaultSignInAsAuthenticationType("External"); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "External", AuthenticationMode = AuthenticationMode.Passive, CookieName = CookieAuthenticationDefaults.CookiePrefix + "External", ExpireTimeSpan = TimeSpan.FromMinutes(5), }); app.UseFacebookAuthentication(new FacebookAuthenticationOptions { AppId = "615948391767418", AppSecret = "c9b1fa6b68db835890ce469e0d98157f", // Scope = "email user_birthday user_website" }); app.UseGoogleAuthentication(); app.UseTwitterAuthentication("6XaCTaLbMqfj6ww3zvZ5g", "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI"); app.UseMicrosoftAccountAuthentication("000000004C0EA787", "QZde5m5HHZPxdieV0lOy7bBVTbVqR9Ju"); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { }); // CORS support app.Use(async (context, next) => { IOwinRequest req = context.Request; IOwinResponse res = context.Response; // for auth2 token requests, and web api requests if (req.Path.StartsWithSegments(new PathString("/Token")) || req.Path.StartsWithSegments(new PathString("/api"))) { // if there is an origin header var origin = req.Headers.Get("Origin"); if (!string.IsNullOrEmpty(origin)) { // allow the cross-site request res.Headers.Set("Access-Control-Allow-Origin", origin); } // if this is pre-flight request if (req.Method == "OPTIONS") { // respond immediately with allowed request methods and headers res.StatusCode = 200; res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST"); res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization"); // no further processing return; } } // continue executing pipeline await next(); }); app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions { AuthorizeEndpointPath = new PathString("/Authorize"), TokenEndpointPath = new PathString("/Token"), ApplicationCanDisplayErrors = true, #if DEBUG AllowInsecureHttp = true, #endif Provider = new OAuthAuthorizationServerProvider { OnValidateClientRedirectUri = ValidateClientRedirectUri, OnValidateClientAuthentication = ValidateClientAuthentication, OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials, }, AuthorizationCodeProvider = new AuthenticationTokenProvider { OnCreate = CreateAuthenticationCode, OnReceive = ReceiveAuthenticationCode, }, RefreshTokenProvider = new AuthenticationTokenProvider { OnCreate = CreateRefreshToken, OnReceive = ReceiveRefreshToken, } }); app.Map("/api", map => map.Run(async context => { var response = context.Response; var result = await context.Authentication.AuthenticateAsync(OAuthDefaults.AuthenticationType); if (result == null || result.Identity == null) { context.Authentication.Challenge(OAuthDefaults.AuthenticationType); return; } var identity = result.Identity; var properties = result.Properties.Dictionary; response.ContentType = "application/json"; response.Write("{\"Details\":["); foreach (var claim in identity.Claims) { response.Write("{\"Name\":\""); response.Write(claim.Type); response.Write("\",\"Value\":\""); response.Write(claim.Value); response.Write("\",\"Issuer\":\""); response.Write(claim.Issuer); response.Write("\"},"); // TODO: No comma on the last one } response.Write("],\"Properties\":["); foreach (var pair in properties) { response.Write("{\"Name\":\""); response.Write(pair.Key); response.Write("\",\"Value\":\""); response.Write(pair.Value); response.Write("\"},"); // TODO: No comma on the last one } response.Write("]}"); })); } private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) { if (context.ClientId == "123456") { context.Validated("http://localhost:18002/Katana.Sandbox.WebClient/ClientApp.aspx"); } else if (context.ClientId == "7890ab") { context.Validated("http://localhost:18002/Katana.Sandbox.WebClient/ClientPageSignIn.html"); } return Task.FromResult(0); } private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId; string clientSecret; if (context.TryGetBasicCredentials(out clientId, out clientSecret) || context.TryGetFormCredentials(out clientId, out clientSecret)) { if (clientId == "123456" && clientSecret == "abcdef") { context.Validated(); } else if (context.ClientId == "7890ab" && clientSecret == "7890ab") { context.Validated(); } } return Task.FromResult(0); } private Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x))); context.Validated(identity); return Task.FromResult(0); } private void CreateAuthenticationCode(AuthenticationTokenCreateContext context) { context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n")); _authenticationCodes[context.Token] = context.SerializeTicket(); } private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context) { string value; if (_authenticationCodes.TryRemove(context.Token, out value)) { context.DeserializeTicket(value); } } private void CreateRefreshToken(AuthenticationTokenCreateContext context) { context.SetToken(context.SerializeTicket()); } private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context) { context.DeserializeTicket(context.Token); } } }
// // UTF7EncodingTest.cs - NUnit Test Cases for System.Text.UTF7Encoding // // Authors // Patrick Kalkman [email protected] // Sebastien Pouliot <[email protected]> // // (C) 2003 Patrick Kalkman // Copyright (C) 2004 Novell (http://www.novell.com) // using NUnit.Framework; using System; using System.Text; namespace MonoTests.System.Text { [TestFixture] public class UTF7EncodingTest : Assertion { [Test] public void TestDirectlyEncoded1() { // Unicode characters a-z, A-Z, 0-9 and '()_./:? are directly encoded. string UniCodeString = "\u0061\u007A\u0041\u005A\u0030\u0039\u0027\u003F"; byte[] UTF7Bytes = null; UTF7Encoding UTF7enc = new UTF7Encoding (); UTF7Bytes = UTF7enc.GetBytes (UniCodeString); Assertion.AssertEquals ("UTF7 #1", 0x61, UTF7Bytes [0]); Assertion.AssertEquals ("UTF7 #2", 0x7A, UTF7Bytes [1]); Assertion.AssertEquals ("UTF7 #3", 0x41, UTF7Bytes [2]); Assertion.AssertEquals ("UTF7 #4", 0x5A, UTF7Bytes [3]); Assertion.AssertEquals ("UTF7 #5", 0x30, UTF7Bytes [4]); Assertion.AssertEquals ("UTF7 #6", 0x39, UTF7Bytes [5]); Assertion.AssertEquals ("UTF7 #7", 0x27, UTF7Bytes [6]); Assertion.AssertEquals ("UTF7 #8", 0x3F, UTF7Bytes [7]); } [Test] public void TestDirectlyEncoded2() { // Unicode characters a-z, A-Z, 0-9 and '()_./:? are directly encoded. string UniCodeString = "\u0061\u007A\u0041\u005A\u0030\u0039\u0027\u003F"; byte[] UTF7Bytes = new byte [8]; int Length = UniCodeString.Length; UTF7Encoding UTF7enc = new UTF7Encoding (); int Cnt = UTF7enc.GetBytes (UniCodeString.ToCharArray(), 0, Length, UTF7Bytes, 0); Assertion.AssertEquals ("UTF7 #1", 0x61, UTF7Bytes [0]); Assertion.AssertEquals ("UTF7 #2", 0x7A, UTF7Bytes [1]); Assertion.AssertEquals ("UTF7 #3", 0x41, UTF7Bytes [2]); Assertion.AssertEquals ("UTF7 #4", 0x5A, UTF7Bytes [3]); Assertion.AssertEquals ("UTF7 #5", 0x30, UTF7Bytes [4]); Assertion.AssertEquals ("UTF7 #6", 0x39, UTF7Bytes [5]); Assertion.AssertEquals ("UTF7 #7", 0x27, UTF7Bytes [6]); Assertion.AssertEquals ("UTF7 #8", 0x3F, UTF7Bytes [7]); } [Test] public void TestEncodeOptionalEncoded() { string UniCodeString = "\u0021\u0026\u002A\u003B"; byte[] UTF7Bytes = null; //Optional Characters are allowed. UTF7Encoding UTF7enc = new UTF7Encoding (true); UTF7Bytes = UTF7enc.GetBytes (UniCodeString); Assertion.AssertEquals ("UTF7 #1", 0x21, UTF7Bytes [0]); Assertion.AssertEquals ("UTF7 #2", 0x26, UTF7Bytes [1]); Assertion.AssertEquals ("UTF7 #3", 0x2A, UTF7Bytes [2]); Assertion.AssertEquals ("UTF7 #4", 0x3B, UTF7Bytes [3]); //Optional characters are not allowed. UTF7enc = new UTF7Encoding (false); UTF7Bytes = UTF7enc.GetBytes (UniCodeString); Assertion.AssertEquals ("UTF7 #5", 0x2B, UTF7Bytes [0]); Assertion.AssertEquals ("UTF7 #6", 0x41, UTF7Bytes [1]); Assertion.AssertEquals ("UTF7 #7", 0x43, UTF7Bytes [2]); Assertion.AssertEquals ("UTF7 #8", 0x45, UTF7Bytes [3]); Assertion.AssertEquals ("UTF7 #6", 0x41, UTF7Bytes [1]); } [Test] public void TestEncodeUnicodeShifted1() { string UniCodeString = "\u0041\u2262\u0391\u002E"; byte[] UTF7Bytes = null; UTF7Encoding UTF7enc = new UTF7Encoding(); UTF7Bytes = UTF7enc.GetBytes (UniCodeString); //"A<NOT IDENTICAL TO><ALPHA>." is encoded as A+ImIDkQ-. see RFC 1642 Assertion.AssertEquals ("UTF7 #1", 0x41, UTF7Bytes [0]); Assertion.AssertEquals ("UTF7 #2", 0x2B, UTF7Bytes [1]); Assertion.AssertEquals ("UTF7 #3", 0x49, UTF7Bytes [2]); Assertion.AssertEquals ("UTF7 #4", 0x6D, UTF7Bytes [3]); Assertion.AssertEquals ("UTF7 #5", 0x49, UTF7Bytes [4]); Assertion.AssertEquals ("UTF7 #6", 0x44, UTF7Bytes [5]); Assertion.AssertEquals ("UTF7 #7", 0x6B, UTF7Bytes [6]); Assertion.AssertEquals ("UTF7 #8", 0x51, UTF7Bytes [7]); Assertion.AssertEquals ("UTF7 #9", 0x2D, UTF7Bytes [8]); Assertion.AssertEquals ("UTF7 #10", 0x2E, UTF7Bytes [9]); } [Test] public void TestEncodeUnicodeShifted2() { string UniCodeString = "\u0041\u2262\u0391\u002E"; byte[] UTF7Bytes = new byte [10]; int Length = UniCodeString.Length; UTF7Encoding UTF7enc = new UTF7Encoding (); int Cnt = UTF7enc.GetBytes (UniCodeString.ToCharArray(), 0, Length, UTF7Bytes, 0); //"A<NOT IDENTICAL TO><ALPHA>." is encoded as A+ImIDkQ-. see RFC 1642 Assertion.AssertEquals ("UTF7 #1", 0x41, UTF7Bytes [0]); Assertion.AssertEquals ("UTF7 #2", 0x2B, UTF7Bytes [1]); Assertion.AssertEquals ("UTF7 #3", 0x49, UTF7Bytes [2]); Assertion.AssertEquals ("UTF7 #4", 0x6D, UTF7Bytes [3]); Assertion.AssertEquals ("UTF7 #5", 0x49, UTF7Bytes [4]); Assertion.AssertEquals ("UTF7 #6", 0x44, UTF7Bytes [5]); Assertion.AssertEquals ("UTF7 #7", 0x6B, UTF7Bytes [6]); Assertion.AssertEquals ("UTF7 #8", 0x51, UTF7Bytes [7]); Assertion.AssertEquals ("UTF7 #9", 0x2D, UTF7Bytes [8]); Assertion.AssertEquals ("UTF7 #10", 0x2E, UTF7Bytes [9]); } [Test] public void RFC1642_Example1 () { string UniCodeString = "\u0041\u2262\u0391\u002E"; char[] expected = UniCodeString.ToCharArray (); byte[] UTF7Bytes = new byte [] {0x41, 0x2B, 0x49, 0x6D, 0x49, 0x44, 0x6B, 0x51, 0x2D, 0x2E}; UTF7Encoding UTF7enc = new UTF7Encoding (); char[] actual = UTF7enc.GetChars (UTF7Bytes); // "A+ImIDkQ-." is decoded as "A<NOT IDENTICAL TO><ALPHA>." see RFC 1642 AssertEquals ("UTF #1", expected [0], actual [0]); AssertEquals ("UTF #2", expected [1], actual [1]); AssertEquals ("UTF #3", expected [2], actual [2]); AssertEquals ("UTF #4", expected [3], actual [3]); AssertEquals ("GetString", UniCodeString, UTF7enc.GetString (UTF7Bytes)); } [Test] public void RFC1642_Example2 () { string UniCodeString = "\u0048\u0069\u0020\u004D\u006F\u004D\u0020\u263A\u0021"; char[] expected = UniCodeString.ToCharArray (); byte[] UTF7Bytes = new byte[] { 0x48, 0x69, 0x20, 0x4D, 0x6F, 0x4D, 0x20, 0x2B, 0x4A, 0x6A, 0x6F, 0x41, 0x49, 0x51, 0x2D }; UTF7Encoding UTF7enc = new UTF7Encoding (); char[] actual = UTF7enc.GetChars (UTF7Bytes); // "Hi Mom +Jjo-!" is decoded as "Hi Mom <WHITE SMILING FACE>!" AssertEquals ("UTF #1", expected [0], actual [0]); AssertEquals ("UTF #2", expected [1], actual [1]); AssertEquals ("UTF #3", expected [2], actual [2]); AssertEquals ("UTF #4", expected [3], actual [3]); AssertEquals ("UTF #5", expected [4], actual [4]); AssertEquals ("UTF #6", expected [5], actual [5]); AssertEquals ("UTF #7", expected [6], actual [6]); AssertEquals ("UTF #8", expected [7], actual [7]); AssertEquals ("UTF #9", expected [8], actual [8]); AssertEquals ("GetString", UniCodeString, UTF7enc.GetString (UTF7Bytes)); } [Test] public void RFC1642_Example3 () { string UniCodeString = "\u65E5\u672C\u8A9E"; char[] expected = UniCodeString.ToCharArray (); byte[] UTF7Bytes = new byte[] { 0x2B, 0x5A, 0x65, 0x56, 0x6E, 0x4C, 0x49, 0x71, 0x65, 0x2D }; UTF7Encoding UTF7enc = new UTF7Encoding (); char[] actual = UTF7enc.GetChars (UTF7Bytes); // "+ZeVnLIqe-" is decoded as Japanese "nihongo" AssertEquals ("UTF #1", expected [0], actual [0]); AssertEquals ("UTF #2", expected [1], actual [1]); AssertEquals ("UTF #3", expected [2], actual [2]); AssertEquals ("GetString", UniCodeString, UTF7enc.GetString (UTF7Bytes)); } [Test] public void RFC1642_Example4 () { string UniCodeString = "\u0049\u0074\u0065\u006D\u0020\u0033\u0020\u0069\u0073\u0020\u00A3\u0031\u002E"; char[] expected = UniCodeString.ToCharArray (); byte[] UTF7Bytes = new byte[] { 0x49, 0x74, 0x65, 0x6D, 0x20, 0x33, 0x20, 0x69, 0x73, 0x20, 0x2B, 0x41, 0x4B, 0x4D, 0x2D, 0x31, 0x2E }; UTF7Encoding UTF7enc = new UTF7Encoding (); char[] actual = UTF7enc.GetChars (UTF7Bytes); // "Item 3 is +AKM-1." is decoded as "Item 3 is <POUND SIGN>1." AssertEquals ("UTF #1", expected [0], actual [0]); AssertEquals ("UTF #2", expected [1], actual [1]); AssertEquals ("UTF #3", expected [2], actual [2]); AssertEquals ("UTF #4", expected [3], actual [3]); AssertEquals ("UTF #5", expected [4], actual [4]); AssertEquals ("UTF #6", expected [5], actual [5]); AssertEquals ("UTF #7", expected [6], actual [6]); AssertEquals ("UTF #8", expected [7], actual [7]); AssertEquals ("UTF #9", expected [8], actual [8]); AssertEquals ("UTF #10", expected [9], actual [9]); AssertEquals ("UTF #11", expected [10], actual [10]); AssertEquals ("UTF #12", expected [11], actual [11]); AssertEquals ("UTF #13", expected [12], actual [12]); AssertEquals ("GetString", UniCodeString, UTF7enc.GetString (UTF7Bytes)); } [Test] public void TestMaxCharCount() { UTF7Encoding UTF7enc = new UTF7Encoding (); Assertion.AssertEquals ("UTF #1", 50, UTF7enc.GetMaxCharCount(50)); } [Test] public void TestMaxByteCount() { UTF7Encoding UTF7enc = new UTF7Encoding (); Assertion.AssertEquals ("UTF #1", 136, UTF7enc.GetMaxByteCount(50)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; namespace System.IO { public static partial class Path { public static char[] GetInvalidFileNameChars() => new char[] { '\0', '/' }; public static char[] GetInvalidPathChars() => new char[] { '\0' }; internal static int MaxPath => Interop.Sys.MaxPath; // Expands the given path to a fully qualified path. public static string GetFullPath(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Arg_PathEmpty, nameof(path)); PathInternal.CheckInvalidPathChars(path); // Expand with current directory if necessary if (!IsPathRooted(path)) { path = Combine(Interop.Sys.GetCwd(), path); } // We would ideally use realpath to do this, but it resolves symlinks, requires that the file actually exist, // and turns it into a full path, which we only want if fullCheck is true. string collapsedString = RemoveRelativeSegments(path); Debug.Assert(collapsedString.Length < path.Length || collapsedString.ToString() == path, "Either we've removed characters, or the string should be unmodified from the input path."); string result = collapsedString.Length == 0 ? PathInternal.DirectorySeparatorCharAsString : collapsedString; return result; } /// <summary> /// Try to remove relative segments from the given path (without combining with a root). /// </summary> /// <param name="skip">Skip the specified number of characters before evaluating.</param> private static string RemoveRelativeSegments(string path, int skip = 0) { bool flippedSeparator = false; // Remove "//", "/./", and "/../" from the path by copying each character to the output, // except the ones we're removing, such that the builder contains the normalized path // at the end. var sb = StringBuilderCache.Acquire(path.Length); if (skip > 0) { sb.Append(path, 0, skip); } for (int i = skip; i < path.Length; i++) { char c = path[i]; if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length) { // Skip this character if it's a directory separator and if the next character is, too, // e.g. "parent//child" => "parent/child" if (PathInternal.IsDirectorySeparator(path[i + 1])) { continue; } // Skip this character and the next if it's referring to the current directory, // e.g. "parent/./child" =? "parent/child" if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) && path[i + 1] == '.') { i++; continue; } // Skip this character and the next two if it's referring to the parent directory, // e.g. "parent/child/../grandchild" => "parent/grandchild" if (i + 2 < path.Length && (i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) && path[i + 1] == '.' && path[i + 2] == '.') { // Unwind back to the last slash (and if there isn't one, clear out everything). int s; for (s = sb.Length - 1; s >= 0; s--) { if (PathInternal.IsDirectorySeparator(sb[s])) { sb.Length = s; break; } } if (s < 0) { sb.Length = 0; } i += 2; continue; } } // Normalize the directory separator if needed if (c != PathInternal.DirectorySeparatorChar && c == PathInternal.AltDirectorySeparatorChar) { c = PathInternal.DirectorySeparatorChar; flippedSeparator = true; } sb.Append(c); } if (flippedSeparator || sb.Length != path.Length) { return StringBuilderCache.GetStringAndRelease(sb); } else { // We haven't changed the source path, return the original StringBuilderCache.Release(sb); return path; } } private static string RemoveLongPathPrefix(string path) { return path; // nop. There's nothing special about "long" paths on Unix. } public static string GetTempPath() { const string TempEnvVar = "TMPDIR"; const string DefaultTempPath = "/tmp/"; // Get the temp path from the TMPDIR environment variable. // If it's not set, just return the default path. // If it is, return it, ensuring it ends with a slash. string path = Environment.GetEnvironmentVariable(TempEnvVar); return string.IsNullOrEmpty(path) ? DefaultTempPath : PathInternal.IsDirectorySeparator(path[path.Length - 1]) ? path : path + PathInternal.DirectorySeparatorChar; } public static string GetTempFileName() { const string Suffix = ".tmp"; const int SuffixByteLength = 4; // mkstemps takes a char* and overwrites the XXXXXX with six characters // that'll result in a unique file name. string template = GetTempPath() + "tmpXXXXXX" + Suffix + "\0"; byte[] name = Encoding.UTF8.GetBytes(template); // Create, open, and close the temp file. IntPtr fd = Interop.CheckIo(Interop.Sys.MksTemps(name, SuffixByteLength)); Interop.Sys.Close(fd); // ignore any errors from close; nothing to do if cleanup isn't possible // 'name' is now the name of the file Debug.Assert(name[name.Length - 1] == '\0'); return Encoding.UTF8.GetString(name, 0, name.Length - 1); // trim off the trailing '\0' } public static bool IsPathRooted(string path) { if (path == null) return false; PathInternal.CheckInvalidPathChars(path); return path.Length > 0 && path[0] == PathInternal.DirectorySeparatorChar; } // The resulting string is null if path is null. If the path is empty or // only contains whitespace characters an ArgumentException gets thrown. public static string GetPathRoot(string path) { if (path == null) return null; if (PathInternal.IsEffectivelyEmpty(path)) throw new ArgumentException(SR.Arg_PathEmpty, nameof(path)); return IsPathRooted(path) ? PathInternal.DirectorySeparatorCharAsString : String.Empty; } /// <summary>Gets whether the system is case-sensitive.</summary> internal static bool IsCaseSensitive { get { #if PLATFORM_OSX return false; #else return true; #endif } } } }
#region License // Copyright (c) Nick Hao http://www.cnblogs.com/haoxinyue // // 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 #region License // Copyright (c) nick hao // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; using System.Collections.Concurrent; namespace Octopus.Common.Communication.Tcp { public class TcpServer : ITcpListener, IDisposable { private Socket _serverSocket; private int port; private Action<TcpConnectionInfo, byte[]> dataReceived; private Action<TcpConnectionInfo> clientConnected; private Action<TcpConnectionInfo, Exception> clientDisconnected; protected bool _isDisposed = false; public TcpServer(int port, Action<TcpConnectionInfo, byte[]> dataReceived, Action<TcpConnectionInfo> clientConnected, Action<TcpConnectionInfo, Exception> clientDisconnected) { this.port = port; this.dataReceived = dataReceived; this.clientConnected = clientConnected; this.clientDisconnected = clientDisconnected; } private ConcurrentDictionary<string, TcpConnectionInfo> _connections = new ConcurrentDictionary<string, TcpConnectionInfo>(); private void SetupServerSocket() { IPEndPoint myEndpoint = new IPEndPoint(IPAddress.Any, port); _serverSocket = new Socket(myEndpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _serverSocket.Bind(myEndpoint); _serverSocket.Listen((int)SocketOptionName.MaxConnections); } public void Start() { SetupServerSocket(); IsWorking = true; _serverSocket.BeginAccept( new AsyncCallback(AcceptCallback), _serverSocket); } private void AcceptCallback(IAsyncResult result) { TcpConnectionInfo connection = new TcpConnectionInfo(); try { Socket s = (Socket)result.AsyncState; connection.Socket = s.EndAccept(result); connection.Buffer = new byte[255]; connection.RemoteAddress = connection.Socket.RemoteEndPoint.ToString(); connection.RemoteEndPoint = (IPEndPoint)connection.Socket.RemoteEndPoint; _connections[((IPEndPoint)connection.Socket.RemoteEndPoint).Address.ToString()] = connection; if (clientConnected != null) { clientConnected(connection); } connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), connection); _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), result.AsyncState); } catch (SocketException e) { CloseConnection(connection, e); } catch (ObjectDisposedException) { } catch (Exception ex) { CloseConnection(connection, ex); } } private void ReceiveCallback(IAsyncResult result) { TcpConnectionInfo connection = (TcpConnectionInfo)result.AsyncState; try { int bytesRead = connection.Socket.EndReceive(result); if (0 != bytesRead) { if (dataReceived != null) { byte[] data = new byte[bytesRead]; Buffer.BlockCopy(connection.Buffer, 0, data, 0, bytesRead); dataReceived(connection, data); } connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), connection); } else { CloseConnection(connection, null); } } catch (SocketException e) { CloseConnection(connection, e); } catch (ObjectDisposedException) { } catch (Exception ex) { CloseConnection(connection, ex); } } private void CloseConnection(TcpConnectionInfo ci, Exception ex) { if (ci != null && ci.Socket != null) { try { TcpConnectionInfo removed = null; _connections.TryRemove(ci.RemoteEndPoint.Address.ToString(), out removed); ci.Socket.Close(); } catch { } if (clientDisconnected != null) { clientDisconnected(ci, ex); } } } public int GetClientCount() { return _connections.Count; } public void Stop() { try { if (_serverSocket != null) { try { _serverSocket.Close(); } catch { } } foreach (var item in _connections) { CloseConnection(item.Value, null); } _connections.Clear(); IsWorking = false; } catch { } } public bool IsWorking { get; set; } public void Send(IPEndPoint endPoint, byte[] data) { if (endPoint != null) { if (_connections.ContainsKey(endPoint.Address.ToString())) { TcpConnectionInfo connection = _connections[endPoint.Address.ToString()]; try { connection.Socket.Send(data); } catch (SocketException e) { CloseConnection(connection, e); } catch (ObjectDisposedException) { } catch (Exception) { } } } else { foreach (var connection in _connections) { try { connection.Value.Socket.Send(data); } catch (SocketException e) { CloseConnection(connection.Value, e); } catch (ObjectDisposedException) { } catch (Exception) { } } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool diposing) { if (!_isDisposed) { if (diposing) { Stop(); } } _isDisposed = true; } } }
using System.IO; using System.Text; using Elasticsearch.Net.Tests.Unit.Responses.Helpers; using Elasticsearch.Net.Tests.Unit.Stubs; using FluentAssertions; using NUnit.Framework; namespace Elasticsearch.Net.Tests.Unit.Responses { [TestFixture] public class BuildInResponseTests { [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void Typed_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<StandardResponse>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); object v = r.Response.value; v.ShouldBeEquivalentTo(responseValue); r.ResponseRaw.Should().BeNull(); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void Typed_Ok_KeepResponse(object responseValue) { using (var request = new Requester<StandardResponse>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); object v = r.Response.value; v.ShouldBeEquivalentTo(responseValue); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void Typed_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<StandardResponse>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); Assert.IsNull(r.Response); r.ResponseRaw.Should().BeNull(); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void Typed_Bad_KeepResponse(object responseValue) { using (var request = new Requester<StandardResponse>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); Assert.IsNull(r.Response); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void DynamicDictionary_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<DynamicDictionary>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream), client => client.Info() )) { var r = request.Result; r.Success.Should().BeTrue(); object v = r.Response["value"]; v.ShouldBeEquivalentTo(responseValue); r.ResponseRaw.Should().BeNull(); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void DynamicDictionary_Ok_KeepResponse(object responseValue) { using (var request = new Requester<DynamicDictionary>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream), client => client.Info() )) { var r = request.Result; r.Success.Should().BeTrue(); object v = r.Response["value"]; v.ShouldBeEquivalentTo(responseValue); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void DynamicDictionary_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<DynamicDictionary>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream), client => client.Info() )) { var r = request.Result; r.Success.Should().BeFalse(); Assert.IsNull(r.Response); r.ResponseRaw.Should().BeNull(); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void DynamicDictionary_Bad_KeepResponse(object responseValue) { using (var request = new Requester<DynamicDictionary>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream), client => client.Info() )) { var r = request.Result; r.Success.Should().BeFalse(); Assert.IsNull(r.Response); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test, TestCase(505123)] public void ByteArray_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<byte[]>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void ByteArray_Ok_KeepResponse(object responseValue) { using (var request = new Requester<byte[]>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test, TestCase(505123)] public void ByteArray_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<byte[]>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void ByteArray_Bad_KeepResponse(object responseValue) { using (var request = new Requester<byte[]>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test, TestCase(505123)] public void String_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<string>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void String_Ok_KeepResponse(object responseValue) { using (var request = new Requester<string>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test, TestCase(505123)] public void String_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<string>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void String_Bad_KeepResponse(object responseValue) { using (var request = new Requester<string>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test, TestCase(505123)] public void Stream_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<Stream>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); using (r.Response) using (var ms = new MemoryStream()) { r.Response.CopyTo(ms); var bytes = ms.ToArray(); bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void Stream_Ok_KeepResponse(object responseValue) { using (var request = new Requester<Stream>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); using (r.Response) using (var ms = new MemoryStream()) { r.Response.CopyTo(ms); var bytes = ms.ToArray(); bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } //raw response is ALWAYS null when requesting the stream directly //the client should not interfere with it r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void Stream_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<Stream>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); using (r.Response) using (var ms = new MemoryStream()) { r.Response.CopyTo(ms); var bytes = ms.ToArray(); bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void Stream_Bad_KeepResponse(object responseValue) { using (var request = new Requester<Stream>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); using (r.Response) using (var ms = new MemoryStream()) { r.Response.CopyTo(ms); var bytes = ms.ToArray(); bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } //raw response is ALWAYS null when requesting the stream directly //the client should not interfere with it r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void VoidResponse_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<VoidResponse>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); //Response and rawresponse should ALWAYS be null for VoidResponse responses r.Response.Should().BeNull(); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void VoidResponse_Ok_KeepResponse(object responseValue) { using (var request = new Requester<VoidResponse>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); //Response and rawresponse should ALWAYS be null for VoidResponse responses r.Response.Should().BeNull(); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void VoidResponse_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<VoidResponse>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); //Response and rawresponse should ALWAYS be null for VoidResponse responses r.Response.Should().BeNull(); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void VoidResponse_Bad_KeepResponse(object responseValue) { using (var request = new Requester<VoidResponse>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); //Response and rawresponse should ALWAYS be null for VoidResponse responses r.Response.Should().BeNull(); r.ResponseRaw.Should().BeNull(); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Facility.Definition; using Facility.Definition.CodeGen; using Facility.Definition.Http; namespace Facility.CodeGen.JavaScript { /// <summary> /// Generates JavaScript and TypeScript. /// </summary> public sealed class JavaScriptGenerator : CodeGenerator { /// <summary> /// Generates JavaScript/TypeScript. /// </summary> /// <param name="settings">The settings.</param> /// <returns>The number of updated files.</returns> public static int GenerateJavaScript(JavaScriptGeneratorSettings settings) => FileGenerator.GenerateFiles(new JavaScriptGenerator { GeneratorName = nameof(JavaScriptGenerator) }, settings); /// <summary> /// The name of the module (optional). /// </summary> public string? ModuleName { get; set; } /// <summary> /// True to generate TypeScript. /// </summary> public bool TypeScript { get; set; } /// <summary> /// True to generate Express service. /// </summary> public bool Express { get; set; } /// <summary> /// True to disable ESLint via code comment. /// </summary> public bool DisableESLint { get; set; } /// <summary> /// Generates the JavaScript/TypeScript output. /// </summary> public override CodeGenOutput GenerateOutput(ServiceInfo service) { var httpServiceInfo = HttpServiceInfo.Create(service); var moduleName = ModuleName ?? service.Name; var capModuleName = CodeGenUtility.Capitalize(moduleName); var typesFileName = CodeGenUtility.Uncapitalize(moduleName) + "Types" + (TypeScript ? ".ts" : ".js"); var clientFileName = CodeGenUtility.Uncapitalize(moduleName) + (TypeScript ? ".ts" : ".js"); var serverFileName = CodeGenUtility.Uncapitalize(moduleName) + "Server" + (TypeScript ? ".ts" : ".js"); var namedTexts = new List<CodeGenFile>(); var typeNames = new List<string>(); if (TypeScript) { namedTexts.Add(CreateFile(typesFileName, code => { WriteFileHeader(code); var allFields = service.Dtos.SelectMany(x => x.Fields).Concat(service.Methods.SelectMany(x => x.RequestFields.Concat(x.ResponseFields))).ToList(); code.WriteLine(); var facilityImports = new List<string>(); if (httpServiceInfo.Methods.Any() || allFields.Any(x => FieldUsesKind(service, x, ServiceTypeKind.Result))) facilityImports.Add("IServiceResult"); if (allFields.Any(x => FieldUsesKind(service, x, ServiceTypeKind.Error))) facilityImports.Add("IServiceError"); WriteImports(code, facilityImports, "facility-core"); code.WriteLine(); WriteJsDoc(code, service); typeNames.Add($"I{capModuleName}"); using (code.Block($"export interface I{capModuleName} {{", "}")) { foreach (var httpMethodInfo in httpServiceInfo.Methods) { var methodName = httpMethodInfo.ServiceMethod.Name; var capMethodName = CodeGenUtility.Capitalize(methodName); code.WriteLineSkipOnce(); WriteJsDoc(code, httpMethodInfo.ServiceMethod); code.WriteLine($"{methodName}(request: I{capMethodName}Request, context?: unknown): Promise<IServiceResult<I{capMethodName}Response>>;"); } } foreach (var methodInfo in service.Methods) { var requestDtoName = $"{CodeGenUtility.Capitalize(methodInfo.Name)}Request"; typeNames.Add($"I{requestDtoName}"); WriteDto(code, new ServiceDtoInfo( name: requestDtoName, fields: methodInfo.RequestFields, summary: $"Request for {CodeGenUtility.Capitalize(methodInfo.Name)}."), service); var responseDtoName = $"{CodeGenUtility.Capitalize(methodInfo.Name)}Response"; typeNames.Add($"I{responseDtoName}"); WriteDto(code, new ServiceDtoInfo( name: responseDtoName, fields: methodInfo.ResponseFields, summary: $"Response for {CodeGenUtility.Capitalize(methodInfo.Name)}."), service); } foreach (var dtoInfo in service.Dtos) { typeNames.Add($"I{dtoInfo.Name}"); WriteDto(code, dtoInfo, service); } foreach (var enumInfo in service.Enums) { typeNames.Add(enumInfo.Name); code.WriteLine(); WriteJsDoc(code, enumInfo); using (code.Block($"export enum {enumInfo.Name} {{", "}")) { foreach (var value in enumInfo.Values) { code.WriteLineSkipOnce(); WriteJsDoc(code, value); code.WriteLine($"{value.Name} = '{value.Name}',"); } } } code.WriteLine(); })); } namedTexts.Add(CreateFile(clientFileName, code => { WriteFileHeader(code); if (!TypeScript) code.WriteLine("'use strict';"); code.WriteLine(); var facilityImports = new List<string> { "HttpClientUtility" }; if (TypeScript) { if (httpServiceInfo.Methods.Any()) facilityImports.Add("IServiceResult"); facilityImports.Add("IHttpClientOptions"); } WriteImports(code, facilityImports, "facility-core"); if (TypeScript) { WriteImports(code, typeNames, $"./{CodeGenUtility.Uncapitalize(moduleName)}Types"); code.WriteLine($"export * from './{CodeGenUtility.Uncapitalize(moduleName)}Types';"); } code.WriteLine(); WriteJsDoc(code, $"Provides access to {capModuleName} over HTTP via fetch."); using (code.Block("export function createHttpClient({ fetch, baseUri }" + IfTypeScript(": IHttpClientOptions") + ")" + IfTypeScript($": I{capModuleName}") + " {", "}")) code.WriteLine($"return new {capModuleName}HttpClient(fetch, baseUri);"); code.WriteLine(); code.WriteLine("const { fetchResponse, createResponseError, createRequiredRequestFieldError } = HttpClientUtility;"); if (TypeScript) { code.WriteLine("type IFetch = HttpClientUtility.IFetch;"); code.WriteLine("type IFetchRequest = HttpClientUtility.IFetchRequest;"); } code.WriteLine(); using (code.Block($"class {capModuleName}HttpClient" + IfTypeScript($" implements I{capModuleName}") + " {", "}")) { using (code.Block("constructor(fetch" + IfTypeScript(": IFetch") + ", baseUri" + IfTypeScript("?: string") + ") {", "}")) { using (code.Block("if (typeof fetch !== 'function') {", "}")) code.WriteLine("throw new TypeError('fetch must be a function.');"); using (code.Block("if (typeof baseUri === 'undefined') {", "}")) code.WriteLine($"baseUri = '{httpServiceInfo.Url ?? ""}';"); using (code.Block(@"if (/[^\/]$/.test(baseUri)) {", "}")) code.WriteLine("baseUri += '/';"); code.WriteLine("this._fetch = fetch;"); code.WriteLine("this._baseUri = baseUri;"); } foreach (var httpMethodInfo in httpServiceInfo.Methods) { var methodName = httpMethodInfo.ServiceMethod.Name; var capMethodName = CodeGenUtility.Capitalize(methodName); code.WriteLine(); WriteJsDoc(code, httpMethodInfo.ServiceMethod); using (code.Block(IfTypeScript("public ") + $"{methodName}(request" + IfTypeScript($": I{capMethodName}Request") + ", context" + IfTypeScript("?: unknown") + ")" + IfTypeScript($": Promise<IServiceResult<I{capMethodName}Response>>") + " {", "}")) { var hasPathFields = httpMethodInfo.PathFields.Count != 0; var jsUriDelim = hasPathFields ? "`" : "'"; var jsUri = jsUriDelim + httpMethodInfo.Path.Substring(1) + jsUriDelim; if (hasPathFields) { foreach (var httpPathField in httpMethodInfo.PathFields) { code.WriteLine($"const uriPart{CodeGenUtility.Capitalize(httpPathField.ServiceField.Name)} = request.{httpPathField.ServiceField.Name} != null && {RenderUriComponent(httpPathField.ServiceField, service)};"); using (code.Block($"if (!uriPart{CodeGenUtility.Capitalize(httpPathField.ServiceField.Name)}) {{", "}")) code.WriteLine($"return Promise.resolve(createRequiredRequestFieldError('{httpPathField.ServiceField.Name}'));"); } foreach (var httpPathField in httpMethodInfo.PathFields) jsUri = jsUri.Replace("{" + httpPathField.Name + "}", $"${{uriPart{CodeGenUtility.Capitalize(httpPathField.ServiceField.Name)}}}"); } var hasQueryFields = httpMethodInfo.QueryFields.Count != 0; code.WriteLine((hasQueryFields ? "let" : "const") + $" uri = {jsUri};"); if (hasQueryFields) { code.WriteLine("const query" + IfTypeScript(": string[]") + " = [];"); foreach (var httpQueryField in httpMethodInfo.QueryFields) code.WriteLine($"request.{httpQueryField.ServiceField.Name} == null || query.push('{httpQueryField.Name}=' + {RenderUriComponent(httpQueryField.ServiceField, service)});"); using (code.Block("if (query.length) {", "}")) code.WriteLine("uri = uri + '?' + query.join('&');"); } using (code.Block("const fetchRequest" + IfTypeScript(": IFetchRequest") + " = {", "};")) { if (httpMethodInfo.RequestBodyField == null && httpMethodInfo.RequestNormalFields.Count == 0) { code.WriteLine($"method: '{httpMethodInfo.Method}',"); if (httpMethodInfo.RequestHeaderFields.Count != 0) code.WriteLine("headers: {},"); } else { code.WriteLine($"method: '{httpMethodInfo.Method}',"); code.WriteLine("headers: { 'Content-Type': 'application/json' },"); if (httpMethodInfo.RequestBodyField != null) { code.WriteLine($"body: JSON.stringify(request.{httpMethodInfo.RequestBodyField.ServiceField.Name})"); } else if (httpMethodInfo.ServiceMethod.RequestFields.Count == httpMethodInfo.RequestNormalFields.Count) { code.WriteLine("body: JSON.stringify(request)"); } else { using (code.Block("body: JSON.stringify({", "})")) { for (var httpFieldIndex = 0; httpFieldIndex < httpMethodInfo.RequestNormalFields.Count; httpFieldIndex++) { var httpFieldInfo = httpMethodInfo.RequestNormalFields[httpFieldIndex]; var isLastField = httpFieldIndex == httpMethodInfo.RequestNormalFields.Count - 1; var fieldName = httpFieldInfo.ServiceField.Name; code.WriteLine(fieldName + ": request." + fieldName + (isLastField ? "" : ",")); } } } } } if (httpMethodInfo.RequestHeaderFields.Count != 0) { foreach (var httpHeaderField in httpMethodInfo.RequestHeaderFields) { using (code.Block($"if (request.{httpHeaderField.ServiceField.Name} != null) {{", "}")) code.WriteLine("fetchRequest.headers" + IfTypeScript("!") + $"['{httpHeaderField.Name}'] = request.{httpHeaderField.ServiceField.Name};"); } } code.WriteLine("return fetchResponse(this._fetch, this._baseUri + uri, fetchRequest, context)"); using (code.Indent()) using (code.Block(".then(result => {", "});")) { code.WriteLine("const status = result.response.status;"); var responseValueType = $"I{capMethodName}Response"; code.WriteLine("let value" + IfTypeScript($": {responseValueType} | null") + " = null;"); using (code.Block("if (result.json) {", "}")) { var validResponses = httpMethodInfo.ValidResponses; var elsePrefix = ""; foreach (var validResponse in validResponses) { var statusCodeAsString = ((int) validResponse.StatusCode).ToString(CultureInfo.InvariantCulture); code.WriteLine($"{elsePrefix}if (status === {statusCodeAsString}) {{"); elsePrefix = "else "; using (code.Indent()) { var bodyField = validResponse.BodyField; if (bodyField != null) { var responseBodyFieldName = bodyField.ServiceField.Name; var bodyFieldType = service.GetFieldType(bodyField.ServiceField)!; if (bodyFieldType.Kind == ServiceTypeKind.Boolean) code.WriteLine($"value = {{ {responseBodyFieldName}: true }};"); else code.WriteLine($"value = {{ {responseBodyFieldName}: result.json }}" + IfTypeScript($" as {responseValueType}") + ";"); } else { if (validResponse.NormalFields!.Count == 0) code.WriteLine("value = {};"); else code.WriteLine("value = result.json" + IfTypeScript($" as {responseValueType} | null") + ";"); } } code.WriteLine("}"); } } using (code.Block("if (!value) {", "}")) code.WriteLine("return createResponseError(status, result.json)" + IfTypeScript($" as IServiceResult<I{capMethodName}Response>") + ";"); if (httpMethodInfo.ResponseHeaderFields.Count != 0) { code.WriteLine("let headerValue" + IfTypeScript(": string | null | undefined") + ";"); foreach (var httpHeaderField in httpMethodInfo.ResponseHeaderFields) { code.WriteLine($"headerValue = result.response.headers.get('{httpHeaderField.Name}');"); using (code.Block("if (headerValue != null) {", "}")) code.WriteLine($"value.{httpHeaderField.ServiceField.Name} = headerValue;"); } } code.WriteLine("return { value: value };"); } } } if (TypeScript) { code.WriteLine(); code.WriteLine("private _fetch: IFetch;"); code.WriteLine("private _baseUri: string;"); } } })); if (Express) { namedTexts.Add(CreateFile(serverFileName, code => { WriteFileHeader(code); if (!TypeScript) code.WriteLine("'use strict';"); code.WriteLine(); code.WriteLine("import * as bodyParser from 'body-parser';"); code.WriteLine("import * as express from 'express';"); var facilityImports = new List<string>(); if (TypeScript) facilityImports.Add("IServiceResult"); WriteImports(code, facilityImports, "facility-core"); if (TypeScript) { WriteImports(code, typeNames, $"./{CodeGenUtility.Uncapitalize(moduleName)}Types"); code.WriteLine($"export * from './{CodeGenUtility.Uncapitalize(moduleName)}Types';"); } // TODO: export this from facility-core code.WriteLine(); using (code.Block("const standardErrorCodes" + IfTypeScript(": { [code: string]: number }") + " = {", "};")) { code.WriteLine("'NotModified': 304,"); code.WriteLine("'InvalidRequest': 400,"); code.WriteLine("'NotAuthenticated': 401,"); code.WriteLine("'NotAuthorized': 403,"); code.WriteLine("'NotFound': 404,"); code.WriteLine("'Conflict': 409,"); code.WriteLine("'RequestTooLarge': 413,"); code.WriteLine("'TooManyRequests': 429,"); code.WriteLine("'InternalError': 500,"); code.WriteLine("'ServiceUnavailable': 503,"); } code.WriteLine(); using (code.Block("function parseBoolean(value" + IfTypeScript(": string | undefined") + ") {", "}")) { using (code.Block("if (typeof value === 'string') {", "}")) { code.WriteLine("const lowerValue = value.toLowerCase();"); using (code.Block("if (lowerValue === 'true') {", "}")) code.WriteLine("return true;"); using (code.Block("if (lowerValue === 'false') {", "}")) code.WriteLine("return false;"); } code.WriteLine("return undefined;"); } code.WriteLine(); using (code.Block("export function createApp(service" + IfTypeScript($": I{capModuleName}") + ")" + IfTypeScript(": express.Application") + " {", "}")) { code.WriteLine("const app = express();"); code.WriteLine("app.use(bodyParser.json());"); code.WriteLine("app.use(bodyParser.urlencoded({ extended: true }));"); foreach (var httpMethodInfo in httpServiceInfo.Methods) { var methodName = httpMethodInfo.ServiceMethod.Name; var capMethodName = CodeGenUtility.Capitalize(methodName); var expressMethod = httpMethodInfo.Method.ToLowerInvariant(); var expressPath = httpMethodInfo.Path; foreach (var httpPathField in httpMethodInfo.PathFields) expressPath = expressPath.Replace("{" + httpPathField.Name + "}", $":{httpPathField.Name}"); code.WriteLine(); WriteJsDoc(code, httpMethodInfo.ServiceMethod); using (code.Block($"app.{expressMethod}('{expressPath}', function (req, res, next) {{", "});")) { code.WriteLine("const request" + IfTypeScript($": I{capMethodName}Request") + " = {};"); foreach (var httpPathField in httpMethodInfo.PathFields) code.WriteLine($"request.{httpPathField.ServiceField.Name} = {RenderJsConversion(httpPathField.ServiceField, service, $"req.params.{httpPathField.Name}")};"); foreach (var httpQueryField in httpMethodInfo.QueryFields) { using (code.Block($"if (typeof req.query['{httpQueryField.Name}'] === 'string') {{", "}")) code.WriteLine($"request.{httpQueryField.ServiceField.Name} = {RenderJsConversion(httpQueryField.ServiceField, service, $"req.query['{httpQueryField.Name}']")};"); } if (httpMethodInfo.RequestBodyField != null) { code.WriteLine($"request.{httpMethodInfo.RequestBodyField.ServiceField.Name} = req.body;"); } else { foreach (var field in httpMethodInfo.RequestNormalFields) code.WriteLine($"request.{field.ServiceField.Name} = req.body.{field.ServiceField.Name};"); } foreach (var field in httpMethodInfo.RequestHeaderFields) code.WriteLine($"request.{field.ServiceField.Name} = req.header('{field.Name}');"); code.WriteLine(); code.WriteLine($"return service.{methodName}(request)"); using (code.Indent()) { using (code.Block(".then(result => {", "})")) { using (code.Block("if (result.error) {", "}")) { code.WriteLine("const status = result.error.code && standardErrorCodes[result.error.code] || 500;"); code.WriteLine("res.status(status).send(result.error);"); code.WriteLine("return;"); } using (code.Block("if (result.value) {", "}")) { foreach (var field in httpMethodInfo.ResponseHeaderFields) { using (code.Block($"if (result.value.{field.ServiceField.Name} != null) {{", "}")) code.WriteLine($"res.setHeader('{field.Name}', result.value.{field.ServiceField.Name});"); } foreach (var validResponse in httpMethodInfo.ValidResponses.Where(x => x.NormalFields == null || x.NormalFields.Count == 0)) { var bodyField = validResponse.BodyField; if (bodyField != null) { var responseBodyFieldName = bodyField.ServiceField.Name; using (code.Block($"if (result.value.{responseBodyFieldName}) {{", "}")) { var bodyFieldType = service.GetFieldType(bodyField.ServiceField)!; if (bodyFieldType.Kind == ServiceTypeKind.Boolean) { code.WriteLine($"res.sendStatus({(int) validResponse.StatusCode});"); code.WriteLine("return;"); } else { code.WriteLine($"res.status({(int) validResponse.StatusCode}).send(result.value.{responseBodyFieldName});"); code.WriteLine("return;"); } } } else { if (validResponse.NormalFields!.Count == 0) { code.WriteLine($"res.sendStatus({(int) validResponse.StatusCode});"); code.WriteLine("return;"); } } } foreach (var validResponse in httpMethodInfo.ValidResponses.Where(x => x.NormalFields != null && x.NormalFields.Count != 0)) { code.WriteLine($"res.status({(int) validResponse.StatusCode}).send({{"); using (code.Indent()) { foreach (var field in validResponse.NormalFields!) { code.WriteLine($"{field.ServiceField.Name}: result.value.{field.ServiceField.Name},"); } } code.WriteLine("});"); code.WriteLine("return;"); } } code.WriteLine("throw new Error('Result must have an error or value.');"); } code.WriteLine(".catch(next);"); } } } code.WriteLine(); code.WriteLine("return app;"); } })); } return new CodeGenOutput(namedTexts, new List<CodeGenPattern>()); } /// <summary> /// Applies generator-specific settings. /// </summary> public override void ApplySettings(FileGeneratorSettings settings) { var ourSettings = (JavaScriptGeneratorSettings) settings; ModuleName = ourSettings.ModuleName; TypeScript = ourSettings.TypeScript; Express = ourSettings.Express; DisableESLint = ourSettings.DisableESLint; } /// <summary> /// Supports writing output to a single file. /// </summary> public override bool SupportsSingleOutput => true; private void WriteFileHeader(CodeWriter code) { code.WriteLine($"// DO NOT EDIT: generated by {GeneratorName}"); if (DisableESLint) code.WriteLine("/* eslint-disable */"); } private static void WriteDto(CodeWriter code, ServiceDtoInfo dtoInfo, ServiceInfo service) { code.WriteLine(); WriteJsDoc(code, dtoInfo); using (code.Block($"export interface I{CodeGenUtility.Capitalize(dtoInfo.Name)} {{", "}")) { foreach (var fieldInfo in dtoInfo.Fields) { code.WriteLineSkipOnce(); WriteJsDoc(code, fieldInfo); code.WriteLine($"{fieldInfo.Name}?: {RenderFieldType(service.GetFieldType(fieldInfo)!)};"); } } } private string IfTypeScript(string value) => TypeScript ? value : ""; private static string RenderFieldType(ServiceTypeInfo fieldType) { switch (fieldType.Kind) { case ServiceTypeKind.String: case ServiceTypeKind.Bytes: return "string"; case ServiceTypeKind.Enum: return fieldType.Enum!.Name; case ServiceTypeKind.Boolean: return "boolean"; case ServiceTypeKind.Double: case ServiceTypeKind.Int32: case ServiceTypeKind.Int64: case ServiceTypeKind.Decimal: return "number"; case ServiceTypeKind.Object: return "{ [name: string]: any }"; case ServiceTypeKind.Error: return "IServiceError"; case ServiceTypeKind.Dto: return $"I{CodeGenUtility.Capitalize(fieldType.Dto!.Name)}"; case ServiceTypeKind.Result: return $"IServiceResult<{RenderFieldType(fieldType.ValueType!)}>"; case ServiceTypeKind.Array: return $"{RenderFieldType(fieldType.ValueType!)}[]"; case ServiceTypeKind.Map: return $"{{ [name: string]: {RenderFieldType(fieldType.ValueType!)} }}"; default: throw new NotSupportedException("Unknown field type " + fieldType.Kind); } } private static string RenderUriComponent(ServiceFieldInfo field, ServiceInfo service) { var fieldTypeKind = service.GetFieldType(field)!.Kind; var fieldName = field.Name; switch (fieldTypeKind) { case ServiceTypeKind.Enum: return $"request.{fieldName}"; case ServiceTypeKind.String: case ServiceTypeKind.Bytes: return $"encodeURIComponent(request.{fieldName})"; case ServiceTypeKind.Boolean: case ServiceTypeKind.Int32: case ServiceTypeKind.Int64: case ServiceTypeKind.Decimal: return $"request.{fieldName}.toString()"; case ServiceTypeKind.Double: return $"encodeURIComponent(request.{fieldName}.toString())"; case ServiceTypeKind.Dto: case ServiceTypeKind.Error: case ServiceTypeKind.Object: throw new NotSupportedException("Field type not supported on path/query: " + fieldTypeKind); default: throw new NotSupportedException("Unknown field type " + fieldTypeKind); } } private static string RenderJsConversion(ServiceFieldInfo field, ServiceInfo service, string value) { var fieldTypeKind = service.GetFieldType(field)!.Kind; switch (fieldTypeKind) { case ServiceTypeKind.Enum: return $"{value} as {field.TypeName}"; case ServiceTypeKind.String: case ServiceTypeKind.Bytes: return value; case ServiceTypeKind.Boolean: return $"parseBoolean({value})"; case ServiceTypeKind.Int32: case ServiceTypeKind.Int64: return $"parseInt({value}, 10)"; case ServiceTypeKind.Decimal: case ServiceTypeKind.Double: return $"parseFloat({value})"; case ServiceTypeKind.Dto: case ServiceTypeKind.Error: case ServiceTypeKind.Object: throw new NotSupportedException("Field type not supported on path/query: " + fieldTypeKind); default: throw new NotSupportedException("Unknown field type " + fieldTypeKind); } } private static void WriteJsDoc(CodeWriter code, ServiceElementWithAttributesInfo element) => WriteJsDoc(code, (element as IServiceHasSummary)?.Summary, isObsolete: element.IsObsolete, obsoleteMessage: element.ObsoleteMessage); private static void WriteJsDoc(CodeWriter code, string? summary, bool isObsolete = false, string? obsoleteMessage = null) { var lines = new List<string>(capacity: 2); if (summary != null && summary.Trim().Length != 0) lines.Add(summary.Trim()); if (isObsolete) lines.Add("@deprecated" + (string.IsNullOrWhiteSpace(obsoleteMessage) ? "" : $" {obsoleteMessage}")); WriteJsDoc(code, lines); } private static void WriteJsDoc(CodeWriter code, IReadOnlyList<string> lines) { if (lines.Count == 1) { code.WriteLine($"/** {lines[0]} */"); } else if (lines.Count != 0) { code.WriteLine("/**"); foreach (var line in lines) code.WriteLine($" * {line}"); code.WriteLine(" */"); } } private static void WriteImports(CodeWriter code, IReadOnlyList<string> imports, string from) { if (imports.Count != 0) code.WriteLine($"import {{ {string.Join(", ", imports)} }} from '{from}';"); } private static bool FieldUsesKind(ServiceInfo service, ServiceFieldInfo field, ServiceTypeKind kind) { var type = service.GetFieldType(field)!; if (type.Kind == kind) return true; var valueType = type; while (true) { if (valueType.ValueType == null) break; valueType = valueType.ValueType; if (valueType.Kind == kind) return true; } return false; } } }
// created on 03/04/2003 at 14:09 // // System.Runtime.Remoting.Channels.SoapMessageFormatter // // Author: Jean-Marc Andre ([email protected]) // // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Reflection; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; namespace System.Runtime.Remoting.Channels { enum RemMessageType { MethodCall, MethodResponse, ServerFault, NotRecognize } internal class SoapMessageFormatter { private static FieldInfo _serverFaultExceptionField; private Type _serverType; private MethodInfo _methodCallInfo; private ParameterInfo[] _methodCallParameters; private string _xmlNamespace; static SoapMessageFormatter() { // Get the ServerFault exception field FieldInfo that // will be used later if an exception occurs on the server MemberInfo[] mi = FormatterServices.GetSerializableMembers(typeof(ServerFault), new StreamingContext(StreamingContextStates.All)); FieldInfo fi; for(int i = 0; i < mi.Length; i++){ fi = mi[i] as FieldInfo; if(fi != null && fi.FieldType == typeof(Exception)){ _serverFaultExceptionField = fi; } } } internal SoapMessageFormatter() { } internal IMessage FormatFault (SoapFault fault, IMethodCallMessage mcm) { ServerFault sf = fault.Detail as ServerFault; Exception e = null; if (sf != null) { if(_serverFaultExceptionField != null) e = (Exception) _serverFaultExceptionField.GetValue(sf); } if (e == null) e = new RemotingException (fault.FaultString); return new ReturnMessage((System.Exception)e, mcm); } // used by the client internal IMessage FormatResponse(ISoapMessage soapMsg, IMethodCallMessage mcm) { IMessage rtnMsg; if(soapMsg.MethodName == "Fault") { // an exception was thrown by the server Exception e = new SerializationException(); int i = Array.IndexOf(soapMsg.ParamNames, "detail"); if(_serverFaultExceptionField != null) // todo: revue this 'cause it's not safe e = (Exception) _serverFaultExceptionField.GetValue( soapMsg.ParamValues[i]); rtnMsg = new ReturnMessage((System.Exception)e, mcm); } else { object rtnObject = null; //RemMessageType messageType; // Get the output of the function if it is not *void* if(_methodCallInfo.ReturnType != typeof(void)){ int index = Array.IndexOf(soapMsg.ParamNames, "return"); rtnObject = soapMsg.ParamValues[index]; if(rtnObject is IConvertible) rtnObject = Convert.ChangeType( rtnObject, _methodCallInfo.ReturnType); } object[] outParams = new object [_methodCallParameters.Length]; int n=0; // check if there are *out* parameters foreach(ParameterInfo paramInfo in _methodCallParameters) { if(paramInfo.ParameterType.IsByRef || paramInfo.IsOut) { int index = Array.IndexOf(soapMsg.ParamNames, paramInfo.Name); object outParam = soapMsg.ParamValues[index]; if(outParam is IConvertible) outParam = Convert.ChangeType (outParam, paramInfo.ParameterType.GetElementType()); outParams[n] = outParam; } else outParams [n] = null; n++; } Header[] headers = new Header [2 + (soapMsg.Headers != null ? soapMsg.Headers.Length : 0)]; headers [0] = new Header ("__Return", rtnObject); headers [1] = new Header ("__OutArgs", outParams); if (soapMsg.Headers != null) soapMsg.Headers.CopyTo (headers, 2); rtnMsg = new MethodResponse (headers, mcm); } return rtnMsg; } // used by the client internal SoapMessage BuildSoapMessageFromMethodCall( IMethodCallMessage mcm, out ITransportHeaders requestHeaders) { requestHeaders = new TransportHeaders(); SoapMessage soapMsg = new SoapMessage(); GetInfoFromMethodCallMessage(mcm); // Format the SoapMessage that will be used to create the RPC soapMsg.MethodName = mcm.MethodName; //int count = mcm.ArgCount; ArrayList paramNames = new ArrayList(_methodCallParameters.Length); ArrayList paramTypes = new ArrayList(_methodCallParameters.Length); ArrayList paramValues = new ArrayList(_methodCallParameters.Length); // Add the function parameters to the SoapMessage class foreach(ParameterInfo paramInfo in _methodCallParameters) { if (!(paramInfo.IsOut && paramInfo.ParameterType.IsByRef)) { Type t = paramInfo.ParameterType; if (t.IsByRef) t = t.GetElementType (); paramNames.Add(paramInfo.Name); paramTypes.Add(t); paramValues.Add(mcm.Args[paramInfo.Position]); } } soapMsg.ParamNames = (string[]) paramNames.ToArray(typeof(string)); soapMsg.ParamTypes = (Type[]) paramTypes.ToArray(typeof(Type)); soapMsg.ParamValues = (object[]) paramValues.ToArray(typeof(object)); soapMsg.XmlNameSpace = SoapServices.GetXmlNamespaceForMethodCall(_methodCallInfo); soapMsg.Headers = BuildMessageHeaders (mcm); // Format the transport headers requestHeaders["Content-Type"] = "text/xml; charset=\"utf-8\""; requestHeaders["SOAPAction"] = "\""+ SoapServices.GetSoapActionFromMethodBase(_methodCallInfo)+"\""; requestHeaders[CommonTransportKeys.RequestUri] = mcm.Uri; return soapMsg; } // used by the server internal IMessage BuildMethodCallFromSoapMessage(SoapMessage soapMessage, string uri) { ArrayList headersList = new ArrayList(); Type[] signature = null; headersList.Add(new Header("__Uri", uri)); headersList.Add(new Header("__MethodName", soapMessage.MethodName)); string typeNamespace, assemblyName; SoapServices.DecodeXmlNamespaceForClrTypeNamespace(soapMessage.XmlNameSpace, out typeNamespace, out assemblyName); _serverType = RemotingServices.GetServerTypeForUri(uri); headersList.Add(new Header("__TypeName", _serverType.FullName, false)); if (soapMessage.Headers != null) { foreach (Header h in soapMessage.Headers) { headersList.Add (h); if (h.Name == "__MethodSignature") signature = (Type[]) h.Value; } } _xmlNamespace = soapMessage.XmlNameSpace; //RemMessageType messageType; BindingFlags bflags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; if (signature == null) _methodCallInfo = _serverType.GetMethod(soapMessage.MethodName, bflags); else _methodCallInfo = _serverType.GetMethod(soapMessage.MethodName, bflags, null, signature, null); // the *out* parameters aren't serialized // have to add them here _methodCallParameters = _methodCallInfo.GetParameters(); object[] args = new object[_methodCallParameters.Length]; int sn = 0; for (int n=0; n<_methodCallParameters.Length; n++) { ParameterInfo paramInfo = _methodCallParameters [n]; Type paramType = (paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType); if (paramInfo.IsOut && paramInfo.ParameterType.IsByRef) { args [n] = GetNullValue (paramType); } else{ object val = soapMessage.ParamValues[sn++]; if(val is IConvertible) args [n] = Convert.ChangeType (val, paramType); else args [n] = val; } } headersList.Add(new Header("__Args", args, false)); Header[] headers = (Header[])headersList.ToArray(typeof(Header)); // build the MethodCall from the headers MethodCall mthCall = new MethodCall(headers); return (IMessage)mthCall; } // used by the server internal object BuildSoapMessageFromMethodResponse(IMethodReturnMessage mrm, out ITransportHeaders responseHeaders) { responseHeaders = new TransportHeaders(); if(mrm.Exception == null) { // *normal* function return SoapMessage soapMessage = new SoapMessage(); // fill the transport headers responseHeaders["Content-Type"] = "text/xml; charset=\"utf-8\""; // build the SoapMessage ArrayList paramNames = new ArrayList(); ArrayList paramValues = new ArrayList(); ArrayList paramTypes = new ArrayList(); soapMessage.MethodName = mrm.MethodName+"Response"; Type retType = ((MethodInfo)mrm.MethodBase).ReturnType; if(retType != typeof(void)) { paramNames.Add("return"); paramValues.Add(mrm.ReturnValue); if (mrm.ReturnValue != null) paramTypes.Add(mrm.ReturnValue.GetType()); else paramTypes.Add(retType); } for(int i = 0; i < mrm.OutArgCount; i++){ paramNames.Add(mrm.GetOutArgName(i)); paramValues.Add(mrm.GetOutArg(i)); if(mrm.GetOutArg(i) != null) paramTypes.Add(mrm.GetOutArg(i).GetType()); } soapMessage.ParamNames = (string[]) paramNames.ToArray(typeof(string)); soapMessage.ParamValues = (object[]) paramValues.ToArray(typeof(object)); soapMessage.ParamTypes = (Type[]) paramTypes.ToArray(typeof(Type)); soapMessage.XmlNameSpace = _xmlNamespace; soapMessage.Headers = BuildMessageHeaders (mrm); return soapMessage; } else { // an Exception was thrown while executing the function responseHeaders["__HttpStatusCode"] = "400"; responseHeaders["__HttpReasonPhrase"] = "Bad Request"; // fill the transport headers responseHeaders["Content-Type"] = "text/xml; charset=\"utf-8\""; ServerFault serverFault = CreateServerFault(mrm.Exception); return new SoapFault("Server", String.Format(" **** {0} - {1}", mrm.Exception.GetType().ToString(), mrm.Exception.Message), null, serverFault); } } internal SoapMessage CreateSoapMessage (bool isRequest) { if (isRequest) return new SoapMessage (); int n = 0; Type[] types = new Type [_methodCallParameters.Length + 1]; if (_methodCallInfo.ReturnType != typeof(void)) { types[0] = _methodCallInfo.ReturnType; n++; } foreach(ParameterInfo paramInfo in _methodCallParameters) { if (paramInfo.ParameterType.IsByRef || paramInfo.IsOut) { Type t = paramInfo.ParameterType; if (t.IsByRef) t = t.GetElementType(); types [n++] = t; } } SoapMessage sm = new SoapMessage (); sm.ParamTypes = types; return sm; } // used by the server when an exception is thrown // by the called function internal ServerFault CreateServerFault(Exception e) { // it's really strange here // a ServerFault object has a private System.Exception member called *exception* // (have a look at a MS Soap message when an exception occurs on the server) // but there is not public .ctor with an Exception as parameter...????.... // (maybe an internal one). So I searched another way... ServerFault sf = (ServerFault) FormatterServices.GetUninitializedObject(typeof(ServerFault)); MemberInfo[] mi = FormatterServices.GetSerializableMembers(typeof(ServerFault), new StreamingContext(StreamingContextStates.All)); FieldInfo fi; object[] mv = new object[mi.Length]; for(int i = 0; i < mi.Length; i++) { fi = mi[i] as FieldInfo; if(fi != null && fi.FieldType == typeof(Exception)) mv[i] = e; } sf = (ServerFault) FormatterServices.PopulateObjectMembers(sf, mi, mv); return sf; } internal void GetInfoFromMethodCallMessage(IMethodCallMessage mcm) { _serverType = Type.GetType(mcm.TypeName, true); if (mcm.MethodSignature != null) _methodCallInfo = _serverType.GetMethod(mcm.MethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, (Type []) mcm.MethodSignature, null); else _methodCallInfo = _serverType.GetMethod(mcm.MethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _methodCallParameters = _methodCallInfo.GetParameters(); } Header[] BuildMessageHeaders (IMethodMessage msg) { ArrayList headers = new ArrayList (1); foreach (string key in msg.Properties.Keys) { switch (key) { case "__Uri": case "__MethodName": case "__TypeName": case "__Args": case "__OutArgs": case "__Return": case "__MethodSignature": case "__CallContext": continue; default: object value = msg.Properties [key]; if (value != null) headers.Add (new Header (key, value, false, "http://schemas.microsoft.com/clr/soap/messageProperties")); break; } } if (RemotingServices.IsMethodOverloaded (msg)) headers.Add (new Header ("__MethodSignature", msg.MethodSignature, false, "http://schemas.microsoft.com/clr/soap/messageProperties")); if (msg.LogicalCallContext != null && msg.LogicalCallContext.HasInfo) headers.Add (new Header ("__CallContext", msg.LogicalCallContext, false, "http://schemas.microsoft.com/clr/soap/messageProperties")); if (headers.Count == 0) return null; return (Header[]) headers.ToArray (typeof(Header)); } object GetNullValue (Type paramType) { switch (Type.GetTypeCode (paramType)) { case TypeCode.Boolean: return false; case TypeCode.Byte: return (byte)0; case TypeCode.Char: return '\0'; case TypeCode.Decimal: return (decimal)0; case TypeCode.Double: return (double)0; case TypeCode.Int16: return (short)0; case TypeCode.Int32: return (int)0; case TypeCode.Int64: return (long)0; case TypeCode.SByte: return (sbyte)0; case TypeCode.Single: return (float)0; case TypeCode.UInt16: return (ushort)0; case TypeCode.UInt32: return (uint)0; case TypeCode.UInt64: return (ulong)0; default: return null; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #region Using directives using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine; using System.Collections; #endregion namespace Microsoft.Build.UnitTests { [TestFixture] public class ProjectManager_Tests { /// <summary> /// Add a project to the ProjectManager, and try to get it back out using the /// correct set of search criteria. /// </summary> /// <owner>RGoel</owner> [Test] public void SimpleAddAndRetrieveProject() { // Initialize engine. Engine engine = new Engine(@"c:\"); // Instantiate new project manager. ProjectManager projectManager = new ProjectManager(); // Set up variables that represent the information we would be getting from // the "MSBuild" task. string fullPath = @"c:\rajeev\temp\myapp.proj"; BuildPropertyGroup globalProperties = new BuildPropertyGroup(); globalProperties.SetProperty("Configuration", "Debug"); // Create a new project that matches the information that we're pretending // to receive from the MSBuild task. Project project1 = new Project(engine); project1.FullFileName = fullPath; project1.GlobalProperties = globalProperties; // Add the new project to the ProjectManager. projectManager.AddProject(project1); // Try and retrieve the project from the ProjectManager based on the fullpath + globalprops, // and make sure we get back the same project we added. Assertion.AssertEquals(project1, projectManager.GetProject(fullPath, globalProperties, null)); } /// <summary> /// Verify project manager does not insert duplicates into project table. /// </summary> [Test] public void TestForDuplicatesInProjectTable() { ProjectManager projectManager = new ProjectManager(); string fullPath = @"c:\foo\bar.proj"; BuildPropertyGroup globalProperties = new BuildPropertyGroup(); globalProperties.SetProperty("p1", "v1"); Project p = new Project(new Engine()); p.FullFileName = fullPath; p.GlobalProperties = globalProperties; p.ToolsVersion = "4.0"; // Add the new project to the ProjectManager, twice Hashtable table = new Hashtable(StringComparer.OrdinalIgnoreCase); ProjectManager.AddProject(table, p); ProjectManager.AddProject(table, p); Assertion.AssertEquals(1, ((ArrayList)table[fullPath]).Count); // Didn't add a duplicate // Add a second, slightly different project, and ensure it DOES get added Project p2 = new Project(new Engine()); p2.FullFileName = fullPath; p2.GlobalProperties = globalProperties; p2.ToolsVersion = "2.0"; ProjectManager.AddProject(table, p2); Project p3 = new Project(new Engine()); p3.FullFileName = fullPath; p3.GlobalProperties = new BuildPropertyGroup(); p3.ToolsVersion = "2.0"; ProjectManager.AddProject(table, p3); Assertion.AssertEquals(3, ((ArrayList)table[fullPath]).Count); } /// <summary> /// Verify project manager does not insert duplicates into project entry table. /// </summary> [Test] public void TestForDuplicatesInProjectEntryTable() { ProjectManager projectManager = new ProjectManager(); string fullPath = @"c:\foo\bar.proj"; BuildPropertyGroup globalProperties = new BuildPropertyGroup(); globalProperties.SetProperty("p1", "v1"); string toolsVersion = "3.5"; // Add the new project entry to the ProjectManager, twice Hashtable table = new Hashtable(StringComparer.OrdinalIgnoreCase); ProjectManager.AddProjectEntry(table, fullPath, globalProperties, toolsVersion, 0); ProjectManager.AddProjectEntry(table, fullPath, globalProperties, toolsVersion, 0); Assertion.AssertEquals(1, ((ArrayList)table[fullPath]).Count); // Didn't add a duplicate // Add a second, slightly different project entry, and ensure it DOES get added ProjectManager.AddProjectEntry(table, fullPath, globalProperties, "2.0", 0); ProjectManager.AddProjectEntry(table, fullPath, new BuildPropertyGroup(), "2.0", 0); Assertion.AssertEquals(3, ((ArrayList)table[fullPath]).Count); } /// <summary> /// Add a project to the ProjectManager, and try to get it back out using the /// wrong set of search criteria (different set of global properties). /// </summary> /// <owner>RGoel</owner> [Test] public void SimpleAddAndRetrieveProjectWithDifferentGlobals() { // Initialize engine. Engine engine = new Engine(@"c:\"); // Instantiate new project manager. ProjectManager projectManager = new ProjectManager(); // Set up variables that represent the information we would be getting from // the "MSBuild" task. string fullPath = @"c:\rajeev\temp\myapp.proj"; BuildPropertyGroup globalProperties = new BuildPropertyGroup(); globalProperties.SetProperty("Configuration", "Release"); // Create a new project that matches the information that we're pretending // to receive from the MSBuild task. Project project1 = new Project(engine); project1.FullFileName = fullPath; project1.GlobalProperties = globalProperties; // Add the new project to the ProjectManager. projectManager.AddProject(project1); // Now search for a project with the same full path but a different set of global // properties. We expect to get back null, because no such project exists. globalProperties.SetProperty("Configuration", "Debug"); Assertion.AssertNull(projectManager.GetProject(fullPath, globalProperties, null)); } /// <summary> /// Add a project to the ProjectManager, and try to get it back out using the /// wrong set of search criteria (different full path). /// </summary> /// <owner>RGoel</owner> [Test] public void SimpleAddAndRetrieveProjectWithDifferentFullPath() { // Initialize engine. Engine engine = new Engine(@"c:\"); // Instantiate new project manager. ProjectManager projectManager = new ProjectManager(); // Set up variables that represent the information we would be getting from // the "MSBuild" task. BuildPropertyGroup globalProperties = new BuildPropertyGroup(); globalProperties.SetProperty("Configuration", "Release"); // Create a new project that matches the information that we're pretending // to receive from the MSBuild task. Project project1 = new Project(engine); project1.FullFileName = @"c:\rajeev\temp\myapp.proj"; project1.GlobalProperties = globalProperties; // Add the new project to the ProjectManager. projectManager.AddProject(project1); // Now search for a project with a different full path but same set of global // properties. We expect to get back null, because no such project exists. Assertion.AssertNull(projectManager.GetProject(@"c:\blah\wrong.proj", globalProperties, null)); } /// <summary> /// Reset the build status for every project stored in the ProjectManager. /// </summary> /// <owner>RGoel</owner> [Test] public void ResetBuildStatusForAllProjects() { // Initialize engine. Need two separate engines because we don't allow two // projects with the same full path to be loaded in the same Engine. Engine engine1 = new Engine(@"c:\"); Engine engine2 = new Engine(@"c:\"); // Instantiate new project manager. ProjectManager projectManager = new ProjectManager(); // Set up a global property group. BuildPropertyGroup globalProperties = new BuildPropertyGroup(); globalProperties.SetProperty("Configuration", "Release"); // Create a few new projects. Project project1 = new Project(engine1); project1.FullFileName = @"c:\rajeev\temp\myapp.proj"; project1.GlobalProperties = globalProperties; Project project2 = new Project(engine1); project2.FullFileName = @"c:\blah\foo.proj"; project2.GlobalProperties = globalProperties; Project project3 = new Project(engine2); project3.FullFileName = @"c:\blah\foo.proj"; globalProperties.SetProperty("Configuration", "Debug"); project3.GlobalProperties = globalProperties; // Add the new projects to the ProjectManager. projectManager.AddProject(project1); projectManager.AddProject(project2); projectManager.AddProject(project3); // Put all the projects in a non-reset state. project1.IsReset = false; project2.IsReset = false; project3.IsReset = false; // Call ResetAllProjects. projectManager.ResetBuildStatusForAllProjects(); // Make sure they all got reset. Assertion.Assert(project1.IsReset); Assertion.Assert(project2.IsReset); Assertion.Assert(project3.IsReset); } /// <summary> /// Removes all projects of a given full path. /// </summary> /// <owner>RGoel</owner> [Test] public void RemoveProjectsByFullPath() { // Initialize engine. Need two separate engines because we don't allow two // projects with the same full path to be loaded in the same Engine. Engine engine1 = new Engine(@"c:\"); Engine engine2 = new Engine(@"c:\"); // Instantiate new project manager. ProjectManager projectManager = new ProjectManager(); // Set up a global property group. BuildPropertyGroup globalProperties = new BuildPropertyGroup(); globalProperties.SetProperty("Configuration", "Release"); // Create a few new projects. Project project1 = new Project(engine1); project1.FullFileName = @"c:\rajeev\temp\myapp.proj"; project1.GlobalProperties = globalProperties; Project project2 = new Project(engine1); project2.FullFileName = @"c:\blah\foo.proj"; project2.GlobalProperties = globalProperties; Project project3 = new Project(engine2); project3.FullFileName = @"c:\blah\foo.proj"; globalProperties.SetProperty("Configuration", "Debug"); project3.GlobalProperties = globalProperties; // Add the new projects to the ProjectManager. projectManager.AddProject(project1); projectManager.AddProject(project2); projectManager.AddProject(project3); // Remove all projects with the full path "c:\blah\foo.proj" (case insenstively). projectManager.RemoveProjects(@"c:\BLAH\FOO.Proj"); // Make sure project 1 is still there. Assertion.AssertEquals(project1, projectManager.GetProject(project1.FullFileName, project1.GlobalProperties, null)); // Make sure projects 2 and 3 are gone. Assertion.AssertNull(projectManager.GetProject(project2.FullFileName, project2.GlobalProperties, null)); Assertion.AssertNull(projectManager.GetProject(project3.FullFileName, project3.GlobalProperties, null)); } } }
#region MigraDoc - Creating Documents on the Fly // // Authors: // Stefan Lange (mailto:[email protected]) // Klaus Potzesny (mailto:[email protected]) // David Stephensen (mailto:[email protected]) // // Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://www.migradoc.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 System.Diagnostics; using System.Reflection; using MigraDoc.DocumentObjectModel.Internals; using MigraDoc.DocumentObjectModel.Visitors; namespace MigraDoc.DocumentObjectModel.Tables { /// <summary> /// Represents the collection of all rows of a table. /// </summary> public class Rows : DocumentObjectCollection, IVisitable { /// <summary> /// Initializes a new instance of the Rows class. /// </summary> public Rows() { } /// <summary> /// Initializes a new instance of the Rows class with the specified parent. /// </summary> internal Rows(DocumentObject parent) : base(parent) { } #region Methods /// <summary> /// Creates a deep copy of this object. /// </summary> public new Rows Clone() { return (Rows)base.DeepCopy(); } /// <summary> /// Adds a new row to the rows collection. Allowed only if at least one column exists. /// </summary> public Row AddRow() { if (Table.Columns.Count == 0) throw new InvalidOperationException("Cannot add row, because no columns exists."); Row row = new Row(); Add(row); return row; } #endregion #region Properties /// <summary> /// Gets the table the rows collection belongs to. /// </summary> public Table Table { get { return this.parent as Table; } } /// <summary> /// Gets a row by its index. /// </summary> public new Row this[int index] { get { return base[index] as Row; } } /// <summary> /// Gets or sets the row alignment of the table. /// </summary> public RowAlignment Alignment { get { return (RowAlignment)this.alignment.Value; } set { this.alignment.Value = (int)value; } } [DV(Type = typeof(RowAlignment))] internal NEnum alignment = NEnum.NullValue(typeof(RowAlignment)); /// <summary> /// Gets or sets the left indent of the table. If row alignment is not Left, /// the value is ignored. /// </summary> public Unit LeftIndent { get { return this.leftIndent; } set { this.leftIndent = value; } } [DV] internal Unit leftIndent = Unit.NullValue; /// <summary> /// Gets or sets the default vertical alignment for all rows. /// </summary> public VerticalAlignment VerticalAlignment { get { return (VerticalAlignment)this.verticalAlignment.Value; } set { this.verticalAlignment.Value = (int)value; } } [DV(Type = typeof(VerticalAlignment))] internal NEnum verticalAlignment = NEnum.NullValue(typeof(VerticalAlignment)); /// <summary> /// Gets or sets the height of the rows. /// </summary> public Unit Height { get { return this.height; } set { this.height = value; } } [DV] internal Unit height = Unit.NullValue; /// <summary> /// Gets or sets the rule which is used to determine the height of the rows. /// </summary> public RowHeightRule HeightRule { get { return (RowHeightRule)this.heightRule.Value; } set { this.heightRule.Value = (int)value; } } [DV(Type = typeof(RowHeightRule))] internal NEnum heightRule = NEnum.NullValue(typeof(RowHeightRule)); /// <summary> /// Gets or sets a comment associated with this object. /// </summary> public string Comment { get { return this.comment.Value; } set { this.comment.Value = value; } } [DV] internal NString comment = NString.NullValue; #endregion #region Internal /// <summary> /// Converts Rows into DDL. /// </summary> internal override void Serialize(Serializer serializer) { serializer.WriteComment(this.comment.Value); serializer.WriteLine("\\rows"); int pos = serializer.BeginAttributes(); if (!this.alignment.IsNull) serializer.WriteSimpleAttribute("Alignment", this.Alignment); if (!this.height.IsNull) serializer.WriteSimpleAttribute("Height", this.Height); if (!this.heightRule.IsNull) serializer.WriteSimpleAttribute("HeightRule", this.HeightRule); if (!this.leftIndent.IsNull) serializer.WriteSimpleAttribute("LeftIndent", this.LeftIndent); if (!this.verticalAlignment.IsNull) serializer.WriteSimpleAttribute("VerticalAlignment", this.VerticalAlignment); serializer.EndAttributes(pos); serializer.BeginContent(); int rows = Count; if (rows > 0) { for (int row = 0; row < rows; row++) this[row].Serialize(serializer); } else serializer.WriteComment("Invalid - no rows defined. Table will not render."); serializer.EndContent(); } /// <summary> /// Allows the visitor object to visit the document object and it's child objects. /// </summary> void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren) { visitor.VisitRows(this); foreach (Row row in this) ((IVisitable)row).AcceptVisitor(visitor, visitChildren); } /// <summary> /// Returns the meta object of this instance. /// </summary> internal override Meta Meta { get { if (meta == null) meta = new Meta(typeof(Rows)); return meta; } } static Meta meta; #endregion } }
namespace Loon.Java.Generics { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; public class LinkedListNode<T> { public T Data; public LinkedListNode<T> Prev; public LinkedListNode<T> Next; public LinkedListNode(T Data) { this.Data = Data; } } public class LinkedList<T> { LinkedListNode<T> Head; LinkedListNode<T> Tail; int LinkedList_Size; public LinkedList() { Head = null; Tail = null; LinkedList_Size = 0; } public LinkedList(T[] collection) { Head = null; Tail = null; LinkedList_Size = 0; AddAll_Internal(Tail, collection); } private LinkedListNode<T> Add_Internal_Before(LinkedListNode<T> offset, T element) { if (offset == null) throw new Exception("Add_Internal: null is not a valid argument"); LinkedListNode<T> Listelement = new LinkedListNode<T>(element); Listelement.Prev = offset.Prev; Listelement.Next = offset; if (offset.Prev != null) offset.Prev.Next = Listelement; offset.Prev = Listelement; if (offset == Head) Head = Listelement; LinkedList_Size++; return Listelement; } private LinkedListNode<T> Add_Internal_After(LinkedListNode<T> offset, T element) { if (offset == null) throw new Exception("Add_Internal: null is not a valid argument"); LinkedListNode<T> Listelement = new LinkedListNode<T>(element); Listelement.Prev = offset; Listelement.Next = offset.Next; if (offset.Next != null) offset.Next.Prev = Listelement; offset.Next = Listelement; if (offset == Tail) Tail = Listelement; LinkedList_Size++; return Listelement; } public bool Add(int Index, T element) { if ((Index == 0) && (Head == null)) AddFirst(element); else Add_Internal_Before(Get_Internal(Index), element); return true; } public void Add(T element) { if (Head == null) AddFirst(element); else Add_Internal_After(Tail, element); } public void AddFirst(T element) { LinkedListNode<T> ListElement = new LinkedListNode<T>(element); if (Tail == null) { Tail = ListElement; } else { ListElement.Next = Head; Head.Prev = ListElement; } Head = ListElement; LinkedList_Size++; } public void AddLast(T element) { LinkedListNode<T> Listelement = new LinkedListNode<T>(element); if (Head == null) { Head = Listelement; } else { Listelement.Prev = Tail; Tail.Next = Listelement; } Tail = Listelement; LinkedList_Size++; } private void AddAll_Internal(LinkedListNode<T> start, T[] collection) { bool First = true; foreach (T element in collection) { if (Head == null) { AddFirst(element); start = Head; First = false; } else { if (First) { start = Add_Internal_Before(start, element); First = false; } else start = Add_Internal_After(start, element); } } } public void AddAll(T[] collection) { AddAll_Internal(Tail, collection); } public void AddAll(int index, T[] collection) { AddAll_Internal(Get_Internal(index), collection); } public void Clear() { LinkedListNode<T> Temp; while (Head != null) { Temp = Head; Head = Head.Next; Temp.Prev = null; Temp.Next = null; } Tail = null; LinkedList_Size = 0; } public LinkedList<T> Clone() { LinkedList<T> ClonedCopy = new LinkedList<T>(); LinkedListNode<T> Iterator = Head; while (Iterator != null) { ClonedCopy.AddLast(Iterator.Data); Iterator = Iterator.Next; } return ClonedCopy; } public bool Contains(T needle) { LinkedListNode<T> Iterator = Head; while (Iterator != null) { if ((needle == null) && (Iterator.Data == null)) return true; if (Iterator.Data != null) if (Iterator.Data.Equals(needle)) return true; Iterator = Iterator.Next; } return false; } public int Size() { return LinkedList_Size; } private LinkedListNode<T> Get_Internal(int Index) { if ((LinkedList_Size == 0) || (Index < 0) || (Index >= LinkedList_Size)) throw new IndexOutOfRangeException("LinkedList<T> Invalid Index"); LinkedListNode<T> iterator; int DistanceFromHead = Index; int DistanceFromTail = LinkedList_Size - Index - 1; if (DistanceFromHead < DistanceFromTail) { iterator = Head; while (iterator != null && DistanceFromHead-- > 0) iterator = iterator.Next; } else { iterator = Tail; while (iterator != null && DistanceFromTail-- > 0) iterator = iterator.Prev; } return iterator; } public T Get(int index) { return Get_Internal(index).Data; } public T GetFirst() { if (LinkedList_Size == 0) throw new IndexOutOfRangeException("LinkedList<T> Invalid Index"); return Head.Data; } public T GetLast() { if (LinkedList_Size == 0) throw new IndexOutOfRangeException("LinkedList<T> Invalid Index"); return Tail.Data; } private LinkedListNode<T> IndexOf_Internal(T element) { int Index = 0; LinkedListNode<T> Iterator = Head; while (Iterator != null) { if ((element == null) && (Iterator.Data == null)) return Iterator; if (Iterator.Data != null) if (Iterator.Data.Equals(element)) return Iterator; Index++; Iterator = Iterator.Next; } return null; } public int IndexOf(T element) { int Index = 0; LinkedListNode<T> Iterator = Head; while (Iterator != null) { if ((element == null) && (Iterator.Data == null)) return Index; if (Iterator.Data != null) if (Iterator.Data.Equals(element)) return Index; Index++; Iterator = Iterator.Next; } return -1; } public int LastIndexOf(T element) { int Index = LinkedList_Size; LinkedListNode<T> Iterator = Tail; while (Iterator != null) { Index--; if ((element == null) && (Iterator.Data == null)) return Index; if (Iterator.Data != null) if (Iterator.Data.Equals(element)) return Index; Iterator = Iterator.Prev; } return -1; } public void Remove_Internal(LinkedListNode<T> element) { if (element == null) throw new Exception("LinkedListNode<T> null is not a valid argument"); if (element == Head) Head = element.Next; if (element == Tail) Tail = element.Prev; if (element.Prev != null) element.Prev.Next = element.Next; if (element.Next != null) element.Next.Prev = element.Prev; LinkedList_Size--; } public T Remove(int Index) { LinkedListNode<T> Element = Get_Internal(Index); T Data = Element.Data; Remove_Internal(Element); return Data; } public bool Remove(T element) { LinkedListNode<T> Node = IndexOf_Internal(element); if (Node != null) { Remove_Internal(Node); return true; } return false; } public T RemoveFirst() { if (LinkedList_Size == 0) throw new IndexOutOfRangeException("LinkedList<T> Empty List"); T Data = Head.Data; Remove_Internal(Head); return Data; } public T RemoveLast() { if (LinkedList_Size == 0) throw new IndexOutOfRangeException("LinkedList<T> Empty List"); T Data = Tail.Data; Remove_Internal(Tail); return Data; } public T Set(int Index, T element) { LinkedListNode<T> OldListEntry = Get_Internal(Index); T Temp = OldListEntry.Data; OldListEntry.Data = element; return Temp; } public T[] ToArray() { LinkedListNode<T> iterator = Head; T[] DataArray = new T[LinkedList_Size]; int Index = 0; while (iterator != null) { DataArray[Index++] = iterator.Data; iterator = iterator.Next; } return DataArray; } public IEnumerator<T> GetEnumerator() { return new LinkedListEnumerator(this); } public class LinkedListEnumerator : IEnumerator<T> { LinkedListNode<T> start; LinkedListNode<T> current; public LinkedListEnumerator(LinkedList<T> list) { start = list.Head; current = null; } public bool MoveNext() { if (current == null) current = start; else current = current.Next; return (current != null); } public T Current { get { if (current == null) throw new InvalidOperationException(); return current.Data; } } object IEnumerator.Current { get { if (current == null) throw new InvalidOperationException(); return current.Data; } } public void Dispose() { } public void Reset() { current = null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using Microsoft.ServiceBus.Management; using Helsenorge.Registries.Abstractions; namespace Helsenorge.Messaging { /// <summary> /// Specfies settings for the messaging system /// </summary> public class MessagingSettings { /// <summary> /// The Her id that we represent /// </summary> public int MyHerId { get; set; } /// <summary> /// The certificate used for signing messages /// </summary> public CertificateSettings SigningCertificate { get; set; } /// <summary> /// The certificate used to decrypt messages /// </summary> public CertificateSettings DecryptionCertificate { get; set; } /// <summary> /// The old certificate used for decryption when we have moved over to a new one. /// </summary> public CertificateSettings LegacyDecryptionCertificate { get; set; } /// <summary> /// Indicates if we should ignore certificate errors when sending /// </summary> public bool IgnoreCertificateErrorOnSend { get; set; } /// <summary> /// Use online certificate revocation list (CRL) check. Default true. /// </summary> public bool UseOnlineRevocationCheck { get; set; } = true; /// <summary> /// Provides access to service bus settings /// </summary> public ServiceBusSettings ServiceBus { get; } /// <summary> /// Indicates if the payload should be logged. This is false by default since the payload can contain sensitive information /// </summary> public bool LogPayload { get; set; } /// <summary> /// Default contructor /// </summary> public MessagingSettings() { IgnoreCertificateErrorOnSend = false; LogPayload = false; ServiceBus = new ServiceBusSettings(this); } internal void Validate() { if (MyHerId <= 0) throw new ArgumentOutOfRangeException(nameof(MyHerId)); if (DecryptionCertificate == null) throw new ArgumentNullException(nameof(DecryptionCertificate)); if (SigningCertificate == null) throw new ArgumentNullException(nameof(SigningCertificate)); ServiceBus.Validate(); } } /// <summary> /// Defines settings for service bus /// </summary> public class ServiceBusSettings { private readonly MessagingSettings _settings; /// <summary> /// Gets or sets the connection string /// </summary> public string ConnectionString { get; set; } /// <summary> /// Provides access to settings related to asynchronous queues /// </summary> public AsynchronousSettings Asynchronous { get; } = new AsynchronousSettings(); /// <summary> /// Provides access to settings related to synchronous queues /// </summary> public SynchronousSettings Synchronous { get; } = new SynchronousSettings(); /// <summary> /// Provides access to settings related to error queues /// </summary> public ErrorSettings Error { get; } = new ErrorSettings(); /// <summary> /// The maximum number of receivers to keep open at any time /// </summary> public uint MaxReceivers { get; set; } = 5; /// <summary> /// The maximum number of senders to keep open at any time /// </summary> public uint MaxSenders { get; set; } = 200; /// <summary> /// The maximum number of messaging factories to use /// </summary> public uint MaxFactories { get; set; } = 5; /// <summary> /// The Her id that we represent /// </summary> public int MyHerId => _settings.MyHerId; /// <summary> /// The certificate used for signing messages /// </summary> public CertificateSettings SigningCertificate => _settings.SigningCertificate; /// <summary> /// The certificate used to decrypt messages /// </summary> public CertificateSettings DecryptionCertificate => _settings.DecryptionCertificate; /// <summary> /// The old certificate used for decryption when we have moved over to a new one. /// </summary> public CertificateSettings LegacyDecryptionCertificate => _settings.LegacyDecryptionCertificate; internal ServiceBusSettings(MessagingSettings settings) { _settings = settings; } internal void Validate() { if (string.IsNullOrEmpty(ConnectionString)) throw new ArgumentNullException(nameof(ConnectionString)); Asynchronous.Validate(); Synchronous.Validate(); Error.Validate(); } } /// <summary> /// Defines settings for synchronous queues /// </summary> public class SynchronousSettings { /// <summary> /// Number of processing tasks /// </summary> public int ProcessingTasks { get; set; } = 2; /// <summary> /// Time to live for messages sent /// </summary> public TimeSpan TimeToLive { get; set; } = TimeSpan.FromSeconds(15); /// <summary> /// Timeout for read operations /// </summary> public TimeSpan ReadTimeout { get; set; } = TimeSpan.FromSeconds(1); /// <summary> /// Sets up a map between reply to queue and server name /// </summary> public Dictionary<string, string> ReplyQueueMapping { get; set; } = new Dictionary<string, string>(); /// <summary> /// The timout for synchronous calls /// </summary> public TimeSpan CallTimeout { get; set; } = TimeSpan.FromSeconds(15); internal SynchronousSettings() { } internal void Validate() { if (ProcessingTasks < 0) throw new ArgumentOutOfRangeException(nameof(ProcessingTasks)); if (TimeToLive == TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(TimeToLive)); if (ReadTimeout == TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ReadTimeout)); if (CallTimeout == TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(CallTimeout)); if (FindReplyQueueForMe() == null) { throw new InvalidOperationException("Could not determine reply to queue for this server"); } } internal string FindReplyQueueForMe() { if (ReplyQueueMapping == null) return null; if (ReplyQueueMapping.Count == 0) return null; var server = (from s in ReplyQueueMapping.Keys where s.Equals(Environment.MachineName, StringComparison.OrdinalIgnoreCase) select s).FirstOrDefault(); return server == null ? null : ReplyQueueMapping[server]; } } /// <summary> /// Defines settings for asynchronous queues /// </summary> public class AsynchronousSettings { /// <summary> /// Number of processing tasks /// </summary> public int ProcessingTasks { get; set; } = 5; /// <summary> /// Time to live for messages sent /// </summary> public TimeSpan TimeToLive { get; set; } = TimeSpan.Zero; /// <summary> /// Timeout for read operations /// </summary> public TimeSpan ReadTimeout { get; set; } = TimeSpan.FromSeconds(1); internal AsynchronousSettings() {} internal void Validate() { if (ProcessingTasks <= 0) throw new ArgumentOutOfRangeException(nameof(ProcessingTasks)); if (ReadTimeout == TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ReadTimeout)); } } /// <summary> /// Defines settings for error queues /// </summary> public class ErrorSettings { /// <summary> /// Number of processing tasks /// </summary> public int ProcessingTasks { get; set; } = 1; /// <summary> /// Time to live for messages sent /// </summary> public TimeSpan TimeToLive { get; set; } = TimeSpan.MaxValue; /// <summary> /// Timeout for read operations /// </summary> public TimeSpan ReadTimeout { get; set; } = TimeSpan.FromSeconds(1); internal ErrorSettings() {} internal void Validate() { if (ProcessingTasks <= 0) throw new ArgumentOutOfRangeException(nameof(ProcessingTasks)); if (TimeToLive == TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(TimeToLive)); if (ReadTimeout == TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ReadTimeout)); } } /// <summary> /// Represents information about a certificate and where to get it /// </summary> public class CertificateSettings { X509Certificate2 _certificate; /// <summary> /// Constructor /// </summary> public CertificateSettings() { StoreLocation = StoreLocation.LocalMachine; StoreName = StoreName.My; } /// <summary> /// The thumbprint of the certificate we should use /// </summary> public string Thumbprint { get; set; } /// <summary> /// The name of the certificate store to use /// </summary> public StoreName StoreName { get; set; } /// <summary> /// The location of the certificate store to use /// </summary> public StoreLocation StoreLocation { get; set; } /// <summary> /// Gets the actual certificate specified by the configuration /// </summary> public X509Certificate2 Certificate { get { if (_certificate != null) return _certificate; var store = new X509Store(StoreName, StoreLocation); store.Open(OpenFlags.ReadOnly); var certCollection = store.Certificates.Find(X509FindType.FindByThumbprint, Thumbprint, false); var enumerator = certCollection.GetEnumerator(); X509Certificate2 cert = null; while (enumerator.MoveNext()) { cert = enumerator.Current; } store.Close(); _certificate = cert; return _certificate; } set { _certificate = value; } } } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; namespace OnlineGraph { public class GraphLineCollection : SortableCollectionBase, ICustomTypeDescriptor { #region CollectionBase implementation public GraphLineCollection() { //In your collection class constructor add this line. //set the SortObjectType for sorting. base.SortObjectType = typeof(GraphLine); } public GraphLine this[int index] { get { return ((GraphLine)List[index]); } set { List[index] = value; } } public int Add(GraphLine value) { return (List.Add(value)); } public int IndexOf(GraphLine value) { return (List.IndexOf(value)); } public void Insert(int index, GraphLine value) { List.Insert(index, value); } public void Remove(GraphLine value) { List.Remove(value); } public bool Contains(GraphLine value) { // If value is not of type Int16, this will return false. return (List.Contains(value)); } protected override void OnInsert(int index, Object value) { // Insert additional code to be run only when inserting values. } protected override void OnRemove(int index, Object value) { // Insert additional code to be run only when removing values. } protected override void OnSet(int index, Object oldValue, Object newValue) { // Insert additional code to be run only when setting values. } protected override void OnValidate(Object value) { } #endregion [TypeConverter(typeof(GraphLineCollectionConverter))] public GraphLineCollection Symbols { get { return this; } } internal class SymbolConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is GraphLine) { // Cast the value to an Employee type GraphLine pp = (GraphLine)value; return pp.Symbol + ", " + pp.Numberofmeasurements.ToString() ; } return base.ConvertTo(context, culture, value, destType); } } // This is a special type converter which will be associated with the EmployeeCollection class. // It converts an EmployeeCollection object to a string representation for use in a property grid. internal class GraphLineCollectionConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is GraphLineCollection) { // Return department and department role separated by comma. return "Symbols"; } return base.ConvertTo(context, culture, value, destType); } } #region ICustomTypeDescriptor impl public String GetClassName() { return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } public String GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } public EventDescriptorCollection GetEvents() { return TypeDescriptor.GetEvents(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) { return this; } /// <summary> /// Called to get the properties of this type. Returns properties with certain /// attributes. this restriction is not implemented here. /// </summary> /// <param name="attributes"></param> /// <returns></returns> public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return GetProperties(); } /// <summary> /// Called to get the properties of this type. /// </summary> /// <returns></returns> public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list of employees for (int i = 0; i < this.List.Count; i++) { // Create a property descriptor for the employee item and add to the property descriptor collection GraphLineCollectionPropertyDescriptor pd = new GraphLineCollectionPropertyDescriptor(this, i); pds.Add(pd); } // return the property descriptor collection return pds; } #endregion public class GraphLineCollectionPropertyDescriptor : PropertyDescriptor { private GraphLineCollection collection = null; private int index = -1; public GraphLineCollectionPropertyDescriptor(GraphLineCollection coll, int idx) : base("#" + idx.ToString(), null) { this.collection = coll; this.index = idx; } public override AttributeCollection Attributes { get { return new AttributeCollection(null); } } public override bool CanResetValue(object component) { return true; } public override Type ComponentType { get { return this.collection.GetType(); } } public override string DisplayName { get { GraphLine emp = this.collection[index]; return (string)(emp.Symbol); } } public override string Description { get { GraphLine emp = this.collection[index]; StringBuilder sb = new StringBuilder(); sb.Append(emp.Symbol); sb.Append(", "); sb.Append(emp.Numberofmeasurements.ToString()); return sb.ToString(); } } public override object GetValue(object component) { return this.collection[index]; } public override bool IsReadOnly { get { return false; } } public override string Name { get { return "#" + index.ToString(); } } public override Type PropertyType { get { return this.collection[index].GetType(); } } public override void ResetValue(object component) { } public override bool ShouldSerializeValue(object component) { return true; } public override void SetValue(object component, object value) { // this.collection[index] = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Security; namespace System.Runtime.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Linq; #if USE_REFEMIT public sealed class ClassDataContract : DataContract #else internal sealed class ClassDataContract : DataContract #endif { public XmlDictionaryString[] ContractNamespaces; public XmlDictionaryString[] MemberNames; public XmlDictionaryString[] MemberNamespaces; private XmlDictionaryString[] _childElementNamespaces; private ClassDataContractCriticalHelper _helper; private bool _isScriptObject; internal ClassDataContract(Type type) : base(new ClassDataContractCriticalHelper(type)) { InitClassDataContract(); } private ClassDataContract(Type type, XmlDictionaryString ns, string[] memberNames) : base(new ClassDataContractCriticalHelper(type, ns, memberNames)) { InitClassDataContract(); } private void InitClassDataContract() { _helper = base.Helper as ClassDataContractCriticalHelper; this.ContractNamespaces = _helper.ContractNamespaces; this.MemberNames = _helper.MemberNames; this.MemberNamespaces = _helper.MemberNamespaces; _isScriptObject = _helper.IsScriptObject; } internal ClassDataContract BaseContract { get { return _helper.BaseContract; } } internal List<DataMember> Members { get { return _helper.Members; } } public XmlDictionaryString[] ChildElementNamespaces { get { if (_childElementNamespaces == null) { lock (this) { if (_childElementNamespaces == null) { if (_helper.ChildElementNamespaces == null) { XmlDictionaryString[] tempChildElementamespaces = CreateChildElementNamespaces(); Interlocked.MemoryBarrier(); _helper.ChildElementNamespaces = tempChildElementamespaces; } _childElementNamespaces = _helper.ChildElementNamespaces; } } } return _childElementNamespaces; } set { _childElementNamespaces = value; } } internal MethodInfo OnSerializing { get { return _helper.OnSerializing; } } internal MethodInfo OnSerialized { get { return _helper.OnSerialized; } } internal MethodInfo OnDeserializing { get { return _helper.OnDeserializing; } } internal MethodInfo OnDeserialized { get { return _helper.OnDeserialized; } } internal MethodInfo ExtensionDataSetMethod { get { return _helper.ExtensionDataSetMethod; } } public override DataContractDictionary KnownDataContracts { get { return _helper.KnownDataContracts; } } public override bool IsISerializable { get { return _helper.IsISerializable; } set { _helper.IsISerializable = value; } } internal bool IsNonAttributedType { get { return _helper.IsNonAttributedType; } } public bool HasExtensionData { get { return _helper.HasExtensionData; } set { _helper.HasExtensionData = value; } } internal bool IsKeyValuePairAdapter { get { return _helper.IsKeyValuePairAdapter; } } internal Type[] KeyValuePairGenericArguments { get { return _helper.KeyValuePairGenericArguments; } } internal ConstructorInfo KeyValuePairAdapterConstructorInfo { get { return _helper.KeyValuePairAdapterConstructorInfo; } } internal MethodInfo GetKeyValuePairMethodInfo { get { return _helper.GetKeyValuePairMethodInfo; } } internal ConstructorInfo GetISerializableConstructor() { return _helper.GetISerializableConstructor(); } private ConstructorInfo _nonAttributedTypeConstructor; internal ConstructorInfo GetNonAttributedTypeConstructor() { if (_nonAttributedTypeConstructor == null) { // Cache the ConstructorInfo to improve performance. _nonAttributedTypeConstructor = _helper.GetNonAttributedTypeConstructor(); } return _nonAttributedTypeConstructor; } private Func<object> _makeNewInstance; private Func<object> MakeNewInstance { get { if (_makeNewInstance == null) { _makeNewInstance = FastInvokerBuilder.GetMakeNewInstanceFunc(UnderlyingType); } return _makeNewInstance; } } internal bool CreateNewInstanceViaDefaultConstructor(out object obj) { ConstructorInfo ci = GetNonAttributedTypeConstructor(); if (ci == null) { obj = null; return false; } if (ci.IsPublic) { // Optimization for calling public default ctor. obj = MakeNewInstance(); } else { obj = ci.Invoke(Array.Empty<object>()); } return true; } private XmlFormatClassWriterDelegate CreateXmlFormatWriterDelegate() { return new XmlFormatWriterGenerator().GenerateClassWriter(this); } internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get { if (_helper.XmlFormatWriterDelegate == null) { lock (this) { if (_helper.XmlFormatWriterDelegate == null) { XmlFormatClassWriterDelegate tempDelegate = CreateXmlFormatWriterDelegate(); Interlocked.MemoryBarrier(); _helper.XmlFormatWriterDelegate = tempDelegate; } } } return _helper.XmlFormatWriterDelegate; } set { } } private XmlFormatClassReaderDelegate CreateXmlFormatReaderDelegate() { return new XmlFormatReaderGenerator().GenerateClassReader(this); } internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get { if (_helper.XmlFormatReaderDelegate == null) { lock (this) { if (_helper.XmlFormatReaderDelegate == null) { XmlFormatClassReaderDelegate tempDelegate = CreateXmlFormatReaderDelegate(); Interlocked.MemoryBarrier(); _helper.XmlFormatReaderDelegate = tempDelegate; } } } return _helper.XmlFormatReaderDelegate; } set { } } internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames) { ClassDataContract cdc = (ClassDataContract)DataContract.GetDataContractFromGeneratedAssembly(type); if (cdc == null) { return new ClassDataContract(type, ns, memberNames); } else { ClassDataContract cloned = cdc.Clone(); cloned.UpdateNamespaceAndMembers(type, ns, memberNames); return cloned; } } internal static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable) { DataMember existingMemberContract; if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract)) { Type declaringType = memberContract.MemberInfo.DeclaringType; DataContract.ThrowInvalidDataContractException( SR.Format((declaringType.IsEnum ? SR.DupEnumMemberValue : SR.DupMemberName), existingMemberContract.MemberInfo.Name, memberContract.MemberInfo.Name, DataContract.GetClrTypeFullName(declaringType), memberContract.Name), declaringType); } memberNamesTable.Add(memberContract.Name, memberContract); members.Add(memberContract); } internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary) { childType = DataContract.UnwrapNullableType(childType); if (!childType.IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType) && DataContract.GetBuiltInDataContract(childType) == null && childType != Globals.TypeOfDBNull) { string ns = DataContract.GetStableName(childType).Namespace; if (ns.Length > 0 && ns != dataContract.Namespace.Value) return dictionary.Add(ns); } return null; } private static bool IsArraySegment(Type t) { return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>)); } /// <SecurityNote> /// RequiresReview - callers may need to depend on isNonAttributedType for a security decision /// isNonAttributedType must be calculated correctly /// IsNonAttributedTypeValidForSerialization is used as part of the isNonAttributedType calculation and /// is therefore marked SRR /// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value /// </SecurityNote> internal static bool IsNonAttributedTypeValidForSerialization(Type type) { if (type.IsArray) return false; if (type.IsEnum) return false; if (type.IsGenericParameter) return false; if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) return false; if (type.IsPointer) return false; if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) return false; Type[] interfaceTypes = type.GetInterfaces(); if (!IsArraySegment(type)) { foreach (Type interfaceType in interfaceTypes) { if (CollectionDataContract.IsCollectionInterface(interfaceType)) return false; } } if (type.IsSerializable) return false; if (Globals.TypeOfISerializable.IsAssignableFrom(type)) return false; if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) return false; if (type.IsValueType) { return type.IsVisible; } else { return (type.IsVisible && type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()) != null); } } private static readonly Dictionary<string, string[]> s_knownSerializableTypeInfos = new Dictionary<string, string[]> { { "System.Collections.Generic.KeyValuePair`2", Array.Empty<string>() }, { "System.Collections.Generic.Queue`1", new[] { "_syncRoot" } }, { "System.Collections.Generic.Stack`1", new[] {"_syncRoot" } }, { "System.Collections.ObjectModel.ReadOnlyCollection`1", new[] {"_syncRoot" } }, { "System.Collections.ObjectModel.ReadOnlyDictionary`2", new[] {"_syncRoot", "_keys", "_values" } }, { "System.Tuple`1", Array.Empty<string>() }, { "System.Tuple`2", Array.Empty<string>() }, { "System.Tuple`3", Array.Empty<string>() }, { "System.Tuple`4", Array.Empty<string>() }, { "System.Tuple`5", Array.Empty<string>() }, { "System.Tuple`6", Array.Empty<string>() }, { "System.Tuple`7", Array.Empty<string>() }, { "System.Tuple`8", Array.Empty<string>() }, { "System.Collections.Queue", new[] {"_syncRoot" } }, { "System.Collections.Stack", new[] {"_syncRoot" } }, { "System.Globalization.CultureInfo", Array.Empty<string>() }, { "System.Version", Array.Empty<string>() }, }; private static string GetGeneralTypeName(Type type) { return type.IsGenericType && !type.IsGenericParameter ? type.GetGenericTypeDefinition().FullName : type.FullName; } internal static bool IsKnownSerializableType(Type type) { // Applies to known types that DCS understands how to serialize/deserialize // string typeFullName = GetGeneralTypeName(type); return s_knownSerializableTypeInfos.ContainsKey(typeFullName); } internal static bool IsNonSerializedMember(Type type, string memberName) { string typeFullName = GetGeneralTypeName(type); string[] members; return s_knownSerializableTypeInfos.TryGetValue(typeFullName, out members) && members.Contains(memberName); } private XmlDictionaryString[] CreateChildElementNamespaces() { if (Members == null) return null; XmlDictionaryString[] baseChildElementNamespaces = null; if (this.BaseContract != null) baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces; int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0; XmlDictionaryString[] childElementNamespaces = new XmlDictionaryString[Members.Count + baseChildElementNamespaceCount]; if (baseChildElementNamespaceCount > 0) Array.Copy(baseChildElementNamespaces, 0, childElementNamespaces, 0, baseChildElementNamespaces.Length); XmlDictionary dictionary = new XmlDictionary(); for (int i = 0; i < this.Members.Count; i++) { childElementNamespaces[i + baseChildElementNamespaceCount] = GetChildNamespaceToDeclare(this, this.Members[i].MemberType, dictionary); } return childElementNamespaces; } private void EnsureMethodsImported() { _helper.EnsureMethodsImported(); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (_isScriptObject) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } XmlFormatWriterDelegate(xmlWriter, obj, context, this); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { if (_isScriptObject) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } xmlReader.Read(); object o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces); xmlReader.ReadEndElement(); return o; } /// <SecurityNote> /// Review - calculates whether this class requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForRead(SecurityException securityException) { EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForRead(securityException)) return true; if (ConstructorRequiresMemberAccess(GetNonAttributedTypeConstructor())) { if (Globals.TypeOfScriptObject_IsAssignableFrom(UnderlyingType)) { return true; } if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustNonAttributedSerializableTypeNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnDeserializing)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnDeserializingNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnDeserializing.Name), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnDeserialized)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnDeserializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnDeserialized.Name), securityException)); } return true; } if (this.Members != null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForSet()) { if (securityException != null) { if (this.Members[i].MemberInfo is FieldInfo) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractFieldSetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractPropertySetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } } return true; } } } return false; } /// <SecurityNote> /// Review - calculates whether this class requires MemberAccessPermission for serialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForWrite(SecurityException securityException) { EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForWrite(securityException)) return true; if (MethodRequiresMemberAccess(this.OnSerializing)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnSerializingNotPublic, DataContract.GetClrTypeFullName(this.UnderlyingType), this.OnSerializing.Name), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnSerialized)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnSerializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnSerialized.Name), securityException)); } return true; } if (this.Members != null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForGet()) { if (securityException != null) { if (this.Members[i].MemberInfo is FieldInfo) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractFieldGetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractPropertyGetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } } return true; } } } return false; } private class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private static Type[] s_serInfoCtorArgs; private ClassDataContract _baseContract; private List<DataMember> _members; private MethodInfo _onSerializing, _onSerialized; private MethodInfo _onDeserializing, _onDeserialized; private MethodInfo _extensionDataSetMethod; private DataContractDictionary _knownDataContracts; private bool _isISerializable; private bool _isKnownTypeAttributeChecked; private bool _isMethodChecked; /// <SecurityNote> /// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and hasDataContract /// </SecurityNote> private bool _isNonAttributedType; /// <SecurityNote> /// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and isNonAttributedType /// </SecurityNote> private bool _hasDataContract; private bool _hasExtensionData; private readonly bool _isScriptObject; private XmlDictionaryString[] _childElementNamespaces; private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate; private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate; public XmlDictionaryString[] ContractNamespaces; public XmlDictionaryString[] MemberNames; public XmlDictionaryString[] MemberNamespaces; internal ClassDataContractCriticalHelper() : base() { } internal ClassDataContractCriticalHelper(Type type) : base(type) { XmlQualifiedName stableName = GetStableNameAndSetHasDataContract(type); if (type == Globals.TypeOfDBNull) { this.StableName = stableName; _members = new List<DataMember>(); XmlDictionary dictionary = new XmlDictionary(2); this.Name = dictionary.Add(StableName.Name); this.Namespace = dictionary.Add(StableName.Namespace); this.ContractNamespaces = this.MemberNames = this.MemberNamespaces = Array.Empty<XmlDictionaryString>(); EnsureMethodsImported(); return; } Type baseType = type.BaseType; _isISerializable = (Globals.TypeOfISerializable.IsAssignableFrom(type)); SetIsNonAttributedType(type); if (_isISerializable) { if (HasDataContract) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.ISerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type)))); if (baseType != null && !(baseType.IsSerializable && Globals.TypeOfISerializable.IsAssignableFrom(baseType))) baseType = null; } SetKeyValuePairAdapterFlags(type); this.IsValueType = type.IsValueType; if (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) { // dotnet/corefx#19629: a DataContract created at runtime does not work with the base DataContract // pre-generated by SG. It's because the runtime DataContract requires full information of a base DataContract // while a pre-generated DataContract is incomplete. // // At this point in code, we're in the midlle of creating a new DataContract at runtime, so we need to make // sure that we create our own base type DataContract when the base type could potentially have SG generated // DataContract. // // We wanted to enable the fix for the issue described above only when SG generated DataContracts are available. // Currently we don't have a good way of detecting usage of SG (either globally or per data contract). DataContract baseContract = DataContract.GetDataContract(baseType); if (baseContract is CollectionDataContract) { this.BaseContract = ((CollectionDataContract)baseContract).SharedTypeContract as ClassDataContract; } else { this.BaseContract = baseContract as ClassDataContract; } if (this.BaseContract != null && this.BaseContract.IsNonAttributedType && !_isNonAttributedType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError (new InvalidDataContractException(SR.Format(SR.AttributedTypesCannotInheritFromNonAttributedSerializableTypes, DataContract.GetClrTypeFullName(type), DataContract.GetClrTypeFullName(baseType)))); } } else { this.BaseContract = null; } _hasExtensionData = (Globals.TypeOfIExtensibleDataObject.IsAssignableFrom(type)); if (_hasExtensionData && !HasDataContract && !IsNonAttributedType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.OnlyDataContractTypesCanHaveExtensionData, DataContract.GetClrTypeFullName(type)))); } if (_isISerializable) { SetDataContractName(stableName); } else { this.StableName = stableName; ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(2 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = dictionary.Add(StableName.Namespace); int baseMemberCount = 0; int baseContractCount = 0; if (BaseContract == null) { MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; ContractNamespaces = new XmlDictionaryString[1]; } else { baseMemberCount = BaseContract.MemberNames.Length; MemberNames = new XmlDictionaryString[Members.Count + baseMemberCount]; Array.Copy(BaseContract.MemberNames, 0, MemberNames, 0, baseMemberCount); MemberNamespaces = new XmlDictionaryString[Members.Count + baseMemberCount]; Array.Copy(BaseContract.MemberNamespaces, 0, MemberNamespaces, 0, baseMemberCount); baseContractCount = BaseContract.ContractNamespaces.Length; ContractNamespaces = new XmlDictionaryString[1 + baseContractCount]; Array.Copy(BaseContract.ContractNamespaces, 0, ContractNamespaces, 0, baseContractCount); } ContractNamespaces[baseContractCount] = Namespace; for (int i = 0; i < Members.Count; i++) { MemberNames[i + baseMemberCount] = dictionary.Add(Members[i].Name); MemberNamespaces[i + baseMemberCount] = Namespace; } } EnsureMethodsImported(); _isScriptObject = this.IsNonAttributedType && Globals.TypeOfScriptObject_IsAssignableFrom(this.UnderlyingType); } internal ClassDataContractCriticalHelper(Type type, XmlDictionaryString ns, string[] memberNames) : base(type) { this.StableName = new XmlQualifiedName(GetStableNameAndSetHasDataContract(type).Name, ns.Value); ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(1 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = ns; ContractNamespaces = new XmlDictionaryString[] { Namespace }; MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; for (int i = 0; i < Members.Count; i++) { Members[i].Name = memberNames[i]; MemberNames[i] = dictionary.Add(Members[i].Name); MemberNamespaces[i] = Namespace; } EnsureMethodsImported(); } private void EnsureIsReferenceImported(Type type) { DataContractAttribute dataContractAttribute; bool isReference = false; bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute); if (BaseContract != null) { if (hasDataContractAttribute && dataContractAttribute.IsReferenceSetExplicitly) { bool baseIsReference = this.BaseContract.IsReference; if ((baseIsReference && !dataContractAttribute.IsReference) || (!baseIsReference && dataContractAttribute.IsReference)) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.InconsistentIsReference, DataContract.GetClrTypeFullName(type), dataContractAttribute.IsReference, DataContract.GetClrTypeFullName(this.BaseContract.UnderlyingType), this.BaseContract.IsReference), type); } else { isReference = dataContractAttribute.IsReference; } } else { isReference = this.BaseContract.IsReference; } } else if (hasDataContractAttribute) { if (dataContractAttribute.IsReference) isReference = dataContractAttribute.IsReference; } if (isReference && type.IsValueType) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.ValueTypeCannotHaveIsReference, DataContract.GetClrTypeFullName(type), true, false), type); return; } this.IsReference = isReference; } private void ImportDataMembers() { Type type = this.UnderlyingType; EnsureIsReferenceImported(type); List<DataMember> tempMembers = new List<DataMember>(); Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>(); MemberInfo[] memberInfos; bool isPodSerializable = !_isNonAttributedType || IsKnownSerializableType(type); if (!isPodSerializable) { memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); } else { memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } for (int i = 0; i < memberInfos.Length; i++) { MemberInfo member = memberInfos[i]; if (HasDataContract) { object[] memberAttributes = member.GetCustomAttributes(typeof(DataMemberAttribute), false).ToArray(); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); DataMember memberContract = new DataMember(member); if (member is PropertyInfo) { PropertyInfo property = (PropertyInfo)member; MethodInfo getMethod = property.GetMethod; if (getMethod != null && IsMethodOverriding(getMethod)) continue; MethodInfo setMethod = property.SetMethod; if (setMethod != null && IsMethodOverriding(setMethod)) continue; if (getMethod == null) ThrowInvalidDataContractException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property.Name)); if (setMethod == null) { if (!SetIfGetOnlyCollection(memberContract)) { ThrowInvalidDataContractException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property.Name)); } } if (getMethod.GetParameters().Length > 0) ThrowInvalidDataContractException(SR.Format(SR.IndexedPropertyCannotBeSerialized, property.DeclaringType, property.Name)); } else if (!(member is FieldInfo)) ThrowInvalidDataContractException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(type), member.Name)); DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0]; if (memberAttribute.IsNameSetExplicitly) { if (memberAttribute.Name == null || memberAttribute.Name.Length == 0) ThrowInvalidDataContractException(SR.Format(SR.InvalidDataMemberName, member.Name, DataContract.GetClrTypeFullName(type))); memberContract.Name = memberAttribute.Name; } else memberContract.Name = member.Name; memberContract.Name = DataContract.EncodeLocalName(memberContract.Name); memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); memberContract.IsRequired = memberAttribute.IsRequired; if (memberAttribute.IsRequired && this.IsReference) { ThrowInvalidDataContractException( SR.Format(SR.IsRequiredDataMemberOnIsReferenceDataContractType, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name, true), type); } memberContract.EmitDefaultValue = memberAttribute.EmitDefaultValue; memberContract.Order = memberAttribute.Order; CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } else if (!isPodSerializable) { FieldInfo field = member as FieldInfo; PropertyInfo property = member as PropertyInfo; if ((field == null && property == null) || (field != null && field.IsInitOnly)) continue; object[] memberAttributes = member.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).ToArray(); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); else continue; } DataMember memberContract = new DataMember(member); if (property != null) { MethodInfo getMethod = property.GetGetMethod(); if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0) continue; MethodInfo setMethod = property.SetMethod; if (setMethod == null) { if (!SetIfGetOnlyCollection(memberContract)) continue; } else { if (!setMethod.IsPublic || IsMethodOverriding(setMethod)) continue; } } memberContract.Name = DataContract.EncodeLocalName(member.Name); memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } else { FieldInfo field = member as FieldInfo; bool canSerializeMember; // Previously System.SerializableAttribute was not available in NetCore, so we had // a list of known [Serializable] types for type in the framework. Although now SerializableAttribute // is available in NetCore, some framework types still do not have [Serializable] // yet, e.g. ReadOnlyDictionary<TKey, TValue>. So, we still need to maintain the known serializable // type list. if (IsKnownSerializableType(type)) { canSerializeMember = CanSerializeMember(field); } else { canSerializeMember = field != null && !field.IsNotSerialized; } if (canSerializeMember) { DataMember memberContract = new DataMember(member); memberContract.Name = DataContract.EncodeLocalName(member.Name); object[] optionalFields = field.GetCustomAttributes(Globals.TypeOfOptionalFieldAttribute, false); if (optionalFields == null || optionalFields.Length == 0) { if (this.IsReference) { ThrowInvalidDataContractException( SR.Format(SR.NonOptionalFieldMemberOnIsReferenceSerializableType, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name, true), type); } memberContract.IsRequired = true; } memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } } if (tempMembers.Count > 1) tempMembers.Sort(DataMemberComparer.Singleton); SetIfMembersHaveConflict(tempMembers); Interlocked.MemoryBarrier(); _members = tempMembers; } private static bool CanSerializeMember(FieldInfo field) { return field != null && !ClassDataContract.IsNonSerializedMember(field.DeclaringType, field.Name); } private bool SetIfGetOnlyCollection(DataMember memberContract) { //OK to call IsCollection here since the use of surrogated collection types is not supported in get-only scenarios if (CollectionDataContract.IsCollection(memberContract.MemberType, false /*isConstructorRequired*/) && !memberContract.MemberType.IsValueType) { memberContract.IsGetOnlyCollection = true; return true; } return false; } private void SetIfMembersHaveConflict(List<DataMember> members) { if (BaseContract == null) return; int baseTypeIndex = 0; List<Member> membersInHierarchy = new List<Member>(); foreach (DataMember member in members) { membersInHierarchy.Add(new Member(member, this.StableName.Namespace, baseTypeIndex)); } ClassDataContract currContract = BaseContract; while (currContract != null) { baseTypeIndex++; foreach (DataMember member in currContract.Members) { membersInHierarchy.Add(new Member(member, currContract.StableName.Namespace, baseTypeIndex)); } currContract = currContract.BaseContract; } IComparer<Member> comparer = DataMemberConflictComparer.Singleton; membersInHierarchy.Sort(comparer); for (int i = 0; i < membersInHierarchy.Count - 1; i++) { int startIndex = i; int endIndex = i; bool hasConflictingType = false; while (endIndex < membersInHierarchy.Count - 1 && string.CompareOrdinal(membersInHierarchy[endIndex].member.Name, membersInHierarchy[endIndex + 1].member.Name) == 0 && string.CompareOrdinal(membersInHierarchy[endIndex].ns, membersInHierarchy[endIndex + 1].ns) == 0) { membersInHierarchy[endIndex].member.ConflictingMember = membersInHierarchy[endIndex + 1].member; if (!hasConflictingType) { if (membersInHierarchy[endIndex + 1].member.HasConflictingNameAndType) { hasConflictingType = true; } else { hasConflictingType = (membersInHierarchy[endIndex].member.MemberType != membersInHierarchy[endIndex + 1].member.MemberType); } } endIndex++; } if (hasConflictingType) { for (int j = startIndex; j <= endIndex; j++) { membersInHierarchy[j].member.HasConflictingNameAndType = true; } } i = endIndex + 1; } } private XmlQualifiedName GetStableNameAndSetHasDataContract(Type type) { return DataContract.GetStableName(type, out _hasDataContract); } /// <SecurityNote> /// RequiresReview - marked SRR because callers may need to depend on isNonAttributedType for a security decision /// isNonAttributedType must be calculated correctly /// SetIsNonAttributedType should not be called before GetStableNameAndSetHasDataContract since it /// is dependent on the correct calculation of hasDataContract /// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value /// </SecurityNote> private void SetIsNonAttributedType(Type type) { _isNonAttributedType = !type.IsSerializable && !_hasDataContract && IsNonAttributedTypeValidForSerialization(type); } private static bool IsMethodOverriding(MethodInfo method) { return method.IsVirtual && ((method.Attributes & MethodAttributes.NewSlot) == 0); } internal void EnsureMethodsImported() { if (!_isMethodChecked && UnderlyingType != null) { lock (this) { if (!_isMethodChecked) { Type type = this.UnderlyingType; MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methods.Length; i++) { MethodInfo method = methods[i]; Type prevAttributeType = null; ParameterInfo[] parameters = method.GetParameters(); if (HasExtensionData && IsValidExtensionDataSetMethod(method, parameters)) { if (method.Name == Globals.ExtensionDataSetExplicitMethod || !method.IsPublic) _extensionDataSetMethod = XmlFormatGeneratorStatics.ExtensionDataSetExplicitMethodInfo; else _extensionDataSetMethod = method; } if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializingAttribute, _onSerializing, ref prevAttributeType)) _onSerializing = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializedAttribute, _onSerialized, ref prevAttributeType)) _onSerialized = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializingAttribute, _onDeserializing, ref prevAttributeType)) _onDeserializing = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializedAttribute, _onDeserialized, ref prevAttributeType)) _onDeserialized = method; } Interlocked.MemoryBarrier(); _isMethodChecked = true; } } } } private bool IsValidExtensionDataSetMethod(MethodInfo method, ParameterInfo[] parameters) { if (method.Name == Globals.ExtensionDataSetExplicitMethod || method.Name == Globals.ExtensionDataSetMethod) { if (_extensionDataSetMethod != null) ThrowInvalidDataContractException(SR.Format(SR.DuplicateExtensionDataSetMethod, method, _extensionDataSetMethod, DataContract.GetClrTypeFullName(method.DeclaringType))); if (method.ReturnType != Globals.TypeOfVoid) DataContract.ThrowInvalidDataContractException(SR.Format(SR.ExtensionDataSetMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfExtensionDataObject) DataContract.ThrowInvalidDataContractException(SR.Format(SR.ExtensionDataSetParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfExtensionDataObject), method.DeclaringType); return true; } return false; } private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType) { if (method.IsDefined(attributeType, false)) { if (currentCallback != null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); else if (prevAttributeType != null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateAttribute, prevAttributeType, attributeType, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); else if (method.IsVirtual) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbacksCannotBeVirtualMethods, method, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); else { if (method.ReturnType != Globals.TypeOfVoid) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfStreamingContext), method.DeclaringType); prevAttributeType = attributeType; } return true; } return false; } internal ClassDataContract BaseContract { get { return _baseContract; } set { _baseContract = value; if (_baseContract != null && IsValueType) ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName.Name, StableName.Namespace, _baseContract.StableName.Name, _baseContract.StableName.Namespace)); } } internal List<DataMember> Members { get { return _members; } } internal MethodInfo OnSerializing { get { EnsureMethodsImported(); return _onSerializing; } } internal MethodInfo OnSerialized { get { EnsureMethodsImported(); return _onSerialized; } } internal MethodInfo OnDeserializing { get { EnsureMethodsImported(); return _onDeserializing; } } internal MethodInfo OnDeserialized { get { EnsureMethodsImported(); return _onDeserialized; } } internal MethodInfo ExtensionDataSetMethod { get { EnsureMethodsImported(); return _extensionDataSetMethod; } } internal override DataContractDictionary KnownDataContracts { get { if (_knownDataContracts != null) { return _knownDataContracts; } if (!_isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!_isKnownTypeAttributeChecked) { _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Interlocked.MemoryBarrier(); _isKnownTypeAttributeChecked = true; } } } return _knownDataContracts; } set { _knownDataContracts = value; } } internal override bool IsISerializable { get { return _isISerializable; } set { _isISerializable = value; } } internal bool HasDataContract { get { return _hasDataContract; } } internal bool HasExtensionData { get { return _hasExtensionData; } set { _hasExtensionData = value; } } internal bool IsNonAttributedType { get { return _isNonAttributedType; } } private void SetKeyValuePairAdapterFlags(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter) { _isKeyValuePairAdapter = true; _keyValuePairGenericArguments = type.GetGenericArguments(); _keyValuePairCtorInfo = type.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfKeyValuePair.MakeGenericType(_keyValuePairGenericArguments) }); _getKeyValuePairMethodInfo = type.GetMethod("GetKeyValuePair", Globals.ScanAllMembers); } } private bool _isKeyValuePairAdapter; private Type[] _keyValuePairGenericArguments; private ConstructorInfo _keyValuePairCtorInfo; private MethodInfo _getKeyValuePairMethodInfo; internal bool IsKeyValuePairAdapter { get { return _isKeyValuePairAdapter; } } internal bool IsScriptObject { get { return _isScriptObject; } } internal Type[] KeyValuePairGenericArguments { get { return _keyValuePairGenericArguments; } } internal ConstructorInfo KeyValuePairAdapterConstructorInfo { get { return _keyValuePairCtorInfo; } } internal MethodInfo GetKeyValuePairMethodInfo { get { return _getKeyValuePairMethodInfo; } } internal ConstructorInfo GetISerializableConstructor() { if (!IsISerializable) return null; ConstructorInfo ctor = UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, SerInfoCtorArgs, null); if (ctor == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(UnderlyingType)))); return ctor; } internal ConstructorInfo GetNonAttributedTypeConstructor() { if (!this.IsNonAttributedType) return null; Type type = UnderlyingType; if (type.IsValueType) return null; ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); return ctor; } internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get { return _xmlFormatWriterDelegate; } set { _xmlFormatWriterDelegate = value; } } internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get { return _xmlFormatReaderDelegate; } set { _xmlFormatReaderDelegate = value; } } public XmlDictionaryString[] ChildElementNamespaces { get { return _childElementNamespaces; } set { _childElementNamespaces = value; } } private static Type[] SerInfoCtorArgs { get { if (s_serInfoCtorArgs == null) s_serInfoCtorArgs = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; return s_serInfoCtorArgs; } } internal struct Member { internal Member(DataMember member, string ns, int baseTypeIndex) { this.member = member; this.ns = ns; this.baseTypeIndex = baseTypeIndex; } internal DataMember member; internal string ns; internal int baseTypeIndex; } internal class DataMemberConflictComparer : IComparer<Member> { public int Compare(Member x, Member y) { int nsCompare = string.CompareOrdinal(x.ns, y.ns); if (nsCompare != 0) return nsCompare; int nameCompare = string.CompareOrdinal(x.member.Name, y.member.Name); if (nameCompare != 0) return nameCompare; return x.baseTypeIndex - y.baseTypeIndex; } internal static DataMemberConflictComparer Singleton = new DataMemberConflictComparer(); } internal ClassDataContractCriticalHelper Clone() { ClassDataContractCriticalHelper clonedHelper = new ClassDataContractCriticalHelper(this.UnderlyingType); clonedHelper._baseContract = this._baseContract; clonedHelper._childElementNamespaces = this._childElementNamespaces; clonedHelper.ContractNamespaces = this.ContractNamespaces; clonedHelper._hasDataContract = this._hasDataContract; clonedHelper._isMethodChecked = this._isMethodChecked; clonedHelper._isNonAttributedType = this._isNonAttributedType; clonedHelper.IsReference = this.IsReference; clonedHelper.IsValueType = this.IsValueType; clonedHelper.MemberNames = this.MemberNames; clonedHelper.MemberNamespaces = this.MemberNamespaces; clonedHelper._members = this._members; clonedHelper.Name = this.Name; clonedHelper.Namespace = this.Namespace; clonedHelper._onDeserialized = this._onDeserialized; clonedHelper._onDeserializing = this._onDeserializing; clonedHelper._onSerialized = this._onSerialized; clonedHelper._onSerializing = this._onSerializing; clonedHelper.StableName = this.StableName; clonedHelper.TopLevelElementName = this.TopLevelElementName; clonedHelper.TopLevelElementNamespace = this.TopLevelElementNamespace; clonedHelper._xmlFormatReaderDelegate = this._xmlFormatReaderDelegate; clonedHelper._xmlFormatWriterDelegate = this._xmlFormatWriterDelegate; return clonedHelper; } } internal class DataMemberComparer : IComparer<DataMember> { public int Compare(DataMember x, DataMember y) { int orderCompare = x.Order - y.Order; if (orderCompare != 0) return orderCompare; return string.CompareOrdinal(x.Name, y.Name); } internal static DataMemberComparer Singleton = new DataMemberComparer(); } /// <summary> /// Get object type for Xml/JsonFormmatReaderGenerator /// </summary> internal Type ObjectType { get { Type type = UnderlyingType; if (type.IsValueType && !IsNonAttributedType) { type = Globals.TypeOfValueType; } return type; } } internal ClassDataContract Clone() { ClassDataContract clonedDc = new ClassDataContract(this.UnderlyingType); clonedDc._helper = _helper.Clone(); clonedDc.ContractNamespaces = this.ContractNamespaces; clonedDc.ChildElementNamespaces = this.ChildElementNamespaces; clonedDc.MemberNames = this.MemberNames; clonedDc.MemberNamespaces = this.MemberNamespaces; clonedDc.XmlFormatWriterDelegate = this.XmlFormatWriterDelegate; clonedDc.XmlFormatReaderDelegate = this.XmlFormatReaderDelegate; return clonedDc; } internal void UpdateNamespaceAndMembers(Type type, XmlDictionaryString ns, string[] memberNames) { this.StableName = new XmlQualifiedName(GetStableName(type).Name, ns.Value); this.Namespace = ns; XmlDictionary dictionary = new XmlDictionary(1 + memberNames.Length); this.Name = dictionary.Add(StableName.Name); this.Namespace = ns; this.ContractNamespaces = new XmlDictionaryString[] { ns }; this.MemberNames = new XmlDictionaryString[memberNames.Length]; this.MemberNamespaces = new XmlDictionaryString[memberNames.Length]; for (int i = 0; i < memberNames.Length; i++) { this.MemberNames[i] = dictionary.Add(memberNames[i]); this.MemberNamespaces[i] = ns; } } internal Type UnadaptedClassType { get { if (IsKeyValuePairAdapter) { return Globals.TypeOfKeyValuePair.MakeGenericType(KeyValuePairGenericArguments); } else { return UnderlyingType; } } } } }
// Copyright(C) David W. Jeske, 2013 // Released to the public domain. Use, modify and relicense at will. using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace SimpleScene { // abstract base class for "tangible" Renderable objects public abstract class SSObject : SSObjectBase { public Color4 ambientMatColor = new Color4(0.001f,0.001f,0.001f,1.0f); public Color4 diffuseMatColor = new Color4(1.2f,1.2f,1.2f,1.2f); public Color4 specularMatColor = new Color4(0.8f,0.8f,0.8f,1.0f); public Color4 emissionMatColor = new Color4(1.0f,1.0f,1.0f,1.0f); public float shininessMatColor = 10.0f; public string Name = ""; public float ScaledRadius { get { if (boundingSphere == null) { return 0f; } else { float scaleMax = float.NegativeInfinity; for (int i = 0; i < 3; ++i) { scaleMax = Math.Max(scaleMax, Scale [i]); } return boundingSphere.radius * scaleMax; } } } public SSObject() : base() { Name = String.Format("Unnamed:{0}",this.GetHashCode()); } protected static void resetTexturingState() { GL.Disable(EnableCap.Texture2D); GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, 0); GL.ActiveTexture(TextureUnit.Texture1); GL.BindTexture(TextureTarget.Texture2D, 0); GL.ActiveTexture(TextureUnit.Texture2); GL.BindTexture(TextureTarget.Texture2D, 0); GL.ActiveTexture(TextureUnit.Texture3); GL.BindTexture(TextureTarget.Texture2D, 0); // don't turn off this stuff, because it might be used for the shadowmap. // GL.ActiveTexture(TextureUnit.Texture4);GL.BindTexture(TextureTarget.Texture2D, 0); // GL.ActiveTexture(TextureUnit.Texture5);GL.BindTexture(TextureTarget.Texture2D, 0); // GL.ActiveTexture(TextureUnit.Texture6);GL.BindTexture(TextureTarget.Texture2D, 0); // GL.ActiveTexture(TextureUnit.Texture7);GL.BindTexture(TextureTarget.Texture2D, 0); // GL.ActiveTexture(TextureUnit.Texture8);GL.BindTexture(TextureTarget.Texture2D, 0); } protected void setMaterialState() { // turn off per-vertex color GL.Disable(EnableCap.ColorMaterial); // setup the base color values... GL.Material(MaterialFace.Front, MaterialParameter.Ambient, ambientMatColor); GL.Material(MaterialFace.Front, MaterialParameter.Diffuse, diffuseMatColor); GL.Material(MaterialFace.Front, MaterialParameter.Specular, specularMatColor); GL.Material(MaterialFace.Front, MaterialParameter.Emission, emissionMatColor); GL.Material(MaterialFace.Front, MaterialParameter.Shininess, shininessMatColor); } protected void setDefaultShaderState(SSMainShaderProgram pgm) { if (pgm != null) { pgm.Activate(); pgm.UniDiffTexEnabled = false; pgm.UniSpecTexEnabled = false; pgm.UniAmbTexEnabled = false; pgm.UniBumpTexEnabled = false; pgm.UniObjectWorldTransform = this.worldMat; } } public virtual void Render (ref SSRenderConfig renderConfig) { // compute and set the modelView matrix, by combining the cameraViewMat // with the object's world matrix // ... http://www.songho.ca/opengl/gl_transform.html // ... http://stackoverflow.com/questions/5798226/3d-graphics-processing-how-to-calculate-modelview-matrix Matrix4 modelViewMat = this.worldMat * renderConfig.invCameraViewMat; GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref modelViewMat); resetTexturingState(); if (renderConfig.drawingShadowMap) { return; // skip the rest of setup... } setDefaultShaderState(renderConfig.MainShader); setMaterialState(); GL.Disable(EnableCap.Blend); if (this.renderState.lighted) { GL.Enable(EnableCap.Lighting); GL.ShadeModel(ShadingModel.Flat); } else { GL.Disable(EnableCap.Lighting); } // ... subclass will render the object itself.. } public SSObjectSphere boundingSphere=null; // TODO: fix this, it's object-space radius, world-space position public SSObject collisionShell=null; public virtual bool Intersect(ref SSRay worldSpaceRay, out float distanceAlongRay) { distanceAlongRay = 0.0f; if (boundingSphere != null) { if (boundingSphere.Intersect(ref worldSpaceRay, out distanceAlongRay)) { if (collisionShell != null) { return collisionShell.Intersect(ref worldSpaceRay, out distanceAlongRay); } else { return PreciseIntersect(ref worldSpaceRay, ref distanceAlongRay); } } } return false; } public virtual bool PreciseIntersect(ref SSRay worldSpaceRay, ref float distanceAlongRay) { return true; } public delegate void ChangedEventHandler(SSObject sender); public event ChangedEventHandler OnChanged; public override void ObjectChanged () { if (OnChanged != null) { OnChanged(this); } } } public class SSOBRenderState { public bool lighted = true; public bool visible = true; public bool castsShadow = false; public bool frustumCulling = true; public bool toBeDeleted = false; } // abstract base class for all transformable objects (objects, lights, ...) public abstract class SSObjectBase { // object orientation protected Vector3 _pos; public Vector3 Pos { get { return _pos; } set { _pos = value; this.calcMatFromState();} } protected Vector3 _scale = new Vector3 (1.0f); public Vector3 Scale { get { return _scale; } set { _scale = value; this.calcMatFromState (); } } public float Size { set { Scale = new Vector3(value); } } protected Vector3 _dir; public Vector3 Dir { get { return _dir; } } protected Vector3 _up; public Vector3 Up { get { return _up; } } protected Vector3 _right; public Vector3 Right { get { return _right; } } // transform matricies public Matrix4 localMat; public Matrix4 worldMat; public SSOBRenderState renderState = new SSOBRenderState(); // TODO: use these! private SSObject parent; private ICollection<SSObject> children; public void Orient(Quaternion orientation) { Matrix4 newOrientation = Matrix4.CreateFromQuaternion(orientation); this._dir = new Vector3(newOrientation.M31, newOrientation.M32, newOrientation.M33); this._up = new Vector3(newOrientation.M21, newOrientation.M22, newOrientation.M23); this._right = Vector3.Cross(this._up, this._dir).Normalized(); this.calcMatFromState(); } private float DegreeToRadian(float angleInDegrees) { return (float)Math.PI * angleInDegrees / 180.0f; } public void EulerDegAngleOrient(float XDelta, float YDelta) { Quaternion yaw_Rotation = Quaternion.FromAxisAngle(Vector3.UnitY,DegreeToRadian(-XDelta)); Quaternion pitch_Rotation = Quaternion.FromAxisAngle(Vector3.UnitX,DegreeToRadian(-YDelta)); this.calcMatFromState(); // make sure our local matrix is current // openGL requires pre-multiplation of these matricies... Quaternion qResult = yaw_Rotation * pitch_Rotation * this.localMat.ExtractRotation(); this.Orient(qResult); } public void updateMat(ref Vector3 pos, ref Quaternion orient) { this._pos = pos; Matrix4 mat = Matrix4.CreateFromQuaternion(orient); this._right = new Vector3(mat.M11,mat.M12,mat.M13); this._up = new Vector3(mat.M21,mat.M22,mat.M23); this._dir = new Vector3(mat.M31,mat.M32,mat.M33); calcMatFromState(); } public void updateMat(ref Matrix4 mat) { this._right = new Vector3(mat.M11,mat.M12,mat.M13); this._up = new Vector3(mat.M21,mat.M22,mat.M23); this._dir = new Vector3(mat.M31,mat.M32,mat.M33); this._pos = new Vector3(mat.M41,mat.M42,mat.M43); calcMatFromState(); } protected void updateMat(ref Vector3 dir, ref Vector3 up, ref Vector3 right, ref Vector3 pos) { this._pos = pos; this._dir = dir; this._right = right; this._up = up; calcMatFromState(); } protected void calcMatFromState() { Matrix4 newLocalMat = Matrix4.Identity; // rotation.. newLocalMat.M11 = _right.X; newLocalMat.M12 = _right.Y; newLocalMat.M13 = _right.Z; newLocalMat.M21 = _up.X; newLocalMat.M22 = _up.Y; newLocalMat.M23 = _up.Z; newLocalMat.M31 = _dir.X; newLocalMat.M32 = _dir.Y; newLocalMat.M33 = _dir.Z; newLocalMat *= Matrix4.CreateScale (this._scale); // position newLocalMat.M41 = _pos.X; newLocalMat.M42 = _pos.Y; newLocalMat.M43 = _pos.Z; // compute world transformation Matrix4 newWorldMat; if (this.parent == null) { newWorldMat = newLocalMat; } else { newWorldMat = newLocalMat * this.parent.worldMat; } // apply the transformations this.localMat = newLocalMat; this.worldMat = newWorldMat; ObjectChanged(); } public virtual void ObjectChanged() { } public virtual void Update (float fElapsedMS) {} // constructor public SSObjectBase() { // position at the origin... this._pos = new Vector3(0.0f,0.0f,0.0f); // base-scale this._dir = new Vector3(0.0f,0.0f,1.0f); // Z+ front this._up = new Vector3(0.0f,1.0f,0.0f); // Y+ up this._right = new Vector3(1.0f,0.0f,0.0f); // X+ right this.calcMatFromState(); // rotate here if we want to. } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml; using Mono.Cecil; using Mono.Cecil.Cil; using Xamarin.Forms.Xaml; using Xamarin.Forms.Xaml.Internals; namespace Xamarin.Forms.Build.Tasks { static class NodeILExtensions { public static IEnumerable<Instruction> PushConvertedValue(this ValueNode node, ILContext context, TypeReference targetTypeRef, IEnumerable<ICustomAttributeProvider> attributeProviders, IEnumerable<Instruction> pushServiceProvider, bool boxValueTypes, bool unboxValueTypes) { TypeReference typeConverter = null; foreach (var attributeProvider in attributeProviders) { CustomAttribute typeConverterAttribute; if ( (typeConverterAttribute = attributeProvider.CustomAttributes.FirstOrDefault( cad => TypeConverterAttribute.TypeConvertersType.Contains(cad.AttributeType.FullName))) != null) { typeConverter = typeConverterAttribute.ConstructorArguments[0].Value as TypeReference; break; } } return node.PushConvertedValue(context, targetTypeRef, typeConverter, pushServiceProvider, boxValueTypes, unboxValueTypes); } public static IEnumerable<Instruction> PushConvertedValue(this ValueNode node, ILContext context, FieldReference bpRef, IEnumerable<Instruction> pushServiceProvider, bool boxValueTypes, bool unboxValueTypes) { var module = context.Body.Method.Module; var targetTypeRef = bpRef.GetBindablePropertyType(node, module); var typeConverter = bpRef.GetBindablePropertyTypeConverter(module); return node.PushConvertedValue(context, targetTypeRef, typeConverter, pushServiceProvider, boxValueTypes, unboxValueTypes); } public static IEnumerable<Instruction> PushConvertedValue(this ValueNode node, ILContext context, TypeReference targetTypeRef, TypeReference typeConverter, IEnumerable<Instruction> pushServiceProvider, bool boxValueTypes, bool unboxValueTypes) { var module = context.Body.Method.Module; var str = (string)node.Value; //If the TypeConverter has a ProvideCompiledAttribute that can be resolved, shortcut this var compiledConverterName = typeConverter?.GetCustomAttribute (module.ImportReference(typeof(ProvideCompiledAttribute)))?.ConstructorArguments?.First().Value as string; Type compiledConverterType; if (compiledConverterName != null && (compiledConverterType = Type.GetType (compiledConverterName)) != null) { var compiledConverter = Activator.CreateInstance (compiledConverterType); var converter = typeof(ICompiledTypeConverter).GetMethods ().FirstOrDefault (md => md.Name == "ConvertFromString"); var instructions = (IEnumerable<Instruction>)converter.Invoke (compiledConverter, new object[] { node.Value as string, context.Body.Method.Module, node as BaseNode}); foreach (var i in instructions) yield return i; if (targetTypeRef.IsValueType && boxValueTypes) yield return Instruction.Create (OpCodes.Box, module.ImportReference (targetTypeRef)); yield break; } //If there's a [TypeConverter], use it if (typeConverter != null) { var isExtendedConverter = typeConverter.ImplementsInterface(module.ImportReference(typeof (IExtendedTypeConverter))); var typeConverterCtor = typeConverter.Resolve().Methods.Single(md => md.IsConstructor && md.Parameters.Count == 0); var typeConverterCtorRef = module.ImportReference(typeConverterCtor); var convertFromInvariantStringDefinition = isExtendedConverter ? module.ImportReference(typeof (IExtendedTypeConverter)) .Resolve() .Methods.FirstOrDefault(md => md.Name == "ConvertFromInvariantString" && md.Parameters.Count == 2) : typeConverter.Resolve() .AllMethods() .FirstOrDefault(md => md.Name == "ConvertFromInvariantString" && md.Parameters.Count == 1); var convertFromInvariantStringReference = module.ImportReference(convertFromInvariantStringDefinition); yield return Instruction.Create(OpCodes.Newobj, typeConverterCtorRef); yield return Instruction.Create(OpCodes.Ldstr, node.Value as string); if (isExtendedConverter) { foreach (var instruction in pushServiceProvider) yield return instruction; } yield return Instruction.Create(OpCodes.Callvirt, convertFromInvariantStringReference); if (targetTypeRef.IsValueType && unboxValueTypes) yield return Instruction.Create(OpCodes.Unbox_Any, module.ImportReference(targetTypeRef)); //ConvertFrom returns an object, no need to Box yield break; } var originalTypeRef = targetTypeRef; var isNullable = false; MethodReference nullableCtor = null; if (targetTypeRef.Resolve().FullName == "System.Nullable`1") { var nullableTypeRef = targetTypeRef; targetTypeRef = ((GenericInstanceType)targetTypeRef).GenericArguments[0]; isNullable = true; nullableCtor = originalTypeRef.GetMethods(md => md.IsConstructor && md.Parameters.Count == 1, module).Single().Item1; nullableCtor = nullableCtor.ResolveGenericParameters(nullableTypeRef, module); } var implicitOperator = module.TypeSystem.String.GetImplicitOperatorTo(targetTypeRef, module); //Obvious Built-in conversions if (targetTypeRef.Resolve().BaseType != null && targetTypeRef.Resolve().BaseType.FullName == "System.Enum") yield return PushParsedEnum(targetTypeRef, str, node); else if (targetTypeRef.FullName == "System.Char") yield return Instruction.Create(OpCodes.Ldc_I4, Char.Parse(str)); else if (targetTypeRef.FullName == "System.SByte") yield return Instruction.Create(OpCodes.Ldc_I4, SByte.Parse(str, CultureInfo.InvariantCulture)); else if (targetTypeRef.FullName == "System.Int16") yield return Instruction.Create(OpCodes.Ldc_I4, Int16.Parse(str, CultureInfo.InvariantCulture)); else if (targetTypeRef.FullName == "System.Int32") yield return Instruction.Create(OpCodes.Ldc_I4, Int32.Parse(str, CultureInfo.InvariantCulture)); else if (targetTypeRef.FullName == "System.Int64") yield return Instruction.Create(OpCodes.Ldc_I8, Int64.Parse(str, CultureInfo.InvariantCulture)); else if (targetTypeRef.FullName == "System.Byte") yield return Instruction.Create(OpCodes.Ldc_I4, Byte.Parse(str, CultureInfo.InvariantCulture)); else if (targetTypeRef.FullName == "System.UInt16") yield return Instruction.Create(OpCodes.Ldc_I4, unchecked((int)UInt16.Parse(str, CultureInfo.InvariantCulture))); else if (targetTypeRef.FullName == "System.UInt32") yield return Instruction.Create(OpCodes.Ldc_I4, UInt32.Parse(str, CultureInfo.InvariantCulture)); else if (targetTypeRef.FullName == "System.UInt64") yield return Instruction.Create(OpCodes.Ldc_I8, unchecked((long)UInt64.Parse(str, CultureInfo.InvariantCulture))); else if (targetTypeRef.FullName == "System.Single") yield return Instruction.Create(OpCodes.Ldc_R4, Single.Parse(str, CultureInfo.InvariantCulture)); else if (targetTypeRef.FullName == "System.Double") yield return Instruction.Create(OpCodes.Ldc_R8, Double.Parse(str, CultureInfo.InvariantCulture)); else if (targetTypeRef.FullName == "System.Boolean") { if (Boolean.Parse(str)) yield return Instruction.Create(OpCodes.Ldc_I4_1); else yield return Instruction.Create(OpCodes.Ldc_I4_0); } else if (targetTypeRef.FullName == "System.TimeSpan") { var ts = TimeSpan.Parse(str, CultureInfo.InvariantCulture); var ticks = ts.Ticks; var timeSpanCtor = module.ImportReference(typeof(TimeSpan)) .Resolve() .Methods.FirstOrDefault(md => md.IsConstructor && md.Parameters.Count == 1); var timeSpanCtorRef = module.ImportReference(timeSpanCtor); yield return Instruction.Create(OpCodes.Ldc_I8, ticks); yield return Instruction.Create(OpCodes.Newobj, timeSpanCtorRef); } else if (targetTypeRef.FullName == "System.DateTime") { var dt = DateTime.Parse(str, CultureInfo.InvariantCulture); var ticks = dt.Ticks; var dateTimeCtor = module.ImportReference(typeof(DateTime)) .Resolve() .Methods.FirstOrDefault(md => md.IsConstructor && md.Parameters.Count == 1); var dateTimeCtorRef = module.ImportReference(dateTimeCtor); yield return Instruction.Create(OpCodes.Ldc_I8, ticks); yield return Instruction.Create(OpCodes.Newobj, dateTimeCtorRef); } else if (targetTypeRef.FullName == "System.String" && str.StartsWith("{}", StringComparison.Ordinal)) yield return Instruction.Create(OpCodes.Ldstr, str.Substring(2)); else if (targetTypeRef.FullName == "System.String") yield return Instruction.Create(OpCodes.Ldstr, str); else if (targetTypeRef.FullName == "System.Object") yield return Instruction.Create(OpCodes.Ldstr, str); else if (targetTypeRef.FullName == "System.Decimal") { decimal outdecimal; if (decimal.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out outdecimal)) { var vardef = new VariableDefinition(context.Body.Method.Module.ImportReference(typeof(decimal))); context.Body.Variables.Add(vardef); //Use an extra temp var so we can push the value to the stack, just like other cases // IL_0003: ldstr "adecimal" // IL_0008: ldc.i4.s 0x6f // IL_000a: call class [mscorlib]System.Globalization.CultureInfo class [mscorlib]System.Globalization.CultureInfo::get_InvariantCulture() // IL_000f: ldloca.s 0 // IL_0011: call bool valuetype [mscorlib]System.Decimal::TryParse(string, valuetype [mscorlib]System.Globalization.NumberStyles, class [mscorlib]System.IFormatProvider, [out] valuetype [mscorlib]System.Decimal&) // IL_0016: pop yield return Instruction.Create(OpCodes.Ldstr, str); yield return Instruction.Create(OpCodes.Ldc_I4, 0x6f); //NumberStyles.Number var getInvariantInfo = context.Body.Method.Module.ImportReference(typeof(CultureInfo)) .Resolve() .Properties.FirstOrDefault(pd => pd.Name == "InvariantCulture") .GetMethod; var getInvariant = context.Body.Method.Module.ImportReference(getInvariantInfo); yield return Instruction.Create(OpCodes.Call, getInvariant); yield return Instruction.Create(OpCodes.Ldloca, vardef); var tryParseInfo = context.Body.Method.Module.ImportReference(typeof(decimal)) .Resolve() .Methods.FirstOrDefault(md => md.Name == "TryParse" && md.Parameters.Count == 4); var tryParse = context.Body.Method.Module.ImportReference(tryParseInfo); yield return Instruction.Create(OpCodes.Call, tryParse); yield return Instruction.Create(OpCodes.Pop); yield return Instruction.Create(OpCodes.Ldloc, vardef); } else { yield return Instruction.Create(OpCodes.Ldc_I4_0); var decimalctorinfo = context.Body.Method.Module.ImportReference(typeof(decimal)) .Resolve() .Methods.FirstOrDefault( md => md.IsConstructor && md.Parameters.Count == 1 && md.Parameters[0].ParameterType.FullName == "System.Int32"); var decimalctor = context.Body.Method.Module.ImportReference(decimalctorinfo); yield return Instruction.Create(OpCodes.Newobj, decimalctor); } } else if (implicitOperator != null) { yield return Instruction.Create(OpCodes.Ldstr, node.Value as string); yield return Instruction.Create(OpCodes.Call, module.ImportReference(implicitOperator)); } else yield return Instruction.Create(OpCodes.Ldnull); if (isNullable) yield return Instruction.Create(OpCodes.Newobj, module.ImportReference(nullableCtor)); if (originalTypeRef.IsValueType && boxValueTypes) yield return Instruction.Create(OpCodes.Box, module.ImportReference(originalTypeRef)); } static Instruction PushParsedEnum(TypeReference enumRef, string value, IXmlLineInfo lineInfo) { var enumDef = enumRef.Resolve(); if (!enumDef.IsEnum) throw new InvalidOperationException(); // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. // https://msdn.microsoft.com/en-us/library/sbbt4032.aspx byte b = 0; sbyte sb = 0; short s = 0; ushort us = 0; int i = 0; uint ui = 0; long l = 0; ulong ul = 0; bool found = false; TypeReference typeRef = null; foreach (var field in enumDef.Fields) if (field.Name == "value__") typeRef = field.FieldType; if (typeRef == null) throw new ArgumentException(); foreach (var v in value.Split(',')) { foreach (var field in enumDef.Fields) { if (field.Name == "value__") continue; if (field.Name == v.Trim()) { switch (typeRef.FullName) { case "System.Byte": b |= (byte)field.Constant; break; case "System.SByte": if (found) throw new XamlParseException($"Multi-valued enums are not valid on sbyte enum types", lineInfo); sb = (sbyte)field.Constant; break; case "System.Int16": s |= (short)field.Constant; break; case "System.UInt16": us |= (ushort)field.Constant; break; case "System.Int32": i |= (int)field.Constant; break; case "System.UInt32": ui |= (uint)field.Constant; break; case "System.Int64": l |= (long)field.Constant; break; case "System.UInt64": ul |= (ulong)field.Constant; break; } found = true; } } } if (!found) throw new XamlParseException($"Enum value not found for {value}", lineInfo); switch (typeRef.FullName) { case "System.Byte": return Instruction.Create(OpCodes.Ldc_I4, (int)b); case "System.SByte": return Instruction.Create(OpCodes.Ldc_I4, (int)sb); case "System.Int16": return Instruction.Create(OpCodes.Ldc_I4, (int)s); case "System.UInt16": return Instruction.Create(OpCodes.Ldc_I4, (int)us); case "System.Int32": return Instruction.Create(OpCodes.Ldc_I4, (int)i); case "System.UInt32": return Instruction.Create(OpCodes.Ldc_I4, (uint)ui); case "System.Int64": return Instruction.Create(OpCodes.Ldc_I4, (long)l); case "System.UInt64": return Instruction.Create(OpCodes.Ldc_I4, (ulong)ul); default: throw new XamlParseException($"Enum value not found for {value}", lineInfo); } } public static IEnumerable<Instruction> PushXmlLineInfo(this INode node, ILContext context) { var module = context.Body.Method.Module; var xmlLineInfo = node as IXmlLineInfo; if (xmlLineInfo == null) { yield return Instruction.Create(OpCodes.Ldnull); yield break; } MethodReference ctor; if (xmlLineInfo.HasLineInfo()) { yield return Instruction.Create(OpCodes.Ldc_I4, xmlLineInfo.LineNumber); yield return Instruction.Create(OpCodes.Ldc_I4, xmlLineInfo.LinePosition); ctor = module.ImportReference(typeof (XmlLineInfo).GetConstructor(new[] { typeof (int), typeof (int) })); } else ctor = module.ImportReference(typeof (XmlLineInfo).GetConstructor(new Type[] { })); yield return Instruction.Create(OpCodes.Newobj, ctor); } public static IEnumerable<Instruction> PushParentObjectsArray(this INode node, ILContext context) { var module = context.Body.Method.Module; var nodes = new List<IElementNode>(); INode n = node.Parent; while (n != null) { var en = n as IElementNode; if (en != null && context.Variables.ContainsKey(en)) nodes.Add(en); n = n.Parent; } if (nodes.Count == 0 && context.ParentContextValues == null) { yield return Instruction.Create(OpCodes.Ldnull); yield break; } if (nodes.Count == 0) { yield return Instruction.Create(OpCodes.Ldarg_0); yield return Instruction.Create(OpCodes.Ldfld, context.ParentContextValues); yield break; } //Compute parent object length if (context.ParentContextValues != null) { yield return Instruction.Create(OpCodes.Ldarg_0); yield return Instruction.Create(OpCodes.Ldfld, context.ParentContextValues); yield return Instruction.Create(OpCodes.Ldlen); yield return Instruction.Create(OpCodes.Conv_I4); } else yield return Instruction.Create(OpCodes.Ldc_I4_0); var parentObjectLength = new VariableDefinition(module.TypeSystem.Int32); context.Body.Variables.Add(parentObjectLength); yield return Instruction.Create(OpCodes.Stloc, parentObjectLength); //Create the final array yield return Instruction.Create(OpCodes.Ldloc, parentObjectLength); yield return Instruction.Create(OpCodes.Ldc_I4, nodes.Count); yield return Instruction.Create(OpCodes.Add); yield return Instruction.Create(OpCodes.Newarr, module.TypeSystem.Object); var finalArray = new VariableDefinition(module.ImportReference(typeof (object[]))); context.Body.Variables.Add(finalArray); yield return Instruction.Create(OpCodes.Stloc, finalArray); //Copy original array to final if (context.ParentContextValues != null) { yield return Instruction.Create(OpCodes.Ldarg_0); yield return Instruction.Create(OpCodes.Ldfld, context.ParentContextValues); //sourceArray yield return Instruction.Create(OpCodes.Ldc_I4_0); //sourceIndex yield return Instruction.Create(OpCodes.Ldloc, finalArray); //destinationArray yield return Instruction.Create(OpCodes.Ldc_I4, nodes.Count); //destinationIndex yield return Instruction.Create(OpCodes.Ldloc, parentObjectLength); //length var arrayCopy = module.ImportReference(typeof (Array)) .Resolve() .Methods.First( md => md.Name == "Copy" && md.Parameters.Count == 5 && md.Parameters[1].ParameterType.FullName == module.TypeSystem.Int32.FullName); yield return Instruction.Create(OpCodes.Call, module.ImportReference(arrayCopy)); } //Add nodes to array yield return Instruction.Create(OpCodes.Ldloc, finalArray); if (nodes.Count > 0) { for (var i = 0; i < nodes.Count; i++) { var en = nodes[i]; yield return Instruction.Create(OpCodes.Dup); yield return Instruction.Create(OpCodes.Ldc_I4, i); yield return Instruction.Create(OpCodes.Ldloc, context.Variables[en]); if (context.Variables[en].VariableType.IsValueType) yield return Instruction.Create(OpCodes.Box, module.ImportReference(context.Variables[en].VariableType)); yield return Instruction.Create(OpCodes.Stelem_Ref); } } } static IEnumerable<Instruction> PushTargetProperty(FieldReference bpRef, PropertyReference propertyRef, TypeReference declaringTypeReference, ModuleDefinition module) { if (bpRef != null) { yield return Instruction.Create(OpCodes.Ldsfld, bpRef); yield break; } if (propertyRef != null) { // IL_0000: ldtoken [mscorlib]System.String // IL_0005: call class [mscorlib]System.Type class [mscorlib] System.Type::GetTypeFromHandle(valuetype [mscorlib] System.RuntimeTypeHandle) // IL_000a: ldstr "Foo" // IL_000f: callvirt instance class [mscorlib] System.Reflection.PropertyInfo class [mscorlib] System.Type::GetProperty(string) var getTypeFromHandle = module.ImportReference(typeof(Type).GetMethod("GetTypeFromHandle", new [] { typeof(RuntimeTypeHandle) })); var getPropertyInfo = module.ImportReference(typeof(Type).GetMethod("GetProperty", new [] { typeof(string) })); yield return Instruction.Create(OpCodes.Ldtoken, module.ImportReference(declaringTypeReference ?? propertyRef.DeclaringType)); yield return Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle)); yield return Instruction.Create(OpCodes.Ldstr, propertyRef.Name); yield return Instruction.Create(OpCodes.Callvirt, module.ImportReference(getPropertyInfo)); yield break; } yield return Instruction.Create(OpCodes.Ldnull); yield break; } public static IEnumerable<Instruction> PushServiceProvider(this INode node, ILContext context, FieldReference bpRef = null, PropertyReference propertyRef = null, TypeReference declaringTypeReference = null) { var module = context.Body.Method.Module; #if NOSERVICEPROVIDER yield return Instruction.Create (OpCodes.Ldnull); yield break; #endif var ctorinfo = typeof (XamlServiceProvider).GetConstructor(new Type[] { }); var ctor = module.ImportReference(ctorinfo); var addServiceInfo = typeof (XamlServiceProvider).GetMethod("Add", new[] { typeof (Type), typeof (object) }); var addService = module.ImportReference(addServiceInfo); var getTypeFromHandle = module.ImportReference(typeof (Type).GetMethod("GetTypeFromHandle", new[] { typeof (RuntimeTypeHandle) })); var getAssembly = module.ImportReference(typeof (Type).GetProperty("Assembly").GetMethod); yield return Instruction.Create(OpCodes.Newobj, ctor); //Add a SimpleValueTargetProvider var pushParentIl = node.PushParentObjectsArray(context).ToList(); if (pushParentIl[pushParentIl.Count - 1].OpCode != OpCodes.Ldnull) { yield return Instruction.Create(OpCodes.Dup); //Keep the serviceProvider on the stack yield return Instruction.Create(OpCodes.Ldtoken, module.ImportReference(typeof (IProvideValueTarget))); yield return Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle)); foreach (var instruction in pushParentIl) yield return instruction; foreach (var instruction in PushTargetProperty(bpRef, propertyRef, declaringTypeReference, module)) yield return instruction; var targetProviderCtor = module.ImportReference(typeof (SimpleValueTargetProvider).GetConstructor(new[] { typeof (object[]), typeof(object) })); yield return Instruction.Create(OpCodes.Newobj, targetProviderCtor); yield return Instruction.Create(OpCodes.Callvirt, addService); } //Add a NamescopeProvider if (context.Scopes.ContainsKey(node)) { yield return Instruction.Create(OpCodes.Dup); //Dupicate the serviceProvider yield return Instruction.Create(OpCodes.Ldtoken, module.ImportReference(typeof (INameScopeProvider))); yield return Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle)); var namescopeProviderCtor = module.ImportReference(typeof (NameScopeProvider).GetConstructor(new Type[] { })); yield return Instruction.Create(OpCodes.Newobj, namescopeProviderCtor); yield return Instruction.Create(OpCodes.Dup); //Duplicate the namescopeProvider var setNamescope = module.ImportReference(typeof (NameScopeProvider).GetProperty("NameScope").GetSetMethod()); yield return Instruction.Create(OpCodes.Ldloc, context.Scopes[node].Item1); yield return Instruction.Create(OpCodes.Callvirt, setNamescope); yield return Instruction.Create(OpCodes.Callvirt, addService); } //Add a XamlTypeResolver if (node.NamespaceResolver != null) { yield return Instruction.Create(OpCodes.Dup); //Dupicate the serviceProvider yield return Instruction.Create(OpCodes.Ldtoken, module.ImportReference(typeof (IXamlTypeResolver))); yield return Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle)); var xmlNamespaceResolverCtor = module.ImportReference(typeof (XmlNamespaceResolver).GetConstructor(new Type[] { })); var addNamespace = module.ImportReference(typeof (XmlNamespaceResolver).GetMethod("Add")); yield return Instruction.Create(OpCodes.Newobj, xmlNamespaceResolverCtor); foreach (var kvp in node.NamespaceResolver.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml)) { yield return Instruction.Create(OpCodes.Dup); //dup the resolver yield return Instruction.Create(OpCodes.Ldstr, kvp.Key); yield return Instruction.Create(OpCodes.Ldstr, kvp.Value); yield return Instruction.Create(OpCodes.Callvirt, addNamespace); } yield return Instruction.Create(OpCodes.Ldtoken, context.Body.Method.DeclaringType); yield return Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle)); yield return Instruction.Create(OpCodes.Callvirt, getAssembly); var xtr = module.ImportReference(typeof (XamlTypeResolver)).Resolve(); var xamlTypeResolverCtor = module.ImportReference(xtr.Methods.First(md => md.IsConstructor && md.Parameters.Count == 2)); yield return Instruction.Create(OpCodes.Newobj, xamlTypeResolverCtor); yield return Instruction.Create(OpCodes.Callvirt, addService); } if (node is IXmlLineInfo) { yield return Instruction.Create(OpCodes.Dup); //Dupicate the serviceProvider yield return Instruction.Create(OpCodes.Ldtoken, module.ImportReference(typeof (IXmlLineInfoProvider))); yield return Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle)); foreach (var instruction in node.PushXmlLineInfo(context)) yield return instruction; var lip = module.ImportReference(typeof (XmlLineInfoProvider)).Resolve(); var lineInfoProviderCtor = module.ImportReference(lip.Methods.First(md => md.IsConstructor && md.Parameters.Count == 1)); yield return Instruction.Create(OpCodes.Newobj, lineInfoProviderCtor); yield return Instruction.Create(OpCodes.Callvirt, addService); } } } }
#region Copyright notice and license // Copyright 2018 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Grpc.Tools { /// <summary> /// Run Google proto compiler (protoc). /// /// After a successful run, the task reads the dependency file if specified /// to be saved by the compiler, and returns its output files. /// /// This task (unlike PrepareProtoCompile) does not attempt to guess anything /// about language-specific behavior of protoc, and therefore can be used for /// any language outputs. /// </summary> public class ProtoCompile : ToolTask { /* Usage: /home/kkm/work/protobuf/src/.libs/lt-protoc [OPTION] PROTO_FILES Parse PROTO_FILES and generate output based on the options given: -IPATH, --proto_path=PATH Specify the directory in which to search for imports. May be specified multiple times; directories will be searched in order. If not given, the current working directory is used. --version Show version info and exit. -h, --help Show this text and exit. --encode=MESSAGE_TYPE Read a text-format message of the given type from standard input and write it in binary to standard output. The message type must be defined in PROTO_FILES or their imports. --decode=MESSAGE_TYPE Read a binary message of the given type from standard input and write it in text format to standard output. The message type must be defined in PROTO_FILES or their imports. --decode_raw Read an arbitrary protocol message from standard input and write the raw tag/value pairs in text format to standard output. No PROTO_FILES should be given when using this flag. --descriptor_set_in=FILES Specifies a delimited list of FILES each containing a FileDescriptorSet (a protocol buffer defined in descriptor.proto). The FileDescriptor for each of the PROTO_FILES provided will be loaded from these FileDescriptorSets. If a FileDescriptor appears multiple times, the first occurrence will be used. -oFILE, Writes a FileDescriptorSet (a protocol buffer, --descriptor_set_out=FILE defined in descriptor.proto) containing all of the input files to FILE. --include_imports When using --descriptor_set_out, also include all dependencies of the input files in the set, so that the set is self-contained. --include_source_info When using --descriptor_set_out, do not strip SourceCodeInfo from the FileDescriptorProto. This results in vastly larger descriptors that include information about the original location of each decl in the source file as well as surrounding comments. --dependency_out=FILE Write a dependency output file in the format expected by make. This writes the transitive set of input file paths to FILE --error_format=FORMAT Set the format in which to print errors. FORMAT may be 'gcc' (the default) or 'msvs' (Microsoft Visual Studio format). --print_free_field_numbers Print the free field numbers of the messages defined in the given proto files. Groups share the same field number space with the parent message. Extension ranges are counted as occupied fields numbers. --plugin=EXECUTABLE Specifies a plugin executable to use. Normally, protoc searches the PATH for plugins, but you may specify additional executables not in the path using this flag. Additionally, EXECUTABLE may be of the form NAME=PATH, in which case the given plugin name is mapped to the given executable even if the executable's own name differs. --cpp_out=OUT_DIR Generate C++ header and source. --csharp_out=OUT_DIR Generate C# source file. --java_out=OUT_DIR Generate Java source file. --javanano_out=OUT_DIR Generate Java Nano source file. --js_out=OUT_DIR Generate JavaScript source. --objc_out=OUT_DIR Generate Objective C header and source. --php_out=OUT_DIR Generate PHP source file. --python_out=OUT_DIR Generate Python source file. --ruby_out=OUT_DIR Generate Ruby source file. @<filename> Read options and filenames from file. If a relative file path is specified, the file will be searched in the working directory. The --proto_path option will not affect how this argument file is searched. Content of the file will be expanded in the position of @<filename> as in the argument list. Note that shell expansion is not applied to the content of the file (i.e., you cannot use quotes, wildcards, escapes, commands, etc.). Each line corresponds to a single argument, even if it contains spaces. */ static string[] s_supportedGenerators = new[] { "cpp", "csharp", "java", "javanano", "js", "objc", "php", "python", "ruby" }; static readonly TimeSpan s_regexTimeout = TimeSpan.FromMilliseconds(100); static readonly List<ErrorListFilter> s_errorListFilters = new List<ErrorListFilter>() { // Example warning with location //../Protos/greet.proto(19) : warning in column=5 : warning : When enum name is stripped and label is PascalCased (Zero), // this value label conflicts with Zero. This will make the proto fail to compile for some languages, such as C#. new ErrorListFilter { Pattern = new Regex( pattern: "^(?'FILENAME'.+?)\\((?'LINE'\\d+)\\) ?: ?warning in column=(?'COLUMN'\\d+) ?: ?(?'TEXT'.*)", options: RegexOptions.Compiled | RegexOptions.IgnoreCase, matchTimeout: s_regexTimeout), LogAction = (log, match) => { int.TryParse(match.Groups["LINE"].Value, out var line); int.TryParse(match.Groups["COLUMN"].Value, out var column); log.LogWarning( subcategory: null, warningCode: null, helpKeyword: null, file: match.Groups["FILENAME"].Value, lineNumber: line, columnNumber: column, endLineNumber: 0, endColumnNumber: 0, message: match.Groups["TEXT"].Value); } }, // Example error with location //../Protos/greet.proto(14) : error in column=10: "name" is already defined in "Greet.HelloRequest". new ErrorListFilter { Pattern = new Regex( pattern: "^(?'FILENAME'.+?)\\((?'LINE'\\d+)\\) ?: ?error in column=(?'COLUMN'\\d+) ?: ?(?'TEXT'.*)", options: RegexOptions.Compiled | RegexOptions.IgnoreCase, matchTimeout: s_regexTimeout), LogAction = (log, match) => { int.TryParse(match.Groups["LINE"].Value, out var line); int.TryParse(match.Groups["COLUMN"].Value, out var column); log.LogError( subcategory: null, errorCode: null, helpKeyword: null, file: match.Groups["FILENAME"].Value, lineNumber: line, columnNumber: column, endLineNumber: 0, endColumnNumber: 0, message: match.Groups["TEXT"].Value); } }, // Example warning without location //../Protos/greet.proto: warning: Import google/protobuf/empty.proto but not used. new ErrorListFilter { Pattern = new Regex( pattern: "^(?'FILENAME'.+?): ?warning: ?(?'TEXT'.*)", options: RegexOptions.Compiled | RegexOptions.IgnoreCase, matchTimeout: s_regexTimeout), LogAction = (log, match) => { log.LogWarning( subcategory: null, warningCode: null, helpKeyword: null, file: match.Groups["FILENAME"].Value, lineNumber: 0, columnNumber: 0, endLineNumber: 0, endColumnNumber: 0, message: match.Groups["TEXT"].Value); } }, // Example error without location //../Protos/greet.proto: Import "google/protobuf/empty.proto" was listed twice. new ErrorListFilter { Pattern = new Regex( pattern: "^(?'FILENAME'.+?): ?(?'TEXT'.*)", options: RegexOptions.Compiled | RegexOptions.IgnoreCase, matchTimeout: s_regexTimeout), LogAction = (log, match) => { log.LogError( subcategory: null, errorCode: null, helpKeyword: null, file: match.Groups["FILENAME"].Value, lineNumber: 0, columnNumber: 0, endLineNumber: 0, endColumnNumber: 0, message: match.Groups["TEXT"].Value); } } }; /// <summary> /// Code generator. /// </summary> [Required] public string Generator { get; set; } /// <summary> /// Protobuf files to compile. /// </summary> [Required] public ITaskItem[] Protobuf { get; set; } /// <summary> /// Directory where protoc dependency files are cached. If provided, dependency /// output filename is autogenerated from source directory hash and file name. /// Mutually exclusive with DependencyOut. /// Switch: --dependency_out (with autogenerated file name). /// </summary> public string ProtoDepDir { get; set; } /// <summary> /// Dependency file full name. Mutually exclusive with ProtoDepDir. /// Autogenerated file name is available in this property after execution. /// Switch: --dependency_out. /// </summary> [Output] public string DependencyOut { get; set; } /// <summary> /// The directories to search for imports. Directories will be searched /// in order. If not given, the current working directory is used. /// Switch: --proto_path. /// </summary> public string[] ProtoPath { get; set; } /// <summary> /// Generated code directory. The generator property determines the language. /// Switch: --GEN-out= (for different generators GEN). /// </summary> [Required] public string OutputDir { get; set; } /// <summary> /// Codegen options. See also OptionsFromMetadata. /// Switch: --GEN_out= (for different generators GEN). /// </summary> public string[] OutputOptions { get; set; } /// <summary> /// Full path to the gRPC plugin executable. If specified, gRPC generation /// is enabled for the files. /// Switch: --plugin=protoc-gen-grpc= /// </summary> public string GrpcPluginExe { get; set; } /// <summary> /// Generated gRPC directory. The generator property determines the /// language. If gRPC is enabled but this is not given, OutputDir is used. /// Switch: --grpc_out= /// </summary> public string GrpcOutputDir { get; set; } /// <summary> /// gRPC Codegen options. See also OptionsFromMetadata. /// --grpc_opt=opt1,opt2=val (comma-separated). /// </summary> public string[] GrpcOutputOptions { get; set; } /// <summary> /// List of files written in addition to generated outputs. Includes a /// single item for the dependency file if written. /// </summary> [Output] public ITaskItem[] AdditionalFileWrites { get; private set; } /// <summary> /// List of language files generated by protoc. Empty unless DependencyOut /// or ProtoDepDir is set, since the file writes are extracted from protoc /// dependency output file. /// </summary> [Output] public ITaskItem[] GeneratedFiles { get; private set; } // Hide this property from MSBuild, we should never use a shell script. private new bool UseCommandProcessor { get; set; } protected override string ToolName => Platform.IsWindows ? "protoc.exe" : "protoc"; // Since we never try to really locate protoc.exe somehow, just try ToolExe // as the full tool location. It will be either just protoc[.exe] from // ToolName above if not set by the user, or a user-supplied full path. The // base class will then resolve the former using system PATH. protected override string GenerateFullPathToTool() => ToolExe; // Log protoc errors with the High priority (bold white in MsBuild, // printed with -v:n, and shown in the Output windows in VS). protected override MessageImportance StandardErrorLoggingImportance => MessageImportance.High; // Called by base class to validate arguments and make them consistent. protected override bool ValidateParameters() { // Part of proto command line switches, must be lowercased. Generator = Generator.ToLowerInvariant(); if (!System.Array.Exists(s_supportedGenerators, g => g == Generator)) { Log.LogError("Invalid value for Generator='{0}'. Supported generators: {1}", Generator, string.Join(", ", s_supportedGenerators)); } if (ProtoDepDir != null && DependencyOut != null) { Log.LogError("Properties ProtoDepDir and DependencyOut may not be both specified"); } if (Protobuf.Length > 1 && (ProtoDepDir != null || DependencyOut != null)) { Log.LogError("Proto compiler currently allows only one input when " + "--dependency_out is specified (via ProtoDepDir or DependencyOut). " + "Tracking issue: https://github.com/google/protobuf/pull/3959"); } // Use ProtoDepDir to autogenerate DependencyOut if (ProtoDepDir != null) { DependencyOut = DepFileUtil.GetDepFilenameForProto(ProtoDepDir, Protobuf[0].ItemSpec); } if (GrpcPluginExe == null) { GrpcOutputOptions = null; GrpcOutputDir = null; } else if (GrpcOutputDir == null) { // Use OutputDir for gRPC output if not specified otherwise by user. GrpcOutputDir = OutputDir; } return !Log.HasLoggedErrors && base.ValidateParameters(); } // Protoc chokes on BOM, naturally. I would! static readonly Encoding s_utf8WithoutBom = new UTF8Encoding(false); protected override Encoding ResponseFileEncoding => s_utf8WithoutBom; // Protoc takes one argument per line from the response file, and does not // require any quoting whatsoever. Otherwise, this is similar to the // standard CommandLineBuilder class ProtocResponseFileBuilder { StringBuilder _data = new StringBuilder(1000); public override string ToString() => _data.ToString(); // If 'value' is not empty, append '--name=value\n'. public void AddSwitchMaybe(string name, string value) { if (!string.IsNullOrEmpty(value)) { _data.Append("--").Append(name).Append("=") .Append(value).Append('\n'); } } // Add switch with the 'values' separated by commas, for options. public void AddSwitchMaybe(string name, string[] values) { if (values?.Length > 0) { _data.Append("--").Append(name).Append("=") .Append(string.Join(",", values)).Append('\n'); } } // Add a positional argument to the file data. public void AddArg(string arg) { _data.Append(arg).Append('\n'); } }; // Called by the base ToolTask to get response file contents. protected override string GenerateResponseFileCommands() { var cmd = new ProtocResponseFileBuilder(); cmd.AddSwitchMaybe(Generator + "_out", TrimEndSlash(OutputDir)); cmd.AddSwitchMaybe(Generator + "_opt", OutputOptions); cmd.AddSwitchMaybe("plugin=protoc-gen-grpc", GrpcPluginExe); cmd.AddSwitchMaybe("grpc_out", TrimEndSlash(GrpcOutputDir)); cmd.AddSwitchMaybe("grpc_opt", GrpcOutputOptions); if (ProtoPath != null) { foreach (string path in ProtoPath) { cmd.AddSwitchMaybe("proto_path", TrimEndSlash(path)); } } cmd.AddSwitchMaybe("dependency_out", DependencyOut); cmd.AddSwitchMaybe("error_format", "msvs"); foreach (var proto in Protobuf) { cmd.AddArg(proto.ItemSpec); } return cmd.ToString(); } // Protoc cannot digest trailing slashes in directory names, // curiously under Linux, but not in Windows. static string TrimEndSlash(string dir) { if (dir == null || dir.Length <= 1) { return dir; } string trim = dir.TrimEnd('/', '\\'); // Do not trim the root slash, drive letter possible. if (trim.Length == 0) { // Slashes all the way down. return dir.Substring(0, 1); } if (trim.Length == 2 && dir.Length > 2 && trim[1] == ':') { // We have a drive letter and root, e. g. 'C:\' return dir.Substring(0, 3); } return trim; } // Called by the base class to log tool's command line. // // Protoc command file is peculiar, with one argument per line, separated // by newlines. Unwrap it for log readability into a single line, and also // quote arguments, lest it look weird and so it may be copied and pasted // into shell. Since this is for logging only, correct enough is correct. protected override void LogToolCommand(string cmd) { var printer = new StringBuilder(1024); // Print 'str' slice into 'printer', wrapping in quotes if contains some // interesting characters in file names, or if empty string. The list of // characters requiring quoting is not by any means exhaustive; we are // just striving to be nice, not guaranteeing to be nice. var quotable = new[] { ' ', '!', '$', '&', '\'', '^' }; void PrintQuoting(string str, int start, int count) { bool wrap = count == 0 || str.IndexOfAny(quotable, start, count) >= 0; if (wrap) printer.Append('"'); printer.Append(str, start, count); if (wrap) printer.Append('"'); } for (int ib = 0, ie; (ie = cmd.IndexOf('\n', ib)) >= 0; ib = ie + 1) { // First line only contains both the program name and the first switch. // We can rely on at least the '--out_dir' switch being always present. if (ib == 0) { int iep = cmd.IndexOf(" --"); if (iep > 0) { PrintQuoting(cmd, 0, iep); ib = iep + 1; } } printer.Append(' '); if (cmd[ib] == '-') { // Print switch unquoted, including '=' if any. int iarg = cmd.IndexOf('=', ib, ie - ib); if (iarg < 0) { // Bare switch without a '='. printer.Append(cmd, ib, ie - ib); continue; } printer.Append(cmd, ib, iarg + 1 - ib); ib = iarg + 1; } // A positional argument or switch value. PrintQuoting(cmd, ib, ie - ib); } base.LogToolCommand(printer.ToString()); } protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance) { foreach (ErrorListFilter filter in s_errorListFilters) { Match match = filter.Pattern.Match(singleLine); if (match.Success) { filter.LogAction(Log, match); return; } } base.LogEventsFromTextOutput(singleLine, messageImportance); } // Main task entry point. public override bool Execute() { base.UseCommandProcessor = false; bool ok = base.Execute(); if (!ok) { return false; } // Read dependency output file from the compiler to retrieve the // definitive list of created files. Report the dependency file // itself as having been written to. if (DependencyOut != null) { string[] outputs = DepFileUtil.ReadDependencyOutputs(DependencyOut, Log); if (HasLoggedErrors) { return false; } GeneratedFiles = new ITaskItem[outputs.Length]; for (int i = 0; i < outputs.Length; i++) { GeneratedFiles[i] = new TaskItem(outputs[i]); } AdditionalFileWrites = new ITaskItem[] { new TaskItem(DependencyOut) }; } return true; } class ErrorListFilter { public Regex Pattern { get; set; } public Action<TaskLoggingHelper, Match> LogAction { get; set; } } }; }
namespace BelkaCloudDownloader.Google.Drive { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using global::Google.Apis.Drive.v3; using Utils; using File = global::Google.Apis.Drive.v3.Data.File; /// <summary> /// Downloads binary and Google Docs files from Google Drive and stores them into target directory. /// </summary> internal sealed class FilesDownloader : AbstractDownloader { /// <summary> /// Google Drive service that is used to download files or meta-information. /// </summary> private readonly DriveService service; /// <summary> /// Directory where we shall store downloaded files. /// </summary> private readonly string targetDir; /// <summary> /// Initializes a new instance of the <see cref="FilesDownloader"/> class. /// </summary> /// <param name="service">Google Drive service that is used to download files or meta-information.</param> /// <param name="targetDir">Directory where we shall store downloaded files.</param> /// <param name="cancellationToken">Token that can be used to abort downloading.</param> public FilesDownloader(DriveService service, string targetDir, CancellationToken cancellationToken) : base(cancellationToken) { this.service = service; this.targetDir = targetDir; } /// <summary> /// Downloads files. /// </summary> /// <param name="files">Meta-information about files to download.</param> /// <param name="exportFormats">A dictionary with possible export formats for Google Docs files, shall be /// received from Google Drive.</param> /// <returns>A list of info objects about downloaded files.</returns> public async Task<IList<DownloadedFile>> DownloadFiles( IEnumerable<File> files, IDictionary<string, IList<string>> exportFormats) { var filesList = files as IList<File> ?? files.ToList(); var weights = filesList.ToDictionary(f => f.Id, f => f.Size ?? Constants.GoogleDocsFileSize); this.Log.LogMessage($"Files to download: {weights.Count}, overall size: {weights.Values.Sum()} bytes."); IDictionary<File, IEnumerable<DirectoryInfo>> directories; try { directories = this.CreateDirectoryStructure(filesList, this.targetDir); } catch (Exception e) { this.Log.LogError("Unexpected error while creating directory structure, aborting download.", e); this.Error(); return new List<DownloadedFile>(); } Func<long, int> weight = size => (int)Math.Max(1, size / 1000000); this.SetGuessEstimation(weights.Values.Select(weight).Sum()); var semaphore = new AsyncSemaphore(Utils.Constants.DownloadThreadsCount); try { return await AsyncHelper.ProcessInChunks( filesList, f => { this.Status = Status.DownloadingFiles; if (exportFormats.ContainsKey(f.MimeType)) { var downloadTask = new TaskWrapper<File, DownloadedFile>(new DownloadGoogleDocsFileTask( exportFormats, semaphore, directories, this.service)); this.AddTask(downloadTask); return downloadTask.Run(f).ContinueWith(t => t.Result, this.CancellationToken); } if (!string.IsNullOrEmpty(f.WebContentLink)) { var binaryFileDownloader = new BinaryFileDownloader(this.CancellationToken); this.AddAsCurrentOperation(binaryFileDownloader); return binaryFileDownloader.DownloadBinaryFile( this.service, f, semaphore, weight(f.Size ?? 0), directories).ContinueWith(t => t.Result, this.CancellationToken); } if (f.MimeType != "application/vnd.google-apps.folder") { this.Log.LogDebugMessage( $"File '{f.Name}' has no web content link, can not be exported" + " and not a folder, skipping."); } return TaskEx.FromResult<DownloadedFile>(null); }, Utils.Constants.TaskChunkSize, this.CancellationToken); } catch (Exception e) { if (this.CancellationToken.IsCancellationRequested) { this.Log.LogMessage("Operation was cancelled."); throw; } this.Log.LogError("Error while downloading file.", e); this.Error(); return new List<DownloadedFile>(); } } /// <summary> /// Creates all directories needed to store files. /// </summary> /// <param name="files">A list with files meta-information.</param> /// <param name="targetDirectory">Root directory where to store downloaded files.</param> /// <returns>A dictionary that for each file contains a list of directories where it can be stored.</returns> /// <exception cref="System.IO.IOException">The directory cannot be created. </exception> /// <exception cref="SecurityException">The caller does not have the required permission. </exception> /// <exception cref="ArgumentException">File path contains invalid characters such as ", &lt;, &gt;, or |. </exception> /// <exception cref="System.IO.PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. /// The specified path, file name, or both are too long.</exception> /// <exception cref="System.IO.DirectoryNotFoundException">The specified path is invalid, such as being on an unmapped drive.</exception> private IDictionary<File, IEnumerable<DirectoryInfo>> CreateDirectoryStructure( IEnumerable<File> files, string targetDirectory) { var filesList = files as IList<File> ?? files.ToList(); var filesDictionary = filesList.ToDictionary(f => f.Id); var result = new Dictionary<File, IEnumerable<DirectoryInfo>>(); foreach (var file in filesList) { if ((file.Parents != null) && (file.Parents.Count > 0)) { var paths = this.GetPaths(file, filesDictionary); var dirInfos = paths.Select( p => { try { return new FileInfo(targetDirectory + Path.DirectorySeparatorChar + p) .Directory; } catch (PathTooLongException) { this.Log.LogDebugMessage($"Path too long for a file '{p}'," + " saving as-is in root."); return new FileInfo(targetDirectory + Path.DirectorySeparatorChar).Directory; } }).ToList(); foreach (var dir in dirInfos) { dir.Create(); } if (dirInfos.Count == 0) { this.Log.LogDebugMessage($"No directory info for file '{file.Name}', saving as-is in root."); dirInfos.Add(new FileInfo(targetDirectory + Path.DirectorySeparatorChar).Directory); } result.Add(file, dirInfos); } else { result.Add(file, new List<DirectoryInfo> { new DirectoryInfo(targetDirectory) }); } } return result; } /// <summary> /// Returns full paths where given file can be stored. /// </summary> /// <param name="file">A file for which we want to get paths.</param> /// <param name="files">A dictionary that maps file id to a file.</param> /// <returns>A list of possible paths for a given file.</returns> private IEnumerable<string> GetPaths(File file, IDictionary<string, File> files) { if ((file.Parents == null) || (file.Parents.Count == 0)) { this.Log.LogDebugMessage($"Meta-information does not contain parents for file '{file.Name}'," + " it seems that it belongs to someone other."); } else { foreach (var parent in file.Parents) { if (files.ContainsKey(parent)) { var parentPaths = this.GetPaths(files[parent], files); foreach (var path in parentPaths) { yield return path + Path.DirectorySeparatorChar + FileUtils.SanitizeFileName(file.Name); } } else { yield return FileUtils.SanitizeFileName(file.Name); } } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Linq; using Microsoft.Research.AbstractDomains; using System.Collections.Generic; using Microsoft.Research.DataStructures; using Microsoft.Research.AbstractDomains.Numerical; using System.Diagnostics.Contracts; using Microsoft.Research.CodeAnalysis; using System.Diagnostics.CodeAnalysis; namespace Microsoft.Research.CodeAnalysis { public static partial class AnalysisWrapper { public class PlugInAnalysisOptions : Analyzers.ValueAnalysisOptions<PlugInAnalysisOptions> { public PlugInAnalysisOptions(ILogOptions options) : base(options) { } } public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable> where Variable : IEquatable<Variable> where Expression : IEquatable<Expression> where Type : IEquatable<Type> { /// <summary> /// This is the class to inherit from if you want to add a new plugin to the Array Analysis /// </summary> /// <typeparam name="AbstractDomain">The abstract domain of the analysis</typeparam> //[ContractClass(typeof(GenericPlugInAnalysisForComposedAnalysisContracts))] public abstract class GenericPlugInAnalysisForComposedAnalysis : GenericValueAnalysis<ArrayState, PlugInAnalysisOptions> { #region State public readonly int Id; #endregion #region Constructor protected GenericPlugInAnalysisForComposedAnalysis( int id, string methodName, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver, PlugInAnalysisOptions options, Predicate<APC> cachePCs ) : base(methodName, mdriver, options, cachePCs) { Contract.Ensures(this.Id == id); this.Id = id; } #endregion #region Abstract methods abstract public IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression> InitialState { get; } //abstract override public IFactQuery<BoxedExpression, Variable> FactQuery(); //abstract override public IFactQuery<BoxedExpression, Variable> FactQuery(IFixpointInfo<APC,ArrayState> fixpoint); abstract public ArrayState.AdditionalStates Kind { get; } /// <returns> /// It should return the renamed *substate* not the whole one /// </returns> abstract public IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression> AssignInParallel (Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> refinedMap, Converter<BoxedVariable<Variable>, BoxedExpression> convert, List<Pair<NormalizedExpression<BoxedVariable<Variable>>, NormalizedExpression<BoxedVariable<Variable>>>> equalities, ArrayState state); #endregion #region Default implementations of overridden public override bool SuggestAnalysisSpecificPostconditions( ContractInferenceManager inferenceManager, IFixpointInfo<APC, ArrayState> fixpointInfo, List<BoxedExpression> postconditions) { return false; } public override bool TrySuggestPostconditionForOutParameters( IFixpointInfo<APC, ArrayState> fixpointInfo, List<BoxedExpression> postconditions, Variable p, FList<PathElement> path) { return false; } #endregion #region Materialize Enumerble protected ArraySegmentation<Elements, BoxedVariable<Variable>, BoxedExpression> MaterializeEnumerable<Elements>( APC postPC, ArraySegmentationEnvironment<Elements, BoxedVariable<Variable>, BoxedExpression> preState, Variable enumerable, Elements initialValue) where Elements : class, IAbstractDomainForArraySegmentationAbstraction<Elements, BoxedVariable<Variable>> { Variable modelArray; if (this.Context.ValueContext.TryGetModelArray(postPC, enumerable, out modelArray)) { MaterializeArray(postPC, preState, (BoxedExpression be) => CheckOutcome.True, modelArray, initialValue, initialValue); } return null; } #endregion #region Materialize Array protected ArraySegmentation<Elements, BoxedVariable<Variable>, BoxedExpression> MaterializeArray<Elements>( APC postPC, ArraySegmentationEnvironment<Elements, BoxedVariable<Variable>, BoxedExpression> preState, Func<BoxedExpression, FlatAbstractDomain<bool>> CheckIfNonZero, Variable arrayValue, Elements initialValue, Elements bottom) where Elements : class, IAbstractDomainForArraySegmentationAbstraction<Elements, BoxedVariable<Variable>> { Contract.Requires(preState != null); Contract.Requires(initialValue != null); var boxSym = new BoxedVariable<Variable>(arrayValue); ArraySegmentation<Elements, BoxedVariable<Variable>, BoxedExpression> arraySegment; if (preState.TryGetValue(boxSym, out arraySegment)) { return arraySegment; // already materialized } Variable array_Length; if (this.Context.ValueContext.TryGetArrayLength(postPC, arrayValue, out array_Length)) { var isNonEmpty = CheckIfNonZero(this.ToBoxedExpression(postPC, array_Length)).IsTrue(); var limits = new NonNullList<SegmentLimit<BoxedVariable<Variable>>>() { new SegmentLimit<BoxedVariable<Variable>>(NormalizedExpression<BoxedVariable<Variable>>.For(0), false), // { 0 } new SegmentLimit<BoxedVariable<Variable>>(NormalizedExpression<BoxedVariable<Variable>>.For(new BoxedVariable<Variable>(array_Length)), !isNonEmpty) // { symb.Length } }; var elements = new NonNullList<Elements>() { initialValue }; var newSegment = new ArraySegmentation<Elements, BoxedVariable<Variable>, BoxedExpression>( limits, elements, bottom, this.ExpressionManager); preState.AddElement(new BoxedVariable<Variable>(arrayValue), newSegment); return newSegment; } return null; } #endregion #region Array loop counter initialization protected ArraySegmentationEnvironment<AbstractDomain, BoxedVariable<Variable>, BoxedExpression> ArrayCounterInitialization<AbstractDomain>(APC pc, Local local, Variable source, ArrayState resultState, ArraySegmentationEnvironment<AbstractDomain, BoxedVariable<Variable>, BoxedExpression> mySubState) where AbstractDomain : class, IAbstractDomainForArraySegmentationAbstraction<AbstractDomain, BoxedVariable<Variable>> { Contract.Ensures(Contract.Result<ArraySegmentationEnvironment<AbstractDomain, BoxedVariable<Variable>, BoxedExpression>>() != null); var sourceExp = ToBoxedExpression(pc, source); // we look for loop initializations i == var Variable localValue; if (sourceExp.IsVariable && this.Context.ValueContext.TryLocalValue(this.Context.MethodContext.CFG.Post(pc), local, out localValue)) { // If source >= 0, we check if source <= arr.Length, for some array 'arr' // If this is the case, then we can try to refine the segmentation including source and locValue if (resultState.Numerical.CheckIfGreaterEqualThanZero(sourceExp).IsTrue()) { var sourceNorm = ToNormalizedExpression(source); var toUpdate = new Dictionary<BoxedVariable<Variable>, ArraySegmentation<AbstractDomain, BoxedVariable<Variable>, BoxedExpression>>(); foreach (var pair in mySubState.Elements) { if (!pair.Value.IsEmptyArray && pair.Value.IsNormal && // We do the trick only for arrays {0} val {Len} as otherwise we should be more careful where we refine the segmentation, as for instance the update below may be too rough. However, I haven't find any interesting non-artificial example for it pair.Value.Elements.Count() == 1) { foreach (var limit in pair.Value.LastLimit) { if (resultState.Numerical.CheckIfLessEqualThan(sourceExp, limit.Convert(this.Encoder)).IsTrue()) { IAbstractDomain abstractValue; if (pair.Value.TryGetAbstractValue( NormalizedExpression<BoxedVariable<Variable>>.For(0), sourceNorm, resultState.Numerical, out abstractValue) && abstractValue is AbstractDomain) { ArraySegmentation<AbstractDomain, BoxedVariable<Variable>, BoxedExpression> newSegment; if (pair.Value.TrySetAbstractValue(sourceNorm, (AbstractDomain) abstractValue, resultState.Numerical, out newSegment)) { toUpdate.Add(pair.Key, newSegment); break; // We've already updated this segmentation } } } } } } foreach (var pair in toUpdate) { mySubState[pair.Key] = pair.Value; } } } return mySubState; } #endregion #region Visitors public override sealed ArrayState GetTopValue() { throw new NotSupportedException(); } public override ArrayState Arglist(APC pc, Variable dest, ArrayState data) { return data; } public override ArrayState Assert(APC pc, string tag, Variable condition, object provenance, ArrayState data) { return Assume(pc, "assert", condition, provenance, data); } public override ArrayState Assume(APC pc, string tag, Variable source, object provenance, ArrayState data) { return data; } public override ArrayState BeginOld(APC pc, APC matchingEnd, ArrayState data) { return data; } public override ArrayState Binary(APC pc, BinaryOperator op, Variable dest, Variable s1, Variable s2, ArrayState data) { return data; } public override ArrayState Box(APC pc, Type type, Variable dest, Variable source, ArrayState data) { return data; } public override ArrayState Branch(APC pc, APC target, bool leave, ArrayState data) { return data; } public override ArrayState BranchCond(APC pc, APC target, BranchOperator bop, Variable value1, Variable value2, ArrayState data) { return data; } public override ArrayState BranchFalse(APC pc, APC target, Variable cond, ArrayState data) { return data; } public override ArrayState BranchTrue(APC pc, APC target, Variable cond, ArrayState data) { return data; } public override ArrayState Break(APC pc, ArrayState data) { return data; } public override ArrayState Call<TypeList, ArgList>(APC pc, Method method, bool tail, bool virt, TypeList extraVarargs, Variable dest, ArgList args, ArrayState data) { return data; } public override ArrayState Calli<TypeList, ArgList>(APC pc, Type returnType, TypeList argTypes, bool tail, bool isInstance, Variable dest, Variable fp, ArgList args, ArrayState data) { return data; } public override ArrayState Castclass(APC pc, Type type, Variable dest, Variable obj, ArrayState data) { return data; } public override ArrayState Ckfinite(APC pc, Variable dest, Variable source, ArrayState data) { return data; } public override ArrayState ConstrainedCallvirt<TypeList, ArgList>(APC pc, Method method, bool tail, Type constraint, TypeList extraVarargs, Variable dest, ArgList args, ArrayState data) { return data; } public override ArrayState Cpblk(APC pc, bool @volatile, Variable destaddr, Variable srcaddr, Variable len, ArrayState data) { return data; } public override ArrayState Cpobj(APC pc, Type type, Variable destptr, Variable srcptr, ArrayState data) { return data; } public override ArrayState Endfilter(APC pc, Variable decision, ArrayState data) { return data; } public override ArrayState Endfinally(APC pc, ArrayState data) { return data; } public override ArrayState EndOld(APC pc, APC matchingBegin, Type type, Variable dest, Variable source, ArrayState data) { return data; } public override ArrayState Entry(APC pc, Method method, ArrayState data) { return data; } internal override ArrayState HelperForJoin(ArrayState newState, ArrayState prevState, Pair<APC, APC> edge) { return base.HelperForJoin(newState, prevState, edge); } internal override ArrayState HelperForWidening(ArrayState newState, ArrayState prevState, Pair<APC, APC> edge) { return base.HelperForWidening(newState, prevState, edge); } public override ArrayState Initblk(APC pc, bool @volatile, Variable destaddr, Variable value, Variable len, ArrayState data) { return data; } public override ArrayState Initobj(APC pc, Type type, Variable ptr, ArrayState data) { return data; } public override ArrayState Isinst(APC pc, Type type, Variable dest, Variable obj, ArrayState data) { return data; } public override ArrayState Jmp(APC pc, Method method, ArrayState data) { return data; } public override ArrayState Join(Pair<APC, APC> edge, ArrayState newState, ArrayState prevState, out bool changed, bool widen) { return base.Join(edge, newState, prevState, out changed, widen) ; } public override ArrayState Ldarg(APC pc, Parameter argument, bool isOld, Variable dest, ArrayState data) { return data; } public override ArrayState Ldarga(APC pc, Parameter argument, bool isOld, Variable dest, ArrayState data) { return data; } public override ArrayState Ldconst(APC pc, object constant, Type type, Variable dest, ArrayState data) { return data; } public override ArrayState Ldelem(APC pc, Type type, Variable dest, Variable array, Variable index, ArrayState data) { return data; } public override ArrayState Ldelema(APC pc, Type type, bool @readonly, Variable dest, Variable array, Variable index, ArrayState data) { return data; } public override ArrayState Ldfieldtoken(APC pc, Field type, Variable dest, ArrayState data) { return data; } public override ArrayState Ldfld(APC pc, Field field, bool @volatile, Variable dest, Variable obj, ArrayState data) { return data; } public override ArrayState Ldflda(APC pc, Field field, Variable dest, Variable obj, ArrayState data) { return data; } public override ArrayState Ldftn(APC pc, Method method, Variable dest, ArrayState data) { return data; } public override ArrayState Ldind(APC pc, Type type, bool @volatile, Variable dest, Variable ptr, ArrayState data) { return data; } public override ArrayState Ldlen(APC pc, Variable dest, Variable array, ArrayState data) { return data; } public override ArrayState Ldloc(APC pc, Local local, Variable dest, ArrayState data) { return data; } public override ArrayState Ldloca(APC pc, Local local, Variable dest, ArrayState data) { return data; } public override ArrayState Ldmethodtoken(APC pc, Method type, Variable dest, ArrayState data) { return data; } public override ArrayState Ldnull(APC pc, Variable dest, ArrayState data) { return data; } public override ArrayState Ldresult(APC pc, Type type, Variable dest, Variable source, ArrayState data) { return data; } public override ArrayState Ldsfld(APC pc, Field field, bool @volatile, Variable dest, ArrayState data) { return data; } public override ArrayState Ldsflda(APC pc, Field field, Variable dest, ArrayState data) { return data; } public override ArrayState Ldstack(APC pc, int offset, Variable dest, Variable source, bool isOld, ArrayState data) { return data; } public override ArrayState Ldstacka(APC pc, int offset, Variable dest, Variable source, Type type, bool isOld, ArrayState data) { return data; } public override ArrayState Ldtypetoken(APC pc, Type type, Variable dest, ArrayState data) { return data; } public override ArrayState Ldvirtftn(APC pc, Method method, Variable dest, Variable obj, ArrayState data) { return data; } public override ArrayState Localloc(APC pc, Variable dest, Variable size, ArrayState data) { return data; } public override ArrayState Mkrefany(APC pc, Type type, Variable dest, Variable obj, ArrayState data) { return data; } public override ArrayState MutableVersion(ArrayState state) { return base.MutableVersion(state); } public override ArrayState Newarray<ArgList>(APC pc, Type type, Variable dest, ArgList lengths, ArrayState data) { return data; } public override ArrayState Newobj<ArgList>(APC pc, Method ctor, Variable dest, ArgList args, ArrayState data) { return data; } public override ArrayState Nop(APC pc, ArrayState data) { return data; } public override ArrayState Pop(APC pc, Variable source, ArrayState data) { return data; } public override ArrayState Refanytype(APC pc, Variable dest, Variable source, ArrayState data) { return data; } public override ArrayState Refanyval(APC pc, Type type, Variable dest, Variable source, ArrayState data) { return data; } public override ArrayState Rethrow(APC pc, ArrayState data) { return data; } public override ArrayState Return(APC pc, Variable source, ArrayState data) { return data; } public override ArrayState Sizeof(APC pc, Type type, Variable dest, ArrayState data) { return data; } public override ArrayState Starg(APC pc, Parameter argument, Variable source, ArrayState data) { return data; } public override ArrayState Stelem(APC pc, Type type, Variable array, Variable index, Variable value, ArrayState data) { return data; } public override ArrayState Stfld(APC pc, Field field, bool @volatile, Variable obj, Variable value, ArrayState data) { return data; } public override ArrayState Stind(APC pc, Type type, bool @volatile, Variable ptr, Variable value, ArrayState data) { return data; } public override ArrayState Stloc(APC pc, Local local, Variable source, ArrayState data) { return data; } public override ArrayState Stsfld(APC pc, Field field, bool @volatile, Variable value, ArrayState data) { return data; } public override ArrayState Switch(APC pc, Type type, IEnumerable<Pair<object, APC>> cases, Variable value, ArrayState data) { return data; } public override ArrayState Throw(APC pc, Variable exn, ArrayState data) { return data; } public override ArrayState Unary(APC pc, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Variable source, ArrayState data) { return data; } public override ArrayState Unbox(APC pc, Type type, Variable dest, Variable obj, ArrayState data) { return data; } public override ArrayState Unboxany(APC pc, Type type, Variable dest, Variable obj, ArrayState data) { return data; } #endregion #region Normalized Expressions static public NormalizedExpression<BoxedVariable<Variable>> ToNormalizedExpression(Variable v) { Contract.Ensures(Contract.Result<NormalizedExpression<BoxedVariable<Variable>>>() != null); return NormalizedExpression<BoxedVariable<Variable>>.For(new BoxedVariable<Variable>(v)); } #endregion #region Postcondition suggestion /// <summary> /// Does nothing, as a plugin as no fixpoint /// </summary> public override void SuggestPrecondition(ContractInferenceManager inferenceManager) { return; } virtual public void SuggestPrecondition(ContractInferenceManager inferenceManager, IFixpointInfo<APC, ArrayState> fixpointInfo) { // does nothing by default } #endregion } #if false // F: C# compiler is not happy for some reason which is unclear to me... [ContractClassFor(typeof(GenericPlugInAnalysisForComposedAnalysis))] abstract class GenericPlugInAnalysisForComposedAnalysisContracts : GenericPlugInAnalysisForComposedAnalysis { public override IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression> InitialState { get { Contract.Ensures(Contract.Result<IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression>>() != null); throw new NotImplementedException(); } } public override IFactQuery<BoxedExpression, Variable> FactQuery { get { throw new NotImplementedException(); } } public override ArrayState.AdditionalStates Kind { get { throw new NotImplementedException(); } } public override IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression> AssignInParallel( Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> refinedMap, Converter<BoxedVariable<Variable>, BoxedExpression> convert, List<Pair<NormalizedExpression<BoxedVariable<Variable>>, NormalizedExpression<BoxedVariable<Variable>>>> equalities, ArrayState state) { Contract.Requires(refinedMap != null); Contract.Requires(convert != null); Contract.Requires(equalities != null); Contract.Requires(state != null); Contract.Ensures(Contract.Result<IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression>>() != null); return default(IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression>); } } #endif } } }
/* * 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.Collections; namespace Apache.NMS.Util { /// <summary> /// This class provides a mechanism to intercept calls to a IPrimitiveMap /// instance and perform validation, handle type conversion, or some other /// function necessary to use the PrimitiveMap in a Message or other NMS /// object. /// /// Be default this class enforces the standard conversion policy for primitive /// types in NMS shown in the table below: /// /// | | boolean byte short char int long float double String byte[] /// |---------------------------------------------------------------------- /// |boolean | X X /// |byte | X X X X X /// |short | X X X X /// |char | X X /// |int | X X X /// |long | X X /// |float | X X X /// |double | X X /// |String | X X X X X X X X /// |byte[] | X /// |---------------------------------------------------------------------- /// /// </summary> public class PrimitiveMapInterceptor : IPrimitiveMap { protected IMessage message; protected IPrimitiveMap properties; private bool readOnly = false; private bool allowByteArrays = true; public PrimitiveMapInterceptor(IMessage message, IPrimitiveMap properties) { this.message = message; this.properties = properties; } public PrimitiveMapInterceptor(IMessage message, IPrimitiveMap properties, bool readOnly) { this.message = message; this.properties = properties; this.readOnly = readOnly; } public PrimitiveMapInterceptor(IMessage message, IPrimitiveMap properties, bool readOnly, bool allowByteArrays) { this.message = message; this.properties = properties; this.readOnly = readOnly; this.allowByteArrays = allowByteArrays; } protected virtual object GetObjectProperty(string name) { return this.properties[name]; } protected virtual void SetObjectProperty(string name, object value) { FailIfReadOnly(); try { if(!this.allowByteArrays && (value is byte[])) { throw new NotSupportedException("Byte Arrays not allowed in this PrimitiveMap"); } this.properties[name] = value; } catch(Exception ex) { throw NMSExceptionSupport.CreateMessageFormatException(ex); } } #region IPrimitiveMap Members public void Clear() { FailIfReadOnly(); this.properties.Clear(); } public bool Contains(object key) { return this.properties.Contains(key); } public void Remove(object key) { FailIfReadOnly(); this.properties.Remove(key); } public int Count { get { return this.properties.Count; } } public System.Collections.ICollection Keys { get { return this.properties.Keys; } } public System.Collections.ICollection Values { get { return this.properties.Values; } } public object this[string key] { get { return GetObjectProperty(key); } set { SetObjectProperty(key, value); } } public string GetString(string key) { Object value = GetObjectProperty(key); if(value == null) { return null; } else if((value is IList) || (value is IDictionary)) { throw new MessageFormatException(" cannot read a boolean from " + value.GetType().Name); } return value.ToString(); } public void SetString(string key, string value) { SetObjectProperty(key, value); } public bool GetBool(string key) { Object value = GetObjectProperty(key); try { if(value is Boolean) { return (bool) value; } else if(value is String) { return ((string) value).ToLower() == "true"; } else { throw new MessageFormatException(" cannot read a boolean from " + value.GetType().Name); } } catch(FormatException ex) { throw NMSExceptionSupport.CreateMessageFormatException(ex); } } public void SetBool(string key, bool value) { SetObjectProperty(key, value); } public byte GetByte(string key) { Object value = GetObjectProperty(key); try { if(value is Byte) { return (byte) value; } else if(value is String) { return Convert.ToByte(value); } else { throw new MessageFormatException(" cannot read a byte from " + value.GetType().Name); } } catch(FormatException ex) { throw NMSExceptionSupport.CreateMessageFormatException(ex); } } public void SetByte(string key, byte value) { SetObjectProperty(key, value); } public char GetChar(string key) { Object value = GetObjectProperty(key); try { if(value is Char) { return (char) value; } else if(value is String) { string svalue = value as string; if(svalue.Length == 1) { return svalue.ToCharArray()[0]; } } throw new MessageFormatException(" cannot read a char from " + value.GetType().Name); } catch(FormatException ex) { throw NMSExceptionSupport.CreateMessageFormatException(ex); } } public void SetChar(string key, char value) { SetObjectProperty(key, value); } public short GetShort(string key) { Object value = GetObjectProperty(key); try { if(value is Int16) { return (short) value; } else if(value is Byte || value is String) { return Convert.ToInt16(value); } else { throw new MessageFormatException(" cannot read a short from " + value.GetType().Name); } } catch(FormatException ex) { throw NMSExceptionSupport.CreateMessageFormatException(ex); } } public void SetShort(string key, short value) { SetObjectProperty(key, value); } public int GetInt(string key) { Object value = GetObjectProperty(key); try { if(value is Int32) { return (int) value; } else if(value is Int16 || value is Byte || value is String) { return Convert.ToInt32(value); } else { throw new MessageFormatException(" cannot read a int from " + value.GetType().Name); } } catch(FormatException ex) { throw NMSExceptionSupport.CreateMessageFormatException(ex); } } public void SetInt(string key, int value) { SetObjectProperty(key, value); } public long GetLong(string key) { Object value = GetObjectProperty(key); try { if(value is Int64) { return (long) value; } else if(value is Int32 || value is Int16 || value is Byte || value is String) { return Convert.ToInt64(value); } else { throw new MessageFormatException(" cannot read a long from " + value.GetType().Name); } } catch(FormatException ex) { throw NMSExceptionSupport.CreateMessageFormatException(ex); } } public void SetLong(string key, long value) { SetObjectProperty(key, value); } public float GetFloat(string key) { Object value = GetObjectProperty(key); try { if(value is Single) { return (float) value; } else if(value is String) { return Convert.ToSingle(value); } else { throw new MessageFormatException(" cannot read a float from " + value.GetType().Name); } } catch(FormatException ex) { throw NMSExceptionSupport.CreateMessageFormatException(ex); } } public void SetFloat(string key, float value) { SetObjectProperty(key, value); } public double GetDouble(string key) { Object value = GetObjectProperty(key); try { if(value is Double) { return (double) value; } else if(value is Single || value is String) { return Convert.ToDouble(value); } else { throw new MessageFormatException(" cannot read a double from " + value.GetType().Name); } } catch(FormatException ex) { throw NMSExceptionSupport.CreateMessageFormatException(ex); } } public void SetDouble(string key, double value) { SetObjectProperty(key, value); } public void SetBytes(String key, byte[] value) { this.SetBytes(key, value, 0, value.Length); } public void SetBytes(String key, byte[] value, int offset, int length) { byte[] copy = new byte[length]; Array.Copy(value, offset, copy, 0, length); SetObjectProperty(key, value); } public byte[] GetBytes(string key) { Object value = GetObjectProperty(key); try { if(value is Byte[]) { return (byte[]) value; } else { throw new MessageFormatException(" cannot read a byte[] from " + value.GetType().Name); } } catch(FormatException ex) { throw NMSExceptionSupport.CreateMessageFormatException(ex); } } public System.Collections.IList GetList(string key) { return (System.Collections.IList) GetObjectProperty(key); } public void SetList(string key, System.Collections.IList list) { SetObjectProperty(key, list); } public System.Collections.IDictionary GetDictionary(string key) { return (System.Collections.IDictionary) GetObjectProperty(key); } public void SetDictionary(string key, System.Collections.IDictionary dictionary) { SetObjectProperty(key, dictionary); } #endregion public bool ReadOnly { get{ return this.readOnly; } set{ this.readOnly = value; } } public bool AllowByteArrays { get{ return this.allowByteArrays; } set{ this.allowByteArrays = value; } } protected virtual void FailIfReadOnly() { if(this.ReadOnly == true) { throw new MessageNotWriteableException("Properties are in Read-Only mode."); } } } }
// 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.AcceptanceTestsBodyInteger { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Extension methods for IntModel. /// </summary> public static partial class IntModelExtensions { /// <summary> /// Get null Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetNull(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetNullAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get invalid Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetInvalid(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetInvalidAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetOverflowInt32(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetOverflowInt32Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOverflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetUnderflowInt32(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetUnderflowInt32Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUnderflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static long? GetOverflowInt64(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<long?> GetOverflowInt64Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOverflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static long? GetUnderflowInt64(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<long?> GetUnderflowInt64Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUnderflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put max int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMax32(this IIntModel operations, int intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMax32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMax32Async(this IIntModel operations, int intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMax32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put max int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMax64(this IIntModel operations, long intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMax64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMax64Async(this IIntModel operations, long intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMax64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put min int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMin32(this IIntModel operations, int intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMin32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMin32Async(this IIntModel operations, int intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMin32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put min int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMin64(this IIntModel operations, long intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMin64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMin64Async(this IIntModel operations, long intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } } }
//----------------------------------------------------------------------- // <copyright file="FieldData.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>Contains a field value and related metadata.</summary> //----------------------------------------------------------------------- using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Csla.Core.FieldManager { /// <summary> /// Contains a field value and related metadata. /// </summary> /// <typeparam name="T">Type of field value contained.</typeparam> [Serializable()] public class FieldData<T> : IFieldData<T> { private string _name; private T _data; private bool _isDirty; /// <summary> /// Creates a new instance of the object. /// </summary> /// <param name="name"> /// Name of the field. /// </param> public FieldData(string name) { _name = name; } /// <summary> /// Gets the name of the field. /// </summary> public string Name { get { return _name; } } /// <summary> /// Gets or sets the value of the field. /// </summary> public virtual T Value { get { return _data; } set { _data = value; _isDirty = true; } } object IFieldData.Value { get { return this.Value; } set { if (value == null) this.Value = default(T); else this.Value = (T)value; } } bool ITrackStatus.IsDeleted { get { ITrackStatus child = _data as ITrackStatus; if (child != null) { return child.IsDeleted; } else { return false; } } } bool ITrackStatus.IsSavable { get { return true; } } bool ITrackStatus.IsChild { get { ITrackStatus child = _data as ITrackStatus; if (child != null) { return child.IsChild; } else { return false; } } } /// <summary> /// Gets a value indicating whether the field /// has been changed. /// </summary> public virtual bool IsSelfDirty { get { return IsDirty; } } /// <summary> /// Gets a value indicating whether the field /// has been changed. /// </summary> public virtual bool IsDirty { get { ITrackStatus child = _data as ITrackStatus; if (child != null) { return child.IsDirty; } else { return _isDirty; } } } /// <summary> /// Marks the field as unchanged. /// </summary> public virtual void MarkClean() { _isDirty = false; } bool ITrackStatus.IsNew { get { ITrackStatus child = _data as ITrackStatus; if (child != null) { return child.IsNew; } else { return false; } } } bool ITrackStatus.IsSelfValid { get { return IsValid; } } bool ITrackStatus.IsValid { get { return IsValid; } } /// <summary> /// Gets a value indicating whether this field /// is considered valid. /// </summary> protected virtual bool IsValid { get { ITrackStatus child = _data as ITrackStatus; if (child != null) { return child.IsValid; } else { return true; } } } #region INotifyBusy Members event BusyChangedEventHandler INotifyBusy.BusyChanged { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } /// <summary> /// Gets a value indicating whether this object or /// any of its child objects are busy. /// </summary> [Browsable(false)] [Display(AutoGenerateField = false)] public bool IsBusy { get { bool isBusy = false; ITrackStatus child = _data as ITrackStatus; if (child != null) isBusy = child.IsBusy; return isBusy; } } bool INotifyBusy.IsSelfBusy { get { return IsBusy; } } #endregion #region INotifyUnhandledAsyncException Members [NotUndoable] [NonSerialized] private EventHandler<ErrorEventArgs> _unhandledAsyncException; /// <summary> /// Event indicating that an exception occurred on /// a background thread. /// </summary> public event EventHandler<ErrorEventArgs> UnhandledAsyncException { add { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Combine(_unhandledAsyncException, value); } remove { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Remove(_unhandledAsyncException, value); } } /// <summary> /// Raises the UnhandledAsyncException event. /// </summary> /// <param name="error">Exception that occurred on the background thread.</param> protected virtual void OnUnhandledAsyncException(ErrorEventArgs error) { if (_unhandledAsyncException != null) _unhandledAsyncException(this, error); } /// <summary> /// Raises the UnhandledAsyncException event. /// </summary> /// <param name="originalSender">Original source of the event.</param> /// <param name="error">Exception that occurred on the background thread.</param> protected void OnUnhandledAsyncException(object originalSender, Exception error) { OnUnhandledAsyncException(new ErrorEventArgs(originalSender, error)); } #endregion } }
// This is always generated file. Do not change anything. using SoftFX.Lrp; namespace SoftFX.Extended.Financial.Generated { internal static class TypesSerializer { public static SoftFX.Extended.Financial.MarginMode ReadMarginMode(this MemoryBuffer buffer) { var result = (SoftFX.Extended.Financial.MarginMode)buffer.ReadInt32(); return result; } public static void WriteMarginMode(this MemoryBuffer buffer, SoftFX.Extended.Financial.MarginMode arg) { buffer.WriteInt32((int)arg); } public static SoftFX.Extended.TradeType ReadTradeType(this MemoryBuffer buffer) { var result = (SoftFX.Extended.TradeType)buffer.ReadInt32(); return result; } public static void WriteTradeType(this MemoryBuffer buffer, SoftFX.Extended.TradeType arg) { buffer.WriteInt32((int)arg); } public static SoftFX.Extended.TradeRecordSide ReadTradeSide(this MemoryBuffer buffer) { var result = (SoftFX.Extended.TradeRecordSide)buffer.ReadInt32(); return result; } public static void WriteTradeSide(this MemoryBuffer buffer, SoftFX.Extended.TradeRecordSide arg) { buffer.WriteInt32((int)arg); } public static SoftFX.Extended.Financial.TradeEntryStatus ReadTradeEntryStatus(this MemoryBuffer buffer) { var result = (SoftFX.Extended.Financial.TradeEntryStatus)buffer.ReadInt32(); return result; } public static void WriteTradeEntryStatus(this MemoryBuffer buffer, SoftFX.Extended.Financial.TradeEntryStatus arg) { buffer.WriteInt32((int)arg); } public static SoftFX.Extended.Financial.AccountEntryStatus ReadAccountEntryStatus(this MemoryBuffer buffer) { var result = (SoftFX.Extended.Financial.AccountEntryStatus)buffer.ReadInt32(); return result; } public static void WriteAccountEntryStatus(this MemoryBuffer buffer, SoftFX.Extended.Financial.AccountEntryStatus arg) { buffer.WriteInt32((int)arg); } public static SoftFX.Extended.AccountType ReadAccountType(this MemoryBuffer buffer) { var result = (SoftFX.Extended.AccountType)buffer.ReadInt32(); return result; } public static void WriteAccountType(this MemoryBuffer buffer, SoftFX.Extended.AccountType arg) { buffer.WriteInt32((int)arg); } public static System.Collections.Generic.List<string> ReadAStringVector(this MemoryBuffer buffer) { int length = buffer.ReadCount(); var result = new System.Collections.Generic.List<string>(length); for(int index = 0; index < length; ++index) { result.Add(buffer.ReadAString()); } return result; } public static void WriteAStringVector(this MemoryBuffer buffer, System.Collections.Generic.List<string> arg) { buffer.WriteInt32(arg.Count); foreach(var element in arg) { buffer.WriteAString(element); } } public static SoftFX.Extended.Financial.Serialization.PriceData ReadPriceData(this MemoryBuffer buffer) { var result = new SoftFX.Extended.Financial.Serialization.PriceData(); result.Symbol = buffer.ReadAString(); result.Bid = buffer.ReadDouble(); result.Ask = buffer.ReadDouble(); return result; } public static void WritePriceData(this MemoryBuffer buffer, SoftFX.Extended.Financial.Serialization.PriceData arg) { buffer.WriteAString(arg.Symbol); buffer.WriteDouble(arg.Bid); buffer.WriteDouble(arg.Ask); } public static System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.PriceData> ReadPriceDataVector(this MemoryBuffer buffer) { int length = buffer.ReadCount(); var result = new System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.PriceData>(length); for(int index = 0; index < length; ++index) { result.Add(buffer.ReadPriceData()); } return result; } public static void WritePriceDataVector(this MemoryBuffer buffer, System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.PriceData> arg) { buffer.WriteInt32(arg.Count); foreach(var element in arg) { buffer.WritePriceData(element); } } public static SoftFX.Extended.Financial.Serialization.SymbolData ReadSymbolData(this MemoryBuffer buffer) { var result = new SoftFX.Extended.Financial.Serialization.SymbolData(); result.Tag = buffer.ReadAString(); result.Symbol = buffer.ReadAString(); result.From = buffer.ReadAString(); result.To = buffer.ReadAString(); result.ContractSize = buffer.ReadDouble(); result.Hedging = buffer.ReadDouble(); result.MarginFactorOfPositions = buffer.ReadDouble(); result.MarginFactorOfLimitOrders = buffer.ReadDouble(); result.MarginFactorOfStopOrders = buffer.ReadDouble(); return result; } public static void WriteSymbolData(this MemoryBuffer buffer, SoftFX.Extended.Financial.Serialization.SymbolData arg) { buffer.WriteAString(arg.Tag); buffer.WriteAString(arg.Symbol); buffer.WriteAString(arg.From); buffer.WriteAString(arg.To); buffer.WriteDouble(arg.ContractSize); buffer.WriteDouble(arg.Hedging); buffer.WriteDouble(arg.MarginFactorOfPositions); buffer.WriteDouble(arg.MarginFactorOfLimitOrders); buffer.WriteDouble(arg.MarginFactorOfStopOrders); } public static System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.SymbolData> ReadSymbolDataVector(this MemoryBuffer buffer) { int length = buffer.ReadCount(); var result = new System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.SymbolData>(length); for(int index = 0; index < length; ++index) { result.Add(buffer.ReadSymbolData()); } return result; } public static void WriteSymbolDataVector(this MemoryBuffer buffer, System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.SymbolData> arg) { buffer.WriteInt32(arg.Count); foreach(var element in arg) { buffer.WriteSymbolData(element); } } public static SoftFX.Extended.Financial.Serialization.TradeData ReadTradeData(this MemoryBuffer buffer) { var result = new SoftFX.Extended.Financial.Serialization.TradeData(); result.Tag = buffer.ReadAString(); result.Type = buffer.ReadTradeType(); result.Side = buffer.ReadTradeSide(); result.Symbol = buffer.ReadAString(); result.Volume = buffer.ReadDouble(); result.MaxVisibleVolume = buffer.ReadNullDouble(); result.Price = buffer.ReadNullDouble(); result.StopPrice = buffer.ReadNullDouble(); result.Commission = buffer.ReadDouble(); result.AgentCommission = buffer.ReadDouble(); result.Swap = buffer.ReadDouble(); result.Rate = buffer.ReadNullDouble(); result.Profit = buffer.ReadNullDouble(); result.ProfitStatus = buffer.ReadTradeEntryStatus(); result.Margin = buffer.ReadNullDouble(); result.MarginStatus = buffer.ReadTradeEntryStatus(); return result; } public static void WriteTradeData(this MemoryBuffer buffer, SoftFX.Extended.Financial.Serialization.TradeData arg) { buffer.WriteAString(arg.Tag); buffer.WriteTradeType(arg.Type); buffer.WriteTradeSide(arg.Side); buffer.WriteAString(arg.Symbol); buffer.WriteDouble(arg.Volume); buffer.WriteNullDouble(arg.MaxVisibleVolume); buffer.WriteNullDouble(arg.Price); buffer.WriteNullDouble(arg.StopPrice); buffer.WriteDouble(arg.Commission); buffer.WriteDouble(arg.AgentCommission); buffer.WriteDouble(arg.Swap); buffer.WriteNullDouble(arg.Rate); buffer.WriteNullDouble(arg.Profit); buffer.WriteTradeEntryStatus(arg.ProfitStatus); buffer.WriteNullDouble(arg.Margin); buffer.WriteTradeEntryStatus(arg.MarginStatus); } public static System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.TradeData> ReadTradeDataVector(this MemoryBuffer buffer) { int length = buffer.ReadCount(); var result = new System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.TradeData>(length); for(int index = 0; index < length; ++index) { result.Add(buffer.ReadTradeData()); } return result; } public static void WriteTradeDataVector(this MemoryBuffer buffer, System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.TradeData> arg) { buffer.WriteInt32(arg.Count); foreach(var element in arg) { buffer.WriteTradeData(element); } } public static SoftFX.Extended.Financial.Serialization.AccountData ReadAccountData(this MemoryBuffer buffer) { var result = new SoftFX.Extended.Financial.Serialization.AccountData(); result.Tag = buffer.ReadAString(); result.Type = buffer.ReadAccountType(); result.Leverage = buffer.ReadDouble(); result.Balance = buffer.ReadDouble(); result.Currency = buffer.ReadAString(); result.Profit = buffer.ReadNullDouble(); result.ProfitStatus = buffer.ReadAccountEntryStatus(); result.Margin = buffer.ReadNullDouble(); result.MarginStatus = buffer.ReadAccountEntryStatus(); result.Trades = buffer.ReadTradeDataVector(); return result; } public static void WriteAccountData(this MemoryBuffer buffer, SoftFX.Extended.Financial.Serialization.AccountData arg) { buffer.WriteAString(arg.Tag); buffer.WriteAccountType(arg.Type); buffer.WriteDouble(arg.Leverage); buffer.WriteDouble(arg.Balance); buffer.WriteAString(arg.Currency); buffer.WriteNullDouble(arg.Profit); buffer.WriteAccountEntryStatus(arg.ProfitStatus); buffer.WriteNullDouble(arg.Margin); buffer.WriteAccountEntryStatus(arg.MarginStatus); buffer.WriteTradeDataVector(arg.Trades); } public static System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.AccountData> ReadAccountDataVector(this MemoryBuffer buffer) { int length = buffer.ReadCount(); var result = new System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.AccountData>(length); for(int index = 0; index < length; ++index) { result.Add(buffer.ReadAccountData()); } return result; } public static void WriteAccountDataVector(this MemoryBuffer buffer, System.Collections.Generic.List<SoftFX.Extended.Financial.Serialization.AccountData> arg) { buffer.WriteInt32(arg.Count); foreach(var element in arg) { buffer.WriteAccountData(element); } } public static SoftFX.Extended.Financial.Serialization.CalculatorData ReadCalculatorData(this MemoryBuffer buffer) { var result = new SoftFX.Extended.Financial.Serialization.CalculatorData(); result.MarginMode = buffer.ReadMarginMode(); result.Prices = buffer.ReadPriceDataVector(); result.Symbols = buffer.ReadSymbolDataVector(); result.Accounts = buffer.ReadAccountDataVector(); result.Currencies = buffer.ReadAStringVector(); return result; } public static void WriteCalculatorData(this MemoryBuffer buffer, SoftFX.Extended.Financial.Serialization.CalculatorData arg) { buffer.WriteMarginMode(arg.MarginMode); buffer.WritePriceDataVector(arg.Prices); buffer.WriteSymbolDataVector(arg.Symbols); buffer.WriteAccountDataVector(arg.Accounts); buffer.WriteAStringVector(arg.Currencies); } public static void Throw(System.Int32 status, MemoryBuffer buffer) { if(status >= 0) { return; } if(MagicNumbers.LRP_EXCEPTION != status) { throw new System.Exception("Unexpected exception has been encountered"); } System.Int32 _id = buffer.ReadInt32(); System.String _message = buffer.ReadAString(); throw new System.Exception(_message); } } }
using System; using System.Collections.Generic; using System.Linq; using JsonApiDotNetCore.AtomicOperations; using JsonApiDotNetCore.AtomicOperations.Processors; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Queries; using JsonApiDotNetCore.Queries.Internal; using JsonApiDotNetCore.QueryStrings; using JsonApiDotNetCore.QueryStrings.Internal; using JsonApiDotNetCore.Repositories; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Serialization; using JsonApiDotNetCore.Serialization.Building; using JsonApiDotNetCore.Serialization.JsonConverters; using JsonApiDotNetCore.Services; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; namespace JsonApiDotNetCore.Configuration { /// <summary> /// A utility class that builds a JsonApi application. It registers all required services and allows the user to override parts of the startup /// configuration. /// </summary> internal sealed class JsonApiApplicationBuilder : IJsonApiApplicationBuilder, IDisposable { private readonly JsonApiOptions _options = new(); private readonly IServiceCollection _services; private readonly IMvcCoreBuilder _mvcBuilder; private readonly ResourceGraphBuilder _resourceGraphBuilder; private readonly ServiceDiscoveryFacade _serviceDiscoveryFacade; private readonly ServiceProvider _intermediateProvider; public Action<MvcOptions> ConfigureMvcOptions { get; set; } public JsonApiApplicationBuilder(IServiceCollection services, IMvcCoreBuilder mvcBuilder) { ArgumentGuard.NotNull(services, nameof(services)); ArgumentGuard.NotNull(mvcBuilder, nameof(mvcBuilder)); _services = services; _mvcBuilder = mvcBuilder; _intermediateProvider = services.BuildServiceProvider(); var loggerFactory = _intermediateProvider.GetRequiredService<ILoggerFactory>(); _resourceGraphBuilder = new ResourceGraphBuilder(_options, loggerFactory); _serviceDiscoveryFacade = new ServiceDiscoveryFacade(_services, _resourceGraphBuilder, loggerFactory); } /// <summary> /// Executes the action provided by the user to configure <see cref="JsonApiOptions" />. /// </summary> public void ConfigureJsonApiOptions(Action<JsonApiOptions> configureOptions) { configureOptions?.Invoke(_options); } /// <summary> /// Executes the action provided by the user to configure <see cref="ServiceDiscoveryFacade" />. /// </summary> public void ConfigureAutoDiscovery(Action<ServiceDiscoveryFacade> configureAutoDiscovery) { configureAutoDiscovery?.Invoke(_serviceDiscoveryFacade); } /// <summary> /// Configures and builds the resource graph with resources from the provided sources and adds it to the DI container. /// </summary> public void AddResourceGraph(ICollection<Type> dbContextTypes, Action<ResourceGraphBuilder> configureResourceGraph) { _serviceDiscoveryFacade.DiscoverResources(); foreach (Type dbContextType in dbContextTypes) { var dbContext = (DbContext)_intermediateProvider.GetRequiredService(dbContextType); AddResourcesFromDbContext(dbContext, _resourceGraphBuilder); } configureResourceGraph?.Invoke(_resourceGraphBuilder); IResourceGraph resourceGraph = _resourceGraphBuilder.Build(); _options.SerializerOptions.Converters.Add(new ResourceObjectConverter(resourceGraph)); _services.AddSingleton(resourceGraph); } /// <summary> /// Configures built-in ASP.NET Core MVC components. Most of this configuration can be adjusted for the developers' need. /// </summary> public void ConfigureMvc() { _mvcBuilder.AddMvcOptions(options => { options.EnableEndpointRouting = true; options.Filters.AddService<IAsyncJsonApiExceptionFilter>(); options.Filters.AddService<IAsyncQueryStringActionFilter>(); options.Filters.AddService<IAsyncConvertEmptyActionResultFilter>(); ConfigureMvcOptions?.Invoke(options); }); if (_options.ValidateModelState) { _mvcBuilder.AddDataAnnotations(); _services.AddSingleton<IModelMetadataProvider, JsonApiModelMetadataProvider>(); } } /// <summary> /// Discovers DI registrable services in the assemblies marked for discovery. /// </summary> public void DiscoverInjectables() { _serviceDiscoveryFacade.DiscoverInjectables(); } /// <summary> /// Registers the remaining internals. /// </summary> public void ConfigureServiceContainer(ICollection<Type> dbContextTypes) { if (dbContextTypes.Any()) { _services.AddScoped(typeof(DbContextResolver<>)); foreach (Type dbContextType in dbContextTypes) { Type contextResolverType = typeof(DbContextResolver<>).MakeGenericType(dbContextType); _services.AddScoped(typeof(IDbContextResolver), contextResolverType); } _services.AddScoped<IOperationsTransactionFactory, EntityFrameworkCoreTransactionFactory>(); } else { _services.AddScoped<IOperationsTransactionFactory, MissingTransactionFactory>(); } AddResourceLayer(); AddRepositoryLayer(); AddServiceLayer(); AddMiddlewareLayer(); AddSerializationLayer(); AddQueryStringLayer(); AddOperationsLayer(); _services.AddScoped(typeof(IResourceChangeTracker<>), typeof(ResourceChangeTracker<>)); _services.AddScoped<IPaginationContext, PaginationContext>(); _services.AddScoped<IEvaluatedIncludeCache, EvaluatedIncludeCache>(); _services.AddScoped<IQueryLayerComposer, QueryLayerComposer>(); _services.AddScoped<IInverseNavigationResolver, InverseNavigationResolver>(); } private void AddMiddlewareLayer() { _services.AddSingleton<IJsonApiOptions>(_options); _services.AddSingleton<IJsonApiApplicationBuilder>(this); _services.AddSingleton<IExceptionHandler, ExceptionHandler>(); _services.AddScoped<IAsyncJsonApiExceptionFilter, AsyncJsonApiExceptionFilter>(); _services.AddScoped<IAsyncQueryStringActionFilter, AsyncQueryStringActionFilter>(); _services.AddScoped<IAsyncConvertEmptyActionResultFilter, AsyncConvertEmptyActionResultFilter>(); _services.AddSingleton<IJsonApiInputFormatter, JsonApiInputFormatter>(); _services.AddSingleton<IJsonApiOutputFormatter, JsonApiOutputFormatter>(); _services.AddSingleton<IJsonApiRoutingConvention, JsonApiRoutingConvention>(); _services.AddSingleton<IControllerResourceMapping>(sp => sp.GetRequiredService<IJsonApiRoutingConvention>()); _services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); _services.AddSingleton<IRequestScopedServiceProvider, RequestScopedServiceProvider>(); _services.AddScoped<IJsonApiRequest, JsonApiRequest>(); _services.AddScoped<IJsonApiWriter, JsonApiWriter>(); _services.AddScoped<IJsonApiReader, JsonApiReader>(); _services.AddScoped<ITargetedFields, TargetedFields>(); _services.AddScoped<IFieldsToSerialize, FieldsToSerialize>(); } private void AddResourceLayer() { RegisterImplementationForOpenInterfaces(ServiceDiscoveryFacade.ResourceDefinitionInterfaces, typeof(JsonApiResourceDefinition<>), typeof(JsonApiResourceDefinition<,>)); _services.AddScoped<IResourceDefinitionAccessor, ResourceDefinitionAccessor>(); _services.AddScoped<IResourceFactory, ResourceFactory>(); } private void AddRepositoryLayer() { RegisterImplementationForOpenInterfaces(ServiceDiscoveryFacade.RepositoryInterfaces, typeof(EntityFrameworkCoreRepository<>), typeof(EntityFrameworkCoreRepository<,>)); _services.AddScoped<IResourceRepositoryAccessor, ResourceRepositoryAccessor>(); } private void AddServiceLayer() { RegisterImplementationForOpenInterfaces(ServiceDiscoveryFacade.ServiceInterfaces, typeof(JsonApiResourceService<>), typeof(JsonApiResourceService<,>)); } private void RegisterImplementationForOpenInterfaces(HashSet<Type> openGenericInterfaces, Type intImplementation, Type implementation) { foreach (Type openGenericInterface in openGenericInterfaces) { Type implementationType = openGenericInterface.GetGenericArguments().Length == 1 ? intImplementation : implementation; _services.TryAddScoped(openGenericInterface, implementationType); } } private void AddQueryStringLayer() { _services.AddScoped<IIncludeQueryStringParameterReader, IncludeQueryStringParameterReader>(); _services.AddScoped<IFilterQueryStringParameterReader, FilterQueryStringParameterReader>(); _services.AddScoped<ISortQueryStringParameterReader, SortQueryStringParameterReader>(); _services.AddScoped<ISparseFieldSetQueryStringParameterReader, SparseFieldSetQueryStringParameterReader>(); _services.AddScoped<IPaginationQueryStringParameterReader, PaginationQueryStringParameterReader>(); _services.AddScoped<IResourceDefinitionQueryableParameterReader, ResourceDefinitionQueryableParameterReader>(); RegisterDependentService<IQueryStringParameterReader, IIncludeQueryStringParameterReader>(); RegisterDependentService<IQueryStringParameterReader, IFilterQueryStringParameterReader>(); RegisterDependentService<IQueryStringParameterReader, ISortQueryStringParameterReader>(); RegisterDependentService<IQueryStringParameterReader, ISparseFieldSetQueryStringParameterReader>(); RegisterDependentService<IQueryStringParameterReader, IPaginationQueryStringParameterReader>(); RegisterDependentService<IQueryStringParameterReader, IResourceDefinitionQueryableParameterReader>(); RegisterDependentService<IQueryConstraintProvider, IIncludeQueryStringParameterReader>(); RegisterDependentService<IQueryConstraintProvider, IFilterQueryStringParameterReader>(); RegisterDependentService<IQueryConstraintProvider, ISortQueryStringParameterReader>(); RegisterDependentService<IQueryConstraintProvider, ISparseFieldSetQueryStringParameterReader>(); RegisterDependentService<IQueryConstraintProvider, IPaginationQueryStringParameterReader>(); RegisterDependentService<IQueryConstraintProvider, IResourceDefinitionQueryableParameterReader>(); _services.AddScoped<IQueryStringReader, QueryStringReader>(); _services.AddSingleton<IRequestQueryStringAccessor, RequestQueryStringAccessor>(); } private void RegisterDependentService<TCollectionElement, TElementToAdd>() where TCollectionElement : class where TElementToAdd : TCollectionElement { _services.AddScoped<TCollectionElement>(serviceProvider => serviceProvider.GetRequiredService<TElementToAdd>()); } private void AddSerializationLayer() { _services.AddScoped<IIncludedResourceObjectBuilder, IncludedResourceObjectBuilder>(); _services.AddScoped<IJsonApiDeserializer, RequestDeserializer>(); _services.AddScoped<IJsonApiSerializerFactory, ResponseSerializerFactory>(); _services.AddScoped<ILinkBuilder, LinkBuilder>(); _services.AddScoped<IResponseMeta, EmptyResponseMeta>(); _services.AddScoped<IMetaBuilder, MetaBuilder>(); _services.AddScoped(typeof(ResponseSerializer<>)); _services.AddScoped(typeof(AtomicOperationsResponseSerializer)); _services.AddScoped(sp => sp.GetRequiredService<IJsonApiSerializerFactory>().GetSerializer()); _services.AddScoped<IResourceObjectBuilder, ResponseResourceObjectBuilder>(); _services.AddSingleton<IFingerprintGenerator, FingerprintGenerator>(); _services.AddSingleton<IETagGenerator, ETagGenerator>(); } private void AddOperationsLayer() { _services.AddScoped(typeof(ICreateProcessor<,>), typeof(CreateProcessor<,>)); _services.AddScoped(typeof(IUpdateProcessor<,>), typeof(UpdateProcessor<,>)); _services.AddScoped(typeof(IDeleteProcessor<,>), typeof(DeleteProcessor<,>)); _services.AddScoped(typeof(IAddToRelationshipProcessor<,>), typeof(AddToRelationshipProcessor<,>)); _services.AddScoped(typeof(ISetRelationshipProcessor<,>), typeof(SetRelationshipProcessor<,>)); _services.AddScoped(typeof(IRemoveFromRelationshipProcessor<,>), typeof(RemoveFromRelationshipProcessor<,>)); _services.AddScoped<IOperationsProcessor, OperationsProcessor>(); _services.AddScoped<IOperationProcessorAccessor, OperationProcessorAccessor>(); _services.AddScoped<ILocalIdTracker, LocalIdTracker>(); } private void AddResourcesFromDbContext(DbContext dbContext, ResourceGraphBuilder builder) { foreach (IEntityType entityType in dbContext.Model.GetEntityTypes()) { if (!IsImplicitManyToManyJoinEntity(entityType)) { builder.Add(entityType.ClrType); } } } private static bool IsImplicitManyToManyJoinEntity(IEntityType entityType) { #pragma warning disable EF1001 // Internal EF Core API usage. return entityType is EntityType { IsImplicitlyCreatedJoinEntityType: true }; #pragma warning restore EF1001 // Internal EF Core API usage. } public void Dispose() { _intermediateProvider.Dispose(); } } }
/// Copyright (C) 2012-2014 Soomla Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. using UnityEngine; using System; using System.Text.RegularExpressions; using System.Collections.Generic; namespace Soomla.Profile { /// <summary> /// This class provides functions for event handling. To handle various events, just add your /// game-specific behavior to the delegates below. /// </summary> public class ProfileEvents : MonoBehaviour { private const string TAG = "SOOMLA ProfileEvents"; private static ProfileEvents instance = null; #pragma warning disable 414 private static ProfileEventPusher pep = null; #pragma warning restore 414 /// <summary> /// Initializes the game state before the game starts. /// </summary> void Awake(){ if(instance == null){ // making sure we only initialize one instance. SoomlaUtils.LogDebug(TAG, "Initializing ProfileEvents (Awake)"); instance = this; GameObject.DontDestroyOnLoad(this.gameObject); Initialize(); // now we initialize the event pusher #if UNITY_ANDROID && !UNITY_EDITOR pep = new ProfileEventPusherAndroid(); #elif UNITY_IOS && !UNITY_EDITOR pep = new ProfileEventPusherIOS(); #endif } else { // Destroying unused instances. GameObject.Destroy(this.gameObject); } } public static void Initialize() { SoomlaUtils.LogDebug (TAG, "Initializing ProfileEvents ..."); #if UNITY_ANDROID && !UNITY_EDITOR AndroidJNI.PushLocalFrame(100); //init ProfileEventHandler using(AndroidJavaClass jniEventHandler = new AndroidJavaClass("com.soomla.profile.unity.ProfileEventHandler")) { jniEventHandler.CallStatic("initialize"); } AndroidJNI.PopLocalFrame(IntPtr.Zero); #elif UNITY_IOS && !UNITY_EDITOR // On iOS, this is initialized inside the bridge library when we call "soomlaProfile_Initialize" in SoomlaProfileIOS #endif } /// <summary> /// Handles an <c>onSoomlaProfileInitialized</c> event, which is fired when SoomlaProfile /// has been initialzed /// </summary> public void onSoomlaProfileInitialized() { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSoomlaProfileInitialized"); SoomlaProfile.TryFireProfileInitialized(); } /// <summary> /// Handles an <c>onUserRatingEvent</c> event /// </summary> public void onUserRatingEvent() { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onUserRatingEvent"); ProfileEvents.OnUserRatingEvent (); } /// <summary> /// Handles an <c>onUserProfileUpdated</c> event /// </summary> /// <param name="message">Will contain a JSON representation of a <c>UserProfile</c></param> public void onUserProfileUpdated(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onUserProfileUpdated"); JSONObject eventJson = new JSONObject(message); UserProfile userProfile = new UserProfile (eventJson ["userProfile"]); ProfileEvents.OnUserProfileUpdated (userProfile); } /// <summary> /// Handles an <c>onLoginStarted</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// as well as payload </param> public void onLoginStarted(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginStarted"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt((int)(eventJson["provider"].n)); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnLoginStarted (provider, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onLoginFinished</c> event /// </summary> /// <param name="message">Will contain a JSON representation of a <c>UserProfile</c> and payload</param> public void onLoginFinished(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginFinished"); JSONObject eventJson = new JSONObject(message); UserProfile userProfile = new UserProfile (eventJson ["userProfile"]); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); //give a reward Reward reward = Reward.GetReward(ProfilePayload.GetRewardId(payloadJSON)); if (reward !=null) reward.Give(); ProfileEvents.OnLoginFinished (userProfile, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onLoginCancelled</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// as well as payload </param> public void onLoginCancelled(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginCancelled"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt((int)(eventJson["provider"].n)); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnLoginCancelled (provider, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onLoginFailed</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// ,error message and payload </param> public void onLoginFailed(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginFailed"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt((int)(eventJson["provider"].n)); String errorMessage = eventJson["message"].str; JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnLoginFailed(provider, errorMessage, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onLogoutStarted</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c></param> public void onLogoutStarted(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLogoutStarted"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)(eventJson["provider"].n)); ProfileEvents.OnLogoutStarted (provider); } /// <summary> /// Handles an <c>onLogoutFinished</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c></param> public void onLogoutFinished(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLogoutFinished"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)(eventJson["provider"].n)); ProfileEvents.OnLogoutFinished(provider); } /// <summary> /// Handles an <c>onLogoutFailed</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// and payload</param> public void onLogoutFailed(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLogoutFailed"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)(eventJson["provider"].n)); String errorMessage = eventJson["message"].str; ProfileEvents.OnLogoutFailed (provider, errorMessage); } /// <summary> /// Handles an <c>onSocialActionStarted</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// numeric representation of <c>SocialActionType</c> and payload</param> public void onSocialActionStarted(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionStarted"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)(eventJson["provider"].n)); SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnSocialActionStarted (provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onSocialActionFinished</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// numeric representation of <c>SocialActionType</c> and payload</param> public void onSocialActionFinished(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionFinished"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); //give a reward Reward reward = Reward.GetReward(ProfilePayload.GetRewardId(payloadJSON)); if (reward != null) reward.Give(); ProfileEvents.OnSocialActionFinished (provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onSocialActionCancelled</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// numeric representation of <c>SocialActionType</c> and payload</param> public void onSocialActionCancelled(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionCancelled"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnSocialActionCancelled (provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onSocialActionFailed</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// numeric representation of <c>SocialActionType</c>, /// error message and payload</param> public void onSocialActionFailed(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionFailed"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n); String errorMessage = eventJson["message"].str; JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnSocialActionFailed (provider, socialAction, errorMessage, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onGetContactsStarted</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// and payload</param> public void onGetContactsStarted(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetContactsStarted"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnGetContactsStarted (provider, 0, ProfilePayload.GetUserPayload (payloadJSON)); } /// <summary> /// Handles an <c>onGetContactsFinished</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// JSON array of <c>UserProfile</c>s and payload</param> public void onGetContactsFinished(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetContactsFinished"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); JSONObject userProfilesArray = eventJson ["contacts"]; List<UserProfile> userProfiles = new List<UserProfile>(); foreach (JSONObject userProfileJson in userProfilesArray.list) { userProfiles.Add(new UserProfile(userProfileJson)); } SocialPageData<UserProfile> data = new SocialPageData<UserProfile>(); data.PageData = userProfiles; data.PageNumber = 0; data.HasMore = false; ProfileEvents.OnGetContactsFinished (provider, data, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onGetContactsFinished</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// error message payload</param> public void onGetContactsFailed(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetContactsFailed"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); String errorMessage = eventJson["message"].str; JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnGetContactsFailed (provider, 0, errorMessage, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onGetFeedStarted</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// and payload</param> public void onGetFeedStarted(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetFeedStarted"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); ProfileEvents.OnGetFeedStarted (provider); } /// <summary> /// Handles an <c>onGetFeedFinished</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// json array of feeds</param> public void onGetFeedFinished(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetFeedFinished"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); JSONObject feedsJson = eventJson ["feeds"]; List<String> feeds = new List<String>(); foreach (String key in feedsJson.keys) { //iterate "feed" keys feeds.Add(feedsJson[key].str); } ProfileEvents.OnGetFeedFinished (provider, feeds); } /// <summary> /// Handles an <c>onGetFeedFailed</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// and an error message</param> public void onGetFeedFailed(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetFeedFailed"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); String errorMessage = eventJson["message"].str; ProfileEvents.OnGetFeedFailed (provider, errorMessage); } public void onTakeScreenshotStarted(Provider provider, String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onTakeScreenshotStarted"); JSONObject eventJson = new JSONObject(message); String errorMessage = eventJson["messge"].str; ProfileEvents.OnTakeScreenshotStarted(provider, errorMessage); } public void onTakeScreenshotFinished(Provider provider, String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onScreenshotCaptured"); JSONObject eventJson = new JSONObject(message); String errorMessage = eventJson["message"].str; ProfileEvents.OnTakeScreenshotFinished (provider, errorMessage); } public delegate void Action(); public static Action OnSoomlaProfileInitialized = delegate {}; public static Action OnUserRatingEvent =delegate {}; public static Action<Provider, string> OnLoginCancelled = delegate {}; public static Action<UserProfile> OnUserProfileUpdated = delegate {}; public static Action<Provider, string, string> OnLoginFailed = delegate {}; public static Action<UserProfile, string> OnLoginFinished = delegate {}; public static Action<Provider, string> OnLoginStarted = delegate {}; public static Action<Provider, string> OnLogoutFailed = delegate {}; public static Action<Provider> OnLogoutFinished = delegate {}; public static Action<Provider> OnLogoutStarted = delegate {}; public static Action<Provider, SocialActionType, string, string> OnSocialActionFailed = delegate {}; public static Action<Provider, SocialActionType, string> OnSocialActionFinished = delegate {}; public static Action<Provider, SocialActionType, string> OnSocialActionStarted = delegate {}; public static Action<Provider, SocialActionType, string> OnSocialActionCancelled = delegate {}; public static Action<Provider, int, string, string> OnGetContactsFailed = delegate {}; public static Action<Provider, SocialPageData<UserProfile>, string> OnGetContactsFinished = delegate {}; public static Action<Provider, int, string> OnGetContactsStarted = delegate {}; public static Action<Provider, string> OnGetFeedFailed = delegate {}; public static Action<Provider, List<string>> OnGetFeedFinished = delegate {}; public static Action<Provider> OnGetFeedStarted = delegate {}; public static Action<Provider> OnAddAppRequestStarted = delegate {}; public static Action<Provider, string> OnAddAppRequestFinished = delegate {}; public static Action<Provider, string> OnAddAppRequestFailed = delegate {}; public static Action<Provider, string> OnInviteStarted = delegate {}; public static Action<Provider, string, List<string>, string> OnInviteFinished = delegate {}; public static Action<Provider, string, string> OnInviteFailed = delegate {}; public static Action<Provider, string> OnInviteCancelled = delegate {}; public static Action<Provider, string> OnTakeScreenshotStarted = delegate {}; public static Action<Provider, string> OnTakeScreenshotFinished = delegate {}; public class ProfileEventPusher { /// <summary> /// Registers all events. /// </summary> public ProfileEventPusher() { ProfileEvents.OnLoginCancelled += _pushEventLoginStarted; ProfileEvents.OnLoginFailed += _pushEventLoginFailed; ProfileEvents.OnLoginFinished += _pushEventLoginFinished; ProfileEvents.OnLoginStarted += _pushEventLoginStarted; ProfileEvents.OnLogoutFailed += _pushEventLogoutFailed; ProfileEvents.OnLogoutFinished += _pushEventLogoutFinished; ProfileEvents.OnLogoutStarted += _pushEventLogoutStarted; ProfileEvents.OnSocialActionCancelled += _pushEventSocialActionCancelled; ProfileEvents.OnSocialActionFailed += _pushEventSocialActionFailed; ProfileEvents.OnSocialActionFinished += _pushEventSocialActionFinished; ProfileEvents.OnSocialActionStarted += _pushEventSocialActionStarted; ProfileEvents.OnGetContactsStarted += _pushEventGetContactsStarted; ProfileEvents.OnGetContactsFinished += _pushEventGetContactsFinished; ProfileEvents.OnGetContactsFailed += _pushEventGetContactsFailed; ProfileEvents.OnInviteStarted += _pushEventInviteStarted; ProfileEvents.OnInviteFinished += _pushEventInviteFinished; ProfileEvents.OnInviteFailed += _pushEventInviteFailed; ProfileEvents.OnInviteCancelled += _pushEventInviteCancelled; } // Event pushing back to native (when using FB Unity SDK) protected virtual void _pushEventLoginStarted(Provider provider, string payload) {} protected virtual void _pushEventLoginFinished(UserProfile userProfileJson, string payload){} protected virtual void _pushEventLoginFailed(Provider provider, string message, string payload){} protected virtual void _pushEventLoginCancelled(Provider provider, string payload){} protected virtual void _pushEventLogoutStarted(Provider provider){} protected virtual void _pushEventLogoutFinished(Provider provider){} protected virtual void _pushEventLogoutFailed(Provider provider, string message){} protected virtual void _pushEventSocialActionStarted(Provider provider, SocialActionType actionType, string payload){} protected virtual void _pushEventSocialActionFinished(Provider provider, SocialActionType actionType, string payload){} protected virtual void _pushEventSocialActionCancelled(Provider provider, SocialActionType actionType, string payload){} protected virtual void _pushEventSocialActionFailed(Provider provider, SocialActionType actionType, string message, string payload){} protected virtual void _pushEventGetContactsStarted(Provider provider, int pageNumber, string payload){} protected virtual void _pushEventGetContactsFinished(Provider provider, SocialPageData<UserProfile> contactsPage, string payload){} protected virtual void _pushEventGetContactsFailed(Provider provider, int pageNumber, string message, string payload){} protected virtual void _pushEventInviteStarted(Provider provider, string payload){} protected virtual void _pushEventInviteFinished(Provider provider, string requestId, List<string> invitedIds, string payload){} protected virtual void _pushEventInviteFailed(Provider provider, string message, string payload){} protected virtual void _pushEventInviteCancelled(Provider provider, string payload){} } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace WpfApplication1.Coversion { public class PrayTimes { //--------------------------- Mine ---------------------------- public TimeName[] timeNames { get; set; } public Dictionary<MethodName, Method> methods { get; set; } public Dictionary<TimeName, object> defaultParams { get; set; } public Dictionary<TimeName, object> setting { get; set; } public Dictionary<TimeName, double> offset { get; set; } private MethodName calcMethod; public MethodName CalcMethod { get { return this.calcMethod; } set { if (this.calcMethod == value) return; this.adjust(this.methods[value]._params); this.calcMethod = value; } } public string timeFormat = "24h"; public string[] timeSuffixes = { "am", "pm" }; public string invalidTime = "-----"; public double numIterations = 1; //----------------------- Local Variables --------------------- public double lat; public double lng; public double elv; // coordinates public double timeZone; public double jDate; // time variables //------------------------ Constants -------------------------- public PrayTimes(MethodName method = MethodName.MWL) { // Time Names timeNames = new[] { TimeName.Imsak, TimeName.Fajr, TimeName.Sunrise, TimeName.Dhuhr, TimeName.Asr, TimeName.Sunset, TimeName.Maghrib, TimeName.Isha, TimeName.Midnight }; // Calculation Methods methods = new Dictionary<MethodName, Method> { { MethodName.MWL, new Method { name = "Muslim World League", _params = new Dictionary<TimeName, object>{{ TimeName.Fajr, 18 }, { TimeName.Isha, 17 }} } }, { MethodName.ISNA, new Method { name = "Islamic Society of North America (ISNA)", _params = new Dictionary<TimeName, object> {{ TimeName.Fajr, 15 }, { TimeName.Isha, 15 }} } }, { MethodName.Egypt, new Method { name = "Egyptian General Authority of Survey", _params = new Dictionary<TimeName, object> {{ TimeName.Fajr, 19.5 }, { TimeName.Isha, 17.5 }} } }, { MethodName.Makkah, new Method { name = "Umm Al-Qura University, Makkah", _params = new Dictionary<TimeName, object> {{ TimeName.Fajr, 18.5 }, { TimeName.Isha, "90 min" }} } }, // fajr was 19 degrees before 1430 hijri { MethodName.Karachi, new Method { name = "University of Islamic Sciences, Karachi", _params = new Dictionary<TimeName, object> {{ TimeName.Fajr, 18 }, { TimeName.Isha, 18 }} } }, { MethodName.Tehran, new Method { name = "Institute of Geophysics, University of Tehran", _params = new Dictionary<TimeName, object> {{ TimeName.Fajr, 17.7 }, { TimeName.Isha, 14 }, { TimeName.Maghrib, 4.5 }, { TimeName.Midnight, "Jafari" }} } }, // isha is not explicitly specified in this method { MethodName.Jafari, new Method { name = "Shia Ithna-Ashari, Leva Institute, Qum", _params = new Dictionary<TimeName, object> {{ TimeName.Fajr, 16 }, { TimeName.Isha, 14 }, { TimeName.Maghrib, 4 }, { TimeName.Midnight, "Jafari" }} } } }; // Default Parameters in Calculation Methods defaultParams = new Dictionary<TimeName, object> { { TimeName.Maghrib, "0 min" }, { TimeName.Midnight, "Standard" } }; //----------------------- Parameter Values ---------------------- /* // Asr Juristic Methods asrJuristics = [ "Standard", // Shafi`i, Maliki, Ja`fari, Hanbali "Hanafi" // Hanafi ], // Midnight Mode midnightMethods = [ "Standard", // Mid Sunset to Sunrise "Jafari" // Mid Sunset to Fajr ], // Adjust Methods for Higher Latitudes highLatMethods = [ "NightMiddle", // middle of night "AngleBased", // angle/60th of night "OneSeventh", // 1/7th of night "None" // No adjustment ], // Time Formats timeFormats = [ "24h", // 24-hour format "12h", // 12-hour format "12hNS", // 12-hour format with no suffix "Float" // floating point number ], */ //---------------------- Default Settings -------------------- // do not change anything here; use adjust method instead setting = new Dictionary<TimeName, object> { {TimeName.Imsak , "10 min"}, {TimeName.Dhuhr , "0 min"}, {TimeName.Asr , AsrMethod.Standard}, {TimeName.HighLats , "NightMiddle"} }; //---------------------- Initialization ----------------------- // set methods defaults foreach (var method1 in methods) { var _paramss = method1.Value._params; var defParams = defaultParams.Where(p => !_paramss.ContainsKey(p.Key)); foreach (var keyValuePair in defParams) { _paramss.Add(keyValuePair.Key, keyValuePair.Value); } } // initialize settings var _params = methods[method]._params; foreach (var param in _params) { setting.Add(param.Key, param.Value); } // init time offsets offset = timeNames.ToDictionary(i => i, i => 0.0); } // set calculation method public void setMethod(MethodName method) { if (methods.ContainsKey(method)) { calcMethod = method; } } // set calculating parameters public void adjust(Dictionary<TimeName, object> paramss) { foreach (var id in paramss) { setting[id.Key] = id.Value; } } // set time offsets public void tune(double[] timeOffsets) { for (int i = 0; i < timeOffsets.Length; i++) { var element = offset.ElementAt(i); offset[element.Key] = timeOffsets[i]; } } // get current calculation method public MethodName getMethod() { return calcMethod; } // get current setting public Dictionary<TimeName, object> getSetting () { return setting; } // get current time offsets public Dictionary<TimeName, double> getOffsets() { return offset; } // get default calc parametrs public Dictionary<MethodName, Method> getDefaults() { return methods; } // return prayer times foreach a given date public Dictionary<TimeName, double> getTimes(DateTime date, GeoCoordinate coords, double? timezone = null, double? dst = null, string format = null) { lat = 1 * coords.Latitude; lng = 1 * coords.Longitude; elv = coords.Elevation.HasValue ? 1 * coords.Elevation.Value : 0; timeFormat = !string.IsNullOrEmpty(format) ? format : timeFormat; if (!timezone.HasValue) timezone = this.getTimeZone(date); if (!dst.HasValue) dst = this.getDst(date); timeZone = 1.0 * timezone.Value + (1.0 * dst.Value); jDate = this.julian(date.Year, date.Month, date.Day) - lng / (15 * 24); return this.computeTimes(); } // convert float time to the given format (see timeFormats) public string getFormattedTime(double time, object format, string[] suffixes = null) { if (double.IsNaN(time)) throw new Exception(invalidTime); if (format == "Float") return time.ToString(); suffixes = suffixes ?? timeSuffixes; time = DMath.fixHour(time + 0.5 / 60); // add 0.5 minutes to round var hours = Math.Floor(time); var minutes = Math.Floor((time - hours) * 60); var suffix = (format == "12h") ? suffixes[hours < 12 ? 0 : 1] : string.Empty; var hour = (format == "24h") ? this.twoDigitsFormat((double)hours) : ((hours + 12 - 1) % 12 + 1).ToString(); return hour + ":" + this.twoDigitsFormat(minutes) + (!string.IsNullOrEmpty(suffix) ? " " + suffix : string.Empty); } //---------------------- Calculation Functions ----------------------- // compute mid-day time public double midDay(double time) { var eqt = this.sunPosition(jDate + time).equation; var noon = DMath.fixHour(12 - eqt); return noon; } // compute the time at which sun reaches a specific angle below horizon public double sunAngleTime(double angle, double time, string direction = null) { var decl = this.sunPosition(jDate + time).declination; var noon = this.midDay(time); var t = 1 / 15 * DMath.arccos((-DMath.sin(angle) - DMath.sin(decl) * DMath.sin(lat)) / (DMath.cos(decl) * DMath.cos(lat))); return noon + (direction == "ccw" ? -t : t); } // compute asr time public double asrTime(double factor, double time) { var decl = this.sunPosition(jDate + time).declination; var angle = -DMath.arccot(factor + DMath.tan(Math.Abs(lat - decl))); return this.sunAngleTime(angle, time); } // compute declination angle of sun and equation of time // Ref: http://aa.usno.navy.mil/faq/docs/SunApprox.php public SunPosition sunPosition(double jd) { var D = jd - 2451545.0; var g = DMath.fixAngle(357.529 + 0.98560028 * D); var q = DMath.fixAngle(280.459 + 0.98564736 * D); var L = DMath.fixAngle(q + 1.915 * DMath.sin(g) + 0.020 * DMath.sin(2 * g)); var R = 1.00014 - 0.01671 * DMath.cos(g) - 0.00014 * DMath.cos(2 * g); var e = 23.439 - 0.00000036 * D; var RA = DMath.arctan2(DMath.cos(e) * DMath.sin(L), DMath.cos(L)) / 15; var eqt = q / 15 - DMath.fixHour(RA); var decl = DMath.arcsin(DMath.sin(e) * DMath.sin(L)); return new SunPosition(decl, eqt); } // convert Gregorian date to Julian day // Ref: Astronomical Algorithms by Jean Meeus public double julian(double year, double month, double day) { if (month <= 2) { year -= 1; month += 12; } var A = Math.Floor(year / 100.0); var B = 2 - A + Math.Floor(A / 4.0); var JD = Math.Floor(365.25 * (year + 4716)) + Math.Floor(30.6001 * (month + 1.0)) + day + B - 1524.5; return JD; } //---------------------- Compute Prayer Times ----------------------- // compute prayer times at given julian date public Dictionary<TimeName, double> computePrayerTimes(Dictionary<TimeName, double> times) { times = this.dayPortion(times); var paramss = setting; var imsak = this.sunAngleTime(this.eval(paramss[TimeName.Imsak]), times[TimeName.Imsak], "ccw"); var fajr = this.sunAngleTime(this.eval(paramss[TimeName.Fajr]), times[TimeName.Fajr], "ccw"); var sunrise = this.sunAngleTime(this.riseSetAngle(), times[TimeName.Sunrise], "ccw"); var dhuhr = this.midDay(times[TimeName.Dhuhr]); var asr = this.asrTime(this.asrFactor((AsrMethod)paramss[TimeName.Asr]), times[TimeName.Asr]); var sunset = this.sunAngleTime(this.riseSetAngle(), times[TimeName.Sunset]); var maghrib = this.sunAngleTime(this.eval(paramss[TimeName.Maghrib]), times[TimeName.Maghrib]); var isha = this.sunAngleTime(this.eval(paramss[TimeName.Isha]), times[TimeName.Isha]); return new Dictionary < TimeName, double> { { TimeName.Imsak, imsak}, { TimeName.Fajr, fajr}, { TimeName.Sunrise, sunrise}, { TimeName.Dhuhr, dhuhr}, { TimeName.Asr, asr}, { TimeName.Sunset, sunset}, { TimeName.Maghrib, maghrib}, { TimeName.Isha, isha} }; } // compute prayer times public Dictionary<TimeName, double> computeTimes() { // default times var times = new Dictionary<TimeName, double> { { TimeName.Imsak, 5}, {TimeName.Fajr, 5}, {TimeName.Sunrise, 6}, { TimeName.Dhuhr, 12}, { TimeName.Asr,13}, { TimeName.Sunset,18}, { TimeName.Maghrib, 18}, { TimeName.Isha, 18} }; // main iterations for (var i = 1; i<=numIterations ; i++) { times = this.computePrayerTimes(times);} times = this.adjustTimes(times); // add midnight time times[TimeName.Midnight] = (setting[TimeName.Midnight] == "Jafari") ? times[TimeName.Sunset]+ this.timeDiff(times[TimeName.Sunset], times[TimeName.Fajr])/ 2 : times[TimeName.Sunset]+ this.timeDiff(times[TimeName.Sunset], times[TimeName.Sunrise])/ 2; times = this.tuneTimes(times); return this.modifyFormats(times); } // adjust times public Dictionary<TimeName, double> adjustTimes(Dictionary<TimeName, double> times) { var paramss = setting; for (int i = 0; i < times.Count; i++) { times[times.ElementAt(i).Key] += timeZone - lng / 15; } if (paramss[TimeName.HighLats] != "None") times = this.adjustHighLats(times); if (this.isMin(paramss[TimeName.Imsak])) times[TimeName.Imsak] = times[TimeName.Fajr] - this.eval(paramss[TimeName.Imsak]) / 60; if (this.isMin(paramss[TimeName.Maghrib])) times[TimeName.Maghrib] = times[TimeName.Sunset] + this.eval(paramss[TimeName.Maghrib]) / 60; if (this.isMin(paramss[TimeName.Isha])) times[TimeName.Isha] = times[TimeName.Maghrib] + this.eval(paramss[TimeName.Isha]) / 60; times[TimeName.Dhuhr] += this.eval(paramss[TimeName.Dhuhr]) / 60; return times; } // get asr shadow factor public double asrFactor(AsrMethod asrParam) { var factor = new Dictionary<AsrMethod, double> { { AsrMethod.Standard, 1}, { AsrMethod.Hanafi, 2}}; //[asrParam]; //return factor || this.eval(asrParam); return factor[asrParam]; } // return sun angle foreach sunset/sunrise public double riseSetAngle() { //var earthRad = 6371009; // in meters //var angle = DMath.arccos(earthRad/(earthRad+ elv)); var angle = 0.0347 * Math.Sqrt(elv); // an approximation return 0.833 + angle; } // apply offsets to the times public Dictionary<TimeName, double> tuneTimes(Dictionary<TimeName, double> times) { for (int i = 0; i < times.Count; i++) { var element = times.ElementAt(i); times[element.Key] += offset[element.Key] / 60.0; } return times; } // convert times to given time format public Dictionary<TimeName, double> modifyFormats(Dictionary<TimeName, double> times) { for (int i = 0; i < times.Count; i++) { var element = times.ElementAt(i); //times[i.Key] = this.getFormattedTime(times[i.Key], timeFormat); var formattedTime = this.getFormattedTime(times[element.Key], this.timeFormat); times[element.Key] = Convert.ToDouble(this.getFormattedTime(times[element.Key], this.timeFormat)); } return times; } // adjust times foreach locations in higher latitudes public Dictionary<TimeName, double> adjustHighLats(Dictionary<TimeName, double> times) { var paramss = setting; var nightTime = this.timeDiff(times[TimeName.Sunset], times[TimeName.Sunrise]); times[TimeName.Imsak] = this.adjustHLTime(times[TimeName.Imsak], times[TimeName.Sunrise], this.eval(paramss[TimeName.Imsak]), nightTime, "ccw"); times[TimeName.Fajr] = this.adjustHLTime(times[TimeName.Fajr], times[TimeName.Sunrise], this.eval(paramss[TimeName.Fajr]), nightTime, "ccw"); times[TimeName.Isha] = this.adjustHLTime(times[TimeName.Isha], times[TimeName.Sunset], this.eval(paramss[TimeName.Isha]), nightTime); times[TimeName.Maghrib] = this.adjustHLTime(times[TimeName.Maghrib], times[TimeName.Sunset], this.eval(paramss[TimeName.Maghrib]), nightTime); return times; } // adjust a time foreach higher latitudes public double adjustHLTime(double time, double _base, double angle, double night, object direction = null) { var portion = this.nightPortion(angle, night); var timeDiff = (direction == "ccw") ? this.timeDiff(time, _base) : this.timeDiff(_base, time); if (double.IsNaN(time) || timeDiff > portion) time = _base + (direction == "ccw" ? -portion : portion); return time; } // the night portion used foreach adjusting times in higher latitudes public double nightPortion(double angle, double night) { var method = setting[TimeName.HighLats]; var portion = 1.0 / 2.0; // MidNight if (method == "AngleBased") portion = 1.0 / 60.0 * angle; if (method == "OneSeventh") portion = 1 / 7; return portion * night; } // convert hours to day portions public Dictionary<TimeName, double> dayPortion(Dictionary<TimeName, double> times) { for (int i = 0; i < times.Count; i++) { times[times.ElementAt(i).Key] /= 24; } return times; } //---------------------- Time Zone Functions ----------------------- // get local time zone public double getTimeZone(DateTime date) { var year = date.Year; double t1 = this.gmtOffset(new DateTime(year, 0, 1)); double t2 = this.gmtOffset(new DateTime(year, 6, 1)); return Math.Min(t1, t2); } // get daylight saving foreach a given date public double getDst(DateTime date) { //return 1 * (this.gmtOffset(date) != this.getTimeZone(date)); return 1 * this.getTimeZone(date); } // GMT offset foreach a given date public double gmtOffset(DateTime date) { var localDate = new DateTime(date.Year, date.Month - 1, date.Day, 12, 0, 0, 0); var GMTString = localDate.ToUniversalTime().ToString(); var GMTDate = DateTime.Parse(GMTString.Substring(0, GMTString.LastIndexOf(" ") - 1)); var hoursDiff = (localDate - GMTDate).TotalHours / (1000 * 60 * 60); return hoursDiff; } //---------------------- Misc Functions ----------------------- // convert given string into a number public double eval(object str) { var fdgdfg = Regex.Split(str + string.Empty, "[^0-9.+-]"); return 1 * double.Parse(Regex.Split(str + string.Empty, "[^0-9.+-]")[0]); } // detect if input contains "min" public bool isMin(object arg) { return (arg + string.Empty).IndexOf("min") != -1; } // compute the difference between two times public double timeDiff(double time1, double time2) { return DMath.fixHour(time2 - time1); } // add a leading 0 if necessary public string twoDigitsFormat(double num) { return (num < 10) ? "0" + num : num.ToString(); } } }
//! \file ArcERI.cs //! \date Wed Jan 27 18:24:06 2016 //! \brief Entis multi-frame image format. // // Copyright (C) 2016 by morkt // // 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.ComponentModel.Composition; using System.IO; using System.Linq; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Utility; namespace GameRes.Formats.Entis { [Export(typeof(ArchiveFormat))] public class EriOpener : ArchiveFormat { public override string Tag { get { return "ERI/MULTI"; } } public override string Description { get { return "Entis multi-frame image format"; } } public override uint Signature { get { return 0x69746e45u; } } // 'Enti' public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public EriOpener () { Extensions = new string[] { "eri" }; } static readonly Lazy<ImageFormat> s_EriFormat = new Lazy<ImageFormat> (() => ImageFormat.FindByTag ("ERI")); public override ArcFile TryOpen (ArcView file) { if (!file.View.AsciiEqual (0x10, "Entis Rasterized Image") && !file.View.AsciiEqual (0x10, "Moving Entis Image")) return null; EriMetaData info; using (var eris = file.CreateStream()) info = s_EriFormat.Value.ReadMetaData (eris) as EriMetaData; if (null == info || null == info.Header || !IsSaneCount (info.Header.FrameCount)) return null; info.FileName = file.Name; string base_name = Path.GetFileNameWithoutExtension (file.Name); int count = info.Header.FrameCount; long current_offset = info.StreamPos; var dir = new List<Entry> (count); var id = new AsciiString (8); Color[] palette = null; int i = 0; while (i < count && current_offset < file.MaxOffset) { if (file.View.Read (current_offset, id.Value, 0, 8) < 8) break; if ("Stream " == id) { current_offset += 0x10; continue; } long section_size = file.View.ReadInt64 (current_offset+8); if (section_size < 0 || section_size > int.MaxValue) throw new FileSizeException(); current_offset += 0x10; if (0 == section_size) continue; if ("Palette " == id) { using (var stream = file.CreateStream (current_offset, (uint)section_size)) palette = EriFormat.ReadPalette (stream, (int)section_size); } else if ("ImageFrm" == id || "DiffeFrm" == id) { var entry = new EriEntry { Name = string.Format ("{0}#{1:D4}", base_name, i++), Type = "image", Offset = current_offset, Size = (uint)section_size, FrameIndex = dir.Count, IsDiff = "DiffeFrm" == id, }; if (!entry.CheckPlacement (file.MaxOffset)) return null; dir.Add (entry); } current_offset += section_size; } if (0 == dir.Count) return null; return new EriMultiImage (file, this, dir, info, palette); } public override IImageDecoder OpenImage (ArcFile arc, Entry entry) { var earc = (EriMultiImage)arc; var eent = (EriEntry)entry; var pixels = earc.GetFrame (eent.FrameIndex); BitmapPalette palette = null; if (8 == earc.Info.BPP && earc.Palette != null) palette = new BitmapPalette (earc.Palette); return new BitmapDecoder (pixels, earc.Info, earc.Format, palette); } } internal class EriMultiImage : ArcFile { public readonly EriMetaData Info; public readonly Color[] Palette; public readonly PixelFormat Format; byte[][] Frames; public EriMultiImage (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, EriMetaData info, Color[] palette) : base (arc, impl, dir) { Info = info; Palette = palette; Frames = new byte[dir.Count][]; if (8 == Info.BPP) { if (null == Palette) Format = PixelFormats.Gray8; else Format = PixelFormats.Indexed8; } else if (32 == Info.BPP) { if (0 == (Info.FormatType & EriType.WithAlpha)) Format = PixelFormats.Bgr32; else Format = PixelFormats.Bgra32; } else if (16 == Info.BPP) Format = PixelFormats.Bgr555; else Format = PixelFormats.Bgr24; } public byte[] GetFrame (int index) { if (index >= Frames.Length) throw new ArgumentException ("index"); if (null != Frames[index]) return Frames[index]; var entry = Dir.ElementAt (index) as EriEntry; byte[] prev_frame = null; if (index > 0 && entry.IsDiff) { prev_frame = GetFrame (index-1); } using (var stream = File.CreateStream (entry.Offset, entry.Size)) { var reader = new EriReader (stream, Info, Palette, prev_frame); reader.DecodeImage(); Frames[index] = reader.Data; } return Frames[index]; } } internal class EriEntry : Entry { public int FrameIndex; public bool IsDiff; } internal class BitmapDecoder : IImageDecoder { public Stream Source { get { return null; } } public ImageFormat SourceFormat { get { return null; } } public ImageMetaData Info { get; private set; } public ImageData Image { get; private set; } public BitmapDecoder (byte[] pixels, ImageMetaData info, PixelFormat format, BitmapPalette palette) { Info = info; Image = ImageData.Create (info, format, palette, pixels); } public void Dispose () { } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. namespace Microsoft.Azure.Management.Rdfe.Models { /// <summary> /// The Get Subscription operation response. /// </summary> public partial class SubscriptionGetResponse : AzureOperationResponse { private string _accountAdminLiveEmailId; /// <summary> /// Optional. The live ID of the account administrator. /// </summary> public string AccountAdminLiveEmailId { get { return this._accountAdminLiveEmailId; } set { this._accountAdminLiveEmailId = value; } } private int _currentCoreCount; /// <summary> /// Optional. The number of currently allocated cores. /// </summary> public int CurrentCoreCount { get { return this._currentCoreCount; } set { this._currentCoreCount = value; } } private int _currentDnsServers; /// <summary> /// Optional. The current number of DNS servers allocated on this /// subscription. /// </summary> public int CurrentDnsServers { get { return this._currentDnsServers; } set { this._currentDnsServers = value; } } private int _currentHostedServices; /// <summary> /// Optional. The number of currently allocated cloud services. /// </summary> public int CurrentHostedServices { get { return this._currentHostedServices; } set { this._currentHostedServices = value; } } private int _currentLocalNetworkSites; /// <summary> /// Optional. The current number of local virtual network sites that /// are allocated on this subscription. /// </summary> public int CurrentLocalNetworkSites { get { return this._currentLocalNetworkSites; } set { this._currentLocalNetworkSites = value; } } private int _currentStorageAccounts; /// <summary> /// Optional. The number of currently allocated storage accounts. /// </summary> public int CurrentStorageAccounts { get { return this._currentStorageAccounts; } set { this._currentStorageAccounts = value; } } private int _currentVirtualNetworkSites; /// <summary> /// Optional. The number of currently allocated virtual network sites. /// </summary> public int CurrentVirtualNetworkSites { get { return this._currentVirtualNetworkSites; } set { this._currentVirtualNetworkSites = value; } } private int _maximumCoreCount; /// <summary> /// Optional. The maximum number of cores that can be allocated on this /// subscription. /// </summary> public int MaximumCoreCount { get { return this._maximumCoreCount; } set { this._maximumCoreCount = value; } } private int _maximumDnsServers; /// <summary> /// Optional. The maximum number of DNS servers that can be allocated /// on this subscription. /// </summary> public int MaximumDnsServers { get { return this._maximumDnsServers; } set { this._maximumDnsServers = value; } } private int _maximumHostedServices; /// <summary> /// Optional. The maximum number of cloud services that can be /// allocated on this subscription. /// </summary> public int MaximumHostedServices { get { return this._maximumHostedServices; } set { this._maximumHostedServices = value; } } private int _maximumLocalNetworkSites; /// <summary> /// Optional. The maximum number of local virtual network sites that /// can be allocated on this subscription. /// </summary> public int MaximumLocalNetworkSites { get { return this._maximumLocalNetworkSites; } set { this._maximumLocalNetworkSites = value; } } private int _maximumStorageAccounts; /// <summary> /// Optional. The maximum number of storage accounts that can be /// allocated on this subscription. /// </summary> public int MaximumStorageAccounts { get { return this._maximumStorageAccounts; } set { this._maximumStorageAccounts = value; } } private int _maximumVirtualNetworkSites; /// <summary> /// Optional. The maximum number of virtual network sites that can be /// allocated on this subscription. /// </summary> public int MaximumVirtualNetworkSites { get { return this._maximumVirtualNetworkSites; } set { this._maximumVirtualNetworkSites = value; } } private string _serviceAdminLiveEmailId; /// <summary> /// Optional. The live ID of the subscription administrator. /// </summary> public string ServiceAdminLiveEmailId { get { return this._serviceAdminLiveEmailId; } set { this._serviceAdminLiveEmailId = value; } } private string _subscriptionID; /// <summary> /// Optional. The subscription ID that the operation was called on. /// </summary> public string SubscriptionID { get { return this._subscriptionID; } set { this._subscriptionID = value; } } private string _subscriptionName; /// <summary> /// Optional. The user-supplied name for the subscription. /// </summary> public string SubscriptionName { get { return this._subscriptionName; } set { this._subscriptionName = value; } } private SubscriptionStatus _subscriptionStatus; /// <summary> /// Optional. The subscription status. /// </summary> public SubscriptionStatus SubscriptionStatus { get { return this._subscriptionStatus; } set { this._subscriptionStatus = value; } } /// <summary> /// Initializes a new instance of the SubscriptionGetResponse class. /// </summary> public SubscriptionGetResponse() { } } }
// 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.Linq; using System.Net.Test.Common; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Security.Tests { public abstract class SslStreamStreamToStreamTest { private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message"); protected abstract bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream); [OuterLoop] // TODO: Issue #11345 [Fact] public void SslStream_StreamToStream_Authentication_Success() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var server = new SslStream(serverStream)) using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { Assert.True(DoHandshake(client, server), "Handshake completed in the allotted time"); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void SslStream_StreamToStream_Authentication_IncorrectServerName_Fail() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new SslStream(clientStream)) using (var server = new SslStream(serverStream)) using (var certificate = Configuration.Certificates.GetServerCertificate()) { Task[] auth = new Task[2]; auth[0] = client.AuthenticateAsClientAsync("incorrectServer"); auth[1] = server.AuthenticateAsServerAsync(certificate); Assert.Throws<AuthenticationException>(() => { auth[0].GetAwaiter().GetResult(); }); auth[1].GetAwaiter().GetResult(); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void SslStream_StreamToStream_Successive_ClientWrite_Sync_Success() { byte[] recvBuf = new byte[_sampleMsg.Length]; VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { bool result = DoHandshake(clientSslStream, serverSslStream); Assert.True(result, "Handshake completed."); clientSslStream.Write(_sampleMsg); serverSslStream.Read(recvBuf, 0, _sampleMsg.Length); Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected."); clientSslStream.Write(_sampleMsg); serverSslStream.Read(recvBuf, 0, _sampleMsg.Length); Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected."); } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] public void SslStream_StreamToStream_LargeWrites_Sync_Success(bool randomizedData) { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer:false)) using (var serverStream = new VirtualNetworkStream(network, isServer:true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { Assert.True(DoHandshake(clientSslStream, serverSslStream), "Handshake complete"); byte[] largeMsg = new byte[4096 * 5]; // length longer than max read chunk size (16K + headers) if (randomizedData) { new Random().NextBytes(largeMsg); // not very compressible } else { for (int i = 0; i < largeMsg.Length; i++) { largeMsg[i] = (byte)i; // very compressible } } byte[] receivedLargeMsg = new byte[largeMsg.Length]; // First do a large write and read blocks at a time clientSslStream.Write(largeMsg); int bytesRead = 0, totalRead = 0; while (totalRead < largeMsg.Length && (bytesRead = serverSslStream.Read(receivedLargeMsg, totalRead, receivedLargeMsg.Length - totalRead)) != 0) { totalRead += bytesRead; } Assert.Equal(receivedLargeMsg.Length, totalRead); Assert.Equal(largeMsg, receivedLargeMsg); // Then write again and read bytes at a time clientSslStream.Write(largeMsg); foreach (byte b in largeMsg) { Assert.Equal(b, serverSslStream.ReadByte()); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public void SslStream_StreamToStream_Successive_ClientWrite_Async_Success() { byte[] recvBuf = new byte[_sampleMsg.Length]; VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { bool result = DoHandshake(clientSslStream, serverSslStream); Assert.True(result, "Handshake completed."); Task[] tasks = new Task[2]; tasks[0] = serverSslStream.ReadAsync(recvBuf, 0, _sampleMsg.Length); tasks[1] = clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length); bool finished = Task.WaitAll(tasks, TestConfiguration.PassingTestTimeoutMilliseconds); Assert.True(finished, "Send/receive completed in the allotted time"); Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected."); tasks[0] = serverSslStream.ReadAsync(recvBuf, 0, _sampleMsg.Length); tasks[1] = clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length); finished = Task.WaitAll(tasks, TestConfiguration.PassingTestTimeoutMilliseconds); Assert.True(finished, "Send/receive completed in the allotted time"); Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected."); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void SslStream_StreamToStream_Write_ReadByte_Success() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer:false)) using (var serverStream = new VirtualNetworkStream(network, isServer:true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { bool result = DoHandshake(clientSslStream, serverSslStream); Assert.True(result, "Handshake completed."); for (int i = 0; i < 3; i++) { clientSslStream.Write(_sampleMsg); foreach (byte b in _sampleMsg) { Assert.Equal(b, serverSslStream.ReadByte()); } } } } private bool VerifyOutput(byte[] actualBuffer, byte[] expectedBuffer) { return expectedBuffer.SequenceEqual(actualBuffer); } private bool AllowAnyServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None; if (!Capability.IsTrustedRootCertificateInstalled()) { expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors; } Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors); if (sslPolicyErrors == expectedSslPolicyErrors) { return true; } else { return false; } } } public sealed class SslStreamStreamToStreamTest_Async : SslStreamStreamToStreamTest { protected override bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream) { using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { Task t1 = clientSslStream.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false)); Task t2 = serverSslStream.AuthenticateAsServerAsync(certificate); return Task.WaitAll(new[] { t1, t2 }, TestConfiguration.PassingTestTimeoutMilliseconds); } } } public sealed class SslStreamStreamToStreamTest_BeginEnd : SslStreamStreamToStreamTest { protected override bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream) { using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { IAsyncResult a1 = clientSslStream.BeginAuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false), null, null); IAsyncResult a2 = serverSslStream.BeginAuthenticateAsServer(certificate, null, null); if (WaitHandle.WaitAll(new[] { a1.AsyncWaitHandle, a2.AsyncWaitHandle }, TestConfiguration.PassingTestTimeoutMilliseconds)) { clientSslStream.EndAuthenticateAsClient(a1); serverSslStream.EndAuthenticateAsServer(a2); return true; } return false; } } } public sealed class SslStreamStreamToStreamTest_Sync : SslStreamStreamToStreamTest { protected override bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream) { using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { Task t1 = Task.Run(() => clientSslStream.AuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false))); Task t2 = Task.Run(() => serverSslStream.AuthenticateAsServer(certificate)); return Task.WaitAll(new[] { t1, t2 }, TestConfiguration.PassingTestTimeoutMilliseconds); } } } }
namespace zlib { using System; internal sealed class InfBlocks { static InfBlocks() { InfBlocks.inflate_mask = new int[] { 0, 1, 3, 7, 15, 0x1f, 0x3f, 0x7f, 0xff, 0x1ff, 0x3ff, 0x7ff, 0xfff, 0x1fff, 0x3fff, 0x7fff, 0xffff }; InfBlocks.border = new int[] { 0x10, 0x11, 0x12, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; } internal InfBlocks(ZStream z, object checkfn, int w) { this.bb = new int[1]; this.tb = new int[1]; this.hufts = new int[0x10e0]; this.window = new byte[w]; this.end = w; this.checkfn = checkfn; this.mode = 0; this.reset(z, null); } internal void free(ZStream z) { this.reset(z, null); this.window = null; this.hufts = null; } internal int inflate_flush(ZStream z, int r) { int num2 = z.next_out_index; int num3 = this.read; int num1 = ((num3 <= this.write) ? this.write : this.end) - num3; if (num1 > z.avail_out) { num1 = z.avail_out; } if ((num1 != 0) && (r == -5)) { r = 0; } z.avail_out -= num1; z.total_out += num1; if (this.checkfn != null) { z.adler = this.check = z._adler.adler32(this.check, this.window, num3, num1); } Array.Copy(this.window, num3, z.next_out, num2, num1); num2 += num1; num3 += num1; if (num3 == this.end) { num3 = 0; if (this.write == this.end) { this.write = 0; } num1 = this.write - num3; if (num1 > z.avail_out) { num1 = z.avail_out; } if ((num1 != 0) && (r == -5)) { r = 0; } z.avail_out -= num1; z.total_out += num1; if (this.checkfn != null) { z.adler = this.check = z._adler.adler32(this.check, this.window, num3, num1); } Array.Copy(this.window, num3, z.next_out, num2, num1); num2 += num1; num3 += num1; } z.next_out_index = num2; this.read = num3; return r; } internal int proc(ZStream z, int r) { int num1; int num4 = z.next_in_index; int num5 = z.avail_in; int num2 = this.bitb; int num3 = this.bitk; int num6 = this.write; int num7 = (num6 < this.read) ? ((this.read - num6) - 1) : (this.end - num6); Label_0047: switch (this.mode) { case 0: while (num3 < 3) { if (num5 != 0) { r = 0; } else { this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } num5--; num2 |= (z.next_in[num4++] & 0xff) << (num3 & 0x1f); num3 += 8; } num1 = num2 & 7; this.last = num1 & 1; switch (SupportClass.URShift(num1, 1)) { case 0: num2 = SupportClass.URShift(num2, 3); num3 -= 3; num1 = num3 & 7; num2 = SupportClass.URShift(num2, num1); num3 -= num1; this.mode = 1; goto Label_0047; case 1: { int[] numArray1 = new int[1]; int[] numArray2 = new int[1]; int[][] numArrayArray1 = new int[1][]; int[][] numArrayArray2 = new int[1][]; InfTree.inflate_trees_fixed(numArray1, numArray2, numArrayArray1, numArrayArray2, z); this.codes = new InfCodes(numArray1[0], numArray2[0], numArrayArray1[0], numArrayArray2[0], z); num2 = SupportClass.URShift(num2, 3); num3 -= 3; this.mode = 6; goto Label_0047; } case 2: num2 = SupportClass.URShift(num2, 3); num3 -= 3; this.mode = 3; goto Label_0047; case 3: num2 = SupportClass.URShift(num2, 3); num3 -= 3; this.mode = 9; z.msg = "invalid block type"; r = -3; this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } goto Label_0047; case 1: while (num3 < 0x20) { if (num5 != 0) { r = 0; } else { this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } num5--; num2 |= (z.next_in[num4++] & 0xff) << (num3 & 0x1f); num3 += 8; } if ((SupportClass.URShift(~num2, 0x10) & 0xffff) != (num2 & 0xffff)) { this.mode = 9; z.msg = "invalid stored block lengths"; r = -3; this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } this.left = num2 & 0xffff; num2 = num3 = 0; this.mode = (this.left != 0) ? 2 : ((this.last != 0) ? 7 : 0); goto Label_0047; case 2: if (num5 == 0) { this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } if (num7 == 0) { if ((num6 == this.end) && (this.read != 0)) { num6 = 0; num7 = (num6 < this.read) ? ((this.read - num6) - 1) : (this.end - num6); } if (num7 == 0) { this.write = num6; r = this.inflate_flush(z, r); num6 = this.write; num7 = (num6 < this.read) ? ((this.read - num6) - 1) : (this.end - num6); if ((num6 == this.end) && (this.read != 0)) { num6 = 0; num7 = (num6 < this.read) ? ((this.read - num6) - 1) : (this.end - num6); } if (num7 == 0) { this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } } } r = 0; num1 = this.left; if (num1 > num5) { num1 = num5; } if (num1 > num7) { num1 = num7; } Array.Copy(z.next_in, num4, this.window, num6, num1); num4 += num1; num5 -= num1; num6 += num1; num7 -= num1; this.left -= num1; if (this.left == 0) { this.mode = (this.last != 0) ? 7 : 0; } goto Label_0047; case 3: while (num3 < 14) { if (num5 != 0) { r = 0; } else { this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } num5--; num2 |= (z.next_in[num4++] & 0xff) << (num3 & 0x1f); num3 += 8; } this.table = num1 = num2 & 0x3fff; if (((num1 & 0x1f) > 0x1d) || (((num1 >> 5) & 0x1f) > 0x1d)) { this.mode = 9; z.msg = "too many length or distance symbols"; r = -3; this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } num1 = (0x102 + (num1 & 0x1f)) + ((num1 >> 5) & 0x1f); this.blens = new int[num1]; num2 = SupportClass.URShift(num2, 14); num3 -= 14; this.index = 0; this.mode = 4; goto Label_06E1; case 4: goto Label_06E1; case 5: goto Label_07B9; case 6: goto Label_0B63; case 7: goto Label_0C2C; case 8: goto Label_0CC1; case 9: r = -3; this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); default: r = -2; this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } Label_06E1: if (this.index < (4 + SupportClass.URShift(this.table, 10))) { while (num3 < 3) { if (num5 != 0) { r = 0; } else { this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } num5--; num2 |= (z.next_in[num4++] & 0xff) << (num3 & 0x1f); num3 += 8; } this.blens[InfBlocks.border[this.index++]] = num2 & 7; num2 = SupportClass.URShift(num2, 3); num3 -= 3; goto Label_06E1; } while (this.index < 0x13) { this.blens[InfBlocks.border[this.index++]] = 0; } this.bb[0] = 7; num1 = InfTree.inflate_trees_bits(this.blens, this.bb, this.tb, this.hufts, z); if (num1 != 0) { r = num1; if (r == -3) { this.blens = null; this.mode = 9; } this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } this.index = 0; this.mode = 5; Label_07B9: num1 = this.table; if (this.index < ((0x102 + (num1 & 0x1f)) + ((num1 >> 5) & 0x1f))) { num1 = this.bb[0]; while (num3 < num1) { if (num5 != 0) { r = 0; } else { this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } num5--; num2 |= (z.next_in[num4++] & 0xff) << (num3 & 0x1f); num3 += 8; } int num17 = this.tb[0]; num1 = this.hufts[((this.tb[0] + (num2 & InfBlocks.inflate_mask[num1])) * 3) + 1]; int num10 = this.hufts[((this.tb[0] + (num2 & InfBlocks.inflate_mask[num1])) * 3) + 2]; if (num10 < 0x10) { num2 = SupportClass.URShift(num2, num1); num3 -= num1; this.blens[this.index++] = num10; goto Label_07B9; } int num8 = (num10 == 0x12) ? 7 : (num10 - 14); int num9 = (num10 == 0x12) ? 11 : 3; while (num3 < (num1 + num8)) { if (num5 != 0) { r = 0; } else { this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } num5--; num2 |= (z.next_in[num4++] & 0xff) << (num3 & 0x1f); num3 += 8; } num2 = SupportClass.URShift(num2, num1); num3 -= num1; num9 += num2 & InfBlocks.inflate_mask[num8]; num2 = SupportClass.URShift(num2, num8); num3 -= num8; num8 = this.index; num1 = this.table; if (((num8 + num9) > ((0x102 + (num1 & 0x1f)) + ((num1 >> 5) & 0x1f))) || ((num10 == 0x10) && (num8 < 1))) { this.blens = null; this.mode = 9; z.msg = "invalid bit length repeat"; r = -3; this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } num10 = (num10 == 0x10) ? this.blens[num8 - 1] : 0; do { this.blens[num8++] = num10; } while (--num9 != 0); this.index = num8; goto Label_07B9; } this.tb[0] = -1; int[] numArray3 = new int[1]; int[] numArray4 = new int[1]; int[] numArray5 = new int[1]; int[] numArray6 = new int[1]; numArray3[0] = 9; numArray4[0] = 6; num1 = this.table; num1 = InfTree.inflate_trees_dynamic(0x101 + (num1 & 0x1f), 1 + ((num1 >> 5) & 0x1f), this.blens, numArray3, numArray4, numArray5, numArray6, this.hufts, z); switch (num1) { case 0: this.codes = new InfCodes(numArray3[0], numArray4[0], this.hufts, numArray5[0], this.hufts, numArray6[0], z); this.blens = null; this.mode = 6; goto Label_0B63; case -3: this.blens = null; this.mode = 9; break; } r = num1; this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); Label_0B63: this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; if ((r = this.codes.proc(this, z, r)) != 1) { return this.inflate_flush(z, r); } r = 0; this.codes.free(z); num4 = z.next_in_index; num5 = z.avail_in; num2 = this.bitb; num3 = this.bitk; num6 = this.write; num7 = (num6 < this.read) ? ((this.read - num6) - 1) : (this.end - num6); if (this.last == 0) { this.mode = 0; goto Label_0047; } this.mode = 7; Label_0C2C: this.write = num6; r = this.inflate_flush(z, r); num6 = this.write; num7 = (num6 < this.read) ? ((this.read - num6) - 1) : (this.end - num6); if (this.read != this.write) { this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } this.mode = 8; Label_0CC1: r = 1; this.bitb = num2; this.bitk = num3; z.avail_in = num5; z.total_in += num4 - z.next_in_index; z.next_in_index = num4; this.write = num6; return this.inflate_flush(z, r); } internal void reset(ZStream z, long[] c) { if (c != null) { c[0] = this.check; } if ((this.mode == 4) || (this.mode == 5)) { this.blens = null; } if (this.mode == 6) { this.codes.free(z); } this.mode = 0; this.bitk = 0; this.bitb = 0; this.read = this.write = 0; if (this.checkfn != null) { z.adler = this.check = z._adler.adler32((long) 0, null, 0, 0); } } internal void set_dictionary(byte[] d, int start, int n) { Array.Copy(d, start, this.window, 0, n); this.read = this.write = n; } internal int sync_point() { if (this.mode != 1) { return 0; } return 1; } private const int BAD = 9; internal int[] bb; internal int bitb; internal int bitk; internal int[] blens; internal static readonly int[] border; private const int BTREE = 4; internal long check; internal object checkfn; internal InfCodes codes; private const int CODES = 6; private const int DONE = 8; private const int DRY = 7; private const int DTREE = 5; internal int end; internal int[] hufts; internal int index; private static readonly int[] inflate_mask; internal int last; internal int left; private const int LENS = 1; private const int MANY = 0x5a0; internal int mode; internal int read; private const int STORED = 2; internal int table; private const int TABLE = 3; internal int[] tb; private const int TYPE = 0; internal byte[] window; internal int write; private const int Z_BUF_ERROR = -5; private const int Z_DATA_ERROR = -3; private const int Z_ERRNO = -1; private const int Z_MEM_ERROR = -4; private const int Z_NEED_DICT = 2; private const int Z_OK = 0; private const int Z_STREAM_END = 1; private const int Z_STREAM_ERROR = -2; private const int Z_VERSION_ERROR = -6; } }
// 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.AcceptanceTestsHttp { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// HttpFailure operations. /// </summary> public partial class HttpFailure : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpFailure { /// <summary> /// Initializes a new instance of the HttpFailure class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public HttpFailure(AutoRestHttpInfrastructureTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestHttpInfrastructureTestService /// </summary> public AutoRestHttpInfrastructureTestService Client { get; private set; } /// <summary> /// Get empty error form server /// </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<HttpOperationResponse<bool?>> GetEmptyErrorWithHttpMessagesAsync(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, "GetEmptyError", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/emptybody/error").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, 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 HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get empty error form server /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// 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<HttpOperationResponse<bool?>> GetNoModelErrorWithHttpMessagesAsync(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, "GetNoModelError", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/nomodel/error").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new 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 HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get empty response from server /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// 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<HttpOperationResponse<bool?>> GetNoModelEmptyWithHttpMessagesAsync(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, "GetNoModelEmpty", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/nomodel/empty").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new 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 HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* * Please keep in mind that this is NOT a refactored code. It is just reformatted, as the task states. * StyleCop and other validation tools will give warnings! =) * A referance to PowerCollections is not required. */ using System; using System.Linq; using System.Text; using Wintellect.PowerCollections; class Event : IComparable { public DateTime date; public String title; public String location; public Event(DateTime date, String title, String location) { this.date = date; this.title = title; this.location = location; } public int CompareTo(object obj) { Event other = obj as Event; int byDate = this.date.CompareTo(other.date); int byTitle = this.title.CompareTo(other.title); int byLocation = this.location.CompareTo(other.location); if (byDate == 0) { if (byTitle == 0) { return byLocation; } else { return byTitle; } } else { return byDate; } } public override string ToString() { StringBuilder toString = new StringBuilder(); toString.Append(date.ToString("yyyy-MM-ddTHH:mm:ss")); toString.Append(" | " + title); if (location != null && location != "") { toString.Append(" | " + location); } return toString.ToString(); } } class Program { static StringBuilder output = new StringBuilder(); static class Messages { public static void EventAdded() { output.Append("Event added\n"); } public static void EventDeleted(int x) { if (x == 0) { NoEventsFound(); } else { output.AppendFormat("{0} events deleted\n", x); } } public static void NoEventsFound() { output.Append("No events found\n"); } public static void PrintEvent(Event eventToPrint) { if (eventToPrint != null) { output.Append(eventToPrint + "\n"); } } } class EventHolder { MultiDictionary<string, Event> byTitle = new MultiDictionary<string, Event>(true); OrderedBag<Event> byDate = new OrderedBag<Event>(); public void AddEvent(DateTime date, string title, string location) { Event newEvent = new Event(date, title, location); byTitle.Add(title.ToLower(), newEvent); byDate.Add(newEvent); Messages.EventAdded(); } public void DeleteEvents(string titleToDelete) { string title = titleToDelete.ToLower(); int removed = 0; foreach (var eventToRemove in byTitle[title]) { removed ++; byDate.Remove(eventToRemove); } byTitle.Remove(title); Messages.EventDeleted(removed); } public void ListEvents(DateTime date, int count) { OrderedBag<Event>.View eventsToShow = byDate.RangeFrom(new Event(date, "", ""), true); int showed = 0; foreach (var eventToShow in eventsToShow) { if (showed == count) { break; } Messages.PrintEvent(eventToShow); showed++; } if (showed == 0) { Messages.NoEventsFound(); } } } static EventHolder events = new EventHolder(); static void Main(string[] args) { while (ExecuteNextCommand()) { } Console.WriteLine(output); } private static bool ExecuteNextCommand() { string command = Console.ReadLine(); if (command[0] == 'A') { AddEvent(command); return true; } if (command[0] == 'D') { DeleteEvents(command); return true; } if (command[0] == 'L') { ListEvents(command); return true; } if (command[0] == 'E') { return false; } return false; } private static void ListEvents(string command) { int pipeIndex = command.IndexOf('|'); DateTime date = GetDate(command, "ListEvents"); string countString = command.Substring(pipeIndex + 1); int count = int.Parse(countString); events.ListEvents(date, count); } private static void DeleteEvents(string command) { string title = command.Substring("DeleteEvents".Length + 1); events.DeleteEvents(title); } private static void AddEvent(string command) { DateTime date; string title; string location; GetParameters(command, "AddEvent", out date, out title, out location); events.AddEvent(date, title, location); } private static void GetParameters(string commandForExecution, string commandType, out DateTime dateAndTime, out string eventTitle, out string eventLocation) { dateAndTime = GetDate(commandForExecution, commandType); int firstPipeIndex = commandForExecution.IndexOf('|'); int lastPipeIndex = commandForExecution.LastIndexOf('|'); if (firstPipeIndex == lastPipeIndex) { eventTitle = commandForExecution .Substring(firstPipeIndex + 1) .Trim(); eventLocation = ""; } else { eventTitle = commandForExecution .Substring(firstPipeIndex + 1, lastPipeIndex - firstPipeIndex - 1) .Trim(); eventLocation = commandForExecution .Substring(lastPipeIndex + 1) .Trim(); } } private static DateTime GetDate(string command, string commandType) { DateTime date = DateTime.Parse(command.Substring(commandType.Length + 1, 20)); return date; } }
//------------------------------------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="Ftp.cs">(c) 2017 Mike Fourie and Contributors (https://github.com/mikefourie/MSBuildExtensionPack) under MIT License. See https://opensource.org/licenses/MIT </copyright> //------------------------------------------------------------------------------------------------------------------------------------------------------------------- namespace MSBuild.ExtensionPack.Communication { using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using Extended; using Microsoft.Build.Framework; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>UploadFiles</i> (<b>Required:</b> Host, FileNames <b>Optional:</b> UserName, UserPassword, WorkingDirectory, RemoteDirectoryName, Port)</para> /// <para><i>DownloadFiles</i> (<b>Required:</b> Host <b>Optional:</b> FileNames, UserName, UserPassword, WorkingDirectory, RemoteDirectoryName, Port)</para> /// <para><i>DeleteFiles</i> (<b>Required:</b> Host, FileNames <b>Optional:</b> UserName, UserPassword, WorkingDirectory, RemoteDirectoryName, Port)</para> /// <para><i>DeleteDirectory</i> (<b>Required:</b> Host<b>Optional:</b> UserName, UserPassword, WorkingDirectory, RemoteDirectoryName, Port)</para> /// <para><i>CreateDirectory</i> (<b>Required:</b> Host<b>Optional:</b> UserName, UserPassword, WorkingDirectory, RemoteDirectoryName, Port)</para> /// <para><b>Remote Execution Support:</b> NA</para> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// <ftpHost>localhost</ftpHost> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <Target Name="Default"> /// <ItemGroup> /// <!-- Specify FilesToUpload --> /// <FilesToUpload Include="C:\demo.txt" /> /// <FilesToUpload Include="C:\demo2.txt" /> /// </ItemGroup> /// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="UploadFiles" Host="$(ftpHost)" FileNames="@(FilesToUpload)"/> /// <ItemGroup> /// <!-- Specify the files to Download--> /// <FilesToDownload Include="demo2.txt" /> /// <FilesToDownload Include="demo.txt" /> /// </ItemGroup> /// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="DownloadFiles" Host="$(ftpHost)" FileNames="@(FilesToDownload)" WorkingDirectory="C:\FtpWorkingFolder"/> /// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="CreateDirectory" Host="$(ftpHost)" RemoteDirectoryName="NewFolder1"/> /// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="CreateDirectory" Host="$(ftpHost)" RemoteDirectoryName="NewFolder2"/> /// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="DeleteDirectory" Host="$(ftpHost)" RemoteDirectoryName="NewFolder1"/> /// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="DeleteFiles" Host="$(ftpHost)" FileNames="@(FilesToDownload)" /> /// </Target> /// </Project> /// ]]></code> /// </example> public class Ftp : BaseTask { private const string UploadFilesTaskAction = "UploadFiles"; private const string DownloadFilesTaskAction = "DownloadFiles"; private const string DeleteFilesTaskAction = "DeleteFiles"; private const string DeleteDirectoryTaskAction = "DeleteDirectory"; private const string CreateDirectoryTaskAction = "CreateDirectory"; /// <summary> /// Sets the Host of the FTP Site. /// </summary> [Required] public string Host { get; set; } /// <summary> /// Sets the Remote Path to connect to the FTP Site /// </summary> public string RemoteDirectoryName { get; set; } /// <summary> /// Sets the working directory on the local machine /// </summary> public string WorkingDirectory { get; set; } /// <summary> /// The port used to connect to the ftp server. /// </summary> public int Port { get; set; } /// <summary> /// Sets if the upload action will overwrite existing files /// </summary> public string Overwrite { get; set; } /// <summary> /// The list of files that needs to be transfered over FTP /// </summary> public ITaskItem[] FileNames { get; set; } /// <summary> /// Performs the action of this task. /// </summary> protected override void InternalExecute() { if (string.IsNullOrEmpty(this.Host)) { this.Log.LogError("The required host attribute has not been set for FTP."); return; } switch (this.TaskAction) { case CreateDirectoryTaskAction: this.CreateDirectory(); break; case DeleteDirectoryTaskAction: this.DeleteDirectory(); break; case DeleteFilesTaskAction: this.DeleteFiles(); break; case DownloadFilesTaskAction: this.DownloadFiles(); break; case UploadFilesTaskAction: this.UploadFiles(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid Task Action passed: {0}", this.TaskAction)); return; } } /// <summary> /// Creates a new Ftp directory on the ftp server. /// </summary> private void CreateDirectory() { if (string.IsNullOrEmpty(this.RemoteDirectoryName)) { this.Log.LogError("The required RemoteDirectoryName attribute has not been set for FTP."); return; } using (FtpConnection ftpConnection = this.CreateFtpConnection()) { ftpConnection.LogOn(); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating Directory: {0}", this.RemoteDirectoryName)); try { ftpConnection.CreateDirectory(this.RemoteDirectoryName); } catch (FtpException ex) { if (ex.Message.Contains("550")) { return; } this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error creating ftp directory: {0}. The Error Details are \"{1}\" and error code is {2} ", this.RemoteDirectoryName, ex.Message, ex.ErrorCode)); } } } /// <summary> /// Deletes an Ftp directory on the ftp server. /// </summary> private void DeleteDirectory() { if (string.IsNullOrEmpty(this.RemoteDirectoryName)) { this.Log.LogError("The required RemoteDirectoryName attribute has not been set for FTP."); return; } using (FtpConnection ftpConnection = this.CreateFtpConnection()) { ftpConnection.LogOn(); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting Directory: {0}", this.RemoteDirectoryName)); try { ftpConnection.DeleteDirectory(this.RemoteDirectoryName); } catch (FtpException ex) { if (ex.Message.Contains("550")) { return; } this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error deleting ftp directory: {0}. The Error Details are \"{1}\" and error code is {2} ", this.RemoteDirectoryName, ex.Message, ex.ErrorCode)); } } } /// <summary> /// Delete given files from the FTP Directory /// </summary> private void DeleteFiles() { if (this.FileNames == null) { this.Log.LogError("The required FileNames attribute has not been set for FTP."); return; } using (FtpConnection ftpConnection = this.CreateFtpConnection()) { ftpConnection.LogOn(); this.LogTaskMessage("Deleting Files"); if (!string.IsNullOrEmpty(this.RemoteDirectoryName)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Current Directory: {0}", this.RemoteDirectoryName)); ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName); } foreach (string fileName in this.FileNames.Select(item => item.ItemSpec)) { try { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting: {0}", fileName)); ftpConnection.DeleteFile(fileName); } catch (FtpException ex) { if (ex.Message.Contains("550")) { continue; } this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error in deleting file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode)); } } } } /// <summary> /// Upload Files /// </summary> private void UploadFiles() { if (this.FileNames == null) { this.Log.LogError("The required fileNames attribute has not been set for FTP."); return; } using (FtpConnection ftpConnection = this.CreateFtpConnection()) { this.LogTaskMessage("Uploading Files"); if (!string.IsNullOrEmpty(this.WorkingDirectory)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Local Directory: {0}", this.WorkingDirectory)); FtpConnection.SetLocalDirectory(this.WorkingDirectory); } ftpConnection.LogOn(); if (!string.IsNullOrEmpty(this.RemoteDirectoryName)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Current Directory: {0}", this.RemoteDirectoryName)); ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName); } var overwrite = true; var files = new List<FtpFileInfo>(); if (!string.IsNullOrEmpty(this.Overwrite)) { if (!bool.TryParse(this.Overwrite, out overwrite)) { overwrite = true; } } if (!overwrite) { files.AddRange(ftpConnection.GetFiles()); } foreach (string fileName in this.FileNames.Select(item => item.ItemSpec)) { try { if (File.Exists(fileName)) { if (!overwrite && files.FirstOrDefault(fi => fi.Name == fileName) != null) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Skipped: {0}", fileName)); continue; } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Uploading: {0}", fileName)); ftpConnection.PutFile(fileName); } } catch (FtpException ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error uploading file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode)); } } } } /// <summary> /// Download Files /// </summary> private void DownloadFiles() { using (FtpConnection ftpConnection = this.CreateFtpConnection()) { if (!string.IsNullOrEmpty(this.WorkingDirectory)) { if (!Directory.Exists(this.WorkingDirectory)) { Directory.CreateDirectory(this.WorkingDirectory); } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Local Directory: {0}", this.WorkingDirectory)); FtpConnection.SetLocalDirectory(this.WorkingDirectory); } ftpConnection.LogOn(); if (!string.IsNullOrEmpty(this.RemoteDirectoryName)) { ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName); } this.LogTaskMessage("Downloading Files"); if (this.FileNames == null) { FtpFileInfo[] filesToDownload = ftpConnection.GetFiles(); foreach (FtpFileInfo fileToDownload in filesToDownload) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Downloading: {0}", fileToDownload)); ftpConnection.GetFile(fileToDownload.Name, false); } } else { foreach (string fileName in this.FileNames.Select(item => item.ItemSpec.Trim())) { try { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Downloading: {0}", fileName)); ftpConnection.GetFile(fileName, false); } catch (FtpException ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error downloading file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode)); } } } } } /// <summary> /// Creates an FTP Connection object /// </summary> /// <returns>An initialised FTP Connection</returns> private FtpConnection CreateFtpConnection() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Connecting to FTP Host: {0}", this.Host)); if (!string.IsNullOrEmpty(this.UserName)) { return this.Port != 0 ? new FtpConnection(this.Host, this.Port, this.UserName, this.UserPassword) : new FtpConnection(this.Host, this.UserName, this.UserPassword); } return this.Port != 0 ? new FtpConnection(this.Host, this.Port) : new FtpConnection(this.Host); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the AprComplicacionIntraoperatorium class. /// </summary> [Serializable] public partial class AprComplicacionIntraoperatoriumCollection : ActiveList<AprComplicacionIntraoperatorium, AprComplicacionIntraoperatoriumCollection> { public AprComplicacionIntraoperatoriumCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprComplicacionIntraoperatoriumCollection</returns> public AprComplicacionIntraoperatoriumCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprComplicacionIntraoperatorium o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the APR_ComplicacionIntraoperatoria table. /// </summary> [Serializable] public partial class AprComplicacionIntraoperatorium : ActiveRecord<AprComplicacionIntraoperatorium>, IActiveRecord { #region .ctors and Default Settings public AprComplicacionIntraoperatorium() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprComplicacionIntraoperatorium(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprComplicacionIntraoperatorium(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprComplicacionIntraoperatorium(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("APR_ComplicacionIntraoperatoria", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdComplicacionIntraoperatoria = new TableSchema.TableColumn(schema); colvarIdComplicacionIntraoperatoria.ColumnName = "idComplicacionIntraoperatoria"; colvarIdComplicacionIntraoperatoria.DataType = DbType.Int32; colvarIdComplicacionIntraoperatoria.MaxLength = 0; colvarIdComplicacionIntraoperatoria.AutoIncrement = true; colvarIdComplicacionIntraoperatoria.IsNullable = false; colvarIdComplicacionIntraoperatoria.IsPrimaryKey = true; colvarIdComplicacionIntraoperatoria.IsForeignKey = false; colvarIdComplicacionIntraoperatoria.IsReadOnly = false; colvarIdComplicacionIntraoperatoria.DefaultSetting = @""; colvarIdComplicacionIntraoperatoria.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdComplicacionIntraoperatoria); TableSchema.TableColumn colvarDTipoComplicacionIntraoperatoria = new TableSchema.TableColumn(schema); colvarDTipoComplicacionIntraoperatoria.ColumnName = "dTipoComplicacionIntraoperatoria"; colvarDTipoComplicacionIntraoperatoria.DataType = DbType.Int32; colvarDTipoComplicacionIntraoperatoria.MaxLength = 0; colvarDTipoComplicacionIntraoperatoria.AutoIncrement = false; colvarDTipoComplicacionIntraoperatoria.IsNullable = false; colvarDTipoComplicacionIntraoperatoria.IsPrimaryKey = false; colvarDTipoComplicacionIntraoperatoria.IsForeignKey = false; colvarDTipoComplicacionIntraoperatoria.IsReadOnly = false; colvarDTipoComplicacionIntraoperatoria.DefaultSetting = @""; colvarDTipoComplicacionIntraoperatoria.ForeignKeyTableName = ""; schema.Columns.Add(colvarDTipoComplicacionIntraoperatoria); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_ComplicacionIntraoperatoria",schema); } } #endregion #region Props [XmlAttribute("IdComplicacionIntraoperatoria")] [Bindable(true)] public int IdComplicacionIntraoperatoria { get { return GetColumnValue<int>(Columns.IdComplicacionIntraoperatoria); } set { SetColumnValue(Columns.IdComplicacionIntraoperatoria, value); } } [XmlAttribute("DTipoComplicacionIntraoperatoria")] [Bindable(true)] public int DTipoComplicacionIntraoperatoria { get { return GetColumnValue<int>(Columns.DTipoComplicacionIntraoperatoria); } set { SetColumnValue(Columns.DTipoComplicacionIntraoperatoria, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varDTipoComplicacionIntraoperatoria,string varNombre) { AprComplicacionIntraoperatorium item = new AprComplicacionIntraoperatorium(); item.DTipoComplicacionIntraoperatoria = varDTipoComplicacionIntraoperatoria; item.Nombre = varNombre; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdComplicacionIntraoperatoria,int varDTipoComplicacionIntraoperatoria,string varNombre) { AprComplicacionIntraoperatorium item = new AprComplicacionIntraoperatorium(); item.IdComplicacionIntraoperatoria = varIdComplicacionIntraoperatoria; item.DTipoComplicacionIntraoperatoria = varDTipoComplicacionIntraoperatoria; item.Nombre = varNombre; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdComplicacionIntraoperatoriaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn DTipoComplicacionIntraoperatoriaColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdComplicacionIntraoperatoria = @"idComplicacionIntraoperatoria"; public static string DTipoComplicacionIntraoperatoria = @"dTipoComplicacionIntraoperatoria"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using RestEase.Implementation.Analysis; using RestEase.Platform; using static RestEase.Implementation.EmitEmitUtils; namespace RestEase.Implementation.Emission { internal class TypeEmitter { private readonly TypeBuilder typeBuilder; private readonly TypeModel typeModel; private readonly FieldBuilder requesterField; private readonly FieldBuilder? classHeadersField; private int numMethods; public TypeEmitter(TypeBuilder typeBuilder, TypeModel typeModel) { this.typeBuilder = typeBuilder; this.typeModel = typeModel; this.SetupType(); // Define a readonly field which holds a reference to the IRequester this.requesterField = typeBuilder.DefineField("requester", typeof(IRequester), FieldAttributes.Private | FieldAttributes.InitOnly); if (typeModel.HeaderAttributes.Count > 0) { this.classHeadersField = typeBuilder.DefineField("classHeaders", typeof(KeyValuePair<string, string>[]), FieldAttributes.Private | FieldAttributes.Static | FieldAttributes.InitOnly); } this.AddInstanceCtor(); this.AddStaticCtor(); } private void SetupType() { this.typeBuilder.AddInterfaceImplementation(this.typeModel.Type); if (this.typeModel.Type.GetTypeInfo().IsGenericTypeDefinition) { var genericTypeParameters = this.typeModel.Type.GetTypeInfo().GenericTypeParameters; var builders = this.typeBuilder.DefineGenericParameters(genericTypeParameters.Select(x => x.Name).ToArray()); AddGenericTypeConstraints(genericTypeParameters, builders); } } private void AddInstanceCtor() { // Add a constructor which takes the IRequester and assigns it to the field // public Name(IRequester requester) // { // this.requester = requester; // } var ctorBuilder = this.typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IRequester) }); var ilGenerator = ctorBuilder.GetILGenerator(); // Load 'this' and the requester onto the stack ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldarg_1); // Store the requester into this.requester ilGenerator.Emit(OpCodes.Stfld, this.requesterField); ilGenerator.Emit(OpCodes.Ret); } private void AddStaticCtor() { if (this.classHeadersField == null) return; var headers = this.typeModel.HeaderAttributes; var staticCtorBuilder = this.typeBuilder.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, ArrayUtil.Empty<Type>()); var ilGenerator = staticCtorBuilder.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldc_I4, headers.Count); ilGenerator.Emit(OpCodes.Newarr, typeof(KeyValuePair<string, string>)); for (int i = 0; i < headers.Count; i++) { ilGenerator.Emit(OpCodes.Dup); ilGenerator.Emit(OpCodes.Ldc_I4, i); ilGenerator.Emit(OpCodes.Ldstr, headers[i].Attribute.Name); // We already check that it's got a non-null value ilGenerator.Emit(OpCodes.Ldstr, headers[i].Attribute.Value!); ilGenerator.Emit(OpCodes.Newobj, MethodInfos.KeyValuePair_Ctor_String_String); ilGenerator.Emit(OpCodes.Stelem, typeof(KeyValuePair<string, string>)); } ilGenerator.Emit(OpCodes.Stsfld, this.classHeadersField); ilGenerator.Emit(OpCodes.Ret); } public EmittedProperty EmitProperty(PropertyModel propertyModel) { MethodAttributes attributes; string namePrefix = ""; string fieldName; if (propertyModel.IsExplicit) { attributes = MethodAttributes.Private | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.NewSlot | MethodAttributes.Virtual; string declaringTypeName = FriendlyNameForType(propertyModel.PropertyInfo.DeclaringType!); namePrefix = declaringTypeName + "."; fieldName = "<" + declaringTypeName + "." + propertyModel.Name + ">k__BackingField"; } else { attributes = MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.NewSlot | MethodAttributes.Virtual; fieldName = "<" + propertyModel.Name + ">k__BackingField"; } var propertyBuilder = this.typeBuilder.DefineProperty( namePrefix + propertyModel.PropertyInfo.Name, PropertyAttributes.None, propertyModel.PropertyInfo.PropertyType, null); var getter = this.typeBuilder.DefineMethod( namePrefix + propertyModel.PropertyInfo.GetMethod!.Name, attributes, propertyModel.PropertyInfo.PropertyType, ArrayUtil.Empty<Type>()); var setter = this.typeBuilder.DefineMethod( namePrefix + propertyModel.PropertyInfo.SetMethod!.Name, attributes, null, new Type[] { propertyModel.PropertyInfo.PropertyType }); if (propertyModel.IsExplicit) { this.typeBuilder.DefineMethodOverride(getter, propertyModel.PropertyInfo.GetMethod); this.typeBuilder.DefineMethodOverride(setter, propertyModel.PropertyInfo.SetMethod); } var backingField = this.typeBuilder.DefineField( fieldName, propertyModel.PropertyInfo.PropertyType, FieldAttributes.Private); var getterIlGenerator = getter.GetILGenerator(); getterIlGenerator.Emit(OpCodes.Ldarg_0); getterIlGenerator.Emit(OpCodes.Ldfld, backingField); getterIlGenerator.Emit(OpCodes.Ret); propertyBuilder.SetGetMethod(getter); var setterIlGenerator = setter.GetILGenerator(); setterIlGenerator.Emit(OpCodes.Ldarg_0); setterIlGenerator.Emit(OpCodes.Ldarg_1); setterIlGenerator.Emit(OpCodes.Stfld, backingField); setterIlGenerator.Emit(OpCodes.Ret); propertyBuilder.SetSetMethod(setter); return new EmittedProperty(propertyModel, backingField); } public void EmitRequesterProperty(PropertyModel propertyModel) { MethodAttributes attributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.SpecialName; var propertyBuilder = this.typeBuilder.DefineProperty(propertyModel.PropertyInfo.Name, PropertyAttributes.None, propertyModel.PropertyInfo.PropertyType, null); var getter = this.typeBuilder.DefineMethod(propertyModel.PropertyInfo.GetMethod!.Name, attributes, propertyModel.PropertyInfo.PropertyType, ArrayUtil.Empty<Type>()); var getterIlGenerator = getter.GetILGenerator(); getterIlGenerator.Emit(OpCodes.Ldarg_0); getterIlGenerator.Emit(OpCodes.Ldfld, this.requesterField); getterIlGenerator.Emit(OpCodes.Ret); propertyBuilder.SetGetMethod(getter); } public void EmitDisposeMethod(MethodModel methodModel) { var methodBuilder = this.typeBuilder.DefineMethod( methodModel.MethodInfo.Name, MethodAttributes.Public | MethodAttributes.Virtual, methodModel.MethodInfo.ReturnType, methodModel.Parameters.Select(x => x.ParameterInfo.ParameterType).ToArray()); this.typeBuilder.DefineMethodOverride(methodBuilder, methodModel.MethodInfo); var ilGenerator = methodBuilder.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, this.requesterField); ilGenerator.Emit(OpCodes.Callvirt, MethodInfos.IDisposable_Dispose); ilGenerator.Emit(OpCodes.Ret); } public MethodEmitter EmitMethod(MethodModel methodModel) { var methodEmitter = new MethodEmitter(this.typeBuilder, methodModel, this.numMethods, this.requesterField, this.classHeadersField); this.numMethods++; return methodEmitter; } public EmittedType Generate() { Type constructedType; try { constructedType = this.typeBuilder.CreateTypeInfo()!.AsType(); } catch (TypeLoadException e) { string msg = string.Format("Unable to create implementation for interface {0}. Ensure that the interface is public, or add [assembly: InternalsVisibleTo(RestClient.FactoryAssemblyName)] to your AssemblyInfo.cs", this.typeModel.Type.FullName); throw new ImplementationCreationException(msg, e); } return new EmittedType(constructedType); } } }
// // Key.cs // // Author: // Lluis Sanchez <[email protected]> // // 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; namespace Xwt { public enum Key { Cancel = 0xff69, BackSpace = 0xff08, Tab = 0xff09, LineFeed = 0xff0a, Clear = 0xff0b, Return = 0xff0d, Pause = 0xff13, CapsLock = 0xffe5, Escape = 0xff1b, Space = 0x20, PageUp = 0xff55, PageDown = 0xff56, End = 0xff57, Begin = 0xff58, Home = 0xff50, Left = 0xff51, Up = 0xff52, Right = 0xff53, Down = 0xff54, Select = 0xff60, Print = 0xff61, Execute = 0xff62, Delete = 0xffff, Help = 0xff6a, K0 = 0x30, K1 = 0x31, K2 = 0x32, K3 = 0x33, K4 = 0x34, K5 = 0x35, K6 = 0x36, K7 = 0x37, K8 = 0x38, K9 = 0x39, a = 0x61, b = 0x62, c = 0x63, d = 0x64, e = 0x65, f = 0x66, g = 0x67, h = 0x68, i = 0x69, j = 0x6a, k = 0x6b, l = 0x6c, m = 0x6d, n = 0x6e, o = 0x6f, p = 0x70, q = 0x71, r = 0x72, s = 0x73, t = 0x74, u = 0x75, v = 0x76, w = 0x77, x = 0x78, y = 0x79, z = 0x7a, NumPadSpace = 0xff80, NumPadTab = 0xff89, NumPadEnter = 0xff8d, NumPadF1 = 0xff91, NumPadF2 = 0xff92, NumPadF3 = 0xff93, NumPadF4 = 0xff94, NumPadHome = 0xff95, NumPadLeft = 0xff96, NumPadUp = 0xff97, NumPadRight = 0xff98, NumPadDown = 0xff99, NumPadPrior = 0xff9a, NumPadNext = 0xff9b, NumPadEnd = 0xff9c, NumPadBegin = 0xff9d, NumPadInsert = 0xff9e, NumPadDelete = 0xff9f, NumPadMultiply = 0xffaa, NumPadAdd = 0xffab, NumPadSeparator = 0xffac, NumPadSubtract = 0xffad, NumPadDecimal = 0xffae, NumPadDivide = 0xffaf, NumPad0 = 0xffb0, NumPad1 = 0xffb1, NumPad2 = 0xffb2, NumPad3 = 0xffb3, NumPad4 = 0xffb4, NumPad5 = 0xffb5, NumPad6 = 0xffb6, NumPad7 = 0xffb7, NumPad8 = 0xffb8, NumPad9 = 0xffb9, F1 = 0xffbe, F2 = 0xffbf, F3 = 0xffc0, F4 = 0xffc1, F5 = 0xffc2, F6 = 0xffc3, F7 = 0xffc4, F8 = 0xffc5, F9 = 0xffc6, F10 = 0xffc7, Insert = 0xff63, ScrollLock = 0xff14, SysReq = 0xff15, Undo = 0xff65, Redo = 0xff66, Menu = 0xff67, Find = 0xff68, Break = 0xff6b, NumLock = 0xff7f, Equal = 0xffbd, ShiftLeft = 0xffe1, ShiftRight = 0xffe2, ControlLeft = 0xffe3, ControlRight = 0xffe4, ShiftLock = 0xffe6, MetaLeft = 0xffe7, MetaRight = 0xffe8, AltLeft = 0xffe9, AltRight = 0xffea, SuperLeft = 0xffeb, SuperRight = 0xffec, HyperLeft = 0xffed, HyperRight = 0xffee, Caret = 0xfe52, Quote = 0x22, LeftBracket = 0x28, RightBracket = 0x29, Asterisk = 0x2a, Plus = 0x2b, Comma = 0x2c, Minus = 0x2d, Period = 0x2e, Slash = 0x2f, Backslash = 0x5c, Colon = 0x3a, Semicolon = 0x3b, Less = 0x3c, Greater = 0x3e, Question = 0x3f, At = 0x40, A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4a, K = 0x4b, L = 0x4c, M = 0x4d, N = 0x4e, O = 0x4f, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5a, OpenSquareBracket = 91, CloseSquareBracket = 93, Underscore = 95, Pipe = 124, SingleQuote = 39, Exclamation = 33, Hash = 35, Dollar = 36, Percent = 37, Ampersand = 38, OpenCurlyBracket = 123, CloseCurlyBracket = 125, BackQuote = 96, Tilde = 126, } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using Validation; namespace System.Collections.Immutable { /// <summary> /// A node in the AVL tree storing key/value pairs with Int32 keys. /// </summary> /// <remarks> /// This is a trimmed down version of <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> /// with <c>TKey</c> fixed to be <see cref="int"/>. This avoids multiple interface-based dispatches while examining /// each node in the tree during a lookup: an interface call to the comparer's <see cref="IComparer{T}.Compare"/> method, /// and then an interface call to <see cref="int"/>'s <see cref="IComparable{T}.CompareTo"/> method as part of /// the <see cref="T:System.Collections.Generic.GenericComparer`1"/>'s <see cref="IComparer{T}.Compare"/> implementation. /// </remarks> [DebuggerDisplay("{_key} = {_value}")] internal sealed class SortedInt32KeyNode<TValue> : IBinaryTree { /// <summary> /// The default empty node. /// </summary> internal static readonly SortedInt32KeyNode<TValue> EmptyNode = new SortedInt32KeyNode<TValue>(); /// <summary> /// The Int32 key associated with this node. /// </summary> private readonly int _key; /// <summary> /// The value associated with this node. /// </summary> /// <remarks> /// Sadly, this field could be readonly but doing so breaks serialization due to bug: /// http://connect.microsoft.com/VisualStudio/feedback/details/312970/weird-argumentexception-when-deserializing-field-in-typedreferences-cannot-be-static-or-init-only /// </remarks> private TValue _value; /// <summary> /// A value indicating whether this node has been frozen (made immutable). /// </summary> /// <remarks> /// Nodes must be frozen before ever being observed by a wrapping collection type /// to protect collections from further mutations. /// </remarks> private bool _frozen; /// <summary> /// The depth of the tree beneath this node. /// </summary> private byte _height; // AVL tree height <= ~1.44 * log2(numNodes + 2) /// <summary> /// The left tree. /// </summary> private SortedInt32KeyNode<TValue> _left; /// <summary> /// The right tree. /// </summary> private SortedInt32KeyNode<TValue> _right; /// <summary> /// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is pre-frozen. /// </summary> private SortedInt32KeyNode() { _frozen = true; // the empty node is *always* frozen. } /// <summary> /// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is not yet frozen. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <param name="frozen">Whether this node is prefrozen.</param> private SortedInt32KeyNode(int key, TValue value, SortedInt32KeyNode<TValue> left, SortedInt32KeyNode<TValue> right, bool frozen = false) { Requires.NotNull(left, "left"); Requires.NotNull(right, "right"); Debug.Assert(!frozen || (left._frozen && right._frozen)); _key = key; _value = value; _left = left; _right = right; _frozen = frozen; _height = checked((byte)(1 + Math.Max(left._height, right._height))); } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return _left == null; } } /// <summary> /// Gets the height of the tree beneath this node. /// </summary> public int Height { get { return _height; } } /// <summary> /// Gets the left branch of this node. /// </summary> public SortedInt32KeyNode<TValue> Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> public SortedInt32KeyNode<TValue> Right { get { return _right; } } /// <summary> /// Gets the left branch of this node. /// </summary> IBinaryTree IBinaryTree.Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> IBinaryTree IBinaryTree.Right { get { return _right; } } /// <summary> /// Gets the number of elements contained by this node and below. /// </summary> int IBinaryTree.Count { get { throw new NotSupportedException(); } } /// <summary> /// Gets the value represented by the current node. /// </summary> public KeyValuePair<int, TValue> Value { get { return new KeyValuePair<int, TValue>(_key, _value); } } /// <summary> /// Gets the values. /// </summary> internal IEnumerable<TValue> Values { get { foreach (var pair in this) { yield return pair.Value; } } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> internal SortedInt32KeyNode<TValue> SetItem(int key, TValue value, IEqualityComparer<TValue> valueComparer, out bool replacedExistingValue, out bool mutated) { Requires.NotNull(valueComparer, "valueComparer"); return this.SetOrAdd(key, value, valueComparer, true, out replacedExistingValue, out mutated); } /// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> internal SortedInt32KeyNode<TValue> Remove(int key, out bool mutated) { return this.RemoveRecursive(key, out mutated); } /// <summary> /// Gets the value or default. /// </summary> /// <param name="key">The key.</param> /// <returns>The value.</returns> [Pure] internal TValue GetValueOrDefault(int key) { var match = this.Search(key); return match.IsEmpty ? default(TValue) : match._value; } /// <summary> /// Tries to get the value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>True if the key was found.</returns> [Pure] internal bool TryGetValue(int key, out TValue value) { var match = this.Search(key); if (match.IsEmpty) { value = default(TValue); return false; } else { value = match._value; return true; } } /// <summary> /// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes. /// </summary> internal void Freeze(Action<KeyValuePair<int, TValue>> freezeAction = null) { // If this node is frozen, all its descendants must already be frozen. if (!_frozen) { if (freezeAction != null) { freezeAction(new KeyValuePair<int, TValue>(_key, _value)); } _left.Freeze(freezeAction); _right.Freeze(freezeAction); _frozen = true; } } /// <summary> /// AVL rotate left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> RotateLeft(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._right.IsEmpty) { return tree; } var right = tree._right; return right.Mutate(left: tree.Mutate(right: right._left)); } /// <summary> /// AVL rotate right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> RotateRight(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._left.IsEmpty) { return tree; } var left = tree._left; return left.Mutate(right: tree.Mutate(left: left._right)); } /// <summary> /// AVL rotate double-left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> DoubleLeft(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._right.IsEmpty) { return tree; } SortedInt32KeyNode<TValue> rotatedRightChild = tree.Mutate(right: RotateRight(tree._right)); return RotateLeft(rotatedRightChild); } /// <summary> /// AVL rotate double-right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> DoubleRight(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._left.IsEmpty) { return tree; } SortedInt32KeyNode<TValue> rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left)); return RotateRight(rotatedLeftChild); } /// <summary> /// Returns a value indicating whether the tree is in balance. /// </summary> /// <param name="tree">The tree.</param> /// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns> [Pure] private static int Balance(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); return tree._right._height - tree._left._height; } /// <summary> /// Determines whether the specified tree is right heavy. /// </summary> /// <param name="tree">The tree.</param> /// <returns> /// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>. /// </returns> [Pure] private static bool IsRightHeavy(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); return Balance(tree) >= 2; } /// <summary> /// Determines whether the specified tree is left heavy. /// </summary> [Pure] private static bool IsLeftHeavy(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); return Balance(tree) <= -2; } /// <summary> /// Balances the specified tree. /// </summary> /// <param name="tree">The tree.</param> /// <returns>A balanced tree.</returns> [Pure] private static SortedInt32KeyNode<TValue> MakeBalanced(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (IsRightHeavy(tree)) { return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree); } if (IsLeftHeavy(tree)) { return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree); } return tree; } /// <summary> /// Creates a node tree that contains the contents of a list. /// </summary> /// <param name="items">An indexable list with the contents that the new node tree should contain.</param> /// <param name="start">The starting index within <paramref name="items"/> that should be captured by the node tree.</param> /// <param name="length">The number of elements from <paramref name="items"/> that should be captured by the node tree.</param> /// <returns>The root of the created node tree.</returns> [Pure] private static SortedInt32KeyNode<TValue> NodeTreeFromList(IOrderedCollection<KeyValuePair<int, TValue>> items, int start, int length) { Requires.NotNull(items, "items"); Requires.Range(start >= 0, "start"); Requires.Range(length >= 0, "length"); if (length == 0) { return EmptyNode; } int rightCount = (length - 1) / 2; int leftCount = (length - 1) - rightCount; SortedInt32KeyNode<TValue> left = NodeTreeFromList(items, start, leftCount); SortedInt32KeyNode<TValue> right = NodeTreeFromList(items, start + leftCount + 1, rightCount); var item = items[start + leftCount]; return new SortedInt32KeyNode<TValue>(item.Key, item.Value, left, right, true); } /// <summary> /// Adds the specified key. Callers are expected to have validated arguments. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="overwriteExistingValue">if <c>true</c>, an existing key=value pair will be overwritten with the new one.</param> /// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> private SortedInt32KeyNode<TValue> SetOrAdd(int key, TValue value, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated) { // Arg validation skipped in this private method because it's recursive and the tax // of revalidating arguments on each recursive call is significant. // All our callers are therefore required to have done input validation. replacedExistingValue = false; if (this.IsEmpty) { mutated = true; return new SortedInt32KeyNode<TValue>(key, value, this, this); } else { SortedInt32KeyNode<TValue> result = this; if (key > _key) { var newRight = _right.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } else if (key < _key) { var newLeft = _left.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { if (valueComparer.Equals(_value, value)) { mutated = false; return this; } else if (overwriteExistingValue) { mutated = true; replacedExistingValue = true; result = new SortedInt32KeyNode<TValue>(key, value, _left, _right); } else { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key)); } } return mutated ? MakeBalanced(result) : result; } } /// <summary> /// Removes the specified key. Callers are expected to validate arguments. /// </summary> /// <param name="key">The key.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> private SortedInt32KeyNode<TValue> RemoveRecursive(int key, out bool mutated) { if (this.IsEmpty) { mutated = false; return this; } else { SortedInt32KeyNode<TValue> result = this; if (key == _key) { // We have a match. mutated = true; // If this is a leaf, just remove it // by returning Empty. If we have only one child, // replace the node with the child. if (_right.IsEmpty && _left.IsEmpty) { result = EmptyNode; } else if (_right.IsEmpty && !_left.IsEmpty) { result = _left; } else if (!_right.IsEmpty && _left.IsEmpty) { result = _right; } else { // We have two children. Remove the next-highest node and replace // this node with it. var successor = _right; while (!successor._left.IsEmpty) { successor = successor._left; } bool dummyMutated; var newRight = _right.Remove(successor._key, out dummyMutated); result = successor.Mutate(left: _left, right: newRight); } } else if (key < _key) { var newLeft = _left.Remove(key, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { var newRight = _right.Remove(key, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } return result.IsEmpty ? result : MakeBalanced(result); } } /// <summary> /// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node /// with the described changes. /// </summary> /// <param name="left">The left branch of the mutated node.</param> /// <param name="right">The right branch of the mutated node.</param> /// <returns>The mutated (or created) node.</returns> private SortedInt32KeyNode<TValue> Mutate(SortedInt32KeyNode<TValue> left = null, SortedInt32KeyNode<TValue> right = null) { if (_frozen) { return new SortedInt32KeyNode<TValue>(_key, _value, left ?? _left, right ?? _right); } else { if (left != null) { _left = left; } if (right != null) { _right = right; } _height = checked((byte)(1 + Math.Max(_left._height, _right._height))); return this; } } /// <summary> /// Searches the specified key. Callers are expected to validate arguments. /// </summary> /// <param name="key">The key.</param> [Pure] private SortedInt32KeyNode<TValue> Search(int key) { if (this.IsEmpty || key == _key) { return this; } if (key > _key) { return _right.Search(key); } return _left.Search(key); } /// <summary> /// Enumerates the contents of a binary tree. /// </summary> /// <remarks> /// This struct can and should be kept in exact sync with the other binary tree enumerators: /// <see cref="ImmutableList{T}.Enumerator"/>, <see cref="ImmutableSortedDictionary{TKey, TValue}.Enumerator"/>, and <see cref="ImmutableSortedSet{T}.Enumerator"/>. /// /// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable /// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool, /// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk /// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data /// corruption and/or exceptions. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator : IEnumerator<KeyValuePair<int, TValue>>, ISecurePooledObjectUser { /// <summary> /// The resource pool of reusable mutable stacks for purposes of enumeration. /// </summary> /// <remarks> /// We utilize this resource pool to make "allocation free" enumeration achievable. /// </remarks> private static readonly SecureObjectPool<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>, Enumerator> s_enumeratingStacks = new SecureObjectPool<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>, Enumerator>(); /// <summary> /// A unique ID for this instance of this enumerator. /// Used to protect pooled objects from use after they are recycled. /// </summary> private readonly int _poolUserId; /// <summary> /// The set being enumerated. /// </summary> private SortedInt32KeyNode<TValue> _root; /// <summary> /// The stack to use for enumerating the binary tree. /// </summary> private SecurePooledObject<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>> _stack; /// <summary> /// The node currently selected. /// </summary> private SortedInt32KeyNode<TValue> _current; /// <summary> /// Initializes an <see cref="Enumerator"/> structure. /// </summary> /// <param name="root">The root of the set to be enumerated.</param> internal Enumerator(SortedInt32KeyNode<TValue> root) { Requires.NotNull(root, "root"); _root = root; _current = null; _poolUserId = SecureObjectPool.NewId(); _stack = null; if (!_root.IsEmpty) { if (!s_enumeratingStacks.TryTake(this, out _stack)) { _stack = s_enumeratingStacks.PrepNew(this, new Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>(root.Height)); } this.PushLeft(_root); } } /// <summary> /// The current element. /// </summary> public KeyValuePair<int, TValue> Current { get { this.ThrowIfDisposed(); if (_current != null) { return _current.Value; } throw new InvalidOperationException(); } } /// <inheritdoc/> int ISecurePooledObjectUser.PoolUserId { get { return _poolUserId; } } /// <summary> /// The current element. /// </summary> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Disposes of this enumerator and returns the stack reference to the resource pool. /// </summary> public void Dispose() { _root = null; _current = null; Stack<RefAsValueType<SortedInt32KeyNode<TValue>>> stack; if (_stack != null && _stack.TryUse(ref this, out stack)) { stack.ClearFastWhenEmpty(); s_enumeratingStacks.TryAdd(this, _stack); } _stack = null; } /// <summary> /// Advances enumeration to the next element. /// </summary> /// <returns>A value indicating whether there is another element in the enumeration.</returns> public bool MoveNext() { this.ThrowIfDisposed(); if (_stack != null) { var stack = _stack.Use(ref this); if (stack.Count > 0) { SortedInt32KeyNode<TValue> n = stack.Pop().Value; _current = n; this.PushLeft(n.Right); return true; } } _current = null; return false; } /// <summary> /// Restarts enumeration. /// </summary> public void Reset() { this.ThrowIfDisposed(); _current = null; if (_stack != null) { var stack = _stack.Use(ref this); stack.ClearFastWhenEmpty(); this.PushLeft(_root); } } /// <summary> /// Throws an <see cref="ObjectDisposedException"/> if this enumerator has been disposed. /// </summary> internal void ThrowIfDisposed() { // Since this is a struct, copies might not have been marked as disposed. // But the stack we share across those copies would know. // This trick only works when we have a non-null stack. // For enumerators of empty collections, there isn't any natural // way to know when a copy of the struct has been disposed of. if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) { Validation.Requires.FailObjectDisposed(this); } } /// <summary> /// Pushes this node and all its Left descendants onto the stack. /// </summary> /// <param name="node">The starting node to push onto the stack.</param> private void PushLeft(SortedInt32KeyNode<TValue> node) { Requires.NotNull(node, "node"); var stack = _stack.Use(ref this); while (!node.IsEmpty) { stack.Push(new RefAsValueType<SortedInt32KeyNode<TValue>>(node)); node = node.Left; } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace Test { /// <summary> /// Barrier unit tests /// </summary> public class BarrierTests { /// <summary> /// Runs all the unit tests /// </summary> /// <returns>True if all tests succeeded, false if one or more tests failed</returns> [Fact] public static void RunBarrierConstructorTests() { RunBarrierTest1_ctor(10, null); RunBarrierTest1_ctor(0, null); } [Fact] public static void RunBarrierConstructorTests_NegativeTests() { RunBarrierTest1_ctor(-1, typeof(ArgumentOutOfRangeException)); RunBarrierTest1_ctor(int.MaxValue, typeof(ArgumentOutOfRangeException)); } /// <summary> /// Testing Barrier constructor /// </summary> /// <param name="initialCount">The intial barrier count</param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>Tru if the test succeeded, false otherwise</returns> private static void RunBarrierTest1_ctor(int initialCount, Type exceptionType) { Exception exception = null; try { Barrier b = new Barrier(initialCount); if (b.ParticipantCount != initialCount) { Assert.True(false, string.Format("BarrierTests: Constructor failed, ParticipantCount doesn't match the initialCount.")); } } catch (Exception ex) { exception = ex; } if (exception != null && exceptionType == null) { Assert.True(false, string.Format("BarrierTests: Constructor failed, unexpected exception has been thrown.")); } if (exception != null && !Type.Equals(exceptionType, exception.GetType())) { Assert.True(false, string.Format("BarrierTests: Constructor failed, exceptions types do not match.")); } } [Fact] public static void RunBarrierSignalAndWaitTests() { RunBarrierTest2_SignalAndWait(1, new TimeSpan(0, 0, 0, 0, -1), true, null); RunBarrierTest2_SignalAndWait(5, new TimeSpan(0, 0, 0, 0, 100), false, null); RunBarrierTest2_SignalAndWait(5, new TimeSpan(0), false, null); RunBarrierTest3_SignalAndWait(3); } [Fact] public static void RunBarrierSignalAndWaitTests_NegativeTests() { RunBarrierTest2_SignalAndWait(1, new TimeSpan(0, 0, 0, 0, -2), false, typeof(ArgumentOutOfRangeException)); } /// <summary> /// Test SignalAndWait sequential /// </summary> /// <param name="initialCount">The initial barrier participants</param> /// <param name="timeout">SignalAndWait timeout</param> /// <param name="result">Expected return value</param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>Tru if the test succeeded, false otherwise</returns> private static void RunBarrierTest2_SignalAndWait(int initialCount, TimeSpan timeout, bool result, Type exceptionType) { Barrier b = new Barrier(initialCount); Exception exception = null; try { if (b.SignalAndWait(timeout) != result) { Assert.True(false, string.Format("BarrierTests: SignalAndWait failed, return value doesn't match the expected value")); } if (result && b.CurrentPhaseNumber != 1) { Assert.True(false, string.Format("BarrierTests: SignalAndWait failed, CurrentPhaseNumber has not been incremented after SignalAndWait")); } if (result && b.ParticipantsRemaining != b.ParticipantCount) { Assert.True(false, string.Format("BarrierTests: SignalAndWait failed, ParticipantsRemaming does not equal the total participants")); } } catch (Exception ex) { exception = ex; } if (exception != null && exceptionType == null) { Assert.True(false, string.Format("BarrierTests: SignalAndWait failed, unexpected exception has been thrown.")); } if (exception != null && !Type.Equals(exceptionType, exception.GetType())) { Assert.True(false, string.Format("BarrierTests: SignalAndWait failed, exceptions types do not match.")); } } /// <summary> /// Test SignalANdWait parallel /// </summary> /// <param name="initialCount">Initial barrier count</param> /// <returns>Tru if the test succeeded, false otherwise</returns> private static void RunBarrierTest3_SignalAndWait(int initialCount) { Barrier b = new Barrier(initialCount); for (int i = 0; i < initialCount - 1; i++) { Task.Run(() => b.SignalAndWait()); } b.SignalAndWait(); if (b.CurrentPhaseNumber != 1) { Assert.True(false, string.Format("BarrierTests: SignalAndWait failed, CurrentPhaseNumber has not been incremented after SignalAndWait")); } if (b.ParticipantsRemaining != b.ParticipantCount) { Assert.True(false, string.Format("BarrierTests: SignalAndWait failed, ParticipantsRemaming does not equal the total participants")); } } [Fact] public static void RunBarrierAddParticipantsTest() { RunBarrierTest4_AddParticipants(0, 1, null); RunBarrierTest4_AddParticipants(5, 3, null); } [Fact] public static void RunBarrierAddParticipantsTest_NegativeTests() { RunBarrierTest4_AddParticipants(0, 0, typeof(ArgumentOutOfRangeException)); RunBarrierTest4_AddParticipants(2, -1, typeof(ArgumentOutOfRangeException)); RunBarrierTest4_AddParticipants(0x00007FFF, 1, typeof(ArgumentOutOfRangeException)); RunBarrierTest4_AddParticipants(100, int.MaxValue, typeof(ArgumentOutOfRangeException)); } [Fact] public static void TooManyParticipants() { Barrier b = new Barrier(Int16.MaxValue); Assert.Throws<InvalidOperationException>(() => b.AddParticipant()); } [Fact] public static void RemovingParticipants() { Barrier b; b = new Barrier(1); b.RemoveParticipant(); Assert.Throws<ArgumentOutOfRangeException>(() => b.RemoveParticipant()); b = new Barrier(1); b.RemoveParticipants(1); Assert.Throws<ArgumentOutOfRangeException>(() => b.RemoveParticipants(1)); b = new Barrier(1); Assert.Throws<ArgumentOutOfRangeException>(() => b.RemoveParticipants(2)); } /// <summary> /// Test AddParticipants /// </summary> /// <param name="initialCount">The initial barrier participants count</param> /// <param name="participantsToAdd">The aprticipants that will be added</param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>Tru if the test succeeded, false otherwise</returns> private static void RunBarrierTest4_AddParticipants(int initialCount, int participantsToAdd, Type exceptionType) { Barrier b = new Barrier(initialCount); Exception exception = null; try { if (b.AddParticipants(participantsToAdd) != 0) { Assert.True(false, string.Format("BarrierTests: AddParticipants failed, the return phase count is not correct")); } if (b.ParticipantCount != initialCount + participantsToAdd) { Assert.True(false, string.Format("BarrierTests: AddParticipants failed, total participant was not increased")); } } catch (Exception ex) { exception = ex; } if (exception != null && exceptionType == null) { Assert.True(false, string.Format("BarrierTests: AddParticipants failed, unexpected exception has been thrown.")); } if (exception != null && !Type.Equals(exceptionType, exception.GetType())) { Assert.True(false, string.Format("BarrierTests: AddParticipants failed, exceptions types do not match.")); } } [Fact] public static void RunBarrierRemoveParticipantsTests() { RunBarrierTest5_RemoveParticipants(1, 1, null); RunBarrierTest5_RemoveParticipants(10, 7, null); } [Fact] public static void RunBarrierRemoveParticipantsTests_NegativeTests() { RunBarrierTest5_RemoveParticipants(10, 0, typeof(ArgumentOutOfRangeException)); RunBarrierTest5_RemoveParticipants(1, -1, typeof(ArgumentOutOfRangeException)); RunBarrierTest5_RemoveParticipants(5, 6, typeof(ArgumentOutOfRangeException)); } /// <summary> /// Test RemoveParticipants /// </summary> /// <param name="initialCount">The initial barrier participants count</param> /// <param name="participantsToRemove">The aprticipants that will be added</param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>Tru if the test succeeded, false otherwise</returns> private static void RunBarrierTest5_RemoveParticipants(int initialCount, int participantsToRemove, Type exceptionType) { Barrier b = new Barrier(initialCount); Exception exception = null; try { b.RemoveParticipants(participantsToRemove); if (b.ParticipantCount != initialCount - participantsToRemove) { Assert.True(false, string.Format("BarrierTests: RemoveParticipants failed, total participant was not decreased")); } } catch (Exception ex) { exception = ex; } if (exception != null && exceptionType == null) { Assert.True(false, string.Format("BarrierTests: RemoveParticipants failed, unexpected exception has been thrown.")); } if (exception != null && !Type.Equals(exceptionType, exception.GetType())) { Assert.True(false, string.Format("BarrierTests: RemoveParticipants failed, exceptions types do not match.")); } } /// <summary> /// Test Dispose /// </summary> /// <returns>Tru if the test succeeded, false otherwise</returns> [Fact] public static void RunBarrierTest6_Dispose() { Barrier b = new Barrier(1); b.Dispose(); try { b.SignalAndWait(); Assert.True(false, string.Format("BarrierTests: Cancel failed, SignalAndWait didn't throw exceptions after Dispose.")); } catch (ObjectDisposedException) { } } [Fact] public static void RunBarrierTest7a() { bool failed = false; for (int j = 0; j < 100 && !failed; j++) { Barrier b = new Barrier(0); Action[] actions = new Action[4]; for (int k = 0; k < 4; k++) { actions[k] = (Action)(() => { for (int i = 0; i < 400; i++) { try { b.AddParticipant(); b.RemoveParticipant(); } catch { failed = true; break; } } }); } Task[] tasks = new Task[actions.Length]; for (int k = 0; k < tasks.Length; k++) tasks[k] = Task.Factory.StartNew((index) => actions[(int)index](), k, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); Task.WaitAll(tasks); if (b.ParticipantCount != 0) failed = true; } if (failed) { Assert.True(false, string.Format("BarrierTests: RunBarrierTest7a failed")); } } /// <summary> /// Test ithe case when the post phase action throws an exception /// </summary> /// <returns>True if the test succeeded, false otherwise</returns> [Fact] public static void RunBarrierTest8_PostPhaseException() { bool shouldThrow = true; int participants = 4; Barrier barrier = new Barrier(participants, (b) => { if (shouldThrow) throw new InvalidOperationException(); }); int succeededCount = 0; // Run threads that will expect BarrierPostPhaseException when they call SignalAndWait, and increment the count in the catch block // The BarrierPostPhaseException inner exception should be the real excption thrown by the post phase action Task[] threads = new Task[participants]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Run(() => { try { barrier.SignalAndWait(); } catch (BarrierPostPhaseException ex) { if (ex.InnerException.GetType().Equals(typeof(InvalidOperationException))) Interlocked.Increment(ref succeededCount); } }); } foreach (Task t in threads) t.Wait(); if (succeededCount != participants) { Assert.True(false, string.Format("BarrierTests: Failed, Not all participants threw the exception, expected {0}, actual {1}", participants, succeededCount)); } // make sure the phase count is incremented if (barrier.CurrentPhaseNumber != 1) { Assert.True(false, string.Format("BarrierTests: Failed, Expected phase count = 1, but did not match.")); } // turn off the exception shouldThrow = false; // Now run the threads again and they shouldn't got the exception, decrement the count if it got the exception threads = new Task[participants]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Run(() => { try { barrier.SignalAndWait(); } catch (BarrierPostPhaseException) { Interlocked.Decrement(ref succeededCount); } }); } foreach (Task t in threads) t.Wait(); if (succeededCount != participants) { Assert.True(false, string.Format("BarrierTests: Failed, At least one participant threw BarrierPostPhaseException.")); } } /// <summary> /// Test ithe case when the post phase action throws an exception /// </summary> /// <returns>Tru if the test succeeded, false otherwise</returns> [Fact] public static void RunBarrierTest9_PostPhaseException() { Barrier barrier = new Barrier(1, (b) => b.SignalAndWait()); EnsurePostPhaseThrew(barrier); barrier = new Barrier(1, (b) => b.Dispose()); EnsurePostPhaseThrew(barrier); barrier = new Barrier(1, (b) => b.AddParticipant()); EnsurePostPhaseThrew(barrier); barrier = new Barrier(1, (b) => b.RemoveParticipant()); EnsurePostPhaseThrew(barrier); } [Fact] [OuterLoop] public static void RunBarrierTest10a() { // Regression test for Barrier race condition for (int j = 0; j < 1000; j++) { Barrier b = new Barrier(2); Task[] tasks = new Task[2]; var src = new CancellationTokenSource(); for (int i = 0; i < tasks.Length; i++) { tasks[i] = Task.Run(() => { try { if (b.SignalAndWait(-1, src.Token)) src.Cancel(); } catch (OperationCanceledException) { } }); } Task.WaitAll(tasks); } } [Fact] [OuterLoop] public static void RunBarrierTest10b() { // Regression test for Barrier race condition for (int j = 0; j < 10000; j++) { Barrier b = new Barrier(2); var t1 = Task.Run(() => { b.SignalAndWait(); b.RemoveParticipant(); b.SignalAndWait(); }); var t2 = Task.Run(() => b.SignalAndWait()); Task.WaitAll(t1, t2); if (j > 0 && j % 1000 == 0) Debug.WriteLine(" > Finished {0} iterations", j); } } [Fact] [OuterLoop] public static void RunBarrierTest10c() { for (int j = 0; j < 10000; j++) { Task[] tasks = new Task[2]; Barrier b = new Barrier(3); tasks[0] = Task.Run(() => b.SignalAndWait()); tasks[1] = Task.Run(() => b.SignalAndWait()); b.SignalAndWait(); b.Dispose(); GC.Collect(); try { Task.WaitAll(tasks); } catch { Assert.True(false, string.Format("RunBarrierTest10c: Error: Only finished {0} iterations, before an exception was thrown.", j)); } } } [Fact] public static void PostPhaseException() { Exception exc = new Exception("inner"); Assert.NotNull(new BarrierPostPhaseException().Message); Assert.NotNull(new BarrierPostPhaseException((string)null).Message); Assert.Equal("test", new BarrierPostPhaseException("test").Message); Assert.NotNull(new BarrierPostPhaseException(exc).Message); Assert.Same(exc, new BarrierPostPhaseException(exc).InnerException); Assert.Equal("test", new BarrierPostPhaseException("test", exc).Message); Assert.Same(exc, new BarrierPostPhaseException("test", exc).InnerException); } #region Helper Methods /// <summary> /// Ensures the post phase action throws if Dispose,SignalAndWait and Add/Remove participants called from it. /// </summary> private static void EnsurePostPhaseThrew(Barrier barrier) { try { barrier.SignalAndWait(); Assert.True(false, string.Format("BarrierTests: PostPhaseException failed, Postphase action didn't throw.")); } catch (BarrierPostPhaseException ex) { if (!ex.InnerException.GetType().Equals(typeof(InvalidOperationException))) { Assert.True(false, string.Format("BarrierTests: PostPhaseException failed, Postphase action didn't throw the correct exception.")); } } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq.Expressions; using System.Reflection; using Lucene.Net.Expressions.JS; using Lucene.Net.Support; using NUnit.Framework; namespace Lucene.Net.Tests.Expressions.JS { [TestFixture] public class TestCustomFunctions : Util.LuceneTestCase { private static double DELTA = 0.0000001; /// <summary>empty list of methods</summary> [Test] public virtual void TestEmpty() { IDictionary<string, MethodInfo> functions = new HashMap<string,MethodInfo>(); try { JavascriptCompiler.Compile("sqrt(20)", functions); Fail(); } catch (ArgumentException e) { IsTrue(e.Message.Contains("Unrecognized method")); } } /// <summary>using the default map explicitly</summary> [Test] public virtual void TestDefaultList() { IDictionary<string, MethodInfo> functions = JavascriptCompiler.DEFAULT_FUNCTIONS; var expr = JavascriptCompiler.Compile("sqrt(20)", functions); AreEqual(Math.Sqrt(20), expr.Evaluate(0, null), DELTA); } public static double ZeroArgMethod() { return 5; } /// <summary>tests a method with no arguments</summary> [Test] public virtual void TestNoArgMethod() { IDictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>(); functions["foo"] = GetType().GetMethod("ZeroArgMethod"); var expr = JavascriptCompiler.Compile("foo()", functions); AreEqual(5, expr.Evaluate(0, null), DELTA); } public static double OneArgMethod(double arg1) { return 3 + arg1; } /// <summary>tests a method with one arguments</summary> [Test] public virtual void TestOneArgMethod() { IDictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>(); functions["foo"] = GetType().GetMethod("OneArgMethod", new []{ typeof(double)}); var expr = JavascriptCompiler.Compile("foo(3)", functions); AreEqual(6, expr.Evaluate(0, null), DELTA); } public static double ThreeArgMethod(double arg1, double arg2, double arg3) { return arg1 + arg2 + arg3; } /// <summary>tests a method with three arguments</summary> [Test] public virtual void TestThreeArgMethod() { IDictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>(); functions["foo"] = GetType().GetMethod("ThreeArgMethod", new []{ typeof(double), typeof( double), typeof(double)}); var expr = JavascriptCompiler.Compile("foo(3, 4, 5)", functions); AreEqual(12, expr.Evaluate(0, null), DELTA); } /// <summary>tests a map with 2 functions</summary> [Test] public virtual void TestTwoMethods() { IDictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>(); functions["foo"] = GetType().GetMethod("ZeroArgMethod"); functions["bar"] = GetType().GetMethod("OneArgMethod", new []{typeof(double)}); var expr = JavascriptCompiler.Compile("foo() + bar(3)", functions); AreEqual(11, expr.Evaluate(0, null), DELTA); } public static string BogusReturnType() { return "bogus!"; } /// <summary>wrong return type: must be double</summary> [Test] public virtual void TestWrongReturnType() { IDictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>(); functions["foo"] = GetType().GetMethod("BogusReturnType"); try { JavascriptCompiler.Compile("foo()", functions); Fail(); } catch (ArgumentException e) { IsTrue(e.Message.Contains("does not return a double")); } } public static double BogusParameterType(string s) { return 0; } /// <summary>wrong param type: must be doubles</summary> [Test] public virtual void TestWrongParameterType() { IDictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>(); functions["foo"] = GetType().GetMethod("BogusParameterType", new []{ typeof(string)}); try { JavascriptCompiler.Compile("foo(2)", functions); Fail(); } catch (ArgumentException e) { IsTrue(e.Message.Contains("must take only double parameters" )); } } public virtual double NonStaticMethod() { return 0; } /// <summary>wrong modifiers: must be static</summary> [Test] public virtual void TestWrongNotStatic() { IDictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>(); functions["foo"] = GetType().GetMethod("NonStaticMethod"); try { JavascriptCompiler.Compile("foo()", functions); Fail(); } catch (ArgumentException e) { IsTrue(e.Message.Contains("is not static")); } } internal static double NonPublicMethod() { return 0; } /// <summary>wrong modifiers: must be public</summary> [Test] public virtual void TestWrongNotPublic() { IDictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>(); functions["foo"] = GetType().GetMethod("NonPublicMethod",BindingFlags.NonPublic|BindingFlags.Static); try { JavascriptCompiler.Compile("foo()", functions); Fail(); } catch (ArgumentException e) { IsTrue(e.Message.Contains("is not public")); } } internal class NestedNotPublic { public static double Method() { return 0; } } /// <summary>wrong class modifiers: class containing method is not public</summary> [Test] public virtual void TestWrongNestedNotPublic() { IDictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>(); functions["foo"] = typeof(NestedNotPublic).GetMethod("Method"); try { JavascriptCompiler.Compile("foo()", functions); Fail(); } catch (ArgumentException e) { IsTrue(e.Message.Contains("is not public")); } } internal static string MESSAGE = "This should not happen but it happens"; public class StaticThrowingException { public static double Method() { throw new ArithmeticException(MESSAGE); } } /// <summary>the method throws an exception.</summary> /// <remarks>the method throws an exception. We should check the stack trace that it contains the source code of the expression as file name. /// </remarks> [Test] public virtual void TestThrowingException() { IDictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>(); functions["foo"] = typeof(StaticThrowingException).GetMethod("Method"); string source = "3 * foo() / 5"; var expr = JavascriptCompiler.Compile(source, functions); try { expr.Evaluate(0, null); Fail(); } catch (ArithmeticException e) { AreEqual(MESSAGE, e.Message); StringWriter sw = new StringWriter(); e.printStackTrace(); //.NET Port IsTrue(e.StackTrace.Contains("Lucene.Net.Expressions.CompiledExpression.Evaluate(Int32 , FunctionValues[] )")); } } /// <summary>test that namespaces work with custom expressions.</summary> /// <remarks>test that namespaces work with custom expressions.</remarks> [Test] public virtual void TestNamespaces() { IDictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>(); functions["foo.bar"] = GetType().GetMethod("ZeroArgMethod"); string source = "foo.bar()"; var expr = JavascriptCompiler.Compile(source, functions); AreEqual(5, expr.Evaluate(0, null), DELTA); } } }
// 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.Reflection; using System.Globalization; using System.Threading; using System.Diagnostics; using System.Collections; using System.Runtime.CompilerServices; using System.Security; using System.Text; using System.Runtime.InteropServices; using System.Configuration.Assemblies; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System.Reflection { internal enum CorElementType : byte { End = 0x00, Void = 0x01, Boolean = 0x02, Char = 0x03, I1 = 0x04, U1 = 0x05, I2 = 0x06, U2 = 0x07, I4 = 0x08, U4 = 0x09, I8 = 0x0A, U8 = 0x0B, R4 = 0x0C, R8 = 0x0D, String = 0x0E, Ptr = 0x0F, ByRef = 0x10, ValueType = 0x11, Class = 0x12, Var = 0x13, Array = 0x14, GenericInst = 0x15, TypedByRef = 0x16, I = 0x18, U = 0x19, FnPtr = 0x1B, Object = 0x1C, SzArray = 0x1D, MVar = 0x1E, CModReqd = 0x1F, CModOpt = 0x20, Internal = 0x21, Max = 0x22, Modifier = 0x40, Sentinel = 0x41, Pinned = 0x45, } [Flags()] internal enum MdSigCallingConvention : byte { CallConvMask = 0x0f, // Calling convention is bottom 4 bits Default = 0x00, C = 0x01, StdCall = 0x02, ThisCall = 0x03, FastCall = 0x04, Vararg = 0x05, Field = 0x06, LocalSig = 0x07, Property = 0x08, Unmgd = 0x09, GenericInst = 0x0a, // generic method instantiation Generic = 0x10, // Generic method sig with explicit number of type arguments (precedes ordinary parameter count) HasThis = 0x20, // Top bit indicates a 'this' parameter ExplicitThis = 0x40, // This parameter is explicitly in the signature } [Flags()] internal enum PInvokeAttributes { NoMangle = 0x0001, CharSetMask = 0x0006, CharSetNotSpec = 0x0000, CharSetAnsi = 0x0002, CharSetUnicode = 0x0004, CharSetAuto = 0x0006, BestFitUseAssem = 0x0000, BestFitEnabled = 0x0010, BestFitDisabled = 0x0020, BestFitMask = 0x0030, ThrowOnUnmappableCharUseAssem = 0x0000, ThrowOnUnmappableCharEnabled = 0x1000, ThrowOnUnmappableCharDisabled = 0x2000, ThrowOnUnmappableCharMask = 0x3000, SupportsLastError = 0x0040, CallConvMask = 0x0700, CallConvWinapi = 0x0100, CallConvCdecl = 0x0200, CallConvStdcall = 0x0300, CallConvThiscall = 0x0400, CallConvFastcall = 0x0500, MaxValue = 0xFFFF, } [Flags()] internal enum MethodSemanticsAttributes { Setter = 0x0001, Getter = 0x0002, Other = 0x0004, AddOn = 0x0008, RemoveOn = 0x0010, Fire = 0x0020, } internal enum MetadataTokenType { Module = 0x00000000, TypeRef = 0x01000000, TypeDef = 0x02000000, FieldDef = 0x04000000, MethodDef = 0x06000000, ParamDef = 0x08000000, InterfaceImpl = 0x09000000, MemberRef = 0x0a000000, CustomAttribute = 0x0c000000, Permission = 0x0e000000, Signature = 0x11000000, Event = 0x14000000, Property = 0x17000000, ModuleRef = 0x1a000000, TypeSpec = 0x1b000000, Assembly = 0x20000000, AssemblyRef = 0x23000000, File = 0x26000000, ExportedType = 0x27000000, ManifestResource = 0x28000000, GenericPar = 0x2a000000, MethodSpec = 0x2b000000, String = 0x70000000, Name = 0x71000000, BaseType = 0x72000000, Invalid = 0x7FFFFFFF, } internal struct ConstArray { public IntPtr Signature { get { return m_constArray; } } public int Length { get { return m_length; } } public byte this[int index] { get { if (index < 0 || index >= m_length) throw new IndexOutOfRangeException(); Contract.EndContractBlock(); unsafe { return ((byte*)m_constArray.ToPointer())[index]; } } } // Keep the definition in sync with vm\ManagedMdImport.hpp internal int m_length; internal IntPtr m_constArray; } internal struct MetadataToken { #region Implicit Cast Operators public static implicit operator int(MetadataToken token) { return token.Value; } public static implicit operator MetadataToken(int token) { return new MetadataToken(token); } #endregion #region Public Static Members public static bool IsTokenOfType(int token, params MetadataTokenType[] types) { for (int i = 0; i < types.Length; i++) { if ((int)(token & 0xFF000000) == (int)types[i]) return true; } return false; } public static bool IsNullToken(int token) { return (token & 0x00FFFFFF) == 0; } #endregion #region Public Data Members public int Value; #endregion #region Constructor public MetadataToken(int token) { Value = token; } #endregion #region Public Members public bool IsGlobalTypeDefToken { get { return (Value == 0x02000001); } } public MetadataTokenType TokenType { get { return (MetadataTokenType)(Value & 0xFF000000); } } public bool IsTypeRef { get { return TokenType == MetadataTokenType.TypeRef; } } public bool IsTypeDef { get { return TokenType == MetadataTokenType.TypeDef; } } public bool IsFieldDef { get { return TokenType == MetadataTokenType.FieldDef; } } public bool IsMethodDef { get { return TokenType == MetadataTokenType.MethodDef; } } public bool IsMemberRef { get { return TokenType == MetadataTokenType.MemberRef; } } public bool IsEvent { get { return TokenType == MetadataTokenType.Event; } } public bool IsProperty { get { return TokenType == MetadataTokenType.Property; } } public bool IsParamDef { get { return TokenType == MetadataTokenType.ParamDef; } } public bool IsTypeSpec { get { return TokenType == MetadataTokenType.TypeSpec; } } public bool IsMethodSpec { get { return TokenType == MetadataTokenType.MethodSpec; } } public bool IsString { get { return TokenType == MetadataTokenType.String; } } public bool IsSignature { get { return TokenType == MetadataTokenType.Signature; } } public bool IsModule { get { return TokenType == MetadataTokenType.Module; } } public bool IsAssembly { get { return TokenType == MetadataTokenType.Assembly; } } public bool IsGenericPar { get { return TokenType == MetadataTokenType.GenericPar; } } #endregion #region Object Overrides public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "0x{0:x8}", Value); } #endregion } internal unsafe struct MetadataEnumResult { // Keep the definition in sync with vm\ManagedMdImport.hpp private int[] largeResult; private int length; private fixed int smallResult[16]; public int Length { get { return length; } } public int this[int index] { get { Contract.Requires(0 <= index && index < Length); if (largeResult != null) return largeResult[index]; fixed (int* p = smallResult) return p[index]; } } } internal struct MetadataImport { #region Private Data Members private IntPtr m_metadataImport2; private object m_keepalive; #endregion #region Override methods from Object internal static readonly MetadataImport EmptyImport = new MetadataImport((IntPtr)0, null); public override int GetHashCode() { return ValueType.GetHashCodeOfPtr(m_metadataImport2); } public override bool Equals(object obj) { if (!(obj is MetadataImport)) return false; return Equals((MetadataImport)obj); } private bool Equals(MetadataImport import) { return import.m_metadataImport2 == m_metadataImport2; } #endregion #region Static Members [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string safeArrayUserDefinedSubType, out int arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie, out int iidParamIndex); internal static void GetMarshalAs(ConstArray nativeType, out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedSubType, out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie, out int iidParamIndex) { int _unmanagedType, _safeArraySubType, _arraySubType; _GetMarshalAs(nativeType.Signature, (int)nativeType.Length, out _unmanagedType, out _safeArraySubType, out safeArrayUserDefinedSubType, out _arraySubType, out sizeParamIndex, out sizeConst, out marshalType, out marshalCookie, out iidParamIndex); unmanagedType = (UnmanagedType)_unmanagedType; safeArraySubType = (VarEnum)_safeArraySubType; arraySubType = (UnmanagedType)_arraySubType; } #endregion #region Internal Static Members internal static void ThrowError(int hResult) { throw new MetadataException(hResult); } #endregion #region Constructor internal MetadataImport(IntPtr metadataImport2, object keepalive) { m_metadataImport2 = metadataImport2; m_keepalive = keepalive; } #endregion #region FCalls [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern void _Enum(IntPtr scope, int type, int parent, out MetadataEnumResult result); public unsafe void Enum(MetadataTokenType type, int parent, out MetadataEnumResult result) { _Enum(m_metadataImport2, (int)type, parent, out result); } public unsafe void EnumNestedTypes(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.TypeDef, mdTypeDef, out result); } public unsafe void EnumCustomAttributes(int mdToken, out MetadataEnumResult result) { Enum(MetadataTokenType.CustomAttribute, mdToken, out result); } public unsafe void EnumParams(int mdMethodDef, out MetadataEnumResult result) { Enum(MetadataTokenType.ParamDef, mdMethodDef, out result); } public unsafe void EnumFields(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.FieldDef, mdTypeDef, out result); } public unsafe void EnumProperties(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.Property, mdTypeDef, out result); } public unsafe void EnumEvents(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.Event, mdTypeDef, out result); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern String _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType); public String GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType) { int _corElementType; String stringVal; stringVal = _GetDefaultValue(m_metadataImport2, mdToken, out value, out length, out _corElementType); corElementType = (CorElementType)_corElementType; return stringVal; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern void _GetUserString(IntPtr scope, int mdToken, void** name, out int length); public unsafe String GetUserString(int mdToken) { void* name; int length; _GetUserString(m_metadataImport2, mdToken, &name, out length); if (name == null) return null; char[] c = new char[length]; for (int i = 0; i < c.Length; i++) { #if ALIGN_ACCESS c[i] = (char)Marshal.ReadInt16( (IntPtr) (((char*)name) + i) ); #else c[i] = ((char*)name)[i]; #endif } return new String(c); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern void _GetName(IntPtr scope, int mdToken, void** name); public unsafe Utf8String GetName(int mdToken) { void* name; _GetName(m_metadataImport2, mdToken, &name); return new Utf8String(name); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern void _GetNamespace(IntPtr scope, int mdToken, void** namesp); public unsafe Utf8String GetNamespace(int mdToken) { void* namesp; _GetNamespace(m_metadataImport2, mdToken, &namesp); return new Utf8String(namesp); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern void _GetEventProps(IntPtr scope, int mdToken, void** name, out int eventAttributes); public unsafe void GetEventProps(int mdToken, out void* name, out EventAttributes eventAttributes) { int _eventAttributes; void* _name; _GetEventProps(m_metadataImport2, mdToken, &_name, out _eventAttributes); name = _name; eventAttributes = (EventAttributes)_eventAttributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetFieldDefProps(IntPtr scope, int mdToken, out int fieldAttributes); public void GetFieldDefProps(int mdToken, out FieldAttributes fieldAttributes) { int _fieldAttributes; _GetFieldDefProps(m_metadataImport2, mdToken, out _fieldAttributes); fieldAttributes = (FieldAttributes)_fieldAttributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern void _GetPropertyProps(IntPtr scope, int mdToken, void** name, out int propertyAttributes, out ConstArray signature); public unsafe void GetPropertyProps(int mdToken, out void* name, out PropertyAttributes propertyAttributes, out ConstArray signature) { int _propertyAttributes; void* _name; _GetPropertyProps(m_metadataImport2, mdToken, &_name, out _propertyAttributes, out signature); name = _name; propertyAttributes = (PropertyAttributes)_propertyAttributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetParentToken(IntPtr scope, int mdToken, out int tkParent); public int GetParentToken(int tkToken) { int tkParent; _GetParentToken(m_metadataImport2, tkToken, out tkParent); return tkParent; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetParamDefProps(IntPtr scope, int parameterToken, out int sequence, out int attributes); public void GetParamDefProps(int parameterToken, out int sequence, out ParameterAttributes attributes) { int _attributes; _GetParamDefProps(m_metadataImport2, parameterToken, out sequence, out _attributes); attributes = (ParameterAttributes)_attributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetGenericParamProps(IntPtr scope, int genericParameter, out int flags); public void GetGenericParamProps( int genericParameter, out GenericParameterAttributes attributes) { int _attributes; _GetGenericParamProps(m_metadataImport2, genericParameter, out _attributes); attributes = (GenericParameterAttributes)_attributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetScopeProps(IntPtr scope, out Guid mvid); public void GetScopeProps( out Guid mvid) { _GetScopeProps(m_metadataImport2, out mvid); } public ConstArray GetMethodSignature(MetadataToken token) { if (token.IsMemberRef) return GetMemberRefProps(token); return GetSigOfMethodDef(token); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetSigOfMethodDef(IntPtr scope, int methodToken, ref ConstArray signature); public ConstArray GetSigOfMethodDef(int methodToken) { ConstArray signature = new ConstArray(); _GetSigOfMethodDef(m_metadataImport2, methodToken, ref signature); return signature; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetSignatureFromToken(IntPtr scope, int methodToken, ref ConstArray signature); public ConstArray GetSignatureFromToken(int token) { ConstArray signature = new ConstArray(); _GetSignatureFromToken(m_metadataImport2, token, ref signature); return signature; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetMemberRefProps(IntPtr scope, int memberTokenRef, out ConstArray signature); public ConstArray GetMemberRefProps(int memberTokenRef) { ConstArray signature = new ConstArray(); _GetMemberRefProps(m_metadataImport2, memberTokenRef, out signature); return signature; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetCustomAttributeProps(IntPtr scope, int customAttributeToken, out int constructorToken, out ConstArray signature); public void GetCustomAttributeProps( int customAttributeToken, out int constructorToken, out ConstArray signature) { _GetCustomAttributeProps(m_metadataImport2, customAttributeToken, out constructorToken, out signature); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetClassLayout(IntPtr scope, int typeTokenDef, out int packSize, out int classSize); public void GetClassLayout( int typeTokenDef, out int packSize, out int classSize) { _GetClassLayout(m_metadataImport2, typeTokenDef, out packSize, out classSize); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool _GetFieldOffset(IntPtr scope, int typeTokenDef, int fieldTokenDef, out int offset); public bool GetFieldOffset( int typeTokenDef, int fieldTokenDef, out int offset) { return _GetFieldOffset(m_metadataImport2, typeTokenDef, fieldTokenDef, out offset); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetSigOfFieldDef(IntPtr scope, int fieldToken, ref ConstArray fieldMarshal); public ConstArray GetSigOfFieldDef(int fieldToken) { ConstArray fieldMarshal = new ConstArray(); _GetSigOfFieldDef(m_metadataImport2, fieldToken, ref fieldMarshal); return fieldMarshal; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetFieldMarshal(IntPtr scope, int fieldToken, ref ConstArray fieldMarshal); public ConstArray GetFieldMarshal(int fieldToken) { ConstArray fieldMarshal = new ConstArray(); _GetFieldMarshal(m_metadataImport2, fieldToken, ref fieldMarshal); return fieldMarshal; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern void _GetPInvokeMap(IntPtr scope, int token, out int attributes, void** importName, void** importDll); public unsafe void GetPInvokeMap( int token, out PInvokeAttributes attributes, out String importName, out String importDll) { int _attributes; void* _importName, _importDll; _GetPInvokeMap(m_metadataImport2, token, out _attributes, &_importName, &_importDll); importName = new Utf8String(_importName).ToString(); importDll = new Utf8String(_importDll).ToString(); attributes = (PInvokeAttributes)_attributes; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool _IsValidToken(IntPtr scope, int token); public bool IsValidToken(int token) { return _IsValidToken(m_metadataImport2, token); } #endregion } internal class MetadataException : Exception { private int m_hr; internal MetadataException(int hr) { m_hr = hr; } public override string ToString() { return String.Format(CultureInfo.CurrentCulture, "MetadataException HResult = {0:x}.", m_hr); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests { private static DiagnosticResult GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleXmlDocumentWithNoSecureResolver).WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleXmlDocumentWithNoSecureResolver).WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs [Fact] public async Task XmlDocumentSetResolverToNullShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); doc.XmlResolver = null; } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() doc.XmlResolver = Nothing End Sub End Class End Namespace " ); } [Fact] public async Task XmlDocumentSetResolverToNullInInitializerShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument() { XmlResolver = null }; } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() With { _ .XmlResolver = Nothing _ } End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentAsFieldSetResolverToNullInInitializerShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument() { XmlResolver = null }; } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() With { _ .XmlResolver = Nothing _ } End Class End Namespace" ); } [Fact] public async Task XmlDocumentAsFieldSetInsecureResolverInInitializerShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument() { XmlResolver = new XmlUrlResolver() }; } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 54) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() With { _ .XmlResolver = New XmlUrlResolver() _ } End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(7, 13) ); } [Fact] public async Task XmlDocumentAsFieldNoResolverPre452ShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37) ); } [Fact] public async Task XmlDocumentAsFieldNoResolverPost452ShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() End Class End Namespace" ); } [Fact] public async Task XmlDocumentUseSecureResolverShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlSecureResolver resolver) { XmlDocument doc = new XmlDocument(); doc.XmlResolver = resolver; } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(resolver As XmlSecureResolver) Dim doc As New XmlDocument() doc.XmlResolver = resolver End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentSetSecureResolverInInitializerShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlSecureResolver resolver) { XmlDocument doc = new XmlDocument() { XmlResolver = resolver }; } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(resolver As XmlSecureResolver) Dim doc As New XmlDocument() With { _ .XmlResolver = resolver _ } End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentUseSecureResolverWithPermissionsShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Net; using System.Security; using System.Security.Permissions; using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { PermissionSet myPermissions = new PermissionSet(PermissionState.None); WebPermission permission = new WebPermission(PermissionState.None); permission.AddPermission(NetworkAccess.Connect, ""http://www.contoso.com/""); permission.AddPermission(NetworkAccess.Connect, ""http://litwareinc.com/data/""); myPermissions.SetPermission(permission); XmlSecureResolver resolver = new XmlSecureResolver(new XmlUrlResolver(), myPermissions); XmlDocument doc = new XmlDocument(); doc.XmlResolver = resolver; } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Net Imports System.Security Imports System.Security.Permissions Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim myPermissions As New PermissionSet(PermissionState.None) Dim permission As New WebPermission(PermissionState.None) permission.AddPermission(NetworkAccess.Connect, ""http://www.contoso.com/"") permission.AddPermission(NetworkAccess.Connect, ""http://litwareinc.com/data/"") myPermissions.SetPermission(permission) Dim resolver As New XmlSecureResolver(New XmlUrlResolver(), myPermissions) Dim doc As New XmlDocument() doc.XmlResolver = resolver End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentSetResolverToNullInTryClauseShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); try { doc.XmlResolver = null; } catch { throw; } } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() Try doc.XmlResolver = Nothing Catch Throw End Try End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentNoResolverPre452ShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(10, 31) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(7, 24) ); } [Fact] public async Task XmlDocumentNoResolverPost452ShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentUseNonSecureResolverShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); doc.XmlResolver = new XmlUrlResolver(); // warn } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() doc.XmlResolver = New XmlUrlResolver() ' warn End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(8, 13) ); } [Fact] public async Task XmlDocumentUseNonSecureResolverInTryClauseShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); try { doc.XmlResolver = new XmlUrlResolver(); // warn } catch { throw; } } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(13, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() Try ' warn doc.XmlResolver = New XmlUrlResolver() Catch Throw End Try End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(10, 17) ); } [Fact] public async Task XmlDocumentReassignmentSetResolverToNullInInitializerShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); doc = new XmlDocument() { XmlResolver = null }; } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() doc = New XmlDocument() With { _ .XmlResolver = Nothing _ } End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentReassignmentDefaultTargetPre452ShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument() { XmlResolver = null }; doc = new XmlDocument(); // warn } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(14, 19) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() With { _ .XmlResolver = Nothing _ } doc = New XmlDocument() ' warn End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(10, 19) ); } [Fact] public async Task XmlDocumentReassignmentDefaultTargetPost452ShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument() { XmlResolver = null }; doc = new XmlDocument(); // ok } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() With { _ .XmlResolver = Nothing _ } doc = New XmlDocument() End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentSetResolversInDifferentBlockPre452ShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { { XmlDocument doc = new XmlDocument(); //warn } { XmlDocument doc = new XmlDocument(); doc.XmlResolver = null; } } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(11, 35) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() If True Then Dim doc As New XmlDocument() End If If True Then Dim doc As New XmlDocument() doc.XmlResolver = Nothing End If End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(8, 28) ); } [Fact] public async Task XmlDocumentSetResolversInDifferentBlockPost452ShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { { XmlDocument doc = new XmlDocument(); //ok in 4.5.2 } { XmlDocument doc = new XmlDocument(); doc.XmlResolver = null; } } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() If True Then Dim doc As New XmlDocument() End If If True Then Dim doc As New XmlDocument() doc.XmlResolver = Nothing End If End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentAsFieldSetResolverToInsecureResolverInOnlyMethodPre452ShouldGenerateDiagnosticsAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); public void Method1() { this.doc.XmlResolver = new XmlUrlResolver(); } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34), GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(12, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() ' warn Public Sub Method1() Me.doc.XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37), GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(9, 13) ); } [Fact] public async Task XmlDocumentAsFieldSetResolverToInsecureResolverInOnlyMethodPost452ShouldGenerateDiagnosticsAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); // ok public void Method1() { this.doc.XmlResolver = new XmlUrlResolver(); // warn } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(12, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() ' ok Public Sub Method1() Me.doc.XmlResolver = New XmlUrlResolver() ' warn End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(9, 13) ); } [Fact] public async Task XmlDocumentAsFieldSetResolverToInsecureResolverInSomeMethodPre452ShouldGenerateDiagnosticsAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); // warn public void Method1() { this.doc.XmlResolver = null; } public void Method2() { this.doc.XmlResolver = new XmlUrlResolver(); // warn } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34), GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(17, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() ' warn Public Sub Method1() Me.doc.XmlResolver = Nothing End Sub Public Sub Method2() Me.doc.XmlResolver = New XmlUrlResolver() ' warn End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37), GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(13, 13) ); } [Fact] public async Task XmlDocumentAsFieldSetResolverToNullInSomeMethodPre452ShouldGenerateDiagnosticsAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); // warn public void Method1() { this.doc.XmlResolver = null; } public void Method2(XmlReader reader) { this.doc.Load(reader); } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() Public Sub Method1() Me.doc.XmlResolver = Nothing End Sub Public Sub Method2(reader As XmlReader) Me.doc.Load(reader) End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37) ); } [Fact] public async Task XmlDocumentAsFieldSetResolverToInsecureResolverInSomeMethodPost452ShouldGenerateDiagnosticsAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); // ok public void Method1() { this.doc.XmlResolver = null; } public void Method2() { this.doc.XmlResolver = new XmlUrlResolver(); // warn } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(17, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() ' ok Public Sub Method1() Me.doc.XmlResolver = Nothing End Sub Public Sub Method2() Me.doc.XmlResolver = New XmlUrlResolver() ' warn End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(13, 25) ); } [Fact] public async Task XmlDocumentAsFieldSetResolverToNullInSomeMethodPost452ShouldNotGenerateDiagnosticsAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); public void Method1() { this.doc.XmlResolver = null; } public void Method2(XmlReader reader) { this.doc.Load(reader); } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() Public Sub Method1() Me.doc.XmlResolver = Nothing End Sub Public Sub Method2(reader As XmlReader) Me.doc.Load(reader) End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentCreatedAsTempNotSetResolverPre452ShouldGenerateDiagnosticsAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public void Method1() { Method2(new XmlDocument()); } public void Method2(XmlDocument doc){} } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(11, 21) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net451.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public Sub Method1() Method2(New XmlDocument()) End Sub Public Sub Method2(doc As XmlDocument) End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(8, 21) ); } [Fact] public async Task XmlDocumentCreatedAsTempNotSetResolverPost452ShouldNotGenerateDiagnosticsAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public void Method1() { Method2(new XmlDocument()); } public void Method2(XmlDocument doc){} } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net452.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public Sub Method1() Method2(New XmlDocument()) End Sub Public Sub Method2(doc As XmlDocument) End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentDerivedTypeNotSetResolverShouldNotGenerateDiagnosticsAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass1 : XmlDocument { public TestClass1() { XmlResolver = null; } } class TestClass2 { void TestMethod() { var c = new TestClass1(); } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass1 Inherits XmlDocument Public Sub New() XmlResolver = Nothing End Sub End Class Class TestClass2 Private Sub TestMethod() Dim c = New TestClass1() End Sub End Class End Namespace " ); } [Fact] public async Task XmlDocumentDerivedTypeWithNoSecureResolverShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Xml; namespace TestNamespace { class DerivedType : XmlDocument {} class TestClass { void TestMethod() { var c = new DerivedType(); } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class DerivedType Inherits XmlDocument End Class Class TestClass Private Sub TestMethod() Dim c = New DerivedType() End Sub End Class End Namespace" ); } } }
namespace java.lang.reflect { [global::MonoJavaBridge.JavaClass()] public sealed partial class Method : java.lang.reflect.AccessibleObject, GenericDeclaration, Member { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Method() { InitJNI(); } internal Method(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _invoke13490; public global::java.lang.Object invoke(java.lang.Object arg0, java.lang.Object[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._invoke13490, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._invoke13490, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _equals13491; public sealed override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.reflect.Method._equals13491, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._equals13491, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString13492; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._toString13492)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._toString13492)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode13493; public sealed override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.reflect.Method._hashCode13493); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._hashCode13493); } internal static global::MonoJavaBridge.MethodId _getModifiers13494; public int getModifiers() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.reflect.Method._getModifiers13494); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getModifiers13494); } internal static global::MonoJavaBridge.MethodId _getName13495; public global::java.lang.String getName() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getName13495)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getName13495)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _isSynthetic13496; public bool isSynthetic() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.reflect.Method._isSynthetic13496); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._isSynthetic13496); } internal static global::MonoJavaBridge.MethodId _getTypeParameters13497; public global::java.lang.reflect.TypeVariable[] getTypeParameters() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.reflect.TypeVariable>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getTypeParameters13497)) as java.lang.reflect.TypeVariable[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.reflect.TypeVariable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getTypeParameters13497)) as java.lang.reflect.TypeVariable[]; } internal static global::MonoJavaBridge.MethodId _getDeclaringClass13498; public global::java.lang.Class getDeclaringClass() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getDeclaringClass13498)) as java.lang.Class; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getDeclaringClass13498)) as java.lang.Class; } internal static global::MonoJavaBridge.MethodId _getAnnotation13499; public sealed override global::java.lang.annotation.Annotation getAnnotation(java.lang.Class arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.annotation.Annotation>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getAnnotation13499, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.annotation.Annotation; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.annotation.Annotation>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getAnnotation13499, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.annotation.Annotation; } internal static global::MonoJavaBridge.MethodId _getDeclaredAnnotations13500; public sealed override global::java.lang.annotation.Annotation[] getDeclaredAnnotations() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.annotation.Annotation>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getDeclaredAnnotations13500)) as java.lang.annotation.Annotation[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.annotation.Annotation>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getDeclaredAnnotations13500)) as java.lang.annotation.Annotation[]; } internal static global::MonoJavaBridge.MethodId _getReturnType13501; public global::java.lang.Class getReturnType() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getReturnType13501)) as java.lang.Class; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getReturnType13501)) as java.lang.Class; } internal static global::MonoJavaBridge.MethodId _getParameterTypes13502; public global::java.lang.Class[] getParameterTypes() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Class>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getParameterTypes13502)) as java.lang.Class[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Class>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getParameterTypes13502)) as java.lang.Class[]; } internal static global::MonoJavaBridge.MethodId _toGenericString13503; public global::java.lang.String toGenericString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._toGenericString13503)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._toGenericString13503)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getGenericReturnType13504; public global::java.lang.reflect.Type getGenericReturnType() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.reflect.Type>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getGenericReturnType13504)) as java.lang.reflect.Type; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.reflect.Type>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getGenericReturnType13504)) as java.lang.reflect.Type; } internal static global::MonoJavaBridge.MethodId _getGenericParameterTypes13505; public global::java.lang.reflect.Type[] getGenericParameterTypes() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.reflect.Type>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getGenericParameterTypes13505)) as java.lang.reflect.Type[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.reflect.Type>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getGenericParameterTypes13505)) as java.lang.reflect.Type[]; } internal static global::MonoJavaBridge.MethodId _getExceptionTypes13506; public global::java.lang.Class[] getExceptionTypes() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Class>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getExceptionTypes13506)) as java.lang.Class[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Class>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getExceptionTypes13506)) as java.lang.Class[]; } internal static global::MonoJavaBridge.MethodId _getGenericExceptionTypes13507; public global::java.lang.reflect.Type[] getGenericExceptionTypes() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.reflect.Type>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getGenericExceptionTypes13507)) as java.lang.reflect.Type[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.reflect.Type>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getGenericExceptionTypes13507)) as java.lang.reflect.Type[]; } internal static global::MonoJavaBridge.MethodId _isBridge13508; public bool isBridge() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.reflect.Method._isBridge13508); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._isBridge13508); } internal static global::MonoJavaBridge.MethodId _isVarArgs13509; public bool isVarArgs() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.reflect.Method._isVarArgs13509); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._isVarArgs13509); } internal static global::MonoJavaBridge.MethodId _getDefaultValue13510; public global::java.lang.Object getDefaultValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getDefaultValue13510)) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getDefaultValue13510)) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _getParameterAnnotations13511; public global::java.lang.annotation.Annotation[][] getParameterAnnotations() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.annotation.Annotation[]>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Method._getParameterAnnotations13511)) as java.lang.annotation.Annotation[][]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.annotation.Annotation[]>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Method.staticClass, global::java.lang.reflect.Method._getParameterAnnotations13511)) as java.lang.annotation.Annotation[][]; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.lang.reflect.Method.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/reflect/Method")); global::java.lang.reflect.Method._invoke13490 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"); global::java.lang.reflect.Method._equals13491 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::java.lang.reflect.Method._toString13492 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "toString", "()Ljava/lang/String;"); global::java.lang.reflect.Method._hashCode13493 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "hashCode", "()I"); global::java.lang.reflect.Method._getModifiers13494 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getModifiers", "()I"); global::java.lang.reflect.Method._getName13495 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getName", "()Ljava/lang/String;"); global::java.lang.reflect.Method._isSynthetic13496 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "isSynthetic", "()Z"); global::java.lang.reflect.Method._getTypeParameters13497 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getTypeParameters", "()[Ljava/lang/reflect/TypeVariable;"); global::java.lang.reflect.Method._getDeclaringClass13498 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getDeclaringClass", "()Ljava/lang/Class;"); global::java.lang.reflect.Method._getAnnotation13499 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getAnnotation", "(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;"); global::java.lang.reflect.Method._getDeclaredAnnotations13500 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getDeclaredAnnotations", "()[Ljava/lang/annotation/Annotation;"); global::java.lang.reflect.Method._getReturnType13501 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getReturnType", "()Ljava/lang/Class;"); global::java.lang.reflect.Method._getParameterTypes13502 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getParameterTypes", "()[Ljava/lang/Class;"); global::java.lang.reflect.Method._toGenericString13503 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "toGenericString", "()Ljava/lang/String;"); global::java.lang.reflect.Method._getGenericReturnType13504 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getGenericReturnType", "()Ljava/lang/reflect/Type;"); global::java.lang.reflect.Method._getGenericParameterTypes13505 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getGenericParameterTypes", "()[Ljava/lang/reflect/Type;"); global::java.lang.reflect.Method._getExceptionTypes13506 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getExceptionTypes", "()[Ljava/lang/Class;"); global::java.lang.reflect.Method._getGenericExceptionTypes13507 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getGenericExceptionTypes", "()[Ljava/lang/reflect/Type;"); global::java.lang.reflect.Method._isBridge13508 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "isBridge", "()Z"); global::java.lang.reflect.Method._isVarArgs13509 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "isVarArgs", "()Z"); global::java.lang.reflect.Method._getDefaultValue13510 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getDefaultValue", "()Ljava/lang/Object;"); global::java.lang.reflect.Method._getParameterAnnotations13511 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Method.staticClass, "getParameterAnnotations", "()[[Ljava/lang/annotation/Annotation;"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Linq; using System.Web; using Examine.LuceneEngine.SearchCriteria; using Umbraco.Core.Dynamics; using Umbraco.Core.Models; using Umbraco.Web.Models; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; using Umbraco.Web.Templates; using umbraco; using umbraco.cms.businesslogic; using Umbraco.Core; using umbraco.cms.businesslogic.template; using umbraco.interfaces; using ContentType = umbraco.cms.businesslogic.ContentType; using Template = umbraco.cms.businesslogic.template.Template; namespace Umbraco.Web { /// <summary> /// Extension methods for IPublishedContent /// </summary> /// <remarks> /// These methods exist in the web project as we need access to web based classes like NiceUrl provider /// which is why they cannot exist in the Core project. /// </remarks> public static class PublishedContentExtensions { /// <summary> /// Converts an INode to an IPublishedContent item /// </summary> /// <param name="node"></param> /// <returns></returns> internal static IPublishedContent ConvertFromNode(this INode node) { var umbHelper = new UmbracoHelper(UmbracoContext.Current); return umbHelper.TypedContent(node.Id); } /// <summary> /// Gets the NiceUrl for the content item /// </summary> /// <param name="doc"></param> /// <returns></returns> [Obsolete("NiceUrl() is obsolete, use the Url() method instead")] public static string NiceUrl(this IPublishedContent doc) { return doc.Url(); } /// <summary> /// Gets the Url for the content item /// </summary> /// <param name="doc"></param> /// <returns></returns> public static string Url(this IPublishedContent doc) { switch (doc.ItemType) { case PublishedItemType.Content: var umbHelper = new UmbracoHelper(UmbracoContext.Current); return umbHelper.NiceUrl(doc.Id); case PublishedItemType.Media: var prop = doc.GetProperty(Constants.Conventions.Media.File); if (prop == null) throw new NotSupportedException("Cannot retreive a Url for a media item if there is no 'umbracoFile' property defined"); return prop.Value.ToString(); default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Gets the NiceUrlWithDomain for the content item /// </summary> /// <param name="doc"></param> /// <returns></returns> [Obsolete("NiceUrlWithDomain() is obsolete, use the UrlWithDomain() method instead")] public static string NiceUrlWithDomain(this IPublishedContent doc) { return doc.UrlWithDomain(); } /// <summary> /// Gets the UrlWithDomain for the content item /// </summary> /// <param name="doc"></param> /// <returns></returns> public static string UrlWithDomain(this IPublishedContent doc) { switch (doc.ItemType) { case PublishedItemType.Content: var umbHelper = new UmbracoHelper(UmbracoContext.Current); return umbHelper.NiceUrlWithDomain(doc.Id); case PublishedItemType.Media: throw new NotSupportedException("NiceUrlWithDomain is not supported for media types"); default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Returns the current template Alias /// </summary> /// <param name="doc"></param> /// <returns></returns> public static string GetTemplateAlias(this IPublishedContent doc) { var template = Template.GetTemplate(doc.TemplateId); return template != null ? template.Alias : string.Empty; } #region GetPropertyValue /// <summary> /// if the val is a string, ensures all internal local links are parsed /// </summary> /// <param name="val"></param> /// <returns></returns> internal static object GetValueWithParsedLinks(object val) { //if it is a string send it through the url parser var text = val as string; if (text != null) { return TemplateUtilities.ResolveUrlsFromTextString( TemplateUtilities.ParseInternalLinks(text)); } //its not a string return val; } public static object GetPropertyValue(this IPublishedContent doc, string alias) { return doc.GetPropertyValue(alias, false); } public static object GetPropertyValue(this IPublishedContent doc, string alias, string fallback) { var prop = doc.GetPropertyValue(alias); return (prop != null && !Convert.ToString(prop).IsNullOrWhiteSpace()) ? prop : fallback; } public static object GetPropertyValue(this IPublishedContent doc, string alias, bool recursive) { var p = doc.GetProperty(alias, recursive); if (p == null) return null; //Here we need to put the value through the IPropertyEditorValueConverter's //get the data type id for the current property var dataType = PublishedContentHelper.GetDataType( ApplicationContext.Current, doc.DocumentTypeAlias, alias, doc.ItemType); //convert the string value to a known type var converted = PublishedContentHelper.ConvertPropertyValue(p.Value, dataType, doc.DocumentTypeAlias, alias); return converted.Success ? GetValueWithParsedLinks(converted.Result) : GetValueWithParsedLinks(p.Value); } public static object GetPropertyValue(this IPublishedContent doc, string alias, bool recursive, string fallback) { var prop = doc.GetPropertyValue(alias, recursive); return (prop != null && !Convert.ToString(prop).IsNullOrWhiteSpace()) ? prop : fallback; } /// <summary> /// Returns the property as the specified type, if the property is not found or does not convert /// then the default value of type T is returned. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="doc"></param> /// <param name="alias"></param> /// <returns></returns> public static T GetPropertyValue<T>(this IPublishedContent doc, string alias) { return doc.GetPropertyValue<T>(alias, default(T)); } public static T GetPropertyValue<T>(this IPublishedContent prop, string alias, bool recursive, T ifCannotConvert) { var p = prop.GetProperty(alias, recursive); if (p == null) return ifCannotConvert; //before we try to convert it manually, lets see if the PropertyEditorValueConverter does this for us //Here we need to put the value through the IPropertyEditorValueConverter's //get the data type id for the current property var dataType = PublishedContentHelper.GetDataType(ApplicationContext.Current, prop.DocumentTypeAlias, alias, prop.ItemType); //convert the value to a known type var converted = PublishedContentHelper.ConvertPropertyValue(p.Value, dataType, prop.DocumentTypeAlias, alias); object parsedLinksVal; if (converted.Success) { parsedLinksVal = GetValueWithParsedLinks(converted.Result); //if its successful, check if its the correct type and return it if (parsedLinksVal is T) { return (T)parsedLinksVal; } //if that's not correct, try converting the converted type var reConverted = converted.Result.TryConvertTo<T>(); if (reConverted.Success) { return reConverted.Result; } } //first, parse links if possible parsedLinksVal = GetValueWithParsedLinks(p.Value); //last, if all the above has failed, we'll just try converting the raw value straight to 'T' var manualConverted = parsedLinksVal.TryConvertTo<T>(); if (manualConverted.Success) return manualConverted.Result; return ifCannotConvert; } public static T GetPropertyValue<T>(this IPublishedContent prop, string alias, T ifCannotConvert) { return prop.GetPropertyValue<T>(alias, false, ifCannotConvert); } #endregion #region Search public static IEnumerable<IPublishedContent> Search(this IPublishedContent d, string term, bool useWildCards = true, string searchProvider = null) { var searcher = Examine.ExamineManager.Instance.DefaultSearchProvider; if (!string.IsNullOrEmpty(searchProvider)) searcher = Examine.ExamineManager.Instance.SearchProviderCollection[searchProvider]; var t = term.Escape().Value; if (useWildCards) t = term.MultipleCharacterWildcard().Value; string luceneQuery = "+__Path:(" + d.Path.Replace("-", "\\-") + "*) +" + t; var crit = searcher.CreateSearchCriteria().RawQuery(luceneQuery); return d.Search(crit, searcher); } public static IEnumerable<IPublishedContent> SearchDescendants(this IPublishedContent d, string term, bool useWildCards = true, string searchProvider = null) { return d.Search(term, useWildCards, searchProvider); } public static IEnumerable<IPublishedContent> SearchChildren(this IPublishedContent d, string term, bool useWildCards = true, string searchProvider = null) { var searcher = Examine.ExamineManager.Instance.DefaultSearchProvider; if (!string.IsNullOrEmpty(searchProvider)) searcher = Examine.ExamineManager.Instance.SearchProviderCollection[searchProvider]; var t = term.Escape().Value; if (useWildCards) t = term.MultipleCharacterWildcard().Value; string luceneQuery = "+parentID:" + d.Id.ToString() + " +" + t; var crit = searcher.CreateSearchCriteria().RawQuery(luceneQuery); return d.Search(crit, searcher); } public static IEnumerable<IPublishedContent> Search(this IPublishedContent d, Examine.SearchCriteria.ISearchCriteria criteria, Examine.Providers.BaseSearchProvider searchProvider = null) { var s = Examine.ExamineManager.Instance.DefaultSearchProvider; if (searchProvider != null) s = searchProvider; var results = s.Search(criteria); return results.ConvertSearchResultToPublishedContent(UmbracoContext.Current.ContentCache); } #endregion #region Linq Wrapping Extensions //NOTE: These are all purely required to fix this issue: http://issues.umbraco.org/issue/U4-1797 which requires that any // content item knows about it's containing collection. public static IEnumerable<IPublishedContent> Where(this IEnumerable<IPublishedContent> source, Func<IPublishedContent, bool> predicate) { var internalResult = Enumerable.Where(source, predicate); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Where(this IEnumerable<IPublishedContent> source, Func<IPublishedContent, int, bool> predicate) { var internalResult = Enumerable.Where(source, predicate); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Take(this IEnumerable<IPublishedContent> source, int count) { var internalResult = Enumerable.Take(source, count); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> TakeWhile(this IEnumerable<IPublishedContent> source, Func<IPublishedContent, bool> predicate) { var internalResult = Enumerable.TakeWhile(source, predicate); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> TakeWhile(this IEnumerable<IPublishedContent> source, Func<IPublishedContent, int, bool> predicate) { var internalResult = Enumerable.TakeWhile(source, predicate); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Skip(this IEnumerable<IPublishedContent> source, int count) { var internalResult = Enumerable.Skip(source, count); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> SkipWhile(this IEnumerable<IPublishedContent> source, Func<IPublishedContent, bool> predicate) { var internalResult = Enumerable.SkipWhile(source, predicate); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> SkipWhile(this IEnumerable<IPublishedContent> source, Func<IPublishedContent, int, bool> predicate) { var internalResult = Enumerable.SkipWhile(source, predicate); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Concat(this IEnumerable<IPublishedContent> first, IEnumerable<IPublishedContent> second) { var internalResult = Enumerable.Concat(first, second); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Distinct(this IEnumerable<IPublishedContent> source) { var internalResult = Enumerable.Distinct(source); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Distinct(this IEnumerable<IPublishedContent> source, IEqualityComparer<IPublishedContent> comparer) { var internalResult = Enumerable.Distinct(source, comparer); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Union(this IEnumerable<IPublishedContent> first, IEnumerable<IPublishedContent> second) { var internalResult = Enumerable.Union(first, second); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Union(this IEnumerable<IPublishedContent> first, IEnumerable<IPublishedContent> second, IEqualityComparer<IPublishedContent> comparer) { var internalResult = Enumerable.Union(first, second, comparer); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Intersect(this IEnumerable<IPublishedContent> first, IEnumerable<IPublishedContent> second) { var internalResult = Enumerable.Intersect(first, second); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Intersect(this IEnumerable<IPublishedContent> first, IEnumerable<IPublishedContent> second, IEqualityComparer<IPublishedContent> comparer) { var internalResult = Enumerable.Intersect(first, second, comparer); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Except(this IEnumerable<IPublishedContent> first, IEnumerable<IPublishedContent> second) { var internalResult = Enumerable.Except(first, second); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Except(this IEnumerable<IPublishedContent> first, IEnumerable<IPublishedContent> second, IEqualityComparer<IPublishedContent> comparer) { var internalResult = Enumerable.Except(first, second, comparer); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> Reverse(this IEnumerable<IPublishedContent> source) { var internalResult = Enumerable.Reverse(source); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> DefaultIfEmpty(this IEnumerable<IPublishedContent> source) { var internalResult = Enumerable.DefaultIfEmpty(source); return new DynamicPublishedContentList(internalResult); } public static IEnumerable<IPublishedContent> DefaultIfEmpty(this IEnumerable<IPublishedContent> source, IPublishedContent defaultValue) { var internalResult = Enumerable.DefaultIfEmpty(source, defaultValue); return new DynamicPublishedContentList(internalResult); } #endregion #region Dynamic Linq Extensions public static IQueryable<IPublishedContent> OrderBy(this IEnumerable<IPublishedContent> list, string predicate) { var dList = new DynamicPublishedContentList(list); return dList.OrderBy<DynamicPublishedContent>(predicate); } public static IQueryable<IPublishedContent> Where(this IEnumerable<IPublishedContent> list, string predicate) { var dList = new DynamicPublishedContentList(list); //we have to wrap the result in another DynamicPublishedContentList so that the OwnersList get's set on //the individual items. See: http://issues.umbraco.org/issue/U4-1797 return new DynamicPublishedContentList( dList.Where<DynamicPublishedContent>(predicate)) .AsQueryable<IPublishedContent>(); } public static IEnumerable<IGrouping<object, IPublishedContent>> GroupBy(this IEnumerable<IPublishedContent> list, string predicate) { var dList = new DynamicPublishedContentList(list); return dList.GroupBy(predicate); } public static IQueryable Select(this IEnumerable<IPublishedContent> list, string predicate, params object[] values) { var dList = new DynamicPublishedContentList(list); return dList.Select(predicate); } #endregion public static dynamic AsDynamic(this IPublishedContent doc) { if (doc == null) throw new ArgumentNullException("doc"); var dd = new DynamicPublishedContent(doc); return dd.AsDynamic(); } /// <summary> /// Converts a IPublishedContent to a DynamicPublishedContent and tests for null /// </summary> /// <param name="content"></param> /// <returns></returns> internal static DynamicPublishedContent AsDynamicPublishedContent(this IPublishedContent content) { if (content == null) return null; return new DynamicPublishedContent(content); } #region Where public static HtmlString Where(this IPublishedContent doc, string predicate, string valueIfTrue) { if (doc == null) throw new ArgumentNullException("doc"); return doc.Where(predicate, valueIfTrue, string.Empty); } public static HtmlString Where(this IPublishedContent doc, string predicate, string valueIfTrue, string valueIfFalse) { if (doc == null) throw new ArgumentNullException("doc"); if (doc.Where(predicate)) { return new HtmlString(valueIfTrue); } return new HtmlString(valueIfFalse); } public static bool Where(this IPublishedContent doc, string predicate) { if (doc == null) throw new ArgumentNullException("doc"); var dynamicDocumentList = new DynamicPublishedContentList(); dynamicDocumentList.Add(doc.AsDynamicPublishedContent()); var filtered = dynamicDocumentList.Where<DynamicPublishedContent>(predicate); if (filtered.Count() == 1) { //this node matches the predicate return true; } return false; } #endregion #region Position/Index public static int Position(this IPublishedContent content) { return content.Index(); } public static int Index(this IPublishedContent content) { var container = content.GetOwnersList().ToList(); int currentIndex = container.FindIndex(n => n.Id == content.Id); if (currentIndex != -1) { return currentIndex; } else { throw new IndexOutOfRangeException(string.Format("Node {0} belongs to a DynamicDocumentList but could not retrieve the index for it's position in the list", content.Id)); } } /// <summary> /// Return the owners collection of the current content item. /// </summary> /// <param name="content"></param> /// <returns></returns> /// <remarks> /// If the content item is of type PublishedContentBase we will have a property called OwnersCollection which will /// be the collection of a resultant set (i.e. from a where clause, a call to Children(), etc...) otherwise it will /// be the item's siblings. All relates to this issue: http://issues.umbraco.org/issue/U4-1797 /// </remarks> private static IEnumerable<IPublishedContent> GetOwnersList(this IPublishedContent content) { //Here we need to type check, we need to see if we have a real OwnersCollection list based on the result set // of a query, otherwise we can only lookup among the item's siblings. All related to this issue here: // http://issues.umbraco.org/issue/U4-1797 var publishedContentBase = content as IOwnerCollectionAware<IPublishedContent>; var ownersList = publishedContentBase != null ? publishedContentBase.OwnersCollection : content.Siblings(); return ownersList; } #endregion #region Is Helpers public static bool IsDocumentType(this IPublishedContent content, string docTypeAlias) { return content.DocumentTypeAlias == docTypeAlias; } public static bool IsNull(this IPublishedContent content, string alias, bool recursive) { var prop = content.GetProperty(alias, recursive); if (prop == null) return true; return ((PropertyResult)prop).HasValue(); } public static bool IsNull(this IPublishedContent content, string alias) { return content.IsNull(alias, false); } #region Position in list public static bool IsFirst(this IPublishedContent content) { return content.IsHelper(n => n.Index() == 0); } public static HtmlString IsFirst(this IPublishedContent content, string valueIfTrue) { return content.IsHelper(n => n.Index() == 0, valueIfTrue); } public static HtmlString IsFirst(this IPublishedContent content, string valueIfTrue, string valueIfFalse) { return content.IsHelper(n => n.Index() == 0, valueIfTrue, valueIfFalse); } public static bool IsNotFirst(this IPublishedContent content) { return !content.IsHelper(n => n.Index() == 0); } public static HtmlString IsNotFirst(this IPublishedContent content, string valueIfTrue) { return content.IsHelper(n => n.Index() != 0, valueIfTrue); } public static HtmlString IsNotFirst(this IPublishedContent content, string valueIfTrue, string valueIfFalse) { return content.IsHelper(n => n.Index() != 0, valueIfTrue, valueIfFalse); } public static bool IsPosition(this IPublishedContent content, int index) { return content.IsHelper(n => n.Index() == index); } public static HtmlString IsPosition(this IPublishedContent content, int index, string valueIfTrue) { return content.IsHelper(n => n.Index() == index, valueIfTrue); } public static HtmlString IsPosition(this IPublishedContent content, int index, string valueIfTrue, string valueIfFalse) { return content.IsHelper(n => n.Index() == index, valueIfTrue, valueIfFalse); } public static bool IsModZero(this IPublishedContent content, int modulus) { return content.IsHelper(n => n.Index() % modulus == 0); } public static HtmlString IsModZero(this IPublishedContent content, int modulus, string valueIfTrue) { return content.IsHelper(n => n.Index() % modulus == 0, valueIfTrue); } public static HtmlString IsModZero(this IPublishedContent content, int modulus, string valueIfTrue, string valueIfFalse) { return content.IsHelper(n => n.Index() % modulus == 0, valueIfTrue, valueIfFalse); } public static bool IsNotModZero(this IPublishedContent content, int modulus) { return content.IsHelper(n => n.Index() % modulus != 0); } public static HtmlString IsNotModZero(this IPublishedContent content, int modulus, string valueIfTrue) { return content.IsHelper(n => n.Index() % modulus != 0, valueIfTrue); } public static HtmlString IsNotModZero(this IPublishedContent content, int modulus, string valueIfTrue, string valueIfFalse) { return content.IsHelper(n => n.Index() % modulus != 0, valueIfTrue, valueIfFalse); } public static bool IsNotPosition(this IPublishedContent content, int index) { return !content.IsHelper(n => n.Index() == index); } public static HtmlString IsNotPosition(this IPublishedContent content, int index, string valueIfTrue) { return content.IsHelper(n => n.Index() != index, valueIfTrue); } public static HtmlString IsNotPosition(this IPublishedContent content, int index, string valueIfTrue, string valueIfFalse) { return content.IsHelper(n => n.Index() != index, valueIfTrue, valueIfFalse); } public static bool IsLast(this IPublishedContent content) { var ownersList = content.GetOwnersList(); var count = ownersList.Count(); return content.IsHelper(n => n.Index() == count - 1); } public static HtmlString IsLast(this IPublishedContent content, string valueIfTrue) { var ownersList = content.GetOwnersList(); var count = ownersList.Count(); return content.IsHelper(n => n.Index() == count - 1, valueIfTrue); } public static HtmlString IsLast(this IPublishedContent content, string valueIfTrue, string valueIfFalse) { var ownersList = content.GetOwnersList(); var count = ownersList.Count(); return content.IsHelper(n => n.Index() == count - 1, valueIfTrue, valueIfFalse); } public static bool IsNotLast(this IPublishedContent content) { var ownersList = content.GetOwnersList(); var count = ownersList.Count(); return !content.IsHelper(n => n.Index() == count - 1); } public static HtmlString IsNotLast(this IPublishedContent content, string valueIfTrue) { var ownersList = content.GetOwnersList(); var count = ownersList.Count(); return content.IsHelper(n => n.Index() != count - 1, valueIfTrue); } public static HtmlString IsNotLast(this IPublishedContent content, string valueIfTrue, string valueIfFalse) { var ownersList = content.GetOwnersList(); var count = ownersList.Count(); return content.IsHelper(n => n.Index() != count - 1, valueIfTrue, valueIfFalse); } public static bool IsEven(this IPublishedContent content) { return content.IsHelper(n => n.Index() % 2 == 0); } public static HtmlString IsEven(this IPublishedContent content, string valueIfTrue) { return content.IsHelper(n => n.Index() % 2 == 0, valueIfTrue); } public static HtmlString IsEven(this IPublishedContent content, string valueIfTrue, string valueIfFalse) { return content.IsHelper(n => n.Index() % 2 == 0, valueIfTrue, valueIfFalse); } public static bool IsOdd(this IPublishedContent content) { return content.IsHelper(n => n.Index() % 2 == 1); } public static HtmlString IsOdd(this IPublishedContent content, string valueIfTrue) { return content.IsHelper(n => n.Index() % 2 == 1, valueIfTrue); } public static HtmlString IsOdd(this IPublishedContent content, string valueIfTrue, string valueIfFalse) { return content.IsHelper(n => n.Index() % 2 == 1, valueIfTrue, valueIfFalse); } #endregion public static bool IsEqual(this IPublishedContent content, IPublishedContent other) { return content.IsHelper(n => n.Id == other.Id); } public static HtmlString IsEqual(this IPublishedContent content, IPublishedContent other, string valueIfTrue) { return content.IsHelper(n => n.Id == other.Id, valueIfTrue); } public static HtmlString IsEqual(this IPublishedContent content, IPublishedContent other, string valueIfTrue, string valueIfFalse) { return content.IsHelper(n => n.Id == other.Id, valueIfTrue, valueIfFalse); } public static bool IsNotEqual(this IPublishedContent content, IPublishedContent other) { return content.IsHelper(n => n.Id != other.Id); } public static HtmlString IsNotEqual(this IPublishedContent content, IPublishedContent other, string valueIfTrue) { return content.IsHelper(n => n.Id != other.Id, valueIfTrue); } public static HtmlString IsNotEqual(this IPublishedContent content, IPublishedContent other, string valueIfTrue, string valueIfFalse) { return content.IsHelper(n => n.Id != other.Id, valueIfTrue, valueIfFalse); } public static bool IsDescendant(this IPublishedContent content, IPublishedContent other) { var ancestors = content.Ancestors(); return content.IsHelper(n => ancestors.FirstOrDefault(ancestor => ancestor.Id == other.Id) != null); } public static HtmlString IsDescendant(this IPublishedContent content, IPublishedContent other, string valueIfTrue) { var ancestors = content.Ancestors(); return content.IsHelper(n => ancestors.FirstOrDefault(ancestor => ancestor.Id == other.Id) != null, valueIfTrue); } public static HtmlString IsDescendant(this IPublishedContent content, IPublishedContent other, string valueIfTrue, string valueIfFalse) { var ancestors = content.Ancestors(); return content.IsHelper(n => ancestors.FirstOrDefault(ancestor => ancestor.Id == other.Id) != null, valueIfTrue, valueIfFalse); } public static bool IsDescendantOrSelf(this IPublishedContent content, IPublishedContent other) { var ancestors = content.AncestorsOrSelf(); return content.IsHelper(n => ancestors.FirstOrDefault(ancestor => ancestor.Id == other.Id) != null); } public static HtmlString IsDescendantOrSelf(this IPublishedContent content, IPublishedContent other, string valueIfTrue) { var ancestors = content.AncestorsOrSelf(); return content.IsHelper(n => ancestors.FirstOrDefault(ancestor => ancestor.Id == other.Id) != null, valueIfTrue); } public static HtmlString IsDescendantOrSelf(this IPublishedContent content, IPublishedContent other, string valueIfTrue, string valueIfFalse) { var ancestors = content.AncestorsOrSelf(); return content.IsHelper(n => ancestors.FirstOrDefault(ancestor => ancestor.Id == other.Id) != null, valueIfTrue, valueIfFalse); } public static bool IsAncestor(this IPublishedContent content, IPublishedContent other) { var descendants = content.Descendants(); return content.IsHelper(n => descendants.FirstOrDefault(descendant => descendant.Id == other.Id) != null); } public static HtmlString IsAncestor(this IPublishedContent content, IPublishedContent other, string valueIfTrue) { var descendants = content.Descendants(); return content.IsHelper(n => descendants.FirstOrDefault(descendant => descendant.Id == other.Id) != null, valueIfTrue); } public static HtmlString IsAncestor(this IPublishedContent content, IPublishedContent other, string valueIfTrue, string valueIfFalse) { var descendants = content.Descendants(); return content.IsHelper(n => descendants.FirstOrDefault(descendant => descendant.Id == other.Id) != null, valueIfTrue, valueIfFalse); } public static bool IsAncestorOrSelf(this IPublishedContent content, IPublishedContent other) { var descendants = content.DescendantsOrSelf(); return content.IsHelper(n => descendants.FirstOrDefault(descendant => descendant.Id == other.Id) != null); } public static HtmlString IsAncestorOrSelf(this IPublishedContent content, IPublishedContent other, string valueIfTrue) { var descendants = content.DescendantsOrSelf(); return content.IsHelper(n => descendants.FirstOrDefault(descendant => descendant.Id == other.Id) != null, valueIfTrue); } public static HtmlString IsAncestorOrSelf(this IPublishedContent content, IPublishedContent other, string valueIfTrue, string valueIfFalse) { var descendants = content.DescendantsOrSelf(); return content.IsHelper(n => descendants.FirstOrDefault(descendant => descendant.Id == other.Id) != null, valueIfTrue, valueIfFalse); } private static bool IsHelper(this IPublishedContent content, Func<IPublishedContent, bool> test) { return test(content); } private static HtmlString IsHelper(this IPublishedContent content, Func<IPublishedContent, bool> test, string valueIfTrue) { return content.IsHelper(test, valueIfTrue, string.Empty); } private static HtmlString IsHelper(this IPublishedContent content, Func<IPublishedContent, bool> test, string valueIfTrue, string valueIfFalse) { return test(content) ? new HtmlString(valueIfTrue) : new HtmlString(valueIfFalse); } #endregion #region Ancestors public static IEnumerable<IPublishedContent> Ancestors(this IPublishedContent content) { return content.AncestorsOrSelf(false, n => true); } public static IEnumerable<IPublishedContent> Ancestors(this IPublishedContent content, int level) { return content.AncestorsOrSelf(false, n => n.Level <= level); } public static IEnumerable<IPublishedContent> Ancestors(this IPublishedContent content, string nodeTypeAlias) { return content.AncestorsOrSelf(false, n => n.DocumentTypeAlias == nodeTypeAlias); } internal static IEnumerable<IPublishedContent> Ancestors(this IPublishedContent content, Func<IPublishedContent, bool> func) { return content.AncestorsOrSelf(false, func); } public static IPublishedContent AncestorOrSelf(this IPublishedContent content) { //TODO: Why is this query like this?? return content.AncestorOrSelf(node => node.Level == 1); } public static IPublishedContent AncestorOrSelf(this IPublishedContent content, int level) { return content.AncestorOrSelf(node => node.Level == level); } public static IPublishedContent AncestorOrSelf(this IPublishedContent content, string nodeTypeAlias) { return content.AncestorOrSelf(node => node.DocumentTypeAlias == nodeTypeAlias); } internal static IPublishedContent AncestorOrSelf(this IPublishedContent content, Func<IPublishedContent, bool> func) { if (func(content)) return content; while (content.Level > 1) // while we have a parent, consider the parent { content = content.Parent; if (func(content)) return content; } return null; } public static IEnumerable<IPublishedContent> AncestorsOrSelf(this IPublishedContent content) { return content.AncestorsOrSelf(true, n => true); } public static IEnumerable<IPublishedContent> AncestorsOrSelf(this IPublishedContent content, int level) { return content.AncestorsOrSelf(true, n => n.Level <= level); } public static IEnumerable<IPublishedContent> AncestorsOrSelf(this IPublishedContent content, string nodeTypeAlias) { return content.AncestorsOrSelf(true, n => n.DocumentTypeAlias == nodeTypeAlias); } internal static IEnumerable<IPublishedContent> AncestorsOrSelf(this IPublishedContent content, Func<IPublishedContent, bool> func) { return content.AncestorsOrSelf(true, func); } internal static IEnumerable<IPublishedContent> AncestorsOrSelf(this IPublishedContent content, bool orSelf, Func<IPublishedContent, bool> func) { var ancestors = new List<IPublishedContent>(); if (orSelf && func(content)) ancestors.Add(content); while (content.Level > 1) // while we have a parent, consider the parent { content = content.Parent; if (func(content)) ancestors.Add(content); } ancestors.Reverse(); return ancestors; } #endregion #region Descendants public static IEnumerable<IPublishedContent> Descendants(this IPublishedContent content, string nodeTypeAlias) { return content.Descendants(p => p.DocumentTypeAlias == nodeTypeAlias); } public static IEnumerable<IPublishedContent> Descendants(this IPublishedContent content, int level) { return content.Descendants(p => p.Level >= level); } public static IEnumerable<IPublishedContent> Descendants(this IPublishedContent content) { return content.Descendants(n => true); } private static IEnumerable<IPublishedContent> Descendants(this IPublishedContent content, Func<IPublishedContent, bool> func) { //return content.Children.Map(func, (IPublishedContent n) => n.Children); return content.Children.FlattenList(x => x.Children).Where(func) .OrderBy(x => x.Level) //ensure its sorted by level and then by sort order .ThenBy(x => x.SortOrder); } public static IEnumerable<IPublishedContent> DescendantsOrSelf(this IPublishedContent content, int level) { return content.DescendantsOrSelf(p => p.Level >= level); } public static IEnumerable<IPublishedContent> DescendantsOrSelf(this IPublishedContent content, string nodeTypeAlias) { return content.DescendantsOrSelf(p => p.DocumentTypeAlias == nodeTypeAlias); } public static IEnumerable<IPublishedContent> DescendantsOrSelf(this IPublishedContent content) { return content.DescendantsOrSelf(p => true); } internal static IEnumerable<IPublishedContent> DescendantsOrSelf(this IPublishedContent content, Func<IPublishedContent, bool> func) { if (content != null) { var thisNode = new List<IPublishedContent>(); if (func(content)) { thisNode.Add(content); } //var flattenedNodes = content.Children.Map(func, (IPublishedContent n) => n.Children); var flattenedNodes = content.Children.FlattenList(n => n.Children).Where(func); return thisNode.Concat(flattenedNodes) .Select(dynamicBackingItem => new DynamicPublishedContent(dynamicBackingItem)) .OrderBy(x => x.Level) //ensure its sorted by level and then by sort order .ThenBy(x => x.SortOrder); } return Enumerable.Empty<IPublishedContent>(); } #endregion #region Traversal public static IPublishedContent Up(this IPublishedContent content) { return content.Up(0); } public static IPublishedContent Up(this IPublishedContent content, int number) { if (number == 0) { return content.Parent; } while ((content = content.Parent) != null && --number >= 0) ; return content; } public static IPublishedContent Up(this IPublishedContent content, string nodeTypeAlias) { if (string.IsNullOrEmpty(nodeTypeAlias)) { return content.Parent; } while ((content = content.Parent) != null && content.DocumentTypeAlias != nodeTypeAlias) ; return content; } public static IPublishedContent Down(this IPublishedContent content) { return content.Down(0); } public static IPublishedContent Down(this IPublishedContent content, int number) { var children = content.Children; if (number == 0) { return children.First(); } var working = content; while (number-- >= 0) { working = children.First(); children = new DynamicPublishedContentList(working.Children); } return working; } public static IPublishedContent Down(this IPublishedContent content, string nodeTypeAlias) { if (string.IsNullOrEmpty(nodeTypeAlias)) { var children = content.Children; return children.First(); } return content.Descendants(nodeTypeAlias).FirstOrDefault(); } public static IPublishedContent Next(this IPublishedContent content) { return content.Next(0); } public static IPublishedContent Next(this IPublishedContent content, int number) { var ownersList = content.GetOwnersList(); var container = ownersList.ToList(); var currentIndex = container.FindIndex(n => n.Id == content.Id); if (currentIndex != -1) { return container.ElementAtOrDefault(currentIndex + (number + 1)); } throw new IndexOutOfRangeException(string.Format("Node {0} belongs to a DynamicNodeList but could not retrieve the index for it's position in the list", content.Id)); } public static IPublishedContent Next(this IPublishedContent content, string nodeTypeAlias) { var ownersList = content.GetOwnersList(); var container = ownersList.ToList(); var currentIndex = container.FindIndex(n => n.Id == content.Id); if (currentIndex != -1) { var newIndex = container.FindIndex(currentIndex, n => n.DocumentTypeAlias == nodeTypeAlias); return newIndex != -1 ? container.ElementAt(newIndex) : null; } throw new IndexOutOfRangeException(string.Format("Node {0} belongs to a DynamicNodeList but could not retrieve the index for it's position in the list", content.Id)); } public static IPublishedContent Previous(this IPublishedContent content) { return content.Previous(0); } public static IPublishedContent Previous(this IPublishedContent content, int number) { var ownersList = content.GetOwnersList(); var container = ownersList.ToList(); var currentIndex = container.FindIndex(n => n.Id == content.Id); if (currentIndex != -1) { return container.ElementAtOrDefault(currentIndex + (number - 1)); } throw new IndexOutOfRangeException(string.Format("Node {0} belongs to a DynamicNodeList but could not retrieve the index for it's position in the list", content.Id)); } public static IPublishedContent Previous(this IPublishedContent content, string nodeTypeAlias) { var ownersList = content.GetOwnersList(); var container = ownersList.ToList(); int currentIndex = container.FindIndex(n => n.Id == content.Id); if (currentIndex != -1) { var previousNodes = container.Take(currentIndex).ToList(); int newIndex = previousNodes.FindIndex(n => n.DocumentTypeAlias == nodeTypeAlias); if (newIndex != -1) { return container.ElementAt(newIndex); } return null; } throw new IndexOutOfRangeException(string.Format("Node {0} belongs to a DynamicNodeList but could not retrieve the index for it's position in the list", content.Id)); } public static IPublishedContent Sibling(this IPublishedContent content, int number) { var siblings = content.Siblings(); var container = siblings.ToList(); var currentIndex = container.FindIndex(n => n.Id == content.Id); if (currentIndex != -1) { return container.ElementAtOrDefault(currentIndex + number); } throw new IndexOutOfRangeException(string.Format("Node {0} belongs to a DynamicNodeList but could not retrieve the index for it's position in the list", content.Id)); } public static IPublishedContent Sibling(this IPublishedContent content, string nodeTypeAlias) { var siblings = content.Siblings(); var container = siblings.ToList(); var currentIndex = container.FindIndex(n => n.Id == content.Id); if (currentIndex != -1) { var workingIndex = currentIndex + 1; while (workingIndex != currentIndex) { var working = container.ElementAtOrDefault(workingIndex); if (working != null && working.DocumentTypeAlias == nodeTypeAlias) { return working; } workingIndex++; if (workingIndex > container.Count) { workingIndex = 0; } } return null; } throw new IndexOutOfRangeException(string.Format("Node {0} belongs to a DynamicNodeList but could not retrieve the index for it's position in the list", content.Id)); } /// <summary> /// Return the items siblings /// </summary> /// <param name="content"></param> /// <returns></returns> public static IEnumerable<IPublishedContent> Siblings(this IPublishedContent content) { //get the root docs if parent is null return content.Parent == null ? UmbracoContext.Current.ContentCache.GetAtRoot() : content.Parent.Children; } #endregion /// <summary> /// Method to return the Children of the content item /// </summary> /// <param name="p"></param> /// <returns></returns> /// <remarks> /// This method exists for consistency, it is the same as calling content.Children as a property. /// </remarks> public static IEnumerable<IPublishedContent> Children(this IPublishedContent p) { return p.Children.OrderBy(x => x.SortOrder); } /// <summary> /// Returns a DataTable object for the IPublishedContent /// </summary> /// <param name="d"></param> /// <param name="nodeTypeAliasFilter"></param> /// <returns></returns> public static DataTable ChildrenAsTable(this IPublishedContent d, string nodeTypeAliasFilter = "") { return GenerateDataTable(d, nodeTypeAliasFilter); } /// <summary> /// Generates the DataTable for the IPublishedContent /// </summary> /// <param name="node"></param> /// <param name="nodeTypeAliasFilter"> </param> /// <returns></returns> private static DataTable GenerateDataTable(IPublishedContent node, string nodeTypeAliasFilter = "") { var firstNode = nodeTypeAliasFilter.IsNullOrWhiteSpace() ? node.Children.Any() ? node.Children.ElementAt(0) : null : node.Children.FirstOrDefault(x => x.DocumentTypeAlias == nodeTypeAliasFilter); if (firstNode == null) return new DataTable(); //no children found var urlProvider = UmbracoContext.Current.RoutingContext.UrlProvider; //use new utility class to create table so that we don't have to maintain code in many places, just one var dt = Umbraco.Core.DataTableExtensions.GenerateDataTable( //pass in the alias of the first child node since this is the node type we're rendering headers for firstNode.DocumentTypeAlias, //pass in the callback to extract the Dictionary<string, string> of all defined aliases to their names alias => GetPropertyAliasesAndNames(alias), //pass in a callback to populate the datatable, yup its a bit ugly but it's already legacy and we just want to maintain code in one place. () => { //create all row data var tableData = Umbraco.Core.DataTableExtensions.CreateTableData(); //loop through each child and create row data for it foreach (var n in node.Children.OrderBy(x => x.SortOrder)) { if (!nodeTypeAliasFilter.IsNullOrWhiteSpace()) { if (n.DocumentTypeAlias != nodeTypeAliasFilter) continue; //skip this one, it doesn't match the filter } var standardVals = new Dictionary<string, object>() { {"Id", n.Id}, {"NodeName", n.Name}, {"NodeTypeAlias", n.DocumentTypeAlias}, {"CreateDate", n.CreateDate}, {"UpdateDate", n.UpdateDate}, {"CreatorName", n.CreatorName}, {"WriterName", n.WriterName}, {"Url", urlProvider.GetUrl(n.Id)} }; var userVals = new Dictionary<string, object>(); foreach (var p in from IPublishedContentProperty p in n.Properties where p.Value != null select p) { userVals[p.Alias] = p.Value; } //add the row data Umbraco.Core.DataTableExtensions.AddRowData(tableData, standardVals, userVals); } return tableData; } ); return dt; } private static Func<string, Dictionary<string, string>> _getPropertyAliasesAndNames; /// <summary> /// This is used only for unit tests to set the delegate to look up aliases/names dictionary of a content type /// </summary> internal static Func<string, Dictionary<string, string>> GetPropertyAliasesAndNames { get { return _getPropertyAliasesAndNames ?? (_getPropertyAliasesAndNames = alias => { var userFields = ContentType.GetAliasesAndNames(alias); //ensure the standard fields are there var allFields = new Dictionary<string, string>() { {"Id", "Id"}, {"NodeName", "NodeName"}, {"NodeTypeAlias", "NodeTypeAlias"}, {"CreateDate", "CreateDate"}, {"UpdateDate", "UpdateDate"}, {"CreatorName", "CreatorName"}, {"WriterName", "WriterName"}, {"Url", "Url"} }; foreach (var f in userFields.Where(f => !allFields.ContainsKey(f.Key))) { allFields.Add(f.Key, f.Value); } return allFields; }); } set { _getPropertyAliasesAndNames = value; } } } }
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 SignNowCSharpExample.Areas.HelpPage.Models; namespace SignNowCSharpExample.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); } } } }
// 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: List for exceptions. ** ** ===========================================================*/ using System.Diagnostics.Contracts; namespace System.Collections { /// This is a simple implementation of IDictionary that is empty and readonly. [Serializable] internal sealed class EmptyReadOnlyDictionaryInternal : IDictionary { // Note that this class must be agile with respect to AppDomains. See its usage in // System.Exception to understand why this is the case. public EmptyReadOnlyDictionaryInternal() { } // IEnumerable members IEnumerator IEnumerable.GetEnumerator() { return new NodeEnumerator(); } // ICollection members public void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < this.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); Contract.EndContractBlock(); // the actual copy is a NOP } public int Count { get { return 0; } } public Object SyncRoot { get { return this; } } public bool IsSynchronized { get { return false; } } // IDictionary members public Object this[Object key] { get { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } Contract.EndContractBlock(); return null; } set { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } if (!key.GetType().IsSerializable) throw new ArgumentException(SR.Argument_NotSerializable, nameof(key)); if ((value != null) && (!value.GetType().IsSerializable)) throw new ArgumentException(SR.Argument_NotSerializable, nameof(value)); Contract.EndContractBlock(); throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } public ICollection Keys { get { return Array.Empty<Object>(); } } public ICollection Values { get { return Array.Empty<Object>(); } } public bool Contains(Object key) { return false; } public void Add(Object key, Object value) { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } if (!key.GetType().IsSerializable) throw new ArgumentException(SR.Argument_NotSerializable, nameof(key)); if ((value != null) && (!value.GetType().IsSerializable)) throw new ArgumentException(SR.Argument_NotSerializable, nameof(value)); Contract.EndContractBlock(); throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } public void Clear() { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } public bool IsReadOnly { get { return true; } } public bool IsFixedSize { get { return true; } } public IDictionaryEnumerator GetEnumerator() { return new NodeEnumerator(); } public void Remove(Object key) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } private sealed class NodeEnumerator : IDictionaryEnumerator { public NodeEnumerator() { } // IEnumerator members public bool MoveNext() { return false; } public Object Current { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } public void Reset() { } // IDictionaryEnumerator members public Object Key { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } public Object Value { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } public DictionaryEntry Entry { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Threading; using TrueCraft.API; using TrueCraft.API.World; using TrueCraft.API.Logic; using fNbt; namespace TrueCraft.Core.World { public class World : IDisposable, IWorld { public static readonly int Height = 128; public string Name { get; set; } public int Seed { get; set; } private Coordinates3D? _SpawnPoint; public Coordinates3D SpawnPoint { get { if (_SpawnPoint == null) _SpawnPoint = ChunkProvider.GetSpawn(this); return _SpawnPoint.Value; } set { _SpawnPoint = value; } } public string BaseDirectory { get; internal set; } public IDictionary<Coordinates2D, IRegion> Regions { get; set; } public IBiomeMap BiomeDiagram { get; set; } public IChunkProvider ChunkProvider { get; set; } public IBlockRepository BlockRepository { get; set; } public DateTime BaseTime { get; set; } public long Time { get { return (long)((DateTime.Now - BaseTime).TotalSeconds * 20) % 24000; } set { BaseTime = DateTime.Now.AddSeconds(-value / 20); } } public event EventHandler<BlockChangeEventArgs> BlockChanged; public World() { Regions = new Dictionary<Coordinates2D, IRegion>(); BaseTime = DateTime.Now; } public World(string name) : this() { Name = name; Seed = new Random().Next(); BiomeDiagram = new BiomeMap(Seed); } public World(string name, IChunkProvider chunkProvider) : this(name) { ChunkProvider = chunkProvider; } public World(string name, int seed, IChunkProvider chunkProvider) : this(name, chunkProvider) { Seed = seed; BiomeDiagram = new BiomeMap(Seed); } public static World LoadWorld(string baseDirectory) { if (!Directory.Exists(baseDirectory)) throw new DirectoryNotFoundException(); var world = new World(Path.GetFileName(baseDirectory)); world.BaseDirectory = baseDirectory; if (File.Exists(Path.Combine(baseDirectory, "manifest.nbt"))) { var file = new NbtFile(Path.Combine(baseDirectory, "manifest.nbt")); world.SpawnPoint = new Coordinates3D(file.RootTag["SpawnPoint"]["X"].IntValue, file.RootTag["SpawnPoint"]["Y"].IntValue, file.RootTag["SpawnPoint"]["Z"].IntValue); world.Seed = file.RootTag["Seed"].IntValue; var providerName = file.RootTag["ChunkProvider"].StringValue; var provider = (IChunkProvider)Activator.CreateInstance(Type.GetType(providerName), world); if (file.RootTag.Contains("Name")) world.Name = file.RootTag["Name"].StringValue; world.ChunkProvider = provider; } return world; } /// <summary> /// Finds a chunk that contains the specified block coordinates. /// </summary> public IChunk FindChunk(Coordinates3D coordinates) { IChunk chunk; FindBlockPosition(coordinates, out chunk); return chunk; } public IChunk GetChunk(Coordinates2D coordinates) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ)); return region.GetChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32)); } public void GenerateChunk(Coordinates2D coordinates) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ)); region.GenerateChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32)); } public void SetChunk(Coordinates2D coordinates, Chunk chunk) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ)); lock (region) { chunk.IsModified = true; region.SetChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32), chunk); } } public void UnloadRegion(Coordinates2D coordinates) { lock (Regions) { Regions[coordinates].Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(coordinates))); Regions.Remove(coordinates); } } public void UnloadChunk(Coordinates2D coordinates) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var regionPosition = new Coordinates2D(regionX, regionZ); if (!Regions.ContainsKey(regionPosition)) throw new ArgumentOutOfRangeException("coordinates"); Regions[regionPosition].UnloadChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32)); } public byte GetBlockID(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetBlockID(coordinates); } public byte GetMetadata(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetMetadata(coordinates); } public byte GetSkyLight(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetSkyLight(coordinates); } public byte GetBlockLight(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetBlockLight(coordinates); } public NbtCompound GetTileEntity(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetTileEntity(coordinates); } public BlockDescriptor GetBlockData(Coordinates3D coordinates) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); return GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); } public void SetBlockData(Coordinates3D coordinates, BlockDescriptor descriptor) { // TODO: Figure out the best way to handle light in this scenario IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); var old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); chunk.SetBlockID(adjustedCoordinates, descriptor.ID); chunk.SetMetadata(adjustedCoordinates, descriptor.Metadata); if (BlockChanged != null) BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates))); } private BlockDescriptor GetBlockDataFromChunk(Coordinates3D adjustedCoordinates, IChunk chunk, Coordinates3D coordinates) { return new BlockDescriptor { ID = chunk.GetBlockID(adjustedCoordinates), Metadata = chunk.GetMetadata(adjustedCoordinates), BlockLight = chunk.GetBlockLight(adjustedCoordinates), SkyLight = chunk.GetSkyLight(adjustedCoordinates), Coordinates = coordinates }; } public void SetBlockID(Coordinates3D coordinates, byte value) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); BlockDescriptor old = new BlockDescriptor(); if (BlockChanged != null) old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); chunk.SetBlockID(adjustedCoordinates, value); if (BlockChanged != null) BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates))); } public void SetMetadata(Coordinates3D coordinates, byte value) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); BlockDescriptor old = new BlockDescriptor(); if (BlockChanged != null) old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); chunk.SetMetadata(adjustedCoordinates, value); if (BlockChanged != null) BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates))); } public void SetSkyLight(Coordinates3D coordinates, byte value) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); chunk.SetSkyLight(coordinates, value); } public void SetBlockLight(Coordinates3D coordinates, byte value) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); chunk.SetBlockLight(coordinates, value); } public void SetTileEntity(Coordinates3D coordinates, NbtCompound value) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); chunk.SetTileEntity(coordinates, value); } public void Save() { lock (Regions) { foreach (var region in Regions) region.Value.Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(region.Key))); } var file = new NbtFile(); file.RootTag.Add(new NbtCompound("SpawnPoint", new[] { new NbtInt("X", this.SpawnPoint.X), new NbtInt("Y", this.SpawnPoint.Y), new NbtInt("Z", this.SpawnPoint.Z) })); file.RootTag.Add(new NbtInt("Seed", this.Seed)); file.RootTag.Add(new NbtString("ChunkProvider", this.ChunkProvider.GetType().FullName)); file.RootTag.Add(new NbtString("Name", Name)); file.SaveToFile(Path.Combine(this.BaseDirectory, "manifest.nbt"), NbtCompression.ZLib); } public void Save(string path) { if (!Directory.Exists(path)) Directory.CreateDirectory(path); BaseDirectory = path; Save(); } public Coordinates3D FindBlockPosition(Coordinates3D coordinates, out IChunk chunk) { if (coordinates.Y < 0 || coordinates.Y >= Chunk.Height) throw new ArgumentOutOfRangeException("coordinates", "Coordinates are out of range"); var chunkX = (int)Math.Floor((double)coordinates.X / Chunk.Width); var chunkZ = (int)Math.Floor((double)coordinates.Z / Chunk.Depth); chunk = GetChunk(new Coordinates2D(chunkX, chunkZ)); return new Coordinates3D( (coordinates.X - chunkX * Chunk.Width) % Chunk.Width, coordinates.Y, (coordinates.Z - chunkZ * Chunk.Depth) % Chunk.Depth); } public bool IsValidPosition(Coordinates3D position) { return position.Y >= 0 && position.Y <= 255; } private Region LoadOrGenerateRegion(Coordinates2D coordinates) { if (Regions.ContainsKey(coordinates)) return (Region)Regions[coordinates]; Region region; if (BaseDirectory != null) { var file = Path.Combine(BaseDirectory, Region.GetRegionFileName(coordinates)); if (File.Exists(file)) region = new Region(coordinates, this, file); else region = new Region(coordinates, this); } else region = new Region(coordinates, this); lock (Regions) Regions[coordinates] = region; return region; } public void Dispose() { foreach (var region in Regions) region.Value.Dispose(); } } }
// 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.Security; using System.Text; using Microsoft.Xml; using System.Diagnostics.CodeAnalysis; using System.ServiceModel; namespace System.Runtime.Diagnostics { internal abstract class DiagnosticTraceBase { //Diagnostics trace protected const string DefaultTraceListenerName = "Default"; protected const string TraceRecordVersion = "http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord"; protected static string AppDomainFriendlyName = String.Empty; private const ushort TracingEventLogCategory = 4; private object _thisLock; protected string TraceSourceName; [Fx.Tag.SecurityNote(Critical = "This determines the event source name.")] [SecurityCritical] private string _eventSourceName; public DiagnosticTraceBase(string traceSourceName) { _thisLock = new object(); this.TraceSourceName = traceSourceName; this.LastFailure = DateTime.MinValue; } protected DateTime LastFailure { get; set; } protected string EventSourceName { [Fx.Tag.SecurityNote(Critical = "Access critical eventSourceName field", Safe = "Doesn't leak info\\resources")] [SecuritySafeCritical] get { return _eventSourceName; } [Fx.Tag.SecurityNote(Critical = "This determines the event source name.")] [SecurityCritical] set { _eventSourceName = value; } } public bool TracingEnabled { get { return false; } } protected static string ProcessName { [Fx.Tag.SecurityNote(Critical = "Satisfies a LinkDemand for 'PermissionSetAttribute' on type 'Process' when calling method GetCurrentProcess", Safe = "Does not leak any resource and has been reviewed")] [SecuritySafeCritical] get { string retval = null; return retval; } } protected static int ProcessId { [Fx.Tag.SecurityNote(Critical = "Satisfies a LinkDemand for 'PermissionSetAttribute' on type 'Process' when calling method GetCurrentProcess", Safe = "Does not leak any resource and has been reviewed")] [SecuritySafeCritical] get { int retval = -1; return retval; } } //only used for exceptions, perf is not important public static string XmlEncode(string text) { if (string.IsNullOrEmpty(text)) { return text; } int len = text.Length; StringBuilder encodedText = new StringBuilder(len + 8); //perf optimization, expecting no more than 2 > characters for (int i = 0; i < len; ++i) { char ch = text[i]; switch (ch) { case '<': encodedText.Append("&lt;"); break; case '>': encodedText.Append("&gt;"); break; case '&': encodedText.Append("&amp;"); break; default: encodedText.Append(ch); break; } } return encodedText.ToString(); } [Fx.Tag.SecurityNote(Critical = "Sets global event handlers for the AppDomain", Safe = "Doesn't leak resources\\Information")] [SecuritySafeCritical] [SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands, Justification = "SecuritySafeCritical method, Does not expose critical resources returned by methods with Link Demands")] protected void AddDomainEventHandlersForCleanup() { } private void ExitOrUnloadEventHandler(object sender, EventArgs e) { } protected static string CreateSourceString(object source) { var traceSourceStringProvider = source as ITraceSourceStringProvider; if (traceSourceStringProvider != null) { return traceSourceStringProvider.GetSourceString(); } return CreateDefaultSourceString(source); } internal static string CreateDefaultSourceString(object source) { if (source == null) { throw new ArgumentNullException("source"); } return String.Format(CultureInfo.CurrentCulture, "{0}/{1}", source.GetType().ToString(), source.GetHashCode()); } protected static void AddExceptionToTraceString(XmlWriter xml, Exception exception) { xml.WriteElementString(DiagnosticStrings.ExceptionTypeTag, XmlEncode(exception.GetType().AssemblyQualifiedName)); xml.WriteElementString(DiagnosticStrings.MessageTag, XmlEncode(exception.Message)); xml.WriteElementString(DiagnosticStrings.StackTraceTag, XmlEncode(StackTraceString(exception))); xml.WriteElementString(DiagnosticStrings.ExceptionStringTag, XmlEncode(exception.ToString())); if (exception.Data != null && exception.Data.Count > 0) { xml.WriteStartElement(DiagnosticStrings.DataItemsTag); foreach (object dataItem in exception.Data.Keys) { xml.WriteStartElement(DiagnosticStrings.DataTag); xml.WriteElementString(DiagnosticStrings.KeyTag, XmlEncode(dataItem.ToString())); xml.WriteElementString(DiagnosticStrings.ValueTag, XmlEncode(exception.Data[dataItem].ToString())); xml.WriteEndElement(); } xml.WriteEndElement(); } if (exception.InnerException != null) { xml.WriteStartElement(DiagnosticStrings.InnerExceptionTag); AddExceptionToTraceString(xml, exception.InnerException); xml.WriteEndElement(); } } protected static string StackTraceString(Exception exception) { string retval = exception.StackTrace; return retval; } // Duplicate code from System.ServiceModel.Diagnostics [Fx.Tag.SecurityNote(Critical = "Calls unsafe methods, UnsafeCreateEventLogger and UnsafeLogEvent.", Safe = "Event identities cannot be spoofed as they are constants determined inside the method, Demands the same permission that is asserted by the unsafe method.")] [SecuritySafeCritical] [SuppressMessage(FxCop.Category.Security, FxCop.Rule.SecureAsserts, Justification = "Should not demand permission that is asserted by the EtwProvider ctor.")] protected void LogTraceFailure(string traceString, Exception exception) { } public static Guid ActivityId { [Fx.Tag.SecurityNote(Critical = "gets the CorrelationManager, which does a LinkDemand for UnmanagedCode", Safe = "only uses the CM to get the ActivityId, which is not protected data, doesn't leak the CM")] [SecuritySafeCritical] [SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands, Justification = "SecuritySafeCriticial method")] get { throw ExceptionHelper.PlatformNotSupported(); } [Fx.Tag.SecurityNote(Critical = "gets the CorrelationManager, which does a LinkDemand for UnmanagedCode", Safe = "only uses the CM to get the ActivityId, which is not protected data, doesn't leak the CM")] [SecuritySafeCritical] set { throw ExceptionHelper.PlatformNotSupported(); } } #pragma warning restore 56500 public abstract bool IsEnabled(); } }
// 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.IO; using System.Linq; using Microsoft.CSharp; using Microsoft.VisualBasic; using Xunit; namespace System.CodeDom.Compiler.Tests { public class CodeDomProviderTests { [Fact] public void GetAllCompilerInfo_ReturnsMinimumOfCSharpAndVB() { Type[] compilerInfos = CodeDomProvider.GetAllCompilerInfo().Where(provider => provider.IsCodeDomProviderTypeValid).Select(provider => provider.CodeDomProviderType).ToArray(); Assert.True(compilerInfos.Length >= 2); Assert.Contains(typeof(CSharpCodeProvider), compilerInfos); Assert.Contains(typeof(VBCodeProvider), compilerInfos); } [Fact] public void FileExtension_ReturnsEmpty() { Assert.Empty(new NullProvider().FileExtension); } [Fact] public void LanguageOptions_ReturnsNone() { Assert.Equal(LanguageOptions.None, new NullProvider().LanguageOptions); } [Fact] public void CreateGenerator_ReturnsOverridenGenerator() { #pragma warning disable 0618 CustomProvider provider = new CustomProvider(); Assert.Same(provider.CreateGenerator(), provider.CreateGenerator("fileName")); Assert.Same(provider.CreateGenerator(), provider.CreateGenerator(new StringWriter())); #pragma warning restore 0618 } [Fact] public void CreateParser_ReturnsNull() { #pragma warning disable 0618 Assert.Null(new NoParserProvider().CreateParser()); #pragma warning restore 0618 } [Fact] public void GetConverter_ReturnsNotNull() { Assert.NotNull(new CustomProvider().GetConverter(typeof(int))); } [Fact] public void GetConverter_NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("type", () => new CustomProvider().GetConverter(null)); } public static IEnumerable<object[]> CreateProvider_String_TestData() { yield return new object[] { "c#", "cs" }; yield return new object[] { " c# ", "cs" }; yield return new object[] { "cs", "cs" }; yield return new object[] { "csharp", "cs" }; yield return new object[] { "CsHaRp", "cs" }; yield return new object[] { "vb", "vb" }; yield return new object[] { "vbs", "vb" }; yield return new object[] { "visualbasic", "vb" }; yield return new object[] { "vbscript", "vb" }; yield return new object[] { "VBSCRIPT", "vb" }; } [Theory] [MemberData(nameof(CreateProvider_String_TestData))] public void CreateProvider_String(string language, string expectedFileExtension) { CodeDomProvider provider = CodeDomProvider.CreateProvider(language); Assert.Equal(expectedFileExtension, provider.FileExtension); } public static IEnumerable<object[]> CreateProvider_String_Dictionary_TestData() { yield return new object[] { "cs", new Dictionary<string, string>(), "cs" }; yield return new object[] { "cs", new Dictionary<string, string>() { { "option", "value" } }, "cs" }; yield return new object[] { "cs", new Dictionary<string, string>() { { "option1", "value1" }, { "option2", "value2" } }, "cs" }; yield return new object[] { "cs", new Dictionary<string, string>() { { "option", null } }, "cs" }; yield return new object[] { "vb", new Dictionary<string, string>(), "vb" }; yield return new object[] { "vb", new Dictionary<string, string>() { { "option", "value" } }, "vb" }; yield return new object[] { "vb", new Dictionary<string, string>() { { "option1", "value1" }, { "option2", "value2" } }, "vb" }; yield return new object[] { "vb", new Dictionary<string, string>() { { "option", null } }, "vb" }; } [Theory] [MemberData(nameof(CreateProvider_String_Dictionary_TestData))] public void CreateProvider_String_Dictionary(string language, Dictionary<string, string> providerOptions, string expectedFileExtension) { CodeDomProvider provider = CodeDomProvider.CreateProvider(language, providerOptions); Assert.Equal(expectedFileExtension, provider.FileExtension); } [Fact] public void CreateProvider_NullProviderOptions_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("providerOptions", () => CodeDomProvider.CreateProvider("cs", null)); AssertExtensions.Throws<ArgumentNullException>("providerOptions", () => CodeDomProvider.CreateProvider("vb", null)); } [Fact] public void CreateProvider_NullLanguage_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.CreateProvider(null)); AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.CreateProvider(null, new Dictionary<string, string>())); } [Theory] [InlineData("")] [InlineData(".cs")] [InlineData("no-such-language")] public void CreateProvider_NoSuchLanguage_ThrowsConfigurationErrorsException(string language) { Exception ex1 = Assert.ThrowsAny<Exception>(() => CodeDomProvider.CreateProvider(language)); AssertIsConfigurationErrorsException(ex1); Exception ex2 = Assert.ThrowsAny<Exception>(() => CodeDomProvider.CreateProvider(language, new Dictionary<string, string>())); AssertIsConfigurationErrorsException(ex2); } [Theory] [InlineData(" cs ", true)] [InlineData("cs", true)] [InlineData("c#", true)] [InlineData("csharp", true)] [InlineData("CsHaRp", true)] [InlineData("vb", true)] [InlineData("vbs", true)] [InlineData("visualbasic", true)] [InlineData("vbscript", true)] [InlineData("VB", true)] [InlineData("", false)] [InlineData(".cs", false)] [InlineData("no-such-language", false)] public void IsDefinedLanguage_ReturnsExpected(string language, bool expected) { Assert.Equal(expected, CodeDomProvider.IsDefinedLanguage(language)); } [Fact] public void IsDefinedLanguage_NullLanguage_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.IsDefinedLanguage(null)); } [Theory] [InlineData("cs", "c#")] [InlineData(" cs ", "c#")] [InlineData(".cs", "c#")] [InlineData("Cs", "c#")] [InlineData("cs", "c#")] [InlineData("vb", "vb")] [InlineData(".vb", "vb")] [InlineData("VB", "vb")] public void GetLanguageFromExtension_ReturnsExpected(string extension, string expected) { Assert.Equal(expected, CodeDomProvider.GetLanguageFromExtension(extension)); } [Fact] public void GetLanguageFromExtension_NullExtension_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("extension", () => CodeDomProvider.GetLanguageFromExtension(null)); } [Theory] [InlineData("")] [InlineData("c#")] [InlineData("no-such-extension")] public void GetLanguageFromExtension_NoSuchExtension_ThrowsConfigurationErrorsException(string extension) { Exception ex = Assert.ThrowsAny<Exception>(() => CodeDomProvider.GetLanguageFromExtension(extension)); AssertIsConfigurationErrorsException(ex); } [Theory] [InlineData("cs", true)] [InlineData(".cs", true)] [InlineData("Cs", true)] [InlineData("cs", true)] [InlineData("vb", true)] [InlineData(".vb", true)] [InlineData("VB", true)] [InlineData("", false)] [InlineData("c#", false)] [InlineData("no-such-extension", false)] public void IsDefinedExtension_ReturnsExpected(string extension, bool expected) { Assert.Equal(expected, CodeDomProvider.IsDefinedExtension(extension)); } [Fact] public void IsDefinedExtension_NullExtension_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("extension", () => CodeDomProvider.IsDefinedExtension(null)); } [Theory] [InlineData(" cs ", typeof(CSharpCodeProvider))] [InlineData("cs", typeof(CSharpCodeProvider))] [InlineData("c#", typeof(CSharpCodeProvider))] [InlineData("csharp", typeof(CSharpCodeProvider))] [InlineData("CsHaRp", typeof(CSharpCodeProvider))] [InlineData("vb", typeof(VBCodeProvider))] [InlineData("vbs", typeof(VBCodeProvider))] [InlineData("visualbasic", typeof(VBCodeProvider))] [InlineData("vbscript", typeof(VBCodeProvider))] [InlineData("VB", typeof(VBCodeProvider))] public void GetCompilerInfo_ReturnsExpected(string language, Type expectedProviderType) { Assert.Equal(expectedProviderType, CodeDomProvider.GetCompilerInfo(language).CodeDomProviderType); } [Fact] public void GetCompilerInfo_NullLanguage_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.GetCompilerInfo(null)); } [Theory] [InlineData("")] [InlineData(".cs")] [InlineData("no-such-extension")] public void GetCompilerInfo_NoSuchExtension_ThrowsKeyNotFoundException(string language) { Exception ex = Assert.ThrowsAny<Exception>(() => CodeDomProvider.GetCompilerInfo(language)); AssertIsConfigurationErrorsException(ex); } [Fact] public void CompileAssemblyFromDom_CallsCompilerMethod() { AssertExtensions.Throws<ArgumentException>(null, () => new CustomProvider().CompileAssemblyFromDom(new CompilerParameters())); } [Fact] public void CompileAssemblyFromDom_NullCompiler_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CompileAssemblyFromDom(new CompilerParameters())); } [Fact] public void CompileAssemblyFromFile_CallsCompilerMethod() { AssertExtensions.Throws<ArgumentNullException>("2", () => new CustomProvider().CompileAssemblyFromFile(new CompilerParameters())); } [Fact] public void CompileAssemblyFromFile_NullCompiler_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CompileAssemblyFromFile(new CompilerParameters())); } [Fact] public void CompileAssemblyFromSource_CallsCompilerMethod() { AssertExtensions.Throws<ArgumentOutOfRangeException>("3", () => new CustomProvider().CompileAssemblyFromSource(new CompilerParameters())); } [Fact] public void CompileAssemblyFromSource_NullCompiler_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CompileAssemblyFromSource(new CompilerParameters())); } [Fact] public void CreateEscapedIdentifier_CallsGeneratorMethod() { AssertExtensions.Throws<ArgumentException>(null, () => new CustomProvider().CreateEscapedIdentifier("value")); } [Fact] public void CreateEscapedIdentifier_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CreateEscapedIdentifier("value")); } [Fact] public void CreateValidIdentifier_CallsGeneratorMethod() { AssertExtensions.Throws<ArgumentNullException>("2", () => new CustomProvider().CreateValidIdentifier("value")); } [Fact] public void CreateValidIdentifier_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CreateValidIdentifier("value")); } [Fact] public void GenerateCodeFromCompileUnit_CallsGeneratorMethod() { AssertExtensions.Throws<ArgumentOutOfRangeException>("3", () => new CustomProvider().GenerateCodeFromCompileUnit(new CodeCompileUnit(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromCompileUnit_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromCompileUnit(new CodeCompileUnit(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromExpression_CallsGeneratorMethod() { Assert.Throws<ArithmeticException>(() => new CustomProvider().GenerateCodeFromExpression(new CodeExpression(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromExpression_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromExpression(new CodeExpression(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromNamespace_CallsGeneratorMethod() { Assert.Throws<ArrayTypeMismatchException>(() => new CustomProvider().GenerateCodeFromNamespace(new CodeNamespace(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromNamespace_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromNamespace(new CodeNamespace(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromStatement_CallsGeneratorMethod() { Assert.Throws<BadImageFormatException>(() => new CustomProvider().GenerateCodeFromStatement(new CodeStatement(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromStatement_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromStatement(new CodeStatement(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromType_CallsGeneratorMethod() { Assert.Throws<CannotUnloadAppDomainException>(() => new CustomProvider().GenerateCodeFromType(new CodeTypeDeclaration(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromType_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromType(new CodeTypeDeclaration(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GetTypeOutput_CallsGeneratorMethod() { Assert.Throws<DataMisalignedException>(() => new CustomProvider().GetTypeOutput(new CodeTypeReference())); } [Fact] public void GetTypeOutput_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GetTypeOutput(new CodeTypeReference())); } [Fact] public void IsValidIdentifier_CallsGeneratorMethod() { Assert.Throws<DirectoryNotFoundException>(() => new CustomProvider().IsValidIdentifier("value")); } [Fact] public void IsValidIdentifier_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().IsValidIdentifier("value")); } [Fact] public void Supports_CallsGeneratorMethod() { Assert.Throws<DivideByZeroException>(() => new CustomProvider().Supports(GeneratorSupport.ArraysOfArrays)); } [Fact] public void Supports_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().Supports(GeneratorSupport.ArraysOfArrays)); } [Fact] public void GenerateCodeFromMember_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromMember(new CodeTypeMember(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void Parse_CallsParserMethod() { Assert.Same(CustomParser.CompileUnit, new CustomProvider().Parse(new StringReader("abc"))); } [Fact] public void Parse_NullParser_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().Parse(new StringReader("abc"))); } private static void AssertIsConfigurationErrorsException(Exception ex) { if (!PlatformDetection.IsNetNative) // Can't do internal Reflection { Assert.Equal("ConfigurationErrorsException", ex.GetType().Name); } } protected class NullProvider : CodeDomProvider { #pragma warning disable 0672 public override ICodeCompiler CreateCompiler() => null; public override ICodeParser CreateParser() => null; public override ICodeGenerator CreateGenerator() => null; #pragma warning restore 067 } protected class NoParserProvider : CodeDomProvider { public override ICodeCompiler CreateCompiler() => null; public override ICodeGenerator CreateGenerator() => null; } protected class CustomProvider : CodeDomProvider { private ICodeCompiler _compiler = new CustomCompiler(); public override ICodeCompiler CreateCompiler() => _compiler; private ICodeGenerator _generator = new CustomGenerator(); public override ICodeGenerator CreateGenerator() => _generator; private ICodeParser _parser = new CustomParser(); public override ICodeParser CreateParser() => _parser; } protected class CustomCompiler : ICodeCompiler { public CompilerResults CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit compilationUnit) => null; public CompilerResults CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] compilationUnits) { throw new ArgumentException("1"); } public CompilerResults CompileAssemblyFromFile(CompilerParameters options, string fileName) => null; public CompilerResults CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) { throw new ArgumentNullException("2"); } public CompilerResults CompileAssemblyFromSource(CompilerParameters options, string source) => null; public CompilerResults CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) { throw new ArgumentOutOfRangeException("3"); } } protected class CustomGenerator : ICodeGenerator { public string CreateEscapedIdentifier(string value) { throw new ArgumentException("1"); } public string CreateValidIdentifier(string value) { throw new ArgumentNullException("2"); } public void GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, CodeGeneratorOptions o) { throw new ArgumentOutOfRangeException("3"); } public void GenerateCodeFromExpression(CodeExpression e, TextWriter w, CodeGeneratorOptions o) { throw new ArithmeticException("4"); } public void GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, CodeGeneratorOptions o) { throw new ArrayTypeMismatchException("5"); } public void GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o) { throw new BadImageFormatException("6"); } public void GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o) { throw new CannotUnloadAppDomainException("7"); } public string GetTypeOutput(CodeTypeReference type) { throw new DataMisalignedException("8"); } public bool IsValidIdentifier(string value) { throw new DirectoryNotFoundException("9"); } public bool Supports(GeneratorSupport supports) { throw new DivideByZeroException("10"); } public void ValidateIdentifier(string value) { throw new DllNotFoundException("11"); } } protected class CustomParser : ICodeParser { public static CodeCompileUnit CompileUnit { get; } = new CodeCompileUnit(); public CodeCompileUnit Parse(TextReader codeStream) => CompileUnit; } } }
using System; using Server; using Server.Gumps; using Server.Network; namespace Server.Gumps { public class GoGump : Gump { public static readonly LocationTree Felucca = new LocationTree( "felucca.xml", Map.Felucca ); public static readonly LocationTree Trammel = new LocationTree( "trammel.xml", Map.Trammel ); public static readonly LocationTree Ilshenar = new LocationTree( "ilshenar.xml", Map.Ilshenar ); public static readonly LocationTree Malas = new LocationTree( "malas.xml", Map.Malas ); public static readonly LocationTree Tokuno = new LocationTree( "tokuno.xml", Map.Tokuno ); public static readonly LocationTree TerMur = new LocationTree( "termur.xml", Map.TerMur ); public static bool OldStyle = PropsConfig.OldStyle; public static readonly int GumpOffsetX = PropsConfig.GumpOffsetX; public static readonly int GumpOffsetY = PropsConfig.GumpOffsetY; public static readonly int TextHue = PropsConfig.TextHue; public static readonly int TextOffsetX = PropsConfig.TextOffsetX; public static readonly int OffsetGumpID = PropsConfig.OffsetGumpID; public static readonly int HeaderGumpID = PropsConfig.HeaderGumpID; public static readonly int EntryGumpID = PropsConfig.EntryGumpID; public static readonly int BackGumpID = PropsConfig.BackGumpID; public static readonly int SetGumpID = PropsConfig.SetGumpID; public static readonly int SetWidth = PropsConfig.SetWidth; public static readonly int SetOffsetX = PropsConfig.SetOffsetX, SetOffsetY = PropsConfig.SetOffsetY; public static readonly int SetButtonID1 = PropsConfig.SetButtonID1; public static readonly int SetButtonID2 = PropsConfig.SetButtonID2; public static readonly int PrevWidth = PropsConfig.PrevWidth; public static readonly int PrevOffsetX = PropsConfig.PrevOffsetX, PrevOffsetY = PropsConfig.PrevOffsetY; public static readonly int PrevButtonID1 = PropsConfig.PrevButtonID1; public static readonly int PrevButtonID2 = PropsConfig.PrevButtonID2; public static readonly int NextWidth = PropsConfig.NextWidth; public static readonly int NextOffsetX = PropsConfig.NextOffsetX, NextOffsetY = PropsConfig.NextOffsetY; public static readonly int NextButtonID1 = PropsConfig.NextButtonID1; public static readonly int NextButtonID2 = PropsConfig.NextButtonID2; public static readonly int OffsetSize = PropsConfig.OffsetSize; public static readonly int EntryHeight = PropsConfig.EntryHeight; public static readonly int BorderSize = PropsConfig.BorderSize; private static bool PrevLabel = false, NextLabel = false; private static readonly int PrevLabelOffsetX = PrevWidth + 1; private static readonly int PrevLabelOffsetY = 0; private static readonly int NextLabelOffsetX = -29; private static readonly int NextLabelOffsetY = 0; private static readonly int EntryWidth = 180; private static readonly int EntryCount = 15; private static readonly int TotalWidth = OffsetSize + EntryWidth + OffsetSize + SetWidth + OffsetSize; private static readonly int TotalHeight = OffsetSize + ((EntryHeight + OffsetSize) * (EntryCount + 1)); private static readonly int BackWidth = BorderSize + TotalWidth + BorderSize; private static readonly int BackHeight = BorderSize + TotalHeight + BorderSize; public static void DisplayTo( Mobile from ) { LocationTree tree; if ( from.Map == Map.Ilshenar ) tree = Ilshenar; else if ( from.Map == Map.Felucca ) tree = Felucca; else if ( from.Map == Map.Trammel ) tree = Trammel; else if ( from.Map == Map.Malas ) tree = Malas; else if ( from.Map == Map.Tokuno ) tree = Tokuno; else tree = TerMur; ParentNode branch = null; tree.LastBranch.TryGetValue( from, out branch ); if ( branch == null ) branch = tree.Root; if ( branch != null ) from.SendGump( new GoGump( 0, from, tree, branch ) ); } private LocationTree m_Tree; private ParentNode m_Node; private int m_Page; private GoGump( int page, Mobile from, LocationTree tree, ParentNode node ) : base( 50, 50 ) { from.CloseGump( typeof( GoGump ) ); tree.LastBranch[from] = node; m_Page = page; m_Tree = tree; m_Node = node; int x = BorderSize + OffsetSize; int y = BorderSize + OffsetSize; int count = node.Children.Length - (page * EntryCount); if ( count < 0 ) count = 0; else if ( count > EntryCount ) count = EntryCount; int totalHeight = OffsetSize + ((EntryHeight + OffsetSize) * (count + 1)); AddPage( 0 ); AddBackground( 0, 0, BackWidth, BorderSize + totalHeight + BorderSize, BackGumpID ); AddImageTiled( BorderSize, BorderSize, TotalWidth - (OldStyle ? SetWidth + OffsetSize : 0), totalHeight, OffsetGumpID ); if ( OldStyle ) AddImageTiled( x, y, TotalWidth - (OffsetSize * 3) - SetWidth, EntryHeight, HeaderGumpID ); else AddImageTiled( x, y, PrevWidth, EntryHeight, HeaderGumpID ); if ( node.Parent != null ) { AddButton( x + PrevOffsetX, y + PrevOffsetY, PrevButtonID1, PrevButtonID2, 1, GumpButtonType.Reply, 0 ); if ( PrevLabel ) AddLabel( x + PrevLabelOffsetX, y + PrevLabelOffsetY, TextHue, "Previous" ); } x += PrevWidth + OffsetSize; int emptyWidth = TotalWidth - (PrevWidth * 2) - NextWidth - (OffsetSize * 5) - (OldStyle ? SetWidth + OffsetSize : 0); if ( !OldStyle ) AddImageTiled( x - (OldStyle ? OffsetSize : 0), y, emptyWidth + (OldStyle ? OffsetSize * 2 : 0), EntryHeight, EntryGumpID ); AddHtml( x + TextOffsetX, y, emptyWidth - TextOffsetX, EntryHeight, String.Format( "<center>{0}</center>", node.Name ), false, false ); x += emptyWidth + OffsetSize; if ( OldStyle ) AddImageTiled( x, y, TotalWidth - (OffsetSize * 3) - SetWidth, EntryHeight, HeaderGumpID ); else AddImageTiled( x, y, PrevWidth, EntryHeight, HeaderGumpID ); if ( page > 0 ) { AddButton( x + PrevOffsetX, y + PrevOffsetY, PrevButtonID1, PrevButtonID2, 2, GumpButtonType.Reply, 0 ); if ( PrevLabel ) AddLabel( x + PrevLabelOffsetX, y + PrevLabelOffsetY, TextHue, "Previous" ); } x += PrevWidth + OffsetSize; if ( !OldStyle ) AddImageTiled( x, y, NextWidth, EntryHeight, HeaderGumpID ); if ( (page + 1) * EntryCount < node.Children.Length ) { AddButton( x + NextOffsetX, y + NextOffsetY, NextButtonID1, NextButtonID2, 3, GumpButtonType.Reply, 1 ); if ( NextLabel ) AddLabel( x + NextLabelOffsetX, y + NextLabelOffsetY, TextHue, "Next" ); } for ( int i = 0, index = page * EntryCount; i < EntryCount && index < node.Children.Length; ++i, ++index ) { x = BorderSize + OffsetSize; y += EntryHeight + OffsetSize; object child = node.Children[index]; string name = ""; if ( child is ParentNode ) name = ((ParentNode)child).Name; else if ( child is ChildNode ) name = ((ChildNode)child).Name; AddImageTiled( x, y, EntryWidth, EntryHeight, EntryGumpID ); AddLabelCropped( x + TextOffsetX, y, EntryWidth - TextOffsetX, EntryHeight, TextHue, name ); x += EntryWidth + OffsetSize; if ( SetGumpID != 0 ) AddImageTiled( x, y, SetWidth, EntryHeight, SetGumpID ); AddButton( x + SetOffsetX, y + SetOffsetY, SetButtonID1, SetButtonID2, index + 4, GumpButtonType.Reply, 0 ); } } public override void OnResponse( NetState state, RelayInfo info ) { Mobile from = state.Mobile; switch ( info.ButtonID ) { case 1: { if ( m_Node.Parent != null ) from.SendGump( new GoGump( 0, from, m_Tree, m_Node.Parent ) ); break; } case 2: { if ( m_Page > 0 ) from.SendGump( new GoGump( m_Page - 1, from, m_Tree, m_Node ) ); break; } case 3: { if ( (m_Page + 1) * EntryCount < m_Node.Children.Length ) from.SendGump( new GoGump( m_Page + 1, from, m_Tree, m_Node ) ); break; } default: { int index = info.ButtonID - 4; if ( index >= 0 && index < m_Node.Children.Length ) { object o = m_Node.Children[index]; if ( o is ParentNode ) { from.SendGump( new GoGump( 0, from, m_Tree, (ParentNode)o ) ); } else { ChildNode n = (ChildNode)o; from.MoveToWorld( n.Location, m_Tree.Map ); } } break; } } } } }
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 WebApiSoup.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <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; } } }
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * 8/2012 directly ported to c# - [email protected] (James Tuley) * */ using System; using System.Globalization; using System.IO; using System.Linq; using NUnit.Framework; using Keyczar; using Keyczar.Unofficial; namespace KeyczarTest { [TestFixture] public class ToolTest : BaseHelper { private String TEST_DATA = Path.GetTempPath(); private string CERTIFICATE_DATA = Path.Combine("remote-testdata", "existing-data", "dotnet", "certificates"); private static String input = "This is some test data"; private static byte[] bigInput = new byte[10000]; [TestCase("zlib")] [TestCase("gzip")] public void TestEncryptCompression(string compress) { string result; var subPath = Util.TestDataPath(TEST_DATA, "compress"); if (Directory.Exists(subPath)) Directory.Delete(subPath, true); result = Util.KeyczarTool(create: null, location: subPath, purpose: "crypt"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool(addkey: null, location: subPath, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); var ptext = Path.Combine(subPath, "ptext"); File.WriteAllBytes(ptext, bigInput); var ctext = Path.Combine(subPath, "ctext"); result = Util.KeyczarTool( usekey: null, location: subPath, file: null, destination: ctext, compression: compress, binary: null, additionalArgs: new[] {ptext} ); var compression = compress == "zlib" ? CompressionType.Zlib : CompressionType.Gzip; using (var crypter = new Crypter(subPath) {Compression = compression}) { using (var write = new MemoryStream()) using (var read = File.OpenRead(ctext)) { crypter.Decrypt(read, write); Expect(write.ToArray(), Is.EqualTo(bigInput)); } Expect(new FileInfo(ctext).Length, Is.LessThan(new FileInfo(ptext).Length)); } } [Test] public void TestImportPublic() { string result; var path = Util.TestDataPath(TEST_DATA, "import"); if (Directory.Exists(path)) Directory.Delete(path, true); result = Util.KeyczarTool(create: null, location: path, purpose: "sign", asymmetric:"rsa"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool("pass", importkey: null, location: path, status: "primary", importlocation: Util.TestDataPath(CERTIFICATE_DATA, "rsa-crypt-pkcs8.pem")); Expect(result, Does.Contain(KeyczarTool.Localized.MsgImportedNewKey)); Directory.Delete(path, true); } [Test] public void TestKeyTypes() { string result; result = Util.KeyczarTool(keytypes: null); Expect(result, Does.Contain("AES_HMAC_SHA1*")); result = Util.KeyczarTool(keytypes: null, unofficial:null); Expect(result, Does.Contain("AES_GCM*")); } [Test] public void TestImportPrivate() { string result; var path = Util.TestDataPath(TEST_DATA, "import"); if (Directory.Exists(path)) Directory.Delete(path, true); result = Util.KeyczarTool(create: null, location: path, purpose: "crypt", asymmetric: "rsa"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool("pass", importkey: null, location: path, status: "primary", importlocation: Util.TestDataPath(CERTIFICATE_DATA, "rsa-crypt-pkcs8.pem")); Expect(result, Does.Contain(KeyczarTool.Localized.MsgImportedNewKey)); Directory.Delete(path, true); } [Test] public void TestOperateOnCryptedKeys() { string result; var path = Util.TestDataPath(TEST_DATA, "crypting"); var pathc = Util.TestDataPath(TEST_DATA, "rsa-crypted"); if (Directory.Exists(path)) Directory.Delete(path, true); if (Directory.Exists(pathc)) Directory.Delete(pathc, true); result = Util.KeyczarTool(create: null, location: path, purpose: "crypt"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool(addkey: null, location: path, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); result = Util.KeyczarTool(create: null, location: pathc, purpose: "crypt", asymmetric: null); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool(addkey: null, location: pathc, crypter: path, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); var pathi = Path.Combine(pathc, "out.pem"); result = Util.KeyczarTool( "pass", "pass", export: null, location: pathc, crypter: path, destination: pathi); Expect(result, Does.Contain(KeyczarTool.Localized.MsgExportedPem)); result = Util.KeyczarTool("pass", importkey: null, location: pathc, status: "primary", crypter: path, importlocation: pathi); Expect(result, Does.Contain(KeyczarTool.Localized.MsgImportedNewKey)); var pathp = Path.Combine(pathc, "export"); result = Util.KeyczarTool( pubkey: null, location: pathc, crypter: path, destination: pathp ); Expect(result, Does.Contain(KeyczarTool.Localized.MsgNewPublicKeySet)); var patho = Path.Combine(pathc, "1.out"); result = Util.KeyczarTool( usekey: null, location: pathc, crypter: path, destination: patho, additionalArgs: new[] {input} ); using (var kcrypter = new Crypter(path)) { using (var eks = KeySet.LayerSecurity(FileSystemKeySet.Creator(pathc), EncryptedKeySet.Creator(kcrypter))){ Expect(eks.Metadata.Encrypted, Is.True); using (var crypter = new Crypter(eks)) { result = crypter.Decrypt((WebBase64)File.ReadAllText(patho)); Expect(result, Is.EqualTo(input)); } } } Directory.Delete(path, true); } [Test] public void TestOperateOnPbeCryptKeys() { string result; var path = Util.TestDataPath(TEST_DATA, "rsa-pbe2"); var pathc = Util.TestDataPath(TEST_DATA, "rsa-crypted2"); if (Directory.Exists(path)) Directory.Delete(path, true); if (Directory.Exists(pathc)) Directory.Delete(pathc, true); result = Util.KeyczarTool(create: null, location: path, purpose: "crypt", unofficial:null); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool("cartman", "cartman", addkey: null, location: path, password: null, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); result = Util.KeyczarTool(create: null, location: pathc, purpose: "crypt", asymmetric: null); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool("cartman", addkey: null, location: pathc, crypter: path, password: null, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); var pathi = Path.Combine(pathc, "out.pem"); result = Util.KeyczarTool( "cartman", "pass", "pass", export: null, location: pathc, password: null, crypter: path, destination: pathi); Expect(result, Does.Contain(KeyczarTool.Localized.MsgExportedPem)); result = Util.KeyczarTool("cartman", "pass", importkey: null, location: pathc, status: "primary", crypter: path, password: null, importlocation: pathi); Expect(result, Does.Contain(KeyczarTool.Localized.MsgImportedNewKey)); var pathp = Path.Combine(pathc, "export"); result = Util.KeyczarTool( "cartman", pubkey: null, location: pathc, crypter: path, password: null, destination: pathp ); Expect(result, Does.Contain(KeyczarTool.Localized.MsgNewPublicKeySet)); var patho = Path.Combine(pathc, "1.out"); result = Util.KeyczarTool( "cartman", usekey: null, location: pathc, crypter: path, password: null, destination: patho, additionalArgs: new[] {input} ); using (var pks = KeySet.LayerSecurity( FileSystemKeySet.Creator(path), PbeKeySet.Creator(() => "cartman" /*hardcoding because this is a test*/))) using (var kcrypter = new Crypter(pks)) { using(var eks = KeySet.LayerSecurity(FileSystemKeySet.Creator(pathc), EncryptedKeySet.Creator(kcrypter))) using (var crypter = new Crypter(eks)) { Expect(pks.Metadata.Encrypted, Is.True); Expect(eks.Metadata.Encrypted, Is.True); result = crypter.Decrypt((WebBase64) File.ReadAllText(patho)); Expect(result, Is.EqualTo(input)); } } Directory.Delete(pathc, true); } [Test] public void TestOperateOnPbeKeys() { string result; var pathc = Util.TestDataPath(TEST_DATA, "rsa-pbe"); if (Directory.Exists(pathc)) Directory.Delete(pathc, true); result = Util.KeyczarTool(create: null, location: pathc, purpose: "crypt", asymmetric: null); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool("cartman", "cartman", addkey: null, location: pathc, password: null, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); var pathi = Path.Combine(pathc, "out.pem"); result = Util.KeyczarTool( "cartman", "pass", "pass", export: null, location: pathc, password: null, destination: pathi); Expect(result, Does.Contain(KeyczarTool.Localized.MsgExportedPem)); result = Util.KeyczarTool("cartman", "pass", importkey: null, location: pathc, status: "primary", password: null, importlocation: pathi); Expect(result, Does.Contain(KeyczarTool.Localized.MsgImportedNewKey)); var pathp = Path.Combine(pathc, "export"); result = Util.KeyczarTool( "cartman", pubkey: null, location: pathc, password: null, destination: pathp ); Expect(result, Does.Contain(KeyczarTool.Localized.MsgNewPublicKeySet)); var patho = Path.Combine(pathc, "1.out"); result = Util.KeyczarTool( "cartman", usekey: null, location: pathc, password: null, destination: patho, additionalArgs: new[] {input} ); using (var pks = KeySet.LayerSecurity( FileSystemKeySet.Creator(pathc), PbeKeySet.Creator(() => "cartman" /*hardcoding because this is a test*/))) using (var crypter = new Crypter(pks)) { Expect(pks.Metadata.Encrypted, Is.True); result = crypter.Decrypt((WebBase64) File.ReadAllText(patho)); Expect(result, Is.EqualTo(input)); } Directory.Delete(pathc, true); } [Test] public void TestPromote() { string result; var path = Util.TestDataPath(TEST_DATA, "promote"); if (Directory.Exists(path)) Directory.Delete(path, true); result = Util.KeyczarTool(create: null, location: path, purpose: "crypt"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool(addkey: null, location: path, status: "active"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); result = Util.KeyczarTool(promote: null, location: path, version: 1); Expect(result, Does.Contain("PRIMARY")); Directory.Delete(path, true); } [Test] public void TestTestForceFail() { string result; var path = Util.TestDataPath(TEST_DATA, "force"); if (Directory.Exists(path)) Directory.Delete(path, true); result = Util.KeyczarTool(create: null, location: path, purpose: "sign", asymmetric: null); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool(addkey: null, location: path, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); result = Util.KeyczarTool(addkey: null, location: path, status: "primary" , type:"RSA_PSS"); Expect(result, Does.Contain(String.Format(KeyczarTool.Localized.MsgMismatchedType, UnofficialKeyType.RSAPrivSign, KeyType.DsaPriv))); result = Util.KeyczarTool("pass", importkey: null, location: path, status: "primary", importlocation: Util.TestDataPath(CERTIFICATE_DATA, "rsa-crypt-pkcs8.pem")); Expect(result, Does.Contain(String.Format(KeyczarTool.Localized.MsgMismatchedType, KeyType.RsaPriv, KeyType.DsaPriv))); } [Test] public void TestTestForceAdd() { string result; var path = Util.TestDataPath(TEST_DATA, "force-add"); if (Directory.Exists(path)) Directory.Delete(path, true); result = Util.KeyczarTool(create: null, location: path, purpose: "sign", asymmetric: null); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool(addkey: null, location: path, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); result = Util.KeyczarTool(addkey: null, location: path, status: "primary", type: "RSA_PSS", force:null); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); result = Util.KeyczarTool("pass", importkey: null, location: path, status: "primary", importlocation: Util.TestDataPath(CERTIFICATE_DATA, "rsa-crypt-pkcs8.pem")); Expect(result, Does.Contain(KeyczarTool.Localized.MsgImportedNewKey)); } [Test] public void TestTestForceImport() { string result; var path = Util.TestDataPath(TEST_DATA, "force-import"); if (Directory.Exists(path)) Directory.Delete(path, true); result = Util.KeyczarTool(create: null, location: path, purpose: "sign", asymmetric: null); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool(addkey: null, location: path, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); result = Util.KeyczarTool("pass", importkey: null, location: path, status: "primary", importlocation: Util.TestDataPath(CERTIFICATE_DATA, "rsa-crypt-pkcs8.pem"), force:null); Expect(result, Does.Contain(KeyczarTool.Localized.MsgImportedNewKey)); result = Util.KeyczarTool(addkey: null, location: path, status: "primary", type: "RSA_PSS"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); } [Test] public void TestInvalid() { string result; var path = Util.TestDataPath(TEST_DATA, "invalid"); if (Directory.Exists(path)) Directory.Delete(path, true); result = Util.KeyczarTool(create: null, location: path, purpose: "crypt"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool(addkey: null, location: path, status: "blah"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgInvalidStatus)); result = Util.KeyczarTool(demote: null, location: path, version: "1"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgUnknownVersion)); result = Util.KeyczarTool(promote: null, location: path, version: "1"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgUnknownVersion)); result = Util.KeyczarTool(revoke: null, location: path, version: "1"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCouldNotRevoke)); //Don't overwrite result = Util.KeyczarTool(create: null, location: path, purpose: "crypt"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgExistingKeySet)); result = Util.KeyczarTool(addkey: null, location: path, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); result = Util.KeyczarTool(demote: null, location: path, version: "1"); Expect(result, Does.Contain("ACTIVE")); result = Util.KeyczarTool(demote: null, location: path, version: "1"); Expect(result, Does.Contain("INACTIVE")); Directory.CreateDirectory(Path.Combine(path, "2.temp")); result = Util.KeyczarTool(addkey: null, location: path, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCouldNotWrite)); Directory.CreateDirectory(Path.Combine(path, "meta.temp")); result = Util.KeyczarTool(demote: null, location: path, version: "1"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCouldNotWrite)); result = Util.KeyczarTool(promote: null, location: path, version: "1"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCouldNotWrite)); result = Util.KeyczarTool(revoke: null, location: path, version: "1"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCouldNotWrite)); Directory.Delete(path, true); } [Test] public void TestAddPadding() { string result; var path = Util.TestDataPath(TEST_DATA, "padding"); var path2 = Util.TestDataPath(TEST_DATA, "padding.public"); if (Directory.Exists(path)) Directory.Delete(path, true); if (Directory.Exists(path2)) Directory.Delete(path2, true); result = Util.KeyczarTool(create: null, location: path, purpose: "crypt", asymmetric: null); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool(addkey: null, location: path, status: "primary", padding: "PKCS", size: "1024"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); var ks = new FileSystemKeySet(path); dynamic key = ks.GetKey(1); Expect((int) key.Size, Is.EqualTo(1024)); Expect((string) key.Padding, Is.EqualTo("PKCS")); result = Util.KeyczarTool(pubkey: null, location: path, destination: path2); Expect(result, Does.Contain(KeyczarTool.Localized.MsgNewPublicKeySet)); var ks2 = new FileSystemKeySet(path); dynamic key2 = ks2.GetKey(1); Expect((int)key2.Size, Is.EqualTo(1024)); Expect((string)key2.Padding, Is.EqualTo("PKCS")); Directory.Delete(path2, true); Directory.Delete(path, true); } [Test] public void TestDemoteRevoke() { string result; var path = Util.TestDataPath(TEST_DATA, "demote"); if (Directory.Exists(path)) Directory.Delete(path, true); result = Util.KeyczarTool(create: null, location: path, purpose: "crypt"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKeySet)); result = Util.KeyczarTool(addkey: null, location: path, status: "primary"); Expect(result, Does.Contain(KeyczarTool.Localized.MsgCreatedKey)); result = Util.KeyczarTool(demote: null, location: path, version: 1); Expect(result, Does.Contain("ACTIVE")); result = Util.KeyczarTool(demote: null, location: path, version: 1); Expect(result, Does.Contain("INACTIVE")); result = Util.KeyczarTool(revoke: null, location: path, version: 1); Expect(result, Does.Contain(KeyczarTool.Localized.MsgRevokedVersion)); var ks = new FileSystemKeySet(path); Expect(ks.Metadata.Versions.Any(), Is.False); Directory.Delete(path, true); } } }
// *********************************************************************** // Copyright (c) 2015 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.TestData.TestCaseAttributeFixture; using NUnit.TestUtilities; #if ASYNC using System.Threading.Tasks; #endif #if NET40 using Task = System.Threading.Tasks.TaskEx; #endif namespace NUnit.Framework.Attributes { [TestFixture] public class TestCaseAttributeTests { [TestCase(12, 3, 4)] [TestCase(12, 2, 6)] [TestCase(12, 4, 3)] public void IntegerDivisionWithResultPassedToTest(int n, int d, int q) { Assert.AreEqual(q, n / d); } [TestCase(12, 3, ExpectedResult = 4)] [TestCase(12, 2, ExpectedResult = 6)] [TestCase(12, 4, ExpectedResult = 3)] public int IntegerDivisionWithResultCheckedByNUnit(int n, int d) { return n / d; } [TestCase(2, 2, ExpectedResult=4)] public double CanConvertIntToDouble(double x, double y) { return x + y; } [TestCase("2.2", "3.3", ExpectedResult = 5.5)] public decimal CanConvertStringToDecimal(decimal x, decimal y) { return x + y; } [TestCase(2.2, 3.3, ExpectedResult = 5.5)] public decimal CanConvertDoubleToDecimal(decimal x, decimal y) { return x + y; } [TestCase(5, 2, ExpectedResult = 7)] public decimal CanConvertIntToDecimal(decimal x, decimal y) { return x + y; } [TestCase(5, 2, ExpectedResult = 7)] public short CanConvertSmallIntsToShort(short x, short y) { return (short)(x + y); } [TestCase(5, 2, ExpectedResult = 7)] public byte CanConvertSmallIntsToByte(byte x, byte y) { return (byte)(x + y); } [TestCase(5, 2, ExpectedResult = 7)] public sbyte CanConvertSmallIntsToSByte(sbyte x, sbyte y) { return (sbyte)(x + y); } [TestCase("MethodCausesConversionOverflow", RunState.NotRunnable)] [TestCase("VoidTestCaseWithExpectedResult", RunState.NotRunnable)] [TestCase("TestCaseWithNullableReturnValueAndNullExpectedResult", RunState.Runnable)] public void TestCaseRunnableState(string methodName, RunState expectedState) { var test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), methodName).Tests[0]; Assert.AreEqual(expectedState, test.RunState); } [TestCase("12-October-1942")] public void CanConvertStringToDateTime(DateTime dt) { Assert.AreEqual(1942, dt.Year); } [TestCase("4:44:15")] public void CanConvertStringToTimeSpan(TimeSpan ts) { Assert.AreEqual(4, ts.Hours); Assert.AreEqual(44, ts.Minutes); Assert.AreEqual(15, ts.Seconds); } [TestCase(null)] public void CanPassNullAsFirstArgument(object a) { Assert.IsNull(a); } [TestCase(new object[] { 1, "two", 3.0 })] [TestCase(new object[] { "zip" })] public void CanPassObjectArrayAsFirstArgument(object[] a) { } [TestCase(new object[] { "a", "b" })] public void CanPassArrayAsArgument(object[] array) { Assert.AreEqual("a", array[0]); Assert.AreEqual("b", array[1]); } [TestCase("a", "b")] public void ArgumentsAreCoalescedInObjectArray(object[] array) { Assert.AreEqual("a", array[0]); Assert.AreEqual("b", array[1]); } [TestCase(1, "b")] public void ArgumentsOfDifferentTypeAreCoalescedInObjectArray(object[] array) { Assert.AreEqual(1, array[0]); Assert.AreEqual("b", array[1]); } [TestCase(ExpectedResult = null)] public object ResultCanBeNull() { return null; } [TestCase("a", "b")] public void HandlesParamsArrayAsSoleArgument(params string[] array) { Assert.AreEqual("a", array[0]); Assert.AreEqual("b", array[1]); } [TestCase("a")] public void HandlesParamsArrayWithOneItemAsSoleArgument(params string[] array) { Assert.AreEqual("a", array[0]); } [TestCase("a", "b", "c", "d")] public void HandlesParamsArrayAsLastArgument(string s1, string s2, params object[] array) { Assert.AreEqual("a", s1); Assert.AreEqual("b", s2); Assert.AreEqual("c", array[0]); Assert.AreEqual("d", array[1]); } [TestCase("a", "b")] public void HandlesParamsArrayWithNoItemsAsLastArgument(string s1, string s2, params object[] array) { Assert.AreEqual("a", s1); Assert.AreEqual("b", s2); Assert.AreEqual(0, array.Length); } [TestCase("a", "b", "c")] public void HandlesParamsArrayWithOneItemAsLastArgument(string s1, string s2, params object[] array) { Assert.AreEqual("a", s1); Assert.AreEqual("b", s2); Assert.AreEqual("c", array[0]); } [TestCase("x", ExpectedResult = new []{"x", "b", "c"})] [TestCase("x", "y", ExpectedResult = new[] { "x", "y", "c" })] [TestCase("x", "y", "z", ExpectedResult = new[] { "x", "y", "z" })] public string[] HandlesOptionalArguments(string s1, string s2 = "b", string s3 = "c") { return new[] {s1, s2, s3}; } [TestCase(ExpectedResult = new []{"a", "b"})] [TestCase("x", ExpectedResult = new[] { "x", "b" })] [TestCase("x", "y", ExpectedResult = new[] { "x", "y" })] public string[] HandlesAllOptionalArguments(string s1 = "a", string s2 = "b") { return new[] {s1, s2}; } [TestCase("a", "b", Explicit = true)] public void ShouldNotRunAndShouldNotFailInConsoleRunner() { Assert.Fail(); } [Test] public void CanSpecifyDescription() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasDescriptionSpecified").Tests[0]; Assert.AreEqual("My Description", test.Properties.Get(PropertyNames.Description)); } [Test] public void CanSpecifyTestName_FixedText() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified_FixedText").Tests[0]; Assert.AreEqual("XYZ", test.Name); Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.TestCaseAttributeFixture.XYZ", test.FullName); } [Test] public void CanSpecifyTestName_WithMethodName() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified_WithMethodName").Tests[0]; var expectedName = "MethodHasTestNameSpecified_WithMethodName+XYZ"; Assert.AreEqual(expectedName, test.Name); Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.TestCaseAttributeFixture." + expectedName, test.FullName); } [Test] public void CanSpecifyCategory() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasSingleCategory").Tests[0]; IList categories = test.Properties["Category"]; Assert.AreEqual(new string[] { "XYZ" }, categories); } [Test] public void CanSpecifyMultipleCategories() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasMultipleCategories").Tests[0]; IList categories = test.Properties["Category"]; Assert.AreEqual(new string[] { "X", "Y", "Z" }, categories); } [Test] public void CanIgnoreIndividualTestCases() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWithIgnoredTestCases"); Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); testCase = TestFinder.Find("MethodWithIgnoredTestCases(3)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Don't Run Me!")); } [Test] public void CanMarkIndividualTestCasesExplicit() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWithExplicitTestCases"); Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Connection failing")); } #if PLATFORM_DETECTION [Test] public void CanIncludePlatform() { bool isLinux = OSPlatform.CurrentPlatform.IsUnix; bool isMacOSX = OSPlatform.CurrentPlatform.IsMacOSX; TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWithIncludePlatform"); Test testCase1 = TestFinder.Find("MethodWithIncludePlatform(1)", suite, false); Test testCase2 = TestFinder.Find("MethodWithIncludePlatform(2)", suite, false); Test testCase3 = TestFinder.Find("MethodWithIncludePlatform(3)", suite, false); Test testCase4 = TestFinder.Find("MethodWithIncludePlatform(4)", suite, false); if (isLinux) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped)); } else if (isMacOSX) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped)); } else { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped)); } } [Test] public void CanExcludePlatform() { bool isLinux = OSPlatform.CurrentPlatform.IsUnix; bool isMacOSX = OSPlatform.CurrentPlatform.IsMacOSX; TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWithExcludePlatform"); Test testCase1 = TestFinder.Find("MethodWithExcludePlatform(1)", suite, false); Test testCase2 = TestFinder.Find("MethodWithExcludePlatform(2)", suite, false); Test testCase3 = TestFinder.Find("MethodWithExcludePlatform(3)", suite, false); Test testCase4 = TestFinder.Find("MethodWithExcludePlatform(4)", suite, false); if (isLinux) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable)); } else if (isMacOSX) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable)); } else { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable)); } } #endif #region Nullable<> tests [TestCase(12, 3, 4)] [TestCase(12, 2, 6)] [TestCase(12, 4, 3)] public void NullableIntegerDivisionWithResultPassedToTest(int? n, int? d, int? q) { Assert.AreEqual(q, n / d); } [TestCase(12, 3, ExpectedResult = 4)] [TestCase(12, 2, ExpectedResult = 6)] [TestCase(12, 4, ExpectedResult = 3)] public int? NullableIntegerDivisionWithResultCheckedByNUnit(int? n, int? d) { return n / d; } [TestCase(2, 2, ExpectedResult = 4)] public double? CanConvertIntToNullableDouble(double? x, double? y) { return x + y; } [TestCase(1)] public void CanConvertIntToNullableShort(short? x) { Assert.That(x.HasValue); Assert.That(x.Value, Is.EqualTo(1)); } [TestCase(1)] public void CanConvertIntToNullableByte(byte? x) { Assert.That(x.HasValue); Assert.That(x.Value, Is.EqualTo(1)); } [TestCase(1)] public void CanConvertIntToNullableSByte(sbyte? x) { Assert.That(x.HasValue); Assert.That(x.Value, Is.EqualTo(1)); } [TestCase(1)] public void CanConvertIntToNullableLong(long? x) { Assert.That(x.HasValue); Assert.That(x.Value, Is.EqualTo(1)); } [TestCase("2.2", "3.3", ExpectedResult = 5.5)] public decimal? CanConvertStringToNullableDecimal(decimal? x, decimal? y) { Assert.That(x.HasValue); Assert.That(y.HasValue); return x.Value + y.Value; } [TestCase(null)] public void SupportsNullableDecimal(decimal? x) { Assert.That(x.HasValue, Is.False); } [TestCase(2.2, 3.3, ExpectedResult = 5.5)] public decimal? CanConvertDoubleToNullableDecimal(decimal? x, decimal? y) { return x + y; } [TestCase(5, 2, ExpectedResult = 7)] public decimal? CanConvertIntToNullableDecimal(decimal? x, decimal? y) { return x + y; } [TestCase(5, 2, ExpectedResult = 7)] public short? CanConvertSmallIntsToNullableShort(short? x, short? y) { return (short)(x + y); } [TestCase(5, 2, ExpectedResult = 7)] public byte? CanConvertSmallIntsToNullableByte(byte? x, byte? y) { return (byte)(x + y); } [TestCase(5, 2, ExpectedResult = 7)] public sbyte? CanConvertSmallIntsToNullableSByte(sbyte? x, sbyte? y) { return (sbyte)(x + y); } [TestCase("12-October-1942")] public void CanConvertStringToNullableDateTime(DateTime? dt) { Assert.That(dt.HasValue); Assert.AreEqual(1942, dt.Value.Year); } [TestCase(null)] public void SupportsNullableDateTime(DateTime? dt) { Assert.That(dt.HasValue, Is.False); } [TestCase("4:44:15")] public void CanConvertStringToNullableTimeSpan(TimeSpan? ts) { Assert.That(ts.HasValue); Assert.AreEqual(4, ts.Value.Hours); Assert.AreEqual(44, ts.Value.Minutes); Assert.AreEqual(15, ts.Value.Seconds); } [TestCase(null)] public void SupportsNullableTimeSpan(TimeSpan? dt) { Assert.That(dt.HasValue, Is.False); } [TestCase(1)] public void NullableSimpleFormalParametersWithArgument(int? a) { Assert.AreEqual(1, a); } [TestCase(null)] public void NullableSimpleFormalParametersWithNullArgument(int? a) { Assert.IsNull(a); } [TestCase(null, ExpectedResult = null)] [TestCase(1, ExpectedResult = 1)] public int? TestCaseWithNullableReturnValue(int? a) { return a; } [TestCase(1, ExpectedResult = 1)] public T TestWithGenericReturnType<T>(T arg1) { return arg1; } #if ASYNC [TestCase(1, ExpectedResult = 1)] public async Task<T> TestWithAsyncGenericReturnType<T>(T arg1) { return await Task.Run(() => arg1); } #endif #endregion } }
// // $Id: MSGraphControl.cs 1599 2009-12-04 01:35:39Z brendanx $ // // // Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu> // // Copyright 2009 Vanderbilt University - Nashville, TN 37232 // // 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.ComponentModel; using System.Drawing; using System.Linq; using System.Windows.Forms; using ZedGraph; namespace pwiz.MSGraph { public partial class MSGraphControl : ZedGraphControl { public MSGraphControl() { InitializeComponent(); GraphPane = new MSGraphPane(new LabelBoundsCache()); // replace default ZedGraph.GraphPane IsZoomOnMouseCenter = true; IsEnableVZoom = false; IsEnableVPan = false; IsEnableHEdit = false; IsEnableVEdit = false; EditButtons = MouseButtons.Left; EditModifierKeys = Keys.None; _unzoomButtons = new MouseButtonClicks( MouseButtons.Middle ); _unzoomButtons2 = new MouseButtonClicks( MouseButtons.None ); _unzoomAllButtons = new MouseButtonClicks( MouseButtons.Left, 2 ); _unzoomAllButtons2 = new MouseButtonClicks( MouseButtons.None ); ZoomEvent += MSGraphControl_ZoomEvent; MouseMoveEvent += MSGraphControl_MouseMoveEvent; MouseClick += MSGraphControl_MouseClick; MouseDoubleClick += MSGraphControl_MouseClick; Resize += MSGraphControl_Resize; } #region On-the-fly rescaling of graph items when panning bool MSGraphControl_MouseMoveEvent( ZedGraphControl sender, MouseEventArgs e ) { if( e.Button == MouseButtons.None ) return false; if( ( IsEnableHPan ) && ( ( e.Button == PanButtons && ModifierKeys == PanModifierKeys ) || ( e.Button == PanButtons2 && ModifierKeys == PanModifierKeys2 ) ) ) { Graphics g = CreateGraphics(); foreach (var pane in MasterPane.PaneList.OfType<MSGraphPane>()) { pane.SetScale(g); } } return false; } #endregion #region Additional mouse events (Unzoom and UnzoomAll) public class MouseButtonClicks { private readonly MouseButtons _buttons; private readonly int _clicks; public MouseButtonClicks( MouseButtons buttons ) { _buttons = buttons; _clicks = 1; } public MouseButtonClicks( string value ) { string[] tokens = value.Split( ",".ToCharArray() ); // Not L10N if( tokens.Length != 2 ) throw new FormatException( "format string must have 2 tokens" ); // Not L10N // ReSharper disable NonLocalizedString switch( tokens[0] ) { case "None": _buttons = MouseButtons.None; break; case "Left": _buttons = MouseButtons.Left; break; case "Middle": _buttons = MouseButtons.Middle; break; case "Right": _buttons = MouseButtons.Right; break; case "XButton1": _buttons = MouseButtons.XButton1; break; case "XButton2": _buttons = MouseButtons.XButton2; break; default: throw new FormatException("first format string token must be one of (None,Left,Middle,Right,XButton1,XButton2)"); // Not L10N } // ReSharper restore NonLocalizedString if( !Int32.TryParse( tokens[1], out _clicks ) ) throw new FormatException("second format string token must be an integer specifying the number of button clicks"); // Not L10N } public MouseButtonClicks( MouseButtons buttons, int clicks ) { _buttons = buttons; _clicks = clicks; } public bool MatchesEvent( MouseEventArgs e ) { return ( _buttons == e.Button && _clicks == e.Clicks ); } } void MSGraphControl_MouseClick( object sender, MouseEventArgs e ) { MSGraphPane pane = MasterPane.FindChartRect( e.Location ) as MSGraphPane; if( pane != null && ( IsEnableHZoom || IsEnableVZoom ) ) { if( ( _unzoomButtons.MatchesEvent( e ) && ModifierKeys == _unzoomModifierKeys ) || ( _unzoomButtons2.MatchesEvent( e ) && ModifierKeys == _unzoomModifierKeys2 ) ) { if( IsSynchronizeXAxes ) { foreach( MSGraphPane syncPane in MasterPane.PaneList ) syncPane.ZoomStack.Pop( syncPane ); } else pane.ZoomStack.Pop( pane ); } else if( _unzoomAllButtons.MatchesEvent( e ) || _unzoomAllButtons2.MatchesEvent( e ) ) { if( IsSynchronizeXAxes ) { foreach( MSGraphPane syncPane in MasterPane.PaneList ) syncPane.ZoomStack.PopAll( syncPane ); } else pane.ZoomStack.PopAll( pane ); } else return; Graphics g = CreateGraphics(); if( IsSynchronizeXAxes ) { foreach( MSGraphPane syncPane in MasterPane.PaneList ) syncPane.SetScale(g); } else { pane.SetScale(g); } Refresh(); } } private MouseButtonClicks _unzoomButtons; private MouseButtonClicks _unzoomButtons2; [NotifyParentProperty( true ), Bindable( true ), Category( "Display" ), DefaultValue( "Middle,1" ), Description( "Determines which mouse button is used as the primary for unzooming" )] public MouseButtonClicks UnzoomButtons { get { return _unzoomButtons; } set { _unzoomButtons = value; } } [Description( "Determines which mouse button is used as the secondary for unzooming" ), NotifyParentProperty( true ), Bindable( true ), Category( "Display" ), DefaultValue( "None,0" )] public MouseButtonClicks UnzoomButtons2 { get { return _unzoomButtons2; } set { _unzoomButtons2 = value; } } private MouseButtonClicks _unzoomAllButtons; private MouseButtonClicks _unzoomAllButtons2; [Description( "Determines which mouse button is used as the secondary for undoing all zoom/pan operations" ), NotifyParentProperty( true ), Bindable( true ), Category( "Display" ), DefaultValue( "Left,1" )] public MouseButtonClicks UnzoomAllButtons { get { return _unzoomAllButtons; } set { _unzoomAllButtons = value; } } [Description( "Determines which mouse button is used as the secondary for undoing all zoom/pan operations" ), NotifyParentProperty( true ), Bindable( true ), Category( "Display" ), DefaultValue( "None,0" )] public MouseButtonClicks UnzoomAllButtons2 { get { return _unzoomAllButtons2; } set { _unzoomAllButtons2 = value; } } Keys _unzoomModifierKeys; Keys _unzoomModifierKeys2; [NotifyParentProperty( true ), Bindable( true ), Description( "Determines which modifier key used as the primary for zooming" ), Category( "Display" ), DefaultValue( Keys.None )] public Keys UnzoomModifierKeys { get { return _unzoomModifierKeys; } set { _unzoomModifierKeys = value; } } [Category( "Display" ), NotifyParentProperty( true ), Bindable( true ), Description( "Determines which modifier key used as the secondary for zooming" ), DefaultValue( Keys.None )] public Keys UnzoomModifierKeys2 { get { return _unzoomModifierKeys2; } set { _unzoomModifierKeys2 = value; } } #endregion #region Rescaling of graph items after zoom or resize events void MSGraphControl_ZoomEvent( ZedGraphControl sender, ZoomState oldState, ZoomState newState, PointF mousePosition ) { MSGraphPane pane = MasterPane.FindChartRect(mousePosition) as MSGraphPane; if( pane == null ) mousePosition = PointToClient(new Point(ContextMenuStrip.Left, ContextMenuStrip.Top)); pane = MasterPane.FindChartRect( mousePosition ) as MSGraphPane; if( pane == null ) return; Graphics g = CreateGraphics(); pane.SetScale(g); if( IsSynchronizeXAxes ) { foreach( MSGraphPane syncPane in MasterPane.PaneList ) { if( syncPane == pane ) continue; syncPane.SetScale(g); } } Refresh(); } void MSGraphControl_Resize( object sender, EventArgs e ) { Graphics g = CreateGraphics(); foreach( GraphPane pane in MasterPane.PaneList ) if( pane is MSGraphPane ) ( pane as MSGraphPane ).SetScale(g); Refresh(); } #endregion #region MS graph management functions private static CurveItem makeMSGraphItem(IMSGraphItemInfo item) { CurveItem newCurve = item.GraphItemDrawMethod == MSGraphItemDrawMethod.stick ? new StickItem( item.Title, new MSPointList( item.Points ), item.Color, item.LineWidth ) : new LineItem( item.Title, new MSPointList( item.Points ), item.Color, SymbolType.None ); if( item.GraphItemDrawMethod != MSGraphItemDrawMethod.stick ) { var line = ((LineItem) newCurve).Line; line.IsAntiAlias = true; if (item.GraphItemDrawMethod == MSGraphItemDrawMethod.fill) { line.Fill = new Fill(item.Color); line.Color = Color.FromArgb(200, 140, 140, 200); } } IMSGraphItemExtended extended = item as IMSGraphItemExtended; if (extended != null) extended.CustomizeCurve(newCurve); newCurve.Tag = item; return newCurve; } public CurveItem AddGraphItem( MSGraphPane pane, IMSGraphItemInfo item ) { return AddGraphItem(pane, item, true); } public CurveItem AddGraphItem( MSGraphPane pane, IMSGraphItemInfo item, bool setScale ) { if( item.GraphItemType != pane.CurrentItemType ) { pane.CurveList.Clear(); pane.CurrentItemType = item.GraphItemType; pane.ZoomStack.PopAll( pane ); item.CustomizeXAxis( pane.XAxis ); item.CustomizeYAxis( pane.YAxis ); } CurveItem newItem = makeMSGraphItem( item ); pane.CurveList.Add( newItem ); // If you are adding multiple graph items, it is quickest to set the scale // once at the end. if (setScale) pane.SetScale( CreateGraphics() ); return newItem; } #endregion [ Bindable(false), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public new MSGraphPane GraphPane { get { // Just return the first GraphPane in the list lock( this ) { if( MasterPane != null && MasterPane.PaneList.Count > 0 ) if( MasterPane.PaneList[0] is MSGraphPane ) return MasterPane.PaneList[0] as MSGraphPane; else throw new Exception( "invalid graph pane type" ); // Not L10N else return null; } } set { lock( this ) { //Clear the list, and replace it with the specified Graphpane if( MasterPane != null ) { MasterPane.PaneList.Clear(); MasterPane.Add( value ); } } } } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NLog.Config; using NLog.Targets; using Xunit; namespace NLog.UnitTests.Targets { public class MethodCallTests : NLogTestBase { private const string CorrectClassName = "NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests"; #region ToBeCalled Methods private static MethodCallRecord LastCallTest = null; public static void StaticAndPublic(string param1, int param2) { LastCallTest = new MethodCallRecord("StaticAndPublic", param1, param2); } public static void StaticAndPublicWrongParameters(string param1, string param2) { LastCallTest = new MethodCallRecord("StaticAndPublic", param1, param2); } public static void StaticAndPublicTooLessParameters(string param1) { LastCallTest = new MethodCallRecord("StaticAndPublicTooLessParameters", param1); } public static void StaticAndPublicTooManyParameters(string param1, int param2, string param3) { LastCallTest = new MethodCallRecord("StaticAndPublicTooManyParameters", param1, param2); } public static void StaticAndPublicOptional(string param1, int param2, string param3 = "fixedValue") { LastCallTest = new MethodCallRecord("StaticAndPublicOptional", param1, param2, param3); } public void NonStaticAndPublic() { LastCallTest = new MethodCallRecord("NonStaticAndPublic"); } public static void StaticAndPrivate() { LastCallTest = new MethodCallRecord("StaticAndPrivate"); } #endregion [Fact] public void TestMethodCall1() { TestMethodCall(new MethodCallRecord("StaticAndPublic", "test1", 2), "StaticAndPublic", CorrectClassName); } [Fact] public void TestMethodCall2() { //Type AssemblyQualifiedName //to find, use typeof(MethodCallTests).AssemblyQualifiedName TestMethodCall(new MethodCallRecord("StaticAndPublic", "test1", 2), "StaticAndPublic", "NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b793d3de60bec2b9"); } [Fact] public void PrivateMethodDontThrow() { TestMethodCall(null, "NonStaticAndPublic", CorrectClassName); } [Fact] public void WrongClassDontThrow() { TestMethodCall(null, "StaticAndPublic", "NLog.UnitTests222.Targets.CallTest, NLog.UnitTests"); } [Fact] public void WrongParametersDontThrow() { TestMethodCall(null, "StaticAndPublicWrongParameters", CorrectClassName); } [Fact] public void TooLessParametersDontThrow() { TestMethodCall(null, "StaticAndPublicTooLessParameters", CorrectClassName); } [Fact] public void TooManyParametersDontThrow() { TestMethodCall(null, "StaticAndPublicTooManyParameters", CorrectClassName); } [Fact] public void OptionalParameters() { TestMethodCall(new MethodCallRecord("StaticAndPublicOptional", "test1", 2, "fixedValue"), "StaticAndPublicOptional", CorrectClassName); } private static void TestMethodCall(MethodCallRecord expected, string methodName, string className) { var target = new MethodCallTarget { Name = "t1", ClassName = className, MethodName = methodName }; target.Parameters.Add(new MethodCallParameter("param1", "test1")); target.Parameters.Add(new MethodCallParameter("param2", "2", typeof(int))); var configuration = new LoggingConfiguration(); configuration.AddTarget(target); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target)); LogManager.Configuration = configuration; LastCallTest = null; LogManager.GetCurrentClassLogger().Debug("test method 1"); Assert.Equal(expected, LastCallTest); } private class MethodCallRecord { /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public MethodCallRecord(string method, params object[] parameterValues) { Method = method; if (parameterValues != null) ParameterValues = parameterValues.ToList(); } public string Method { get; set; } public List<object> ParameterValues { get; set; } protected bool Equals(MethodCallRecord other) { return string.Equals(Method, other.Method) && ParameterValues.SequenceEqual(other.ParameterValues); } /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> /// <returns> /// true if the specified object is equal to the current object; otherwise, false. /// </returns> /// <param name="obj">The object to compare with the current object. </param> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((MethodCallRecord)obj); } /// <summary> /// Serves as the default hash function. /// </summary> /// <returns> /// A hash code for the current object. /// </returns> public override int GetHashCode() { unchecked { return ((Method != null ? Method.GetHashCode() : 0) * 397) ^ (ParameterValues != null ? ParameterValues.GetHashCode() : 0); } } } } }
using System; using log4net; using Umbraco.Core.Logging; using System.IO; using System.Linq; using Umbraco.Core.IO; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Core.Publishing; using umbraco.interfaces; using Umbraco.Core.Events; namespace Umbraco.Core.Services { /// <summary> /// These are used currently to return the temporary 'operation' interfaces for services /// which are used to return a status from operational methods so we can determine if things are /// cancelled, etc... /// /// These will be obsoleted in v8 since all real services methods will be changed to have the correct result. /// </summary> public static class ServiceWithResultExtensions { public static IContentServiceOperations WithResult(this IContentService contentService) { return (IContentServiceOperations)contentService; } public static IMediaServiceOperations WithResult(this IMediaService mediaService) { return (IMediaServiceOperations)mediaService; } } /// <summary> /// The Umbraco ServiceContext, which provides access to the following services: /// <see cref="IContentService"/>, <see cref="IContentTypeService"/>, <see cref="IDataTypeService"/>, /// <see cref="IFileService"/>, <see cref="ILocalizationService"/> and <see cref="IMediaService"/>. /// </summary> public class ServiceContext { private Lazy<IMigrationEntryService> _migrationEntryService; private Lazy<IPublicAccessService> _publicAccessService; private Lazy<ITaskService> _taskService; private Lazy<IDomainService> _domainService; private Lazy<IAuditService> _auditService; private Lazy<ILocalizedTextService> _localizedTextService; private Lazy<ITagService> _tagService; private Lazy<IContentService> _contentService; private Lazy<IUserService> _userService; private Lazy<IMemberService> _memberService; private Lazy<IMediaService> _mediaService; private Lazy<IContentTypeService> _contentTypeService; private Lazy<IDataTypeService> _dataTypeService; private Lazy<IFileService> _fileService; private Lazy<ILocalizationService> _localizationService; private Lazy<IPackagingService> _packagingService; private Lazy<IServerRegistrationService> _serverRegistrationService; private Lazy<IEntityService> _entityService; private Lazy<IRelationService> _relationService; private Lazy<IApplicationTreeService> _treeService; private Lazy<ISectionService> _sectionService; private Lazy<IMacroService> _macroService; private Lazy<IMemberTypeService> _memberTypeService; private Lazy<IMemberGroupService> _memberGroupService; private Lazy<INotificationService> _notificationService; private Lazy<IExternalLoginService> _externalLoginService; /// <summary> /// public ctor - will generally just be used for unit testing all items are optional and if not specified, the defaults will be used /// </summary> /// <param name="contentService"></param> /// <param name="mediaService"></param> /// <param name="contentTypeService"></param> /// <param name="dataTypeService"></param> /// <param name="fileService"></param> /// <param name="localizationService"></param> /// <param name="packagingService"></param> /// <param name="entityService"></param> /// <param name="relationService"></param> /// <param name="memberGroupService"></param> /// <param name="memberTypeService"></param> /// <param name="memberService"></param> /// <param name="userService"></param> /// <param name="sectionService"></param> /// <param name="treeService"></param> /// <param name="tagService"></param> /// <param name="notificationService"></param> /// <param name="localizedTextService"></param> /// <param name="auditService"></param> /// <param name="domainService"></param> /// <param name="taskService"></param> /// <param name="macroService"></param> /// <param name="publicAccessService"></param> /// <param name="externalLoginService"></param> /// <param name="migrationEntryService"></param> public ServiceContext( IContentService contentService = null, IMediaService mediaService = null, IContentTypeService contentTypeService = null, IDataTypeService dataTypeService = null, IFileService fileService = null, ILocalizationService localizationService = null, IPackagingService packagingService = null, IEntityService entityService = null, IRelationService relationService = null, IMemberGroupService memberGroupService = null, IMemberTypeService memberTypeService = null, IMemberService memberService = null, IUserService userService = null, ISectionService sectionService = null, IApplicationTreeService treeService = null, ITagService tagService = null, INotificationService notificationService = null, ILocalizedTextService localizedTextService = null, IAuditService auditService = null, IDomainService domainService = null, ITaskService taskService = null, IMacroService macroService = null, IPublicAccessService publicAccessService = null, IExternalLoginService externalLoginService = null, IMigrationEntryService migrationEntryService = null) { if (migrationEntryService != null) _migrationEntryService = new Lazy<IMigrationEntryService>(() => migrationEntryService); if (externalLoginService != null) _externalLoginService = new Lazy<IExternalLoginService>(() => externalLoginService); if (auditService != null) _auditService = new Lazy<IAuditService>(() => auditService); if (localizedTextService != null) _localizedTextService = new Lazy<ILocalizedTextService>(() => localizedTextService); if (tagService != null) _tagService = new Lazy<ITagService>(() => tagService); if (contentService != null) _contentService = new Lazy<IContentService>(() => contentService); if (mediaService != null) _mediaService = new Lazy<IMediaService>(() => mediaService); if (contentTypeService != null) _contentTypeService = new Lazy<IContentTypeService>(() => contentTypeService); if (dataTypeService != null) _dataTypeService = new Lazy<IDataTypeService>(() => dataTypeService); if (fileService != null) _fileService = new Lazy<IFileService>(() => fileService); if (localizationService != null) _localizationService = new Lazy<ILocalizationService>(() => localizationService); if (packagingService != null) _packagingService = new Lazy<IPackagingService>(() => packagingService); if (entityService != null) _entityService = new Lazy<IEntityService>(() => entityService); if (relationService != null) _relationService = new Lazy<IRelationService>(() => relationService); if (sectionService != null) _sectionService = new Lazy<ISectionService>(() => sectionService); if (memberGroupService != null) _memberGroupService = new Lazy<IMemberGroupService>(() => memberGroupService); if (memberTypeService != null) _memberTypeService = new Lazy<IMemberTypeService>(() => memberTypeService); if (treeService != null) _treeService = new Lazy<IApplicationTreeService>(() => treeService); if (memberService != null) _memberService = new Lazy<IMemberService>(() => memberService); if (userService != null) _userService = new Lazy<IUserService>(() => userService); if (notificationService != null) _notificationService = new Lazy<INotificationService>(() => notificationService); if (domainService != null) _domainService = new Lazy<IDomainService>(() => domainService); if (taskService != null) _taskService = new Lazy<ITaskService>(() => taskService); if (macroService != null) _macroService = new Lazy<IMacroService>(() => macroService); if (publicAccessService != null) _publicAccessService = new Lazy<IPublicAccessService>(() => publicAccessService); } /// <summary> /// Creates a service context with a RepositoryFactory which is used to construct Services /// </summary> /// <param name="repositoryFactory"></param> /// <param name="dbUnitOfWorkProvider"></param> /// <param name="fileUnitOfWorkProvider"></param> /// <param name="publishingStrategy"></param> /// <param name="cache"></param> /// <param name="logger"></param> /// <param name="eventMessagesFactory"></param> public ServiceContext( RepositoryFactory repositoryFactory, IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider, IUnitOfWorkProvider fileUnitOfWorkProvider, BasePublishingStrategy publishingStrategy, CacheHelper cache, ILogger logger, IEventMessagesFactory eventMessagesFactory) { if (repositoryFactory == null) throw new ArgumentNullException("repositoryFactory"); if (dbUnitOfWorkProvider == null) throw new ArgumentNullException("dbUnitOfWorkProvider"); if (fileUnitOfWorkProvider == null) throw new ArgumentNullException("fileUnitOfWorkProvider"); if (publishingStrategy == null) throw new ArgumentNullException("publishingStrategy"); if (cache == null) throw new ArgumentNullException("cache"); if (logger == null) throw new ArgumentNullException("logger"); if (eventMessagesFactory == null) throw new ArgumentNullException("eventMessagesFactory"); BuildServiceCache(dbUnitOfWorkProvider, fileUnitOfWorkProvider, publishingStrategy, cache, repositoryFactory, logger, eventMessagesFactory); } /// <summary> /// Builds the various services /// </summary> private void BuildServiceCache( IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider, IUnitOfWorkProvider fileUnitOfWorkProvider, BasePublishingStrategy publishingStrategy, CacheHelper cache, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory) { var provider = dbUnitOfWorkProvider; var fileProvider = fileUnitOfWorkProvider; if (_migrationEntryService == null) _migrationEntryService = new Lazy<IMigrationEntryService>(() => new MigrationEntryService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_externalLoginService == null) _externalLoginService = new Lazy<IExternalLoginService>(() => new ExternalLoginService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_publicAccessService == null) _publicAccessService = new Lazy<IPublicAccessService>(() => new PublicAccessService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_taskService == null) _taskService = new Lazy<ITaskService>(() => new TaskService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_domainService == null) _domainService = new Lazy<IDomainService>(() => new DomainService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_auditService == null) _auditService = new Lazy<IAuditService>(() => new AuditService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_localizedTextService == null) { _localizedTextService = new Lazy<ILocalizedTextService>(() => new LocalizedTextService( new Lazy<LocalizedTextServiceFileSources>(() => { var mainLangFolder = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Umbraco + "/config/lang/")); var appPlugins = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.AppPlugins)); var configLangFolder = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Config + "/lang/")); var pluginLangFolders = appPlugins.Exists == false ? Enumerable.Empty<LocalizedTextServiceSupplementaryFileSource>() : appPlugins.GetDirectories() .SelectMany(x => x.GetDirectories("Lang")) .SelectMany(x => x.GetFiles("*.xml", SearchOption.TopDirectoryOnly)) .Where(x => Path.GetFileNameWithoutExtension(x.FullName).Length == 5) .Select(x => new LocalizedTextServiceSupplementaryFileSource(x, false)); //user defined langs that overwrite the default, these should not be used by plugin creators var userLangFolders = configLangFolder.Exists == false ? Enumerable.Empty<LocalizedTextServiceSupplementaryFileSource>() : configLangFolder .GetFiles("*.user.xml", SearchOption.TopDirectoryOnly) .Where(x => Path.GetFileNameWithoutExtension(x.FullName).Length == 10) .Select(x => new LocalizedTextServiceSupplementaryFileSource(x, true)); return new LocalizedTextServiceFileSources( logger, cache.RuntimeCache, mainLangFolder, pluginLangFolders.Concat(userLangFolders)); }), logger)); } if (_notificationService == null) _notificationService = new Lazy<INotificationService>(() => new NotificationService(provider, _userService.Value, _contentService.Value, logger)); if (_serverRegistrationService == null) _serverRegistrationService = new Lazy<IServerRegistrationService>(() => new ServerRegistrationService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_userService == null) _userService = new Lazy<IUserService>(() => new UserService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_memberService == null) _memberService = new Lazy<IMemberService>(() => new MemberService(provider, repositoryFactory, logger, eventMessagesFactory, _memberGroupService.Value, _dataTypeService.Value)); if (_contentService == null) _contentService = new Lazy<IContentService>(() => new ContentService(provider, repositoryFactory, logger, eventMessagesFactory, publishingStrategy, _dataTypeService.Value, _userService.Value)); if (_mediaService == null) _mediaService = new Lazy<IMediaService>(() => new MediaService(provider, repositoryFactory, logger, eventMessagesFactory, _dataTypeService.Value, _userService.Value)); if (_contentTypeService == null) _contentTypeService = new Lazy<IContentTypeService>(() => new ContentTypeService(provider, repositoryFactory, logger, eventMessagesFactory, _contentService.Value, _mediaService.Value)); if (_dataTypeService == null) _dataTypeService = new Lazy<IDataTypeService>(() => new DataTypeService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_fileService == null) _fileService = new Lazy<IFileService>(() => new FileService(fileProvider, provider, repositoryFactory)); if (_localizationService == null) _localizationService = new Lazy<ILocalizationService>(() => new LocalizationService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_packagingService == null) _packagingService = new Lazy<IPackagingService>(() => new PackagingService(logger, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _macroService.Value, _dataTypeService.Value, _fileService.Value, _localizationService.Value, _userService.Value, repositoryFactory, provider)); if (_entityService == null) _entityService = new Lazy<IEntityService>(() => new EntityService( provider, repositoryFactory, logger, eventMessagesFactory, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _dataTypeService.Value, _memberService.Value, _memberTypeService.Value, cache.RuntimeCache)); if (_relationService == null) _relationService = new Lazy<IRelationService>(() => new RelationService(provider, repositoryFactory, logger, eventMessagesFactory, _entityService.Value)); if (_treeService == null) _treeService = new Lazy<IApplicationTreeService>(() => new ApplicationTreeService(logger, cache)); if (_sectionService == null) _sectionService = new Lazy<ISectionService>(() => new SectionService(_userService.Value, _treeService.Value, provider, cache)); if (_macroService == null) _macroService = new Lazy<IMacroService>(() => new MacroService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_memberTypeService == null) _memberTypeService = new Lazy<IMemberTypeService>(() => new MemberTypeService(provider, repositoryFactory, logger, eventMessagesFactory, _memberService.Value)); if (_tagService == null) _tagService = new Lazy<ITagService>(() => new TagService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_memberGroupService == null) _memberGroupService = new Lazy<IMemberGroupService>(() => new MemberGroupService(provider, repositoryFactory, logger, eventMessagesFactory)); } /// <summary> /// Gets the <see cref="IMigrationEntryService"/> /// </summary> public IMigrationEntryService MigrationEntryService { get { return _migrationEntryService.Value; } } /// <summary> /// Gets the <see cref="IPublicAccessService"/> /// </summary> public IPublicAccessService PublicAccessService { get { return _publicAccessService.Value; } } /// <summary> /// Gets the <see cref="ITaskService"/> /// </summary> public ITaskService TaskService { get { return _taskService.Value; } } /// <summary> /// Gets the <see cref="IDomainService"/> /// </summary> public IDomainService DomainService { get { return _domainService.Value; } } /// <summary> /// Gets the <see cref="IAuditService"/> /// </summary> public IAuditService AuditService { get { return _auditService.Value; } } /// <summary> /// Gets the <see cref="ILocalizedTextService"/> /// </summary> public ILocalizedTextService TextService { get { return _localizedTextService.Value; } } /// <summary> /// Gets the <see cref="INotificationService"/> /// </summary> public INotificationService NotificationService { get { return _notificationService.Value; } } /// <summary> /// Gets the <see cref="ServerRegistrationService"/> /// </summary> public IServerRegistrationService ServerRegistrationService { get { return _serverRegistrationService.Value; } } /// <summary> /// Gets the <see cref="ITagService"/> /// </summary> public ITagService TagService { get { return _tagService.Value; } } /// <summary> /// Gets the <see cref="IMacroService"/> /// </summary> public IMacroService MacroService { get { return _macroService.Value; } } /// <summary> /// Gets the <see cref="IEntityService"/> /// </summary> public IEntityService EntityService { get { return _entityService.Value; } } /// <summary> /// Gets the <see cref="IRelationService"/> /// </summary> public IRelationService RelationService { get { return _relationService.Value; } } /// <summary> /// Gets the <see cref="IContentService"/> /// </summary> public IContentService ContentService { get { return _contentService.Value; } } /// <summary> /// Gets the <see cref="IContentTypeService"/> /// </summary> public IContentTypeService ContentTypeService { get { return _contentTypeService.Value; } } /// <summary> /// Gets the <see cref="IDataTypeService"/> /// </summary> public IDataTypeService DataTypeService { get { return _dataTypeService.Value; } } /// <summary> /// Gets the <see cref="IFileService"/> /// </summary> public IFileService FileService { get { return _fileService.Value; } } /// <summary> /// Gets the <see cref="ILocalizationService"/> /// </summary> public ILocalizationService LocalizationService { get { return _localizationService.Value; } } /// <summary> /// Gets the <see cref="IMediaService"/> /// </summary> public IMediaService MediaService { get { return _mediaService.Value; } } /// <summary> /// Gets the <see cref="PackagingService"/> /// </summary> public IPackagingService PackagingService { get { return _packagingService.Value; } } /// <summary> /// Gets the <see cref="UserService"/> /// </summary> public IUserService UserService { get { return _userService.Value; } } /// <summary> /// Gets the <see cref="MemberService"/> /// </summary> public IMemberService MemberService { get { return _memberService.Value; } } /// <summary> /// Gets the <see cref="SectionService"/> /// </summary> public ISectionService SectionService { get { return _sectionService.Value; } } /// <summary> /// Gets the <see cref="ApplicationTreeService"/> /// </summary> public IApplicationTreeService ApplicationTreeService { get { return _treeService.Value; } } /// <summary> /// Gets the MemberTypeService /// </summary> public IMemberTypeService MemberTypeService { get { return _memberTypeService.Value; } } /// <summary> /// Gets the MemberGroupService /// </summary> public IMemberGroupService MemberGroupService { get { return _memberGroupService.Value; } } public IExternalLoginService ExternalLoginService { get { return _externalLoginService.Value; } } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Models { /// <summary> /// PipelineStepImpl /// </summary> [DataContract(Name = "PipelineStepImpl")] public partial class PipelineStepImpl : IEquatable<PipelineStepImpl>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PipelineStepImpl" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="links">links.</param> /// <param name="displayName">displayName.</param> /// <param name="durationInMillis">durationInMillis.</param> /// <param name="id">id.</param> /// <param name="input">input.</param> /// <param name="result">result.</param> /// <param name="startTime">startTime.</param> /// <param name="state">state.</param> public PipelineStepImpl(string _class = default(string), PipelineStepImpllinks links = default(PipelineStepImpllinks), string displayName = default(string), int durationInMillis = default(int), string id = default(string), InputStepImpl input = default(InputStepImpl), string result = default(string), string startTime = default(string), string state = default(string)) { this.Class = _class; this.Links = links; this.DisplayName = displayName; this.DurationInMillis = durationInMillis; this.Id = id; this.Input = input; this.Result = result; this.StartTime = startTime; this.State = state; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Gets or Sets Links /// </summary> [DataMember(Name = "_links", EmitDefaultValue = false)] public PipelineStepImpllinks Links { get; set; } /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name = "displayName", EmitDefaultValue = false)] public string DisplayName { get; set; } /// <summary> /// Gets or Sets DurationInMillis /// </summary> [DataMember(Name = "durationInMillis", EmitDefaultValue = false)] public int DurationInMillis { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name = "id", EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// Gets or Sets Input /// </summary> [DataMember(Name = "input", EmitDefaultValue = false)] public InputStepImpl Input { get; set; } /// <summary> /// Gets or Sets Result /// </summary> [DataMember(Name = "result", EmitDefaultValue = false)] public string Result { get; set; } /// <summary> /// Gets or Sets StartTime /// </summary> [DataMember(Name = "startTime", EmitDefaultValue = false)] public string StartTime { get; set; } /// <summary> /// Gets or Sets State /// </summary> [DataMember(Name = "state", EmitDefaultValue = false)] public string State { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PipelineStepImpl {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" DurationInMillis: ").Append(DurationInMillis).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Input: ").Append(Input).Append("\n"); sb.Append(" Result: ").Append(Result).Append("\n"); sb.Append(" StartTime: ").Append(StartTime).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as PipelineStepImpl); } /// <summary> /// Returns true if PipelineStepImpl instances are equal /// </summary> /// <param name="input">Instance of PipelineStepImpl to be compared</param> /// <returns>Boolean</returns> public bool Equals(PipelineStepImpl input) { if (input == null) return false; return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.Links == input.Links || (this.Links != null && this.Links.Equals(input.Links)) ) && ( this.DisplayName == input.DisplayName || (this.DisplayName != null && this.DisplayName.Equals(input.DisplayName)) ) && ( this.DurationInMillis == input.DurationInMillis || this.DurationInMillis.Equals(input.DurationInMillis) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.Input == input.Input || (this.Input != null && this.Input.Equals(input.Input)) ) && ( this.Result == input.Result || (this.Result != null && this.Result.Equals(input.Result)) ) && ( this.StartTime == input.StartTime || (this.StartTime != null && this.StartTime.Equals(input.StartTime)) ) && ( this.State == input.State || (this.State != null && this.State.Equals(input.State)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) hashCode = hashCode * 59 + this.Class.GetHashCode(); if (this.Links != null) hashCode = hashCode * 59 + this.Links.GetHashCode(); if (this.DisplayName != null) hashCode = hashCode * 59 + this.DisplayName.GetHashCode(); hashCode = hashCode * 59 + this.DurationInMillis.GetHashCode(); if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.Input != null) hashCode = hashCode * 59 + this.Input.GetHashCode(); if (this.Result != null) hashCode = hashCode * 59 + this.Result.GetHashCode(); if (this.StartTime != null) hashCode = hashCode * 59 + this.StartTime.GetHashCode(); if (this.State != null) hashCode = hashCode * 59 + this.State.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // 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 YamlDotNet.Core; using YamlDotNet.Core.Events; using TagDirective = YamlDotNet.Core.Tokens.TagDirective; using VersionDirective = YamlDotNet.Core.Tokens.VersionDirective; // ReSharper disable MemberHidesStaticFromOuterClass namespace YamlDotNet.Test.Core { public class EventsHelper { protected const bool Explicit = false; protected const bool Implicit = true; protected const string TagYaml = "tag:yaml.org,2002:"; protected static readonly TagDirective[] DefaultTags = new[] { new TagDirective("!", "!"), new TagDirective("!!", TagYaml) }; protected static StreamStart StreamStart { get { return new StreamStart(); } } protected static StreamEnd StreamEnd { get { return new StreamEnd(); } } protected DocumentStart DocumentStart(bool isImplicit) { return DocumentStart(isImplicit, null, DefaultTags); } protected DocumentStart DocumentStart(bool isImplicit, VersionDirective version, params TagDirective[] tags) { return new DocumentStart(version, new TagDirectiveCollection(tags), isImplicit); } protected VersionDirective Version(int major, int minor) { return new VersionDirective(new Version(major, minor)); } protected TagDirective TagDirective(string handle, string prefix) { return new TagDirective(handle, prefix); } protected DocumentEnd DocumentEnd(bool isImplicit) { return new DocumentEnd(isImplicit); } protected ScalarBuilder Scalar(string text) { return new ScalarBuilder(text, ScalarStyle.Any); } protected ScalarBuilder PlainScalar(string text) { return new ScalarBuilder(text, ScalarStyle.Plain); } protected ScalarBuilder SingleQuotedScalar(string text) { return new ScalarBuilder(text, ScalarStyle.SingleQuoted); } protected ScalarBuilder DoubleQuotedScalar(string text) { return new ScalarBuilder(text, ScalarStyle.DoubleQuoted); } protected ScalarBuilder LiteralScalar(string text) { return new ScalarBuilder(text, ScalarStyle.Literal); } protected ScalarBuilder FoldedScalar(string text) { return new ScalarBuilder(text, ScalarStyle.Folded); } protected SequenceStartBuilder BlockSequenceStart { get { return new SequenceStartBuilder(SequenceStyle.Block); } } protected SequenceStartBuilder FlowSequenceStart { get { return new SequenceStartBuilder(SequenceStyle.Flow); } } protected SequenceEnd SequenceEnd { get { return new SequenceEnd(); } } protected MappingStart MappingStart { get { return new MappingStart(); } } protected MappingStartBuilder BlockMappingStart { get { return new MappingStartBuilder(MappingStyle.Block); } } protected MappingStartBuilder FlowMappingStart { get { return new MappingStartBuilder(MappingStyle.Flow); } } protected MappingEnd MappingEnd { get { return new MappingEnd(); } } protected AnchorAlias AnchorAlias(string alias) { return new AnchorAlias(alias); } protected Comment StandaloneComment(string value) { return new Comment(value, false); } protected Comment InlineComment(string value) { return new Comment(value, true); } protected class ScalarBuilder { private readonly string text; private readonly ScalarStyle style; private string tag; private bool plainImplicit; private bool quotedImplicit; public ScalarBuilder(string text, ScalarStyle style) { this.text = text; this.style = style; plainImplicit = style == ScalarStyle.Plain; quotedImplicit = style != ScalarStyle.Plain && style != ScalarStyle.Any; } public ScalarBuilder T(string tag) { this.tag = tag; plainImplicit = false; quotedImplicit = false; return this; } public ScalarBuilder ImplicitPlain { get { plainImplicit = true; return this; } } public ScalarBuilder ImplicitQuoted { get { quotedImplicit = true; return this; } } public static implicit operator Scalar(ScalarBuilder builder) { return new Scalar(null, builder.tag, builder.text, builder.style, builder.plainImplicit, builder.quotedImplicit); } } protected class SequenceStartBuilder { private const bool DefaultImplicit = true; private readonly SequenceStyle style; private string anchor; private bool @implicit; public SequenceStartBuilder(SequenceStyle style) { this.style = style; @implicit = DefaultImplicit; } public SequenceStartBuilder A(string anchor) { this.anchor = anchor; return this; } public SequenceStartBuilder Explicit { get { @implicit = false; return this; } } public static implicit operator SequenceStart(SequenceStartBuilder builder) { return new SequenceStart(builder.anchor, null, builder.@implicit, builder.style); } } protected class MappingStartBuilder { private const bool DefaultImplicit = true; private readonly MappingStyle style; private string tag; private bool @implicit; public MappingStartBuilder(MappingStyle style) { this.style = style; @implicit = DefaultImplicit; } public MappingStartBuilder T(string tag) { this.tag = tag; return this; } public MappingStartBuilder Explicit { get { @implicit = false; return this; } } public static implicit operator MappingStart(MappingStartBuilder builder) { return new MappingStart(null, builder.tag, builder.@implicit, builder.style); } } } }
/* * SETTE - Symbolic Execution based Test Tool Evaluator * * SETTE is a tool to help the evaluation and comparison of symbolic execution * based test input generator tools. * * Budapest University of Technology and Economics (BME) * * Authors: Lajos Cseppento <[email protected]>, Zoltan Micskei * <[email protected]> * * Copyright 2014 * * 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 BME.MIT.SETTE.Basic.B2 { public static class B2d_Linear { /** * Equation: 20x+2 = 42<br/> * Solution: x = 2 * * @param x * @return */ public static bool oneParamInt(int x) { if (20 * x + 2 == 42) { return true; } else { return false; } } /** * Equation: 20x+2 = 41<br/> * Solution: x = 1 (not integer) * * @param x * @return */ //@SetteRequiredStatementCoverage(value = 50) public static bool oneParamIntNoSolution(int x) { if (20 * x + 2 == 41) { return true; } else { return false; } } /** * Equation system:<br/> * <br/> * x+2y = 3<br/> * 3x+4y = 11<br/> * <br/> * Solution: {x, y} = {5, -1} * * @param x * @param y * @return */ public static bool twoParamsInt(int x, int y) { // it is usual that the results are saved into variables and the // variables are used in conditional statements int e1 = x + 2 * y; int e2 = 3 * x + 4 * y; if (e1 == 3 && e2 == 11) { return true; } else { return false; } } /** * Equation system:<br/> * <br/> * x+2y = 3<br/> * 3x+4y = 10<br/> * <br/> * Solution: {x, y} = {4, -0.5} (not integer) * * @param x * @param y * @return */ //@SetteRequiredStatementCoverage(value = 66) public static bool twoParamsIntNoSolution(int x, int y) { // it is usual that the results are saved into variables and the // variables are used in conditional statements int e1 = x + 2 * y; int e2 = 3 * x + 4 * y; if (e1 == 3 && e2 == 10) { return true; } else { return false; } } /** * Equation system:<br/> * <br/> * x+2y+3z = 9<br/> * 3x+y-2z = 10<br/> * 5x-y-z = 24<br/> * <br/> * Solution: {x, y, z} = {5, -1, 2} * * @param x * @param y * @param z * @return */ public static bool threeParamsInt(int x, int y, int z) { // it is usual that the results are saved into variables and the // variables are used in conditional statements int e1 = x + 2 * y + 3 * z; int e2 = 3 * x + y - 2 * z; int e3 = 5 * x - y - z; if (e1 == 9 && e2 == 10 && e3 == 24) { return true; } else { return false; } } /** * Equation system:<br/> * <br/> * x+2y+3z = 9<br/> * 3x+y-2z = 10<br/> * 5x-y-z = 23<br/> * <br/> * Solution: {x, y, z} = {198/41, -30/41, 77/41}<br/> * Solution with overflow (32bit integer): {x, y, z} = {-1257063594, * 1361818898, 942797701} * * @param x * @param y * @param z * @return */ //@SetteRequiredStatementCoverage(value = 71) public static bool threeParamsIntNoSolution(int x, int y, int z) { // it is usual that the results are saved into variables and the // variables are used in conditional statements int e1 = x + 2 * y + 3 * z; int e2 = 3 * x + y - 2 * z; int e3 = 5 * x - y - z; if (e1 == 9 && e2 == 10 && e3 == 23) { return true; } else { return false; } } /** * Equation: 20x+2 = 17<br/> * Solution: x = 0.75 * * (0.75 = 3/4 can be precisely represented, see IEEE 754) * * @param x * @return */ public static bool oneParamFloat(float x) { if (20 * x + 2 == 17) { return true; } else { return false; } } /** * Equation system:<br/> * <br/> * x+2y = 3<br/> * 3x+4y = 10<br/> * <br/> * Solution: {x, y} = {4, -0.5} * * (-0.5 = -1/2 can be precisely represented, see IEEE 754) * * @param x * @param y * @return */ public static bool twoParamsFloat(float x, float y) { // it is usual that the results are saved into variables and the // variables are used in conditional statements float e1 = x + 2 * y; float e2 = 3 * x + 4 * y; if (e1 == 3 && e2 == 10) { return true; } else { return false; } } /** * Equation system:<br/> * <br/> * x+2y+3z = 9<br/> * 3x+y-2z = 10<br/> * 5x-y-z = 23<br/> * <br/> * Solution: {x, y, z} = {198/41, -30/41, 77/41}<br/> * Threshold: 1e-3 (Note: constants and Math.abs() cannot be used because * they may not be supported) * * @param x * @param y * @param z * @return */ public static bool threeParamsFloat(float x, float y, float z) { // it is usual that the results are saved into variables and the // variables are used in conditional statements float e1 = x + 2 * y + 3 * z; float e2 = 3 * x + y - 2 * z; float e3 = 5 * x - y - z; if (8.999f < e1 && e1 < 9.001f && 9.999f < e2 && e2 < 10.001f && 22.999f < e3 && e3 < 23.001f) { return true; } else { return false; } } /** * Equation: 20x+2 = 17<br/> * Solution: x = 0.75 * * (0.75 = 3/4 can be precisely represented, see IEEE 754) * * @param x * @return */ public static bool oneParamDouble(double x) { if (20 * x + 2 == 17) { return true; } else { return false; } } /** * Equation system:<br/> * <br/> * x+2y = 3<br/> * 3x+4y = 10<br/> * <br/> * Solution: {x, y} = {4, -0.5} * * (-0.5 = -1/2 can be precisely represented, see IEEE 754) * * @param x * @param y * @return */ public static bool twoParamsDouble(double x, double y) { // it is usual that the results are saved into variables and the // variables are used in conditional statements double e1 = x + 2 * y; double e2 = 3 * x + 4 * y; if (e1 == 3 && e2 == 10) { return true; } else { return false; } } /** * Equation system:<br/> * <br/> * x+2y+3z = 9<br/> * 3x+y-2z = 10<br/> * 5x-y-z = 23<br/> * <br/> * Solution: {x, y, z} = {198/41, -30/41, 77/41} <br/> * Threshold: 1e-3 (Note: constants and Math.abs() cannot be used because * they may not be supported) * * @param x * @param y * @param z * @return */ public static bool threeParamsDouble(double x, double y, double z) { double e1 = x + 2 * y + 3 * z; double e2 = 3 * x + y - 2 * z; double e3 = 5 * x - y - z; if (8.999 < e1 && e1 < 9.001 && 9.999 < e2 && e2 < 10.001 && 22.999 < e3 && e3 < 23.001) { return true; } else { return false; } } } }
#region /* Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu. All rights reserved. http://code.google.com/p/msnp-sharp/ 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 names of Bas Geertsema or Xih Solutions nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Globalization; namespace MSNPSharp.Core { using MSNPSharp; /// <summary> /// Buffers the incoming data from the notification server (NS). /// </summary> /// <remarks> /// The main purpose of this class is to ensure that MSG, IPG and NOT payload commands are processed /// only when they are complete. Payload commands can be quite large and may be larger /// than the socket buffer. This pool will buffer the data and release the messages, or commands, /// when they are fully retrieved from the server. /// </remarks> public class NSMessagePool : MessagePool, IDisposable { Queue<MemoryStream> messageQueue = new Queue<MemoryStream>(); MemoryStream bufferStream; int remainingBuffer; public NSMessagePool() { CreateNewBuffer(); } ~NSMessagePool() { Dispose(false); } /// <summary> /// Is true when there are message available to retrieve. /// </summary> public override bool MessageAvailable { get { return messageQueue.Count > 0; } } protected Queue<MemoryStream> MessageQueue { get { return messageQueue; } } /// <summary> /// This points to the current message we are writing to. /// </summary> protected MemoryStream BufferStream { get { return bufferStream; } set { bufferStream = value; } } /// <summary> /// Creates a new memorystream to server as the buffer. /// </summary> private void CreateNewBuffer() { bufferStream = new MemoryStream(64); } /// <summary> /// Enques the current buffer memorystem when a message is completely retrieved. /// </summary> private void EnqueueCurrentBuffer() { bufferStream.Position = 0; messageQueue.Enqueue(bufferStream); } /// <summary> /// Get the next message as a byte array. The returned data includes all newlines which seperate the commands ("\r\n") /// </summary> /// <returns></returns> public override byte[] GetNextMessageData() { return messageQueue.Dequeue().ToArray(); } /// <summary> /// Stores the raw data in a buffer. When a full message is detected it is inserted on the internal stack. /// You can retrieve these messages bij calling GetNextMessageData(). /// </summary> /// <param name="reader"></param> public override void BufferData(BinaryReader reader) { int length = (int)(reader.BaseStream.Length - reader.BaseStream.Position); // there is nothing in the bufferstream so we expect a command right away while (length > 0) { // should we buffer the current message if (remainingBuffer > 0) { // read as much as possible in the current message stream int readLength = Math.Min(remainingBuffer, length); byte[] msgBuffer = reader.ReadBytes(readLength); bufferStream.Write(msgBuffer, 0, msgBuffer.Length); // subtract what we have read from the total length remainingBuffer -= readLength; length = (int)(reader.BaseStream.Length - reader.BaseStream.Position); // when we have read everything we can start a new message if (remainingBuffer == 0) { EnqueueCurrentBuffer(); CreateNewBuffer(); } } else { // read until we come across a newline byte val = reader.ReadByte(); bufferStream.WriteByte(val); length--; if (val == '\n') { // read command bufferStream.Position = 0; string cmd3 = System.Text.Encoding.ASCII.GetString(new byte[3] { (byte)bufferStream.ReadByte(), (byte)bufferStream.ReadByte(), (byte)bufferStream.ReadByte() }); switch (cmd3) { #region Known payloads case "SDG": // SDG SendDataGram case "NFY": // NFY Notify PUT/DEL case "PUT": // PUT Put case "DEL": // DEL Delete case "ADL": // ADL Add List case "RML": // RML Remove List case "MSG": // MSG Message case "NOT": // NOT Notification case "GCF": // GCF privacy settings case "GET": // GET case "IPG": // IPG pager command case "FSL": // FSL case "201": // 201 case "203": // 203 case "204": // 204 Invalid contact network in ADL/RML case "205": // 205 case "210": // 210 case "234": // 234 case "241": // 241 Invalid membership for ADL/RML case "508": // 508 case "509": // 509 UpsFailure, when sending mobile message case "511": // 511 case "591": // 591 case "731": // 731 case "801": // 801 case "933": // 933 default: // Unknown command. If the last param is int, assume payload and parse dynamically. { // calculate the length by reading backwards from the end remainingBuffer = 0; bufferStream.Seek(-3, SeekOrigin.End); for (int p = 0, b; ((b = bufferStream.ReadByte()) > 0) && b >= '0' && b <= '9'; p++) { remainingBuffer += (int)((b - '0') * Math.Pow(10, p)); bufferStream.Seek(-2, SeekOrigin.Current); } if (remainingBuffer > 0) { // move to the end of the stream before we are going to write bufferStream.Seek(0, SeekOrigin.End); } else { EnqueueCurrentBuffer(); CreateNewBuffer(); } } break; #endregion #region Known non-payloads case "CHL": case "CVR": case "OUT": case "QNG": case "QRY": case "SBS": case "USR": case "VER": case "XFR": { EnqueueCurrentBuffer(); CreateNewBuffer(); } break; #endregion } } } } } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // Dispose managed resources if (bufferStream != null) bufferStream.Dispose(); if (messageQueue.Count > 0) messageQueue.Clear(); } // Free native resources } #endregion } };
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void OrByte() { var test = new SimpleBinaryOpTest__OrByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__OrByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__OrByte testClass) { var result = Sse2.Or(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrByte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.Or( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__OrByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleBinaryOpTest__OrByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Or( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Or( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Or( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Sse2.Or( Sse2.LoadVector128((Byte*)(pClsVar1)), Sse2.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Sse2.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__OrByte(); var result = Sse2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__OrByte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Sse2.Or( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.Or( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Or( Sse2.LoadVector128((Byte*)(&test._fld1)), Sse2.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((byte)(left[0] | right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((byte)(left[i] | right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Or)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.Runtime.InteropServices; using Grpc.Core; using Grpc.Core.Utils; using Grpc.Core.Profiling; namespace Grpc.Core.Internal { /// <summary> /// grpc_call from <c>grpc/grpc.h</c> /// </summary> internal class CallSafeHandle : SafeHandleZeroIsInvalid, INativeCall { public static readonly CallSafeHandle NullInstance = new CallSafeHandle(); static readonly NativeMethods Native = NativeMethods.Get(); const uint GRPC_WRITE_BUFFER_HINT = 1; CompletionRegistry completionRegistry; CompletionQueueSafeHandle completionQueue; private CallSafeHandle() { } public void Initialize(CompletionRegistry completionRegistry, CompletionQueueSafeHandle completionQueue) { this.completionRegistry = completionRegistry; this.completionQueue = completionQueue; } public void SetCredentials(CallCredentialsSafeHandle credentials) { Native.grpcsharp_call_set_credentials(this, credentials).CheckOk(); } public void StartUnary(UnaryResponseClientHandler callback, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessage(), context.GetReceivedInitialMetadata())); Native.grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray, writeFlags) .CheckOk(); } } public void StartUnary(BatchContextSafeHandle ctx, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags) { using (Profilers.ForCurrentThread().NewScope("CallSafeHandle.StartUnary")) { Native.grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray, writeFlags) .CheckOk(); } } public void StartClientStreaming(UnaryResponseClientHandler callback, MetadataArraySafeHandle metadataArray) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessage(), context.GetReceivedInitialMetadata())); Native.grpcsharp_call_start_client_streaming(this, ctx, metadataArray).CheckOk(); } } public void StartServerStreaming(ReceivedStatusOnClientHandler callback, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient())); Native.grpcsharp_call_start_server_streaming(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray, writeFlags).CheckOk(); } } public void StartDuplexStreaming(ReceivedStatusOnClientHandler callback, MetadataArraySafeHandle metadataArray) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient())); Native.grpcsharp_call_start_duplex_streaming(this, ctx, metadataArray).CheckOk(); } } public void StartSendMessage(SendCompletionHandler callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); Native.grpcsharp_call_send_message(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, sendEmptyInitialMetadata).CheckOk(); } } public void StartSendCloseFromClient(SendCompletionHandler callback) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); Native.grpcsharp_call_send_close_from_client(this, ctx).CheckOk(); } } public void StartSendStatusFromServer(SendCompletionHandler callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); Native.grpcsharp_call_send_status_from_server(this, ctx, status.StatusCode, status.Detail, metadataArray, sendEmptyInitialMetadata).CheckOk(); } } public void StartReceiveMessage(ReceivedMessageHandler callback) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedMessage())); Native.grpcsharp_call_recv_message(this, ctx).CheckOk(); } } public void StartReceiveInitialMetadata(ReceivedResponseHeadersHandler callback) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedInitialMetadata())); Native.grpcsharp_call_recv_initial_metadata(this, ctx).CheckOk(); } } public void StartServerSide(ReceivedCloseOnServerHandler callback) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedCloseOnServerCancelled())); Native.grpcsharp_call_start_serverside(this, ctx).CheckOk(); } } public void StartSendInitialMetadata(SendCompletionHandler callback, MetadataArraySafeHandle metadataArray) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); Native.grpcsharp_call_send_initial_metadata(this, ctx, metadataArray).CheckOk(); } } public void Cancel() { Native.grpcsharp_call_cancel(this).CheckOk(); } public void CancelWithStatus(Status status) { Native.grpcsharp_call_cancel_with_status(this, status.StatusCode, status.Detail).CheckOk(); } public string GetPeer() { using (var cstring = Native.grpcsharp_call_get_peer(this)) { return cstring.GetValue(); } } protected override bool ReleaseHandle() { Native.grpcsharp_call_destroy(handle); return true; } private static uint GetFlags(bool buffered) { return buffered ? 0 : GRPC_WRITE_BUFFER_HINT; } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeFixes.Async; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Async { public partial class AddAwaitTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand1() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { [|return Test();|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { return await Test(); } }"; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_WithLeadingTrivia1() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { return // Useful comment [|Test()|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { return // Useful comment await Test(); } }"; await TestAsync(initial, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_SingleLine() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() {[| return true ? Test() /* true */ : Test() /* false */; |]} }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (true ? Test() /* true */ : Test() /* false */); } }"; await TestAsync(initial, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_Multiline() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() {[| return true ? Test() // aaa : Test() // bbb ; |]} }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (true ? Test() // aaa : Test()) // bbb ; } }"; await TestAsync(initial, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_SingleLine() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() {[| return null /* 0 */ ?? Test() /* 1 */; |]} }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (null /* 0 */ ?? Test() /* 1 */); } }"; await TestAsync(initial, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_Multiline() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() {[| return null // aaa ?? Test() // bbb ; |]} }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (null // aaa ?? Test()) // bbb ; } }"; await TestAsync(initial, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_SingleLine() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test2() {[| return null /* 0 */ as Task<int> /* 1 */; |]} }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test2() { return await (null /* 0 */ as Task<int> /* 1 */); } }"; await TestAsync(initial, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_Multiline() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() {[| return null // aaa as Task<int> // bbb ; |]} }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (null // aaa as Task<int>) // bbb ; } }"; await TestAsync(initial, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TaskNotAwaited() { var initial = @"using System; using System.Threading.Tasks; class Program { async void Test() { [|Task.Delay(3);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async void Test() { await Task.Delay(3); } }"; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TaskNotAwaited_WithLeadingTrivia() { var initial = @"using System; using System.Threading.Tasks; class Program { async void Test() { // Useful comment [|Task.Delay(3);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async void Test() { // Useful comment await Task.Delay(3); } }"; await TestAsync(initial, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task FunctionNotAwaited() { var initial = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { [|AwaitableFunction();|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { await AwaitableFunction(); } }"; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task FunctionNotAwaited_WithLeadingTrivia() { var initial = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { // Useful comment [|AwaitableFunction();|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { // Useful comment await AwaitableFunction(); } }"; await TestAsync(initial, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task FunctionNotAwaited_WithLeadingTrivia1() { var initial = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { var i = 0; [|AwaitableFunction();|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { var i = 0; await AwaitableFunction(); } }"; await TestAsync(initial, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression() { await TestAsync( @"using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { int myInt = [|MyIntMethodAsync ( )|] ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } ", @"using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { int myInt = await MyIntMethodAsync ( ) ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpressionWithConversion() { await TestAsync( @"using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { long myInt = [|MyIntMethodAsync ( )|] ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } ", @"using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { long myInt = await MyIntMethodAsync ( ) ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpressionWithConversionInNonAsyncFunction() { await TestMissingAsync( @"using System . Threading . Tasks ; class TestClass { private Task MyTestMethod1Async ( ) { long myInt = [|MyIntMethodAsync ( )|] ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpressionWithConversionInAsyncFunction() { await TestAsync( @"using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { long myInt = [|MyIntMethodAsync ( )|] ; } private Task < object > MyIntMethodAsync ( ) { return Task . FromResult ( new object ( ) ) ; } } ", @"using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { long myInt = await MyIntMethodAsync ( ) ; } private Task < object > MyIntMethodAsync ( ) { return Task . FromResult ( new object ( ) ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression1() { await TestAsync( @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Action lambda = async ( ) => { int myInt = [|MyIntMethodAsync ( )|] ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } ", @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Action lambda = async ( ) => { int myInt = await MyIntMethodAsync ( ) ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression2() { await TestAsync( @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Func < Task > lambda = async ( ) => { int myInt = [|MyIntMethodAsync ( )|] ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } ", @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Func < Task > lambda = async ( ) => { int myInt = await MyIntMethodAsync ( ) ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression3() { await TestMissingAsync( @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Func < Task > lambda = ( ) => { int myInt = MyInt [||] MethodAsync ( ) ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression4() { await TestMissingAsync( @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Action lambda = ( ) => { int myInt = MyIntM [||] ethodAsync ( ) ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression5() { await TestAsync( @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Action @delegate = async delegate { int myInt = [|MyIntMethodAsync ( )|] ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } ", @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Action @delegate = async delegate { int myInt = await MyIntMethodAsync ( ) ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression6() { await TestAsync( @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Func < Task > @delegate = async delegate { int myInt = [|MyIntMethodAsync ( )|] ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } ", @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Func < Task > @delegate = async delegate { int myInt = await MyIntMethodAsync ( ) ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression7() { await TestMissingAsync( @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Action @delegate = delegate { int myInt = MyInt [||] MethodAsync ( ) ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression8() { await TestMissingAsync( @"using System ; using System . Threading . Tasks ; class TestClass { private async Task MyTestMethod1Async ( ) { Func < Task > @delegate = delegate { int myInt = MyIntM [||] ethodAsync ( ) ; } ; } private Task < int > MyIntMethodAsync ( ) { return Task . FromResult ( result : 1 ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestTernaryOperator() { await TestAsync( @"using System ; using System . Threading . Tasks ; class Program { async Task < int > A ( ) { return [|true ? Task . FromResult ( 0 ) : Task . FromResult ( 1 )|] ; } } ", @"using System ; using System . Threading . Tasks ; class Program { async Task < int > A ( ) { return await ( true ? Task . FromResult ( 0 ) : Task . FromResult ( 1 ) ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestNullCoalescingOperator() { await TestAsync( @"using System ; using System . Threading . Tasks ; class Program { async Task < int > A ( ) { return [|null ?? Task . FromResult ( 1 )|] } } ", @"using System ; using System . Threading . Tasks ; class Program { async Task < int > A ( ) { return await ( null ?? Task . FromResult ( 1 ) ) } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAsExpression() { await TestAsync( @"using System ; using System . Threading . Tasks ; class Program { async Task < int > A ( ) { return [|null as Task < int >|] } } ", @"using System ; using System . Threading . Tasks ; class Program { async Task < int > A ( ) { return await ( null as Task < int > ) } } "); } internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(null, new CSharpAddAwaitCodeFixProvider()); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Marten.Linq; using Marten.Services.BatchQuerying; using Npgsql; namespace Marten { public interface IQuerySession : IDisposable { /// <summary> /// Find or load a single document of type T by a string id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <returns></returns> T Load<T>(string id); /// <summary> /// Asynchronously find or load a single document of type T by a string id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <param name="token"></param> /// <returns></returns> Task<T> LoadAsync<T>(string id, CancellationToken token = default(CancellationToken)); /// <summary> /// Load or find a single document of type T with either a numeric or Guid id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <returns></returns> T Load<T>(int id); /// <summary> /// Load or find a single document of type T with either a numeric or Guid id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <returns></returns> T Load<T>(long id); /// <summary> /// Load or find a single document of type T with either a numeric or Guid id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <returns></returns> T Load<T>(Guid id); /// <summary> /// Asynchronously load or find a single document of type T with either a numeric or Guid id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <param name="token"></param> /// <returns></returns> Task<T> LoadAsync<T>(int id, CancellationToken token = default(CancellationToken)); /// <summary> /// Asynchronously load or find a single document of type T with either a numeric or Guid id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <param name="token"></param> /// <returns></returns> Task<T> LoadAsync<T>(long id, CancellationToken token = default(CancellationToken)); /// <summary> /// Asynchronously load or find a single document of type T with either a numeric or Guid id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <param name="token"></param> /// <returns></returns> Task<T> LoadAsync<T>(Guid id, CancellationToken token = default(CancellationToken)); // SAMPLE: querying_with_linq /// <summary> /// Use Linq operators to query the documents /// stored in Postgresql /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> IMartenQueryable<T> Query<T>(); // ENDSAMPLE /// <summary> /// Queries the document storage table for the document type T by supplied SQL. See http://jasperfx.github.io/marten/documentation/documents/querying/sql/ for more information on usage. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="parameters"></param> /// <returns></returns> IList<T> Query<T>(string sql, params object[] parameters); /// <summary> /// Asynchronously queries the document storage table for the document type T by supplied SQL. See http://jasperfx.github.io/marten/documentation/documents/querying/sql/ for more information on usage. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="token"></param> /// <param name="parameters"></param> /// <returns></returns> Task<IList<T>> QueryAsync<T>(string sql, CancellationToken token = default(CancellationToken), params object[] parameters); /// <summary> /// Define a batch of deferred queries and load operations to be conducted in one asynchronous request to the /// database for potentially performance /// </summary> /// <returns></returns> IBatchedQuery CreateBatchQuery(); /// <summary> /// The currently open Npgsql connection for this session. Use with caution. /// </summary> NpgsqlConnection Connection { get; } /// <summary> /// The session specific logger for this session. Can be set for better integration /// with custom diagnostics /// </summary> IMartenSessionLogger Logger { get; set; } /// <summary> /// Request count /// </summary> int RequestCount { get; } /// <summary> /// The document store that created this session /// </summary> IDocumentStore DocumentStore { get; } /// <summary> /// A query that is compiled so a copy of the DbCommand can be used directly in subsequent requests. /// </summary> /// <typeparam name="TDoc">The document</typeparam> /// <typeparam name="TOut">The output</typeparam> /// <param name="query">The instance of a compiled query</param> /// <returns>A single item query result</returns> TOut Query<TDoc, TOut>(ICompiledQuery<TDoc, TOut> query); /// <summary> /// An async query that is compiled so a copy of the DbCommand can be used directly in subsequent requests. /// </summary> /// <typeparam name="TDoc">The document</typeparam> /// <typeparam name="TOut">The output</typeparam> /// <param name="query">The instance of a compiled query</param> /// <param name="token">A cancellation token</param> /// <returns>A task for a single item query result</returns> Task<TOut> QueryAsync<TDoc, TOut>(ICompiledQuery<TDoc, TOut> query, CancellationToken token = default(CancellationToken)); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> IList<T> LoadMany<T>(params string[] ids); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> IList<T> LoadMany<T>(params Guid[] ids); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> IList<T> LoadMany<T>(params int[] ids); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> IList<T> LoadMany<T>(params long[] ids); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> Task<IList<T>> LoadManyAsync<T>(params string[] ids); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> Task<IList<T>> LoadManyAsync<T>(params Guid[] ids); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> Task<IList<T>> LoadManyAsync<T>(params int[] ids); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> Task<IList<T>> LoadManyAsync<T>(params long[] ids); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> Task<IList<T>> LoadManyAsync<T>(CancellationToken token, params string[] ids); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> Task<IList<T>> LoadManyAsync<T>(CancellationToken token, params Guid[] ids); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> Task<IList<T>> LoadManyAsync<T>(CancellationToken token, params int[] ids); /// <summary> /// Load or find multiple documents by id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> Task<IList<T>> LoadManyAsync<T>(CancellationToken token, params long[] ids); /// <summary> /// Directly load the persisted JSON data for documents by Id /// </summary> IJsonLoader Json { get; } } }
// // System.IO.Path Test Cases // // Authors: // Marcin Szczepanski ([email protected]) // Gonzalo Paniagua Javier ([email protected]) // Ben Maurer ([email protected]) // Gilles Freart ([email protected]) // Atsushi Enomoto ([email protected]) // // (c) Marcin Szczepanski // (c) 2002 Ximian, Inc. (http://www.ximian.com) // (c) 2003 Ben Maurer // (c) 2003 Gilles Freart // using NUnit.Framework; using System.IO; using System; using System.Text; namespace MonoTests.System.IO { enum OsType { Windows, Unix, Mac } [TestFixture] public class PathTest : Assertion { static string path1; static string path2; static string path3; static OsType OS; static char DSC = Path.DirectorySeparatorChar; [SetUp] public void SetUp () { if ('/' == DSC) { OS = OsType.Unix; path1 = "/foo/test.txt"; path2 = "/etc"; path3 = "init.d"; } else if ('\\' == DSC) { OS = OsType.Windows; path1 = "c:\\foo\\test.txt"; path2 = Environment.GetEnvironmentVariable ("SYSTEMROOT"); path3 = "system32"; } else { OS = OsType.Mac; //FIXME: For Mac. figure this out when we need it path1 = "foo:test.txt"; path2 = "foo"; path3 = "bar"; } } bool Windows { get { return OS == OsType.Windows; } } bool Unix { get { return OS == OsType.Unix; } } bool Mac { get { return OS == OsType.Mac; } } public void TestChangeExtension () { string [] files = new string [3]; files [(int) OsType.Unix] = "/foo/test.doc"; files [(int) OsType.Windows] = "c:\\foo\\test.doc"; files [(int) OsType.Mac] = "foo:test.doc"; string testPath = Path.ChangeExtension (path1, "doc"); AssertEquals ("ChangeExtension #01", files [(int) OS], testPath); testPath = Path.ChangeExtension ("", ".extension"); AssertEquals ("ChangeExtension #02", String.Empty, testPath); testPath = Path.ChangeExtension (null, ".extension"); AssertEquals ("ChangeExtension #03", null, testPath); testPath = Path.ChangeExtension ("path", null); AssertEquals ("ChangeExtension #04", "path", testPath); testPath = Path.ChangeExtension ("path.ext", "doc"); AssertEquals ("ChangeExtension #05", "path.doc", testPath); testPath = Path.ChangeExtension ("path.ext1.ext2", "doc"); AssertEquals ("ChangeExtension #06", "path.ext1.doc", testPath); testPath = Path.ChangeExtension ("hogehoge.xml", ".xsl"); AssertEquals ("ChangeExtension #07", "hogehoge.xsl", testPath); testPath = Path.ChangeExtension ("hogehoge", ".xsl"); AssertEquals ("ChangeExtension #08", "hogehoge.xsl", testPath); testPath = Path.ChangeExtension ("hogehoge.xml", "xsl"); AssertEquals ("ChangeExtension #09", "hogehoge.xsl", testPath); testPath = Path.ChangeExtension ("hogehoge", "xsl"); AssertEquals ("ChangeExtension #10", "hogehoge.xsl", testPath); testPath = Path.ChangeExtension ("hogehoge.xml", String.Empty); AssertEquals ("ChangeExtension #11", "hogehoge.", testPath); testPath = Path.ChangeExtension ("hogehoge", String.Empty); AssertEquals ("ChangeExtension #12", "hogehoge.", testPath); testPath = Path.ChangeExtension ("hogehoge.", null); AssertEquals ("ChangeExtension #13", "hogehoge", testPath); testPath = Path.ChangeExtension ("hogehoge", null); AssertEquals ("ChangeExtension #14", "hogehoge", testPath); testPath = Path.ChangeExtension (String.Empty, null); AssertEquals ("ChangeExtension #15", String.Empty, testPath); testPath = Path.ChangeExtension (String.Empty, "bashrc"); AssertEquals ("ChangeExtension #16", String.Empty, testPath); testPath = Path.ChangeExtension (String.Empty, ".bashrc"); AssertEquals ("ChangeExtension #17", String.Empty, testPath); testPath = Path.ChangeExtension (null, null); AssertNull ("ChangeExtension #18", testPath); } [Test] [ExpectedException (typeof (ArgumentException))] public void ChangeExtension_BadPath () { if (!Windows) throw new ArgumentException ("Test Only On Windows"); Path.ChangeExtension ("<", ".extension"); } [Test] public void ChangeExtension_BadExtension () { if (Windows) { string fn = Path.ChangeExtension ("file.ext", "<"); AssertEquals ("Invalid filename", "file.<", fn); } } public void TestCombine () { string [] files = new string [3]; files [(int) OsType.Unix] = "/etc/init.d"; files [(int) OsType.Windows] = Environment.GetEnvironmentVariable ("SYSTEMROOT") + @"\system32"; files [(int) OsType.Mac] = "foo:bar"; string testPath = Path.Combine (path2, path3); AssertEquals ("Combine #01", files [(int) OS], testPath); testPath = Path.Combine ("one", ""); AssertEquals ("Combine #02", "one", testPath); testPath = Path.Combine ("", "one"); AssertEquals ("Combine #03", "one", testPath); string current = Directory.GetCurrentDirectory (); testPath = Path.Combine (current, "one"); string expected = current + DSC + "one"; AssertEquals ("Combine #04", expected, testPath); testPath = Path.Combine ("one", current); // LAMESPEC noted in Path.cs AssertEquals ("Combine #05", current, testPath); testPath = Path.Combine (current, expected); AssertEquals ("Combine #06", expected, testPath); testPath = DSC + "one"; testPath = Path.Combine (testPath, "two" + DSC); expected = DSC + "one" + DSC + "two" + DSC; AssertEquals ("Combine #06", expected, testPath); testPath = "one" + DSC; testPath = Path.Combine (testPath, DSC + "two"); expected = DSC + "two"; AssertEquals ("Combine #06", expected, testPath); testPath = "one" + DSC; testPath = Path.Combine (testPath, "two" + DSC); expected = "one" + DSC + "two" + DSC; AssertEquals ("Combine #07", expected, testPath); //TODO: Tests for UNC names try { testPath = Path.Combine ("one", null); Fail ("Combine Fail #01"); } catch (Exception e) { AssertEquals ("Combine Exc. #01", typeof (ArgumentNullException), e.GetType ()); } try { testPath = Path.Combine (null, "one"); Fail ("Combine Fail #02"); } catch (Exception e) { AssertEquals ("Combine Exc. #02", typeof (ArgumentNullException), e.GetType ()); } if (Windows) { try { testPath = Path.Combine ("a>", "one"); Fail ("Combine Fail #03"); } catch (Exception e) { AssertEquals ("Combine Exc. #03", typeof (ArgumentException), e.GetType ()); } try { testPath = Path.Combine ("one", "aaa<"); Fail ("Combine Fail #04"); } catch (Exception e) { AssertEquals ("Combine Exc. #04", typeof (ArgumentException), e.GetType ()); } } } [Test] [ExpectedException (typeof(ArgumentException))] public void EmptyDirectoryName () { string testDirName = Path.GetDirectoryName (""); } public void TestDirectoryName () { string [] files = new string [3]; files [(int) OsType.Unix] = "/foo"; files [(int) OsType.Windows] = "c:\\foo"; files [(int) OsType.Mac] = "foo"; AssertEquals ("GetDirectoryName #01", null, Path.GetDirectoryName (null)); string testDirName = Path.GetDirectoryName (path1); AssertEquals ("GetDirectoryName #02", files [(int) OS], testDirName); testDirName = Path.GetDirectoryName (files [(int) OS] + DSC); AssertEquals ("GetDirectoryName #03", files [(int) OS], testDirName); if (Windows) { try { testDirName = Path.GetDirectoryName ("aaa>"); Fail ("GetDirectoryName Fail #02"); } catch (Exception e) { AssertEquals ("GetDirectoryName Exc. #02", typeof (ArgumentException), e.GetType ()); } } try { testDirName = Path.GetDirectoryName (" "); Fail ("GetDirectoryName Fail #03"); } catch (Exception e) { AssertEquals ("GetDirectoryName Exc. #03", typeof (ArgumentException), e.GetType ()); } } public void TestGetExtension () { string testExtn = Path.GetExtension (path1); AssertEquals ("GetExtension #01", ".txt", testExtn); testExtn = Path.GetExtension (path2); AssertEquals ("GetExtension #02", String.Empty, testExtn); testExtn = Path.GetExtension (String.Empty); AssertEquals ("GetExtension #03", String.Empty, testExtn); testExtn = Path.GetExtension (null); AssertEquals ("GetExtension #04", null, testExtn); testExtn = Path.GetExtension (" "); AssertEquals ("GetExtension #05", String.Empty, testExtn); testExtn = Path.GetExtension (path1 + ".doc"); AssertEquals ("GetExtension #06", ".doc", testExtn); testExtn = Path.GetExtension (path1 + ".doc" + DSC + "a.txt"); AssertEquals ("GetExtension #07", ".txt", testExtn); testExtn = Path.GetExtension ("."); AssertEquals ("GetExtension #08", String.Empty, testExtn); testExtn = Path.GetExtension ("end."); AssertEquals ("GetExtension #09", String.Empty, testExtn); testExtn = Path.GetExtension (".start"); AssertEquals ("GetExtension #10", ".start", testExtn); testExtn = Path.GetExtension (".a"); AssertEquals ("GetExtension #11", ".a", testExtn); testExtn = Path.GetExtension ("a."); AssertEquals ("GetExtension #12", String.Empty, testExtn); testExtn = Path.GetExtension ("a"); AssertEquals ("GetExtension #13", String.Empty, testExtn); testExtn = Path.GetExtension ("makefile"); AssertEquals ("GetExtension #14", String.Empty, testExtn); if (Windows) { try { testExtn = Path.GetExtension ("hi<there.txt"); Fail ("GetExtension Fail #01"); } catch (Exception e) { AssertEquals ("GetExtension Exc. #01", typeof (ArgumentException), e.GetType ()); } } } public void TestGetFileName () { string testFileName = Path.GetFileName (path1); AssertEquals ("GetFileName #01", "test.txt", testFileName); testFileName = Path.GetFileName (null); AssertEquals ("GetFileName #02", null, testFileName); testFileName = Path.GetFileName (String.Empty); AssertEquals ("GetFileName #03", String.Empty, testFileName); testFileName = Path.GetFileName (" "); AssertEquals ("GetFileName #04", " ", testFileName); if (Windows) { try { testFileName = Path.GetFileName ("hi<"); Fail ("GetFileName Fail #01"); } catch (Exception e) { AssertEquals ("GetFileName Exc. #01", typeof (ArgumentException), e.GetType ()); } } } public void TestGetFileNameWithoutExtension () { string testFileName = Path.GetFileNameWithoutExtension (path1); AssertEquals ("GetFileNameWithoutExtension #01", "test", testFileName); testFileName = Path.GetFileNameWithoutExtension (null); AssertEquals ("GetFileNameWithoutExtension #02", null, testFileName); testFileName = Path.GetFileNameWithoutExtension (String.Empty); AssertEquals ("GetFileNameWithoutExtension #03", String.Empty, testFileName); } [Ignore("This does not work under windows. See ERROR comments below.")] public void TestGetFullPath () { string current = Directory.GetCurrentDirectory (); string testFullPath = Path.GetFullPath ("foo.txt"); string expected = current + DSC + "foo.txt"; AssertEquals ("GetFullPath #01", expected, testFullPath); testFullPath = Path.GetFullPath ("a//./.././foo.txt"); AssertEquals ("GetFullPath #02", expected, testFullPath); string root = Windows ? "C:\\" : "/"; string [,] test = new string [,] { {"root////././././././../root/././../root", "root"}, {"root/", "root/"}, {"root/./", "root/"}, {"root/./", "root/"}, {"root/../", ""}, {"root/../", ""}, {"root/../..", ""}, {"root/.hiddenfile", "root/.hiddenfile"}, {"root/. /", "root/. /"}, {"root/.. /", "root/.. /"}, {"root/..weirdname", "root/..weirdname"}, {"root/..", ""}, {"root/../a/b/../../..", ""}, {"root/./..", ""}, {"..", ""}, {".", ""}, {"root//dir", "root/dir"}, {"root/. /", "root/. /"}, {"root/.. /", "root/.. /"}, {"root/ . /", "root/ . /"}, {"root/ .. /", "root/ .. /"}, {"root/./", "root/"}, //ERROR! Paths are trimmed {"root/.. /", "root/.. /"}, {".//", ""} }; //ERROR! GetUpperBound (1) returns 1. GetUpperBound (0) == 23 //... so only the first test was being done. for (int i = 0; i < test.GetUpperBound (1); i++) { AssertEquals (String.Format ("GetFullPath #{0}", i), root + test [i, 1], Path.GetFullPath (root + test [i, 0])); } if (Windows) { string uncroot = @"\\server\share\"; string [,] testunc = new string [,] { {"root////././././././../root/././../root", "root"}, {"root/", "root/"}, {"root/./", "root/"}, {"root/./", "root/"}, {"root/../", ""}, {"root/../", ""}, {"root/../..", ""}, {"root/.hiddenfile", "root/.hiddenfile"}, {"root/. /", "root/. /"}, {"root/.. /", "root/.. /"}, {"root/..weirdname", "root/..weirdname"}, {"root/..", ""}, {"root/../a/b/../../..", ""}, {"root/./..", ""}, {"..", ""}, {".", ""}, {"root//dir", "root/dir"}, {"root/. /", "root/. /"}, {"root/.. /", "root/.. /"}, {"root/ . /", "root/ . /"}, {"root/ .. /", "root/ .. /"}, {"root/./", "root/"}, {"root/.. /", "root/.. /"}, {".//", ""} }; for (int i = 0; i < test.GetUpperBound (1); i++) { AssertEquals (String.Format ("GetFullPath UNC #{0}", i), uncroot + test [i, 1], Path.GetFullPath (uncroot + test [i, 0])); } } try { testFullPath = Path.GetFullPath (null); Fail ("GetFullPath Fail #01"); } catch (Exception e) { AssertEquals ("GetFullPath Exc. #01", typeof (ArgumentNullException), e.GetType ()); } try { testFullPath = Path.GetFullPath (String.Empty); Fail ("GetFullPath Fail #02"); } catch (Exception e) { AssertEquals ("GetFullPath Exc. #02", typeof (ArgumentException), e.GetType ()); } } public void TestGetFullPath2 () { if (Windows) { AssertEquals ("GetFullPath w#01", @"Z:\", Path.GetFullPath ("Z:")); AssertEquals ("GetFullPath w#02", @"c:\abc\def", Path.GetFullPath (@"c:\abc\def")); Assert ("GetFullPath w#03", Path.GetFullPath (@"\").EndsWith (@"\")); // "\\\\" is not allowed Assert ("GetFullPath w#05", Path.GetFullPath ("/").EndsWith (@"\")); // "//" is not allowed Assert ("GetFullPath w#07", Path.GetFullPath ("readme.txt").EndsWith (@"\readme.txt")); Assert ("GetFullPath w#08", Path.GetFullPath ("c").EndsWith (@"\c")); Assert ("GetFullPath w#09", Path.GetFullPath (@"abc\def").EndsWith (@"abc\def")); Assert ("GetFullPath w#10", Path.GetFullPath (@"\abc\def").EndsWith (@"\abc\def")); AssertEquals ("GetFullPath w#11", @"\\abc\def", Path.GetFullPath (@"\\abc\def")); AssertEquals ("GetFullPath w#12", Directory.GetCurrentDirectory () + @"\abc\def", Path.GetFullPath (@"abc//def")); AssertEquals ("GetFullPath w#13", Directory.GetCurrentDirectory ().Substring (0,2) + @"\abc\def", Path.GetFullPath ("/abc/def")); AssertEquals ("GetFullPath w#14", @"\\abc\def", Path.GetFullPath ("//abc/def")); } } public void TestGetPathRoot () { string current; string expected; if (!Windows){ current = Directory.GetCurrentDirectory (); expected = current [0].ToString (); } else { current = @"J:\Some\Strange Directory\Name"; expected = "J:\\"; } string pathRoot = Path.GetPathRoot (current); AssertEquals ("GetPathRoot #01", expected, pathRoot); } [Test] public void TestGetPathRoot2 () { // note: this method doesn't call Directory.GetCurrentDirectory so it can be // reused for partial trust unit tests in PathCas.cs string pathRoot = Path.GetPathRoot ("hola"); AssertEquals ("GetPathRoot #02", String.Empty, pathRoot); pathRoot = Path.GetPathRoot (null); AssertEquals ("GetPathRoot #03", null, pathRoot); if (Windows) { AssertEquals ("GetPathRoot w#01", "z:", Path.GetPathRoot ("z:")); AssertEquals ("GetPathRoot w#02", "c:\\", Path.GetPathRoot ("c:\\abc\\def")); AssertEquals ("GetPathRoot w#03", "\\", Path.GetPathRoot ("\\")); AssertEquals ("GetPathRoot w#04", "\\\\", Path.GetPathRoot ("\\\\")); AssertEquals ("GetPathRoot w#05", "\\", Path.GetPathRoot ("/")); AssertEquals ("GetPathRoot w#06", "\\\\", Path.GetPathRoot ("//")); AssertEquals ("GetPathRoot w#07", String.Empty, Path.GetPathRoot ("readme.txt")); AssertEquals ("GetPathRoot w#08", String.Empty, Path.GetPathRoot ("c")); AssertEquals ("GetPathRoot w#09", String.Empty, Path.GetPathRoot ("abc\\def")); AssertEquals ("GetPathRoot w#10", "\\", Path.GetPathRoot ("\\abc\\def")); AssertEquals ("GetPathRoot w#11", "\\\\abc\\def", Path.GetPathRoot ("\\\\abc\\def")); AssertEquals ("GetPathRoot w#12", String.Empty, Path.GetPathRoot ("abc//def")); AssertEquals ("GetPathRoot w#13", "\\", Path.GetPathRoot ("/abc/def")); AssertEquals ("GetPathRoot w#14", "\\\\abc\\def", Path.GetPathRoot ("//abc/def")); } else { // TODO: Same tests for Unix. } } public void TestGetTempPath () { string getTempPath = Path.GetTempPath (); Assert ("GetTempPath #01", getTempPath != String.Empty); Assert ("GetTempPath #02", Path.IsPathRooted (getTempPath)); AssertEquals ("GetTempPath #03", Path.DirectorySeparatorChar, getTempPath [getTempPath.Length - 1]); } public void TestGetTempFileName () { string getTempFileName = null; try { getTempFileName = Path.GetTempFileName (); Assert ("GetTempFileName #01", getTempFileName != String.Empty); Assert ("GetTempFileName #02", File.Exists (getTempFileName)); } finally { if (getTempFileName != null && getTempFileName != String.Empty){ File.Delete (getTempFileName); } } } public void TestHasExtension () { AssertEquals ("HasExtension #01", true, Path.HasExtension ("foo.txt")); AssertEquals ("HasExtension #02", false, Path.HasExtension ("foo")); AssertEquals ("HasExtension #03", true, Path.HasExtension (path1)); AssertEquals ("HasExtension #04", false, Path.HasExtension (path2)); AssertEquals ("HasExtension #05", false, Path.HasExtension (null)); AssertEquals ("HasExtension #06", false, Path.HasExtension (String.Empty)); AssertEquals ("HasExtension #07", false, Path.HasExtension (" ")); AssertEquals ("HasExtension #08", false, Path.HasExtension (".")); AssertEquals ("HasExtension #09", false, Path.HasExtension ("end.")); AssertEquals ("HasExtension #10", true, Path.HasExtension (".start")); AssertEquals ("HasExtension #11", true, Path.HasExtension (".a")); AssertEquals ("HasExtension #12", false, Path.HasExtension ("a.")); AssertEquals ("HasExtension #13", false, Path.HasExtension ("Makefile")); } public void TestRooted () { Assert ("IsPathRooted #01", Path.IsPathRooted (path2)); Assert ("IsPathRooted #02", !Path.IsPathRooted (path3)); Assert ("IsPathRooted #03", !Path.IsPathRooted (null)); Assert ("IsPathRooted #04", !Path.IsPathRooted (String.Empty)); Assert ("IsPathRooted #05", !Path.IsPathRooted (" ")); Assert ("IsPathRooted #06", Path.IsPathRooted ("/")); if (Windows) Assert ("IsPathRooted #07", Path.IsPathRooted ("\\")); else Assert ("IsPathRooted #07", !Path.IsPathRooted ("\\")); Assert ("IsPathRooted #08", Path.IsPathRooted ("//")); if (Windows) Assert ("IsPathRooted #09", Path.IsPathRooted ("\\\\")); else Assert ("IsPathRooted #09", !Path.IsPathRooted ("\\\\")); Assert ("IsPathRooted #10", !Path.IsPathRooted (":")); if (Windows) Assert ("IsPathRooted #11", Path.IsPathRooted ("z:")); else Assert ("IsPathRooted #11", !Path.IsPathRooted ("z:")); if (Windows) { Assert ("IsPathRooted #12", Path.IsPathRooted ("z:\\")); Assert ("IsPathRooted #13", Path.IsPathRooted ("z:\\topdir")); // This looks MS BUG. It is treated as absolute path Assert ("IsPathRooted #14", Path.IsPathRooted ("z:curdir")); Assert ("IsPathRooted #15", Path.IsPathRooted ("\\abc\\def")); } } public void TestCanonicalizeDots () { string current = Path.GetFullPath ("."); Assert ("TestCanonicalizeDotst #01", !current.EndsWith (".")); string parent = Path.GetFullPath (".."); Assert ("TestCanonicalizeDotst #02", !current.EndsWith ("..")); } public void TestDirectoryNameBugs () { if (Windows) { AssertEquals ("Win #01", "C:\\foo", Path.GetDirectoryName ("C:\\foo\\foo.txt")); } else { AssertEquals ("No win #01", "/etc", Path.GetDirectoryName ("/etc/hostname")); } } public void TestGetFullPathUnix () { if (Windows) return; AssertEquals ("#01", "/", Path.GetFullPath ("/")); AssertEquals ("#02", "/hey", Path.GetFullPath ("/hey")); AssertEquals ("#03", Environment.CurrentDirectory, Path.GetFullPath (".")); AssertEquals ("#04", Path.Combine (Environment.CurrentDirectory, "hey"), Path.GetFullPath ("hey")); } } }
using System; using Tweetinvi.Models; using Tweetinvi.Parameters; namespace Tweetinvi.Core.Client.Validators { public interface ITwitterListsClientRequiredParametersValidator : ITwitterListsClientParametersValidator { } public class TwitterListsClientRequiredParametersValidator : ITwitterListsClientRequiredParametersValidator { private readonly IUserQueryValidator _userQueryValidator; public TwitterListsClientRequiredParametersValidator(IUserQueryValidator userQueryValidator) { _userQueryValidator = userQueryValidator; } public void Validate(ICreateListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (string.IsNullOrEmpty(parameters.Name)) { throw new ArgumentNullException($"{nameof(parameters.Name)}"); } } public void Validate(IGetListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); } public void Validate(IGetListsSubscribedByUserParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } } public void Validate(IUpdateListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); } public void Validate(IDestroyListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); } public void Validate(IGetListsOwnedByAccountParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } } public void Validate(IGetListsOwnedByUserParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } _userQueryValidator.ThrowIfUserCannotBeIdentified(parameters.User); } public void Validate(IGetTweetsFromListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); } public void Validate(IAddMemberToListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); _userQueryValidator.ThrowIfUserCannotBeIdentified(parameters.User); } public void Validate(IAddMembersToListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); } public void Validate(IGetUserListMembershipsParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } _userQueryValidator.ThrowIfUserCannotBeIdentified(parameters.User); } public void Validate(IGetMembersOfListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); } public void Validate(ICheckIfUserIsMemberOfListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); _userQueryValidator.ThrowIfUserCannotBeIdentified(parameters.User); } public void Validate(IRemoveMemberFromListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); _userQueryValidator.ThrowIfUserCannotBeIdentified(parameters.User); } public void Validate(IRemoveMembersFromListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); } public void Validate(IGetAccountListMembershipsParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } } // SUBSCRIBERS public void Validate(ISubscribeToListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); } public void Validate(IUnsubscribeFromListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); } public void Validate(IGetListSubscribersParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); } public void Validate(IGetAccountListSubscriptionsParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } } public void Validate(IGetUserListSubscriptionsParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } _userQueryValidator.ThrowIfUserCannotBeIdentified(parameters.User); } public void Validate(ICheckIfUserIsSubscriberOfListParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } ThrowIfListIdentifierIsNotValid(parameters.List); _userQueryValidator.ThrowIfUserCannotBeIdentified(parameters.User); } public void ThrowIfListIdentifierIsNotValid(ITwitterListIdentifier twitterListIdentifier) { if (twitterListIdentifier == null) { throw new ArgumentNullException(nameof(twitterListIdentifier), $"{nameof(twitterListIdentifier)} cannot be null"); } var isIdValid = twitterListIdentifier.Id > 0; var isSlugWithUsernameValid = twitterListIdentifier.Slug != null && (twitterListIdentifier.OwnerScreenName != null || twitterListIdentifier.OwnerId > 0); if (!isIdValid && !isSlugWithUsernameValid) { throw new ArgumentException("List identifier(id or slug + userIdentifier) must be specified."); } } } }
namespace AutoMapper { using System; using System.Collections.Generic; //TODO: may want to make ResolutionContext disposable if it makes sense to do so... /// <summary> /// Context information regarding resolution of a destination value /// </summary> public class ResolutionContext : IEquatable<ResolutionContext> { /// <summary> /// Mapping operation options /// </summary> public MappingOperationOptions Options { get; } /// <summary> /// Current type map /// </summary> public TypeMap TypeMap { get; } /// <summary> /// Current property map /// </summary> public PropertyMap PropertyMap { get; } /// <summary> /// Current source type /// </summary> public Type SourceType { get; } /// <summary> /// Current attempted destination type /// </summary> public Type DestinationType { get; } /// <summary> /// Index of current collection mapping /// </summary> public int? ArrayIndex { get; } /// <summary> /// Source value /// </summary> public object SourceValue { get; } /// <summary> /// Destination value /// </summary> public object DestinationValue { get; private set; } /// <summary> /// Parent resolution context /// </summary> public ResolutionContext Parent { get; } /// <summary> /// Instance cache for resolving circular references /// </summary> public Dictionary<ResolutionContext, object> InstanceCache { get; } /// <summary> /// Current mapper context /// </summary> public IMapperContext MapperContext { get; } /// <summary> /// /// </summary> /// <param name="typeMap"></param> /// <param name="source"></param> /// <param name="sourceType"></param> /// <param name="destinationType"></param> /// <param name="options"></param> /// <param name="mapperContext"></param> public ResolutionContext(TypeMap typeMap, object source, Type sourceType, Type destinationType, MappingOperationOptions options, IMapperContext mapperContext) : this(typeMap, source, null, sourceType, destinationType, options, mapperContext) { } /// <summary> /// /// </summary> /// <param name="typeMap"></param> /// <param name="source"></param> /// <param name="destination"></param> /// <param name="sourceType"></param> /// <param name="destinationType"></param> /// <param name="options"></param> /// <param name="mapperContext"></param> public ResolutionContext(TypeMap typeMap, object source, object destination, Type sourceType, Type destinationType, MappingOperationOptions options, IMapperContext mapperContext) { TypeMap = typeMap; SourceValue = source; DestinationValue = destination; if (typeMap != null) { SourceType = typeMap.SourceType; DestinationType = typeMap.DestinationType; } else { SourceType = sourceType; DestinationType = destinationType; } InstanceCache = new Dictionary<ResolutionContext, object>(); Options = options; MapperContext = mapperContext; } private ResolutionContext(ResolutionContext context, object sourceValue, Type sourceType) { ArrayIndex = context.ArrayIndex; TypeMap = null; PropertyMap = context.PropertyMap; SourceType = sourceType; SourceValue = sourceValue; DestinationValue = context.DestinationValue; Parent = context; DestinationType = context.DestinationType; InstanceCache = context.InstanceCache; Options = context.Options; MapperContext = context.MapperContext; } private ResolutionContext(ResolutionContext context, TypeMap memberTypeMap, object sourceValue, object destinationValue, Type sourceType, Type destinationType) { TypeMap = memberTypeMap; SourceValue = sourceValue; DestinationValue = destinationValue; Parent = context; if (memberTypeMap != null) { SourceType = memberTypeMap.SourceType; DestinationType = memberTypeMap.DestinationType; } else { SourceType = sourceType; DestinationType = destinationType; } InstanceCache = context.InstanceCache; Options = context.Options; MapperContext = context.MapperContext; } private ResolutionContext(ResolutionContext context, object sourceValue, object destinationValue, TypeMap memberTypeMap, PropertyMap propertyMap) { TypeMap = memberTypeMap; PropertyMap = propertyMap; SourceValue = sourceValue; DestinationValue = destinationValue; Parent = context; InstanceCache = context.InstanceCache; SourceType = memberTypeMap.SourceType; DestinationType = memberTypeMap.DestinationType; Options = context.Options; MapperContext = context.MapperContext; } private ResolutionContext(ResolutionContext context, object sourceValue, object destinationValue, Type sourceType, PropertyMap propertyMap) { PropertyMap = propertyMap; SourceType = sourceType; SourceValue = sourceValue; DestinationValue = destinationValue; Parent = context; DestinationType = propertyMap.DestinationProperty.MemberType; InstanceCache = context.InstanceCache; Options = context.Options; MapperContext = context.MapperContext; } private ResolutionContext(ResolutionContext context, object sourceValue, TypeMap typeMap, Type sourceType, Type destinationType, int arrayIndex) { ArrayIndex = arrayIndex; TypeMap = typeMap; PropertyMap = context.PropertyMap; SourceValue = sourceValue; Parent = context; InstanceCache = context.InstanceCache; if (typeMap != null) { SourceType = typeMap.SourceType; DestinationType = typeMap.DestinationType; } else { SourceType = sourceType; DestinationType = destinationType; } Options = context.Options; MapperContext = context.MapperContext; } /// <summary> /// /// </summary> /// <param name="destintationValue"></param> public void SetResolvedDestinationValue(object destintationValue) { DestinationValue = destintationValue; } /// <summary> /// /// </summary> public string MemberName => PropertyMap == null ? string.Empty : (ArrayIndex == null ? PropertyMap.DestinationProperty.Name : PropertyMap.DestinationProperty.Name + ArrayIndex.Value); /// <summary> /// /// </summary> public bool IsSourceValueNull => Equals(null, SourceValue); /// <summary> /// /// </summary> /// <param name="sourceValue"></param> /// <param name="sourceType"></param> /// <returns></returns> public ResolutionContext CreateValueContext(object sourceValue, Type sourceType) { return new ResolutionContext(this, sourceValue, sourceType); } /// <summary> /// /// </summary> /// <param name="memberTypeMap"></param> /// <param name="sourceValue"></param> /// <param name="destinationValue"></param> /// <param name="sourceType"></param> /// <param name="destinationType"></param> /// <returns></returns> public ResolutionContext CreateTypeContext(TypeMap memberTypeMap, object sourceValue, object destinationValue, Type sourceType, Type destinationType) { return new ResolutionContext(this, memberTypeMap, sourceValue, destinationValue, sourceType, destinationType); } /// <summary> /// /// </summary> /// <param name="propertyMap"></param> /// <returns></returns> public ResolutionContext CreatePropertyMapContext(PropertyMap propertyMap) { return new ResolutionContext(this, SourceValue, DestinationValue, SourceType, propertyMap); } /// <summary> /// /// </summary> /// <param name="memberTypeMap"></param> /// <param name="memberValue"></param> /// <param name="destinationValue"></param> /// <param name="sourceMemberType"></param> /// <param name="propertyMap"></param> /// <returns></returns> public ResolutionContext CreateMemberContext(TypeMap memberTypeMap, object memberValue, object destinationValue, Type sourceMemberType, PropertyMap propertyMap) { return memberTypeMap != null ? new ResolutionContext(this, memberValue, destinationValue, memberTypeMap, propertyMap) : new ResolutionContext(this, memberValue, destinationValue, sourceMemberType, propertyMap); } /// <summary> /// /// </summary> /// <param name="elementTypeMap"></param> /// <param name="item"></param> /// <param name="sourceElementType"></param> /// <param name="destinationElementType"></param> /// <param name="arrayIndex"></param> /// <returns></returns> public ResolutionContext CreateElementContext(TypeMap elementTypeMap, object item, Type sourceElementType, Type destinationElementType, int arrayIndex) { return new ResolutionContext(this, item, elementTypeMap, sourceElementType, destinationElementType, arrayIndex); } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { return $"Trying to map {SourceType.Name} to {DestinationType.Name}."; } /// <summary> /// /// </summary> /// <returns></returns> public TypeMap GetContextTypeMap() { TypeMap typeMap = TypeMap; ResolutionContext parent = Parent; while ((typeMap == null) && (parent != null)) { typeMap = parent.TypeMap; parent = parent.Parent; } return typeMap; } /// <summary> /// /// </summary> /// <returns></returns> public PropertyMap GetContextPropertyMap() { PropertyMap propertyMap = PropertyMap; ResolutionContext parent = Parent; while ((propertyMap == null) && (parent != null)) { propertyMap = parent.PropertyMap; parent = parent.Parent; } return propertyMap; } /// <summary> /// /// </summary> /// <param name="other"></param> /// <returns></returns> public bool Equals(ResolutionContext other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.TypeMap, TypeMap) && Equals(other.SourceType, SourceType) && Equals(other.DestinationType, DestinationType) && Equals(other.SourceValue, SourceValue); } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (ResolutionContext)) return false; return Equals((ResolutionContext) obj); } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() { unchecked { int result = (TypeMap != null ? TypeMap.GetHashCode() : 0); result = (result*397) ^ (SourceType != null ? SourceType.GetHashCode() : 0); result = (result*397) ^ (DestinationType != null ? DestinationType.GetHashCode() : 0); result = (result*397) ^ (SourceValue != null ? SourceValue.GetHashCode() : 0); return result; } } } /// <summary> /// /// </summary> public static class ResolutionContextExtensionMethods { /// <summary> /// /// </summary> /// <typeparam name="TSource"></typeparam> /// <param name="mapperContext"></param> /// <param name="sourceValue"></param> /// <returns></returns> [Obsolete] public static ResolutionContext NewResolutionContext<TSource>(this IMapperContext mapperContext, TSource sourceValue) { return new ResolutionContext(null, sourceValue, typeof(TSource), null, new MappingOperationOptions(), mapperContext); } } }
using UnityEngine; using UnityEditor; using System; using System.IO; using System.Linq; using System.Reflection; using System.Collections; using System.Collections.Generic; namespace AssetBundleGraph { public class AssetBundleGraphEditorWindow : EditorWindow { [Serializable] public struct KeyObject { public string key; public KeyObject (string val) { key = val; } } [Serializable] public struct ActiveObject { [SerializeField] public SerializableVector2Dictionary idPosDict; public ActiveObject (Dictionary<string, Vector2> idPosDict) { this.idPosDict = new SerializableVector2Dictionary(idPosDict); } } [Serializable] public struct CopyField { [SerializeField] public List<string> datas; [SerializeField] public CopyType type; public CopyField (List<string> datas, CopyType type) { this.datas = datas; this.type = type; } } // hold selection start data. public struct AssetBundleGraphSelection { public readonly float x; public readonly float y; public AssetBundleGraphSelection (Vector2 position) { this.x = position.x; this.y = position.y; } } // hold scale start data. public struct ScalePoint { public readonly float x; public readonly float y; public readonly float startScale; public readonly int scaledDistance; public ScalePoint (Vector2 point, float scaleFactor, int scaledDistance) { this.x = point.x; this.y = point.y; this.startScale = scaleFactor; this.scaledDistance = scaledDistance; } } public enum ModifyMode : int { NONE, CONNECTING, SELECTING, SCALING, } public enum CopyType : int { COPYTYPE_COPY, COPYTYPE_CUT } public enum ScriptType : int { SCRIPT_MODIFIER, SCRIPT_PREFABBUILDER, SCRIPT_POSTPROCESS } [SerializeField] private List<NodeGUI> nodes = new List<NodeGUI>(); [SerializeField] private List<ConnectionGUI> connections = new List<ConnectionGUI>(); [SerializeField] private ActiveObject activeObject = new ActiveObject(new Dictionary<string, Vector2>()); private bool showErrors; private bool showVerboseLog; private NodeEvent currentEventSource; private Texture2D _selectionTex; private GUIContent _reloadButtonTexture; private ModifyMode modifyMode; private string lastLoaded; private Vector2 spacerRectRightBottom; private Vector2 scrollPos = new Vector2(1500,0); private Vector2 errorScrollPos = new Vector2(0,0); private Rect graphRegion = new Rect(); private CopyField copyField = new CopyField(); private AssetBundleGraphSelection selection; private ScalePoint scalePoint; private GraphBackground background = new GraphBackground(); private AssetBundleGraphController controller = new AssetBundleGraphController(); private static AssetBundleGraphController s_currentController; private static BuildTarget s_selectedTarget; private Texture2D selectionTex { get{ if(_selectionTex == null) { _selectionTex = LoadTextureFromFile(AssetBundleGraphSettings.GUI.RESOURCE_SELECTION); } return _selectionTex; } } private GUIContent reloadButtonTexture { get { if( _reloadButtonTexture == null ) { _reloadButtonTexture = EditorGUIUtility.IconContent("RotateTool"); } return _reloadButtonTexture; } } public static void GenerateScript (ScriptType scriptType) { var destinationBasePath = AssetBundleGraphSettings.USERSPACE_PATH; var destinationPath = string.Empty; var sourceFileName = string.Empty; switch (scriptType) { case ScriptType.SCRIPT_MODIFIER: { sourceFileName = FileUtility.PathCombine(AssetBundleGraphSettings.SCRIPT_TEMPLATE_PATH, "MyModifier.cs.template"); destinationPath = FileUtility.PathCombine(destinationBasePath, "MyModifier.cs"); break; } case ScriptType.SCRIPT_PREFABBUILDER: { sourceFileName = FileUtility.PathCombine(AssetBundleGraphSettings.SCRIPT_TEMPLATE_PATH, "MyPrefabBuilder.cs.template"); destinationPath = FileUtility.PathCombine(destinationBasePath, "MyPrefabBuilder.cs"); break; } case ScriptType.SCRIPT_POSTPROCESS: { sourceFileName = FileUtility.PathCombine(AssetBundleGraphSettings.SCRIPT_TEMPLATE_PATH, "MyPostprocess.cs.template"); destinationPath = FileUtility.PathCombine(destinationBasePath, "MyPostprocess.cs"); break; } default: { LogUtility.Logger.LogError(LogUtility.kTag, "Unknown script type found:" + scriptType); break; } } if (string.IsNullOrEmpty(sourceFileName)) { return; } FileUtility.CopyFile(sourceFileName, destinationPath); AssetDatabase.Refresh(); //Highlight in ProjectView MonoScript s = AssetDatabase.LoadAssetAtPath<MonoScript>(destinationPath); UnityEngine.Assertions.Assert.IsNotNull(s); EditorGUIUtility.PingObject(s); } /* menu items */ [MenuItem(AssetBundleGraphSettings.GUI_TEXT_MENU_GENERATE_MODIFIER)] public static void GenerateModifier () { GenerateScript(ScriptType.SCRIPT_MODIFIER); } [MenuItem(AssetBundleGraphSettings.GUI_TEXT_MENU_GENERATE_PREFABBUILDER)] public static void GeneratePrefabBuilder () { GenerateScript(ScriptType.SCRIPT_PREFABBUILDER); } [MenuItem(AssetBundleGraphSettings.GUI_TEXT_MENU_GENERATE_POSTPROCESS)] public static void GeneratePostprocess () { GenerateScript(ScriptType.SCRIPT_POSTPROCESS); } [MenuItem(AssetBundleGraphSettings.GUI_TEXT_MENU_OPEN, false, 1)] public static void Open () { GetWindow<AssetBundleGraphEditorWindow>(); } [MenuItem(AssetBundleGraphSettings.GUI_TEXT_MENU_BUILD, true, 1 + 11)] public static bool BuildFromMenuValidator () { // Calling GetWindow<>() will force open window // That's not what we want to do in validator function, // so just reference s_currentController directly return (s_currentController != null && !s_currentController.IsAnyIssueFound); } [MenuItem(AssetBundleGraphSettings.GUI_TEXT_MENU_BUILD, false, 1 + 11)] public static void BuildFromMenu () { var window = GetWindow<AssetBundleGraphEditorWindow>(); window.Run(ActiveBuildTarget); } [MenuItem(AssetBundleGraphSettings.GUI_TEXT_MENU_DELETE_CACHE)] public static void DeleteCache () { FileUtility.RemakeDirectory(AssetBundleGraphSettings.APPLICATIONDATAPATH_CACHE_PATH); AssetDatabase.Refresh(); } [MenuItem(AssetBundleGraphSettings.GUI_TEXT_MENU_DELETE_IMPORTSETTING_SETTINGS)] public static void DeleteImportSettingSample () { FileUtility.RemakeDirectory(AssetBundleGraphSettings.IMPORTER_SETTINGS_PLACE); AssetDatabase.Refresh(); } public static BuildTarget ActiveBuildTarget { get { return s_selectedTarget; } } public void OnFocus () { // update handlers. these static handlers are erase when window is full-screened and badk to normal window. modifyMode = ModifyMode.NONE; NodeGUIUtility.NodeEventHandler = HandleNodeEvent; ConnectionGUIUtility.ConnectionEventHandler = HandleConnectionEvent; } public void OnLostFocus() { modifyMode = ModifyMode.NONE; } public void OnProjectChange() { Repaint(); } public void SelectNode(string nodeId) { var selectObject = nodes.Find(node => node.Id == nodeId); // set deactive for all nodes. foreach (var node in nodes) { node.SetInactive(); } if(selectObject != null) { selectObject.SetActive(); } } private void Init() { s_currentController = this.controller; s_selectedTarget = EditorUserBuildSettings.activeBuildTarget; LogUtility.Logger.filterLogType = LogType.Warning; this.titleContent = new GUIContent("AssetBundle"); SaveData.Reload(); Undo.undoRedoPerformed += () => { Setup(ActiveBuildTarget); Repaint(); }; modifyMode = ModifyMode.NONE; NodeGUIUtility.NodeEventHandler = HandleNodeEvent; ConnectionGUIUtility.ConnectionEventHandler = HandleConnectionEvent; InitializeGraph(); Setup(ActiveBuildTarget); if (nodes.Any()) { UpdateSpacerRect(); } } private void ShowErrorOnNodes () { foreach (var node in nodes) { node.ResetErrorStatus(); var errorsForeachNode = controller.Issues.Where(e => e.Id == node.Id).Select(e => e.reason).ToList(); if (errorsForeachNode.Any()) { node.AppendErrorSources(errorsForeachNode); } } } public static Texture2D LoadTextureFromFile(string path) { Texture2D texture = new Texture2D(1, 1); texture.LoadImage(File.ReadAllBytes(path)); return texture; } private ActiveObject RenewActiveObject (List<string> ids) { var idPosDict = new Dictionary<string, Vector2>(); foreach (var node in nodes) { if (ids.Contains(node.Id)) idPosDict[node.Id] = node.GetPos(); } foreach (var connection in connections) { if (ids.Contains(connection.Id)) idPosDict[connection.Id] = Vector2.zero; } return new ActiveObject(idPosDict); } /** node graph initializer. setup nodes, points and connections from saved data. */ public void InitializeGraph () { /* do nothing if json does not modified after first load. */ if (SaveData.Data.LastModified == lastLoaded) { return; } lastLoaded = SaveData.Data.LastModified; minSize = new Vector2(600f, 300f); wantsMouseMove = true; modifyMode = ModifyMode.NONE; /* load graph data from deserialized data. */ ConstructGraphFromSaveData(out this.nodes, out this.connections); } /** * Get WindowId does not collide with other nodeGUIs */ private static int GetSafeWindowId(List<NodeGUI> nodeGUIs) { int id = -1; foreach(var nodeGui in nodeGUIs) { if(nodeGui.WindowId > id) { id = nodeGui.WindowId; } } return id + 1; } /** * Creates Graph structure with NodeGUI and ConnectionGUI from SaveData */ private static void ConstructGraphFromSaveData (out List<NodeGUI> nodes, out List<ConnectionGUI> connections) { var saveData = SaveData.Data; var currentNodes = new List<NodeGUI>(); var currentConnections = new List<ConnectionGUI>(); foreach (var node in saveData.Nodes) { var newNodeGUI = new NodeGUI(node); newNodeGUI.WindowId = GetSafeWindowId(currentNodes); currentNodes.Add(newNodeGUI); } // load connections foreach (var c in saveData.Connections) { var startNode = currentNodes.Find(node => node.Id == c.FromNodeId); if (startNode == null) { continue; } var endNode = currentNodes.Find(node => node.Id == c.ToNodeId); if (endNode == null) { continue; } var startPoint = startNode.Data.FindConnectionPoint (c.FromNodeConnectionPointId); var endPoint = endNode.Data.FindConnectionPoint (c.ToNodeConnectionPointId); currentConnections.Add(ConnectionGUI.LoadConnection(c, startPoint, endPoint)); } nodes = currentNodes; connections = currentConnections; } private void SaveGraph () { SaveData.Data.ApplyGraph(nodes, connections); } /** * Save Graph and update all nodes & connections */ private void Setup (BuildTarget target, bool forceVisitAll = false) { EditorUtility.ClearProgressBar(); try { foreach (var node in nodes) { node.HideProgress(); } SaveGraph(); // update static all node names. NodeGUIUtility.allNodeNames = new List<string>(nodes.Select(node => node.Name).ToList()); controller.Perform(target, false, forceVisitAll, null); RefreshInspector(controller.StreamManager); ShowErrorOnNodes(); } catch(Exception e) { LogUtility.Logger.LogError(LogUtility.kTag, e); } finally { EditorUtility.ClearProgressBar(); } } private void Validate (BuildTarget target, NodeGUI node) { EditorUtility.ClearProgressBar(); try { node.ResetErrorStatus(); node.HideProgress(); SaveGraph (); controller.Validate(node, target); RefreshInspector(controller.StreamManager); ShowErrorOnNodes(); } catch(Exception e) { LogUtility.Logger.LogError(LogUtility.kTag, e); } finally { EditorUtility.ClearProgressBar(); Repaint(); } } /** * Execute the build. */ private void Run (BuildTarget target) { try { AssetDatabase.SaveAssets(); List<NodeGUI> currentNodes = null; List<ConnectionGUI> currentConnections = null; ConstructGraphFromSaveData(out currentNodes, out currentConnections); float currentCount = 0f; float totalCount = (float)currentNodes.Count; NodeData lastNode = null; Action<NodeData, string, float> updateHandler = (node, message, progress) => { if(lastNode != node) { // do not add count on first node visit to // calcurate percantage correctly if(lastNode != null) { ++currentCount; } lastNode = node; } float currentNodeProgress = progress * (1.0f / totalCount); float currentTotalProgress = (currentCount/totalCount) + currentNodeProgress; string title = string.Format("Processing AssetBundle Graph[{0}/{1}]", currentCount, totalCount); string info = string.Format("{0}:{1}", node.Name, message); EditorUtility.DisplayProgressBar(title, "Processing " + info, currentTotalProgress); }; // perform setup. Fails if any exception raises. controller.Perform(target, false, true, null); // if there is not error reported, then run if(!controller.IsAnyIssueFound) { controller.Perform(target, true, true, updateHandler); } RefreshInspector(controller.StreamManager); AssetDatabase.Refresh(); ShowErrorOnNodes(); } catch(Exception e) { LogUtility.Logger.LogError(LogUtility.kTag, e); } finally { EditorUtility.ClearProgressBar(); } } private static void RefreshInspector (AssetReferenceStreamManager streamManager) { if (Selection.activeObject == null) { return; } switch (Selection.activeObject.GetType().ToString()) { case "AssetBundleGraph.ConnectionGUIInspectorHelper": { var con = ((ConnectionGUIInspectorHelper)Selection.activeObject).connectionGUI; // null when multiple connection deleted. if (string.IsNullOrEmpty(con.Id)) { return; } ((ConnectionGUIInspectorHelper)Selection.activeObject).UpdateAssetGroups(streamManager.FindAssetGroup(con.Id)); break; } default: { // do nothing. break; } } } public static IEnumerable<Dictionary<string, List<AssetReference>>> EnumurateIncomingAssetGroups(ConnectionPointData inputPoint) { if(s_currentController != null) { return s_currentController.StreamManager.EnumurateIncomingAssetGroups(inputPoint); } return null; } public static void OnAssetsReimported(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { if(s_currentController != null) { s_currentController.OnAssetsReimported(s_selectedTarget, importedAssets, deletedAssets, movedAssets, movedFromAssetPaths); } } private void DrawGUIToolBar() { using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar)) { if (GUILayout.Button(new GUIContent("Refresh", reloadButtonTexture.image, "Refresh and reload"), EditorStyles.toolbarButton, GUILayout.Width(80), GUILayout.Height(AssetBundleGraphSettings.GUI.TOOLBAR_HEIGHT))) { Setup(ActiveBuildTarget); } showErrors = GUILayout.Toggle(showErrors, "Show Error", EditorStyles.toolbarButton, GUILayout.Height(AssetBundleGraphSettings.GUI.TOOLBAR_HEIGHT)); GUILayout.Space(4); showVerboseLog = GUILayout.Toggle(showVerboseLog, "Show Verbose Log", EditorStyles.toolbarButton, GUILayout.Height(AssetBundleGraphSettings.GUI.TOOLBAR_HEIGHT)); LogUtility.Logger.filterLogType = (showVerboseLog)? LogType.Log : LogType.Warning; GUILayout.FlexibleSpace(); if(controller.IsAnyIssueFound) { GUIStyle errorStyle = new GUIStyle("ErrorLabel"); errorStyle.alignment = TextAnchor.MiddleCenter; GUILayout.Label("All errors needs to be fixed before building", errorStyle); GUILayout.FlexibleSpace(); } GUIStyle tbLabel = new GUIStyle(EditorStyles.toolbar); tbLabel.alignment = TextAnchor.MiddleCenter; GUIStyle tbLabelTarget = new GUIStyle(tbLabel); tbLabelTarget.fontStyle = FontStyle.Bold; GUILayout.Label("Platform:", tbLabel, GUILayout.Height(AssetBundleGraphSettings.GUI.TOOLBAR_HEIGHT)); // GUILayout.Label(BuildTargetUtility.TargetToHumaneString(ActiveBuildTarget), tbLabelTarget, GUILayout.Height(AssetBundleGraphSettings.GUI.TOOLBAR_HEIGHT)); var supportedTargets = NodeGUIUtility.SupportedBuildTargets; int currentIndex = Mathf.Max(0, supportedTargets.FindIndex(t => t == s_selectedTarget)); int newIndex = EditorGUILayout.Popup(currentIndex, NodeGUIUtility.supportedBuildTargetNames, EditorStyles.toolbarButton, GUILayout.Width(150), GUILayout.Height(AssetBundleGraphSettings.GUI.TOOLBAR_HEIGHT)); if(newIndex != currentIndex) { s_selectedTarget = supportedTargets[newIndex]; Setup(ActiveBuildTarget, true); } using(new EditorGUI.DisabledScope(controller.IsAnyIssueFound)) { if (GUILayout.Button("Build", EditorStyles.toolbarButton, GUILayout.Height(AssetBundleGraphSettings.GUI.TOOLBAR_HEIGHT))) { SaveGraph(); Run(ActiveBuildTarget); } } } } private void DrawGUINodeErrors() { errorScrollPos = EditorGUILayout.BeginScrollView(errorScrollPos, GUI.skin.box, GUILayout.Width(200)); { using (new EditorGUILayout.VerticalScope()) { foreach(NodeException e in controller.Issues) { EditorGUILayout.HelpBox(e.reason, MessageType.Error); if( GUILayout.Button("Go to Node") ) { SelectNode(e.Id); } } } } EditorGUILayout.EndScrollView(); } private void DrawGUINodeGraph() { background.Draw(graphRegion, scrollPos); using(var scrollScope = new EditorGUILayout.ScrollViewScope(scrollPos) ) { scrollPos = scrollScope.scrollPosition; // draw node window x N. { BeginWindows(); nodes.ForEach(node => node.DrawNode()); EndWindows(); } // draw connection input point marks. foreach (var node in nodes) { node.DrawConnectionInputPointMark(currentEventSource, modifyMode == ModifyMode.CONNECTING); } // draw connections. foreach (var con in connections) { con.DrawConnection(nodes, controller.StreamManager.FindAssetGroup(con.Id)); } // draw connection output point marks. foreach (var node in nodes) { node.DrawConnectionOutputPointMark(currentEventSource, modifyMode == ModifyMode.CONNECTING, Event.current); } // draw connecting line if modifing connection. switch (modifyMode) { case ModifyMode.CONNECTING: { // from start node to mouse. DrawStraightLineFromCurrentEventSourcePointTo(Event.current.mousePosition, currentEventSource); break; } case ModifyMode.SELECTING: { GUI.DrawTexture(new Rect(selection.x, selection.y, Event.current.mousePosition.x - selection.x, Event.current.mousePosition.y - selection.y), selectionTex); break; } } // handle Graph GUI events HandleGraphGUIEvents(); // set rect for scroll. if (nodes.Any()) { GUILayoutUtility.GetRect(new GUIContent(string.Empty), GUIStyle.none, GUILayout.Width(spacerRectRightBottom.x), GUILayout.Height(spacerRectRightBottom.y)); } } if(Event.current.type == EventType.Repaint) { var newRgn = GUILayoutUtility.GetLastRect(); if(newRgn != graphRegion) { graphRegion = newRgn; Repaint(); } } } private void HandleGraphGUIEvents() { //mouse drag event handling. switch (Event.current.type) { // draw line while dragging. case EventType.MouseDrag: { switch (modifyMode) { case ModifyMode.NONE: { switch (Event.current.button) { case 0:{// left click if (Event.current.command) { scalePoint = new ScalePoint(Event.current.mousePosition, NodeGUI.scaleFactor, 0); modifyMode = ModifyMode.SCALING; break; } selection = new AssetBundleGraphSelection(Event.current.mousePosition); modifyMode = ModifyMode.SELECTING; break; } case 2:{// middle click. scalePoint = new ScalePoint(Event.current.mousePosition, NodeGUI.scaleFactor, 0); modifyMode = ModifyMode.SCALING; break; } } break; } case ModifyMode.SELECTING: { // do nothing. break; } case ModifyMode.SCALING: { var baseDistance = (int)Vector2.Distance(Event.current.mousePosition, new Vector2(scalePoint.x, scalePoint.y)); var distance = baseDistance / NodeGUI.SCALE_WIDTH; var direction = (0 < Event.current.mousePosition.y - scalePoint.y); if (!direction) distance = -distance; // var before = NodeGUI.scaleFactor; NodeGUI.scaleFactor = scalePoint.startScale + (distance * NodeGUI.SCALE_RATIO); if (NodeGUI.scaleFactor < NodeGUI.SCALE_MIN) NodeGUI.scaleFactor = NodeGUI.SCALE_MIN; if (NodeGUI.SCALE_MAX < NodeGUI.scaleFactor) NodeGUI.scaleFactor = NodeGUI.SCALE_MAX; break; } } HandleUtility.Repaint(); Event.current.Use(); break; } } // mouse up event handling. // use rawType for detect for detectiong mouse-up which raises outside of window. switch (Event.current.rawType) { case EventType.MouseUp: { switch (modifyMode) { /* select contained nodes & connections. */ case ModifyMode.SELECTING: { var x = 0f; var y = 0f; var width = 0f; var height = 0f; if (Event.current.mousePosition.x < selection.x) { x = Event.current.mousePosition.x; width = selection.x - Event.current.mousePosition.x; } if (selection.x < Event.current.mousePosition.x) { x = selection.x; width = Event.current.mousePosition.x - selection.x; } if (Event.current.mousePosition.y < selection.y) { y = Event.current.mousePosition.y; height = selection.y - Event.current.mousePosition.y; } if (selection.y < Event.current.mousePosition.y) { y = selection.y; height = Event.current.mousePosition.y - selection.y; } var activeObjectIds = new List<string>(); var selectedRect = new Rect(x, y, width, height); foreach (var node in nodes) { var nodeRect = new Rect(node.GetRect()); nodeRect.x = nodeRect.x * NodeGUI.scaleFactor; nodeRect.y = nodeRect.y * NodeGUI.scaleFactor; nodeRect.width = nodeRect.width * NodeGUI.scaleFactor; nodeRect.height = nodeRect.height * NodeGUI.scaleFactor; // get containd nodes, if (nodeRect.Overlaps(selectedRect)) { activeObjectIds.Add(node.Id); } } foreach (var connection in connections) { // get contained connection badge. if (connection.GetRect().Overlaps(selectedRect)) { activeObjectIds.Add(connection.Id); } } if (Event.current.shift) { // add current active object ids to new list. foreach (var alreadySelectedObjectId in activeObject.idPosDict.ReadonlyDict().Keys) { if (!activeObjectIds.Contains(alreadySelectedObjectId)) activeObjectIds.Add(alreadySelectedObjectId); } } else { // do nothing, means cancel selections if nodes are not contained by selection. } Undo.RecordObject(this, "Select Objects"); activeObject = RenewActiveObject(activeObjectIds); UpdateActivationOfObjects(activeObject); selection = new AssetBundleGraphSelection(Vector2.zero); modifyMode = ModifyMode.NONE; HandleUtility.Repaint(); Event.current.Use(); break; } case ModifyMode.SCALING: { modifyMode = ModifyMode.NONE; break; } } break; } } } public void OnEnable () { Init(); } public void OnDisable() { LogUtility.Logger.Log("OnDisable"); SaveData.SetSavedataDirty(); } public void OnGUI () { DrawGUIToolBar(); using (new EditorGUILayout.HorizontalScope()) { DrawGUINodeGraph(); if(showErrors) { DrawGUINodeErrors(); } } /* Event Handling: - Supporting dragging script into window to create node. - Context Menu - NodeGUI connection. - Command(Delete, Copy, etc...) */ switch (Event.current.type) { // detect dragging script then change interface to "(+)" icon. case EventType.DragUpdated: { var refs = DragAndDrop.objectReferences; foreach (var refe in refs) { if (refe.GetType() == typeof(UnityEditor.MonoScript)) { Type scriptTypeInfo = ((MonoScript)refe).GetClass(); Type inheritedTypeInfo = GetDragAndDropAcceptableScriptType(scriptTypeInfo); if (inheritedTypeInfo != null) { // at least one asset is script. change interface. DragAndDrop.visualMode = DragAndDropVisualMode.Copy; break; } } } break; } // script drop on editor. case EventType.DragPerform: { var pathAndRefs = new Dictionary<string, object>(); for (var i = 0; i < DragAndDrop.paths.Length; i++) { var path = DragAndDrop.paths[i]; var refe = DragAndDrop.objectReferences[i]; pathAndRefs[path] = refe; } var shouldSave = false; foreach (var item in pathAndRefs) { var refe = (MonoScript)item.Value; if (refe.GetType() == typeof(UnityEditor.MonoScript)) { Type scriptTypeInfo = refe.GetClass(); Type inheritedTypeInfo = GetDragAndDropAcceptableScriptType(scriptTypeInfo); if (inheritedTypeInfo != null) { var dropPos = Event.current.mousePosition; var scriptName = refe.name; var scriptClassName = scriptName; AddNodeFromCode(scriptName, scriptClassName, inheritedTypeInfo, dropPos.x, dropPos.y); shouldSave = true; } } } if (shouldSave) { Setup(ActiveBuildTarget); } break; } // show context menu case EventType.ContextClick: { var rightClickPos = Event.current.mousePosition; var menu = new GenericMenu(); foreach (var menuItemStr in AssetBundleGraphSettings.GUI_Menu_Item_TargetGUINodeDict.Keys) { var kind = AssetBundleGraphSettings.GUI_Menu_Item_TargetGUINodeDict[menuItemStr]; menu.AddItem( new GUIContent(menuItemStr), false, () => { AddNodeFromGUI(kind, rightClickPos.x, rightClickPos.y); Setup(ActiveBuildTarget); Repaint(); } ); } menu.ShowAsContext(); break; } /* Handling mouseUp at empty space. */ case EventType.MouseUp: { modifyMode = ModifyMode.NONE; HandleUtility.Repaint(); if (activeObject.idPosDict.ReadonlyDict().Any()) { Undo.RecordObject(this, "Unselect"); foreach (var activeObjectId in activeObject.idPosDict.ReadonlyDict().Keys) { // unselect all. foreach (var node in nodes) { if (activeObjectId == node.Id) { node.SetInactive(); } } foreach (var connection in connections) { if (activeObjectId == connection.Id) { connection.SetInactive(); } } } activeObject = RenewActiveObject(new List<string>()); } // clear inspector if( Selection.activeObject is NodeGUIInspectorHelper || Selection.activeObject is ConnectionGUIInspectorHelper) { Selection.activeObject = null; } break; } /* scale up or down by command & + or command & -. */ case EventType.KeyDown: { if (Event.current.command) { if (Event.current.shift && Event.current.keyCode == KeyCode.Semicolon) { NodeGUI.scaleFactor = NodeGUI.scaleFactor + 0.1f; if (NodeGUI.scaleFactor < NodeGUI.SCALE_MIN) NodeGUI.scaleFactor = NodeGUI.SCALE_MIN; if (NodeGUI.SCALE_MAX < NodeGUI.scaleFactor) NodeGUI.scaleFactor = NodeGUI.SCALE_MAX; Event.current.Use(); break; } if (Event.current.keyCode == KeyCode.Minus) { NodeGUI.scaleFactor = NodeGUI.scaleFactor - 0.1f; if (NodeGUI.scaleFactor < NodeGUI.SCALE_MIN) NodeGUI.scaleFactor = NodeGUI.SCALE_MIN; if (NodeGUI.SCALE_MAX < NodeGUI.scaleFactor) NodeGUI.scaleFactor = NodeGUI.SCALE_MAX; Event.current.Use(); break; } } break; } case EventType.ValidateCommand: { switch (Event.current.commandName) { // Delete active node or connection. case "Delete": { if (activeObject.idPosDict.ReadonlyDict().Any()) { Event.current.Use(); } break; } case "Copy": { if (activeObject.idPosDict.ReadonlyDict().Any()) { Event.current.Use(); } break; } case "Cut": { if (activeObject.idPosDict.ReadonlyDict().Any()) { Event.current.Use(); } break; } case "Paste": { if(copyField.datas == null) { break; } if (copyField.datas.Any()) { Event.current.Use(); } break; } case "SelectAll": { Event.current.Use(); break; } } break; } case EventType.ExecuteCommand: { switch (Event.current.commandName) { // Delete active node or connection. case "Delete": { if (!activeObject.idPosDict.ReadonlyDict().Any()) break; Undo.RecordObject(this, "Delete Selection"); foreach (var targetId in activeObject.idPosDict.ReadonlyDict().Keys) { DeleteNode(targetId); DeleteConnectionById(targetId); } Setup(ActiveBuildTarget); activeObject = RenewActiveObject(new List<string>()); UpdateActivationOfObjects(activeObject); Event.current.Use(); break; } case "Copy": { if (!activeObject.idPosDict.ReadonlyDict().Any()) { break; } Undo.RecordObject(this, "Copy Selection"); var targetNodeIds = activeObject.idPosDict.ReadonlyDict().Keys.ToList(); var targetNodeJsonRepresentations = JsonRepresentations(targetNodeIds); copyField = new CopyField(targetNodeJsonRepresentations, CopyType.COPYTYPE_COPY); Event.current.Use(); break; } case "Cut": { if (!activeObject.idPosDict.ReadonlyDict().Any()) { break; } Undo.RecordObject(this, "Cut Selection"); var targetNodeIds = activeObject.idPosDict.ReadonlyDict().Keys.ToList(); var targetNodeJsonRepresentations = JsonRepresentations(targetNodeIds); copyField = new CopyField(targetNodeJsonRepresentations, CopyType.COPYTYPE_CUT); foreach (var targetId in activeObject.idPosDict.ReadonlyDict().Keys) { DeleteNode(targetId); DeleteConnectionById(targetId); } Setup(ActiveBuildTarget); InitializeGraph(); activeObject = RenewActiveObject(new List<string>()); UpdateActivationOfObjects(activeObject); Event.current.Use(); break; } case "Paste": { if(copyField.datas == null) { break; } var nodeNames = nodes.Select(node => node.Name).ToList(); var duplicatingData = new List<NodeGUI>(); if (copyField.datas.Any()) { var pasteType = copyField.type; foreach (var copyFieldData in copyField.datas) { var nodeJsonDict = AssetBundleGraph.Json.Deserialize(copyFieldData) as Dictionary<string, object>; var pastingNode = new NodeGUI(new NodeData(nodeJsonDict)); var pastingNodeName = pastingNode.Name; var nameOverlapping = nodeNames.Where(name => name == pastingNodeName).ToList(); switch (pasteType) { case CopyType.COPYTYPE_COPY: { if (2 <= nameOverlapping.Count) { continue; } break; } case CopyType.COPYTYPE_CUT: { if (1 <= nameOverlapping.Count) { continue; } break; } } duplicatingData.Add(pastingNode); } } // consume copyField copyField.datas = null; if (!duplicatingData.Any()) { break; } Undo.RecordObject(this, "Paste"); foreach (var newNode in duplicatingData) { DuplicateNode(newNode); } Setup(ActiveBuildTarget); InitializeGraph(); Event.current.Use(); break; } case "SelectAll": { Undo.RecordObject(this, "Select All Objects"); var nodeIds = nodes.Select(node => node.Id).ToList(); activeObject = RenewActiveObject(nodeIds); // select all. foreach (var node in nodes) { node.SetActive(); } foreach (var connection in connections) { connection.SetActive(); } Event.current.Use(); break; } default: { break; } } break; } } } private List<string> JsonRepresentations (List<string> nodeIds) { return nodes.Where(nodeGui => nodeIds.Contains(nodeGui.Id)).Select(nodeGui => nodeGui.Data.ToJsonString()).ToList(); } private Type GetDragAndDropAcceptableScriptType (Type type) { if (typeof(IPrefabBuilder).IsAssignableFrom(type) && !type.IsInterface && PrefabBuilderUtility.HasValidCustomPrefabBuilderAttribute(type)) { return typeof(IPrefabBuilder); } if (typeof(IModifier).IsAssignableFrom(type) && !type.IsInterface && ModifierUtility.HasValidCustomModifierAttribute(type)) { return typeof(IModifier); } return null; } private void AddNodeFromCode (string name, string scriptClassName, Type scriptBaseType, float x, float y) { NodeGUI newNode = null; if (scriptBaseType == typeof(IModifier)) { var modifier = ModifierUtility.CreateModifier(scriptClassName); UnityEngine.Assertions.Assert.IsNotNull(modifier); newNode = new NodeGUI(new NodeData(name, NodeKind.MODIFIER_GUI, x, y)); newNode.Data.ScriptClassName = scriptClassName; newNode.Data.InstanceData.DefaultValue = modifier.Serialize(); } if (scriptBaseType == typeof(IPrefabBuilder)) { var builder = PrefabBuilderUtility.CreatePrefabBuilderByClassName(scriptClassName); UnityEngine.Assertions.Assert.IsNotNull(builder); newNode = new NodeGUI(new NodeData(name, NodeKind.PREFABBUILDER_GUI, x, y)); newNode.Data.ScriptClassName = scriptClassName; newNode.Data.InstanceData.DefaultValue = builder.Serialize(); } if (newNode == null) { LogUtility.Logger.LogError(LogUtility.kTag, "Could not add node from code. " + scriptClassName + "(base:" + scriptBaseType + ") is not supported to create from code."); return; } AddNodeGUI(newNode); } private void AddNodeFromGUI (NodeKind kind, float x, float y) { string nodeName = AssetBundleGraphSettings.DEFAULT_NODE_NAME[kind] + nodes.Where(node => node.Kind == kind).ToList().Count; NodeGUI newNode = new NodeGUI(new NodeData(nodeName, kind, x, y)); Undo.RecordObject(this, "Add " + AssetBundleGraphSettings.DEFAULT_NODE_NAME[kind] + " Node"); AddNodeGUI(newNode); } private void DrawStraightLineFromCurrentEventSourcePointTo (Vector2 to, NodeEvent eventSource) { if (eventSource == null) { return; } var p = eventSource.point.GetGlobalPosition(eventSource.eventSourceNode); Handles.DrawLine(new Vector3(p.x, p.y, 0f), new Vector3(to.x, to.y, 0f)); } /** * Handle Node Event */ private void HandleNodeEvent (NodeEvent e) { switch (modifyMode) { case ModifyMode.CONNECTING: { switch (e.eventType) { /* handling */ case NodeEvent.EventType.EVENT_NODE_MOVING: { // do nothing. break; } /* connection drop detected from toward node. */ case NodeEvent.EventType.EVENT_NODE_CONNECTION_RAISED: { // finish connecting mode. modifyMode = ModifyMode.NONE; if (currentEventSource == null) { break; } var sourceNode = currentEventSource.eventSourceNode; var sourceConnectionPoint = currentEventSource.point; var targetNode = e.eventSourceNode; var targetConnectionPoint = e.point; if (sourceNode.Id == targetNode.Id) { break; } if (!IsConnectablePointFromTo(sourceConnectionPoint, targetConnectionPoint)) { break; } var startNode = sourceNode; var startConnectionPoint = sourceConnectionPoint; var endNode = targetNode; var endConnectionPoint = targetConnectionPoint; // reverse if connected from input to output. if (sourceConnectionPoint.IsInput) { startNode = targetNode; startConnectionPoint = targetConnectionPoint; endNode = sourceNode; endConnectionPoint = sourceConnectionPoint; } var outputPoint = startConnectionPoint; var inputPoint = endConnectionPoint; var label = startConnectionPoint.Label; // if two nodes are not supposed to connect, dismiss if(!ConnectionData.CanConnect(startNode.Data, endNode.Data)) { break; } AddConnection(label, startNode, outputPoint, endNode, inputPoint); Setup(ActiveBuildTarget); break; } /* connection drop detected by started node. */ case NodeEvent.EventType.EVENT_NODE_CONNECTION_OVERED: { // finish connecting mode. modifyMode = ModifyMode.NONE; /* connect when dropped target is connectable from start connectionPoint. */ var node = FindNodeByPosition(e.globalMousePosition); if (node == null) { break; } // ignore if target node is source itself. if (node == e.eventSourceNode) { break; } var pointAtPosition = node.FindConnectionPointByPosition(e.globalMousePosition); if (pointAtPosition == null) { break; } var sourcePoint = currentEventSource.point; // limit by connectable or not. if(!IsConnectablePointFromTo(sourcePoint, pointAtPosition)) { break; } var isInput = currentEventSource.point.IsInput; var startNode = (isInput)? node : e.eventSourceNode; var endNode = (isInput)? e.eventSourceNode: node; var startConnectionPoint = (isInput)? pointAtPosition : currentEventSource.point; var endConnectionPoint = (isInput)? currentEventSource.point: pointAtPosition; var outputPoint = startConnectionPoint; var inputPoint = endConnectionPoint; var label = startConnectionPoint.Label; // if two nodes are not supposed to connect, dismiss if(!ConnectionData.CanConnect(startNode.Data, endNode.Data)) { break; } AddConnection(label, startNode, outputPoint, endNode, inputPoint); Setup(ActiveBuildTarget); break; } default: { modifyMode = ModifyMode.NONE; break; } } break; } case ModifyMode.NONE: { switch (e.eventType) { /* node move detected. */ case NodeEvent.EventType.EVENT_NODE_MOVING: { var tappedNode = e.eventSourceNode; var tappedNodeId = tappedNode.Id; if (activeObject.idPosDict.ContainsKey(tappedNodeId)) { // already active, do nothing for this node. var distancePos = tappedNode.GetPos() - activeObject.idPosDict.ReadonlyDict()[tappedNodeId]; foreach (var node in nodes) { if (node.Id == tappedNodeId) continue; if (!activeObject.idPosDict.ContainsKey(node.Id)) continue; var relativePos = activeObject.idPosDict.ReadonlyDict()[node.Id] + distancePos; node.SetPos(relativePos); } break; } if (Event.current.shift) { Undo.RecordObject(this, "Select Objects"); var additiveIds = new List<string>(activeObject.idPosDict.ReadonlyDict().Keys); additiveIds.Add(tappedNodeId); activeObject = RenewActiveObject(additiveIds); UpdateActivationOfObjects(activeObject); UpdateSpacerRect(); break; } Undo.RecordObject(this, "Select " + tappedNode.Name); activeObject = RenewActiveObject(new List<string>{tappedNodeId}); UpdateActivationOfObjects(activeObject); break; } /* start connection handling. */ case NodeEvent.EventType.EVENT_NODE_CONNECT_STARTED: { modifyMode = ModifyMode.CONNECTING; currentEventSource = e; break; } case NodeEvent.EventType.EVENT_CLOSE_TAPPED: { Undo.RecordObject(this, "Delete Node"); var deletingNodeId = e.eventSourceNode.Id; DeleteNode(deletingNodeId); Setup(ActiveBuildTarget); InitializeGraph(); break; } /* releasse detected. node move over. node tapped. */ case NodeEvent.EventType.EVENT_NODE_TOUCHED: { var movedNode = e.eventSourceNode; var movedNodeId = movedNode.Id; // already active, node(s) are just tapped or moved. if (activeObject.idPosDict.ContainsKey(movedNodeId)) { /* active nodes(contains tap released node) are possibly moved. */ var movedIdPosDict = new Dictionary<string, Vector2>(); foreach (var node in nodes) { if (!activeObject.idPosDict.ContainsKey(node.Id)) continue; var startPos = activeObject.idPosDict.ReadonlyDict()[node.Id]; if (node.GetPos() != startPos) { // moved. movedIdPosDict[node.Id] = node.GetPos(); } } if (movedIdPosDict.Any()) { foreach (var node in nodes) { if (activeObject.idPosDict.ReadonlyDict().Keys.Contains(node.Id)) { var startPos = activeObject.idPosDict.ReadonlyDict()[node.Id]; node.SetPos(startPos); } } Undo.RecordObject(this, "Move " + movedNode.Name); foreach (var node in nodes) { if (movedIdPosDict.Keys.Contains(node.Id)) { var endPos = movedIdPosDict[node.Id]; node.SetPos(endPos); } } var activeObjectIds = activeObject.idPosDict.ReadonlyDict().Keys.ToList(); activeObject = RenewActiveObject(activeObjectIds); } else { // nothing moved, should cancel selecting this node. var cancelledActivatedIds = new List<string>(activeObject.idPosDict.ReadonlyDict().Keys); cancelledActivatedIds.Remove(movedNodeId); Undo.RecordObject(this, "Select Objects"); activeObject = RenewActiveObject(cancelledActivatedIds); } UpdateActivationOfObjects(activeObject); UpdateSpacerRect(); //SaveGraph(); break; } if (Event.current.shift) { Undo.RecordObject(this, "Select Objects"); var additiveIds = new List<string>(activeObject.idPosDict.ReadonlyDict().Keys); // already contained, cancel. if (additiveIds.Contains(movedNodeId)) { additiveIds.Remove(movedNodeId); } else { additiveIds.Add(movedNodeId); } activeObject = RenewActiveObject(additiveIds); UpdateActivationOfObjects(activeObject); UpdateSpacerRect(); //SaveGraph(); break; } Undo.RecordObject(this, "Select " + movedNode.Name); activeObject = RenewActiveObject(new List<string>{movedNodeId}); UpdateActivationOfObjects(activeObject); UpdateSpacerRect(); //SaveGraph(); break; } case NodeEvent.EventType.EVENT_NODE_UPDATED: { break; } default: { break; } } break; } } switch (e.eventType) { case NodeEvent.EventType.EVENT_DELETE_ALL_CONNECTIONS_TO_POINT: { // deleting all connections to this point connections.RemoveAll( c => (c.InputPoint == e.point || c.OutputPoint == e.point) ); Repaint(); break; } case NodeEvent.EventType.EVENT_CONNECTIONPOINT_DELETED: { // deleting point is handled by caller, so we are deleting connections associated with it. connections.RemoveAll( c => (c.InputPoint == e.point || c.OutputPoint == e.point) ); Repaint(); break; } case NodeEvent.EventType.EVENT_CONNECTIONPOINT_LABELCHANGED: { // point label change is handled by caller, so we are changing label of connection associated with it. var affectingConnections = connections.FindAll( c=> c.OutputPoint.Id == e.point.Id ); affectingConnections.ForEach(c => c.Label = e.point.Label); Repaint(); break; } case NodeEvent.EventType.EVENT_NODE_UPDATED: { Validate(ActiveBuildTarget, e.eventSourceNode); break; } case NodeEvent.EventType.EVENT_RECORDUNDO: { Undo.RecordObject(this, e.message); break; } case NodeEvent.EventType.EVENT_SAVE: { Setup(ActiveBuildTarget); Repaint(); break; } } } /** once expand, keep max size. it's convenience. */ private void UpdateSpacerRect () { var rightPoint = nodes.OrderByDescending(node => node.GetRightPos()).Select(node => node.GetRightPos()).ToList()[0] + AssetBundleGraphSettings.WINDOW_SPAN; if (rightPoint < spacerRectRightBottom.x) rightPoint = spacerRectRightBottom.x; var bottomPoint = nodes.OrderByDescending(node => node.GetBottomPos()).Select(node => node.GetBottomPos()).ToList()[0] + AssetBundleGraphSettings.WINDOW_SPAN; if (bottomPoint < spacerRectRightBottom.y) bottomPoint = spacerRectRightBottom.y; spacerRectRightBottom = new Vector2(rightPoint, bottomPoint); } public void DuplicateNode (NodeGUI node) { var newNode = node.Duplicate( node.GetX() + 10f, node.GetY() + 10f ); AddNodeGUI(newNode); } private void AddNodeGUI(NodeGUI newNode) { int id = -1; foreach(var node in nodes) { if(node.WindowId > id) { id = node.WindowId; } } newNode.WindowId = id + 1; nodes.Add(newNode); } public void DeleteNode (string deletingNodeId) { var deletedNodeIndex = nodes.FindIndex(node => node.Id == deletingNodeId); if (0 <= deletedNodeIndex) { nodes[deletedNodeIndex].SetInactive(); nodes.RemoveAt(deletedNodeIndex); } } public void HandleConnectionEvent (ConnectionEvent e) { switch (modifyMode) { case ModifyMode.NONE: { switch (e.eventType) { case ConnectionEvent.EventType.EVENT_CONNECTION_TAPPED: { if (Event.current.shift) { Undo.RecordObject(this, "Select Objects"); var objectId = string.Empty; if (e.eventSourceCon != null) { objectId = e.eventSourceCon.Id; if (!activeObject.idPosDict.ReadonlyDict().Any()) { activeObject = RenewActiveObject(new List<string>{objectId}); } else { var additiveIds = new List<string>(activeObject.idPosDict.ReadonlyDict().Keys); // already contained, cancel. if (additiveIds.Contains(objectId)) { additiveIds.Remove(objectId); } else { additiveIds.Add(objectId); } activeObject = RenewActiveObject(additiveIds); } } UpdateActivationOfObjects(activeObject); break; } Undo.RecordObject(this, "Select Connection"); var tappedConnectionId = e.eventSourceCon.Id; foreach (var con in connections) { if (con.Id == tappedConnectionId) { con.SetActive(); activeObject = RenewActiveObject(new List<string>{con.Id}); } else { con.SetInactive(); } } // set deactive for all nodes. foreach (var node in nodes) { node.SetInactive(); } break; } case ConnectionEvent.EventType.EVENT_CONNECTION_DELETED: { Undo.RecordObject(this, "Delete Connection"); var deletedConnectionId = e.eventSourceCon.Id; DeleteConnectionById(deletedConnectionId); Setup(ActiveBuildTarget); Repaint(); break; } default: { break; } } break; } } } private void UpdateActivationOfObjects (ActiveObject currentActiveObject) { foreach (var node in nodes) { if (currentActiveObject.idPosDict.ContainsKey(node.Id)) { node.SetActive(); continue; } node.SetInactive(); } foreach (var connection in connections) { if (currentActiveObject.idPosDict.ContainsKey(connection.Id)) { connection.SetActive(); continue; } connection.SetInactive(); } } /** create new connection if same relationship is not exist yet. */ private void AddConnection (string label, NodeGUI startNode, ConnectionPointData startPoint, NodeGUI endNode, ConnectionPointData endPoint) { Undo.RecordObject(this, "Add Connection"); var connectionsFromThisNode = connections .Where(con => con.OutputNodeId == startNode.Id) .Where(con => con.OutputPoint == startPoint) .ToList(); if (connectionsFromThisNode.Any()) { var alreadyExistConnection = connectionsFromThisNode[0]; DeleteConnectionById(alreadyExistConnection.Id); } if (!connections.ContainsConnection(startPoint, endPoint)) { connections.Add(ConnectionGUI.CreateConnection(label, startPoint, endPoint)); } } private NodeGUI FindNodeByPosition (Vector2 globalPos) { return nodes.Find(n => n.Conitains(globalPos)); } private bool IsConnectablePointFromTo (ConnectionPointData sourcePoint, ConnectionPointData destPoint) { if( sourcePoint.IsInput ) { return destPoint.IsOutput; } else { return destPoint.IsInput; } } private void DeleteConnectionById (string id) { var deletedConnectionIndex = connections.FindIndex(con => con.Id == id); if (0 <= deletedConnectionIndex) { connections[deletedConnectionIndex].SetInactive(); connections.RemoveAt(deletedConnectionIndex); } } public int GetUnusedWindowId() { int highest = 0; nodes.ForEach((NodeGUI n) => { if(n.WindowId > highest) highest = n.WindowId; }); return highest + 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.DirectoryServices.ActiveDirectory { using System; using System.Net; using System.Collections; using System.ComponentModel; using System.Runtime.InteropServices; using System.Threading; using System.Security.Permissions; using System.Globalization; public class AdamInstance : DirectoryServer { private string[] _becomeRoleOwnerAttrs = null; private bool _disposed = false; // for public properties private string _cachedHostName = null; private int _cachedLdapPort = -1; private int _cachedSslPort = -1; private bool _defaultPartitionInitialized = false; private bool _defaultPartitionModified = false; private ConfigurationSet _currentConfigSet = null; private string _cachedDefaultPartition = null; private AdamRoleCollection _cachedRoles = null; private IntPtr _ADAMHandle = (IntPtr)0; private IntPtr _authIdentity = IntPtr.Zero; private SyncUpdateCallback _userDelegate = null; private SyncReplicaFromAllServersCallback _syncAllFunctionPointer = null; #region constructors internal AdamInstance(DirectoryContext context, string adamInstanceName) : this(context, adamInstanceName, new DirectoryEntryManager(context), true) { } internal AdamInstance(DirectoryContext context, string adamInstanceName, DirectoryEntryManager directoryEntryMgr, bool nameIncludesPort) { this.context = context; this.replicaName = adamInstanceName; this.directoryEntryMgr = directoryEntryMgr; // initialize the transfer role owner attributes _becomeRoleOwnerAttrs = new String[2]; _becomeRoleOwnerAttrs[0] = PropertyManager.BecomeSchemaMaster; _becomeRoleOwnerAttrs[1] = PropertyManager.BecomeDomainMaster; // initialize the callback function _syncAllFunctionPointer = new SyncReplicaFromAllServersCallback(SyncAllCallbackRoutine); } internal AdamInstance(DirectoryContext context, string adamHostName, DirectoryEntryManager directoryEntryMgr) { this.context = context; // the replica name should be in the form dnshostname:port this.replicaName = adamHostName; string portNumber; Utils.SplitServerNameAndPortNumber(context.Name, out portNumber); if (portNumber != null) { this.replicaName = this.replicaName + ":" + portNumber; } // initialize the directory entry manager this.directoryEntryMgr = directoryEntryMgr; // initialize the transfer role owner attributes _becomeRoleOwnerAttrs = new String[2]; _becomeRoleOwnerAttrs[0] = PropertyManager.BecomeSchemaMaster; _becomeRoleOwnerAttrs[1] = PropertyManager.BecomeDomainMaster; // initialize the callback function _syncAllFunctionPointer = new SyncReplicaFromAllServersCallback(SyncAllCallbackRoutine); } #endregion constructors #region IDisposable ~AdamInstance() { // finalizer is called => Dispose has not been called yet. Dispose(false); } // private Dispose method protected override void Dispose(bool disposing) { if (!_disposed) { try { // if there are any managed or unmanaged // resources to be freed, those should be done here // if disposing = true, only unmanaged resources should // be freed, else both managed and unmanaged. FreeADAMHandle(); _disposed = true; } finally { base.Dispose(); } } } #endregion IDisposable #region public methods public static AdamInstance GetAdamInstance(DirectoryContext context) { DirectoryEntryManager directoryEntryMgr = null; string dnsHostName = null; // check that the context is not null if (context == null) { throw new ArgumentNullException("context"); } // contexttype should be DirectoryServer if (context.ContextType != DirectoryContextType.DirectoryServer) { throw new ArgumentException(SR.TargetShouldBeADAMServer, "context"); } // target must be a server if ((!context.isServer())) { throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.AINotFound , context.Name), typeof(AdamInstance), context.Name); } // work with copy of the context context = new DirectoryContext(context); // bind to the given adam instance try { directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); // This will ensure that we are talking to ADAM instance only if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryApplicationMode)) { throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.AINotFound , context.Name), typeof(AdamInstance), context.Name); } dnsHostName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName); } catch (COMException e) { int errorCode = e.ErrorCode; if (errorCode == unchecked((int)0x8007203a)) { throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.AINotFound , context.Name), typeof(AdamInstance), context.Name); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } return new AdamInstance(context, dnsHostName, directoryEntryMgr); } public static AdamInstance FindOne(DirectoryContext context, string partitionName) { // validate parameters (partitionName validated by the call to ConfigSet) if (context == null) { throw new ArgumentNullException("context"); } // contexttype should be ConfigurationSet if (context.ContextType != DirectoryContextType.ConfigurationSet) { throw new ArgumentException(SR.TargetShouldBeConfigSet, "context"); } if (partitionName == null) { throw new ArgumentNullException("partitionName"); } if (partitionName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "partitionName"); } // work with copy of the context context = new DirectoryContext(context); return ConfigurationSet.FindOneAdamInstance(context, partitionName, null); } public static AdamInstanceCollection FindAll(DirectoryContext context, string partitionName) { AdamInstanceCollection adamInstanceCollection = null; // validate parameters (partitionName validated by the call to ConfigSet) if (context == null) { throw new ArgumentNullException("context"); } // contexttype should be ConfigurationSet if (context.ContextType != DirectoryContextType.ConfigurationSet) { throw new ArgumentException(SR.TargetShouldBeConfigSet, "context"); } if (partitionName == null) { throw new ArgumentNullException("partitionName"); } if (partitionName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "partitionName"); } // work with copy of the context context = new DirectoryContext(context); try { adamInstanceCollection = ConfigurationSet.FindAdamInstances(context, partitionName, null); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where we could not find an ADAM instance in that config set (return empty collection) adamInstanceCollection = new AdamInstanceCollection(new ArrayList()); } return adamInstanceCollection; } public void TransferRoleOwnership(AdamRole role) { CheckIfDisposed(); if (role < AdamRole.SchemaRole || role > AdamRole.NamingRole) { throw new InvalidEnumArgumentException("role", (int)role, typeof(AdamRole)); } // set the appropriate attribute on the root dse try { DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); rootDSE.Properties[_becomeRoleOwnerAttrs[(int)role]].Value = 1; rootDSE.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } // invalidate the role collection so that it gets loaded again next time _cachedRoles = null; } public void SeizeRoleOwnership(AdamRole role) { // set the "fsmoRoleOwner" attribute on the appropriate role object // to the NTDSAObjectName of this ADAM Instance string roleObjectDN = null; CheckIfDisposed(); switch (role) { case AdamRole.SchemaRole: { roleObjectDN = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext); break; } case AdamRole.NamingRole: { roleObjectDN = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer); break; } default: { throw new InvalidEnumArgumentException("role", (int)role, typeof(AdamRole)); } } DirectoryEntry roleObjectEntry = null; try { roleObjectEntry = DirectoryEntryManager.GetDirectoryEntry(context, roleObjectDN); roleObjectEntry.Properties[PropertyManager.FsmoRoleOwner].Value = NtdsaObjectName; roleObjectEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { if (roleObjectEntry != null) { roleObjectEntry.Dispose(); } } // invalidate the role collection so that it gets loaded again next time _cachedRoles = null; } public override void CheckReplicationConsistency() { if (_disposed) throw new ObjectDisposedException(GetType().Name); // get the handle GetADAMHandle(); // call private helper function CheckConsistencyHelper(_ADAMHandle, DirectoryContext.ADAMHandle); } public override ReplicationCursorCollection GetReplicationCursors(string partition) { IntPtr info = (IntPtr)0; int context = 0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); if (partition == null) throw new ArgumentNullException("partition"); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "partition"); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_3_FOR_NC, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_FOR_NC, partition, ref advanced, context, DirectoryContext.ADAMHandle); return ConstructReplicationCursors(_ADAMHandle, advanced, info, partition, this, DirectoryContext.ADAMHandle); } public override ReplicationOperationInformation GetReplicationOperationInformation() { IntPtr info = (IntPtr)0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_PENDING_OPS, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_PENDING_OPS, null, ref advanced, 0, DirectoryContext.ADAMHandle); return ConstructPendingOperations(info, this, DirectoryContext.ADAMHandle); } public override ReplicationNeighborCollection GetReplicationNeighbors(string partition) { IntPtr info = (IntPtr)0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); if (partition == null) throw new ArgumentNullException("partition"); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "partition"); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, partition, ref advanced, 0, DirectoryContext.ADAMHandle); return ConstructNeighbors(info, this, DirectoryContext.ADAMHandle); } public override ReplicationNeighborCollection GetAllReplicationNeighbors() { IntPtr info = (IntPtr)0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, null, ref advanced, 0, DirectoryContext.ADAMHandle); return ConstructNeighbors(info, this, DirectoryContext.ADAMHandle); } public override ReplicationFailureCollection GetReplicationConnectionFailures() { return GetReplicationFailures(DS_REPL_INFO_TYPE.DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES); } public override ActiveDirectoryReplicationMetadata GetReplicationMetadata(string objectPath) { IntPtr info = (IntPtr)0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); if (objectPath == null) throw new ArgumentNullException("objectPath"); if (objectPath.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "objectPath"); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_2_FOR_OBJ, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_FOR_OBJ, objectPath, ref advanced, 0, DirectoryContext.ADAMHandle); return ConstructMetaData(advanced, info, this, DirectoryContext.ADAMHandle); } public override void SyncReplicaFromServer(string partition, string sourceServer) { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (partition == null) throw new ArgumentNullException("partition"); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "partition"); if (sourceServer == null) throw new ArgumentNullException("sourceServer"); if (sourceServer.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "sourceServer"); // get the dsHandle GetADAMHandle(); SyncReplicaHelper(_ADAMHandle, true, partition, sourceServer, 0, DirectoryContext.ADAMHandle); } public override void TriggerSyncReplicaFromNeighbors(string partition) { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (partition == null) throw new ArgumentNullException("partition"); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "partition"); // get the dsHandle GetADAMHandle(); SyncReplicaHelper(_ADAMHandle, true, partition, null, DS_REPSYNC_ASYNCHRONOUS_OPERATION | DS_REPSYNC_ALL_SOURCES, DirectoryContext.ADAMHandle); } public override void SyncReplicaFromAllServers(string partition, SyncFromAllServersOptions options) { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (partition == null) throw new ArgumentNullException("partition"); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "partition"); // get the dsHandle GetADAMHandle(); SyncReplicaAllHelper(_ADAMHandle, _syncAllFunctionPointer, partition, options, SyncFromAllServersCallback, DirectoryContext.ADAMHandle); } public void Save() { CheckIfDisposed(); // only thing to be saved is the ntdsa entry (for default partition) if (_defaultPartitionModified) { DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); try { ntdsaEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } // reset the bools associated with this property _defaultPartitionInitialized = false; _defaultPartitionModified = false; } #endregion public methods #region public properties public ConfigurationSet ConfigurationSet { get { CheckIfDisposed(); if (_currentConfigSet == null) { DirectoryContext configSetContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context); _currentConfigSet = ConfigurationSet.GetConfigurationSet(configSetContext); } return _currentConfigSet; } } public string HostName { get { CheckIfDisposed(); if (_cachedHostName == null) { DirectoryEntry serverEntry = directoryEntryMgr.GetCachedDirectoryEntry(ServerObjectName); _cachedHostName = (string)PropertyManager.GetPropertyValue(context, serverEntry, PropertyManager.DnsHostName); } return _cachedHostName; } } public int LdapPort { get { CheckIfDisposed(); if (_cachedLdapPort == -1) { DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); _cachedLdapPort = (int)PropertyManager.GetPropertyValue(context, ntdsaEntry, PropertyManager.MsDSPortLDAP); } return _cachedLdapPort; } } public int SslPort { get { CheckIfDisposed(); if (_cachedSslPort == -1) { DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); _cachedSslPort = (int)PropertyManager.GetPropertyValue(context, ntdsaEntry, PropertyManager.MsDSPortSSL); } return _cachedSslPort; } } // Abstract Properties public AdamRoleCollection Roles { get { CheckIfDisposed(); DirectoryEntry schemaEntry = null; DirectoryEntry partitionsEntry = null; try { if (_cachedRoles == null) { // check for the fsmoRoleOwner attribute on the Config and Schema objects ArrayList roleList = new ArrayList(); schemaEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext)); if (NtdsaObjectName.Equals((string)PropertyManager.GetPropertyValue(context, schemaEntry, PropertyManager.FsmoRoleOwner))) { roleList.Add(AdamRole.SchemaRole); } partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); if (NtdsaObjectName.Equals((string)PropertyManager.GetPropertyValue(context, partitionsEntry, PropertyManager.FsmoRoleOwner))) { roleList.Add(AdamRole.NamingRole); } _cachedRoles = new AdamRoleCollection(roleList); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { if (schemaEntry != null) { schemaEntry.Dispose(); } if (partitionsEntry != null) { partitionsEntry.Dispose(); } } return _cachedRoles; } } public string DefaultPartition { get { CheckIfDisposed(); if (!_defaultPartitionInitialized || _defaultPartitionModified) { DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); try { ntdsaEntry.RefreshCache(); if (ntdsaEntry.Properties[PropertyManager.MsDSDefaultNamingContext].Value == null) { // property has not been set _cachedDefaultPartition = null; } else { _cachedDefaultPartition = (string)PropertyManager.GetPropertyValue(context, ntdsaEntry, PropertyManager.MsDSDefaultNamingContext); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } _defaultPartitionInitialized = true; } return _cachedDefaultPartition; } set { CheckIfDisposed(); DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); if (value == null) { if (ntdsaEntry.Properties.Contains(PropertyManager.MsDSDefaultNamingContext)) { ntdsaEntry.Properties[PropertyManager.MsDSDefaultNamingContext].Clear(); } } else { // // should be in DN format // if (!Utils.IsValidDNFormat(value)) { throw new ArgumentException(SR.InvalidDNFormat, "value"); } // this value should be one of partitions currently being hosted by // this adam instance if (!Partitions.Contains(value)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ServerNotAReplica , value), "value"); } ntdsaEntry.Properties[PropertyManager.MsDSDefaultNamingContext].Value = value; } _defaultPartitionModified = true; } } public override string IPAddress { get { CheckIfDisposed(); IPHostEntry hostEntry = Dns.GetHostEntry(HostName); if (hostEntry.AddressList.GetLength(0) > 0) { return (hostEntry.AddressList[0]).ToString(); } else { return null; } } } public override String SiteName { get { CheckIfDisposed(); if (cachedSiteName == null) { DirectoryEntry siteEntry = DirectoryEntryManager.GetDirectoryEntry(context, SiteObjectName); try { cachedSiteName = (string)PropertyManager.GetPropertyValue(context, siteEntry, PropertyManager.Cn); } finally { siteEntry.Dispose(); } } return cachedSiteName; } } internal String SiteObjectName { get { CheckIfDisposed(); if (cachedSiteObjectName == null) { // get the site object name from the server object name // CN=server1,CN=Servers,CN=Site1,CN=Sites // the site object name is the third component onwards string[] components = ServerObjectName.Split(new char[] { ',' }); if (components.GetLength(0) < 3) { // should not happen throw new ActiveDirectoryOperationException(SR.InvalidServerNameFormat); } cachedSiteObjectName = components[2]; for (int i = 3; i < components.GetLength(0); i++) { cachedSiteObjectName += "," + components[i]; } } return cachedSiteObjectName; } } internal String ServerObjectName { get { CheckIfDisposed(); if (cachedServerObjectName == null) { DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { cachedServerObjectName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.ServerName); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { rootDSE.Dispose(); } } return cachedServerObjectName; } } internal String NtdsaObjectName { get { CheckIfDisposed(); if (cachedNtdsaObjectName == null) { DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { cachedNtdsaObjectName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DsServiceName); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { rootDSE.Dispose(); } } return cachedNtdsaObjectName; } } internal Guid NtdsaObjectGuid { get { CheckIfDisposed(); if (cachedNtdsaObjectGuid == Guid.Empty) { DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); byte[] guidByteArray = (byte[])PropertyManager.GetPropertyValue(context, ntdsaEntry, PropertyManager.ObjectGuid); cachedNtdsaObjectGuid = new Guid(guidByteArray); } return cachedNtdsaObjectGuid; } } public override SyncUpdateCallback SyncFromAllServersCallback { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _userDelegate; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); _userDelegate = value; } } public override ReplicationConnectionCollection InboundConnections { get { return GetInboundConnectionsHelper(); } } public override ReplicationConnectionCollection OutboundConnections { get { return GetOutboundConnectionsHelper(); } } #endregion public properties #region private methods private ReplicationFailureCollection GetReplicationFailures(DS_REPL_INFO_TYPE type) { IntPtr info = (IntPtr)0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)type, (int)type, null, ref advanced, 0, DirectoryContext.ADAMHandle); return ConstructFailures(info, this, DirectoryContext.ADAMHandle); } private void GetADAMHandle() { // this part of the code needs to be synchronized lock (this) { if (_ADAMHandle == IntPtr.Zero) { // get the credentials object if (_authIdentity == IntPtr.Zero) { _authIdentity = Utils.GetAuthIdentity(context, DirectoryContext.ADAMHandle); } // DSBind, but we need to have port as annotation specified string bindingString = HostName + ":" + LdapPort; _ADAMHandle = Utils.GetDSHandle(bindingString, null, _authIdentity, DirectoryContext.ADAMHandle); } } } private void FreeADAMHandle() { lock (this) { // DsUnbind Utils.FreeDSHandle(_ADAMHandle, DirectoryContext.ADAMHandle); // free the credentials object Utils.FreeAuthIdentity(_authIdentity, DirectoryContext.ADAMHandle); } } #endregion private methods } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedBillingSetupServiceClientTest { [Category("Autogenerated")][Test] public void GetBillingSetupRequestObject() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup response = client.GetBillingSetup(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetBillingSetupRequestObjectAsync() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BillingSetup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup responseCallSettings = await client.GetBillingSetupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::BillingSetup responseCancellationToken = await client.GetBillingSetupAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetBillingSetup() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup response = client.GetBillingSetup(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetBillingSetupAsync() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BillingSetup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup responseCallSettings = await client.GetBillingSetupAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::BillingSetup responseCancellationToken = await client.GetBillingSetupAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetBillingSetupResourceNames() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup response = client.GetBillingSetup(request.ResourceNameAsBillingSetupName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetBillingSetupResourceNamesAsync() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BillingSetup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup responseCallSettings = await client.GetBillingSetupAsync(request.ResourceNameAsBillingSetupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::BillingSetup responseCancellationToken = await client.GetBillingSetupAsync(request.ResourceNameAsBillingSetupName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateBillingSetupRequestObject() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); MutateBillingSetupRequest request = new MutateBillingSetupRequest { CustomerId = "customer_id3b3724cb", Operation = new BillingSetupOperation(), }; MutateBillingSetupResponse expectedResponse = new MutateBillingSetupResponse { Result = new MutateBillingSetupResult(), }; mockGrpcClient.Setup(x => x.MutateBillingSetup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); MutateBillingSetupResponse response = client.MutateBillingSetup(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateBillingSetupRequestObjectAsync() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); MutateBillingSetupRequest request = new MutateBillingSetupRequest { CustomerId = "customer_id3b3724cb", Operation = new BillingSetupOperation(), }; MutateBillingSetupResponse expectedResponse = new MutateBillingSetupResponse { Result = new MutateBillingSetupResult(), }; mockGrpcClient.Setup(x => x.MutateBillingSetupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateBillingSetupResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); MutateBillingSetupResponse responseCallSettings = await client.MutateBillingSetupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateBillingSetupResponse responseCancellationToken = await client.MutateBillingSetupAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateBillingSetup() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); MutateBillingSetupRequest request = new MutateBillingSetupRequest { CustomerId = "customer_id3b3724cb", Operation = new BillingSetupOperation(), }; MutateBillingSetupResponse expectedResponse = new MutateBillingSetupResponse { Result = new MutateBillingSetupResult(), }; mockGrpcClient.Setup(x => x.MutateBillingSetup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); MutateBillingSetupResponse response = client.MutateBillingSetup(request.CustomerId, request.Operation); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateBillingSetupAsync() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); MutateBillingSetupRequest request = new MutateBillingSetupRequest { CustomerId = "customer_id3b3724cb", Operation = new BillingSetupOperation(), }; MutateBillingSetupResponse expectedResponse = new MutateBillingSetupResponse { Result = new MutateBillingSetupResult(), }; mockGrpcClient.Setup(x => x.MutateBillingSetupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateBillingSetupResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); MutateBillingSetupResponse responseCallSettings = await client.MutateBillingSetupAsync(request.CustomerId, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateBillingSetupResponse responseCancellationToken = await client.MutateBillingSetupAsync(request.CustomerId, request.Operation, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Numerics; using System.Text; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace IronPython.Runtime { public static class LiteralParser { internal delegate IReadOnlyList<char> ParseStringErrorHandler<T>(in ReadOnlySpan<T> data, int start, int end, string reason); internal static string ParseString(char[] text, int start, int length, bool isRaw, bool isUniEscape, bool normalizeLineEndings) => ParseString(text.AsSpan(start, length), isRaw, isUniEscape, normalizeLineEndings); internal static string ParseString(in ReadOnlySpan<char> text, bool isRaw, bool isUniEscape, bool normalizeLineEndings) { if (isRaw && !isUniEscape && !normalizeLineEndings) return text.ToString(); return DoParseString(text, isRaw, isUniEscape, normalizeLineEndings) ?? text.ToString(); } internal static string ParseString(byte[] bytes, int start, int length, bool isRaw, ParseStringErrorHandler<byte> errorHandler) => ParseString(bytes.AsSpan(start, length), isRaw, errorHandler); internal static string ParseString(in ReadOnlySpan<byte> bytes, bool isRaw, ParseStringErrorHandler<byte> errorHandler) => DoParseString(bytes, isRaw, isUniEscape: true, normalizeLineEndings: false, errorHandler) ?? bytes.MakeString(); private static string DoParseString<T>(ReadOnlySpan<T> data, bool isRaw, bool isUniEscape, bool normalizeLineEndings, ParseStringErrorHandler<T> errorHandler = default) where T : unmanaged, IConvertible { StringBuilder buf = null; int i = 0; int length = data.Length; int val; while (i < length) { char ch = data[i++].ToChar(null); if ((!isRaw || isUniEscape) && ch == '\\') { StringBuilderInit(ref buf, data, i - 1); if (i >= length) { if (isRaw) { buf.Append('\\'); } else { handleError(data, i - 1, i, "\\ at end of string"); } break; } ch = data[i++].ToChar(null); if ((ch == 'u' || ch == 'U') && isUniEscape) { int len = (ch == 'u') ? 4 : 8; int max = 16; if (TryParseInt(data, i, len, max, out val, out int consumed)) { if (val < 0 || val > 0x10ffff) { handleError(data, i - 2, i + consumed, isRaw ? @"\Uxxxxxxxx out of range" : "illegal Unicode character"); } else if (val < 0x010000) { buf.Append((char)val); } else { buf.Append(char.ConvertFromUtf32(val)); } } else { handleError(data, i - 2, i + consumed, ch == 'u' ? @"truncated \uXXXX escape" : @"truncated \UXXXXXXXX escape"); } i += consumed; } else { if (isRaw) { buf.Append('\\'); buf.Append(ch); continue; } switch (ch) { case 'a': buf.Append('\a'); continue; case 'b': buf.Append('\b'); continue; case 'f': buf.Append('\f'); continue; case 'n': buf.Append('\n'); continue; case 'r': buf.Append('\r'); continue; case 't': buf.Append('\t'); continue; case 'v': buf.Append('\v'); continue; case '\\': buf.Append('\\'); continue; case '\'': buf.Append('\''); continue; case '\"': buf.Append('\"'); continue; case '\n': continue; case '\r': if (!normalizeLineEndings) { goto default; } else if (i < length && data[i].ToChar(null) == '\n') { i++; } continue; case 'N': { Modules.unicodedata.EnsureInitialized(); StringBuilder namebuf = new StringBuilder(); bool namestarted = false; bool namecomplete = false; if (i < length && data[i].ToChar(null) == '{') { namestarted = true; i++; while (i < length) { char namech = data[i++].ToChar(null); if (namech != '}') { namebuf.Append(namech); } else { namecomplete = true; break; } } } if (!namecomplete || namebuf.Length == 0) { handleError(data, i - 2 - (namestarted ? 1 : 0) - namebuf.Length - (namecomplete ? 1 : 0), // 2 for \N and 1 for { and 1 for } i - (namecomplete ? 1 : 0), // 1 for } @"malformed \N character escape"); if (namecomplete) { buf.Append('}'); } } else { try { string uval = IronPython.Modules.unicodedata.lookup(namebuf.ToString()); buf.Append(uval); } catch (KeyNotFoundException) { handleError(data, i - 4 - namebuf.Length, // 4 for \N{} i, "unknown Unicode character name"); } } } continue; case 'x': //hex if (!TryParseInt(data, i, 2, 16, out val, out int consumed)) { handleError(data, i - 2, i + consumed, @"truncated \xXX escape"); } else { buf.Append((char)val); } i += consumed; continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { val = ch - '0'; if (i < length && HexValue(data[i].ToChar(null), out int onechar) && onechar < 8) { val = val * 8 + onechar; i++; if (i < length && HexValue(data[i].ToChar(null), out onechar) && onechar < 8) { val = val * 8 + onechar; i++; } } } buf.Append((char)val); continue; default: buf.Append("\\"); buf.Append(ch); continue; } } } else if (ch == '\r' && normalizeLineEndings) { StringBuilderInit(ref buf, data, i - 1); // normalize line endings if (i < length && data[i].ToChar(null) == '\n') { i++; } buf.Append('\n'); } else { buf?.Append(ch); } } return buf?.ToString(); void handleError(in ReadOnlySpan<T> data, int start, int end, string reason) { if (errorHandler == null) { Bytes bytesData = null; if (typeof(T) == typeof(byte)) { bytesData = Bytes.Make(data.ToArray() as byte[]); } throw PythonExceptions.CreateThrowable(PythonExceptions.UnicodeDecodeError, isRaw ? "rawunicodeescape" : "unicodeescape", bytesData, start, end, reason); } var substitute = errorHandler(data, start, end, reason); if (substitute != null) { buf.Append(substitute.ToArray()); } } } private static void StringBuilderInit<T>(ref StringBuilder sb, in ReadOnlySpan<T> data, int toCopy) where T : unmanaged, IConvertible { Debug.Assert(toCopy <= data.Length); if (sb != null) return; sb = new StringBuilder(data.Length); unsafe { if (sizeof(T) == sizeof(char)) { fixed (T* cp = data) { sb.Append((char*)cp, toCopy); } return; } } // T is not char for (int i = 0; i < toCopy; i++) { sb.Append(data[i].ToChar(null)); } } internal delegate IReadOnlyList<byte> ParseBytesErrorHandler<T>(in ReadOnlySpan<T> data, int start, int end, string reason); internal static List<byte> ParseBytes<T>(ReadOnlySpan<T> data, bool isRaw, bool isAscii, bool normalizeLineEndings, ParseBytesErrorHandler<T> errorHandler = default) where T : IConvertible { List<byte> buf = new List<byte>(data.Length); int i = 0; int length = data.Length; int val; while (i < length) { char ch = data[i++].ToChar(null); if (!isRaw && ch == '\\') { if (i >= length) { throw PythonOps.ValueError("Trailing \\ in string"); } ch = data[i++].ToChar(null); switch (ch) { case 'a': buf.Add((byte)'\a'); continue; case 'b': buf.Add((byte)'\b'); continue; case 'f': buf.Add((byte)'\f'); continue; case 'n': buf.Add((byte)'\n'); continue; case 'r': buf.Add((byte)'\r'); continue; case 't': buf.Add((byte)'\t'); continue; case 'v': buf.Add((byte)'\v'); continue; case '\\': buf.Add((byte)'\\'); continue; case '\'': buf.Add((byte)'\''); continue; case '\"': buf.Add((byte)'\"'); continue; case '\n': continue; case '\r': if (!normalizeLineEndings) { goto default; } else if (i < length && data[i].ToChar(null) == '\n') { i++; } continue; case 'x': //hex if (!TryParseInt(data, i, 2, 16, out val, out int consumed)) { int pos = i - 2; string message = $"invalid \\x escape at position {pos}"; if (errorHandler == null) { throw PythonOps.ValueError(message); } var substitute = errorHandler(data, pos, pos + consumed, message); if (substitute != null) { buf.AddRange(substitute); } } else { buf.Add((byte)val); } i += consumed; continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { val = ch - '0'; if (i < length && HexValue(data[i].ToChar(null), out int onechar) && onechar < 8) { val = val * 8 + onechar; i++; if (i < length && HexValue(data[i].ToChar(null), out onechar) && onechar < 8) { val = val * 8 + onechar; i++; } } } buf.Add((byte)val); continue; default: if (isAscii && ch >= 0x80) { throw PythonOps.SyntaxError("bytes can only contain ASCII literal characters."); } buf.Add((byte)'\\'); buf.Add((byte)ch); continue; } } else if (ch == '\r' && normalizeLineEndings) { // normalize line endings if (i < length && data[i].ToChar(null) == '\n') { i++; } buf.Add((byte)'\n'); } else if (isAscii && ch >= 0x80) { throw PythonOps.SyntaxError("bytes can only contain ASCII literal characters."); } else { buf.Add((byte)ch); } } return buf; } private static bool HexValue(char ch, out int value) { switch (ch) { case '0': case '\x660': value = 0; break; case '1': case '\x661': value = 1; break; case '2': case '\x662': value = 2; break; case '3': case '\x663': value = 3; break; case '4': case '\x664': value = 4; break; case '5': case '\x665': value = 5; break; case '6': case '\x666': value = 6; break; case '7': case '\x667': value = 7; break; case '8': case '\x668': value = 8; break; case '9': case '\x669': value = 9; break; default: if (ch >= 'a' && ch <= 'z') { value = ch - 'a' + 10; } else if (ch >= 'A' && ch <= 'Z') { value = ch - 'A' + 10; } else { value = -1; return false; } break; } return true; } private static int HexValue(char ch) { int value; if (!HexValue(ch, out value)) { throw new ValueErrorException("bad char for integer value: " + ch); } return value; } private static int CharValue(char ch, int b) { int val = HexValue(ch); if (val >= b) { throw new ValueErrorException(String.Format("bad char for the integer value: '{0}' (base {1})", ch, b)); } return val; } private static bool ParseInt(string text, int b, out int ret) { ret = 0; long m = 1; for (int i = text.Length - 1; i >= 0; i--) { // avoid the exception here. Not only is throwing it expensive, // but loading the resources for it is also expensive long lret = ret + m * CharValue(text[i], b); if (Int32.MinValue <= lret && lret <= Int32.MaxValue) { ret = (int)lret; } else { return false; } m *= b; if (Int32.MinValue > m || m > Int32.MaxValue) { return false; } } return true; } private static bool TryParseInt<T>(in ReadOnlySpan<T> text, int start, int length, int b, out int value, out int consumed) where T : IConvertible { value = 0; for (int i = start, end = start + length; i < end; i++) { if (i < text.Length && HexValue(text[i].ToChar(null), out int onechar) && onechar < b) { value = value * b + onechar; } else { consumed = i - start; return false; } } consumed = length; return true; } public static object ParseInteger(string text, int b) { Debug.Assert(b != 0); int iret; if (!ParseInt(text, b, out iret)) { BigInteger ret = ParseBigInteger(text, b); if (!ret.AsInt32(out iret)) { return ret; } } return ScriptingRuntimeHelpers.Int32ToObject(iret); } public static object ParseIntegerSign(string text, int b, int start = 0) { if (TryParseIntegerSign(text, b, start, out object val)) return val; throw new ValueErrorException(string.Format("invalid literal for int() with base {0}: {1}", b, StringOps.__repr__(text))); } internal static bool TryParseIntegerSign(string text, int b, int start, out object val) { int end = text.Length, saveb = b, savestart = start; if (start < 0 || start > end) throw new ArgumentOutOfRangeException(nameof(start)); short sign = 1; if (b < 0 || b == 1 || b > 36) { throw new ValueErrorException("int() base must be >= 2 and <= 36, or 0"); } ParseIntegerStart(text, ref b, ref start, end, ref sign); if (start < end && char.IsWhiteSpace(text, start)) { val = default; return false; } int ret = 0; try { int saveStart = start; for (; ; ) { int digit; if (start >= end) { if (saveStart == start) { val = default; return false; } break; } if (!HexValue(text[start], out digit)) break; if (!(digit < b)) { val = default; return false; } checked { // include sign here so that System.Int32.MinValue won't overflow ret = ret * b + sign * digit; } start++; } } catch (OverflowException) { if (TryParseBigIntegerSign(text, saveb, savestart, out var bi)) { val = bi; return true; } val = default; return false; } ParseIntegerEnd(text, ref start, ref end); if (start < end) { val = default; return false; } val = ScriptingRuntimeHelpers.Int32ToObject(ret); return true; } private static void ParseIntegerStart(string text, ref int b, ref int start, int end, ref short sign) { // Skip whitespace while (start < end && Char.IsWhiteSpace(text, start)) start++; // Sign? if (start < end) { switch (text[start]) { case '-': sign = -1; goto case '+'; case '+': start++; break; } } // Determine base if (b == 0) { if (start < end && text[start] == '0') { // Hex, oct, or bin if (++start < end) { switch(text[start]) { case 'x': case 'X': start++; b = 16; break; case 'o': case 'O': b = 8; start++; break; case 'b': case 'B': start++; b = 2; break; } } if (b == 0) { // Keep the leading zero start--; b = 8; } } else { b = 10; } } } private static void ParseIntegerEnd(string text, ref int start, ref int end) { // Skip whitespace while (start < end && char.IsWhiteSpace(text, start)) start++; } internal static BigInteger ParseBigInteger(string text, int b) { Debug.Assert(b != 0); BigInteger ret = BigInteger.Zero; BigInteger m = BigInteger.One; int i = text.Length - 1; int groupMax = 7; if (b <= 10) groupMax = 9;// 2 147 483 647 while (i >= 0) { // extract digits in a batch int smallMultiplier = 1; uint uval = 0; for (int j = 0; j < groupMax && i >= 0; j++) { uval = (uint)(CharValue(text[i--], b) * smallMultiplier + uval); smallMultiplier *= b; } // this is more generous than needed ret += m * (BigInteger)uval; if (i >= 0) m = m * (smallMultiplier); } return ret; } internal static BigInteger ParseBigIntegerSign(string text, int b, int start = 0) { if (TryParseBigIntegerSign(text, b, start, out var val)) return val; throw new ValueErrorException(string.Format("invalid literal for int() with base {0}: {1}", b, StringOps.__repr__(text))); } private static bool TryParseBigIntegerSign(string text, int b, int start, out BigInteger val) { int end = text.Length; if (start < 0 || start > end) throw new ArgumentOutOfRangeException(nameof(start)); short sign = 1; if (b < 0 || b == 1 || b > 36) { throw new ValueErrorException("int() base must be >= 2 and <= 36, or 0"); } ParseIntegerStart(text, ref b, ref start, end, ref sign); if (start < end && char.IsWhiteSpace(text, start)) { val = default; return false; } BigInteger ret = BigInteger.Zero; int saveStart = start; for (; ; ) { int digit; if (start >= end) { if (start == saveStart) { val = default; return false; } break; } if (!HexValue(text[start], out digit)) break; if (!(digit < b)) { val = default; return false; } ret = ret * b + digit; start++; } ParseIntegerEnd(text, ref start, ref end); if (start < end) { val = default; return false; } val = sign < 0 ? -ret : ret; return true; } internal static bool TryParseFloat(string text, out double res, bool replaceUnicode) { try { // // Strings that end with '\0' is the specific case that CLR libraries allow, // however Python doesn't. Since we use CLR floating point number parser, // we must check explicitly for the strings that end with '\0' // if (text != null && text.Length > 0 && text[text.Length - 1] == '\0') { res = default; return false; } res = ParseFloatNoCatch(text, replaceUnicode: replaceUnicode); } catch (OverflowException) { res = text.lstrip().StartsWith("-", StringComparison.Ordinal) ? Double.NegativeInfinity : Double.PositiveInfinity; } catch(FormatException) { res = default; return false; } return true; } public static double ParseFloat(string text) { try { // // Strings that end with '\0' is the specific case that CLR libraries allow, // however Python doesn't. Since we use CLR floating point number parser, // we must check explicitly for the strings that end with '\0' // if (text != null && text.Length > 0 && text[text.Length - 1] == '\0') { throw PythonOps.ValueError("null byte in float literal"); } return ParseFloatNoCatch(text); } catch (OverflowException) { return text.lstrip().StartsWith("-", StringComparison.Ordinal) ? Double.NegativeInfinity : Double.PositiveInfinity; } } private static double ParseFloatNoCatch(string text, bool replaceUnicode = true) { string s = replaceUnicode ? ReplaceUnicodeCharacters(text) : text; switch (s.ToLowerAsciiTriggered().lstrip()) { case "nan": case "+nan": case "-nan": return double.NaN; case "inf": case "+inf": case "infinity": case "+infinity": return double.PositiveInfinity; case "-inf": case "-infinity": return double.NegativeInfinity; default: // pass NumberStyles to disallow ,'s in float strings. double res = double.Parse(s, NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture); return (res == 0.0 && text.lstrip().StartsWith("-", StringComparison.Ordinal)) ? DoubleOps.NegativeZero : res; } } private static string ReplaceUnicodeCharacters(string text) { StringBuilder replacement = null; for (int i = 0; i < text.Length; i++) { char ch = text[i]; if (ch >= '\x660' && ch <= '\x669') { // replace unicode digits if (replacement == null) replacement = new StringBuilder(text); replacement[i] = (char)(ch - '\x660' + '0'); } else if (ch >= '\x80' && char.IsWhiteSpace(ch)) { // replace unicode whitespace if (replacement == null) replacement = new StringBuilder(text); replacement[i] = ' '; } } if (replacement != null) { text = replacement.ToString(); } return text; } // ParseComplex helpers private static char[] signs = new char[] { '+', '-' }; private static Exception ExnMalformed() { return PythonOps.ValueError("complex() arg is a malformed string"); } public static Complex ParseComplex(string s) { // remove no-meaning spaces and convert to lowercase string text = s.Trim().ToLower(); // remove 1 layer of parens if (text.StartsWith("(", StringComparison.Ordinal) && text.EndsWith(")", StringComparison.Ordinal)) { text = text.Substring(1, text.Length - 2); } text = text.Trim(); if (string.IsNullOrEmpty(text) || text.IndexOf(' ') != -1) { throw ExnMalformed(); } try { int len = text.Length; var idx = text.IndexOf('j'); if (idx == -1) { return MathUtils.MakeReal(ParseFloatNoCatch(text)); } else if (idx == len - 1) { // last sign delimits real and imaginary... int signPos = text.LastIndexOfAny(signs); // ... unless it's after 'e', so we bypass up to 2 of those here for (int i = 0; signPos > 0 && text[signPos - 1] == 'e'; i++) { if (i == 2) { // too many 'e's throw ExnMalformed(); } signPos = text.Substring(0, signPos - 1).LastIndexOfAny(signs); } // no real component if (signPos < 0) { return MathUtils.MakeImaginary((len == 1) ? 1 : ParseFloatNoCatch(text.Substring(0, len - 1))); } string real = text.Substring(0, signPos); string imag = text.Substring(signPos, len - signPos - 1); if (imag.Length == 1) { imag += "1"; // convert +/- to +1/-1 } return new Complex(String.IsNullOrEmpty(real) ? 0 : ParseFloatNoCatch(real), ParseFloatNoCatch(imag)); } else { throw ExnMalformed(); } } catch (OverflowException) { throw PythonOps.ValueError("complex() literal too large to convert"); } catch { throw ExnMalformed(); } } public static Complex ParseImaginary(string text) { try { return MathUtils.MakeImaginary(double.Parse( text.Substring(0, text.Length - 1), System.Globalization.CultureInfo.InvariantCulture.NumberFormat )); } catch (OverflowException) { return new Complex(0, Double.PositiveInfinity); } } } }
/* Gaigen 2.5 Test Suite */ /* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; namespace c3ga_ns { /// <summary>This class can hold a specialized multivector of type rotor. /// /// The coordinates are stored in type double. /// /// The variable non-zero coordinates are: /// - coordinate 1 (array index: SCALAR = 0) /// - coordinate e1^e2 (array index: E1_E2 = 1) /// - coordinate e2^e3 (array index: E2_E3 = 2) /// - coordinate -1*e1^e3 (array index: E3_E1 = 3) /// /// The type has no constant coordinates. /// /// /// </summary> public class rotor : mv_if { /// <summary>The 1 coordinate. /// </summary> protected internal double m_scalar; /// <summary>The e1^e2 coordinate. /// </summary> protected internal double m_e1_e2; /// <summary>The e2^e3 coordinate. /// </summary> protected internal double m_e2_e3; /// <summary>The -1*e1^e3 coordinate. /// </summary> protected internal double m_e3_e1; /// <summary>Array indices of rotor coordinates. /// </summary> /// <summary>index of coordinate for 1 in rotor /// </summary> public const int SCALAR = 0; /// <summary>index of coordinate for e1^e2 in rotor /// </summary> public const int E1_E2 = 1; /// <summary>index of coordinate for e2^e3 in rotor /// </summary> public const int E2_E3 = 2; /// <summary>index of coordinate for -1*e1^e3 in rotor /// </summary> public const int E3_E1 = 3; /// <summary>The order of coordinates (this is the type of the first argument of coordinate-handling functions. /// </summary> public enum CoordinateOrder { coord_scalar_e1e2_e2e3_e3e1 }; public const CoordinateOrder coord_scalar_e1e2_e2e3_e3e1 = CoordinateOrder.coord_scalar_e1e2_e2e3_e3e1; /// <summary> /// Converts this multivector to a 'mv' (implementation of interface 'mv_interface') /// </summary> public mv to_mv() { return new mv(this); } /// <summary> /// Constructs a new rotor with variable coordinates set to 0. /// </summary> public rotor() {Set();} /// <summary> /// Copy constructor. /// </summary> public rotor(rotor A) {Set(A);} /// <summary> /// Constructs a new rotor with scalar value 'scalar'. /// </summary> public rotor(double scalar) {Set(scalar);} /// <summary> /// Constructs a new rotor from mv. /// </summary> /// <param name="A">The value to copy. Coordinates that cannot be represented are silently dropped. </param> public rotor(mv A /*, int filler */) {Set(A);} /// <summary> /// Constructs a new rotor. Coordinate values come from 'A'. /// </summary> public rotor(CoordinateOrder co, double[] A) {Set(co, A);} /// <summary> /// Constructs a new rotor with each coordinate specified. /// </summary> public rotor(CoordinateOrder co, double scalar, double e1_e2, double e2_e3, double e3_e1) { Set(co, scalar, e1_e2, e2_e3, e3_e1); } public void Set() { m_scalar = m_e1_e2 = m_e2_e3 = m_e3_e1 = 0.0; } public void Set(double scalarVal) { m_scalar = scalarVal; m_e1_e2 = m_e2_e3 = m_e3_e1 = 0.0; } public void Set(CoordinateOrder co, double _scalar, double _e1_e2, double _e2_e3, double _e3_e1) { m_scalar = _scalar; m_e1_e2 = _e1_e2; m_e2_e3 = _e2_e3; m_e3_e1 = _e3_e1; } public void Set(CoordinateOrder co, double[] A) { m_scalar = A[0]; m_e1_e2 = A[1]; m_e2_e3 = A[2]; m_e3_e1 = A[3]; } public void Set(rotor a) { m_scalar = a.m_scalar; m_e1_e2 = a.m_e1_e2; m_e2_e3 = a.m_e2_e3; m_e3_e1 = a.m_e3_e1; } public void Set(mv src) { if (src.c()[0] != null) { double[] ptr = src.c()[0]; m_scalar = ptr[0]; } else { m_scalar = 0.0; } if (src.c()[2] != null) { double[] ptr = src.c()[2]; m_e1_e2 = ptr[0]; m_e2_e3 = ptr[2]; m_e3_e1 = -ptr[1]; } else { m_e1_e2 = 0.0; m_e2_e3 = 0.0; m_e3_e1 = 0.0; } } /// <summary>Returns the absolute largest coordinate. /// </summary> public double LargestCoordinate() { double maxValue = Math.Abs(m_scalar); if (Math.Abs(m_e1_e2) > maxValue) { maxValue = Math.Abs(m_e1_e2); } if (Math.Abs(m_e2_e3) > maxValue) { maxValue = Math.Abs(m_e2_e3); } if (Math.Abs(m_e3_e1) > maxValue) { maxValue = Math.Abs(m_e3_e1); } return maxValue; } /// <summary>Returns the absolute largest coordinate, /// and the corresponding basis blade bitmap. /// </summary> public double LargestBasisBlade(int bm) { double maxValue = Math.Abs(m_scalar); bm = 0; if (Math.Abs(m_e1_e2) > maxValue) { maxValue = Math.Abs(m_e1_e2); bm = 3; } if (Math.Abs(m_e2_e3) > maxValue) { maxValue = Math.Abs(m_e2_e3); bm = 6; } if (Math.Abs(m_e3_e1) > maxValue) { maxValue = Math.Abs(m_e3_e1); bm = 5; } return maxValue; } /// <summary> /// Returns this multivector, converted to a string. /// The floating point formatter is controlled via c3ga.setStringFormat(). /// </summary> public override string ToString() { return c3ga.String(this); } /// <summary> /// Returns this multivector, converted to a string. /// The floating point formatter is "F". /// </summary> public string ToString_f() { return ToString("F"); } /// <summary> /// Returns this multivector, converted to a string. /// The floating point formatter is "E". /// </summary> public string ToString_e() { return ToString("E"); } /// <summary> /// Returns this multivector, converted to a string. /// The floating point formatter is "E20". /// </summary> public string ToString_e20() { return ToString("E20"); } /// <summary> /// Returns this multivector, converted to a string. /// <param name="fp">floating point format. Use 'null' for the default format (see setStringFormat()).</param> /// </summary> public string ToString(string fp) { return c3ga.String(this, fp); } /// <summary>Returns the 1 coordinate. /// </summary> public double get_scalar() { return m_scalar;} /// <summary>Sets the 1 coordinate. /// </summary> public void set_scalar(double scalar) { m_scalar = scalar;} /// <summary>Returns the e1^e2 coordinate. /// </summary> public double get_e1_e2() { return m_e1_e2;} /// <summary>Sets the e1^e2 coordinate. /// </summary> public void set_e1_e2(double e1_e2) { m_e1_e2 = e1_e2;} /// <summary>Returns the e2^e3 coordinate. /// </summary> public double get_e2_e3() { return m_e2_e3;} /// <summary>Sets the e2^e3 coordinate. /// </summary> public void set_e2_e3(double e2_e3) { m_e2_e3 = e2_e3;} /// <summary>Returns the -1*e1^e3 coordinate. /// </summary> public double get_e3_e1() { return m_e3_e1;} /// <summary>Sets the -1*e1^e3 coordinate. /// </summary> public void set_e3_e1(double e3_e1) { m_e3_e1 = e3_e1;} } // end of class rotor } // end of namespace c3ga_ns
// 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 Infrastructure.Common; using System; using System.ServiceModel; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; public partial class ExpectedExceptionTests : ConditionalWcfTest { [WcfFact] [OuterLoop] public static void NotExistentHost_Throws_EndpointNotFoundException() { string nonExistentHost = "http://nonexisthost/WcfService/WindowsCommunicationFoundation"; ChannelFactory<IWcfService> factory = null; EndpointAddress endpointAddress = null; BasicHttpBinding binding = null; IWcfService serviceProxy = null; // *** VALIDATE *** \\ EndpointNotFoundException exception = Assert.Throws<EndpointNotFoundException>(() => { // *** SETUP *** \\ binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMilliseconds(40000); endpointAddress = new EndpointAddress(nonExistentHost); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { serviceProxy.Echo("Hello"); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }); // *** ADDITIONAL VALIDATION FOR NET NATIVE *** \\ // On .Net Native retail, exception message is stripped to include only parameter Assert.True(exception.Message.Contains(nonExistentHost), string.Format("Expected exception message to contain: '{0}'\nThe exception message was: {1}", nonExistentHost, exception.Message)); } [WcfFact] [Issue(1717, Framework = FrameworkID.NetNative)] [OuterLoop] public static void ServiceRestart_Throws_CommunicationException() { // This test validates that if the Service were to shut-down, re-start or otherwise die in the // middle of an operation the client will not just hang. It should instead receive a CommunicationException. string restartServiceAddress = ""; ChannelFactory<IWcfService> setupHostFactory = null; IWcfService setupHostServiceProxy = null; ChannelFactory<IWcfRestartService> factory = null; IWcfRestartService serviceProxy = null; BasicHttpBinding binding = new BasicHttpBinding(); // *** Step 1 *** \\ // We need the Service to create and open a ServiceHost and then give us the endpoint address for it. try { setupHostFactory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); setupHostServiceProxy = setupHostFactory.CreateChannel(); restartServiceAddress = setupHostServiceProxy.GetRestartServiceEndpoint(); // *** CLEANUP *** \\ ((ICommunicationObject)setupHostServiceProxy).Close(); setupHostFactory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)setupHostServiceProxy, setupHostFactory); } // *** Additional Setup *** \\ // The restartServiceAddress we got from the Service used localhost as the host name. // We need the actual host name for the client call to work. // To make it easier to parse, localhost was replaced with '[HOST]'. // Use Endpoints.HttpBaseAddress_Basic only for the purpose of extracting the Service host name. // Then update 'restartServiceAddress' with it. string hostName = new Uri(Endpoints.HttpBaseAddress_Basic).Host; restartServiceAddress = restartServiceAddress.Replace("[HOST]", hostName); // Get the last portion of the restart service url which is a Guid and convert it back to a Guid // This is needed by the RestartService operation as a Dictionary key to get the ServiceHost string uniqueIdentifier = restartServiceAddress.Substring(restartServiceAddress.LastIndexOf("/") + 1); Guid guid = new Guid(uniqueIdentifier); // *** Step 2 *** \\ // Simple echo call to make sure the newly created endpoint is working. try { factory = new ChannelFactory<IWcfRestartService>(binding, new EndpointAddress(restartServiceAddress)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.NonRestartService(guid); Assert.True(result == "Success!", string.Format("Test Case failed, expected the returned string to be: {0}, instead it was: {1}", "Success!", result)); } catch (Exception ex) { string exceptionMessage = ex.Message; string innerExceptionMessage = ex.InnerException?.Message; string testExceptionMessage = $"The ping to validate the newly created endpoint failed.\nThe endpoint pinged was: {restartServiceAddress}\nThe GUID used to extract the ServiceHost from the server side dictionary was: {guid}"; string fullExceptionMessage = $"testExceptionMessage: {testExceptionMessage}\nexceptionMessage: {exceptionMessage}\ninnerExceptionMessage: {innerExceptionMessage}"; Assert.True(false, fullExceptionMessage); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } // *** Step 3 *** \\ // The actual part of the test where the host is killed in the middle of the operation. // We expect the test should not hang and should receive a CommunicationException. CommunicationException exception = Assert.Throws<CommunicationException>(() => { factory = new ChannelFactory<IWcfRestartService>(binding, new EndpointAddress(restartServiceAddress)); serviceProxy = factory.CreateChannel(); try { // *** EXECUTE *** \\ serviceProxy.RestartService(guid); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }); } [WcfFact] [OuterLoop] public static void UnknownUrl_Throws_EndpointNotFoundException() { // We need a running service host at the other end but mangle the endpoint suffix string notFoundUrl = Endpoints.HttpBaseAddress_Basic + "not-an-endpoint"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; EndpointAddress endpointAddress = null; IWcfService serviceProxy = null; // *** VALIDATE *** \\ EndpointNotFoundException exception = Assert.Throws<EndpointNotFoundException>(() => { // *** SETUP *** \\ binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMilliseconds(10000); endpointAddress = new EndpointAddress(notFoundUrl); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { serviceProxy.Echo("Hello"); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }); // *** ADDITIONAL VALIDATION FOR NET NATIVE *** \\ // On .Net Native retail, exception message is stripped to include only parameter Assert.True(exception.Message.Contains(notFoundUrl), string.Format("Expected exception message to contain: '{0}'\nThe exception message was:{1}", notFoundUrl, exception.Message)); } [WcfFact] [OuterLoop] public static void UnknownUrl_Throws_ProtocolException() { string protocolExceptionUri = Endpoints.HttpProtocolError_Address; BasicHttpBinding binding = null; EndpointAddress endpointAddress = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; // *** VALIDATE *** \\ ProtocolException exception = Assert.Throws<ProtocolException>(() => { // *** SETUP *** \\ binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMilliseconds(10000); endpointAddress = new EndpointAddress(protocolExceptionUri); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { serviceProxy.Echo("Hello"); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }); // *** ADDITIONAL VALIDATION FOR NET NATIVE *** \\ // On .Net Native retail, exception message is stripped to include only parameter Assert.True(exception.Message.Contains(protocolExceptionUri), string.Format("Expected exception message to contain: '{0}'\nThe exception was: '{1}'", protocolExceptionUri, exception.Message)); } [WcfFact] [OuterLoop] public static void DuplexCallback_Throws_FaultException_DirectThrow() { DuplexChannelFactory<IWcfDuplexTaskReturnService> factory = null; Guid guid = Guid.NewGuid(); EndpointAddress endpointAddress = null; NetTcpBinding binding = null; DuplexTaskReturnServiceCallback callbackService = null; InstanceContext context = null; IWcfDuplexTaskReturnService serviceProxy = null; // *** VALIDATE *** \\ FaultException<FaultDetail> exception = Assert.Throws<FaultException<FaultDetail>>(() => { // *** SETUP *** \\ binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; callbackService = new DuplexTaskReturnServiceCallback(true); context = new InstanceContext(callbackService); endpointAddress = new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address); factory = new DuplexChannelFactory<IWcfDuplexTaskReturnService>(context, binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { Task<Guid> task = serviceProxy.FaultPing(guid); if ((task as IAsyncResult).AsyncWaitHandle.WaitOne(ScenarioTestHelpers.TestTimeout)) { Guid returnedGuid = task.GetAwaiter().GetResult(); } else { throw new TimeoutException(String.Format("The call to the Service did not complete within the alloted time of: {0}", ScenarioTestHelpers.TestTimeout)); } } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }); // *** ADDITIONAL VALIDATION *** \\ string exceptionCodeName = "ServicePingFaultCallback"; string exceptionReason = "Reason: Testing FaultException returned from Duplex Callback"; Assert.True(String.Equals(exceptionCodeName, exception.Code.Name), String.Format("Expected exception code name: {0}\nActual exception code name: {1}", exceptionCodeName, exception.Code.Name)); Assert.True(String.Equals(exceptionReason, exception.Reason.GetMatchingTranslation().Text), String.Format("Expected exception reason: {0}\nActual exception reason: {1}", exceptionReason, exception.Reason.GetMatchingTranslation().Text)); } [WcfFact] [OuterLoop] public static void DuplexCallback_Throws_FaultException_ReturnsFaultedTask() { DuplexChannelFactory<IWcfDuplexTaskReturnService> factory = null; Guid guid = Guid.NewGuid(); NetTcpBinding binding = null; DuplexTaskReturnServiceCallback callbackService = null; InstanceContext context = null; EndpointAddress endpointAddress = null; IWcfDuplexTaskReturnService serviceProxy = null; // *** VALIDATE *** \\ FaultException<FaultDetail> exception = Assert.Throws<FaultException<FaultDetail>>(() => { // *** SETUP *** \\ binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; endpointAddress = new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address); callbackService = new DuplexTaskReturnServiceCallback(); context = new InstanceContext(callbackService); factory = new DuplexChannelFactory<IWcfDuplexTaskReturnService>(context, binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { Task<Guid> task = serviceProxy.FaultPing(guid); if ((task as IAsyncResult).AsyncWaitHandle.WaitOne(ScenarioTestHelpers.TestTimeout)) { Guid returnedGuid = task.GetAwaiter().GetResult(); } else { throw new TimeoutException(String.Format("The call to the Service did not complete within the alloted time of: {0}", ScenarioTestHelpers.TestTimeout)); } } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }); // *** ADDITIONAL VALIDATION *** \\ string exceptionCodeName = "ServicePingFaultCallback"; string exceptionReason = "Reason: Testing FaultException returned from Duplex Callback"; Assert.True(String.Equals(exceptionCodeName, exception.Code.Name), String.Format("Expected exception code name: {0}\nActual exception code name: {1}", exceptionCodeName, exception.Code.Name)); Assert.True(String.Equals(exceptionReason, exception.Reason.GetMatchingTranslation().Text), String.Format("Expected exception reason: {0}\nActual exception reason: {1}", exceptionReason, exception.Reason.GetMatchingTranslation().Text)); } [WcfFact] [OuterLoop] // Verify product throws MessageSecurityException when the Dns identity from the server does not match the expectation public static void TCP_ServiceCertExpired_Throw_MessageSecurityException() { string testString = "Hello"; NetTcpBinding binding = null; EndpointAddress endpointAddress = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; // *** SETUP *** \\ binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.Transport; binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; endpointAddress = new EndpointAddress(Endpoints.Tcp_ExpiredServerCertResource_Address); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { serviceProxy.Echo(testString); Assert.True(false, "Expected: SecurityNegotiationException, Actual: no exception"); } catch (CommunicationException exception) { // *** VALIDATE *** \\ // Cannot explicitly catch a SecurityNegotiationException as it is not in the public contract. string exceptionType = exception.GetType().Name; if (exceptionType != "SecurityNegotiationException") { Assert.True(false, string.Format("Expected type SecurityNegotiationException, Actual: {0}", exceptionType)); } } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] // Verify product throws SecurityNegotiationException when the service cert is revoked public static void TCP_ServiceCertRevoked_Throw_SecurityNegotiationException() { string testString = "Hello"; NetTcpBinding binding = null; EndpointAddress endpointAddress = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; // *** SETUP *** \\ binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.Transport; binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; endpointAddress = new EndpointAddress(new Uri(Endpoints.Tcp_RevokedServerCertResource_Address), new DnsEndpointIdentity(Endpoints.Tcp_RevokedServerCertResource_HostName)); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { serviceProxy.Echo(testString); Assert.True(false, "Expected: SecurityNegotiationException, Actual: no exception"); } catch (CommunicationException exception) { // *** VALIDATION *** \\ // Cannot explicitly catch a SecurityNegotiationException as it is not in the public contract. string exceptionType = exception.GetType().Name; if (exceptionType != "SecurityNegotiationException") { Assert.True(false, string.Format("Expected type SecurityNegotiationException, Actual: {0}", exceptionType)); } Assert.True(exception.Message.Contains(Endpoints.Tcp_RevokedServerCertResource_HostName), string.Format("Expected message contains {0}, actual message: {1}", Endpoints.Tcp_RevokedServerCertResource_HostName, exception.ToString())); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] // Verify product throws SecurityNegotiationException when the service cert only has the ClientAuth usage public static void TCP_ServiceCertInvalidEKU_Throw_SecurityNegotiationException() { string testString = "Hello"; NetTcpBinding binding = null; EndpointAddress endpointAddress = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; // *** SETUP *** \\ binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.Transport; binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; endpointAddress = new EndpointAddress(new Uri(Endpoints.Tcp_InvalidEkuServerCertResource_Address), new DnsEndpointIdentity(Endpoints.Tcp_InvalidEkuServerCertResource_HostName)); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { serviceProxy.Echo(testString); Assert.True(false, "Expected: SecurityNegotiationException, Actual: no exception"); } catch (CommunicationException exception) { // *** VALIDATION *** \\ // Cannot explicitly catch a SecurityNegotiationException as it is not in the public contract. string exceptionType = exception.GetType().Name; if (exceptionType != "SecurityNegotiationException") { Assert.True(false, string.Format("Expected type SecurityNegotiationException, Actual: {0}", exceptionType)); } Assert.True(exception.Message.Contains(Endpoints.Tcp_RevokedServerCertResource_HostName), string.Format("Expected message contains {0}, actual message: {1}", Endpoints.Tcp_RevokedServerCertResource_HostName, exception.ToString())); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void Abort_During_Implicit_Open_Closes_Sync_Waiters() { // This test is a regression test of an issue with CallOnceManager. // When a single proxy is used to make several service calls without // explicitly opening it, the CallOnceManager queues up all the requests // that happen while it is opening the channel (or handling previously // queued service calls. If the channel was closed or faulted during // the handling of any queued requests, it caused a pathological worst // case where every queued request waited for its complete SendTimeout // before failing. // // This test operates by making multiple concurrent synchronous service // calls, but stalls the Opening event to allow them to be queued before // any of them are allowed to proceed. It then aborts the channel when // the first service operation is allowed to proceed. This causes the // CallOnce manager to deal with all its queued operations and cause // them to complete other than by timing out. BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; int timeoutMs = 20000; long operationsQueued = 0; int operationCount = 5; Task<string>[] tasks = new Task<string>[operationCount]; Exception[] exceptions = new Exception[operationCount]; string[] results = new string[operationCount]; bool isClosed = false; DateTime endOfOpeningStall = DateTime.Now; int serverDelayMs = 100; TimeSpan serverDelayTimeSpan = TimeSpan.FromMilliseconds(serverDelayMs); string testMessage = "testMessage"; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Streamed; // SendTimeout is the timeout used for implicit opens binding.SendTimeout = TimeSpan.FromMilliseconds(timeoutMs); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); // Force the implicit open to stall until we have multiple concurrent calls pending. // This forces the CallOnceManager to have a queue of waiters it will need to notify. ((ICommunicationObject)serviceProxy).Opening += (s, e) => { // Wait until we see sync calls have been queued DateTime startOfOpeningStall = DateTime.Now; while (true) { endOfOpeningStall = DateTime.Now; // Don't wait forever -- if we stall longer than the SendTimeout, it means something // is wrong other than what we are testing, so just fail early. if ((endOfOpeningStall - startOfOpeningStall).TotalMilliseconds > timeoutMs) { Assert.True(false, "The Opening event timed out waiting for operations to queue, which was not expected for this test."); } // As soon as we have all our Tasks at least running, wait a little // longer to allow them finish queuing up their waiters, then stop stalling the Opening if (Interlocked.Read(ref operationsQueued) >= operationCount) { Task.Delay(500).Wait(); endOfOpeningStall = DateTime.Now; return; } Task.Delay(100).Wait(); } }; // Each task will make a synchronous service call, which will cause all but the // first to be queued for the implicit open. The first call to complete then closes // the channel so that it is forced to deal with queued waiters. Func<string> callFunc = () => { // We increment the # ops queued before making the actual sync call, which is // technically a short race condition in the test. But reversing the order would // timeout the implicit open and fault the channel. Interlocked.Increment(ref operationsQueued); // The call of the operation is what creates the entry in the CallOnceManager queue. // So as each Task below starts, it increments the count and adds a waiter to the // queue. We ask for a small delay on the server side just to introduce a small // stall after the sync request has been made before it can complete. Otherwise // fast machines can finish all the requests before the first one finishes the Close(). string result = serviceProxy.EchoWithTimeout("test", serverDelayTimeSpan); lock (tasks) { if (!isClosed) { try { isClosed = true; ((ICommunicationObject)serviceProxy).Abort(); } catch { } } } return result; }; // *** EXECUTE *** \\ DateTime startTime = DateTime.Now; for (int i = 0; i < operationCount; ++i) { tasks[i] = Task.Run(callFunc); } for (int i = 0; i < operationCount; ++i) { try { results[i] = tasks[i].GetAwaiter().GetResult(); } catch (Exception ex) { exceptions[i] = ex; } } // *** VALIDATE *** \\ double elapsedMs = (DateTime.Now - endOfOpeningStall).TotalMilliseconds; // Before validating that the issue was fixed, first validate that we received the exceptions or the // results we expected. This is to verify the fix did not introduce a behavioral change other than the // elimination of the long unnecessary timeouts after the channel was closed. int nFailures = 0; for (int i = 0; i < operationCount; ++i) { if (exceptions[i] == null) { Assert.True((String.Equals("test", results[i])), String.Format("Expected operation #{0} to return '{1}' but actual was '{2}'", i, testMessage, results[i])); } else { ++nFailures; TimeoutException toe = exceptions[i] as TimeoutException; Assert.True(toe == null, String.Format("Task [{0}] should not have failed with TimeoutException", i)); } } Assert.True(nFailures > 0, String.Format("Expected at least one operation to throw an exception, but none did. Elapsed time = {0} ms.", elapsedMs)); Assert.True(nFailures < operationCount, String.Format("Expected at least one operation to succeed but none did. Elapsed time = {0} ms.", elapsedMs)); // The original issue was that sync waiters in the CallOnceManager were not notified when // the channel became unusable and therefore continued to time out for the full amount. // Additionally, because they were executed sequentially, it was also possible for each one // to time out for the full amount. Given that we closed the channel, we expect all the queued // waiters to have been immediately waked up and detected failure. int expectedElapsedMs = (operationCount * serverDelayMs) + timeoutMs / 2; Assert.True(elapsedMs < expectedElapsedMs, String.Format("The {0} operations took {1} ms to complete which exceeds the expected {2} ms", operationCount, elapsedMs, expectedElapsedMs)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: testsuite_remote.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Remote { /// <summary>Holder for reflection information generated from testsuite_remote.proto</summary> public static partial class TestsuiteRemoteReflection { #region Descriptor /// <summary>File descriptor for testsuite_remote.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TestsuiteRemoteReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChZ0ZXN0c3VpdGVfcmVtb3RlLnByb3RvEgZyZW1vdGUiOQoDTG9nEiEKB0xv", "Z1R5cGUYASABKA4yEC5yZW1vdGUuTE9HX1RZUEUSDwoHQ29udGVudBgCIAEo", "CSIFCgNOaWwiYAoNQ2FwdHVyZVBhcmFtcxISCgpGdWxsU2NyZWVuGAEgASgI", "EgkKAXgYAiABKAUSCQoBeRgDIAEoBRIJCgF3GAQgASgFEgkKAWgYBSABKAUS", "DwoHUXVhbGl0eRgGIAEoBSInCgpDbWRSZXF1ZXN0EgsKA0NtZBgBIAEoCRIM", "CgRBcmdzGAIgAygJImQKEU1vdXNlQ2xpY2tSZXF1ZXN0EgkKAXgYASABKAUS", "CQoBeRgCIAEoBRITCgtEb3VibGVDbGljaxgDIAEoCBIkCgZCdXR0b24YBCAB", "KA4yFC5yZW1vdGUuTW91c2VCdXR0b25zIkMKEE1vdXNlTW92ZVJlcXVlc3QS", "CQoBeBgBIAEoBRIJCgF5GAIgASgFEgsKA0xvdxgDIAEoAhIMCgRIaWdoGAQg", "ASgCIi8KDUtleVRhcFJlcXVlc3QSDwoHS2V5Q29kZRgBIAMoCRINCgVEZWxh", "eRgCIAEoAiI4ChFLZXlMaXN0VGFwUmVxdWVzdBIjCgRLZXlzGAEgAygLMhUu", "cmVtb3RlLktleVRhcFJlcXVlc3QiJQoITG9nUmVwbHkSGQoETG9ncxgBIAMo", "CzILLnJlbW90ZS5Mb2ciLAoJSW1hZ2VEYXRhEhEKCVRpbWVTdGFtcBgBIAEo", "AxIMCgREYXRhGAIgASgMIiUKDU1vdXNlUG9zaXRpb24SCQoBeBgBIAEoBRIJ", "CgF5GAIgASgFKi0KCExPR19UWVBFEgkKBURlYnVnEAASCwoHV2FybmluZxAB", "EgkKBUVycm9yEAIqYwoMTW91c2VCdXR0b25zEggKBE5vbmUQABIKCgRMZWZ0", "EICAQBIMCgVSaWdodBCAgIABEg0KBk1pZGRsZRCAgIACEg8KCFhCdXR0b24x", "EICAgAQSDwoIWEJ1dHRvbjIQgICACDLZAgoNUmVtb3RlU2VydmljZRIxCgdF", "eGVjQ21kEhIucmVtb3RlLkNtZFJlcXVlc3QaEC5yZW1vdGUuTG9nUmVwbHki", "ABI7Cg1DYXB0dXJlU2NyZWVuEhUucmVtb3RlLkNhcHR1cmVQYXJhbXMaES5y", "ZW1vdGUuSW1hZ2VEYXRhIgASNgoKTW91c2VDbGljaxIZLnJlbW90ZS5Nb3Vz", "ZUNsaWNrUmVxdWVzdBoLLnJlbW90ZS5Mb2ciABIuCgZLZXlUYXASFS5yZW1v", "dGUuS2V5VGFwUmVxdWVzdBoLLnJlbW90ZS5Mb2ciABI2CgpLZXlMaXN0VGFw", "EhkucmVtb3RlLktleUxpc3RUYXBSZXF1ZXN0GgsucmVtb3RlLkxvZyIAEjgK", "EEdldE1vdXNlUG9zaXRpb24SCy5yZW1vdGUuTmlsGhUucmVtb3RlLk1vdXNl", "UG9zaXRpb24iAGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Remote.LOG_TYPE), typeof(global::Remote.MouseButtons), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Remote.Log), global::Remote.Log.Parser, new[]{ "LogType", "Content" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Remote.Nil), global::Remote.Nil.Parser, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Remote.CaptureParams), global::Remote.CaptureParams.Parser, new[]{ "FullScreen", "X", "Y", "W", "H", "Quality" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Remote.CmdRequest), global::Remote.CmdRequest.Parser, new[]{ "Cmd", "Args" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Remote.MouseClickRequest), global::Remote.MouseClickRequest.Parser, new[]{ "X", "Y", "DoubleClick", "Button" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Remote.MouseMoveRequest), global::Remote.MouseMoveRequest.Parser, new[]{ "X", "Y", "Low", "High" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Remote.KeyTapRequest), global::Remote.KeyTapRequest.Parser, new[]{ "KeyCode", "Delay" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Remote.KeyListTapRequest), global::Remote.KeyListTapRequest.Parser, new[]{ "Keys" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Remote.LogReply), global::Remote.LogReply.Parser, new[]{ "Logs" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Remote.ImageData), global::Remote.ImageData.Parser, new[]{ "TimeStamp", "Data" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Remote.MousePosition), global::Remote.MousePosition.Parser, new[]{ "X", "Y" }, null, null, null) })); } #endregion } #region Enums public enum LOG_TYPE { [pbr::OriginalName("Debug")] Debug = 0, [pbr::OriginalName("Warning")] Warning = 1, [pbr::OriginalName("Error")] Error = 2, } public enum MouseButtons { [pbr::OriginalName("None")] None = 0, [pbr::OriginalName("Left")] Left = 1048576, [pbr::OriginalName("Right")] Right = 2097152, [pbr::OriginalName("Middle")] Middle = 4194304, [pbr::OriginalName("XButton1")] Xbutton1 = 8388608, [pbr::OriginalName("XButton2")] Xbutton2 = 16777216, } #endregion #region Messages public sealed partial class Log : pb::IMessage<Log> { private static readonly pb::MessageParser<Log> _parser = new pb::MessageParser<Log>(() => new Log()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Log> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Remote.TestsuiteRemoteReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Log() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Log(Log other) : this() { logType_ = other.logType_; content_ = other.content_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Log Clone() { return new Log(this); } /// <summary>Field number for the "LogType" field.</summary> public const int LogTypeFieldNumber = 1; private global::Remote.LOG_TYPE logType_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Remote.LOG_TYPE LogType { get { return logType_; } set { logType_ = value; } } /// <summary>Field number for the "Content" field.</summary> public const int ContentFieldNumber = 2; private string content_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Content { get { return content_; } set { content_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Log); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Log other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (LogType != other.LogType) return false; if (Content != other.Content) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (LogType != 0) hash ^= LogType.GetHashCode(); if (Content.Length != 0) hash ^= Content.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (LogType != 0) { output.WriteRawTag(8); output.WriteEnum((int) LogType); } if (Content.Length != 0) { output.WriteRawTag(18); output.WriteString(Content); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (LogType != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) LogType); } if (Content.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Content); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Log other) { if (other == null) { return; } if (other.LogType != 0) { LogType = other.LogType; } if (other.Content.Length != 0) { Content = other.Content; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { logType_ = (global::Remote.LOG_TYPE) input.ReadEnum(); break; } case 18: { Content = input.ReadString(); break; } } } } } public sealed partial class Nil : pb::IMessage<Nil> { private static readonly pb::MessageParser<Nil> _parser = new pb::MessageParser<Nil>(() => new Nil()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Nil> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Remote.TestsuiteRemoteReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Nil() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Nil(Nil other) : this() { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Nil Clone() { return new Nil(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Nil); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Nil other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Nil other) { if (other == null) { return; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; } } } } public sealed partial class CaptureParams : pb::IMessage<CaptureParams> { private static readonly pb::MessageParser<CaptureParams> _parser = new pb::MessageParser<CaptureParams>(() => new CaptureParams()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CaptureParams> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Remote.TestsuiteRemoteReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CaptureParams() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CaptureParams(CaptureParams other) : this() { fullScreen_ = other.fullScreen_; x_ = other.x_; y_ = other.y_; w_ = other.w_; h_ = other.h_; quality_ = other.quality_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CaptureParams Clone() { return new CaptureParams(this); } /// <summary>Field number for the "FullScreen" field.</summary> public const int FullScreenFieldNumber = 1; private bool fullScreen_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool FullScreen { get { return fullScreen_; } set { fullScreen_ = value; } } /// <summary>Field number for the "x" field.</summary> public const int XFieldNumber = 2; private int x_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int X { get { return x_; } set { x_ = value; } } /// <summary>Field number for the "y" field.</summary> public const int YFieldNumber = 3; private int y_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Y { get { return y_; } set { y_ = value; } } /// <summary>Field number for the "w" field.</summary> public const int WFieldNumber = 4; private int w_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int W { get { return w_; } set { w_ = value; } } /// <summary>Field number for the "h" field.</summary> public const int HFieldNumber = 5; private int h_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int H { get { return h_; } set { h_ = value; } } /// <summary>Field number for the "Quality" field.</summary> public const int QualityFieldNumber = 6; private int quality_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Quality { get { return quality_; } set { quality_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CaptureParams); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CaptureParams other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (FullScreen != other.FullScreen) return false; if (X != other.X) return false; if (Y != other.Y) return false; if (W != other.W) return false; if (H != other.H) return false; if (Quality != other.Quality) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (FullScreen != false) hash ^= FullScreen.GetHashCode(); if (X != 0) hash ^= X.GetHashCode(); if (Y != 0) hash ^= Y.GetHashCode(); if (W != 0) hash ^= W.GetHashCode(); if (H != 0) hash ^= H.GetHashCode(); if (Quality != 0) hash ^= Quality.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (FullScreen != false) { output.WriteRawTag(8); output.WriteBool(FullScreen); } if (X != 0) { output.WriteRawTag(16); output.WriteInt32(X); } if (Y != 0) { output.WriteRawTag(24); output.WriteInt32(Y); } if (W != 0) { output.WriteRawTag(32); output.WriteInt32(W); } if (H != 0) { output.WriteRawTag(40); output.WriteInt32(H); } if (Quality != 0) { output.WriteRawTag(48); output.WriteInt32(Quality); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (FullScreen != false) { size += 1 + 1; } if (X != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(X); } if (Y != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Y); } if (W != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(W); } if (H != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(H); } if (Quality != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Quality); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CaptureParams other) { if (other == null) { return; } if (other.FullScreen != false) { FullScreen = other.FullScreen; } if (other.X != 0) { X = other.X; } if (other.Y != 0) { Y = other.Y; } if (other.W != 0) { W = other.W; } if (other.H != 0) { H = other.H; } if (other.Quality != 0) { Quality = other.Quality; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { FullScreen = input.ReadBool(); break; } case 16: { X = input.ReadInt32(); break; } case 24: { Y = input.ReadInt32(); break; } case 32: { W = input.ReadInt32(); break; } case 40: { H = input.ReadInt32(); break; } case 48: { Quality = input.ReadInt32(); break; } } } } } /// <summary> ///Request /// </summary> public sealed partial class CmdRequest : pb::IMessage<CmdRequest> { private static readonly pb::MessageParser<CmdRequest> _parser = new pb::MessageParser<CmdRequest>(() => new CmdRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CmdRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Remote.TestsuiteRemoteReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CmdRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CmdRequest(CmdRequest other) : this() { cmd_ = other.cmd_; args_ = other.args_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CmdRequest Clone() { return new CmdRequest(this); } /// <summary>Field number for the "Cmd" field.</summary> public const int CmdFieldNumber = 1; private string cmd_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Cmd { get { return cmd_; } set { cmd_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "Args" field.</summary> public const int ArgsFieldNumber = 2; private static readonly pb::FieldCodec<string> _repeated_args_codec = pb::FieldCodec.ForString(18); private readonly pbc::RepeatedField<string> args_ = new pbc::RepeatedField<string>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Args { get { return args_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CmdRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CmdRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Cmd != other.Cmd) return false; if(!args_.Equals(other.args_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Cmd.Length != 0) hash ^= Cmd.GetHashCode(); hash ^= args_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Cmd.Length != 0) { output.WriteRawTag(10); output.WriteString(Cmd); } args_.WriteTo(output, _repeated_args_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Cmd.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Cmd); } size += args_.CalculateSize(_repeated_args_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CmdRequest other) { if (other == null) { return; } if (other.Cmd.Length != 0) { Cmd = other.Cmd; } args_.Add(other.args_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Cmd = input.ReadString(); break; } case 18: { args_.AddEntriesFrom(input, _repeated_args_codec); break; } } } } } public sealed partial class MouseClickRequest : pb::IMessage<MouseClickRequest> { private static readonly pb::MessageParser<MouseClickRequest> _parser = new pb::MessageParser<MouseClickRequest>(() => new MouseClickRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MouseClickRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Remote.TestsuiteRemoteReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MouseClickRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MouseClickRequest(MouseClickRequest other) : this() { x_ = other.x_; y_ = other.y_; doubleClick_ = other.doubleClick_; button_ = other.button_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MouseClickRequest Clone() { return new MouseClickRequest(this); } /// <summary>Field number for the "x" field.</summary> public const int XFieldNumber = 1; private int x_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int X { get { return x_; } set { x_ = value; } } /// <summary>Field number for the "y" field.</summary> public const int YFieldNumber = 2; private int y_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Y { get { return y_; } set { y_ = value; } } /// <summary>Field number for the "DoubleClick" field.</summary> public const int DoubleClickFieldNumber = 3; private bool doubleClick_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool DoubleClick { get { return doubleClick_; } set { doubleClick_ = value; } } /// <summary>Field number for the "Button" field.</summary> public const int ButtonFieldNumber = 4; private global::Remote.MouseButtons button_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Remote.MouseButtons Button { get { return button_; } set { button_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MouseClickRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MouseClickRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (X != other.X) return false; if (Y != other.Y) return false; if (DoubleClick != other.DoubleClick) return false; if (Button != other.Button) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (X != 0) hash ^= X.GetHashCode(); if (Y != 0) hash ^= Y.GetHashCode(); if (DoubleClick != false) hash ^= DoubleClick.GetHashCode(); if (Button != 0) hash ^= Button.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (X != 0) { output.WriteRawTag(8); output.WriteInt32(X); } if (Y != 0) { output.WriteRawTag(16); output.WriteInt32(Y); } if (DoubleClick != false) { output.WriteRawTag(24); output.WriteBool(DoubleClick); } if (Button != 0) { output.WriteRawTag(32); output.WriteEnum((int) Button); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (X != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(X); } if (Y != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Y); } if (DoubleClick != false) { size += 1 + 1; } if (Button != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Button); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MouseClickRequest other) { if (other == null) { return; } if (other.X != 0) { X = other.X; } if (other.Y != 0) { Y = other.Y; } if (other.DoubleClick != false) { DoubleClick = other.DoubleClick; } if (other.Button != 0) { Button = other.Button; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { X = input.ReadInt32(); break; } case 16: { Y = input.ReadInt32(); break; } case 24: { DoubleClick = input.ReadBool(); break; } case 32: { button_ = (global::Remote.MouseButtons) input.ReadEnum(); break; } } } } } public sealed partial class MouseMoveRequest : pb::IMessage<MouseMoveRequest> { private static readonly pb::MessageParser<MouseMoveRequest> _parser = new pb::MessageParser<MouseMoveRequest>(() => new MouseMoveRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MouseMoveRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Remote.TestsuiteRemoteReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MouseMoveRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MouseMoveRequest(MouseMoveRequest other) : this() { x_ = other.x_; y_ = other.y_; low_ = other.low_; high_ = other.high_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MouseMoveRequest Clone() { return new MouseMoveRequest(this); } /// <summary>Field number for the "x" field.</summary> public const int XFieldNumber = 1; private int x_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int X { get { return x_; } set { x_ = value; } } /// <summary>Field number for the "y" field.</summary> public const int YFieldNumber = 2; private int y_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Y { get { return y_; } set { y_ = value; } } /// <summary>Field number for the "Low" field.</summary> public const int LowFieldNumber = 3; private float low_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float Low { get { return low_; } set { low_ = value; } } /// <summary>Field number for the "High" field.</summary> public const int HighFieldNumber = 4; private float high_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float High { get { return high_; } set { high_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MouseMoveRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MouseMoveRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (X != other.X) return false; if (Y != other.Y) return false; if (Low != other.Low) return false; if (High != other.High) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (X != 0) hash ^= X.GetHashCode(); if (Y != 0) hash ^= Y.GetHashCode(); if (Low != 0F) hash ^= Low.GetHashCode(); if (High != 0F) hash ^= High.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (X != 0) { output.WriteRawTag(8); output.WriteInt32(X); } if (Y != 0) { output.WriteRawTag(16); output.WriteInt32(Y); } if (Low != 0F) { output.WriteRawTag(29); output.WriteFloat(Low); } if (High != 0F) { output.WriteRawTag(37); output.WriteFloat(High); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (X != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(X); } if (Y != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Y); } if (Low != 0F) { size += 1 + 4; } if (High != 0F) { size += 1 + 4; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MouseMoveRequest other) { if (other == null) { return; } if (other.X != 0) { X = other.X; } if (other.Y != 0) { Y = other.Y; } if (other.Low != 0F) { Low = other.Low; } if (other.High != 0F) { High = other.High; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { X = input.ReadInt32(); break; } case 16: { Y = input.ReadInt32(); break; } case 29: { Low = input.ReadFloat(); break; } case 37: { High = input.ReadFloat(); break; } } } } } public sealed partial class KeyTapRequest : pb::IMessage<KeyTapRequest> { private static readonly pb::MessageParser<KeyTapRequest> _parser = new pb::MessageParser<KeyTapRequest>(() => new KeyTapRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<KeyTapRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Remote.TestsuiteRemoteReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KeyTapRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KeyTapRequest(KeyTapRequest other) : this() { keyCode_ = other.keyCode_.Clone(); delay_ = other.delay_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KeyTapRequest Clone() { return new KeyTapRequest(this); } /// <summary>Field number for the "KeyCode" field.</summary> public const int KeyCodeFieldNumber = 1; private static readonly pb::FieldCodec<string> _repeated_keyCode_codec = pb::FieldCodec.ForString(10); private readonly pbc::RepeatedField<string> keyCode_ = new pbc::RepeatedField<string>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> KeyCode { get { return keyCode_; } } /// <summary>Field number for the "Delay" field.</summary> public const int DelayFieldNumber = 2; private float delay_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float Delay { get { return delay_; } set { delay_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as KeyTapRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(KeyTapRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!keyCode_.Equals(other.keyCode_)) return false; if (Delay != other.Delay) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= keyCode_.GetHashCode(); if (Delay != 0F) hash ^= Delay.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { keyCode_.WriteTo(output, _repeated_keyCode_codec); if (Delay != 0F) { output.WriteRawTag(21); output.WriteFloat(Delay); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += keyCode_.CalculateSize(_repeated_keyCode_codec); if (Delay != 0F) { size += 1 + 4; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(KeyTapRequest other) { if (other == null) { return; } keyCode_.Add(other.keyCode_); if (other.Delay != 0F) { Delay = other.Delay; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { keyCode_.AddEntriesFrom(input, _repeated_keyCode_codec); break; } case 21: { Delay = input.ReadFloat(); break; } } } } } public sealed partial class KeyListTapRequest : pb::IMessage<KeyListTapRequest> { private static readonly pb::MessageParser<KeyListTapRequest> _parser = new pb::MessageParser<KeyListTapRequest>(() => new KeyListTapRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<KeyListTapRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Remote.TestsuiteRemoteReflection.Descriptor.MessageTypes[7]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KeyListTapRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KeyListTapRequest(KeyListTapRequest other) : this() { keys_ = other.keys_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KeyListTapRequest Clone() { return new KeyListTapRequest(this); } /// <summary>Field number for the "Keys" field.</summary> public const int KeysFieldNumber = 1; private static readonly pb::FieldCodec<global::Remote.KeyTapRequest> _repeated_keys_codec = pb::FieldCodec.ForMessage(10, global::Remote.KeyTapRequest.Parser); private readonly pbc::RepeatedField<global::Remote.KeyTapRequest> keys_ = new pbc::RepeatedField<global::Remote.KeyTapRequest>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Remote.KeyTapRequest> Keys { get { return keys_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as KeyListTapRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(KeyListTapRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!keys_.Equals(other.keys_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= keys_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { keys_.WriteTo(output, _repeated_keys_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += keys_.CalculateSize(_repeated_keys_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(KeyListTapRequest other) { if (other == null) { return; } keys_.Add(other.keys_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { keys_.AddEntriesFrom(input, _repeated_keys_codec); break; } } } } } /// <summary> ///Reply /// </summary> public sealed partial class LogReply : pb::IMessage<LogReply> { private static readonly pb::MessageParser<LogReply> _parser = new pb::MessageParser<LogReply>(() => new LogReply()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<LogReply> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Remote.TestsuiteRemoteReflection.Descriptor.MessageTypes[8]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogReply() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogReply(LogReply other) : this() { logs_ = other.logs_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogReply Clone() { return new LogReply(this); } /// <summary>Field number for the "Logs" field.</summary> public const int LogsFieldNumber = 1; private static readonly pb::FieldCodec<global::Remote.Log> _repeated_logs_codec = pb::FieldCodec.ForMessage(10, global::Remote.Log.Parser); private readonly pbc::RepeatedField<global::Remote.Log> logs_ = new pbc::RepeatedField<global::Remote.Log>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Remote.Log> Logs { get { return logs_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as LogReply); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(LogReply other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!logs_.Equals(other.logs_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= logs_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { logs_.WriteTo(output, _repeated_logs_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += logs_.CalculateSize(_repeated_logs_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(LogReply other) { if (other == null) { return; } logs_.Add(other.logs_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { logs_.AddEntriesFrom(input, _repeated_logs_codec); break; } } } } } public sealed partial class ImageData : pb::IMessage<ImageData> { private static readonly pb::MessageParser<ImageData> _parser = new pb::MessageParser<ImageData>(() => new ImageData()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ImageData> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Remote.TestsuiteRemoteReflection.Descriptor.MessageTypes[9]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ImageData() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ImageData(ImageData other) : this() { timeStamp_ = other.timeStamp_; data_ = other.data_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ImageData Clone() { return new ImageData(this); } /// <summary>Field number for the "TimeStamp" field.</summary> public const int TimeStampFieldNumber = 1; private long timeStamp_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long TimeStamp { get { return timeStamp_; } set { timeStamp_ = value; } } /// <summary>Field number for the "Data" field.</summary> public const int DataFieldNumber = 2; private pb::ByteString data_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString Data { get { return data_; } set { data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ImageData); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ImageData other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (TimeStamp != other.TimeStamp) return false; if (Data != other.Data) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (TimeStamp != 0L) hash ^= TimeStamp.GetHashCode(); if (Data.Length != 0) hash ^= Data.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (TimeStamp != 0L) { output.WriteRawTag(8); output.WriteInt64(TimeStamp); } if (Data.Length != 0) { output.WriteRawTag(18); output.WriteBytes(Data); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (TimeStamp != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(TimeStamp); } if (Data.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ImageData other) { if (other == null) { return; } if (other.TimeStamp != 0L) { TimeStamp = other.TimeStamp; } if (other.Data.Length != 0) { Data = other.Data; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { TimeStamp = input.ReadInt64(); break; } case 18: { Data = input.ReadBytes(); break; } } } } } public sealed partial class MousePosition : pb::IMessage<MousePosition> { private static readonly pb::MessageParser<MousePosition> _parser = new pb::MessageParser<MousePosition>(() => new MousePosition()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MousePosition> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Remote.TestsuiteRemoteReflection.Descriptor.MessageTypes[10]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MousePosition() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MousePosition(MousePosition other) : this() { x_ = other.x_; y_ = other.y_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MousePosition Clone() { return new MousePosition(this); } /// <summary>Field number for the "x" field.</summary> public const int XFieldNumber = 1; private int x_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int X { get { return x_; } set { x_ = value; } } /// <summary>Field number for the "y" field.</summary> public const int YFieldNumber = 2; private int y_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Y { get { return y_; } set { y_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MousePosition); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MousePosition other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (X != other.X) return false; if (Y != other.Y) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (X != 0) hash ^= X.GetHashCode(); if (Y != 0) hash ^= Y.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (X != 0) { output.WriteRawTag(8); output.WriteInt32(X); } if (Y != 0) { output.WriteRawTag(16); output.WriteInt32(Y); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (X != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(X); } if (Y != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Y); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MousePosition other) { if (other == null) { return; } if (other.X != 0) { X = other.X; } if (other.Y != 0) { Y = other.Y; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { X = input.ReadInt32(); break; } case 16: { Y = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Fearfry { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { public enum GameState { Menu, Playing, Paused } public enum PlayState { Walking, Interacting, Cooking } GameState gameState = GameState.Menu; PlayState playState = PlayState.Walking; int Height; int Width; Vector2 TargetLocation; // XNA Vars GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Dictionary<string,Texture2D> images; SpriteFont MurderFont; SpriteFont BigMurderFont; KeyboardState[] keyboard = new KeyboardState[2]; MouseState[] mouse = new MouseState[2]; Vector2[] mousePos = new Vector2[2]; // NON-XNA Vars public List<InSceneObject> ObjectsInScene; private Player player; private Rectangle[] MenuRects; private Texture2D[] MenuImages; private bool[] MenuHovered; private Inventory inventory; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; images = new Dictionary<string, Texture2D>(); mouse[0] = Mouse.GetState(); keyboard[0] = Keyboard.GetState(); mousePos[0] = new Vector2(mouse[0].X,mouse[0].Y); MenuHovered = new bool[2]; ObjectsInScene = new List<InSceneObject>(); } // Updates all data dependent upon XNA interaction and code // EX: MouseState, KeyboardState, etc... public void UpdateXNAData() { // Update Mouse Data mouse[1] = mouse[0]; mouse[0] = Mouse.GetState(); // Update KeyStates keyboard[1] = keyboard[0]; keyboard[0] = Keyboard.GetState(); // Update Mouse Position mousePos[1] = mousePos[0]; mousePos[0] = new Vector2(mouse[0].X, mouse[0].Y); if(gameState == GameState.Menu) { if (MenuRects[0].Intersects(new Rectangle((int)mousePos[0].X, (int)mousePos[0].Y, 1, 1))) { MenuHovered[0] = true; } else { MenuHovered[0] = false; } if (MenuRects[1].Intersects(new Rectangle((int)mousePos[0].X, (int)mousePos[0].Y, 1, 1))) { MenuHovered[1] = true; } else { MenuHovered[1] = false; } } // MIN/MAX Values for Mouse location if (mousePos[0].X < 0) mousePos[0].X = 0; if (mousePos[0].Y < 0) mousePos[0].Y = 0; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // Note Dimensions Height = graphics.GraphicsDevice.Viewport.Height; Width = graphics.GraphicsDevice.Viewport.Width; MenuRects = new Rectangle[2]; MenuImages = new Texture2D[2]; MenuRects[0] = new Rectangle(0, Height / 3, Width, Height / 3); MenuRects[1] = new Rectangle(0, 2 * Height / 3, Width, Height / 3); // Content Loading // Fonts MurderFont = Content.Load<SpriteFont>("Default"); BigMurderFont = Content.Load<SpriteFont>("BigDefault"); // Player Texture2D[] PlayerImages = new Texture2D[3]; PlayerImages[0] = Content.Load<Texture2D>("LEFT"); PlayerImages[1] = Content.Load<Texture2D>("RIGHT"); PlayerImages[2] = Content.Load<Texture2D>("MID"); player = new Player(new Rectangle(100, 200, 108, 272), PlayerImages); ObjectsInScene.Add(player); // Menu MenuImages[0] = Content.Load<Texture2D>("PLAY"); MenuImages[1] = Content.Load<Texture2D>("QUIT"); // Inventory images["inventory"] = Content.Load<Texture2D>("Inventory"); inventory = new Inventory(images["inventory"], new Rectangle(0,0,Width, Height/6)); ObjectsInScene.Add(inventory); ObjectsInScene.Add(new Fridge(new Vector2(0, 282), new Vector2(108, 190), Content.Load<Texture2D>("Fridge"), "FRIDGE")); ObjectsInScene.Add(new Sink(new Vector2(324, 320), new Vector2(108, 90), Content.Load<Texture2D>("Sink"), "SINK")); ObjectsInScene.Add(new Cabinet(new Vector2(432, 200), new Vector2(108, 90), Content.Load<Texture2D>("Cabinet"), "CABINET")); ObjectsInScene.Add(new Stove(new Vector2(216, 320), new Vector2(108, 90), Content.Load<Texture2D>("Stove"), "STOVE")); ObjectsInScene.Add(new Counter(new Vector2(108, 320), new Vector2(108, 90), Content.Load<Texture2D>("Counter"), "COUNTER")); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // XNA Input Data Update UpdateXNAData(); ///------------- :GAME LOOP LOGIC AFTER THIS LINE: -------------- /// // MAIN Loop switch(gameState) { case GameState.Menu: MenuUpdate(gameTime); break; case GameState.Paused: break; case GameState.Playing: PlayUpdate(gameTime); // Enter Game Loop break; } base.Update(gameTime); } /// <summary> /// Menu Loop Update --- While in Main Menu /// </summary> /// <param name="gameTime"></param> public void MenuUpdate(GameTime gameTime) { if (mouse[0].LeftButton == ButtonState.Pressed && mouse[1].LeftButton != ButtonState.Pressed) { gameState = GameState.Playing; } } /// <summary> /// Menu Loop Draw --- While in Main Menu /// </summary> /// <param name="gameTime"></param> public void MenuDraw(GameTime gameTime) { spriteBatch.Begin(); spriteBatch.Draw(MenuImages[0], MenuRects[0], (MenuHovered[0]) ? new Color(100,0,255,200) : Color.White); spriteBatch.Draw(MenuImages[1], MenuRects[1], (MenuHovered[1]) ? new Color(100,0, 255, 200) : Color.White); spriteBatch.End(); Console.WriteLine(MenuHovered); DrawString("Fearfry", new Vector2(Width / 2, Height / 6), new Color(115,6,15), 1); } /// <summary> /// Game Loop Update --- While Playing /// - Can go back to Paused mode and return regardless of PlayState /// </summary> /// <param name="gameTime"></param> public void PlayUpdate(GameTime gameTime) { if(playState == PlayState.Walking) { if(keyboard[0].IsKeyDown(Keys.Left)){ player.SetDirection("left"); player.Update(new Vector2(-1,0)); } else if (keyboard[0].IsKeyDown(Keys.Up)) { player.SetDirection("mid"); player.Update(); } else if (keyboard[0].IsKeyDown(Keys.Right)) { player.SetDirection("right"); player.Update(new Vector2(1, 0)); } } } /// <summary> /// Game Loop Draw --- While Playing /// </summary> /// <param name="gameTime">gameTime</param> public void PlayDraw(GameTime gameTime) { spriteBatch.Begin(); InSceneObject iso; for(int i = 1; i< ObjectsInScene.Count; i++) { iso = ObjectsInScene[i]; iso.Draw(spriteBatch); } ObjectsInScene[0].Draw(spriteBatch); spriteBatch.End(); // TODO: Add your drawing code here } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(new Color(0,1,10)); switch(gameState) { case GameState.Menu: MenuDraw(gameTime); break; case GameState.Playing: PlayDraw(gameTime); break; case GameState.Paused: break; } DrawString("Mouse", mousePos[0], Color.Yellow, 0); base.Draw(gameTime); } public void DrawString(String text, Vector2 location, Color color = default(Color), int size=0) { // TODO: Add your drawing code here SpriteFont font = (size == 1) ? BigMurderFont : MurderFont; Vector2 Size = font.MeasureString(text); spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); spriteBatch.DrawString( font, text, new Vector2(location.X + 2, location.Y + 2), new Color(5,5,5), 0.0f, new Vector2(Size.X / 2, Size.Y / 2), 1.0f, SpriteEffects.None, 0.0f); spriteBatch.DrawString( font, text, location, color, 0.0f, new Vector2(Size.X / 2, Size.Y / 2), 1.0f, SpriteEffects.None, 0.0f); spriteBatch.End(); } } }
// 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. /*============================================================ ** ** ** ** Provides a way for an app to not start an operation unless ** there's a reasonable chance there's enough memory ** available for the operation to succeed. ** ** ===========================================================*/ using System; using System.IO; using Microsoft.Win32; using System.Runtime.InteropServices; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; /* This class allows an application to fail before starting certain activities. The idea is to fail early instead of failing in the middle of some long-running operation to increase the survivability of the application and ensure you don't have to write tricky code to handle an OOM anywhere in your app's code (which implies state corruption, meaning you should unload the appdomain, if you have a transacted environment to ensure rollback of individual transactions). This is an incomplete tool to attempt hoisting all your OOM failures from anywhere in your worker methods to one particular point where it is easier to handle an OOM failure, and you can optionally choose to not start a workitem if it will likely fail. This does not help the performance of your code directly (other than helping to avoid AD unloads). The point is to avoid starting work if it is likely to fail. The Enterprise Services team has used these memory gates effectively in the unmanaged world for a decade. In Whidbey, we will simply check to see if there is enough memory available in the OS's page file & attempt to ensure there might be enough space free within the process's address space (checking for address space fragmentation as well). We will not commit or reserve any memory. To avoid race conditions with other threads using MemoryFailPoints, we'll also keep track of a process-wide amount of memory "reserved" via all currently-active MemoryFailPoints. This has two problems: 1) This can account for memory twice. If a thread creates a MemoryFailPoint for 100 MB then allocates 99 MB, we'll see 99 MB less free memory and 100 MB less reserved memory. Yet, subtracting off the 100 MB is necessary because the thread may not have started allocating memory yet. Disposing of this class immediately after front-loaded allocations have completed is a great idea. 2) This is still vulnerable to race conditions with other threads that don't use MemoryFailPoints. So this class is far from perfect. But it may be good enough to meaningfully reduce the frequency of OutOfMemoryExceptions in managed apps. In Orcas or later, we might allocate some memory from the OS and add it to a allocation context for this thread. Obviously, at that point we need some way of conveying when we release this block of memory. So, we implemented IDisposable on this type in Whidbey and expect all users to call this from within a using block to provide lexical scope for their memory usage. The call to Dispose (implicit with the using block) will give us an opportunity to release this memory, perhaps. We anticipate this will give us the possibility of a more effective design in a future version. In Orcas, we may also need to differentiate between allocations that would go into the normal managed heap vs. the large object heap, or we should consider checking for enough free space in both locations (with any appropriate adjustments to ensure the memory is contiguous). */ namespace System.Runtime { public sealed class MemoryFailPoint : CriticalFinalizerObject, IDisposable { // Find the top section of user mode memory. Avoid the last 64K. // Windows reserves that block for the kernel, apparently, and doesn't // let us ask about that memory. But since we ask for memory in 1 MB // chunks, we don't have to special case this. Also, we need to // deal with 32 bit machines in 3 GB mode. // Using Win32's GetSystemInfo should handle all this for us. private static readonly ulong s_topOfMemory; // Walking the address space is somewhat expensive, taking around half // a millisecond. Doing that per transaction limits us to a max of // ~2000 transactions/second. Instead, let's do this address space // walk once every 10 seconds, or when we will likely fail. This // amortization scheme can reduce the cost of a memory gate by about // a factor of 100. private static long s_hiddenLastKnownFreeAddressSpace = 0; private static long s_hiddenLastTimeCheckingAddressSpace = 0; private const int CheckThreshold = 10 * 1000; // 10 seconds private static long LastKnownFreeAddressSpace { get { return Volatile.Read(ref s_hiddenLastKnownFreeAddressSpace); } set { Volatile.Write(ref s_hiddenLastKnownFreeAddressSpace, value); } } private static long AddToLastKnownFreeAddressSpace(long addend) { return Interlocked.Add(ref s_hiddenLastKnownFreeAddressSpace, addend); } private static long LastTimeCheckingAddressSpace { get { return Volatile.Read(ref s_hiddenLastTimeCheckingAddressSpace); } set { Volatile.Write(ref s_hiddenLastTimeCheckingAddressSpace, value); } } // When allocating memory segment by segment, we've hit some cases // where there are only 22 MB of memory available on the machine, // we need 1 16 MB segment, and the OS does not succeed in giving us // that memory. Reasons for this could include: // 1) The GC does allocate memory when doing a collection. // 2) Another process on the machine could grab that memory. // 3) Some other part of the runtime might grab this memory. // If we build in a little padding, we can help protect // ourselves against some of these cases, and we want to err on the // conservative side with this class. private const int LowMemoryFudgeFactor = 16 << 20; // Round requested size to a 16MB multiple to have a better granularity // when checking for available memory. private const int MemoryCheckGranularity = 16; // Note: This may become dynamically tunable in the future. // Also note that we can have different segment sizes for the normal vs. // large object heap. We currently use the max of the two. private static readonly ulong s_GCSegmentSize = RuntimeImports.RhGetGCSegmentSize(); // For multi-threaded workers, we want to ensure that if two workers // use a MemoryFailPoint at the same time, and they both succeed, that // they don't trample over each other's memory. Keep a process-wide // count of "reserved" memory, and decrement this in Dispose and // in the critical finalizer. See // SharedStatics.MemoryFailPointReservedMemory private ulong _reservedMemory; // The size of this request (from user) private bool _mustSubtractReservation; // Did we add data to SharedStatics? static MemoryFailPoint() { Interop.Kernel32.SYSTEM_INFO info = new Interop.Kernel32.SYSTEM_INFO(); Interop.Kernel32.GetSystemInfo(ref info); s_topOfMemory = (ulong)info.lpMaximumApplicationAddress; } // We can remove this link demand in a future version - we will // have scenarios for this in partial trust in the future, but // we're doing this just to restrict this in case the code below // is somehow incorrect. public MemoryFailPoint(int sizeInMegabytes) { if (sizeInMegabytes <= 0) throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), SR.ArgumentOutOfRange_NeedNonNegNum); ulong size = ((ulong)sizeInMegabytes) << 20; _reservedMemory = size; // Check to see that we both have enough memory on the system // and that we have enough room within the user section of the // process's address space. Also, we need to use the GC segment // size, not the amount of memory the user wants to allocate. // Consider correcting this to reflect free memory within the GC // heap, and to check both the normal & large object heaps. ulong segmentSize = (ulong)(Math.Ceiling((double)size / s_GCSegmentSize) * s_GCSegmentSize); if (segmentSize >= s_topOfMemory) throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_TooBig); ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity); //re-convert into bytes requestedSizeRounded <<= 20; ulong availPageFile = 0; // available VM (physical + page file) ulong totalAddressSpaceFree = 0; // non-contiguous free address space // Check for available memory, with 2 attempts at getting more // memory. // Stage 0: If we don't have enough, trigger a GC. // Stage 1: If we don't have enough, try growing the swap file. // Stage 2: Update memory state, then fail or leave loop. // // (In the future, we could consider adding another stage after // Stage 0 to run finalizers. However, before doing that make sure // that we could abort this constructor when we call // GC.WaitForPendingFinalizers, noting that this method uses a CER // so it can't be aborted, and we have a critical finalizer. It // would probably work, but do some thinking first.) for (int stage = 0; stage < 3; stage++) { CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree); // If we have enough room, then skip some stages. // Note that multiple threads can still lead to a race condition for our free chunk // of address space, which can't be easily solved. ulong reserved = MemoryFailPointReservedMemory; ulong segPlusReserved = segmentSize + reserved; bool overflow = segPlusReserved < segmentSize || segPlusReserved < reserved; bool needPageFile = availPageFile < (requestedSizeRounded + reserved + LowMemoryFudgeFactor) || overflow; bool needAddressSpace = totalAddressSpaceFree < segPlusReserved || overflow; // Ensure our cached amount of free address space is not stale. long now = Environment.TickCount; // Handle wraparound. if ((now > LastTimeCheckingAddressSpace + CheckThreshold || now < LastTimeCheckingAddressSpace) || LastKnownFreeAddressSpace < (long)segmentSize) { CheckForFreeAddressSpace(segmentSize, false); } bool needContiguousVASpace = (ulong)LastKnownFreeAddressSpace < segmentSize; if (!needPageFile && !needAddressSpace && !needContiguousVASpace) break; switch (stage) { case 0: // The GC will release empty segments to the OS. This will // relieve us from having to guess whether there's // enough memory in either GC heap, and whether // internal fragmentation will prevent those // allocations from succeeding. GC.Collect(); continue; case 1: // Do this step if and only if the page file is too small. if (!needPageFile) continue; // Attempt to grow the OS's page file. Note that we ignore // any allocation routines from the host intentionally. RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // This shouldn't overflow due to the if clauses above. UIntPtr numBytes = new UIntPtr(segmentSize); unsafe { void* pMemory = Interop.Kernel32.VirtualAlloc(null, numBytes, Interop.Kernel32.MEM_COMMIT, Interop.Kernel32.PAGE_READWRITE); if (pMemory != null) { bool r = Interop.Kernel32.VirtualFree(pMemory, UIntPtr.Zero, Interop.Kernel32.MEM_RELEASE); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } } continue; case 2: // The call to CheckForAvailableMemory above updated our // state. if (needPageFile || needAddressSpace) { InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint); #if DEBUG e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize, needPageFile, needAddressSpace, needContiguousVASpace, availPageFile >> 20, totalAddressSpaceFree >> 20, LastKnownFreeAddressSpace >> 20, reserved); #endif throw e; } if (needContiguousVASpace) { InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag); #if DEBUG e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize, needPageFile, needAddressSpace, needContiguousVASpace, availPageFile >> 20, totalAddressSpaceFree >> 20, LastKnownFreeAddressSpace >> 20, reserved); #endif throw e; } break; default: Debug.Assert(false, "Fell through switch statement!"); break; } } // Success - we have enough room the last time we checked. // Now update our shared state in a somewhat atomic fashion // and handle a simple race condition with other MemoryFailPoint instances. AddToLastKnownFreeAddressSpace(-((long)size)); if (LastKnownFreeAddressSpace < 0) CheckForFreeAddressSpace(segmentSize, true); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { AddMemoryFailPointReservation((long)size); _mustSubtractReservation = true; } } private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree) { bool r; Interop.Kernel32.MEMORYSTATUSEX memory = new Interop.Kernel32.MEMORYSTATUSEX(); r = Interop.Kernel32.GlobalMemoryStatusEx(ref memory); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); availPageFile = memory.availPageFile; totalAddressSpaceFree = memory.availVirtual; } // Based on the shouldThrow parameter, this will throw an exception, or // returns whether there is enough space. In all cases, we update // our last known free address space, hopefully avoiding needing to // probe again. private static unsafe bool CheckForFreeAddressSpace(ulong size, bool shouldThrow) { // Start walking the address space at 0. VirtualAlloc may wrap // around the address space. We don't need to find the exact // pages that VirtualAlloc would return - we just need to // know whether VirtualAlloc could succeed. ulong freeSpaceAfterGCHeap = MemFreeAfterAddress(null, size); // We may set these without taking a lock - I don't believe // this will hurt, as long as we never increment this number in // the Dispose method. If we do an extra bit of checking every // once in a while, but we avoid taking a lock, we may win. LastKnownFreeAddressSpace = (long)freeSpaceAfterGCHeap; LastTimeCheckingAddressSpace = Environment.TickCount; if (freeSpaceAfterGCHeap < size && shouldThrow) throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag); return freeSpaceAfterGCHeap >= size; } // Returns the amount of consecutive free memory available in a block // of pages. If we didn't have enough address space, we still return // a positive value < size, to help potentially avoid the overhead of // this check if we use a MemoryFailPoint with a smaller size next. private static unsafe ulong MemFreeAfterAddress(void* address, ulong size) { if (size >= s_topOfMemory) return 0; ulong largestFreeRegion = 0; Interop.Kernel32.MEMORY_BASIC_INFORMATION memInfo = new Interop.Kernel32.MEMORY_BASIC_INFORMATION(); UIntPtr sizeOfMemInfo = (UIntPtr)sizeof(Interop.Kernel32.MEMORY_BASIC_INFORMATION); while (((ulong)address) + size < s_topOfMemory) { UIntPtr r = Interop.Kernel32.VirtualQuery(address, ref memInfo, sizeOfMemInfo); if (r == UIntPtr.Zero) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); ulong regionSize = memInfo.RegionSize.ToUInt64(); if (memInfo.State == Interop.Kernel32.MEM_FREE) { if (regionSize >= size) return regionSize; else largestFreeRegion = Math.Max(largestFreeRegion, regionSize); } address = (void*)((ulong)address + regionSize); } return largestFreeRegion; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetMemorySettings(out ulong maxGCSegmentSize, out ulong topOfMemory); ~MemoryFailPoint() { Dispose(false); } // Applications must call Dispose, which conceptually "releases" the // memory that was "reserved" by the MemoryFailPoint. This affects a // global count of reserved memory in this version (helping to throttle // future MemoryFailPoints) in this version. We may in the // future create an allocation context and release it in the Dispose // method. While the finalizer will eventually free this block of // memory, apps will help their performance greatly by calling Dispose. public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { // This is just bookkeeping to ensure multiple threads can really // get enough memory, and this does not actually reserve memory // within the GC heap. if (_mustSubtractReservation) { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { AddMemoryFailPointReservation(-((long)_reservedMemory)); _mustSubtractReservation = false; } } /* // Prototype performance // Let's pretend that we returned at least some free memory to // the GC heap. We don't know this is true - the objects could // have a longer lifetime, and the memory could be elsewhere in the // GC heap. Additionally, we subtracted off the segment size, not // this size. That's ok - we don't mind if this slowly degrades // and requires us to refresh the value a little bit sooner. // But releasing the memory here should help us avoid probing for // free address space excessively with large workItem sizes. Interlocked.Add(ref LastKnownFreeAddressSpace, _reservedMemory); */ } // This is the total amount of memory currently "reserved" via // all MemoryFailPoints allocated within the process. // Stored as a long because we need to use Interlocked.Add. private static long s_memFailPointReservedMemory; internal static long AddMemoryFailPointReservation(long size) { // Size can legitimately be negative - see Dispose. return Interlocked.Add(ref s_memFailPointReservedMemory, (long)size); } internal static ulong MemoryFailPointReservedMemory { get { Debug.Assert(Volatile.Read(ref s_memFailPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!"); return (ulong)Volatile.Read(ref s_memFailPointReservedMemory); } } #if DEBUG internal sealed class MemoryFailPointState { private ulong _segmentSize; private int _allocationSizeInMB; private bool _needPageFile; private bool _needAddressSpace; private bool _needContiguousVASpace; private ulong _availPageFile; private ulong _totalFreeAddressSpace; private long _lastKnownFreeAddressSpace; private ulong _reservedMem; private String _stackTrace; // Where did we fail, for additional debugging. internal MemoryFailPointState(int allocationSizeInMB, ulong segmentSize, bool needPageFile, bool needAddressSpace, bool needContiguousVASpace, ulong availPageFile, ulong totalFreeAddressSpace, long lastKnownFreeAddressSpace, ulong reservedMem) { _allocationSizeInMB = allocationSizeInMB; _segmentSize = segmentSize; _needPageFile = needPageFile; _needAddressSpace = needAddressSpace; _needContiguousVASpace = needContiguousVASpace; _availPageFile = availPageFile; _totalFreeAddressSpace = totalFreeAddressSpace; _lastKnownFreeAddressSpace = lastKnownFreeAddressSpace; _reservedMem = reservedMem; try { _stackTrace = Environment.StackTrace; } catch (System.Security.SecurityException) { _stackTrace = "no permission"; } catch (OutOfMemoryException) { _stackTrace = "out of memory"; } } public override String ToString() { return String.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB", _segmentSize >> 20, _allocationSizeInMB, _needPageFile, _needAddressSpace, _needContiguousVASpace, _availPageFile >> 20, _totalFreeAddressSpace >> 20, _lastKnownFreeAddressSpace >> 20, _reservedMem); } } #endif } }
namespace AutoMapper.Internal { using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using TypeInfo = AutoMapper.TypeInfo; public class MappingExpression : MappingExpression<object, object>, IMappingExpression, IMemberConfigurationExpression { public MappingExpression(TypeMap typeMap, Func<Type, object> typeConverterCtor, IProfileExpression configurationContainer) : base(typeMap, typeConverterCtor, configurationContainer) { } public new IMappingExpression ReverseMap() { var mappingExpression = ConfigurationContainer.CreateMap(TypeMap.DestinationType, TypeMap.SourceType, MemberList.Source, TypeMap.Profile); return (IMappingExpression) ConfigureReverseMap((MappingExpression)mappingExpression); } public new IMappingExpression Substitute(Func<object, object> substituteFunc) { return (IMappingExpression)base.Substitute(substituteFunc); } public new IMappingExpression ConstructUsingServiceLocator() { return (IMappingExpression)base.ConstructUsingServiceLocator(); } public void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions) { base.ForAllMembers(o => memberOptions((IMemberConfigurationExpression)o)); } void IMappingExpression.ConvertUsing<TTypeConverter>() { ConvertUsing(typeof(TTypeConverter)); } public void ConvertUsing(Type typeConverterType) { var interfaceType = typeof(ITypeConverter<,>).MakeGenericType(TypeMap.SourceType, TypeMap.DestinationType); var convertMethodType = interfaceType.IsAssignableFrom(typeConverterType) ? interfaceType : typeConverterType; var converter = new DeferredInstantiatedConverter(convertMethodType, BuildCtor<object>(typeConverterType)); TypeMap.UseCustomMapper(converter.Convert); } public void As(Type typeOverride) { TypeMap.DestinationTypeOverride = typeOverride; } public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions) { return (IMappingExpression) base.ForMember(name, c => memberOptions((IMemberConfigurationExpression)c)); } IMappingExpression IMappingExpression.WithProfile(string profileName) { return (IMappingExpression) base.WithProfile(profileName); } public new IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions) { return (IMappingExpression) base.ForSourceMember(sourceMemberName, memberOptions); } public void MapFrom(string sourceMember) { var members = TypeMap.SourceType.GetMember(sourceMember); if(!members.Any()) throw new AutoMapperConfigurationException( $"Unable to find source member {sourceMember} on type {TypeMap.SourceType.FullName}"); if(members.Skip(1).Any()) throw new AutoMapperConfigurationException( $"Source member {sourceMember} is ambiguous on type {TypeMap.SourceType.FullName}"); var member = members.Single(); PropertyMap.SourceMember = member; PropertyMap.AssignCustomValueResolver(member.ToMemberGetter()); } public new IMappingExpression Include(Type otherSourceType, Type otherDestinationType) { return (IMappingExpression) base.Include(otherSourceType, otherDestinationType); } public new IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter() { return (IMappingExpression)base.IgnoreAllPropertiesWithAnInaccessibleSetter(); } public new IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter() { return (IMappingExpression)base.IgnoreAllSourcePropertiesWithAnInaccessibleSetter(); } public new IMappingExpression IncludeBase(Type sourceBase, Type destinationBase) { return (IMappingExpression)base.IncludeBase(sourceBase, destinationBase); } public void ProjectUsing(LambdaExpression projectionExpression) { TypeMap.UseCustomProjection(projectionExpression); } public new IMappingExpression BeforeMap(Action<object, object> beforeFunction) { return (IMappingExpression)base.BeforeMap(beforeFunction); } public new IMappingExpression BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<object, object> { return (IMappingExpression)base.BeforeMap<TMappingAction>(); } public new IMappingExpression AfterMap(Action<object, object> afterFunction) { return (IMappingExpression)base.AfterMap(afterFunction); } public new IMappingExpression AfterMap<TMappingAction>() where TMappingAction : IMappingAction<object, object> { return (IMappingExpression)base.AfterMap<TMappingAction>(); } public new IMappingExpression ConstructUsing(Func<object, object> ctor) { return (IMappingExpression)base.ConstructUsing(ctor); } public new IMappingExpression ConstructUsing(Func<ResolutionContext, object> ctor) { return (IMappingExpression)base.ConstructUsing(ctor); } public IMappingExpression ConstructProjectionUsing(LambdaExpression ctor) { var func = ctor.Compile(); TypeMap.ConstructExpression = ctor; return ConstructUsing(ctxt => func.DynamicInvoke(ctxt.SourceValue)); } public new IMappingExpression MaxDepth(int depth) { return (IMappingExpression)base.MaxDepth(depth); } public new IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions) { return (IMappingExpression)base.ForCtorParam(ctorParamName, paramOptions); } } class SourceMappingExpression : ISourceMemberConfigurationExpression { private readonly SourceMemberConfig _sourcePropertyConfig; public SourceMappingExpression(TypeMap typeMap, MemberInfo sourceMember) { _sourcePropertyConfig = typeMap.FindOrCreateSourceMemberConfigFor(sourceMember); } public void Ignore() { _sourcePropertyConfig.Ignore(); } } public class MappingExpression<TSource, TDestination> : IMappingExpression<TSource, TDestination>, IMemberConfigurationExpression<TSource> { private readonly Func<Type, object> _serviceCtor; private readonly IProfileExpression _configurationContainer; private PropertyMap _propertyMap; public MappingExpression(TypeMap typeMap, Func<Type, object> serviceCtor, IProfileExpression configurationContainer) { TypeMap = typeMap; _serviceCtor = serviceCtor; _configurationContainer = configurationContainer; } public TypeMap TypeMap { get; } public PropertyMap PropertyMap =>_propertyMap; public IProfileExpression ConfigurationContainer => _configurationContainer; public IMappingExpression<TSource, TDestination> ForMember(Expression<Func<TDestination, object>> destinationMember, Action<IMemberConfigurationExpression<TSource>> memberOptions) { var memberInfo = ReflectionHelper.FindProperty(destinationMember); IMemberAccessor destProperty = memberInfo.ToMemberAccessor(); ForDestinationMember(destProperty, memberOptions); return this; } public IMappingExpression<TSource, TDestination> ForMember(string name, Action<IMemberConfigurationExpression<TSource>> memberOptions) { IMemberAccessor destMember = null; var propertyInfo = TypeMap.DestinationType.GetProperty(name); if (propertyInfo != null) { destMember = new PropertyAccessor(propertyInfo); } if (destMember == null) { var fieldInfo = TypeMap.DestinationType.GetField(name); if(fieldInfo == null) { throw new ArgumentOutOfRangeException("name", "Cannot find a field or property named " + name); } destMember = new FieldAccessor(fieldInfo); } ForDestinationMember(destMember, memberOptions); return this; } public void ForAllMembers(Action<IMemberConfigurationExpression<TSource>> memberOptions) { var typeInfo = new TypeInfo(TypeMap.DestinationType, _configurationContainer.ShouldMapProperty, _configurationContainer.ShouldMapField); typeInfo.PublicWriteAccessors.Each(acc => ForDestinationMember(acc.ToMemberAccessor(), memberOptions)); } public IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter() { var properties = typeof(TDestination).GetDeclaredProperties().Where(HasAnInaccessibleSetter); foreach (var property in properties) ForMember(property.Name, opt => opt.Ignore()); return this; } public IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter() { var properties = typeof(TSource).GetDeclaredProperties().Where(HasAnInaccessibleSetter); foreach (var property in properties) ForSourceMember(property.Name, opt => opt.Ignore()); return this; } private bool HasAnInaccessibleSetter(PropertyInfo property) { var setMethod = property.GetSetMethod(true); return setMethod == null || setMethod.IsPrivate || setMethod.IsFamily; } public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>() where TOtherSource : TSource where TOtherDestination : TDestination { return Include(typeof(TOtherSource), typeof(TOtherDestination)); } public IMappingExpression<TSource, TDestination> Include(Type otherSourceType, Type otherDestinationType) { TypeMap.IncludeDerivedTypes(otherSourceType, otherDestinationType); return this; } public IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>() { return IncludeBase(typeof(TSourceBase), typeof(TDestinationBase)); } public IMappingExpression<TSource, TDestination> IncludeBase(Type sourceBase, Type destinationBase) { TypeMap baseTypeMap = _configurationContainer.CreateMap(sourceBase, destinationBase).TypeMap; baseTypeMap.IncludeDerivedTypes(typeof(TSource), typeof(TDestination)); TypeMap.ApplyInheritedMap(baseTypeMap); return this; } public IMappingExpression<TSource, TDestination> WithProfile(string profileName) { TypeMap.Profile = profileName; return this; } public void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression) { TypeMap.UseCustomProjection(projectionExpression); ConvertUsing(projectionExpression.Compile()); } public void NullSubstitute(object nullSubstitute) { _propertyMap.SetNullSubstitute(nullSubstitute); } public IResolverConfigurationExpression<TSource, TValueResolver> ResolveUsing<TValueResolver>() where TValueResolver : IValueResolver { var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>(typeof(TValueResolver))); ResolveUsing(resolver); return new ResolutionExpression<TSource, TValueResolver>(TypeMap.SourceType, _propertyMap); } public IResolverConfigurationExpression<TSource> ResolveUsing(Type valueResolverType) { var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>(valueResolverType)); ResolveUsing(resolver); return new ResolutionExpression<TSource>(TypeMap.SourceType, _propertyMap); } public IResolutionExpression<TSource> ResolveUsing(IValueResolver valueResolver) { _propertyMap.AssignCustomValueResolver(valueResolver); return new ResolutionExpression<TSource>(TypeMap.SourceType, _propertyMap); } public void ResolveUsing(Func<TSource, object> resolver) { _propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(r => resolver((TSource)r.Value))); } public void ResolveUsing(Func<ResolutionResult, object> resolver) { _propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(resolver)); } public void ResolveUsing(Func<ResolutionResult, TSource, object> resolver) { _propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(r => resolver(r, (TSource)r.Value))); } public void MapFrom<TMember>(Expression<Func<TSource, TMember>> sourceMember) { _propertyMap.SetCustomValueResolverExpression(sourceMember); } public void MapFrom<TMember>(string property) { var par = Expression.Parameter(typeof (TSource)); var prop = Expression.Property(par, property); var lambda = Expression.Lambda<Func<TSource, TMember>>(prop, par); _propertyMap.SetCustomValueResolverExpression(lambda); } public void UseValue<TValue>(TValue value) { MapFrom(src => value); } public void UseValue(object value) { _propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(src => value)); } public void Condition(Func<TSource, bool> condition) { Condition(context => condition((TSource)context.Parent.SourceValue)); } public void Condition(Func<ResolutionContext, bool> condition) { _propertyMap.ApplyCondition(condition); } public void PreCondition(Func<TSource, bool> condition) { PreCondition(context => condition((TSource)context.Parent.SourceValue)); } public void PreCondition(Func<ResolutionContext, bool> condition) { _propertyMap.ApplyPreCondition(condition); } public void ExplicitExpansion() { _propertyMap.ExplicitExpansion = true; } public IMappingExpression<TSource, TDestination> MaxDepth(int depth) { TypeMap.MaxDepth = depth; return this; } public IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator() { TypeMap.ConstructDestinationUsingServiceLocator = true; return this; } public IMappingExpression<TDestination, TSource> ReverseMap() { var mappingExpression = _configurationContainer.CreateMap<TDestination, TSource>(TypeMap.Profile, MemberList.Source); return ConfigureReverseMap(mappingExpression); } protected IMappingExpression<TDestination, TSource> ConfigureReverseMap(IMappingExpression<TDestination, TSource> mappingExpression) { foreach(var destProperty in TypeMap.GetPropertyMaps().Where(pm => pm.IsIgnored())) { mappingExpression.ForSourceMember(destProperty.DestinationProperty.Name, opt => opt.Ignore()); } foreach(var includedDerivedType in TypeMap.IncludedDerivedTypes) { mappingExpression.Include(includedDerivedType.DestinationType, includedDerivedType.SourceType); } return mappingExpression; } public IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember, Action<ISourceMemberConfigurationExpression> memberOptions) { var memberInfo = ReflectionHelper.FindProperty(sourceMember); var srcConfig = new SourceMappingExpression(TypeMap, memberInfo); memberOptions(srcConfig); return this; } public IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions) { var memberInfo = TypeMap.SourceType.GetMember(sourceMemberName).First(); var srcConfig = new SourceMappingExpression(TypeMap, memberInfo); memberOptions(srcConfig); return this; } public IMappingExpression<TSource, TDestination> Substitute(Func<TSource, object> substituteFunc) { TypeMap.Substitution = src => substituteFunc((TSource) src); return this; } public void Ignore() { _propertyMap.Ignore(); } public void UseDestinationValue() { _propertyMap.UseDestinationValue = true; } public void DoNotUseDestinationValue() { _propertyMap.UseDestinationValue = false; } public void SetMappingOrder(int mappingOrder) { _propertyMap.SetMappingOrder(mappingOrder); } public void ConvertUsing(Func<TSource, TDestination> mappingFunction) { TypeMap.UseCustomMapper(source => mappingFunction((TSource)source.SourceValue)); } public void ConvertUsing(Func<ResolutionContext, TDestination> mappingFunction) { TypeMap.UseCustomMapper(context => mappingFunction(context)); } public void ConvertUsing(Func<ResolutionContext, TSource, TDestination> mappingFunction) { TypeMap.UseCustomMapper(source => mappingFunction(source, (TSource)source.SourceValue)); } public void ConvertUsing(ITypeConverter<TSource, TDestination> converter) { ConvertUsing(converter.Convert); } public void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination> { var converter = new DeferredInstantiatedConverter<TSource, TDestination>(BuildCtor<ITypeConverter<TSource, TDestination>>(typeof(TTypeConverter))); ConvertUsing(converter.Convert); } public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction) { TypeMap.AddBeforeMapAction((src, dest) => beforeFunction((TSource)src, (TDestination)dest)); return this; } public IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination> { Action<TSource, TDestination> beforeFunction = (src, dest) => ((TMappingAction)_serviceCtor(typeof(TMappingAction))).Process(src, dest); return BeforeMap(beforeFunction); } public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction) { TypeMap.AddAfterMapAction((src, dest) => afterFunction((TSource)src, (TDestination)dest)); return this; } public IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination> { Action<TSource, TDestination> afterFunction = (src, dest) => ((TMappingAction)_serviceCtor(typeof(TMappingAction))).Process(src, dest); return AfterMap(afterFunction); } public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor) { return ConstructUsing(ctxt => ctor((TSource)ctxt.SourceValue)); } public IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor) { TypeMap.DestinationCtor = ctxt => ctor(ctxt); return this; } public IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor) { var func = ctor.Compile(); TypeMap.ConstructExpression = ctor; return ConstructUsing(ctxt => func((TSource)ctxt.SourceValue)); } private void ForDestinationMember(IMemberAccessor destinationProperty, Action<IMemberConfigurationExpression<TSource>> memberOptions) { _propertyMap = TypeMap.FindOrCreatePropertyMapFor(destinationProperty); memberOptions(this); } public void As<T>() { TypeMap.DestinationTypeOverride = typeof(T); } public IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions) { var param = TypeMap.ConstructorMap.CtorParams.Single(p => p.Parameter.Name == ctorParamName); var ctorParamExpression = new CtorParamConfigurationExpression<TSource>(param); param.CanResolve = true; paramOptions(ctorParamExpression); return this; } protected Func<ResolutionContext, TServiceType> BuildCtor<TServiceType>(Type type) { return context => { if(type.IsGenericTypeDefinition()) { type = type.MakeGenericType(context.SourceType.GetGenericArguments()); } var obj = context.Options.ServiceCtor?.Invoke(type); if(obj != null) return (TServiceType)obj; return (TServiceType)_serviceCtor(type); }; } } }
// <copyright file="HypergeometricTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Linq; using MathNet.Numerics.Distributions; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.DistributionTests.Discrete { /// <summary> /// Hypergeometric tests. /// </summary> [TestFixture, Category("Distributions")] public class HypergeometricTests { /// <summary> /// Can create Hypergeometric. /// </summary> /// <param name="population">Population size.</param> /// <param name="success">M parameter.</param> /// <param name="draws">N parameter.</param> [TestCase(0, 0, 0)] [TestCase(1, 1, 1)] [TestCase(2, 1, 1)] [TestCase(2, 2, 2)] [TestCase(10, 1, 1)] [TestCase(10, 5, 3)] public void CanCreateHypergeometric(int population, int success, int draws) { var d = new Hypergeometric(population, success, draws); Assert.AreEqual(population, d.Population); Assert.AreEqual(success, d.Success); Assert.AreEqual(draws, d.Draws); } /// <summary> /// Hypergeometric create fails with bad parameters. /// </summary> /// <param name="population">Population size.</param> /// <param name="success">M parameter.</param> /// <param name="n">N parameter.</param> [TestCase(2, 3, 2)] [TestCase(10, 5, 20)] [TestCase(-2, 1, 1)] [TestCase(0, 1, 1)] public void HypergeometricCreateFailsWithBadParameters(int population, int success, int n) { Assert.That(() => new Hypergeometric(population, success, n), Throws.ArgumentException); } /// <summary> /// Validate ToString. /// </summary> [Test] public void ValidateToString() { var d = new Hypergeometric(10, 1, 1); Assert.AreEqual("Hypergeometric(N = 10, M = 1, n = 1)", d.ToString()); } /// <summary> /// Validate entropy throws <c>NotSupportedException</c>. /// </summary> [Test] public void ValidateEntropyThrowsNotSupportedException() { var d = new Hypergeometric(10, 1, 1); Assert.Throws<NotSupportedException>(() => { var e = d.Entropy; }); } /// <summary> /// Validate skewness. /// </summary> /// <param name="population">Population size.</param> /// <param name="success">M parameter.</param> /// <param name="draws">N parameter.</param> [TestCase(0, 0, 0)] [TestCase(1, 1, 1)] [TestCase(2, 1, 1)] [TestCase(2, 2, 2)] [TestCase(10, 1, 1)] [TestCase(10, 5, 3)] public void ValidateSkewness(int population, int success, int draws) { var d = new Hypergeometric(population, success, draws); Assert.AreEqual((Math.Sqrt(population - 1.0)*(population - (2*draws))*(population - (2*success)))/(Math.Sqrt(draws*success*(population - success)*(population - draws))*(population - 2.0)), d.Skewness); } /// <summary> /// Validate mode. /// </summary> /// <param name="population">Population size.</param> /// <param name="success">M parameter.</param> /// <param name="draws">N parameter.</param> [TestCase(0, 0, 0)] [TestCase(1, 1, 1)] [TestCase(2, 1, 1)] [TestCase(2, 2, 2)] [TestCase(10, 1, 1)] [TestCase(10, 5, 3)] public void ValidateMode(int population, int success, int draws) { var d = new Hypergeometric(population, success, draws); Assert.AreEqual((draws + 1)*(success + 1)/(population + 2), d.Mode); } /// <summary> /// Validate median throws <c>NotSupportedException</c>. /// </summary> [Test] public void ValidateMedianThrowsNotSupportedException() { var d = new Hypergeometric(10, 1, 1); Assert.Throws<NotSupportedException>(() => { var m = d.Median; }); } /// <summary> /// Validate minimum. /// </summary> /// <param name="population">Population size.</param> /// <param name="success">M parameter.</param> /// <param name="draws">N parameter.</param> [TestCase(0, 0, 0)] [TestCase(1, 1, 1)] [TestCase(2, 1, 1)] [TestCase(2, 2, 2)] [TestCase(10, 1, 1)] [TestCase(10, 5, 3)] public void ValidateMinimum(int population, int success, int draws) { var d = new Hypergeometric(population, success, draws); Assert.AreEqual(Math.Max(0, draws + success - population), d.Minimum); } /// <summary> /// Validate maximum. /// </summary> /// <param name="population">Population size.</param> /// <param name="success">M parameter.</param> /// <param name="draws">N parameter.</param> [TestCase(0, 0, 0)] [TestCase(1, 1, 1)] [TestCase(2, 1, 1)] [TestCase(2, 2, 2)] [TestCase(10, 1, 1)] [TestCase(10, 5, 3)] public void ValidateMaximum(int population, int success, int draws) { var d = new Hypergeometric(population, success, draws); Assert.AreEqual(Math.Min(success, draws), d.Maximum); } /// <summary> /// Validate probability. /// </summary> /// <param name="population">Population size.</param> /// <param name="success">M parameter.</param> /// <param name="draws">N parameter.</param> /// <param name="x">Input X value.</param> [TestCase(0, 0, 0, 0)] [TestCase(1, 1, 1, 1)] [TestCase(2, 1, 1, 0)] [TestCase(2, 1, 1, 1)] [TestCase(2, 2, 2, 2)] [TestCase(10, 1, 1, 0)] [TestCase(10, 1, 1, 1)] [TestCase(10, 5, 3, 1)] [TestCase(10, 5, 3, 3)] public void ValidateProbability(int population, int success, int draws, int x) { var d = new Hypergeometric(population, success, draws); Assert.That(d.Probability(x), Is.EqualTo(SpecialFunctions.Binomial(success, x)*SpecialFunctions.Binomial(population - success, draws - x)/SpecialFunctions.Binomial(population, draws))); } /// <summary> /// Validate probability log. /// </summary> /// <param name="population">Population size.</param> /// <param name="success">M parameter.</param> /// <param name="draws">N parameter.</param> /// <param name="x">Input X value.</param> [TestCase(0, 0, 0, 0)] [TestCase(1, 1, 1, 1)] [TestCase(2, 1, 1, 0)] [TestCase(2, 1, 1, 1)] [TestCase(2, 2, 2, 2)] [TestCase(10, 1, 1, 0)] [TestCase(10, 1, 1, 1)] [TestCase(10, 5, 3, 1)] [TestCase(10, 5, 3, 3)] public void ValidateProbabilityLn(int population, int success, int draws, int x) { var d = new Hypergeometric(population, success, draws); Assert.That(d.ProbabilityLn(x), Is.EqualTo(Math.Log(d.Probability(x))).Within(1e-14)); } /// <summary> /// Can sample. /// </summary> [Test] public void CanSample() { var d = new Hypergeometric(10, 1, 1); d.Sample(); } /// <summary> /// Can sample sequence /// </summary> [Test] public void CanSampleSequence() { var d = new Hypergeometric(10, 1, 1); var ied = d.Samples(); GC.KeepAlive(ied.Take(5).ToArray()); } /// <summary> /// Validate cumulative distribution. /// </summary> /// <param name="population">Population size.</param> /// <param name="success">M parameter.</param> /// <param name="draws">N parameter.</param> /// <param name="x">Input X value.</param> /// <param name="cdf">Expected value.</param> [TestCase(0, 0, 0, 0.5, 1.0)] [TestCase(1, 1, 1, 1.1, 1.0)] [TestCase(2, 1, 1, 0.3, 0.5)] [TestCase(2, 1, 1, 1.2, 1.0)] [TestCase(2, 2, 2, 2.4, 1.0)] [TestCase(10, 1, 1, 0.3, 0.9)] [TestCase(10, 1, 1, 1.2, 1.0)] [TestCase(10, 5, 3, 1.1, 0.5)] [TestCase(10, 5, 3, 2.0, 11.0/12.0)] [TestCase(10, 5, 3, 3.0, 1.0)] [TestCase(10000, 2, 9800, 0.0, 199.0/499950.0)] [TestCase(10000, 2, 9800, 0.5, 199.0/499950.0)] [TestCase(10000, 2, 9800, 1.5, 19799.0/499950.0)] public void ValidateCumulativeDistribution(int population, int success, int draws, double x, double cdf) { var d = new Hypergeometric(population, success, draws); AssertHelpers.AlmostEqualRelative(cdf, d.CumulativeDistribution(x), 9); } [Test] public void CumulativeDistributionMustNotOverflow_CodePlexIssue5729() { var d = new Hypergeometric(10000, 2, 9800); Assert.That(d.CumulativeDistribution(0.0), Is.Not.NaN); Assert.That(d.CumulativeDistribution(0.1), Is.Not.NaN); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Abp.Application.Features; using Abp.Application.Navigation; using Abp.Authorization; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Localization; using Abp.Runtime.Session; using Abp.Timing; using Abp.Timing.Timezone; using Abp.Web.Models.AbpUserConfiguration; using Abp.Web.Security.AntiForgery; using System.Linq; using Abp.Dependency; using Abp.Extensions; namespace Abp.Web.Configuration { public class AbpUserConfigurationBuilder : ITransientDependency { private readonly IMultiTenancyConfig _multiTenancyConfig; private readonly ILanguageManager _languageManager; private readonly ILocalizationManager _localizationManager; private readonly IFeatureManager _featureManager; private readonly IFeatureChecker _featureChecker; private readonly IPermissionManager _permissionManager; private readonly IUserNavigationManager _userNavigationManager; private readonly ISettingDefinitionManager _settingDefinitionManager; private readonly ISettingManager _settingManager; private readonly IAbpAntiForgeryConfiguration _abpAntiForgeryConfiguration; private readonly IAbpSession _abpSession; private readonly IPermissionChecker _permissionChecker; public AbpUserConfigurationBuilder( IMultiTenancyConfig multiTenancyConfig, ILanguageManager languageManager, ILocalizationManager localizationManager, IFeatureManager featureManager, IFeatureChecker featureChecker, IPermissionManager permissionManager, IUserNavigationManager userNavigationManager, ISettingDefinitionManager settingDefinitionManager, ISettingManager settingManager, IAbpAntiForgeryConfiguration abpAntiForgeryConfiguration, IAbpSession abpSession, IPermissionChecker permissionChecker) { _multiTenancyConfig = multiTenancyConfig; _languageManager = languageManager; _localizationManager = localizationManager; _featureManager = featureManager; _featureChecker = featureChecker; _permissionManager = permissionManager; _userNavigationManager = userNavigationManager; _settingDefinitionManager = settingDefinitionManager; _settingManager = settingManager; _abpAntiForgeryConfiguration = abpAntiForgeryConfiguration; _abpSession = abpSession; _permissionChecker = permissionChecker; } public async Task<AbpUserConfigurationDto> GetAll() { return new AbpUserConfigurationDto { MultiTenancy = GetUserMultiTenancyConfig(), Session = GetUserSessionConfig(), Localization = GetUserLocalizationConfig(), Features = await GetUserFeaturesConfig(), Auth = await GetUserAuthConfig(), Nav = await GetUserNavConfig(), Setting = await GetUserSettingConfig(), Clock = GetUserClockConfig(), Timing = await GetUserTimingConfig(), Security = GetUserSecurityConfig() }; } private AbpMultiTenancyConfigDto GetUserMultiTenancyConfig() { return new AbpMultiTenancyConfigDto { IsEnabled = _multiTenancyConfig.IsEnabled }; } private AbpUserSessionConfigDto GetUserSessionConfig() { return new AbpUserSessionConfigDto { UserId = _abpSession.UserId, TenantId = _abpSession.TenantId, ImpersonatorUserId = _abpSession.ImpersonatorUserId, ImpersonatorTenantId = _abpSession.ImpersonatorTenantId, MultiTenancySide = _abpSession.MultiTenancySide }; } private AbpUserLocalizationConfigDto GetUserLocalizationConfig() { var currentCulture = Thread.CurrentThread.CurrentUICulture; var languages = _languageManager.GetLanguages(); var config = new AbpUserLocalizationConfigDto { CurrentCulture = new AbpUserCurrentCultureConfigDto { Name = currentCulture.Name, DisplayName = currentCulture.DisplayName }, Languages = languages.ToList() }; if (languages.Count > 0) { config.CurrentLanguage = _languageManager.CurrentLanguage; } var sources = _localizationManager.GetAllSources().OrderBy(s => s.Name).ToArray(); config.Sources = sources.Select(s => new AbpLocalizationSourceDto { Name = s.Name, Type = s.GetType().Name }).ToList(); config.Values = new Dictionary<string, Dictionary<string, string>>(); foreach (var source in sources) { var stringValues = source.GetAllStrings(currentCulture).OrderBy(s => s.Name).ToList(); var stringDictionary = stringValues .ToDictionary(_ => _.Name, _ => _.Value); config.Values.Add(source.Name, stringDictionary); } return config; } private async Task<AbpUserFeatureConfigDto> GetUserFeaturesConfig() { var config = new AbpUserFeatureConfigDto() { AllFeatures = new Dictionary<string, AbpStringValueDto>() }; var allFeatures = _featureManager.GetAll().ToList(); if (_abpSession.TenantId.HasValue) { var currentTenantId = _abpSession.GetTenantId(); foreach (var feature in allFeatures) { var value = await _featureChecker.GetValueAsync(currentTenantId, feature.Name); config.AllFeatures.Add(feature.Name, new AbpStringValueDto { Value = value }); } } else { foreach (var feature in allFeatures) { config.AllFeatures.Add(feature.Name, new AbpStringValueDto { Value = feature.DefaultValue }); } } return config; } private async Task<AbpUserAuthConfigDto> GetUserAuthConfig() { var config = new AbpUserAuthConfigDto(); var allPermissionNames = _permissionManager.GetAllPermissions(false).Select(p => p.Name).ToList(); var grantedPermissionNames = new List<string>(); if (_abpSession.UserId.HasValue) { foreach (var permissionName in allPermissionNames) { if (await _permissionChecker.IsGrantedAsync(permissionName)) { grantedPermissionNames.Add(permissionName); } } } config.AllPermissions = allPermissionNames.ToDictionary(permissionName => permissionName, permissionName => "true"); config.GrantedPermissions = grantedPermissionNames.ToDictionary(permissionName => permissionName, permissionName => "true"); return config; } private async Task<AbpUserNavConfigDto> GetUserNavConfig() { var userMenus = await _userNavigationManager.GetMenusAsync(_abpSession.ToUserIdentifier()); return new AbpUserNavConfigDto { Menus = userMenus.ToDictionary(userMenu => userMenu.Name, userMenu => userMenu) }; } private async Task<AbpUserSettingConfigDto> GetUserSettingConfig() { var config = new AbpUserSettingConfigDto { Values = new Dictionary<string, string>() }; var settingDefinitions = _settingDefinitionManager .GetAllSettingDefinitions() .Where(sd => sd.IsVisibleToClients); foreach (var settingDefinition in settingDefinitions) { var settingValue = await _settingManager.GetSettingValueAsync(settingDefinition.Name); config.Values.Add(settingDefinition.Name, settingValue); } return config; } private AbpUserClockConfigDto GetUserClockConfig() { return new AbpUserClockConfigDto { Provider = Clock.Provider.GetType().Name.ToCamelCase() }; } private async Task<AbpUserTimingConfigDto> GetUserTimingConfig() { var timezoneId = await _settingManager.GetSettingValueAsync(TimingSettingNames.TimeZone); var timezone = TimeZoneInfo.FindSystemTimeZoneById(timezoneId); return new AbpUserTimingConfigDto { TimeZoneInfo = new AbpUserTimeZoneConfigDto { Windows = new AbpUserWindowsTimeZoneConfigDto { TimeZoneId = timezoneId, BaseUtcOffsetInMilliseconds = timezone.BaseUtcOffset.TotalMilliseconds, CurrentUtcOffsetInMilliseconds = timezone.GetUtcOffset(Clock.Now).TotalMilliseconds, IsDaylightSavingTimeNow = timezone.IsDaylightSavingTime(Clock.Now) }, Iana = new AbpUserIanaTimeZoneConfigDto { TimeZoneId = TimezoneHelper.WindowsToIana(timezoneId) } } }; } private AbpUserSecurityConfigDto GetUserSecurityConfig() { return new AbpUserSecurityConfigDto() { AntiForgery = new AbpUserAntiForgeryConfigDto { TokenCookieName = _abpAntiForgeryConfiguration.TokenCookieName, TokenHeaderName = _abpAntiForgeryConfiguration.TokenHeaderName } }; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Security; namespace System.IO.MemoryMappedFiles { public partial class MemoryMappedFile : IDisposable { private readonly SafeMemoryMappedFileHandle _handle; private readonly bool _leaveOpen; private readonly FileStream _fileStream; internal const int DefaultSize = 0; // Private constructors to be used by the factory methods. [SecurityCritical] private MemoryMappedFile(SafeMemoryMappedFileHandle handle) { Debug.Assert(handle != null && !handle.IsClosed && !handle.IsInvalid, "handle is null, closed, or invalid"); _handle = handle; _leaveOpen = true; // No FileStream to dispose of in this case. } [SecurityCritical] private MemoryMappedFile(SafeMemoryMappedFileHandle handle, FileStream fileStream, bool leaveOpen) { Debug.Assert(handle != null && !handle.IsClosed && !handle.IsInvalid, "handle is null, closed, or invalid"); Debug.Assert(fileStream != null, "fileStream is null"); _handle = handle; _fileStream = fileStream; _leaveOpen = leaveOpen; } // Factory Method Group #1: Opens an existing named memory mapped file. The native OpenFileMapping call // will check the desiredAccessRights against the ACL on the memory mapped file. Note that a memory // mapped file created without an ACL will use a default ACL taken from the primary or impersonation token // of the creator. On my machine, I always get ReadWrite access to it so I never have to use anything but // the first override of this method. Note: having ReadWrite access to the object does not mean that we // have ReadWrite access to the pages mapping the file. The OS will check against the access on the pages // when a view is created. public static MemoryMappedFile OpenExisting(string mapName) { return OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.None); } public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights) { return OpenExisting(mapName, desiredAccessRights, HandleInheritability.None); } [SecurityCritical] public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights, HandleInheritability inheritability) { if (mapName == null) { throw new ArgumentNullException("mapName", SR.ArgumentNull_MapName); } if (mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } if (((int)desiredAccessRights & ~((int)(MemoryMappedFileRights.FullControl | MemoryMappedFileRights.AccessSystemSecurity))) != 0) { throw new ArgumentOutOfRangeException("desiredAccessRights"); } SafeMemoryMappedFileHandle handle = OpenCore(mapName, inheritability, desiredAccessRights, false); return new MemoryMappedFile(handle); } // Factory Method Group #2: Creates a new memory mapped file where the content is taken from an existing // file on disk. This file must be opened by a FileStream before given to us. Specifying DefaultSize to // the capacity will make the capacity of the memory mapped file match the size of the file. Specifying // a value larger than the size of the file will enlarge the new file to this size. Note that in such a // case, the capacity (and there for the size of the file) will be rounded up to a multiple of the system // page size. One can use FileStream.SetLength to bring the length back to a desirable size. By default, // the MemoryMappedFile will close the FileStream object when it is disposed. This behavior can be // changed by the leaveOpen boolean argument. public static MemoryMappedFile CreateFromFile(string path) { return CreateFromFile(path, FileMode.Open, null, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(string path, FileMode mode) { return CreateFromFile(path, mode, null, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string mapName) { return CreateFromFile(path, mode, mapName, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string mapName, long capacity) { return CreateFromFile(path, mode, mapName, capacity, MemoryMappedFileAccess.ReadWrite); } [SecurityCritical] public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access) { if (path == null) { throw new ArgumentNullException("path"); } if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (mode == FileMode.Append) { throw new ArgumentException(SR.Argument_NewMMFAppendModeNotAllowed, "mode"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } bool existed = File.Exists(path); FileStream fileStream = new FileStream(path, mode, GetFileAccess(access), FileShare.None, 0x1000, FileOptions.None); if (capacity == 0 && fileStream.Length == 0) { CleanupFile(fileStream, existed, path); throw new ArgumentException(SR.Argument_EmptyFile); } if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length) { CleanupFile(fileStream, existed, path); throw new ArgumentException(SR.Argument_ReadAccessWithLargeCapacity); } if (capacity == DefaultSize) { capacity = fileStream.Length; } // one can always create a small view if they do not want to map an entire file if (fileStream.Length > capacity) { CleanupFile(fileStream, existed, path); throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityGEFileSizeRequired); } SafeMemoryMappedFileHandle handle = null; try { handle = CreateCore(fileStream, mapName, HandleInheritability.None, access, MemoryMappedFileOptions.None, capacity); } catch { CleanupFile(fileStream, existed, path); throw; } Debug.Assert(handle != null && !handle.IsInvalid); return new MemoryMappedFile(handle, fileStream, false); } [SecurityCritical] public static MemoryMappedFile CreateFromFile(FileStream fileStream, string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen) { if (fileStream == null) { throw new ArgumentNullException("fileStream", SR.ArgumentNull_FileStream); } if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired); } if (capacity == 0 && fileStream.Length == 0) { throw new ArgumentException(SR.Argument_EmptyFile); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length) { throw new ArgumentException(SR.Argument_ReadAccessWithLargeCapacity); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } // flush any bytes written to the FileStream buffer so that we can see them in our MemoryMappedFile fileStream.Flush(); if (capacity == DefaultSize) { capacity = fileStream.Length; } // one can always create a small view if they do not want to map an entire file if (fileStream.Length > capacity) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityGEFileSizeRequired); } SafeMemoryMappedFileHandle handle = CreateCore(fileStream, mapName, inheritability, access, MemoryMappedFileOptions.None, capacity); return new MemoryMappedFile(handle, fileStream, leaveOpen); } // Factory Method Group #3: Creates a new empty memory mapped file. Such memory mapped files are ideal // for IPC, when mapName != null. public static MemoryMappedFile CreateNew(string mapName, long capacity) { return CreateNew(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); } public static MemoryMappedFile CreateNew(string mapName, long capacity, MemoryMappedFileAccess access) { return CreateNew(mapName, capacity, access, MemoryMappedFileOptions.None, HandleInheritability.None); } [SecurityCritical] public static MemoryMappedFile CreateNew(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedPositiveNumber); } if (IntPtr.Size == 4 && capacity > uint.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle = CreateCore(null, mapName, inheritability, access, options, capacity); return new MemoryMappedFile(handle); } // Factory Method Group #4: Creates a new empty memory mapped file or opens an existing // memory mapped file if one exists with the same name. The capacity, options, and // memoryMappedFileSecurity arguments will be ignored in the case of the later. // This is ideal for P2P style IPC. public static MemoryMappedFile CreateOrOpen(string mapName, long capacity) { return CreateOrOpen(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); } public static MemoryMappedFile CreateOrOpen(string mapName, long capacity, MemoryMappedFileAccess access) { return CreateOrOpen(mapName, capacity, access, MemoryMappedFileOptions.None, HandleInheritability.None); } [SecurityCritical] public static MemoryMappedFile CreateOrOpen(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName == null) { throw new ArgumentNullException("mapName", SR.ArgumentNull_MapName); } if (mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedPositiveNumber); } if (IntPtr.Size == 4 && capacity > uint.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle; // special case for write access; create will never succeed if (access == MemoryMappedFileAccess.Write) { handle = OpenCore(mapName, inheritability, access, true); } else { handle = CreateOrOpenCore(mapName, inheritability, access, options, capacity); } return new MemoryMappedFile(handle); } // Creates a new view in the form of a stream. public MemoryMappedViewStream CreateViewStream() { return CreateViewStream(0, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public MemoryMappedViewStream CreateViewStream(long offset, long size) { return CreateViewStream(offset, size, MemoryMappedFileAccess.ReadWrite); } [SecurityCritical] public MemoryMappedViewStream CreateViewStream(long offset, long size, MemoryMappedFileAccess access) { if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (size < 0) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (IntPtr.Size == 4 && size > uint.MaxValue) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size); return new MemoryMappedViewStream(view); } // Creates a new view in the form of an accessor. Accessors are for random access. public MemoryMappedViewAccessor CreateViewAccessor() { return CreateViewAccessor(0, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public MemoryMappedViewAccessor CreateViewAccessor(long offset, long size) { return CreateViewAccessor(offset, size, MemoryMappedFileAccess.ReadWrite); } [SecurityCritical] public MemoryMappedViewAccessor CreateViewAccessor(long offset, long size, MemoryMappedFileAccess access) { if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (size < 0) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (IntPtr.Size == 4 && size > uint.MaxValue) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size); return new MemoryMappedViewAccessor(view); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [SecuritySafeCritical] protected virtual void Dispose(bool disposing) { try { if (_handle != null && !_handle.IsClosed) { _handle.Dispose(); } } finally { if (_fileStream != null && _leaveOpen == false) { _fileStream.Dispose(); } } } public SafeMemoryMappedFileHandle SafeMemoryMappedFileHandle { [SecurityCritical] get { return _handle; } } // This converts a MemoryMappedFileAccess to a FileAccess. MemoryMappedViewStream and // MemoryMappedViewAccessor subclass UnmanagedMemoryStream and UnmanagedMemoryAccessor, which both use // FileAccess to determine whether they are writable and/or readable. internal static FileAccess GetFileAccess(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Read: case MemoryMappedFileAccess.ReadExecute: return FileAccess.Read; case MemoryMappedFileAccess.Write: return FileAccess.Write; case MemoryMappedFileAccess.ReadWrite: case MemoryMappedFileAccess.CopyOnWrite: case MemoryMappedFileAccess.ReadWriteExecute: return FileAccess.ReadWrite; default: throw new ArgumentOutOfRangeException("access"); } } // clean up: close file handle and delete files we created private static void CleanupFile(FileStream fileStream, bool existed, string path) { fileStream.Dispose(); if (!existed) { File.Delete(path); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Interfaces; using log4net; namespace OpenSim.Region.ScriptEngine.XEngine { /// <summary> /// Prepares events so they can be directly executed upon a script by EventQueueManager, then queues it. /// </summary> public class EventManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private XEngine myScriptEngine; public EventManager(XEngine _ScriptEngine) { myScriptEngine = _ScriptEngine; // m_log.Info("[XEngine] Hooking up to server events"); myScriptEngine.World.EventManager.OnAttach += attach; myScriptEngine.World.EventManager.OnObjectGrab += touch_start; myScriptEngine.World.EventManager.OnObjectGrabbing += touch; myScriptEngine.World.EventManager.OnObjectDeGrab += touch_end; myScriptEngine.World.EventManager.OnScriptChangedEvent += changed; myScriptEngine.World.EventManager.OnScriptAtTargetEvent += at_target; myScriptEngine.World.EventManager.OnScriptNotAtTargetEvent += not_at_target; myScriptEngine.World.EventManager.OnScriptAtRotTargetEvent += at_rot_target; myScriptEngine.World.EventManager.OnScriptNotAtRotTargetEvent += not_at_rot_target; myScriptEngine.World.EventManager.OnScriptMovingStartEvent += moving_start; myScriptEngine.World.EventManager.OnScriptMovingEndEvent += moving_end; myScriptEngine.World.EventManager.OnScriptControlEvent += control; myScriptEngine.World.EventManager.OnScriptColliderStart += collision_start; myScriptEngine.World.EventManager.OnScriptColliding += collision; myScriptEngine.World.EventManager.OnScriptCollidingEnd += collision_end; myScriptEngine.World.EventManager.OnScriptLandColliderStart += land_collision_start; myScriptEngine.World.EventManager.OnScriptLandColliding += land_collision; myScriptEngine.World.EventManager.OnScriptLandColliderEnd += land_collision_end; IMoneyModule money = myScriptEngine.World.RequestModuleInterface<IMoneyModule>(); if (money != null) { money.OnObjectPaid+=HandleObjectPaid; } } /// <summary> /// When an object gets paid by an avatar and generates the paid event, /// this will pipe it to the script engine /// </summary> /// <param name="objectID">Object ID that got paid</param> /// <param name="agentID">Agent Id that did the paying</param> /// <param name="amount">Amount paid</param> private void HandleObjectPaid(UUID objectID, UUID agentID, int amount) { // Since this is an event from a shared module, all scenes will // get it. But only one has the object in question. The others // just ignore it. // SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(objectID); if (part == null) return; if ((part.ScriptEvents & scriptEvents.money) == 0) part = part.ParentGroup.RootPart; m_log.Debug("Paid: " + objectID + " from " + agentID + ", amount " + amount); // part = part.ParentGroup.RootPart; money(part.LocalId, agentID, amount); } /// <summary> /// Handles piping the proper stuff to The script engine for touching /// Including DetectedParams /// </summary> /// <param name="localID"></param> /// <param name="originalID"></param> /// <param name="offsetPos"></param> /// <param name="remoteClient"></param> /// <param name="surfaceArgs"></param> public void touch_start(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { // Add to queue for all scripts in ObjectID object DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = remoteClient.AgentId; det[0].Populate(myScriptEngine.World); if (originalID == 0) { SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID); if (part == null) return; det[0].LinkNum = part.LinkNum; } else { SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID); det[0].LinkNum = originalPart.LinkNum; } if (surfaceArgs != null) { det[0].SurfaceTouchArgs = surfaceArgs; } myScriptEngine.PostObjectEvent(localID, new EventParams( "touch_start", new Object[] { new LSL_Types.LSLInteger(1) }, det)); } public void touch(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { // Add to queue for all scripts in ObjectID object DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = remoteClient.AgentId; det[0].Populate(myScriptEngine.World); det[0].OffsetPos = offsetPos; if (originalID == 0) { SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID); if (part == null) return; det[0].LinkNum = part.LinkNum; } else { SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID); det[0].LinkNum = originalPart.LinkNum; } if (surfaceArgs != null) { det[0].SurfaceTouchArgs = surfaceArgs; } myScriptEngine.PostObjectEvent(localID, new EventParams( "touch", new Object[] { new LSL_Types.LSLInteger(1) }, det)); } public void touch_end(uint localID, uint originalID, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { // Add to queue for all scripts in ObjectID object DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = remoteClient.AgentId; det[0].Populate(myScriptEngine.World); if (originalID == 0) { SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID); if (part == null) return; det[0].LinkNum = part.LinkNum; } else { SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID); det[0].LinkNum = originalPart.LinkNum; } if (surfaceArgs != null) { det[0].SurfaceTouchArgs = surfaceArgs; } myScriptEngine.PostObjectEvent(localID, new EventParams( "touch_end", new Object[] { new LSL_Types.LSLInteger(1) }, det)); } public void changed(uint localID, uint change) { // Add to queue for all scripts in localID, Object pass change. myScriptEngine.PostObjectEvent(localID, new EventParams( "changed",new object[] { new LSL_Types.LSLInteger(change) }, new DetectParams[0])); } // state_entry: not processed here // state_exit: not processed here public void money(uint localID, UUID agentID, int amount) { myScriptEngine.PostObjectEvent(localID, new EventParams( "money", new object[] { new LSL_Types.LSLString(agentID.ToString()), new LSL_Types.LSLInteger(amount) }, new DetectParams[0])); } public void collision_start(uint localID, ColliderArgs col) { // Add to queue for all scripts in ObjectID object List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Key =detobj.keyUUID; d.Populate(myScriptEngine.World); d.LinkNum = detobj.linkNumber; // do it here since currently linknum is collided part det.Add(d); } if (det.Count > 0) myScriptEngine.PostObjectEvent(localID, new EventParams( "collision_start", new Object[] { new LSL_Types.LSLInteger(det.Count) }, det.ToArray())); } public void collision(uint localID, ColliderArgs col) { // Add to queue for all scripts in ObjectID object List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Key =detobj.keyUUID; d.Populate(myScriptEngine.World); d.LinkNum = detobj.linkNumber; // do it here since currently linknum is collided part det.Add(d); } if (det.Count > 0) myScriptEngine.PostObjectEvent(localID, new EventParams( "collision", new Object[] { new LSL_Types.LSLInteger(det.Count) }, det.ToArray())); } public void collision_end(uint localID, ColliderArgs col) { // Add to queue for all scripts in ObjectID object List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Key =detobj.keyUUID; d.Populate(myScriptEngine.World); d.LinkNum = detobj.linkNumber; // do it here since currently linknum is collided part det.Add(d); } if (det.Count > 0) myScriptEngine.PostObjectEvent(localID, new EventParams( "collision_end", new Object[] { new LSL_Types.LSLInteger(det.Count) }, det.ToArray())); } public void land_collision_start(uint localID, ColliderArgs col) { List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Position = detobj.posVector; d.Populate(myScriptEngine.World); det.Add(d); myScriptEngine.PostObjectEvent(localID, new EventParams( "land_collision_start", new Object[] { new LSL_Types.Vector3(d.Position) }, det.ToArray())); } } public void land_collision(uint localID, ColliderArgs col) { List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Position = detobj.posVector; d.Populate(myScriptEngine.World); det.Add(d); myScriptEngine.PostObjectEvent(localID, new EventParams( "land_collision", new Object[] { new LSL_Types.Vector3(d.Position) }, det.ToArray())); } } public void land_collision_end(uint localID, ColliderArgs col) { List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Position = detobj.posVector; d.Populate(myScriptEngine.World); det.Add(d); myScriptEngine.PostObjectEvent(localID, new EventParams( "land_collision_end", new Object[] { new LSL_Types.Vector3(d.Position) }, det.ToArray())); } } // timer: not handled here // listen: not handled here public void control(UUID itemID, UUID agentID, uint held, uint change) { myScriptEngine.PostScriptEvent(itemID, new EventParams( "control",new object[] { new LSL_Types.LSLString(agentID.ToString()), new LSL_Types.LSLInteger(held), new LSL_Types.LSLInteger(change)}, new DetectParams[0])); } public void email(uint localID, UUID itemID, string timeSent, string address, string subject, string message, int numLeft) { myScriptEngine.PostObjectEvent(localID, new EventParams( "email",new object[] { new LSL_Types.LSLString(timeSent), new LSL_Types.LSLString(address), new LSL_Types.LSLString(subject), new LSL_Types.LSLString(message), new LSL_Types.LSLInteger(numLeft)}, new DetectParams[0])); } public void at_target(uint localID, uint handle, Vector3 targetpos, Vector3 atpos) { myScriptEngine.PostObjectEvent(localID, new EventParams( "at_target", new object[] { new LSL_Types.LSLInteger(handle), new LSL_Types.Vector3(targetpos), new LSL_Types.Vector3(atpos) }, new DetectParams[0])); } public void not_at_target(uint localID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "not_at_target",new object[0], new DetectParams[0])); } public void at_rot_target(uint localID, uint handle, Quaternion targetrot, Quaternion atrot) { myScriptEngine.PostObjectEvent(localID, new EventParams( "at_rot_target", new object[] { new LSL_Types.LSLInteger(handle), new LSL_Types.Quaternion(targetrot), new LSL_Types.Quaternion(atrot) }, new DetectParams[0])); } public void not_at_rot_target(uint localID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "not_at_rot_target",new object[0], new DetectParams[0])); } // run_time_permissions: not handled here public void attach(uint localID, UUID itemID, UUID avatar) { myScriptEngine.PostObjectEvent(localID, new EventParams( "attach",new object[] { new LSL_Types.LSLString(avatar.ToString()) }, new DetectParams[0])); } // dataserver: not handled here // link_message: not handled here public void moving_start(uint localID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "moving_start",new object[0], new DetectParams[0])); } public void moving_end(uint localID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "moving_end",new object[0], new DetectParams[0])); } // object_rez: not handled here // remote_data: not handled here // http_response: not handled here } }
/* * daap-sharp * Copyright (C) 2005 James Willcox <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Net; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; namespace Daap { public delegate void TrackHandler (object o, TrackArgs args); public class TrackArgs : EventArgs { private Track track; public Track Track { get { return track; } } public TrackArgs (Track track) { this.track = track; } } public delegate void PlaylistHandler (object o, PlaylistArgs args); public class PlaylistArgs : EventArgs { private Playlist pl; public Playlist Playlist { get { return pl; } } public PlaylistArgs (Playlist pl) { this.pl = pl; } } public class Database : ICloneable { private const int ChunkLength = 8192; private const string TrackQuery = "meta=dmap.itemid,dmap.itemname,dmap.itemkind,dmap.persistentid," + "daap.songalbum,daap.songgrouping,daap.songartist,daap.songbitrate," + "daap.songbeatsperminute,daap.songcomment,daap.songcodectype," + "daap.songcodecsubtype,daap.songcompilation,daap.songcomposer," + "daap.songdateadded,daap.songdatemodified,daap.songdisccount," + "daap.songdiscnumber,daap.songdisabled,daap.songeqpreset," + "daap.songformat,daap.songgenre,daap.songdescription," + "daap.songsamplerate,daap.songsize,daap.songstarttime," + "daap.songstoptime,daap.songtime,daap.songtrackcount," + "daap.songtracknumber,daap.songuserrating,daap.songyear," + "daap.songdatakind,daap.songdataurl,com.apple.itunes.norm-volume," + "com.apple.itunes.itms-songid,com.apple.itunes.itms-artistid," + "com.apple.itunes.itms-playlistid,com.apple.itunes.itms-composerid," + "com.apple.itunes.itms-genreid"; private static int nextid = 1; private Client client; private int id; private long persistentId; private string name; private List<Track> tracks = new List<Track> (); private List<Playlist> playlists = new List<Playlist> (); private Playlist basePlaylist = new Playlist (); private int nextTrackId = 1; public event TrackHandler TrackAdded; public event TrackHandler TrackRemoved; public event PlaylistHandler PlaylistAdded; public event PlaylistHandler PlaylistRemoved; public int Id { get { return id; } } public string Name { get { return name; } set { name = value; basePlaylist.Name = value; } } public IList<Track> Tracks { get { return new ReadOnlyCollection<Track> (tracks); } } public int TrackCount { get { return tracks.Count; } } public Track TrackAt(int index) { return tracks[index] as Track; } public IList<Playlist> Playlists { get { return new ReadOnlyCollection<Playlist> (playlists); } } internal Client Client { get { return client; } } private Database () { this.id = nextid++; } public Database (string name) : this () { this.Name = name; } internal Database (Client client, ContentNode dbNode) : this () { this.client = client; Parse (dbNode); } private void Parse (ContentNode dbNode) { foreach (ContentNode item in (ContentNode[]) dbNode.Value) { switch (item.Name) { case "dmap.itemid": id = (int) item.Value; break; case "dmap.persistentid": persistentId = (long) item.Value; break; case "dmap.itemname": name = (string) item.Value; break; default: break; } } } public Track LookupTrackById (int id) { foreach (Track track in tracks) { if (track.Id == id) return track; } return null; } public Playlist LookupPlaylistById (int id) { if (id == basePlaylist.Id) return basePlaylist; foreach (Playlist pl in playlists) { if (pl.Id == id) return pl; } return null; } internal ContentNode ToTracksNode (string[] fields, int[] deletedIds) { List <ContentNode> trackNodes = new List <ContentNode> (); foreach (Track track in tracks) { trackNodes.Add (track.ToNode (fields)); } List <ContentNode> deletedNodes = null; if (deletedIds.Length > 0) { deletedNodes = new List <ContentNode> (); foreach (int id in deletedIds) { deletedNodes.Add (new ContentNode ("dmap.itemid", id)); } } List <ContentNode> children = new List <ContentNode> (); children.Add (new ContentNode ("dmap.status", 200)); children.Add (new ContentNode ("dmap.updatetype", deletedNodes == null ? (byte) 0 : (byte) 1)); children.Add (new ContentNode ("dmap.specifiedtotalcount", tracks.Count)); children.Add (new ContentNode ("dmap.returnedcount", tracks.Count)); children.Add (new ContentNode ("dmap.listing", trackNodes)); if (deletedNodes != null) { children.Add (new ContentNode ("dmap.deletedidlisting", deletedNodes)); } return new ContentNode ("daap.databasesongs", children); } internal ContentNode ToPlaylistsNode () { List <ContentNode> nodes = new List <ContentNode> (); nodes.Add (basePlaylist.ToNode (true)); foreach (Playlist pl in playlists) { nodes.Add (pl.ToNode (false)); } return new ContentNode ("daap.databaseplaylists", new ContentNode ("dmap.status", 200), new ContentNode ("dmap.updatetype", (byte) 0), new ContentNode ("dmap.specifiedtotalcount", nodes.Count), new ContentNode ("dmap.returnedcount", nodes.Count), new ContentNode ("dmap.listing", nodes)); } internal ContentNode ToDatabaseNode () { return new ContentNode ("dmap.listingitem", new ContentNode ("dmap.itemid", id), new ContentNode ("dmap.persistentid", (long) id), new ContentNode ("dmap.itemname", name), new ContentNode ("dmap.itemcount", tracks.Count), new ContentNode ("dmap.containercount", playlists.Count + 1)); } public void Clear () { if (client != null) throw new InvalidOperationException ("cannot clear client databases"); ClearPlaylists (); ClearTracks (); } private void ClearPlaylists () { foreach (Playlist pl in new List<Playlist> (playlists)) { RemovePlaylist (pl); } } private void ClearTracks () { foreach (Track track in new List<Track> (tracks)) { RemoveTrack (track); } } private bool IsUpdateResponse (ContentNode node) { return node.Name == "dmap.updateresponse"; } private void RefreshPlaylists (string revquery) { byte[] playlistsData; try { playlistsData = client.Fetcher.Fetch (String.Format ("/databases/{0}/containers", id), revquery); } catch (WebException) { return; } ContentNode playlistsNode = ContentParser.Parse (client.Bag, playlistsData); if (IsUpdateResponse (playlistsNode)) return; // handle playlist additions/changes List <int> plids = new List <int> (); foreach (ContentNode playlistNode in (ContentNode[]) playlistsNode.GetChild ("dmap.listing").Value) { Playlist pl = Playlist.FromNode (playlistNode); if (pl != null) { plids.Add (pl.Id); Playlist existing = LookupPlaylistById (pl.Id); if (existing == null) { AddPlaylist (pl); } else { existing.Update (pl); } } } // delete playlists that no longer exist foreach (Playlist pl in new List<Playlist> (playlists)) { if (!plids.Contains (pl.Id)) { RemovePlaylist (pl); } } plids = null; // add/remove tracks in the playlists foreach (Playlist pl in playlists) { byte [] playlistTracksData = client.Fetcher.Fetch (String.Format ( "/databases/{0}/containers/{1}/items", id, pl.Id), String.Format ("meta=dmap.itemid,dmap.containeritemid&{0}", revquery) ); ContentNode playlistTracksNode = ContentParser.Parse (client.Bag, playlistTracksData); if (IsUpdateResponse (playlistTracksNode)) return; if ((byte) playlistTracksNode.GetChild ("dmap.updatetype").Value == 1) { // handle playlist track deletions ContentNode deleteList = playlistTracksNode.GetChild ("dmap.deletedidlisting"); if (deleteList != null) { foreach (ContentNode deleted in (ContentNode[]) deleteList.Value) { int index = pl.LookupIndexByContainerId ((int) deleted.Value); if (index < 0) continue; pl.RemoveAt (index); } } } // add new tracks, or reorder existing ones int plindex = 0; foreach (ContentNode plTrackNode in (ContentNode[]) playlistTracksNode.GetChild ("dmap.listing").Value) { Track pltrack = null; int containerId = 0; Track.FromPlaylistNode (this, plTrackNode, out pltrack, out containerId); if (pl[plindex] != null && pl.GetContainerId (plindex) != containerId) { pl.RemoveAt (plindex); pl.InsertTrack (plindex, pltrack, containerId); } else if (pl[plindex] == null) { pl.InsertTrack (plindex, pltrack, containerId); } plindex++; } } } private void RefreshTracks (string revquery) { byte[] tracksData = client.Fetcher.Fetch (String.Format ("/databases/{0}/items", id), TrackQuery + "&" + revquery); ContentNode tracksNode = ContentParser.Parse (client.Bag, tracksData); if (IsUpdateResponse (tracksNode)) return; // handle track additions/changes foreach (ContentNode trackNode in (ContentNode[]) tracksNode.GetChild ("dmap.listing").Value) { Track track = Track.FromNode (trackNode); Track existing = LookupTrackById (track.Id); if (existing == null) AddTrack (track); else existing.Update (track); } if ((byte) tracksNode.GetChild ("dmap.updatetype").Value == 1) { // handle track deletions ContentNode deleteList = tracksNode.GetChild ("dmap.deletedidlisting"); if (deleteList != null) { foreach (ContentNode deleted in (ContentNode[]) deleteList.Value) { Track track = LookupTrackById ((int) deleted.Value); if (track != null) RemoveTrack (track); } } } } internal void Refresh (int newrev) { if (client == null) throw new InvalidOperationException ("cannot refresh server databases"); string revquery = null; if (client.Revision != 0) revquery = String.Format ("revision-number={0}&delta={1}", newrev, newrev - client.Revision); RefreshTracks (revquery); RefreshPlaylists (revquery); } private HttpWebResponse FetchTrack (int track_id, string format, long offset) { return client.Fetcher.FetchFile (String.Format ("/databases/{0}/items/{1}.{2}", id, track_id, format), offset); } public Stream StreamTrack (Track track, out long length) { return StreamTrack (track, -1, out length); } public Stream StreamTrack (Track track, long offset, out long length) { return StreamTrack (track.Id, track.Format, offset, out length); } public Stream StreamTrack (int track_id, string track_format, out long length) { return StreamTrack (track_id, track_format, -1, out length); } public Stream StreamTrack (int track_id, string track_format, long offset, out long length) { HttpWebResponse response = FetchTrack (track_id, track_format, offset); length = response.ContentLength; return response.GetResponseStream (); } public IEnumerable<double> DownloadTrack (int track_id, string track_format, string dest) { BinaryWriter writer = new BinaryWriter (File.Open (dest, FileMode.Create)); try { long len, pos = 0, i = 0; using (BinaryReader reader = new BinaryReader (StreamTrack (track_id, track_format, out len))) { int count = 0; byte [] buf = new byte[ChunkLength]; do { count = reader.Read (buf, 0, ChunkLength); pos += count; writer.Write (buf, 0, count); // Roughly every 40KB yield an updated percent-done double if (i++ % 5 == 0) { yield return (double)pos / (double)len; } } while (count != 0); } } finally { writer.Close (); } } public void AddTrack (Track track) { if (track.Id == 0) track.SetId (nextTrackId++); tracks.Add (track); basePlaylist.AddTrack (track); if (TrackAdded != null) TrackAdded (this, new TrackArgs (track)); } public void RemoveTrack (Track track) { tracks.Remove (track); basePlaylist.RemoveTrack (track); foreach (Playlist pl in playlists) { pl.RemoveTrack (track); } if (TrackRemoved != null) TrackRemoved (this, new TrackArgs (track)); } public void AddPlaylist (Playlist pl) { playlists.Add (pl); if (PlaylistAdded != null) PlaylistAdded (this, new PlaylistArgs (pl)); } public void RemovePlaylist (Playlist pl) { playlists.Remove (pl); if (PlaylistRemoved != null) PlaylistRemoved (this, new PlaylistArgs (pl)); } private Playlist ClonePlaylist (Database db, Playlist pl) { Playlist clonePl = new Playlist (pl.Name); clonePl.Id = pl.Id; IList<Track> pltracks = pl.Tracks; for (int i = 0; i < pltracks.Count; i++) { clonePl.AddTrack (db.LookupTrackById (pltracks[i].Id), pl.GetContainerId (i)); } return clonePl; } public object Clone () { Database db = new Database (this.name); db.id = id; db.persistentId = persistentId; List<Track> cloneTracks = new List<Track> (); foreach (Track track in tracks) { cloneTracks.Add ((Track) track.Clone ()); } db.tracks = cloneTracks; List<Playlist> clonePlaylists = new List<Playlist> (); foreach (Playlist pl in playlists) { clonePlaylists.Add (ClonePlaylist (db, pl)); } db.playlists = clonePlaylists; db.basePlaylist = ClonePlaylist (db, basePlaylist); return db; } } }
//----------------------------------------------------------------------------- // Verve // Copyright (C) - Violent Tulip //----------------------------------------------------------------------------- function VerveWindowMenu::Clear( %this ) { while ( %this.getItemCount() > 0 ) { %this.removeItem( 0 ); } } function VerveWindowMenu::Init( %this ) { // Clear Items. %this.Clear(); %i = 0; while ( %this.Item[%i] !$= "" ) { %itemString = %this.Item[%i]; %itemLabel = getField( %itemString, 0 ); %itemAccel = getField( %itemString, 1 ); %itemMethod = getField( %itemString, 2 ); %itemMap = getField( %itemString, 3 ); if ( !isObject( %itemMap ) ) { %itemMap = VerveEditorMap; } if ( isObject( %itemAccel ) ) { %this.insertSubMenu( %i, %itemLabel, %itemAccel ); } else { // Insert Item. %this.insertItem( %i, %itemLabel, %itemAccel ); if ( !%this.IsPopup && %itemAccel !$= "" && isObject( %itemMap ) ) { // Label Hack... switch$( %itemAccel ) { case "DEL" : %itemAccel = "DELETE"; case "ESC" : %itemAccel = "ESCAPE"; } // Perform Keybind. %itemMap.bindCmd( "keyboard", strreplace( %itemAccel, "+", " " ), %itemMethod, "" ); } } %i++; } } function VerveWindowMenu::onSelectItem( %this, %id, %text ) { %command = getField( %this.item[%id], 2 ); if ( %command !$= "" ) { eval( %command ); return true; } return false; } //------------------------------------------------------------------------- function VerveEditorWindow::onCreateMenu( %this ) { // Store Menu Bars. if ( !isObject( %this.MenuSet ) ) { %this.MenuSet = new SimSet(); } // CMD Key. %cmdKey = $platform $= "macos" ? "Cmd" : "Ctrl"; //--------------------------------------------------------------------- // // File Menu // //--------------------------------------------------------------------- %recentSequenceMenu = new PopupMenu() { Class = "VerveRecentFileMenu"; SuperClass = "VerveWindowMenu"; Label = "Recent Files"; Position = 0; Item[0] = "None"; }; %fileMenu = new PopupMenu() { SuperClass = "VerveWindowMenu"; Label = "&File"; Position = 0; Item[0] = "&New" TAB %cmdKey @ "+N" TAB "VerveEditor::NewFile();"; Item[1] = "&Open" TAB %cmdKey @ "+O" TAB "VerveEditor::LoadFile();"; Item[2] = "" TAB ""; Item[3] = "&Save" TAB %cmdKey @ "+S" TAB "VerveEditor::SaveFile();"; Item[4] = "Save &As" TAB %cmdKey @ "-Shift+S" TAB "VerveEditor::SaveFile( true );"; Item[5] = "" TAB ""; Item[6] = "Recent Files" TAB %recentSequenceMenu; }; %this.MenuSet.add( %fileMenu ); if ( $platform !$= "macos" ) { %fileMenu.Item[7] = "" TAB ""; %fileMenu.Item[8] = "&Close" TAB %cmdKey @ "+F4" TAB "ToggleVerveEditor( true );"; } //--------------------------------------------------------------------- // // Edit Menu // //--------------------------------------------------------------------- %editMenu = new PopupMenu() { Class = "VerveWindowEditMenu"; SuperClass = "VerveWindowMenu"; Label = "&Edit"; Position = 1; Item[0] = "&Undo" TAB %cmdKey @ "+Z" TAB "VerveEditor::Undo();"; Item[1] = "&Redo" TAB %cmdKey @ "+Y" TAB "VerveEditor::Redo();"; Item[2] = "" TAB ""; Item[3] = "Cu&t" TAB %cmdKey @ "+X" TAB "VerveEditor::CutSelection();" TAB VerveEditorEditMap; Item[4] = "&Copy" TAB %cmdKey @ "+C" TAB "VerveEditor::CopySelection();" TAB VerveEditorEditMap; Item[5] = "&Paste" TAB %cmdKey @ "+V" TAB "VerveEditor::Paste();" TAB VerveEditorEditMap; Item[6] = "" TAB ""; Item[7] = "&Delete" TAB "Del" TAB "VerveEditor::DeleteSelection();" TAB VerveEditorEditMap; Item[8] = "" TAB ""; Item[9] = "&Clear Selection" TAB "Esc" TAB "VerveEditor::ClearSelection();"; Item[10] = "" TAB ""; Item[11] = "&Preferences" TAB %cmdKey @ "+P" TAB "VerveEditor::LaunchEditorPreferences();"; }; %this.MenuSet.add( %editMenu ); // Init Popups. %fileMenu.Init(); %editMenu.Init(); // Attach. %fileMenu.attachToMenuBar( %this, %fileMenu.Position, %fileMenu.Label ); %editMenu.attachToMenuBar( %this, %editMenu.Position, %editMenu.Label ); } function VerveEditorWindow::ClearMenu( %this ) { if ( isObject( %this.MenuSet ) ) { while( %this.MenuSet.getCount() > 0 ) { // Fetch Object. %menuObject = %this.MenuSet.getObject( 0 ); // Detach. %menuObject.removeFromMenuBar(); // Delete. %menuObject.delete(); } } } function VerveEditorWindow::onDestroyMenu( %this ) { // Clear the Menu. %this.ClearMenu(); // Delete the Menu Set. if ( isObject( %this.MenuSet ) ) { %this.MenuSet.delete(); } } function VerveRecentFileMenu::onMenuSelect( %this ) { %this.Refresh(); } function VerveRecentFileMenu::onSelectItem( %this, %index, %text ) { // Load the File. VerveEditor::LoadFile( $Pref::VerveEditor::RecentFile[ %index ] ); return false; } function VerveRecentFileMenu::Refresh( %this ) { // Clear The List. %this.Clear(); // Populate Menu. if ( $Pref::VerveEditor::RecentFileSize == 0 || $Pref::VerveEditor::RecentFile[0] $= "" ) { // Insert Default Item. %this.insertItem( 0, %this.Item[0], "" ); // Disable. %this.enableItem( 0, false ); } else { for ( %i = 0; %i < $Pref::VerveEditor::RecentFileSize; %i++ ) { // Valid? if ( $Pref::VerveEditor::RecentFile[%i] $= "" ) { // Nope! break; } // Insert Item. %this.insertItem( %i, makeRelativePath( $Pref::VerveEditor::RecentFile[%i], $VerveEditor::FilePath ), "" ); } } } function VerveWindowEditMenu::onMenuSelect( %this ) { %this.Refresh(); } function VerveWindowEditMenu::Refresh( %this ) { // Undo & Redo. %this.enableItem( 0, VerveEditor::CanUndo() ); %this.enableItem( 1, VerveEditor::CanRedo() ); // Cut, Copy & Paste. %this.enableItem( 3, VerveEditor::CanCopy() ); %this.enableItem( 4, VerveEditor::CanCopy() ); %this.enableItem( 5, VerveEditor::CanPaste() ); // Delete. %this.enableItem( 7, VerveEditor::CanCopy() ); // Clear Selection. %this.enableItem( 9, VerveEditor::CanCopy() ); }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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. ************************************************************************************/ // #define SHOW_DK2_VARIABLES // Use the Unity new GUI with Unity 4.6 or above. #if UNITY_4_6 || UNITY_5_0 #define USE_NEW_GUI #endif using System; using System.Collections; using UnityEngine; #if USE_NEW_GUI using UnityEngine.UI; # endif //------------------------------------------------------------------------------------- // ***** OVRMainMenu // /// <summary> /// OVRMainMenu is used to control the loading of different scenes. It also renders out /// a menu that allows a user to modify various Rift settings, and allow for storing /// these settings for recall later. /// /// A user of this component can add as many scenes that they would like to be able to /// have access to. /// /// OVRMainMenu is currently attached to the OVRPlayerController prefab for convenience, /// but can safely removed from it and added to another GameObject that is used for general /// Unity logic. /// /// </summary> public class OVRMainMenu : MonoBehaviour { /// <summary> /// The amount of time in seconds that it takes for the menu to fade in. /// </summary> public float FadeInTime = 2.0f; /// <summary> /// An optional texture that appears before the menu fades in. /// </summary> public UnityEngine.Texture FadeInTexture = null; /// <summary> /// An optional font that replaces Unity's default Arial. /// </summary> public Font FontReplace = null; /// <summary> /// The key that toggles the menu. /// </summary> public KeyCode MenuKey = KeyCode.Space; /// <summary> /// The key that quits the application. /// </summary> public KeyCode QuitKey = KeyCode.Escape; /// <summary> /// Scene names to show on-screen for each of the scenes in Scenes. /// </summary> public string [] SceneNames; /// <summary> /// The set of scenes that the user can jump to. /// </summary> public string [] Scenes; private bool ScenesVisible = false; // Spacing for scenes menu private int StartX = 490; private int StartY = 250; private int WidthX = 300; private int WidthY = 23; // Spacing for variables that users can change private int VRVarsSX = 553; private int VRVarsSY = 250; private int VRVarsWidthX = 175; private int VRVarsWidthY = 23; private int StepY = 25; // Handle to OVRCameraRig private OVRCameraRig CameraController = null; // Handle to OVRPlayerController private OVRPlayerController PlayerController = null; // Controller buttons private bool PrevStartDown; private bool PrevHatDown; private bool PrevHatUp; private bool ShowVRVars; private bool OldSpaceHit; // FPS private float UpdateInterval = 0.5f; private float Accum = 0; private int Frames = 0; private float TimeLeft = 0; private string strFPS = "FPS: 0"; private string strIPD = "IPD: 0.000"; /// <summary> /// Prediction (in ms) /// </summary> public float PredictionIncrement = 0.001f; // 1 ms private string strPrediction = "Pred: OFF"; private string strFOV = "FOV: 0.0f"; private string strHeight = "Height: 0.0f"; /// <summary> /// Controls how quickly the player's speed and rotation change based on input. /// </summary> public float SpeedRotationIncrement = 0.05f; private string strSpeedRotationMultipler = "Spd. X: 0.0f Rot. X: 0.0f"; private bool LoadingLevel = false; private float AlphaFadeValue = 1.0f; private int CurrentLevel = 0; // Rift detection private bool HMDPresent = false; private float RiftPresentTimeout = 0.0f; private string strRiftPresent = ""; // Replace the GUI with our own texture and 3D plane that // is attached to the rendder camera for true 3D placement private OVRGUI GuiHelper = new OVRGUI(); private GameObject GUIRenderObject = null; private RenderTexture GUIRenderTexture = null; // We want to use new Unity GUI built in 4.6 for OVRMainMenu GUI // Enable the UsingNewGUI option in the editor, // if you want to use new GUI and Unity version is higher than 4.6 #if USE_NEW_GUI private GameObject NewGUIObject = null; private GameObject RiftPresentGUIObject = null; #endif /// <summary> /// We can set the layer to be anything we want to, this allows /// a specific camera to render it. /// </summary> public string LayerName = "Default"; /// <summary> /// Crosshair rendered onto 3D plane. /// </summary> public UnityEngine.Texture CrosshairImage = null; private OVRCrosshair Crosshair = new OVRCrosshair(); // Resolution Eye Texture private string strResolutionEyeTexture = "Resolution: 0 x 0"; // Latency values private string strLatencies = "Ren: 0.0f TWrp: 0.0f PostPresent: 0.0f"; // Vision mode on/off private bool VisionMode = true; #if SHOW_DK2_VARIABLES private string strVisionMode = "Vision Enabled: ON"; #endif // We want to hold onto GridCube, for potential sharing // of the menu RenderTarget OVRGridCube GridCube = null; // We want to hold onto the VisionGuide so we can share // the menu RenderTarget OVRVisionGuide VisionGuide = null; #region MonoBehaviour Message Handlers /// <summary> /// Awake this instance. /// </summary> void Awake() { // Find camera controller OVRCameraRig[] CameraControllers; CameraControllers = gameObject.GetComponentsInChildren<OVRCameraRig>(); if(CameraControllers.Length == 0) Debug.LogWarning("OVRMainMenu: No OVRCameraRig attached."); else if (CameraControllers.Length > 1) Debug.LogWarning("OVRMainMenu: More then 1 OVRCameraRig attached."); else{ CameraController = CameraControllers[0]; #if USE_NEW_GUI OVRUGUI.CameraController = CameraController; #endif } // Find player controller OVRPlayerController[] PlayerControllers; PlayerControllers = gameObject.GetComponentsInChildren<OVRPlayerController>(); if(PlayerControllers.Length == 0) Debug.LogWarning("OVRMainMenu: No OVRPlayerController attached."); else if (PlayerControllers.Length > 1) Debug.LogWarning("OVRMainMenu: More then 1 OVRPlayerController attached."); else{ PlayerController = PlayerControllers[0]; #if USE_NEW_GUI OVRUGUI.PlayerController = PlayerController; #endif } #if USE_NEW_GUI // Create canvas for using new GUI NewGUIObject = new GameObject(); NewGUIObject.name = "OVRGUIMain"; NewGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform r = NewGUIObject.AddComponent<RectTransform>(); r.sizeDelta = new Vector2(100f, 100f); r.localScale = new Vector3(0.001f, 0.001f, 0.001f); r.localPosition = new Vector3(0.01f, 0.17f, 0.53f); r.localEulerAngles = Vector3.zero; Canvas c = NewGUIObject.AddComponent<Canvas>(); #if (UNITY_5_0) // TODO: Unity 5.0b11 has an older version of the new GUI being developed in Unity 4.6. // Remove this once Unity 5 has a more recent merge of Unity 4.6. c.renderMode = RenderMode.World; #else c.renderMode = RenderMode.WorldSpace; #endif c.pixelPerfect = false; #endif } /// <summary> /// Start this instance. /// </summary> void Start() { AlphaFadeValue = 1.0f; CurrentLevel = 0; PrevStartDown = false; PrevHatDown = false; PrevHatUp = false; ShowVRVars = false; OldSpaceHit = false; strFPS = "FPS: 0"; LoadingLevel = false; ScenesVisible = false; // Set the GUI target GUIRenderObject = GameObject.Instantiate(Resources.Load("OVRGUIObjectMain")) as GameObject; if(GUIRenderObject != null) { // Chnge the layer GUIRenderObject.layer = LayerMask.NameToLayer(LayerName); if(GUIRenderTexture == null) { int w = Screen.width; int h = Screen.height; // We don't need a depth buffer on this texture GUIRenderTexture = new RenderTexture(w, h, 0); GuiHelper.SetPixelResolution(w, h); // NOTE: All GUI elements are being written with pixel values based // from DK1 (1280x800). These should change to normalized locations so // that we can scale more cleanly with varying resolutions GuiHelper.SetDisplayResolution(1280.0f, 800.0f); } } // Attach GUI texture to GUI object and GUI object to Camera if(GUIRenderTexture != null && GUIRenderObject != null) { GUIRenderObject.GetComponent<Renderer>().material.mainTexture = GUIRenderTexture; if(CameraController != null) { // Grab transform of GUI object Vector3 ls = GUIRenderObject.transform.localScale; Vector3 lp = GUIRenderObject.transform.localPosition; Quaternion lr = GUIRenderObject.transform.localRotation; // Attach the GUI object to the camera GUIRenderObject.transform.parent = CameraController.centerEyeAnchor; // Reset the transform values (we will be maintaining state of the GUI object // in local state) GUIRenderObject.transform.localScale = ls; GUIRenderObject.transform.localPosition = lp; GUIRenderObject.transform.localRotation = lr; // Deactivate object until we have completed the fade-in // Also, we may want to deactive the render object if there is nothing being rendered // into the UI GUIRenderObject.SetActive(false); } } // Make sure to hide cursor if(Application.isEditor == false) { #if UNITY_5_0 Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; #else Screen.showCursor = false; Screen.lockCursor = true; #endif } // CameraController updates if(CameraController != null) { // Add a GridCube component to this object GridCube = gameObject.AddComponent<OVRGridCube>(); GridCube.SetOVRCameraController(ref CameraController); // Add a VisionGuide component to this object VisionGuide = gameObject.AddComponent<OVRVisionGuide>(); VisionGuide.SetOVRCameraController(ref CameraController); VisionGuide.SetFadeTexture(ref FadeInTexture); VisionGuide.SetVisionGuideLayer(ref LayerName); } // Crosshair functionality Crosshair.Init(); Crosshair.SetCrosshairTexture(ref CrosshairImage); Crosshair.SetOVRCameraController (ref CameraController); Crosshair.SetOVRPlayerController(ref PlayerController); // Check for HMD and sensor CheckIfRiftPresent(); #if USE_NEW_GUI if (!string.IsNullOrEmpty(strRiftPresent)){ ShowRiftPresentGUI(); } #endif } /// <summary> /// Update this instance. /// </summary> void Update() { if(LoadingLevel == true) return; // Main update UpdateFPS(); // CameraController updates if(CameraController != null) { UpdateIPD(); UpdateRecenterPose(); UpdateVisionMode(); UpdateFOV(); UpdateEyeHeightOffset(); UpdateResolutionEyeTexture(); UpdateLatencyValues(); } // PlayerController updates if(PlayerController != null) { UpdateSpeedAndRotationScaleMultiplier(); UpdatePlayerControllerMovement(); } // MainMenu updates UpdateSelectCurrentLevel(); // Device updates UpdateDeviceDetection(); // Crosshair functionality Crosshair.UpdateCrosshair(); #if USE_NEW_GUI if (ShowVRVars && RiftPresentTimeout <= 0.0f) { NewGUIObject.SetActive(true); UpdateNewGUIVars(); OVRUGUI.UpdateGUI(); } else { NewGUIObject.SetActive(false); } #endif // Toggle Fullscreen if(Input.GetKeyDown(KeyCode.F11)) Screen.fullScreen = !Screen.fullScreen; if (Input.GetKeyDown(KeyCode.M)) OVRManager.display.mirrorMode = !OVRManager.display.mirrorMode; // Escape Application if (Input.GetKeyDown(QuitKey)) Application.Quit(); } /// <summary> /// Updates Variables for new GUI. /// </summary> #if USE_NEW_GUI void UpdateNewGUIVars() { #if SHOW_DK2_VARIABLES // Print out Vision Mode OVRUGUI.strVisionMode = strVisionMode; #endif // Print out FPS OVRUGUI.strFPS = strFPS; // Don't draw these vars if CameraController is not present if (CameraController != null) { OVRUGUI.strPrediction = strPrediction; OVRUGUI.strIPD = strIPD; OVRUGUI.strFOV = strFOV; OVRUGUI.strResolutionEyeTexture = strResolutionEyeTexture; OVRUGUI.strLatencies = strLatencies; } // Don't draw these vars if PlayerController is not present if (PlayerController != null) { OVRUGUI.strHeight = strHeight; OVRUGUI.strSpeedRotationMultipler = strSpeedRotationMultipler; } OVRUGUI.strRiftPresent = strRiftPresent; } #endif void OnGUI() { // Important to keep from skipping render events if (Event.current.type != EventType.Repaint) return; #if !USE_NEW_GUI // Fade in screen if(AlphaFadeValue > 0.0f) { AlphaFadeValue -= Mathf.Clamp01(Time.deltaTime / FadeInTime); if(AlphaFadeValue < 0.0f) { AlphaFadeValue = 0.0f; } else { GUI.color = new Color(0, 0, 0, AlphaFadeValue); GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture ); return; } } #endif // We can turn on the render object so we can render the on-screen menu if(GUIRenderObject != null) { if (ScenesVisible || ShowVRVars || Crosshair.IsCrosshairVisible() || RiftPresentTimeout > 0.0f || VisionGuide.GetFadeAlphaValue() > 0.0f) { GUIRenderObject.SetActive(true); } else { GUIRenderObject.SetActive(false); } } //*** // Set the GUI matrix to deal with portrait mode Vector3 scale = Vector3.one; Matrix4x4 svMat = GUI.matrix; // save current matrix // substitute matrix - only scale is altered from standard GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale); // Cache current active render texture RenderTexture previousActive = RenderTexture.active; // if set, we will render to this texture if(GUIRenderTexture != null && GUIRenderObject.activeSelf) { RenderTexture.active = GUIRenderTexture; GL.Clear (false, true, new Color (0.0f, 0.0f, 0.0f, 0.0f)); } // Update OVRGUI functions (will be deprecated eventually when 2D renderingc // is removed from GUI) GuiHelper.SetFontReplace(FontReplace); // If true, we are displaying information about the Rift not being detected // So do not show anything else if(GUIShowRiftDetected() != true) { GUIShowLevels(); GUIShowVRVariables(); } // The cross-hair may need to go away at some point, unless someone finds it // useful Crosshair.OnGUICrosshair(); // Since we want to draw into the main GUI that is shared within the MainMenu, // we call the OVRVisionGuide GUI function here VisionGuide.OnGUIVisionGuide(); // Restore active render texture if (GUIRenderObject.activeSelf) { RenderTexture.active = previousActive; } // *** // Restore previous GUI matrix GUI.matrix = svMat; } #endregion #region Internal State Management Functions /// <summary> /// Updates the FPS. /// </summary> void UpdateFPS() { TimeLeft -= Time.deltaTime; Accum += Time.timeScale/Time.deltaTime; ++Frames; // Interval ended - update GUI text and start new interval if( TimeLeft <= 0.0 ) { // display two fractional digits (f2 format) float fps = Accum / Frames; if(ShowVRVars == true)// limit gc strFPS = System.String.Format("FPS: {0:F2}",fps); TimeLeft += UpdateInterval; Accum = 0.0f; Frames = 0; } } /// <summary> /// Updates the IPD. /// </summary> void UpdateIPD() { if(ShowVRVars == true) // limit gc { strIPD = System.String.Format("IPD (mm): {0:F4}", OVRManager.profile.ipd * 1000.0f); } } void UpdateRecenterPose() { if(Input.GetKeyDown(KeyCode.R)) { OVRManager.display.RecenterPose(); } } /// <summary> /// Updates the vision mode. /// </summary> void UpdateVisionMode() { if (Input.GetKeyDown(KeyCode.F2)) { VisionMode = !VisionMode; OVRManager.tracker.isEnabled = VisionMode; #if SHOW_DK2_VARIABLES strVisionMode = VisionMode ? "Vision Enabled: ON" : "Vision Enabled: OFF"; #endif } } /// <summary> /// Updates the FOV. /// </summary> void UpdateFOV() { if(ShowVRVars == true)// limit gc { OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left); strFOV = System.String.Format ("FOV (deg): {0:F3}", eyeDesc.fov.y); } } /// <summary> /// Updates resolution of eye texture /// </summary> void UpdateResolutionEyeTexture() { if (ShowVRVars == true) // limit gc { OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left); OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Right); float scale = OVRManager.instance.nativeTextureScale * OVRManager.instance.virtualTextureScale; float w = (int)(scale * (float)(leftEyeDesc.resolution.x + rightEyeDesc.resolution.x)); float h = (int)(scale * (float)Mathf.Max(leftEyeDesc.resolution.y, rightEyeDesc.resolution.y)); strResolutionEyeTexture = System.String.Format("Resolution : {0} x {1}", w, h); } } /// <summary> /// Updates latency values /// </summary> void UpdateLatencyValues() { #if !UNITY_ANDROID || UNITY_EDITOR if (ShowVRVars == true) // limit gc { OVRDisplay.LatencyData latency = OVRManager.display.latency; if (latency.render < 0.000001f && latency.timeWarp < 0.000001f && latency.postPresent < 0.000001f) strLatencies = System.String.Format("Ren : N/A TWrp: N/A PostPresent: N/A"); else strLatencies = System.String.Format("Ren : {0:F3} TWrp: {1:F3} PostPresent: {2:F3}", latency.render, latency.timeWarp, latency.postPresent); } #endif } /// <summary> /// Updates the eye height offset. /// </summary> void UpdateEyeHeightOffset() { if(ShowVRVars == true)// limit gc { float eyeHeight = OVRManager.profile.eyeHeight; strHeight = System.String.Format ("Eye Height (m): {0:F3}", eyeHeight); } } /// <summary> /// Updates the speed and rotation scale multiplier. /// </summary> void UpdateSpeedAndRotationScaleMultiplier() { float moveScaleMultiplier = 0.0f; PlayerController.GetMoveScaleMultiplier(ref moveScaleMultiplier); if(Input.GetKeyDown(KeyCode.Alpha7)) moveScaleMultiplier -= SpeedRotationIncrement; else if (Input.GetKeyDown(KeyCode.Alpha8)) moveScaleMultiplier += SpeedRotationIncrement; PlayerController.SetMoveScaleMultiplier(moveScaleMultiplier); float rotationScaleMultiplier = 0.0f; PlayerController.GetRotationScaleMultiplier(ref rotationScaleMultiplier); if(Input.GetKeyDown(KeyCode.Alpha9)) rotationScaleMultiplier -= SpeedRotationIncrement; else if (Input.GetKeyDown(KeyCode.Alpha0)) rotationScaleMultiplier += SpeedRotationIncrement; PlayerController.SetRotationScaleMultiplier(rotationScaleMultiplier); if(ShowVRVars == true)// limit gc strSpeedRotationMultipler = System.String.Format ("Spd.X: {0:F2} Rot.X: {1:F2}", moveScaleMultiplier, rotationScaleMultiplier); } /// <summary> /// Updates the player controller movement. /// </summary> void UpdatePlayerControllerMovement() { if(PlayerController != null) PlayerController.SetHaltUpdateMovement(ScenesVisible); } /// <summary> /// Updates the select current level. /// </summary> void UpdateSelectCurrentLevel() { ShowLevels(); if (!ScenesVisible) return; CurrentLevel = GetCurrentLevel(); if (Scenes.Length != 0 && (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.A) || Input.GetKeyDown(KeyCode.Return))) { LoadingLevel = true; Application.LoadLevelAsync(Scenes[CurrentLevel]); } } /// <summary> /// Shows the levels. /// </summary> /// <returns><c>true</c>, if levels was shown, <c>false</c> otherwise.</returns> bool ShowLevels() { if (Scenes.Length == 0) { ScenesVisible = false; return ScenesVisible; } bool curStartDown = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Start); bool startPressed = (curStartDown && !PrevStartDown) || Input.GetKeyDown(KeyCode.RightShift); PrevStartDown = curStartDown; if (startPressed) { ScenesVisible = !ScenesVisible; } return ScenesVisible; } /// <summary> /// Gets the current level. /// </summary> /// <returns>The current level.</returns> int GetCurrentLevel() { bool curHatDown = false; if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true) curHatDown = true; bool curHatUp = false; if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true) curHatUp = true; if((PrevHatDown == false) && (curHatDown == true) || Input.GetKeyDown(KeyCode.DownArrow)) { CurrentLevel = (CurrentLevel + 1) % SceneNames.Length; } else if((PrevHatUp == false) && (curHatUp == true) || Input.GetKeyDown(KeyCode.UpArrow)) { CurrentLevel--; if(CurrentLevel < 0) CurrentLevel = SceneNames.Length - 1; } PrevHatDown = curHatDown; PrevHatUp = curHatUp; return CurrentLevel; } #endregion #region Internal GUI Functions /// <summary> /// Show the GUI levels. /// </summary> void GUIShowLevels() { if(ScenesVisible == true) { // Darken the background by rendering fade texture GUI.color = new Color(0, 0, 0, 0.5f); GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture ); GUI.color = Color.white; if(LoadingLevel == true) { string loading = "LOADING..."; GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref loading, Color.yellow); return; } for (int i = 0; i < SceneNames.Length; i++) { Color c; if(i == CurrentLevel) c = Color.yellow; else c = Color.black; int y = StartY + (i * StepY); GuiHelper.StereoBox (StartX, y, WidthX, WidthY, ref SceneNames[i], c); } } } /// <summary> /// Show the VR variables. /// </summary> void GUIShowVRVariables() { bool SpaceHit = Input.GetKey(MenuKey); if ((OldSpaceHit == false) && (SpaceHit == true)) { if (ShowVRVars == true) { ShowVRVars = false; } else { ShowVRVars = true; #if USE_NEW_GUI OVRUGUI.InitUIComponent = ShowVRVars; #endif } } OldSpaceHit = SpaceHit; // Do not render if we are not showing if (ShowVRVars == false) return; #if !USE_NEW_GUI int y = VRVarsSY; #if SHOW_DK2_VARIABLES // Print out Vision Mode GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strVisionMode, Color.green); #endif // Draw FPS GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strFPS, Color.green); // Don't draw these vars if CameraController is not present if (CameraController != null) { GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strPrediction, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strIPD, Color.yellow); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strFOV, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strResolutionEyeTexture, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strLatencies, Color.white); } // Don't draw these vars if PlayerController is not present if (PlayerController != null) { GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strHeight, Color.yellow); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strSpeedRotationMultipler, Color.white); } #endif } // RIFT DETECTION /// <summary> /// Checks to see if HMD and / or sensor is available, and displays a /// message if it is not. /// </summary> void CheckIfRiftPresent() { HMDPresent = OVRManager.display.isPresent; if (!HMDPresent) { RiftPresentTimeout = 15.0f; if (!HMDPresent) strRiftPresent = "NO HMD DETECTED"; #if USE_NEW_GUI OVRUGUI.strRiftPresent = strRiftPresent; #endif } } /// <summary> /// Show if Rift is detected. /// </summary> /// <returns><c>true</c>, if show rift detected was GUIed, <c>false</c> otherwise.</returns> bool GUIShowRiftDetected() { #if !USE_NEW_GUI if(RiftPresentTimeout > 0.0f) { GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref strRiftPresent, Color.white); return true; } #else if(RiftPresentTimeout < 0.0f) DestroyImmediate(RiftPresentGUIObject); #endif return false; } /// <summary> /// Updates the device detection. /// </summary> void UpdateDeviceDetection() { if(RiftPresentTimeout > 0.0f) RiftPresentTimeout -= Time.deltaTime; } /// <summary> /// Show rift present GUI with new GUI /// </summary> void ShowRiftPresentGUI() { #if USE_NEW_GUI RiftPresentGUIObject = new GameObject(); RiftPresentGUIObject.name = "RiftPresentGUIMain"; RiftPresentGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform r = RiftPresentGUIObject.AddComponent<RectTransform>(); r.sizeDelta = new Vector2(100f, 100f); r.localPosition = new Vector3(0.01f, 0.17f, 0.53f); r.localEulerAngles = Vector3.zero; r.localScale = new Vector3(0.001f, 0.001f, 0.001f); Canvas c = RiftPresentGUIObject.AddComponent<Canvas>(); #if UNITY_5_0 // TODO: Unity 5.0b11 has an older version of the new GUI being developed in Unity 4.6. // Remove this once Unity 5 has a more recent merge of Unity 4.6. c.renderMode = RenderMode.World; #else c.renderMode = RenderMode.WorldSpace; #endif c.pixelPerfect = false; OVRUGUI.RiftPresentGUI(RiftPresentGUIObject); #endif } #endregion }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Collections.Generic.SortedList_2.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Collections.Generic { public partial class SortedList<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, System.Collections.IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { #region Methods and constructors public void Add(TKey key, TValue value) { } public void Clear() { } public bool ContainsKey(TKey key) { return default(bool); } public bool ContainsValue(TValue value) { return default(bool); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { Contract.Ensures(Contract.Result<System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>>() != null); return default(IEnumerator<KeyValuePair<TKey, TValue>>); } public int IndexOfKey(TKey key) { Contract.Ensures(-1 <= Contract.Result<int>()); return default(int); } public int IndexOfValue(TValue value) { return default(int); } public bool Remove(TKey key) { return default(bool); } public void RemoveAt(int index) { } public SortedList() { } public SortedList(int capacity, IComparer<TKey> comparer) { } public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) { Contract.Requires(dictionary.Keys != null); } public SortedList(IComparer<TKey> comparer) { } public SortedList(IDictionary<TKey, TValue> dictionary) { Contract.Requires(dictionary.Keys != null); } public SortedList(int capacity) { } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); } IEnumerator<KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>.GetEnumerator() { return default(IEnumerator<KeyValuePair<TKey, TValue>>); } void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { } void System.Collections.IDictionary.Add(Object key, Object value) { } bool System.Collections.IDictionary.Contains(Object key) { return default(bool); } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } void System.Collections.IDictionary.Remove(Object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public void TrimExcess() { } public bool TryGetValue(TKey key, out TValue value) { value = default(TValue); return default(bool); } #endregion #region Properties and indexers public int Capacity { get { Contract.Ensures(0 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 2147483647); return default(int); } set { } } public IComparer<TKey> Comparer { get { return default(IComparer<TKey>); } } public int Count { get { return default(int); } } public TValue this [TKey key] { get { return default(TValue); } set { } } public IList<TKey> Keys { get { Contract.Ensures(Contract.Result<System.Collections.Generic.IList<TKey>>() != null); return default(IList<TKey>); } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.IsReadOnly { get { return default(bool); } } ICollection<TKey> System.Collections.Generic.IDictionary<TKey,TValue>.Keys { get { return default(ICollection<TKey>); } } ICollection<TValue> System.Collections.Generic.IDictionary<TKey,TValue>.Values { get { return default(ICollection<TValue>); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } Object System.Collections.ICollection.SyncRoot { get { return default(Object); } } bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } } bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } } Object System.Collections.IDictionary.this [Object key] { get { return default(Object); } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } } System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } } public IList<TValue> Values { get { Contract.Ensures(Contract.Result<System.Collections.Generic.IList<TValue>>() != null); return default(IList<TValue>); } } #endregion } }
using AjaxControlToolkit.Design; using System; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// The ModalPopup extender allows you to display content in an element that mimics a modal dialog box, /// which prevents a user from interacting with the rest of pages. The modal content can contain any /// hierarchy of controls. It is displayed above background (in z-order) that can have a custom style applied to it. /// /// Clicking OK or Cancel in the modal popup dismisses the content and optionally runs a custom script. /// The custom script is typically used to apply changes that were made in the modal popup. If a postback /// is required, you can allow the OK or Cancel control to perform a postback. /// /// By default, the modal content is centered on the page. However, you can set absolute positiniong and /// set only X or Y to center the content vertically or horizontally. /// </summary> [Designer(typeof(ModalPopupExtenderDesigner))] [ClientScriptResource("Sys.Extended.UI.ModalPopupBehavior", Constants.ModalPopup)] [RequiredScript(typeof(CommonToolkitScripts))] [RequiredScript(typeof(DragPanelExtender))] [RequiredScript(typeof(DropShadowExtender))] [RequiredScript(typeof(AnimationExtender))] [TargetControlType(typeof(WebControl))] [TargetControlType(typeof(HtmlControl))] [TargetControlType(typeof(HiddenField))] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.ModalPopup + Constants.IconPostfix)] public class ModalPopupExtender : DynamicPopulateExtenderControlBase { // Desired visibility state: true, false or none bool? _show; Animation _onHidden, _onShown, _onHiding, _onShowing; /// <summary> /// ID of an element to display as a modal popup /// </summary> [ExtenderControlProperty] [DefaultValue("")] [IDReferenceProperty(typeof(WebControl))] [RequiredProperty] [ClientPropertyName("popupControlID")] public string PopupControlID { get { return GetPropertyValue("PopupControlID", String.Empty); } set { SetPropertyValue("PopupControlID", value); } } /// <summary> /// A CSS class to apply to the background when the modal popup is displayed /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("backgroundCssClass")] public string BackgroundCssClass { get { return GetPropertyValue("BackgroundCssClass", String.Empty); } set { SetPropertyValue("BackgroundCssClass", value); } } /// <summary> /// ID of an element that dismisses the modal popup /// </summary> [ExtenderControlProperty] [DefaultValue("")] [IDReferenceProperty(typeof(WebControl))] [ClientPropertyName("okControlID")] public string OkControlID { get { return GetPropertyValue("OkControlID", String.Empty); } set { SetPropertyValue("OkControlID", value); } } /// <summary> /// ID of an element that cancels the modal popup /// </summary> [ExtenderControlProperty] [DefaultValue("")] [IDReferenceProperty(typeof(WebControl))] [ClientPropertyName("cancelControlID")] public string CancelControlID { get { return GetPropertyValue("CancelControlID", String.Empty); } set { SetPropertyValue("CancelControlID", value); } } /// <summary> /// A script to run when the modal popup is dismissed using the element specified in OkControlID /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("onOkScript")] public string OnOkScript { get { return GetPropertyValue("OnOkScript", String.Empty); } set { SetPropertyValue("OnOkScript", value); } } /// <summary> /// A script to run when the modal popup is dismissed using the element specified in CancelControlID /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("onCancelScript")] public string OnCancelScript { get { return GetPropertyValue("OnCancelScript", String.Empty); } set { SetPropertyValue("OnCancelScript", value); } } /// <summary> /// The X coordinate of the top/left corner of the modal popup /// </summary> /// <remarks> /// If this value is not specified, the popup will be centered horizontally /// </remarks> [ExtenderControlProperty] [DefaultValue(-1)] [ClientPropertyName("x")] public int X { get { return GetPropertyValue("X", -1); } set { SetPropertyValue("X", value); } } /// <summary> /// The Y coordinate of the top/left corner of the modal popup /// </summary> /// <remarks> /// If this value is not specified, the popup will be centered vertically /// </remarks> [ExtenderControlProperty] [DefaultValue(-1)] [ClientPropertyName("y")] public int Y { get { return GetPropertyValue("Y", -1); } set { SetPropertyValue("Y", value); } } /// <summary> /// A Boolean value that specifies whether or not the modal popup can be dragged /// </summary> /// <remarks> /// This property is obsolete /// </remarks> [ExtenderControlProperty] [DefaultValue(false)] [Obsolete("The drag feature on modal popup will be automatically turned on if you specify the PopupDragHandleControlID property. Setting the Drag property is a noop")] [ClientPropertyName("drag")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public bool Drag { get { return GetPropertyValue("stringDrag", false); } set { SetPropertyValue("stringDrag", value); } } /// <summary> /// ID of the embedded element that contains a popup header and title that will /// be used as a drag handle /// </summary> [ExtenderControlProperty] [IDReferenceProperty(typeof(WebControl))] [DefaultValue("")] [ClientPropertyName("popupDragHandleControlID")] public string PopupDragHandleControlID { get { return GetPropertyValue("PopupDragHandleControlID", String.Empty); } set { SetPropertyValue("PopupDragHandleControlID", value); } } /// <summary> /// Set to True to automatically add a drop shadow to the modal popup /// </summary> [ExtenderControlProperty] [DefaultValue(false)] [ClientPropertyName("dropShadow")] public bool DropShadow { get { return GetPropertyValue("stringDropShadow", false); } set { SetPropertyValue("stringDropShadow", value); } } /// <summary> /// A value that determines if the popup must be repositioned when the window /// is resized or scrolled /// </summary> [ExtenderControlProperty] [DefaultValue(ModalPopupRepositionMode.RepositionOnWindowResizeAndScroll)] [ClientPropertyName("repositionMode")] public ModalPopupRepositionMode RepositionMode { get { return GetPropertyValue("RepositionMode", ModalPopupRepositionMode.RepositionOnWindowResizeAndScroll); } set { SetPropertyValue("RepositionMode", value); } } /// <summary> /// Animation to perform once the modal popup is shown /// </summary> [Browsable(false)] [ExtenderControlProperty] [ClientPropertyName("onShown")] public Animation OnShown { get { return GetAnimation(ref _onShown, "OnShown"); } set { SetAnimation(ref _onShown, "OnShown", value); } } /// <summary> /// Animation to perform once the modal popup is hidden /// </summary> [Browsable(false)] [ExtenderControlProperty] [ClientPropertyName("onHidden")] public Animation OnHidden { get { return GetAnimation(ref _onHidden, "OnHidden"); } set { SetAnimation(ref _onHidden, "OnHidden", value); } } /// <summary> /// Animation to perform just before the modal popup is shown /// </summary> [Browsable(false)] [ExtenderControlProperty] [ClientPropertyName("onShowing")] public Animation OnShowing { get { return GetAnimation(ref _onShowing, "OnShowing"); } set { SetAnimation(ref _onShowing, "OnShowing", value); } } /// <summary> /// Animation to perform just before the modal popup is hidden. /// The popup closes only after animation completes /// </summary> [Browsable(false)] [ExtenderControlProperty] [ClientPropertyName("onHiding")] public Animation OnHiding { get { return GetAnimation(ref _onHiding, "OnHiding"); } set { SetAnimation(ref _onHiding, "OnHiding", value); } } public void Show() { _show = true; } public void Hide() { _show = false; } protected override void OnPreRender(EventArgs e) { // If Show() or Hide() were called during the request, change the visibility now if(_show.HasValue) ChangeVisibility(_show.Value); ResolveControlIDs(_onShown); ResolveControlIDs(_onHidden); ResolveControlIDs(_onShowing); ResolveControlIDs(_onHiding); base.OnPreRender(e); } // Emit script to the client that will cause the modal popup behavior // to be shown or hidden private void ChangeVisibility(bool show) { if(TargetControl == null) throw new ArgumentNullException("TargetControl", "TargetControl property cannot be null"); var operation = show ? "show" : "hide"; if(ScriptManager.GetCurrent(Page).IsInAsyncPostBack) // RegisterDataItem is more elegant, but we can only call it during an async postback ScriptManager.GetCurrent(Page).RegisterDataItem(TargetControl, operation); else { // Add a load handler to show the popup and then remove itself var script = string.Format(CultureInfo.InvariantCulture, "(function() {{" + "var fn = function() {{" + "Sys.Extended.UI.ModalPopupBehavior.invokeViaServer('{0}', {1}); " + "Sys.Application.remove_load(fn);" + "}};" + "Sys.Application.add_load(fn);" + "}})();", BehaviorID, show ? "true" : "false"); ScriptManager.RegisterStartupScript(this, typeof(ModalPopupExtender), operation + BehaviorID, script, true); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Transport.Channels { using System; using System.Diagnostics.Contracts; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using DotNetty.Buffers; using DotNetty.Common.Concurrency; using DotNetty.Common.Utilities; public abstract class AbstractChannel : /*DefaultAttributeMap, */ IChannel { //static readonly InternalLogger logger = InternalLoggerFactory.getInstance(AbstractChannel.class); protected static readonly ClosedChannelException ClosedChannelException = new ClosedChannelException(); static readonly NotYetConnectedException NotYetConnectedException = new NotYetConnectedException(); IMessageSizeEstimatorHandle estimatorHandle; readonly IChannelUnsafe channelUnsafe; readonly DefaultChannelPipeline pipeline; readonly TaskCompletionSource closeFuture = new TaskCompletionSource(); volatile PausableChannelEventLoop eventLoop; volatile bool registered; /// <summary> Cache for the string representation of this channel /// </summary> bool strValActive; string strVal; ///// <summary> // /// Creates a new instance. // /// // /// @param parent // /// the parent of this channel. {@code null} if there's no parent. // /// </summary> //protected AbstractChannel(IChannel parent) // : this(DefaultChannelId.NewInstance()) //{ //} /// <summary> /// Creates a new instance. /// //* @param parent //* the parent of this channel. {@code null} if there's no parent. /// </summary> protected AbstractChannel(IChannel parent /*, ChannelId id*/) { this.Parent = parent; //this.Id = id; this.channelUnsafe = this.NewUnsafe(); this.pipeline = new DefaultChannelPipeline(this); } // todo: public ChannelId Id { get; private set; } public bool IsWritable { get { ChannelOutboundBuffer buf = this.channelUnsafe.OutboundBuffer; return buf != null && buf.IsWritable; } } public IChannel Parent { get; private set; } public IChannelPipeline Pipeline { get { return this.pipeline; } } public abstract IChannelConfiguration Configuration { get; } public IByteBufferAllocator Allocator { get { return this.Configuration.Allocator; } } public IEventLoop EventLoop { get { IEventLoop eventLoop = this.eventLoop; if (eventLoop == null) { throw new InvalidOperationException("channel not registered to an event loop"); } return eventLoop; } } public abstract bool Open { get; } public abstract bool Active { get; } public abstract bool DisconnectSupported { get; } public abstract EndPoint LocalAddress { get; } public abstract EndPoint RemoteAddress { get; } /// <summary> /// Reset the stored remoteAddress /// </summary> public bool Registered { get { return this.registered; } } public Task BindAsync(EndPoint localAddress) { return this.pipeline.BindAsync(localAddress); } public Task ConnectAsync(EndPoint remoteAddress) { return this.pipeline.ConnectAsync(remoteAddress); } public Task ConnectAsync(EndPoint remoteAddress, EndPoint localAddress) { return this.pipeline.ConnectAsync(remoteAddress, localAddress); } public Task DisconnectAsync() { return this.pipeline.DisconnectAsync(); } public Task CloseAsync() { return this.pipeline.CloseAsync(); } public Task DeregisterAsync() { /// <summary> /// One problem of channel deregistration is that after a channel has been deregistered /// there may still be tasks, created from within one of the channel's ChannelHandlers, /// input the {@link EventLoop}'s task queue. That way, an unfortunate twist of events could lead /// to tasks still being input the old {@link EventLoop}'s queue even after the channel has been /// registered with a new {@link EventLoop}. This would lead to the tasks being executed by two /// different {@link EventLoop}s. /// /// Our solution to this problem is to always perform the actual deregistration of /// the channel as a task and to reject any submission of new tasks, from within /// one of the channel's ChannelHandlers, until the channel is registered with /// another {@link EventLoop}. That way we can be sure that there are no more tasks regarding /// that particular channel after it has been deregistered (because the deregistration /// task is the last one.). /// /// This only works for one time tasks. To see how we handle periodic/delayed tasks have a look /// at {@link io.netty.util.concurrent.ScheduledFutureTask#run()}. /// /// Also see {@link HeadContext#deregister(ChannelHandlerContext, ChannelPromise)}. /// </summary> this.eventLoop.RejectNewTasks(); return this.pipeline.DeregisterAsync(); } public IChannel Flush() { this.pipeline.Flush(); return this; } public IChannel Read() { this.pipeline.Read(); return this; } public Task WriteAsync(object msg) { return this.pipeline.WriteAsync(msg); } public Task WriteAndFlushAsync(object message) { return this.pipeline.WriteAndFlushAsync(message); } public Task CloseCompletion { get { return this.closeFuture.Task; } } public IChannelUnsafe Unsafe { get { return this.channelUnsafe; } } /// <summary> /// Create a new {@link AbstractUnsafe} instance which will be used for the life-time of the {@link Channel} /// </summary> protected abstract IChannelUnsafe NewUnsafe(); // /// <summary> //* Returns the ID of this channel. ///// </summary> //public override int GetHashCode() //{ // return id.hashCode(); //} /// <summary> /// Returns {@code true} if and only if the specified object is identical /// with this channel (i.e: {@code this == o}). /// </summary> public override bool Equals(object o) { return this == o; } //public int CompareTo(IChannel o) //{ // if (ReferenceEquals(this, o)) // { // return 0; // } // return id().compareTo(o.id()); //} /// <summary> /// Returns the {@link String} representation of this channel. The returned /// string contains the {@linkplain #hashCode()} ID}, {@linkplain #localAddress() local address}, /// and {@linkplain #remoteAddress() remote address} of this channel for /// easier identification. /// </summary> public override string ToString() { bool active = this.Active; if (this.strValActive == active && this.strVal != null) { return this.strVal; } EndPoint remoteAddr = this.RemoteAddress; EndPoint localAddr = this.LocalAddress; if (remoteAddr != null) { EndPoint srcAddr; EndPoint dstAddr; if (this.Parent == null) { srcAddr = localAddr; dstAddr = remoteAddr; } else { srcAddr = remoteAddr; dstAddr = localAddr; } StringBuilder buf = new StringBuilder(96) .Append("[id: 0x") //.Append(id.asShortText()) .Append(", ") .Append(srcAddr) .Append(active ? " => " : " :> ") .Append(dstAddr) .Append(']'); this.strVal = buf.ToString(); } else if (localAddr != null) { StringBuilder buf = new StringBuilder(64) .Append("[id: 0x") //.Append(id.asShortText()) .Append(", ") .Append(localAddr) .Append(']'); this.strVal = buf.ToString(); } else { StringBuilder buf = new StringBuilder(16) .Append("[id: 0x") //.Append(id.asShortText()) .Append(']'); this.strVal = buf.ToString(); } this.strValActive = active; return this.strVal; } internal IMessageSizeEstimatorHandle EstimatorHandle { get { if (this.estimatorHandle == null) { this.estimatorHandle = this.Configuration.MessageSizeEstimator.NewHandle(); } return this.estimatorHandle; } } /// <summary> /// {@link Unsafe} implementation which sub-classes must extend and use. /// </summary> protected abstract class AbstractUnsafe : IChannelUnsafe { protected readonly AbstractChannel channel; ChannelOutboundBuffer outboundBuffer; IRecvByteBufAllocatorHandle recvHandle; bool inFlush0; /// <summary> true if the channel has never been registered, false otherwise /// </summary> bool neverRegistered = true; public IRecvByteBufAllocatorHandle RecvBufAllocHandle { get { if (this.recvHandle == null) { this.recvHandle = this.channel.Configuration.RecvByteBufAllocator.NewHandle(); } return this.recvHandle; } } //public ChannelHandlerInvoker invoker() { // // return the unwrapped invoker. // return ((PausableChannelEventExecutor) eventLoop().asInvoker()).unwrapInvoker(); //} protected AbstractUnsafe(AbstractChannel channel) { this.channel = channel; this.outboundBuffer = new ChannelOutboundBuffer(channel); } public ChannelOutboundBuffer OutboundBuffer { get { return this.outboundBuffer; } } public Task RegisterAsync(IEventLoop eventLoop) { Contract.Requires(eventLoop != null); if (this.channel.Registered) { return TaskEx.FromException(new InvalidOperationException("registered to an event loop already")); } if (!this.channel.IsCompatible(eventLoop)) { return TaskEx.FromException(new InvalidOperationException("incompatible event loop type: " + eventLoop.GetType().Name)); } // It's necessary to reuse the wrapped eventloop object. Otherwise the user will end up with multiple // objects that do not share a common state. if (this.channel.eventLoop == null) { this.channel.eventLoop = new PausableChannelEventLoop(this.channel, eventLoop); } else { this.channel.eventLoop.Unwrapped = eventLoop; } var promise = new TaskCompletionSource(); if (eventLoop.InEventLoop) { this.Register0(promise); } else { try { eventLoop.Execute(() => this.Register0(promise)); } catch (Exception ex) { ChannelEventSource.Log.Warning( string.Format("Force-closing a channel whose registration task was not accepted by an event loop: {0}", this.channel), ex); this.CloseForcibly(); this.channel.closeFuture.Complete(); Util.SafeSetFailure(promise, ex); } } return promise.Task; } void Register0(TaskCompletionSource promise) { try { // check if the channel is still open as it could be closed input the mean time when the register // call was outside of the eventLoop if (!promise.setUncancellable() || !this.EnsureOpen(promise)) { Util.SafeSetFailure(promise, ClosedChannelException); return; } bool firstRegistration = this.neverRegistered; this.channel.DoRegister(); this.neverRegistered = false; this.channel.registered = true; this.channel.eventLoop.AcceptNewTasks(); Util.SafeSetSuccess(promise); this.channel.pipeline.FireChannelRegistered(); // Only fire a channelActive if the channel has never been registered. This prevents firing // multiple channel actives if the channel is deregistered and re-registered. if (firstRegistration && this.channel.Active) { this.channel.pipeline.FireChannelActive(); } } catch (Exception t) { // Close the channel directly to avoid FD leak. this.CloseForcibly(); this.channel.closeFuture.Complete(); Util.SafeSetFailure(promise, t); } } public Task BindAsync(EndPoint localAddress) { // todo: cancellation support if ( /*!promise.setUncancellable() || */!this.channel.Open) { return this.CreateClosedChannelExceptionTask(); } //// See: https://github.com/netty/netty/issues/576 //if (bool.TrueString.Equals(this.channel.Configuration.getOption(ChannelOption.SO_BROADCAST)) && // localAddress is IPEndPoint && // !((IPEndPoint)localAddress).Address.getAddress().isAnyLocalAddress() && // !Environment.OSVersion.Platform == PlatformID.Win32NT && !Environment.isRoot()) //{ // // Warn a user about the fact that a non-root user can't receive a // // broadcast packet on *nix if the socket is bound on non-wildcard address. // logger.warn( // "A non-root user can't receive a broadcast packet if the socket " + // "is not bound to a wildcard address; binding to a non-wildcard " + // "address (" + localAddress + ") anyway as requested."); //} bool wasActive = this.channel.Active; var promise = new TaskCompletionSource(); try { this.channel.DoBind(localAddress); } catch (Exception t) { Util.SafeSetFailure(promise, t); this.CloseIfClosed(); return promise.Task; } if (!wasActive && this.channel.Active) { this.InvokeLater(() => this.channel.pipeline.FireChannelActive()); } this.SafeSetSuccess(promise); return promise.Task; } public abstract Task ConnectAsync(EndPoint remoteAddress, EndPoint localAddress); void SafeSetFailure(TaskCompletionSource promise, Exception cause) { Util.SafeSetFailure(promise, cause); } public Task DisconnectAsync() { var promise = new TaskCompletionSource(); if (!promise.setUncancellable()) { return promise.Task; } bool wasActive = this.channel.Active; try { this.channel.DoDisconnect(); } catch (Exception t) { this.SafeSetFailure(promise, t); this.CloseIfClosed(); return promise.Task; } if (wasActive && !this.channel.Active) { this.InvokeLater(() => this.channel.pipeline.FireChannelInactive()); } this.SafeSetSuccess(promise); this.CloseIfClosed(); // doDisconnect() might have closed the channel return promise.Task; } void SafeSetSuccess(TaskCompletionSource promise) { Util.SafeSetSuccess(promise); } public Task CloseAsync() //CancellationToken cancellationToken) { var promise = new TaskCompletionSource(); if (!promise.setUncancellable()) { return promise.Task; } //if (cancellationToken.IsCancellationRequested) //{ // return TaskEx.Cancelled; //} if (this.outboundBuffer == null) { // Only needed if no VoidChannelPromise. if (promise != TaskCompletionSource.Void) { // This means close() was called before so we just register a listener and return return this.channel.closeFuture.Task; } return promise.Task; } if (this.channel.closeFuture.Task.IsCompleted) { // Closed already. Util.SafeSetSuccess(promise); return promise.Task; } bool wasActive = this.channel.Active; ChannelOutboundBuffer buffer = this.outboundBuffer; this.outboundBuffer = null; // Disallow adding any messages and flushes to outboundBuffer. IEventExecutor closeExecutor = null; // todo closeExecutor(); if (closeExecutor != null) { closeExecutor.Execute(() => { try { // Execute the close. this.DoClose0(promise); } finally { // Call invokeLater so closeAndDeregister is executed input the EventLoop again! this.InvokeLater(() => { // Fail all the queued messages buffer.FailFlushed(ClosedChannelException, false); buffer.Close(ClosedChannelException); this.FireChannelInactiveAndDeregister(wasActive); }); } }); } else { try { // Close the channel and fail the queued messages input all cases. this.DoClose0(promise); } finally { // Fail all the queued messages. buffer.FailFlushed(ClosedChannelException, false); buffer.Close(ClosedChannelException); } if (this.inFlush0) { this.InvokeLater(() => this.FireChannelInactiveAndDeregister(wasActive)); } else { this.FireChannelInactiveAndDeregister(wasActive); } } return promise.Task; } void DoClose0(TaskCompletionSource promise) { try { this.channel.DoClose(); this.channel.closeFuture.Complete(); this.SafeSetSuccess(promise); } catch (Exception t) { this.channel.closeFuture.Complete(); this.SafeSetFailure(promise, t); } } void FireChannelInactiveAndDeregister(bool wasActive) { if (wasActive && !this.channel.Active) { this.InvokeLater(() => { this.channel.pipeline.FireChannelInactive(); this.DeregisterAsync(); }); } else { this.InvokeLater(() => this.DeregisterAsync()); } } public void CloseForcibly() { try { this.channel.DoClose(); } catch (Exception e) { ChannelEventSource.Log.Warning("Failed to close a channel.", e); } } /// <summary> /// This method must NEVER be called directly, but be executed as an /// extra task with a clean call stack instead. The reason for this /// is that this method calls {@link ChannelPipeline#fireChannelUnregistered()} /// directly, which might lead to an unfortunate nesting of independent inbound/outbound /// events. See the comments input {@link #invokeLater(Runnable)} for more details. /// </summary> public Task DeregisterAsync() { //if (!promise.setUncancellable()) //{ // return; //} if (!this.channel.registered) { return TaskEx.Completed; } try { this.channel.DoDeregister(); } catch (Exception t) { ChannelEventSource.Log.Warning("Unexpected exception occurred while deregistering a channel.", t); return TaskEx.FromException(t); } finally { if (this.channel.registered) { this.channel.registered = false; this.channel.pipeline.FireChannelUnregistered(); } else { // Some transports like local and AIO does not allow the deregistration of // an open channel. Their doDeregister() calls close(). Consequently, // close() calls deregister() again - no need to fire channelUnregistered. } } return TaskEx.Completed; } public void BeginRead() { if (!this.channel.Active) { return; } try { this.channel.DoBeginRead(); } catch (Exception e) { this.InvokeLater(() => this.channel.pipeline.FireExceptionCaught(e)); this.CloseAsync(); } } public Task WriteAsync(object msg) { ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; if (outboundBuffer == null) { // If the outboundBuffer is null we know the channel was closed and so // need to fail the future right away. If it is not null the handling of the rest // will be done input flush0() // See https://github.com/netty/netty/issues/2362 // release message now to prevent resource-leak ReferenceCountUtil.Release(msg); return TaskEx.FromException(ClosedChannelException); } int size; try { msg = this.channel.FilterOutboundMessage(msg); size = this.channel.EstimatorHandle.Size(msg); if (size < 0) { size = 0; } } catch (Exception t) { ReferenceCountUtil.Release(msg); return TaskEx.FromException(t); } var promise = new TaskCompletionSource(); outboundBuffer.AddMessage(msg, size, promise); return promise.Task; } public void Flush() { ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; if (outboundBuffer == null) { return; } outboundBuffer.AddFlush(); this.Flush0(); } protected virtual void Flush0() { if (this.inFlush0) { // Avoid re-entrance return; } ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; if (outboundBuffer == null || outboundBuffer.IsEmpty) { return; } this.inFlush0 = true; // Mark all pending write requests as failure if the channel is inactive. if (!this.channel.Active) { try { if (this.channel.Open) { outboundBuffer.FailFlushed(NotYetConnectedException, true); } else { // Do not trigger channelWritabilityChanged because the channel is closed already. outboundBuffer.FailFlushed(ClosedChannelException, false); } } finally { this.inFlush0 = false; } return; } try { this.channel.DoWrite(outboundBuffer); } catch (Exception t) { outboundBuffer.FailFlushed(t, true); } finally { this.inFlush0 = false; } } protected bool EnsureOpen(TaskCompletionSource promise) { if (this.channel.Open) { return true; } Util.SafeSetFailure(promise, ClosedChannelException); return false; } protected Task CreateClosedChannelExceptionTask() { return TaskEx.FromException(ClosedChannelException); } protected void CloseIfClosed() { if (this.channel.Open) { return; } this.CloseAsync(); } void InvokeLater(Action task) { try { // This method is used by outbound operation implementations to trigger an inbound event later. // They do not trigger an inbound event immediately because an outbound operation might have been // triggered by another inbound event handler method. If fired immediately, the call stack // will look like this for example: // // handlerA.inboundBufferUpdated() - (1) an inbound handler method closes a connection. // -> handlerA.ctx.close() // -> channel.unsafe.close() // -> handlerA.channelInactive() - (2) another inbound handler method called while input (1) yet // // which means the execution of two inbound handler methods of the same handler overlap undesirably. this.channel.EventLoop.Execute(task); } catch (RejectedExecutionException e) { ChannelEventSource.Log.Warning("Can't invoke task later as EventLoop rejected it", e); } } protected Exception AnnotateConnectException(Exception exception, EndPoint remoteAddress) { if (exception is SocketException) { return new ConnectException("LogError connecting to " + remoteAddress, exception); } return exception; } // /// <summary> //* @return {@link EventLoop} to execute {@link #doClose()} or {@code null} if it should be done input the //* {@link EventLoop}. //+ ///// </summary> // protected IEventExecutor closeExecutor() // { // return null; // } } /// <summary> /// Return {@code true} if the given {@link EventLoop} is compatible with this instance. /// </summary> protected abstract bool IsCompatible(IEventLoop eventLoop); /// <summary> /// Is called after the {@link Channel} is registered with its {@link EventLoop} as part of the register process. /// /// Sub-classes may override this method /// </summary> protected virtual void DoRegister() { // NOOP } /// <summary> /// Bind the {@link Channel} to the {@link EndPoint} /// </summary> protected abstract void DoBind(EndPoint localAddress); /// <summary> /// Disconnect this {@link Channel} from its remote peer /// </summary> protected abstract void DoDisconnect(); /// <summary> /// Close the {@link Channel} /// </summary> protected abstract void DoClose(); /// <summary> /// Deregister the {@link Channel} from its {@link EventLoop}. /// /// Sub-classes may override this method /// </summary> protected virtual void DoDeregister() { // NOOP } /// <summary> /// Schedule a read operation. /// </summary> protected abstract void DoBeginRead(); /// <summary> /// Flush the content of the given buffer to the remote peer. /// </summary> protected abstract void DoWrite(ChannelOutboundBuffer input); /// <summary> /// Invoked when a new message is added to a {@link ChannelOutboundBuffer} of this {@link AbstractChannel}, so that /// the {@link Channel} implementation converts the message to another. (e.g. heap buffer -> direct buffer) /// </summary> protected virtual object FilterOutboundMessage(object msg) { return msg; } sealed class PausableChannelEventLoop : PausableChannelEventExecutor, IEventLoop { volatile bool isAcceptingNewTasks = true; public volatile IEventLoop Unwrapped; readonly IChannel channel; public PausableChannelEventLoop(IChannel channel, IEventLoop unwrapped) { this.channel = channel; this.Unwrapped = unwrapped; } public override void RejectNewTasks() { this.isAcceptingNewTasks = false; } public override void AcceptNewTasks() { this.isAcceptingNewTasks = true; } public override bool IsAcceptingNewTasks { get { return this.isAcceptingNewTasks; } } public override IEventLoop Unwrap() { return this.Unwrapped; } public IChannelHandlerInvoker Invoker { get { return this.Unwrap().Invoker; } } public Task RegisterAsync(IChannel c) { return this.Unwrap().RegisterAsync(c); } internal override IChannel Channel { get { return this.channel; } } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Redshift.Model { /// <summary> /// Describes a snapshot. /// </summary> public partial class Snapshot { private List<AccountWithRestoreAccess> _accountsWithRestoreAccess = new List<AccountWithRestoreAccess>(); private double? _actualIncrementalBackupSizeInMegaBytes; private string _availabilityZone; private double? _backupProgressInMegaBytes; private DateTime? _clusterCreateTime; private string _clusterIdentifier; private string _clusterVersion; private double? _currentBackupRateInMegaBytesPerSecond; private string _dbName; private long? _elapsedTimeInSeconds; private bool? _encrypted; private bool? _encryptedWithHSM; private long? _estimatedSecondsToCompletion; private string _kmsKeyId; private string _masterUsername; private string _nodeType; private int? _numberOfNodes; private string _ownerAccount; private int? _port; private List<string> _restorableNodeTypes = new List<string>(); private DateTime? _snapshotCreateTime; private string _snapshotIdentifier; private string _snapshotType; private string _sourceRegion; private string _status; private List<Tag> _tags = new List<Tag>(); private double? _totalBackupSizeInMegaBytes; private string _vpcId; /// <summary> /// Gets and sets the property AccountsWithRestoreAccess. /// <para> /// A list of the AWS customer accounts authorized to restore the snapshot. Returns <code>null</code> /// if no accounts are authorized. Visible only to the snapshot owner. /// </para> /// </summary> public List<AccountWithRestoreAccess> AccountsWithRestoreAccess { get { return this._accountsWithRestoreAccess; } set { this._accountsWithRestoreAccess = value; } } // Check to see if AccountsWithRestoreAccess property is set internal bool IsSetAccountsWithRestoreAccess() { return this._accountsWithRestoreAccess != null && this._accountsWithRestoreAccess.Count > 0; } /// <summary> /// Gets and sets the property ActualIncrementalBackupSizeInMegaBytes. /// <para> /// The size of the incremental backup. /// </para> /// </summary> public double ActualIncrementalBackupSizeInMegaBytes { get { return this._actualIncrementalBackupSizeInMegaBytes.GetValueOrDefault(); } set { this._actualIncrementalBackupSizeInMegaBytes = value; } } // Check to see if ActualIncrementalBackupSizeInMegaBytes property is set internal bool IsSetActualIncrementalBackupSizeInMegaBytes() { return this._actualIncrementalBackupSizeInMegaBytes.HasValue; } /// <summary> /// Gets and sets the property AvailabilityZone. /// <para> /// The Availability Zone in which the cluster was created. /// </para> /// </summary> public string AvailabilityZone { get { return this._availabilityZone; } set { this._availabilityZone = value; } } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this._availabilityZone != null; } /// <summary> /// Gets and sets the property BackupProgressInMegaBytes. /// <para> /// The number of megabytes that have been transferred to the snapshot backup. /// </para> /// </summary> public double BackupProgressInMegaBytes { get { return this._backupProgressInMegaBytes.GetValueOrDefault(); } set { this._backupProgressInMegaBytes = value; } } // Check to see if BackupProgressInMegaBytes property is set internal bool IsSetBackupProgressInMegaBytes() { return this._backupProgressInMegaBytes.HasValue; } /// <summary> /// Gets and sets the property ClusterCreateTime. /// <para> /// The time (UTC) when the cluster was originally created. /// </para> /// </summary> public DateTime ClusterCreateTime { get { return this._clusterCreateTime.GetValueOrDefault(); } set { this._clusterCreateTime = value; } } // Check to see if ClusterCreateTime property is set internal bool IsSetClusterCreateTime() { return this._clusterCreateTime.HasValue; } /// <summary> /// Gets and sets the property ClusterIdentifier. /// <para> /// The identifier of the cluster for which the snapshot was taken. /// </para> /// </summary> public string ClusterIdentifier { get { return this._clusterIdentifier; } set { this._clusterIdentifier = value; } } // Check to see if ClusterIdentifier property is set internal bool IsSetClusterIdentifier() { return this._clusterIdentifier != null; } /// <summary> /// Gets and sets the property ClusterVersion. /// <para> /// The version ID of the Amazon Redshift engine that is running on the cluster. /// </para> /// </summary> public string ClusterVersion { get { return this._clusterVersion; } set { this._clusterVersion = value; } } // Check to see if ClusterVersion property is set internal bool IsSetClusterVersion() { return this._clusterVersion != null; } /// <summary> /// Gets and sets the property CurrentBackupRateInMegaBytesPerSecond. /// <para> /// The number of megabytes per second being transferred to the snapshot backup. Returns /// <code>0</code> for a completed backup. /// </para> /// </summary> public double CurrentBackupRateInMegaBytesPerSecond { get { return this._currentBackupRateInMegaBytesPerSecond.GetValueOrDefault(); } set { this._currentBackupRateInMegaBytesPerSecond = value; } } // Check to see if CurrentBackupRateInMegaBytesPerSecond property is set internal bool IsSetCurrentBackupRateInMegaBytesPerSecond() { return this._currentBackupRateInMegaBytesPerSecond.HasValue; } /// <summary> /// Gets and sets the property DBName. /// <para> /// The name of the database that was created when the cluster was created. /// </para> /// </summary> public string DBName { get { return this._dbName; } set { this._dbName = value; } } // Check to see if DBName property is set internal bool IsSetDBName() { return this._dbName != null; } /// <summary> /// Gets and sets the property ElapsedTimeInSeconds. /// <para> /// The amount of time an in-progress snapshot backup has been running, or the amount /// of time it took a completed backup to finish. /// </para> /// </summary> public long ElapsedTimeInSeconds { get { return this._elapsedTimeInSeconds.GetValueOrDefault(); } set { this._elapsedTimeInSeconds = value; } } // Check to see if ElapsedTimeInSeconds property is set internal bool IsSetElapsedTimeInSeconds() { return this._elapsedTimeInSeconds.HasValue; } /// <summary> /// Gets and sets the property Encrypted. /// <para> /// If <code>true</code>, the data in the snapshot is encrypted at rest. /// </para> /// </summary> public bool Encrypted { get { return this._encrypted.GetValueOrDefault(); } set { this._encrypted = value; } } // Check to see if Encrypted property is set internal bool IsSetEncrypted() { return this._encrypted.HasValue; } /// <summary> /// Gets and sets the property EncryptedWithHSM. /// <para> /// A boolean that indicates whether the snapshot data is encrypted using the HSM keys /// of the source cluster. <code>true</code> indicates that the data is encrypted using /// HSM keys. /// </para> /// </summary> public bool EncryptedWithHSM { get { return this._encryptedWithHSM.GetValueOrDefault(); } set { this._encryptedWithHSM = value; } } // Check to see if EncryptedWithHSM property is set internal bool IsSetEncryptedWithHSM() { return this._encryptedWithHSM.HasValue; } /// <summary> /// Gets and sets the property EstimatedSecondsToCompletion. /// <para> /// The estimate of the time remaining before the snapshot backup will complete. Returns /// <code>0</code> for a completed backup. /// </para> /// </summary> public long EstimatedSecondsToCompletion { get { return this._estimatedSecondsToCompletion.GetValueOrDefault(); } set { this._estimatedSecondsToCompletion = value; } } // Check to see if EstimatedSecondsToCompletion property is set internal bool IsSetEstimatedSecondsToCompletion() { return this._estimatedSecondsToCompletion.HasValue; } /// <summary> /// Gets and sets the property KmsKeyId. /// <para> /// The AWS Key Management Service (KMS) key ID of the encryption key that was used to /// encrypt data in the cluster from which the snapshot was taken. /// </para> /// </summary> public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } // Check to see if KmsKeyId property is set internal bool IsSetKmsKeyId() { return this._kmsKeyId != null; } /// <summary> /// Gets and sets the property MasterUsername. /// <para> /// The master user name for the cluster. /// </para> /// </summary> public string MasterUsername { get { return this._masterUsername; } set { this._masterUsername = value; } } // Check to see if MasterUsername property is set internal bool IsSetMasterUsername() { return this._masterUsername != null; } /// <summary> /// Gets and sets the property NodeType. /// <para> /// The node type of the nodes in the cluster. /// </para> /// </summary> public string NodeType { get { return this._nodeType; } set { this._nodeType = value; } } // Check to see if NodeType property is set internal bool IsSetNodeType() { return this._nodeType != null; } /// <summary> /// Gets and sets the property NumberOfNodes. /// <para> /// The number of nodes in the cluster. /// </para> /// </summary> public int NumberOfNodes { get { return this._numberOfNodes.GetValueOrDefault(); } set { this._numberOfNodes = value; } } // Check to see if NumberOfNodes property is set internal bool IsSetNumberOfNodes() { return this._numberOfNodes.HasValue; } /// <summary> /// Gets and sets the property OwnerAccount. /// <para> /// For manual snapshots, the AWS customer account used to create or copy the snapshot. /// For automatic snapshots, the owner of the cluster. The owner can perform all snapshot /// actions, such as sharing a manual snapshot. /// </para> /// </summary> public string OwnerAccount { get { return this._ownerAccount; } set { this._ownerAccount = value; } } // Check to see if OwnerAccount property is set internal bool IsSetOwnerAccount() { return this._ownerAccount != null; } /// <summary> /// Gets and sets the property Port. /// <para> /// The port that the cluster is listening on. /// </para> /// </summary> public int Port { get { return this._port.GetValueOrDefault(); } set { this._port = value; } } // Check to see if Port property is set internal bool IsSetPort() { return this._port.HasValue; } /// <summary> /// Gets and sets the property RestorableNodeTypes. /// <para> /// The list of node types that this cluster snapshot is able to restore into. /// </para> /// </summary> public List<string> RestorableNodeTypes { get { return this._restorableNodeTypes; } set { this._restorableNodeTypes = value; } } // Check to see if RestorableNodeTypes property is set internal bool IsSetRestorableNodeTypes() { return this._restorableNodeTypes != null && this._restorableNodeTypes.Count > 0; } /// <summary> /// Gets and sets the property SnapshotCreateTime. /// <para> /// The time (UTC) when Amazon Redshift began the snapshot. A snapshot contains a copy /// of the cluster data as of this exact time. /// </para> /// </summary> public DateTime SnapshotCreateTime { get { return this._snapshotCreateTime.GetValueOrDefault(); } set { this._snapshotCreateTime = value; } } // Check to see if SnapshotCreateTime property is set internal bool IsSetSnapshotCreateTime() { return this._snapshotCreateTime.HasValue; } /// <summary> /// Gets and sets the property SnapshotIdentifier. /// <para> /// The snapshot identifier that is provided in the request. /// </para> /// </summary> public string SnapshotIdentifier { get { return this._snapshotIdentifier; } set { this._snapshotIdentifier = value; } } // Check to see if SnapshotIdentifier property is set internal bool IsSetSnapshotIdentifier() { return this._snapshotIdentifier != null; } /// <summary> /// Gets and sets the property SnapshotType. /// <para> /// The snapshot type. Snapshots created using <a>CreateClusterSnapshot</a> and <a>CopyClusterSnapshot</a> /// will be of type "manual". /// </para> /// </summary> public string SnapshotType { get { return this._snapshotType; } set { this._snapshotType = value; } } // Check to see if SnapshotType property is set internal bool IsSetSnapshotType() { return this._snapshotType != null; } /// <summary> /// Gets and sets the property SourceRegion. /// <para> /// The source region from which the snapshot was copied. /// </para> /// </summary> public string SourceRegion { get { return this._sourceRegion; } set { this._sourceRegion = value; } } // Check to see if SourceRegion property is set internal bool IsSetSourceRegion() { return this._sourceRegion != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// The snapshot status. The value of the status depends on the API operation used. <ul> /// <li> <a>CreateClusterSnapshot</a> and <a>CopyClusterSnapshot</a> returns status as /// "creating". </li> <li> <a>DescribeClusterSnapshots</a> returns status as "creating", /// "available", "final snapshot", or "failed".</li> <li> <a>DeleteClusterSnapshot</a> /// returns status as "deleted".</li> </ul> /// </para> /// </summary> public string Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// The list of tags for the cluster snapshot. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property TotalBackupSizeInMegaBytes. /// <para> /// The size of the complete set of backup data that would be used to restore the cluster. /// /// </para> /// </summary> public double TotalBackupSizeInMegaBytes { get { return this._totalBackupSizeInMegaBytes.GetValueOrDefault(); } set { this._totalBackupSizeInMegaBytes = value; } } // Check to see if TotalBackupSizeInMegaBytes property is set internal bool IsSetTotalBackupSizeInMegaBytes() { return this._totalBackupSizeInMegaBytes.HasValue; } /// <summary> /// Gets and sets the property VpcId. /// <para> /// The VPC identifier of the cluster if the snapshot is from a cluster in a VPC. Otherwise, /// this field is not in the output. /// </para> /// </summary> public string VpcId { get { return this._vpcId; } set { this._vpcId = value; } } // Check to see if VpcId property is set internal bool IsSetVpcId() { return this._vpcId != 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. using System.ComponentModel; using System.Runtime.InteropServices; using System.Threading; using System.Linq; using Xunit; using System.Threading.Tasks; namespace System.Diagnostics.Tests { public class ProcessThreadTests : ProcessTestBase { [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestCommonPriorityAndTimeProperties() { CreateDefaultProcess(); ProcessThreadCollection threadCollection = _process.Threads; Assert.True(threadCollection.Count > 0); ProcessThread thread = threadCollection[0]; try { if (ThreadState.Terminated != thread.ThreadState) { // On OSX, thread id is a 64bit unsigned value. We truncate the ulong to int // due to .NET API surface area. Hence, on overflow id can be negative while // casting the ulong to int. Assert.True(thread.Id >= 0 || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)); Assert.Equal(_process.BasePriority, thread.BasePriority); Assert.True(thread.CurrentPriority >= 0); Assert.True(thread.PrivilegedProcessorTime.TotalSeconds >= 0); Assert.True(thread.UserProcessorTime.TotalSeconds >= 0); Assert.True(thread.TotalProcessorTime.TotalSeconds >= 0); } } catch (Exception e) when (e is Win32Exception || e is InvalidOperationException) { // Win32Exception is thrown when getting threadinfo fails, or // InvalidOperationException if it fails because the thread already exited. } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestThreadCount() { int numOfThreads = 10; CountdownEvent counter = new CountdownEvent(numOfThreads); ManualResetEventSlim mre = new ManualResetEventSlim(); for (int i = 0; i < numOfThreads; i++) { new Thread(() => { counter.Signal(); mre.Wait(); }) { IsBackground = true }.Start(); } counter.Wait(); try { Assert.True(Process.GetCurrentProcess().Threads.Count >= numOfThreads); } finally { mre.Set(); } } [Fact] [PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)] // OSX and FreeBSD throw PNSE from StartTime public void TestStartTimeProperty_OSX() { using (Process p = Process.GetCurrentProcess()) { ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); ProcessThread thread = threads[0]; Assert.NotNull(thread); Assert.Throws<PlatformNotSupportedException>(() => thread.StartTime); } } [Fact] [PlatformSpecific(TestPlatforms.Linux|TestPlatforms.Windows)] // OSX and FreeBSD throw PNSE from StartTime [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public async Task TestStartTimeProperty() { TimeSpan allowedWindow = TimeSpan.FromSeconds(2); using (Process p = Process.GetCurrentProcess()) { // Get the process' start time DateTime startTime = p.StartTime.ToUniversalTime(); // Get the process' threads ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); // Get the current time DateTime curTime = DateTime.UtcNow; // Make sure each thread's start time is at least the process' // start time and not beyond the current time. int passed = 0; foreach (ProcessThread t in threads.Cast<ProcessThread>()) { try { Assert.InRange(t.StartTime.ToUniversalTime(), startTime - allowedWindow, curTime + allowedWindow); passed++; } catch (InvalidOperationException) { // The thread may have gone away between our getting its info and attempting to access its StartTime } } Assert.True(passed > 0, "Expected at least one thread to be valid for StartTime"); // Now add a thread, and from that thread, while it's still alive, verify // that there's at least one thread greater than the current time we previously grabbed. await Task.Factory.StartNew(() => { p.Refresh(); try { var newest = p.Threads.Cast<ProcessThread>().OrderBy(t => t.StartTime.ToUniversalTime()).Last(); Assert.InRange(newest.StartTime.ToUniversalTime(), curTime - allowedWindow, DateTime.Now.ToUniversalTime() + allowedWindow); } catch (InvalidOperationException) { // A thread may have gone away between our getting its info and attempting to access its StartTime } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestStartAddressProperty() { using (Process p = Process.GetCurrentProcess()) { ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); IntPtr startAddress = threads[0].StartAddress; // There's nothing we can really validate about StartAddress, other than that we can get its value // without throwing. All values (even zero) are valid on all platforms. } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPriorityLevelProperty() { CreateDefaultProcess(); ProcessThread thread = _process.Threads[0]; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel); Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal); return; } ThreadPriorityLevel originalPriority = thread.PriorityLevel; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal); return; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD"))) { Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal); return; } try { thread.PriorityLevel = ThreadPriorityLevel.AboveNormal; Assert.Equal(ThreadPriorityLevel.AboveNormal, thread.PriorityLevel); } finally { thread.PriorityLevel = originalPriority; Assert.Equal(originalPriority, thread.PriorityLevel); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestThreadStateProperty() { CreateDefaultProcess(); ProcessThread thread = _process.Threads[0]; if (ThreadState.Wait != thread.ThreadState) { Assert.Throws<InvalidOperationException>(() => thread.WaitReason); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void Threads_GetMultipleTimes_ReturnsSameInstance() { CreateDefaultProcess(); Assert.Same(_process.Threads, _process.Threads); } [Fact] public void Threads_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.Threads); } } }
#region License /* * Copyright 2002-2010 the original author or 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. */ #endregion #region using System; using System.Collections.Specialized; using Common.Logging; using GemStone.GemFire.Cache; using Spring.Dao; using Spring.Dao.Support; using Spring.Objects.Factory; using Spring.Util; using Properties=GemStone.GemFire.Cache.Properties; #endregion namespace Spring.Data.GemFire { /// <summary> /// Factory used for configuring a Gemfire Cache manager. Allows either retrieval of an existing, opened cache /// or the creation of a new one. /// </summary> /// <remarks>This class implements the <see cref="IPersistenceExceptionTranslator"/> interface, as /// auto-detected by Spring's PersistenceExceptionTranslationPostProcessor for AOP-based translation of /// native exceptions to Spring DataAccessExceptions. Hence, the presence of this class automatically enables /// a PersistenceExceptionTranslationPostProcessor to translate GemFire exceptions. /// </remarks> /// <author>Costin Leau</author> /// <author>Mark Pollack (.NET)</author> public class CacheFactoryObject : IDisposable, IInitializingObject, IObjectNameAware, IFactoryObject, IPersistenceExceptionTranslator { #region Fields protected static readonly ILog log = LogManager.GetLogger(typeof (CacheFactoryObject)); private static readonly string DEFAULT_DISTRIBUTED_SYSTEM_NAME = "DistributedSystemDotNet"; private static readonly string DEFAULT_CACHE_NAME = ""; private Cache cache; private string distributedSystemName = DEFAULT_DISTRIBUTED_SYSTEM_NAME; private string name = DEFAULT_CACHE_NAME; private bool disconnectOnClose = true; private bool keepAliveOnClose = true; private DistributedSystem system; private NameValueCollection properties; private string cacheXml; #endregion #region Properties /// <summary> /// Sets the name of the distributed system. /// </summary> /// <value>The name of the distributed system.</value> public string DistributedSystemName { set { distributedSystemName = value; } } /// <summary> /// Sets the properties used to configure the Gemfire Cache. These are copied into /// a GemStone.GemFire.Cache.Properties object and used to initialize the DistributedSystem. /// </summary> /// <value>The properties used to configure the cache..</value> public NameValueCollection Properties { set { properties = value; } } /// <summary> /// Sets the name of the cache XML that can be used to configure the cache. /// </summary> /// <value>The cache XML.</value> public string CacheXml { set { cacheXml = value; } } /// <summary> /// Sets a value indicating whether to call DistributedSystem.Disconnect when this object is /// disposed. There is a bug in the 3.0.0.9 client that may hang calls to close. The default is /// true, set to false if you experience a hang in the application. /// </summary> /// <value><c>true</c> to call DistributedSystem.Disconnect when this object is dispose; otherwise, <c>false</c>.</value> public bool DisconnectOnClose { set { disconnectOnClose = value; } } /// <summary> /// Sets a value indicating whether to call cache.close(keepalive) which determines /// whether to keep a durable client's queue alive. /// </summary> /// <value><c>true</c> call keep alive on close; otherwise, <c>false</c>.</value> public bool KeepAliveOnClose { set { keepAliveOnClose = value; } } #endregion /// <summary> /// Initialization callback called by Spring. Responsible for connecting to the distributed system /// and creating the cache. /// </summary> public void AfterPropertiesSet() { AssertUtils.ArgumentNotNull("name", name, "Cache name can not be null"); Properties gemfirePropertes = MergePropertes(); if (DistributedSystem.IsConnected) { DistributedSystem.Disconnect(); } system = DistributedSystem.Connect(distributedSystemName, gemfirePropertes); log.Info("Connected to Distributed System [" + system.Name + "]"); // first look for open caches String msg = null; try { cache = CacheFactory.GetInstance(system); msg = "Retrieved existing"; } catch (Exception) { if (cacheXml == null) { cache = CacheFactory.Create(name, system); } else { //TODO call Create method that takes CacheAttributes cache = CacheFactory.Create(name, system, cacheXml); log.Debug("Initialized cache from " + cacheXml); } //TODO call Create method that takes CacheAttributes msg = "Created"; } log.Info(msg + " GemFire v." + CacheFactory.Version + " Cache ['" + cache.Name + "']"); } protected bool IsDurableClient { get { return (properties != null && properties["durable-client-id"] != null); } } private Properties MergePropertes() { GemStone.GemFire.Cache.Properties gemfirePropertes = GemStone.GemFire.Cache.Properties.Create(); if (properties != null) { foreach (string key in properties.Keys) { gemfirePropertes.Insert(key, properties[key]); if (key.Equals("name")) { this.name = properties[key]; } } } return gemfirePropertes; } /// <summary> /// Closes the cache and disconnects from the distributed system. /// </summary> public void Dispose() { if (cache != null && !cache.IsClosed) { if (IsDurableClient) { log.Info("Closing durable client with keepalive = " + keepAliveOnClose); cache.Close(keepAliveOnClose); } else { cache.Close(); } } cache = null; if (disconnectOnClose) { if (system != null && DistributedSystem.IsConnected) { DistributedSystem.Disconnect(); } system = null; } } /// <summary> /// Translate the given exception thrown by a persistence framework to a /// corresponding exception from Spring's generic DataAccessException hierarchy, /// if possible. /// </summary> /// <param name="ex">The exception thrown.</param> /// <returns> /// the corresponding DataAccessException (or <code>null</code> if the /// exception could not be translated, as in this case it may result from /// user code rather than an actual persistence problem) /// </returns> /// <remarks> /// <para> /// Do not translate exceptions that are not understand by this translator: /// for example, if coming from another persistence framework, or resulting /// from user code and unrelated to persistence. /// </para> /// <para> /// Of particular importance is the correct translation to <see cref="T:Spring.Dao.DataIntegrityViolationException"/> /// for example on constraint violation. Implementations may use Spring ADO.NET Framework's /// sophisticated exception translation to provide further information in the event of SQLException as a root cause. /// </para> /// </remarks> /// <seealso cref="T:Spring.Dao.DataIntegrityViolationException"/> /// <seealso cref="T:Spring.Data.Support.ErrorCodeExceptionTranslator"/> /// <author>Rod Johnson</author> /// <author>Juergen Hoeller</author> /// <author>Mark Pollack (.NET)</author> public DataAccessException TranslateExceptionIfPossible(Exception ex) { if (ex is GemFireException) { return GemFireCacheUtils.ConvertGemFireAccessException((GemFireException) ex); } log.Info("Could not translate exception of type " + ex.GetType()); return null; } /// <summary> /// Returns the cache object /// </summary> /// <returns>The cache object</returns> public object GetObject() { return cache; } /// <summary> /// Returns Gemstone.GemFire.Cache.Cache /// </summary> public Type ObjectType { get { return typeof (Cache); } } /// <summary> /// Returns true /// </summary> public bool IsSingleton { get { return true; } } /// <summary> /// Sets the name of the cache to the name of the Spring object definition. Can be overrided by /// specifying 'name' as the key in the Properties collection. /// </summary> public string ObjectName { set { this.name = value; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/reservations/reservation_contact_person.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Booking.Reservations { /// <summary>Holder for reflection information generated from booking/reservations/reservation_contact_person.proto</summary> public static partial class ReservationContactPersonReflection { #region Descriptor /// <summary>File descriptor for booking/reservations/reservation_contact_person.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ReservationContactPersonReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjVib29raW5nL3Jlc2VydmF0aW9ucy9yZXNlcnZhdGlvbl9jb250YWN0X3Bl", "cnNvbi5wcm90bxIgaG9sbXMudHlwZXMuYm9va2luZy5yZXNlcnZhdGlvbnMa", "PWJvb2tpbmcvaW5kaWNhdG9ycy9yZXNlcnZhdGlvbl9jb250YWN0X3BlcnNv", "bl9pbmRpY2F0b3IucHJvdG8ijQEKGFJlc2VydmF0aW9uQ29udGFjdFBlcnNv", "bhJUCgllbnRpdHlfaWQYASABKAsyQS5ob2xtcy50eXBlcy5ib29raW5nLmlu", "ZGljYXRvcnMuUmVzZXJ2YXRpb25Db250YWN0UGVyc29uSW5kaWNhdG9yEgwK", "BG5hbWUYAiABKAkSDQoFZW1haWwYAyABKAlCOVoUYm9va2luZy9yZXNlcnZh", "dGlvbnOqAiBIT0xNUy5UeXBlcy5Cb29raW5nLlJlc2VydmF0aW9uc2IGcHJv", "dG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationContactPersonIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Reservations.ReservationContactPerson), global::HOLMS.Types.Booking.Reservations.ReservationContactPerson.Parser, new[]{ "EntityId", "Name", "Email" }, null, null, null) })); } #endregion } #region Messages public sealed partial class ReservationContactPerson : pb::IMessage<ReservationContactPerson> { private static readonly pb::MessageParser<ReservationContactPerson> _parser = new pb::MessageParser<ReservationContactPerson>(() => new ReservationContactPerson()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ReservationContactPerson> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.Reservations.ReservationContactPersonReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationContactPerson() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationContactPerson(ReservationContactPerson other) : this() { EntityId = other.entityId_ != null ? other.EntityId.Clone() : null; name_ = other.name_; email_ = other.email_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationContactPerson Clone() { return new ReservationContactPerson(this); } /// <summary>Field number for the "entity_id" field.</summary> public const int EntityIdFieldNumber = 1; private global::HOLMS.Types.Booking.Indicators.ReservationContactPersonIndicator entityId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.ReservationContactPersonIndicator EntityId { get { return entityId_; } set { entityId_ = value; } } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 2; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "email" field.</summary> public const int EmailFieldNumber = 3; private string email_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Email { get { return email_; } set { email_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ReservationContactPerson); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ReservationContactPerson other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(EntityId, other.EntityId)) return false; if (Name != other.Name) return false; if (Email != other.Email) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (entityId_ != null) hash ^= EntityId.GetHashCode(); if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Email.Length != 0) hash ^= Email.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (entityId_ != null) { output.WriteRawTag(10); output.WriteMessage(EntityId); } if (Name.Length != 0) { output.WriteRawTag(18); output.WriteString(Name); } if (Email.Length != 0) { output.WriteRawTag(26); output.WriteString(Email); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (entityId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId); } if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Email.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Email); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ReservationContactPerson other) { if (other == null) { return; } if (other.entityId_ != null) { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.ReservationContactPersonIndicator(); } EntityId.MergeFrom(other.EntityId); } if (other.Name.Length != 0) { Name = other.Name; } if (other.Email.Length != 0) { Email = other.Email; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.ReservationContactPersonIndicator(); } input.ReadMessage(entityId_); break; } case 18: { Name = input.ReadString(); break; } case 26: { Email = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
//--------------------------------------------------------------------------- // File: ScrollChrome.cs // // Description: // Implementation of chrome for scrollbar and combobox buttons and thumbs in Luna. // // Copyright (C) 2004 by Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Windows.Shapes; using System.Windows.Controls; using System.Diagnostics; using System.Threading; using System.Windows; using System.Windows.Media; using System.Windows.Media.Animation; using MS.Internal; namespace Microsoft.Windows.Themes { /// <summary> /// The ScrollChrome element /// This element is a theme-specific type that is used as an optimization /// for a common complex rendering used in Aero /// </summary> public sealed class ScrollChrome : FrameworkElement { #region Constructors static ScrollChrome() { IsEnabledProperty.OverrideMetadata(typeof(ScrollChrome), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnEnabledChanged))); } /// <summary> /// Instantiates a new instance of a ScrollChrome with no parent element. /// </summary> public ScrollChrome() { } #endregion Constructors #region Dynamic Properties /// <summary> /// Attached DependencyProperty to assign the orientation and type of the glyph /// </summary> public static readonly DependencyProperty ScrollGlyphProperty = DependencyProperty.RegisterAttached( "ScrollGlyph", typeof(ScrollGlyph), typeof(ScrollChrome), new FrameworkPropertyMetadata( ScrollGlyph.None, FrameworkPropertyMetadataOptions.AffectsRender), new ValidateValueCallback(IsValidScrollGlyph)); /// <summary> /// Gets the value of the ScrollGlyph property on the object. /// </summary> /// <param name="element">The element to which the property is attached.</param> /// <returns>The value of the property.</returns> public static ScrollGlyph GetScrollGlyph(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return (ScrollGlyph) element.GetValue(ScrollGlyphProperty); } /// <summary> /// Attachs the value to the object. /// </summary> /// <param name="element">The element on which the value will be attached.</param> /// <param name="value">The value to attach.</param> public static void SetScrollGlyph(DependencyObject element, ScrollGlyph value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(ScrollGlyphProperty, value); } private ScrollGlyph ScrollGlyph { get { return (ScrollGlyph) GetValue(ScrollGlyphProperty); } } private static bool IsValidScrollGlyph(object o) { ScrollGlyph glyph = (ScrollGlyph)o; return glyph == ScrollGlyph.None || glyph == ScrollGlyph.LeftArrow || glyph == ScrollGlyph.RightArrow || glyph == ScrollGlyph.UpArrow || glyph == ScrollGlyph.DownArrow || glyph == ScrollGlyph.VerticalGripper || glyph == ScrollGlyph.HorizontalGripper; } private static void OnEnabledChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ScrollChrome chrome = ((ScrollChrome)o); if (chrome.Animates) { if (((bool)e.NewValue)) { if (chrome._localResources == null) { chrome._localResources = new LocalResources(); chrome.InvalidateVisual(); } Duration duration = new Duration(TimeSpan.FromSeconds(0.3)); if (chrome._scrollGlyph == ScrollGlyph.HorizontalGripper || chrome._scrollGlyph == ScrollGlyph.VerticalGripper) { DoubleAnimation da = new DoubleAnimation(1, duration); chrome.Glyph.BeginAnimation(LinearGradientBrush.OpacityProperty, da); da = new DoubleAnimation(0.63, duration); chrome.GlyphShadow.BeginAnimation(LinearGradientBrush.OpacityProperty, da); } else { DoubleAnimation da = new DoubleAnimation(1, duration); chrome.Fill.BeginAnimation(LinearGradientBrush.OpacityProperty, da); chrome.OuterBorder.Brush.BeginAnimation(SolidColorBrush.OpacityProperty, da); da = new DoubleAnimation(0.63, duration); chrome.InnerBorder.Brush.BeginAnimation(LinearGradientBrush.OpacityProperty, da); da = new DoubleAnimation(0.5, duration); chrome.Shadow.Brush.BeginAnimation(SolidColorBrush.OpacityProperty, da); ColorAnimation ca = new ColorAnimation(Color.FromRgb(0x21, 0x21, 0x21), duration); chrome.Glyph.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x57, 0x57, 0x57), duration); chrome.Glyph.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0xB3, 0xB3, 0xB3), duration); chrome.Glyph.GradientStops[2].BeginAnimation(GradientStop.ColorProperty, ca); } } else if (chrome._localResources == null) { chrome.InvalidateVisual(); } else { Duration duration = new Duration(TimeSpan.FromSeconds(0.2)); if (chrome._scrollGlyph == ScrollGlyph.HorizontalGripper || chrome._scrollGlyph == ScrollGlyph.VerticalGripper) { DoubleAnimation da = new DoubleAnimation(); da.Duration = duration; chrome.Glyph.BeginAnimation(LinearGradientBrush.OpacityProperty, da); chrome.GlyphShadow.BeginAnimation(LinearGradientBrush.OpacityProperty, da); } else { DoubleAnimation da = new DoubleAnimation(); da.Duration = duration; chrome.Fill.BeginAnimation(LinearGradientBrush.OpacityProperty, da); chrome.OuterBorder.Brush.BeginAnimation(SolidColorBrush.OpacityProperty, da); chrome.InnerBorder.Brush.BeginAnimation(LinearGradientBrush.OpacityProperty, da); chrome.Shadow.Brush.BeginAnimation(SolidColorBrush.OpacityProperty, da); ColorAnimation ca = new ColorAnimation(); ca.Duration = duration; chrome.Glyph.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca); chrome.Glyph.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca); chrome.Glyph.GradientStops[2].BeginAnimation(GradientStop.ColorProperty, ca); } } } else { chrome._localResources = null; chrome.InvalidateVisual(); } } /// <summary> /// DependencyProperty for <see cref="RenderMouseOver" /> property. /// </summary> public static readonly DependencyProperty RenderMouseOverProperty = DependencyProperty.Register("RenderMouseOver", typeof(bool), typeof(ScrollChrome), new FrameworkPropertyMetadata( false, FrameworkPropertyMetadataOptions.AffectsRender, new PropertyChangedCallback(OnRenderMouseOverChanged))); /// <summary> /// When true the chrome renders with a mouse over look. /// </summary> public bool RenderMouseOver { get { return (bool)GetValue(RenderMouseOverProperty); } set { SetValue(RenderMouseOverProperty, value); } } private static void OnRenderMouseOverChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ScrollChrome chrome = ((ScrollChrome)o); if (chrome.Animates) { if (chrome._localResources == null) { chrome._localResources = new LocalResources(); chrome.InvalidateVisual(); } if (((bool)e.NewValue)) { chrome.AnimateToHover(); } else { Duration duration = new Duration(TimeSpan.FromSeconds(0.2)); ColorAnimation ca = new ColorAnimation(); ca.Duration = duration; chrome.OuterBorder.Brush.BeginAnimation(SolidColorBrush.ColorProperty, ca); chrome.Fill.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca); chrome.Fill.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca); chrome.Fill.GradientStops[2].BeginAnimation(GradientStop.ColorProperty, ca); chrome.Fill.GradientStops[3].BeginAnimation(GradientStop.ColorProperty, ca); chrome.Glyph.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca); chrome.Glyph.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca); chrome.Glyph.GradientStops[2].BeginAnimation(GradientStop.ColorProperty, ca); } } else { chrome._localResources = null; chrome.InvalidateVisual(); } } private void AnimateToHover() { Duration duration = new Duration(TimeSpan.FromSeconds(0.3)); ColorAnimation ca = new ColorAnimation(Color.FromRgb(0x3C, 0x7F, 0xB1), duration); OuterBorder.Brush.BeginAnimation(SolidColorBrush.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0xE3, 0xF4, 0xFC), duration); Fill.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0xD6, 0xEE, 0xFB), duration); Fill.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0xA9, 0xDB, 0xF6), duration); Fill.GradientStops[2].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0xA4, 0xD5, 0xEF), duration); Fill.GradientStops[3].BeginAnimation(GradientStop.ColorProperty, ca); if (_scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper) { ca = new ColorAnimation(Color.FromRgb(0x15, 0x30, 0x3E), duration); Glyph.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x3C, 0x7F, 0xB1), duration); Glyph.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x9C, 0xCE, 0xE9), duration); Glyph.GradientStops[2].BeginAnimation(GradientStop.ColorProperty, ca); } else { ca = new ColorAnimation(Color.FromRgb(0x0D, 0x2A, 0x3A), duration); Glyph.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x1F, 0x63, 0x8A), duration); Glyph.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x2E, 0x97, 0xCF), duration); Glyph.GradientStops[2].BeginAnimation(GradientStop.ColorProperty, ca); } } /// <summary> /// DependencyProperty for <see cref="RenderPressed" /> property. /// </summary> public static readonly DependencyProperty RenderPressedProperty = DependencyProperty.Register("RenderPressed", typeof(bool), typeof(ScrollChrome), new FrameworkPropertyMetadata( false, FrameworkPropertyMetadataOptions.AffectsRender, new PropertyChangedCallback(OnRenderPressedChanged))); /// <summary> /// When true the chrome renders with a pressed look. /// </summary> public bool RenderPressed { get { return (bool)GetValue(RenderPressedProperty); } set { SetValue(RenderPressedProperty, value); } } private static void OnRenderPressedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ScrollChrome chrome = ((ScrollChrome)o); if (chrome.Animates) { if (chrome._localResources == null) { chrome._localResources = new LocalResources(); chrome.InvalidateVisual(); } if (((bool)e.NewValue)) { Duration duration = new Duration(TimeSpan.FromSeconds(0.3)); ColorAnimation ca = new ColorAnimation(Color.FromRgb(0x15, 0x59, 0x8A), duration); chrome.OuterBorder.Brush.BeginAnimation(SolidColorBrush.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0xCA, 0xEC, 0xF9), duration); chrome.Fill.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0xAF, 0xE1, 0xF7), duration); chrome.Fill.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x6F, 0xCA, 0xF0), duration); chrome.Fill.GradientStops[2].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x66, 0xBA, 0xDD), duration); chrome.Fill.GradientStops[3].BeginAnimation(GradientStop.ColorProperty, ca); if (chrome._scrollGlyph == ScrollGlyph.HorizontalGripper || chrome._scrollGlyph == ScrollGlyph.VerticalGripper) { ca = new ColorAnimation(Color.FromRgb(0x0F, 0x24, 0x30), duration); chrome.Glyph.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x2E, 0x73, 0x97), duration); chrome.Glyph.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x8F, 0xB8, 0xCE), duration); chrome.Glyph.GradientStops[2].BeginAnimation(GradientStop.ColorProperty, ca); } else { ca = new ColorAnimation(Color.FromRgb(0x0E, 0x22, 0x2D), duration); chrome.Glyph.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x2F, 0x79, 0x9E), duration); chrome.Glyph.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x6B, 0xA0, 0xBC), duration); chrome.Glyph.GradientStops[2].BeginAnimation(GradientStop.ColorProperty, ca); } } else { chrome.AnimateToHover(); } } else { chrome._localResources = null; chrome.InvalidateVisual(); } } #endregion Dynamic Properties #region Protected Methods /// <summary> /// Updates DesiredSize of the ScrollChrome. Called by parent UIElement. This is the first pass of layout. /// </summary> /// <remarks> /// ScrollChrome basically constrains the value of its Width and Height properties. /// </remarks> /// <param name="availableSize">Available size is an "upper limit" that the return value should not exceed.</param> /// <returns>The ScrollChrome's desired size.</returns> protected override Size MeasureOverride(Size availableSize) { _transform = null; return new Size(0,0); } /// <summary> /// ScrollChrome does no work here and returns arrangeSize. /// </summary> /// <param name="finalSize">Size the ContentPresenter will assume.</param> protected override Size ArrangeOverride(Size finalSize) { _transform = null; return finalSize; } /// <summary> /// Render callback. /// Note: Assumes all borders are 1 unit. /// </summary> protected override void OnRender(DrawingContext drawingContext) { Rect bounds = new Rect(0, 0, ActualWidth, ActualHeight); _scrollGlyph = ScrollGlyph; if ((bounds.Width >= 1.0) && (bounds.Height >= 1.0)) { bounds.X += 0.5; bounds.Y += 0.5; bounds.Width -= 1.0; bounds.Height -= 1.0; } switch (_scrollGlyph) { case ScrollGlyph.LeftArrow: case ScrollGlyph.RightArrow: case ScrollGlyph.HorizontalGripper: if (bounds.Height >= 1.0) { bounds.Y += 1.0; bounds.Height -= 1.0; } break; case ScrollGlyph.UpArrow: case ScrollGlyph.DownArrow: case ScrollGlyph.VerticalGripper: if (bounds.Width >= 1.0) { bounds.X += 1.0; bounds.Width -= 1.0; } break; } DrawShadow(drawingContext, ref bounds); DrawBorders(drawingContext, ref bounds); DrawGlyph(drawingContext, ref bounds); } #endregion #region Private Methods private void DrawShadow(DrawingContext dc, ref Rect bounds) { if ((bounds.Width > 0.0) && (bounds.Height > 2.0)) { Pen pen = Shadow; if (pen != null) { dc.DrawRoundedRectangle( null, pen, new Rect(bounds.X, bounds.Y + 2.0, bounds.Width, bounds.Height - 2.0), 3.0, 3.0); } bounds.Height -= 1.0; bounds.Width = Math.Max(0.0, bounds.Width - 1.0); } } private void DrawBorders(DrawingContext dc, ref Rect bounds) { if ((bounds.Width >= 2.0) && (bounds.Height >= 2.0)) { Brush brush = Fill; Pen pen = OuterBorder; if (pen != null) { dc.DrawRoundedRectangle( brush, pen, new Rect(bounds.X, bounds.Y, bounds.Width, bounds.Height), 1.0, 1.0); brush = null; // Done with the fill } bounds.Inflate(-1.0, -1.0); if ((bounds.Width >= 2.0) && (bounds.Height >= 2.0)) { pen = InnerBorder; if ((pen != null) || (brush != null)) { dc.DrawRoundedRectangle( brush, pen, new Rect(bounds.X, bounds.Y, bounds.Width, bounds.Height), 0.5, 0.5); } bounds.Inflate(-1.0, -1.0); } } } private void DrawGlyph(DrawingContext dc, ref Rect bounds) { if ((bounds.Width > 0.0) && (bounds.Height > 0.0)) { Brush brush = Glyph; if ((brush != null) && (_scrollGlyph != ScrollGlyph.None)) { switch (_scrollGlyph) { case ScrollGlyph.HorizontalGripper: DrawHorizontalGripper(dc, brush, bounds); break; case ScrollGlyph.VerticalGripper: DrawVerticalGripper(dc, brush, bounds); break; case ScrollGlyph.LeftArrow: case ScrollGlyph.RightArrow: case ScrollGlyph.UpArrow: case ScrollGlyph.DownArrow: DrawArrow(dc, brush, bounds); break; } } } } private void DrawHorizontalGripper(DrawingContext dc, Brush brush, Rect bounds) { if ((bounds.Width > 15.0) && (bounds.Height > 2.0)) { Brush glyphShadow = GlyphShadow; double height = Math.Min(7.0, bounds.Height); double shadowHeight = height + 1.0; double x = bounds.X + ((bounds.Width * 0.5) - 4.0); double y = bounds.Y + ((bounds.Height - height) * 0.5); for (int i = 0; i < 9; i += 3) { if (glyphShadow != null) { dc.DrawRectangle(glyphShadow, null, new Rect(x + i - 0.5, y - 0.5, 3.0, shadowHeight)); } dc.DrawRectangle(brush, null, new Rect(x + i, y, 2.0, height)); } } } private void DrawVerticalGripper(DrawingContext dc, Brush brush, Rect bounds) { if ((bounds.Width > 2.0) && (bounds.Height > 15.0)) { Brush glyphShadow = GlyphShadow; double width = Math.Min(7.0, bounds.Width); double shadowWidth = width + 1.0; double x = bounds.X + ((bounds.Width - width) * 0.5); double y = bounds.Y + ((bounds.Height * 0.5) - 4.0); for (int i = 0; i < 9; i += 3) { if (glyphShadow != null) { dc.DrawRectangle(glyphShadow, null, new Rect(x - 0.5, y + i - 0.5, shadowWidth, 3.0)); } dc.DrawRectangle(brush, null, new Rect(x, y + i, width, 2.0)); } } } #region Arrow Geometry Generation // Geometries for arrows don't change so use static versions to reduce working set private static object _glyphAccess = new object(); private static Geometry _leftArrowGeometry; private static Geometry _rightArrowGeometry; private static Geometry _upArrowGeometry; private static Geometry _downArrowGeometry; private static Geometry LeftArrowGeometry { get { if (_leftArrowGeometry == null) { lock (_glyphAccess) { if (_leftArrowGeometry == null) { PathFigure figure = new PathFigure(); figure.StartPoint = new Point(4.0, 0.0); figure.Segments.Add(new LineSegment(new Point(0, 3.5), true)); figure.Segments.Add(new LineSegment(new Point(4.0, 7.0), true)); figure.IsClosed = true; figure.Freeze(); PathGeometry path = new PathGeometry(); path.Figures.Add(figure); path.Freeze(); _leftArrowGeometry = path; } } } return _leftArrowGeometry; } } private static Geometry RightArrowGeometry { get { if (_rightArrowGeometry == null) { lock (_glyphAccess) { if (_rightArrowGeometry == null) { PathFigure figure = new PathFigure(); figure.StartPoint = new Point(0.0, 0.0); figure.Segments.Add(new LineSegment(new Point(4, 3.5), true)); figure.Segments.Add(new LineSegment(new Point(0.0, 7.0), true)); figure.IsClosed = true; figure.Freeze(); PathGeometry path = new PathGeometry(); path.Figures.Add(figure); path.Freeze(); _rightArrowGeometry = path; } } } return _rightArrowGeometry; } } private static Geometry UpArrowGeometry { get { if (_upArrowGeometry == null) { lock (_glyphAccess) { if (_upArrowGeometry == null) { PathFigure figure = new PathFigure(); figure.StartPoint = new Point(0.0, 4.0); figure.Segments.Add(new LineSegment(new Point(3.5, 0), true)); figure.Segments.Add(new LineSegment(new Point(7.0, 4.0), true)); figure.IsClosed = true; figure.Freeze(); PathGeometry path = new PathGeometry(); path.Figures.Add(figure); path.Freeze(); _upArrowGeometry = path; } } } return _upArrowGeometry; } } private static Geometry DownArrowGeometry { get { if (_downArrowGeometry == null) { lock (_glyphAccess) { if (_downArrowGeometry == null) { PathFigure figure = new PathFigure(); figure.StartPoint = new Point(0.0, 0.0); figure.Segments.Add(new LineSegment(new Point(3.5, 4.0), true)); figure.Segments.Add(new LineSegment(new Point(7.0, 0.0), true)); figure.IsClosed = true; figure.Freeze(); PathGeometry path = new PathGeometry(); path.Figures.Add(figure); path.Freeze(); _downArrowGeometry = path; } } } return _downArrowGeometry; } } #endregion private void DrawArrow(DrawingContext dc, Brush brush, Rect bounds) { if (_transform == null) { double glyphWidth = 7.0; double glyphHeight = 4.0; if (_scrollGlyph == ScrollGlyph.LeftArrow || _scrollGlyph == ScrollGlyph.RightArrow) { glyphWidth = 4.0; glyphHeight = 7.0; } Matrix matrix = new Matrix(); if ((bounds.Width < glyphWidth) || (bounds.Height < glyphHeight)) { double widthScale = Math.Min(glyphWidth, bounds.Width) / glyphWidth; double heightScale = Math.Min(glyphHeight, bounds.Height) / glyphHeight; double x = (bounds.X + (bounds.Width * 0.5)) / widthScale - (glyphWidth * 0.5); double y = (bounds.Y + (bounds.Height * 0.5)) / heightScale - (glyphHeight * 0.5); if (double.IsNaN(widthScale) || double.IsInfinity(widthScale) || double.IsNaN(heightScale) || double.IsInfinity(heightScale) || double.IsNaN(x) || double.IsInfinity(x) || double.IsNaN(y) || double.IsInfinity(y)) { return; } matrix.Translate(x, y); matrix.Scale(widthScale, heightScale); } else { double x = bounds.X + (bounds.Width * 0.5) - (glyphWidth * 0.5); double y = bounds.Y + (bounds.Height * 0.5) - (glyphHeight * 0.5); matrix.Translate(x, y); } _transform = new MatrixTransform(); _transform.Matrix = matrix; } dc.PushTransform(_transform); switch (_scrollGlyph) { case ScrollGlyph.LeftArrow: dc.DrawGeometry(brush, null, LeftArrowGeometry); break; case ScrollGlyph.RightArrow: dc.DrawGeometry(brush, null, RightArrowGeometry); break; case ScrollGlyph.UpArrow: dc.DrawGeometry(brush, null, UpArrowGeometry); break; case ScrollGlyph.DownArrow: dc.DrawGeometry(brush, null, DownArrowGeometry); break; } dc.Pop(); // Center and scaling transform } // // This property // 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject // 2. This is a performance optimization // internal override int EffectiveValuesInitialSize { get { return 19; } } #endregion #region Data private bool Animates { get { return SystemParameters.ClientAreaAnimation && RenderCapability.Tier > 0; } } private static LinearGradientBrush CommonHorizontalThumbFill { get { if (_commonHorizontalThumbFill == null) { lock (_resourceAccess) { if (_commonHorizontalThumbFill == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(0, 1); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xF3, 0xF3, 0xF3), 0)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xE8, 0xE8, 0xE9), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xD6, 0xD6, 0xD8), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xBC, 0xBD, 0xC0), 1)); temp.Freeze(); // Static field must not be set until the local has been frozen _commonHorizontalThumbFill = temp; } } } return _commonHorizontalThumbFill; } } private static LinearGradientBrush CommonHorizontalThumbHoverFill { get { if (_commonHorizontalThumbHoverFill == null) { lock (_resourceAccess) { if (_commonHorizontalThumbHoverFill == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(0, 1); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xE3, 0xF4, 0xFC), 0)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xD6, 0xEE, 0xFB), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xA9, 0xDB, 0xF6), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xA4, 0xD5, 0xEF), 1)); temp.Freeze(); _commonHorizontalThumbHoverFill = temp; } } } return _commonHorizontalThumbHoverFill; } } private static LinearGradientBrush CommonHorizontalThumbPressedFill { get { if (_commonHorizontalThumbPressedFill == null) { lock (_resourceAccess) { if (_commonHorizontalThumbPressedFill == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(0, 1); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xCA, 0xEC, 0xF9), 0)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xAF, 0xE1, 0xF7), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x6F, 0xCA, 0xF0), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x66, 0xBA, 0xDD), 1)); temp.Freeze(); _commonHorizontalThumbPressedFill = temp; } } } return _commonHorizontalThumbPressedFill; } } private static LinearGradientBrush CommonVerticalThumbFill { get { if (_commonVerticalThumbFill == null) { lock (_resourceAccess) { if (_commonVerticalThumbFill == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(1, 0); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xF3, 0xF3, 0xF3), 0)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xE8, 0xE8, 0xE9), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xD6, 0xD6, 0xD8), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xBC, 0xBD, 0xC0), 1)); temp.Freeze(); _commonVerticalThumbFill = temp; } } } return _commonVerticalThumbFill; } } private static LinearGradientBrush CommonVerticalThumbHoverFill { get { if (_commonVerticalThumbHoverFill == null) { lock (_resourceAccess) { if (_commonVerticalThumbHoverFill == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(1, 0); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xE3, 0xF4, 0xFC), 0)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xD6, 0xEE, 0xFB), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xA9, 0xDB, 0xF6), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xA4, 0xD5, 0xEF), 1)); temp.Freeze(); _commonVerticalThumbHoverFill = temp; } } } return _commonVerticalThumbHoverFill; } } private static LinearGradientBrush CommonVerticalThumbPressedFill { get { if (_commonVerticalThumbPressedFill == null) { lock (_resourceAccess) { if (_commonVerticalThumbPressedFill == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(1, 0); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xCA, 0xEC, 0xF9), 0)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xAF, 0xE1, 0xF7), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x6F, 0xCA, 0xF0), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x66, 0xBA, 0xDD), 1)); temp.Freeze(); _commonVerticalThumbPressedFill = temp; } } } return _commonVerticalThumbPressedFill; } } private LinearGradientBrush Fill { get { if (!Animates) { if (_scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.LeftArrow || _scrollGlyph == ScrollGlyph.RightArrow) { if (RenderPressed) { return CommonHorizontalThumbPressedFill; } else if (RenderMouseOver) { return CommonHorizontalThumbHoverFill; } else if (IsEnabled || _scrollGlyph == ScrollGlyph.HorizontalGripper) { return CommonHorizontalThumbFill; } else { return null; } } else { if (RenderPressed) { return CommonVerticalThumbPressedFill; } else if (RenderMouseOver) { return CommonVerticalThumbHoverFill; } else if (IsEnabled || _scrollGlyph == ScrollGlyph.VerticalGripper) { return CommonVerticalThumbFill; } else { return null; } } } if (_localResources != null) { if (_localResources.Fill == null) { if (_scrollGlyph == ScrollGlyph.HorizontalGripper) { _localResources.Fill = CommonHorizontalThumbFill.Clone(); } else if (_scrollGlyph == ScrollGlyph.VerticalGripper) { _localResources.Fill = CommonVerticalThumbFill.Clone(); } else { if (_scrollGlyph == ScrollGlyph.LeftArrow || _scrollGlyph == ScrollGlyph.RightArrow) { _localResources.Fill = CommonHorizontalThumbFill.Clone(); } else { _localResources.Fill = CommonVerticalThumbFill.Clone(); } _localResources.Fill.Opacity = 0; } } return _localResources.Fill; } else { if (_scrollGlyph == ScrollGlyph.HorizontalGripper) { return CommonHorizontalThumbFill; } else if (_scrollGlyph == ScrollGlyph.VerticalGripper) { return CommonVerticalThumbFill; } else { return null; } } } } private static Pen CommonThumbOuterBorder { get { if (_commonThumbOuterBorder == null) { lock (_resourceAccess) { if (_commonThumbOuterBorder == null) { Pen temp = new Pen(); temp.Thickness = 1; temp.Brush = new SolidColorBrush(Color.FromRgb(0x95, 0x95, 0x95)); temp.Freeze(); _commonThumbOuterBorder = temp; } } } return _commonThumbOuterBorder; } } private static Pen CommonThumbHoverOuterBorder { get { if (_commonThumbHoverOuterBorder == null) { lock (_resourceAccess) { if (_commonThumbHoverOuterBorder == null) { Pen temp = new Pen(); temp.Thickness = 1; temp.Brush = new SolidColorBrush(Color.FromRgb(0x3C, 0x7F, 0xB1)); temp.Freeze(); _commonThumbHoverOuterBorder = temp; } } } return _commonThumbHoverOuterBorder; } } private static Pen CommonThumbPressedOuterBorder { get { if (_commonThumbPressedOuterBorder == null) { lock (_resourceAccess) { if (_commonThumbPressedOuterBorder == null) { Pen temp = new Pen(); temp.Thickness = 1; temp.Brush = new SolidColorBrush(Color.FromRgb(0x15, 0x59, 0x8A)); temp.Freeze(); _commonThumbPressedOuterBorder = temp; } } } return _commonThumbPressedOuterBorder; } } private Pen OuterBorder { get { if (!Animates) { if (RenderPressed) { return CommonThumbPressedOuterBorder; } else if (RenderMouseOver) { return CommonThumbHoverOuterBorder; } else if (IsEnabled || _scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper) { return CommonThumbOuterBorder; } else { return null; } } if (_localResources != null) { if (_localResources.OuterBorder == null) { _localResources.OuterBorder = CommonThumbOuterBorder.Clone(); if (!(_scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper)) { _localResources.OuterBorder.Brush.Opacity = 0; } } return _localResources.OuterBorder; } else { if (_scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper) { return CommonThumbOuterBorder; } else { return null; } } } } private static Pen CommonThumbInnerBorder { get { if (_commonThumbInnerBorder == null) { lock (_resourceAccess) { if (_commonThumbInnerBorder == null) { Pen temp = new Pen(); temp.Thickness = 1; temp.Brush = new SolidColorBrush(Colors.White); temp.Brush.Opacity = 0.63; temp.Freeze(); _commonThumbInnerBorder = temp; } } } return _commonThumbInnerBorder; } } private Pen InnerBorder { get { if (!Animates) { if (IsEnabled || _scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper) { return CommonThumbInnerBorder; } else { return null; } } if (_localResources != null) { if (_localResources.InnerBorder == null) { _localResources.InnerBorder = CommonThumbInnerBorder.Clone(); if (!(_scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper)) { _localResources.InnerBorder.Brush.Opacity = 0; } } return _localResources.InnerBorder; } else { if (_scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper) { return CommonThumbInnerBorder; } else { return null; } } } } private static Pen CommonThumbShadow { get { if (_commonThumbShadow == null) { lock (_resourceAccess) { if (_commonThumbShadow == null) { Pen temp = new Pen(); temp.Thickness = 1; temp.Brush = new SolidColorBrush(Color.FromRgb(0xCF, 0xCF, 0xCF)); temp.Brush.Opacity = 0.5; temp.Freeze(); _commonThumbShadow = temp; } } } return _commonThumbShadow; } } private Pen Shadow { get { if (!Animates) { if (IsEnabled || _scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper) { return CommonThumbShadow; } else { return null; } } if (_localResources != null) { if (_localResources.Shadow == null) { _localResources.Shadow = CommonThumbShadow.Clone(); if (!(_scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper)) { _localResources.Shadow.Brush.Opacity = 0; } } return _localResources.Shadow; } else { if (_scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper) { return CommonThumbShadow; } else { return null; } } } } private LinearGradientBrush CommonHorizontalThumbEnabledGlyph { get { if (_commonHorizontalThumbEnabledGlyph == null) { lock (_resourceAccess) { if (_commonHorizontalThumbEnabledGlyph == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(1, 0.05); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x00, 0x00, 0x00), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x97, 0x97, 0x97), 0.7)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xCA, 0xCA, 0xCA), 1)); temp.Freeze(); _commonHorizontalThumbEnabledGlyph = temp; } } } return _commonHorizontalThumbEnabledGlyph; } } private LinearGradientBrush CommonHorizontalThumbHoverGlyph { get { if (_commonHorizontalThumbHoverGlyph == null) { lock (_resourceAccess) { if (_commonHorizontalThumbHoverGlyph == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(1, 0.05); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x15, 0x30, 0x3E), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x3C, 0x7F, 0xB1), 0.7)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x9C, 0xCE, 0xE9), 1)); temp.Freeze(); _commonHorizontalThumbHoverGlyph = temp; } } } return _commonHorizontalThumbHoverGlyph; } } private LinearGradientBrush CommonHorizontalThumbPressedGlyph { get { if (_commonHorizontalThumbPressedGlyph == null) { lock (_resourceAccess) { if (_commonHorizontalThumbPressedGlyph == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(1, 0.05); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x0F, 0x24, 0x30), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x2E, 0x73, 0x97), 0.7)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x8F, 0xB8, 0xCE), 1)); temp.Freeze(); _commonHorizontalThumbPressedGlyph = temp; } } } return _commonHorizontalThumbPressedGlyph; } } private LinearGradientBrush CommonVerticalThumbEnabledGlyph { get { if (_commonVerticalThumbEnabledGlyph == null) { lock (_resourceAccess) { if (_commonVerticalThumbEnabledGlyph == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(0.05, 1); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x00, 0x00, 0x00), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x97, 0x97, 0x97), 0.7)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xCA, 0xCA, 0xCA), 1)); temp.Freeze(); _commonVerticalThumbEnabledGlyph = temp; } } } return _commonVerticalThumbEnabledGlyph; } } private LinearGradientBrush CommonVerticalThumbHoverGlyph { get { if (_commonVerticalThumbHoverGlyph == null) { lock (_resourceAccess) { if (_commonVerticalThumbHoverGlyph == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(0.05, 1); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x15, 0x30, 0x3E), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x3C, 0x7F, 0xB1), 0.7)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x9C, 0xCE, 0xE9), 1)); temp.Freeze(); _commonVerticalThumbHoverGlyph = temp; } } } return _commonVerticalThumbHoverGlyph; } } private LinearGradientBrush CommonVerticalThumbPressedGlyph { get { if (_commonVerticalThumbPressedGlyph == null) { lock (_resourceAccess) { if (_commonVerticalThumbPressedGlyph == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(0.05, 1); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x0F, 0x24, 0x30), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x2E, 0x73, 0x97), 0.7)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x8F, 0xB8, 0xCE), 1)); temp.Freeze(); _commonVerticalThumbPressedGlyph = temp; } } } return _commonVerticalThumbPressedGlyph; } } private LinearGradientBrush CommonButtonGlyph { get { if (_commonButtonGlyph == null) { lock (_resourceAccess) { if (_commonButtonGlyph == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.MappingMode = BrushMappingMode.Absolute; temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(4, 4); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x70, 0x70, 0x70), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x76, 0x76, 0x76), 0.7)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xCB, 0xCB, 0xCB), 1)); temp.Freeze(); _commonButtonGlyph = temp; } } } return _commonButtonGlyph; } } private LinearGradientBrush CommonButtonEnabledGlyph { get { if (_commonButtonEnabledGlyph == null) { lock (_resourceAccess) { if (_commonButtonEnabledGlyph == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.MappingMode = BrushMappingMode.Absolute; temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(4, 4); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x21, 0x21, 0x21), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x57, 0x57, 0x57), 0.7)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0xB3, 0xB3, 0xB3), 1)); temp.Freeze(); _commonButtonEnabledGlyph = temp; } } } return _commonButtonEnabledGlyph; } } private LinearGradientBrush CommonButtonHoverGlyph { get { if (_commonButtonHoverGlyph == null) { lock (_resourceAccess) { if (_commonButtonHoverGlyph == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.MappingMode = BrushMappingMode.Absolute; temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(4, 4); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x0D, 0x2A, 0x3A), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x1F, 0x63, 0x8A), 0.7)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x2E, 0x97, 0xCF), 1)); temp.Freeze(); _commonButtonHoverGlyph = temp; } } } return _commonButtonHoverGlyph; } } private static LinearGradientBrush CommonButtonPressedGlyph { get { if (_commonButtonPressedGlyph == null) { lock (_resourceAccess) { if (_commonButtonPressedGlyph == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.MappingMode = BrushMappingMode.Absolute; temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(4, 4); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x0E, 0x22, 0x2D), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x2F, 0x79, 0x9E), 0.7)); temp.GradientStops.Add(new GradientStop(Color.FromRgb(0x6B, 0xA0, 0xBC), 1)); temp.Freeze(); _commonButtonPressedGlyph = temp; } } } return _commonButtonPressedGlyph; } } private LinearGradientBrush Glyph { get { if (!Animates) { if (_scrollGlyph == ScrollGlyph.HorizontalGripper) { if (RenderPressed) { return CommonHorizontalThumbPressedGlyph; } else if (RenderMouseOver) { return CommonHorizontalThumbHoverGlyph; } else { return CommonHorizontalThumbEnabledGlyph; } } else if (_scrollGlyph == ScrollGlyph.VerticalGripper) { if (RenderPressed) { return CommonVerticalThumbPressedGlyph; } else if (RenderMouseOver) { return CommonVerticalThumbHoverGlyph; } else { return CommonVerticalThumbEnabledGlyph; } } else { if (RenderPressed) { return CommonButtonPressedGlyph; } else if (RenderMouseOver) { return CommonButtonHoverGlyph; } else if (IsEnabled) { return CommonButtonEnabledGlyph; } else { return CommonButtonGlyph; } } } if (_localResources != null) { if (_localResources.Glyph == null) { if (_scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper) { _localResources.Glyph = new LinearGradientBrush(); _localResources.Glyph.StartPoint = new Point(0, 0); if (_scrollGlyph == ScrollGlyph.HorizontalGripper) { _localResources.Glyph.EndPoint = new Point(1, 0.05); } else { _localResources.Glyph.EndPoint = new Point(0.05, 1); } _localResources.Glyph.GradientStops.Add(new GradientStop(Color.FromRgb(0x00, 0x00, 0x00), 0.5)); _localResources.Glyph.GradientStops.Add(new GradientStop(Color.FromRgb(0x97, 0x97, 0x97), 0.7)); _localResources.Glyph.GradientStops.Add(new GradientStop(Color.FromRgb(0xCA, 0xCA, 0xCA), 1)); } else { _localResources.Glyph = CommonButtonGlyph.Clone(); } } return _localResources.Glyph; } else { if (_scrollGlyph == ScrollGlyph.HorizontalGripper) { return CommonHorizontalThumbEnabledGlyph; } else if (_scrollGlyph == ScrollGlyph.VerticalGripper) { return CommonVerticalThumbEnabledGlyph; } else { return CommonButtonGlyph; } } } } private static SolidColorBrush CommonThumbEnabledGlyphShadow { get { if (_commonThumbEnabledGlyphShadow == null) { lock (_resourceAccess) { if (_commonThumbEnabledGlyphShadow == null) { SolidColorBrush temp = new SolidColorBrush(Colors.White); temp.Opacity = 0.63; temp.Freeze(); _commonThumbEnabledGlyphShadow = temp; } } } return _commonThumbEnabledGlyphShadow; } } private SolidColorBrush GlyphShadow { get { if (!Animates) { if ((_scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper)) { return CommonThumbEnabledGlyphShadow; } else { return null; } } if (_localResources != null) { if (_localResources.GlyphShadow == null) { if (_scrollGlyph == ScrollGlyph.HorizontalGripper || _scrollGlyph == ScrollGlyph.VerticalGripper) { _localResources.GlyphShadow = new SolidColorBrush(Colors.White); } } return _localResources.GlyphShadow; } else { return null; } } } // Common Resources private static LinearGradientBrush _commonHorizontalThumbFill; private static LinearGradientBrush _commonVerticalThumbFill; private static Pen _commonThumbOuterBorder; private static Pen _commonThumbInnerBorder; private static Pen _commonThumbShadow; private static LinearGradientBrush _commonHorizontalThumbEnabledGlyph; private static LinearGradientBrush _commonVerticalThumbEnabledGlyph; private static SolidColorBrush _commonThumbEnabledGlyphShadow; private static LinearGradientBrush _commonHorizontalThumbHoverFill; private static LinearGradientBrush _commonVerticalThumbHoverFill; private static Pen _commonThumbHoverOuterBorder; private static LinearGradientBrush _commonHorizontalThumbHoverGlyph; private static LinearGradientBrush _commonVerticalThumbHoverGlyph; private static LinearGradientBrush _commonHorizontalThumbPressedFill; private static LinearGradientBrush _commonVerticalThumbPressedFill; private static Pen _commonThumbPressedOuterBorder; private static LinearGradientBrush _commonHorizontalThumbPressedGlyph; private static LinearGradientBrush _commonVerticalThumbPressedGlyph; private static LinearGradientBrush _commonButtonGlyph; private static LinearGradientBrush _commonButtonEnabledGlyph; private static LinearGradientBrush _commonButtonHoverGlyph; private static LinearGradientBrush _commonButtonPressedGlyph; private static object _resourceAccess = new object(); // Per instance data private ScrollGlyph _scrollGlyph; private MatrixTransform _transform; private LocalResources _localResources; private class LocalResources { public LinearGradientBrush Fill; public Pen OuterBorder; public Pen InnerBorder; public Pen Shadow; public LinearGradientBrush Glyph; public SolidColorBrush GlyphShadow; } #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.Apis.DomainsRDAP.v1 { /// <summary>The DomainsRDAP Service.</summary> public class DomainsRDAPService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public DomainsRDAPService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public DomainsRDAPService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Autnum = new AutnumResource(this); Domain = new DomainResource(this); Entity = new EntityResource(this); Ip = new IpResource(this); Nameserver = new NameserverResource(this); V1 = new V1Resource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "domainsrdap"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://domainsrdap.googleapis.com/"; #else "https://domainsrdap.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://domainsrdap.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Gets the Autnum resource.</summary> public virtual AutnumResource Autnum { get; } /// <summary>Gets the Domain resource.</summary> public virtual DomainResource Domain { get; } /// <summary>Gets the Entity resource.</summary> public virtual EntityResource Entity { get; } /// <summary>Gets the Ip resource.</summary> public virtual IpResource Ip { get; } /// <summary>Gets the Nameserver resource.</summary> public virtual NameserverResource Nameserver { get; } /// <summary>Gets the V1 resource.</summary> public virtual V1Resource V1 { get; } } /// <summary>A base abstract class for DomainsRDAP requests.</summary> public abstract class DomainsRDAPBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new DomainsRDAPBaseServiceRequest instance.</summary> protected DomainsRDAPBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes DomainsRDAP parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "autnum" collection of methods.</summary> public class AutnumResource { private const string Resource = "autnum"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public AutnumResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> /// <param name="autnumId"><c>null</c></param> public virtual GetRequest Get(string autnumId) { return new GetRequest(service, autnumId); } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public class GetRequest : DomainsRDAPBaseServiceRequest<Google.Apis.DomainsRDAP.v1.Data.RdapResponse> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string autnumId) : base(service) { AutnumId = autnumId; InitParameters(); } [Google.Apis.Util.RequestParameterAttribute("autnumId", Google.Apis.Util.RequestParameterType.Path)] public virtual string AutnumId { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/autnum/{autnumId}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("autnumId", new Google.Apis.Discovery.Parameter { Name = "autnumId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "domain" collection of methods.</summary> public class DomainResource { private const string Resource = "domain"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public DomainResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Look up RDAP information for a domain by name.</summary> /// <param name="domainName">Full domain name to look up. Example: "example.com"</param> public virtual GetRequest Get(string domainName) { return new GetRequest(service, domainName); } /// <summary>Look up RDAP information for a domain by name.</summary> public class GetRequest : DomainsRDAPBaseServiceRequest<Google.Apis.DomainsRDAP.v1.Data.HttpBody> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string domainName) : base(service) { DomainName = domainName; InitParameters(); } /// <summary>Full domain name to look up. Example: "example.com"</summary> [Google.Apis.Util.RequestParameterAttribute("domainName", Google.Apis.Util.RequestParameterType.Path)] public virtual string DomainName { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/domain/{+domainName}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("domainName", new Google.Apis.Discovery.Parameter { Name = "domainName", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^[^/]+$", }); } } } /// <summary>The "entity" collection of methods.</summary> public class EntityResource { private const string Resource = "entity"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public EntityResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> /// <param name="entityId"><c>null</c></param> public virtual GetRequest Get(string entityId) { return new GetRequest(service, entityId); } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public class GetRequest : DomainsRDAPBaseServiceRequest<Google.Apis.DomainsRDAP.v1.Data.RdapResponse> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string entityId) : base(service) { EntityId = entityId; InitParameters(); } [Google.Apis.Util.RequestParameterAttribute("entityId", Google.Apis.Util.RequestParameterType.Path)] public virtual string EntityId { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/entity/{entityId}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("entityId", new Google.Apis.Discovery.Parameter { Name = "entityId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "ip" collection of methods.</summary> public class IpResource { private const string Resource = "ip"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public IpResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> /// <param name="ipId"><c>null</c></param> /// <param name="ipId1"><c>null</c></param> public virtual GetRequest Get(string ipId, string ipId1) { return new GetRequest(service, ipId, ipId1); } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public class GetRequest : DomainsRDAPBaseServiceRequest<Google.Apis.DomainsRDAP.v1.Data.RdapResponse> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string ipId, string ipId1) : base(service) { IpId = ipId; IpId1 = ipId1; InitParameters(); } [Google.Apis.Util.RequestParameterAttribute("ipId", Google.Apis.Util.RequestParameterType.Path)] public virtual string IpId { get; private set; } [Google.Apis.Util.RequestParameterAttribute("ipId1", Google.Apis.Util.RequestParameterType.Path)] public virtual string IpId1 { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/ip/{ipId}/{ipId1}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("ipId", new Google.Apis.Discovery.Parameter { Name = "ipId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add("ipId1", new Google.Apis.Discovery.Parameter { Name = "ipId1", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "nameserver" collection of methods.</summary> public class NameserverResource { private const string Resource = "nameserver"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public NameserverResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> /// <param name="nameserverId"><c>null</c></param> public virtual GetRequest Get(string nameserverId) { return new GetRequest(service, nameserverId); } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public class GetRequest : DomainsRDAPBaseServiceRequest<Google.Apis.DomainsRDAP.v1.Data.RdapResponse> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string nameserverId) : base(service) { NameserverId = nameserverId; InitParameters(); } [Google.Apis.Util.RequestParameterAttribute("nameserverId", Google.Apis.Util.RequestParameterType.Path)] public virtual string NameserverId { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/nameserver/{nameserverId}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("nameserverId", new Google.Apis.Discovery.Parameter { Name = "nameserverId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "v1" collection of methods.</summary> public class V1Resource { private const string Resource = "v1"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public V1Resource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public virtual GetDomainsRequest GetDomains() { return new GetDomainsRequest(service); } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public class GetDomainsRequest : DomainsRDAPBaseServiceRequest<Google.Apis.DomainsRDAP.v1.Data.RdapResponse> { /// <summary>Constructs a new GetDomains request.</summary> public GetDomainsRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>Gets the method name.</summary> public override string MethodName => "getDomains"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/domains"; /// <summary>Initializes GetDomains parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public virtual GetEntitiesRequest GetEntities() { return new GetEntitiesRequest(service); } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public class GetEntitiesRequest : DomainsRDAPBaseServiceRequest<Google.Apis.DomainsRDAP.v1.Data.RdapResponse> { /// <summary>Constructs a new GetEntities request.</summary> public GetEntitiesRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>Gets the method name.</summary> public override string MethodName => "getEntities"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/entities"; /// <summary>Initializes GetEntities parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Get help information for the RDAP API, including links to documentation.</summary> public virtual GetHelpRequest GetHelp() { return new GetHelpRequest(service); } /// <summary>Get help information for the RDAP API, including links to documentation.</summary> public class GetHelpRequest : DomainsRDAPBaseServiceRequest<Google.Apis.DomainsRDAP.v1.Data.HttpBody> { /// <summary>Constructs a new GetHelp request.</summary> public GetHelpRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>Gets the method name.</summary> public override string MethodName => "getHelp"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/help"; /// <summary>Initializes GetHelp parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public virtual GetIpRequest GetIp() { return new GetIpRequest(service); } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public class GetIpRequest : DomainsRDAPBaseServiceRequest<Google.Apis.DomainsRDAP.v1.Data.HttpBody> { /// <summary>Constructs a new GetIp request.</summary> public GetIpRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>Gets the method name.</summary> public override string MethodName => "getIp"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/ip"; /// <summary>Initializes GetIp parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public virtual GetNameserversRequest GetNameservers() { return new GetNameserversRequest(service); } /// <summary> /// The RDAP API recognizes this command from the RDAP specification but does not support it. The response is a /// formatted 501 error. /// </summary> public class GetNameserversRequest : DomainsRDAPBaseServiceRequest<Google.Apis.DomainsRDAP.v1.Data.RdapResponse> { /// <summary>Constructs a new GetNameservers request.</summary> public GetNameserversRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>Gets the method name.</summary> public override string MethodName => "getNameservers"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/nameservers"; /// <summary>Initializes GetNameservers parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.DomainsRDAP.v1.Data { /// <summary> /// Message that represents an arbitrary HTTP body. It should only be used for payload formats that can't be /// represented as JSON, such as raw binary or an HTML page. This message can be used both in streaming and /// non-streaming API methods in the request as well as the response. It can be used as a top-level request field, /// which is convenient if one wants to extract parameters from either the URL or HTTP template into the request /// fields and also want access to the raw HTTP body. Example: message GetResourceRequest { // A unique request id. /// string request_id = 1; // The raw HTTP body is bound to this field. google.api.HttpBody http_body = 2; } service /// ResourceService { rpc GetResource(GetResourceRequest) returns (google.api.HttpBody); rpc /// UpdateResource(google.api.HttpBody) returns (google.protobuf.Empty); } Example with streaming methods: service /// CaldavService { rpc GetCalendar(stream google.api.HttpBody) returns (stream google.api.HttpBody); rpc /// UpdateCalendar(stream google.api.HttpBody) returns (stream google.api.HttpBody); } Use of this type only changes /// how the request and response bodies are handled, all other features will continue to work unchanged. /// </summary> public class HttpBody : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The HTTP Content-Type header value specifying the content type of the body.</summary> [Newtonsoft.Json.JsonPropertyAttribute("contentType")] public virtual string ContentType { get; set; } /// <summary>The HTTP request/response body as raw binary.</summary> [Newtonsoft.Json.JsonPropertyAttribute("data")] public virtual string Data { get; set; } /// <summary> /// Application specific response metadata. Must be set in the first response for streaming APIs. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("extensions")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Extensions { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Links object defined in [section 4.2 of RFC 7483](https://tools.ietf.org/html/rfc7483#section-4.2). /// </summary> public class Link : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Target URL of a link. Example: "http://example.com/previous".</summary> [Newtonsoft.Json.JsonPropertyAttribute("href")] public virtual string Href { get; set; } /// <summary>Language code of a link. Example: "en".</summary> [Newtonsoft.Json.JsonPropertyAttribute("hreflang")] public virtual string Hreflang { get; set; } /// <summary>Media type of the link destination. Example: "screen".</summary> [Newtonsoft.Json.JsonPropertyAttribute("media")] public virtual string Media { get; set; } /// <summary>Relation type of a link. Example: "previous".</summary> [Newtonsoft.Json.JsonPropertyAttribute("rel")] public virtual string Rel { get; set; } /// <summary>Title of this link. Example: "title".</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>Content type of the link. Example: "application/json".</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>URL giving context for the link. Example: "http://example.com/current".</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual string Value { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Notices object defined in [section 4.3 of RFC 7483](https://tools.ietf.org/html/rfc7483#section-4.3). /// </summary> public class Notice : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Description of the notice.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual System.Collections.Generic.IList<string> Description { get; set; } /// <summary>Link to a document containing more information.</summary> [Newtonsoft.Json.JsonPropertyAttribute("links")] public virtual System.Collections.Generic.IList<Link> Links { get; set; } /// <summary>Title of a notice. Example: "Terms of Service".</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary> /// Type values defined in [section 10.2.1 of RFC 7483](https://tools.ietf.org/html/rfc7483#section-10.2.1) /// specific to a whole response: "result set truncated due to authorization", "result set truncated due to /// excessive load", "result set truncated due to unexplainable reasons". /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response to a general RDAP query.</summary> public class RdapResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Error description.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual System.Collections.Generic.IList<string> Description { get; set; } /// <summary>Error HTTP code. Example: "501".</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorCode")] public virtual System.Nullable<int> ErrorCode { get; set; } /// <summary>HTTP response with content type set to "application/json+rdap".</summary> [Newtonsoft.Json.JsonPropertyAttribute("jsonResponse")] public virtual HttpBody JsonResponse { get; set; } /// <summary> /// Error language code. Error response info fields are defined in [section 6 of RFC /// 7483](https://tools.ietf.org/html/rfc7483#section-6). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("lang")] public virtual string Lang { get; set; } /// <summary>Notices applying to this response.</summary> [Newtonsoft.Json.JsonPropertyAttribute("notices")] public virtual System.Collections.Generic.IList<Notice> Notices { get; set; } /// <summary>RDAP conformance level.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rdapConformance")] public virtual System.Collections.Generic.IList<string> RdapConformance { get; set; } /// <summary>Error title.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Runtime.InteropServices; using Microsoft.DotNet.Cli.Build.Framework; using Microsoft.Extensions.PlatformAbstractions; using static Microsoft.DotNet.Cli.Build.Framework.BuildHelpers; namespace Microsoft.DotNet.Cli.Build { public static class PackageTargets { public static readonly string[] ProjectsToPack = new string[] { "Microsoft.DotNet.Cli.Utils", "Microsoft.DotNet.ProjectModel", "Microsoft.DotNet.ProjectModel.Loader", "Microsoft.DotNet.ProjectModel.Workspaces", "Microsoft.DotNet.InternalAbstractions", "Microsoft.Extensions.DependencyModel", "Microsoft.Extensions.Testing.Abstractions", "Microsoft.DotNet.Compiler.Common", "Microsoft.DotNet.Files", "dotnet-compile-fsc" }; [Target(nameof(PackageTargets.CopyCLISDKLayout), nameof(PackageTargets.CopySharedHostLayout), nameof(PackageTargets.CopySharedFxLayout), nameof(PackageTargets.CopyCombinedFrameworkSDKHostLayout), nameof(PackageTargets.CopyCombinedFrameworkHostLayout))] public static BuildTargetResult InitPackage(BuildTargetContext c) { Directory.CreateDirectory(Dirs.Packages); return c.Success(); } [Target(nameof(PrepareTargets.Init), nameof(PackageTargets.InitPackage), nameof(PackageTargets.GenerateVersionBadge), nameof(PackageTargets.GenerateCompressedFile), nameof(InstallerTargets.GenerateInstaller), nameof(PackageTargets.GenerateNugetPackages), nameof(InstallerTargets.TestInstaller))] [Environment("DOTNET_BUILD_SKIP_PACKAGING", null, "0", "false")] public static BuildTargetResult Package(BuildTargetContext c) { return c.Success(); } [Target] public static BuildTargetResult GenerateVersionBadge(BuildTargetContext c) { var buildVersion = c.BuildContext.Get<BuildVersion>("BuildVersion"); var versionSvg = Path.Combine(Dirs.RepoRoot, "resources", "images", "version_badge.svg"); var outputVersionSvg = c.BuildContext.Get<string>("VersionBadge"); var versionSvgContent = File.ReadAllText(versionSvg); versionSvgContent = versionSvgContent.Replace("ver_number", buildVersion.NuGetVersion); File.WriteAllText(outputVersionSvg, versionSvgContent); return c.Success(); } [Target] public static BuildTargetResult CopyCLISDKLayout(BuildTargetContext c) { var cliSdkRoot = Path.Combine(Dirs.Output, "obj", "clisdk"); if (Directory.Exists(cliSdkRoot)) { Utils.DeleteDirectory(cliSdkRoot); } Directory.CreateDirectory(cliSdkRoot); Utils.CopyDirectoryRecursively(Path.Combine(Dirs.Stage2, "sdk"), cliSdkRoot, true); FixPermissions(cliSdkRoot); c.BuildContext["CLISDKRoot"] = cliSdkRoot; return c.Success(); } [Target] public static BuildTargetResult CopySharedHostLayout(BuildTargetContext c) { var sharedHostRoot = Path.Combine(Dirs.Output, "obj", "sharedHost"); if (Directory.Exists(sharedHostRoot)) { Utils.DeleteDirectory(sharedHostRoot); } Directory.CreateDirectory(sharedHostRoot); foreach (var file in Directory.GetFiles(Dirs.Stage2, "*", SearchOption.TopDirectoryOnly)) { var destFile = file.Replace(Dirs.Stage2, sharedHostRoot); File.Copy(file, destFile, true); } FixPermissions(sharedHostRoot); c.BuildContext["SharedHostPublishRoot"] = sharedHostRoot; return c.Success(); } [Target] public static BuildTargetResult CopySharedFxLayout(BuildTargetContext c) { var sharedFxRoot = Path.Combine(Dirs.Output, "obj", "sharedFx"); if (Directory.Exists(sharedFxRoot)) { Utils.DeleteDirectory(sharedFxRoot); } Directory.CreateDirectory(sharedFxRoot); Utils.CopyDirectoryRecursively(Path.Combine(Dirs.Stage2, "shared"), sharedFxRoot, true); FixPermissions(sharedFxRoot); c.BuildContext["SharedFrameworkPublishRoot"] = sharedFxRoot; return c.Success(); } [Target] public static BuildTargetResult CopyCombinedFrameworkSDKHostLayout(BuildTargetContext c) { var combinedRoot = Path.Combine(Dirs.Output, "obj", "combined-framework-sdk-host"); if (Directory.Exists(combinedRoot)) { Utils.DeleteDirectory(combinedRoot); } string sdkPublishRoot = c.BuildContext.Get<string>("CLISDKRoot"); Utils.CopyDirectoryRecursively(sdkPublishRoot, combinedRoot); string sharedFrameworkPublishRoot = c.BuildContext.Get<string>("SharedFrameworkPublishRoot"); Utils.CopyDirectoryRecursively(sharedFrameworkPublishRoot, combinedRoot); string sharedHostPublishRoot = c.BuildContext.Get<string>("SharedHostPublishRoot"); Utils.CopyDirectoryRecursively(sharedHostPublishRoot, combinedRoot); c.BuildContext["CombinedFrameworkSDKHostRoot"] = combinedRoot; return c.Success(); } [Target] public static BuildTargetResult CopyCombinedFrameworkHostLayout(BuildTargetContext c) { var combinedRoot = Path.Combine(Dirs.Output, "obj", "combined-framework-host"); if (Directory.Exists(combinedRoot)) { Utils.DeleteDirectory(combinedRoot); } string sharedFrameworkPublishRoot = c.BuildContext.Get<string>("SharedFrameworkPublishRoot"); Utils.CopyDirectoryRecursively(sharedFrameworkPublishRoot, combinedRoot); string sharedHostPublishRoot = c.BuildContext.Get<string>("SharedHostPublishRoot"); Utils.CopyDirectoryRecursively(sharedHostPublishRoot, combinedRoot); c.BuildContext["CombinedFrameworkHostRoot"] = combinedRoot; return c.Success(); } [Target(nameof(PackageTargets.GenerateZip), nameof(PackageTargets.GenerateTarBall))] public static BuildTargetResult GenerateCompressedFile(BuildTargetContext c) { return c.Success(); } [Target(nameof(PackageTargets.InitPackage))] [BuildPlatforms(BuildPlatform.Windows)] public static BuildTargetResult GenerateZip(BuildTargetContext c) { CreateZipFromDirectory(c.BuildContext.Get<string>("CombinedFrameworkSDKHostRoot"), c.BuildContext.Get<string>("CombinedFrameworkSDKHostCompressedFile")); CreateZipFromDirectory(c.BuildContext.Get<string>("CombinedFrameworkHostRoot"), c.BuildContext.Get<string>("CombinedFrameworkHostCompressedFile")); CreateZipFromDirectory(Path.Combine(Dirs.Stage2Symbols, "sdk"), c.BuildContext.Get<string>("SdkSymbolsCompressedFile")); return c.Success(); } [Target(nameof(PackageTargets.InitPackage))] [BuildPlatforms(BuildPlatform.Unix)] public static BuildTargetResult GenerateTarBall(BuildTargetContext c) { CreateTarBallFromDirectory(c.BuildContext.Get<string>("CombinedFrameworkSDKHostRoot"), c.BuildContext.Get<string>("CombinedFrameworkSDKHostCompressedFile")); CreateTarBallFromDirectory(c.BuildContext.Get<string>("CombinedFrameworkHostRoot"), c.BuildContext.Get<string>("CombinedFrameworkHostCompressedFile")); CreateTarBallFromDirectory(Path.Combine(Dirs.Stage2Symbols, "sdk"), c.BuildContext.Get<string>("SdkSymbolsCompressedFile")); return c.Success(); } [Target] public static BuildTargetResult GenerateNugetPackages(BuildTargetContext c) { var versionSuffix = c.BuildContext.Get<BuildVersion>("BuildVersion").VersionSuffix; var configuration = c.BuildContext.Get<string>("Configuration"); var env = GetCommonEnvVars(c); var dotnet = DotNetCli.Stage2; var packagingBuildBasePath = Path.Combine(Dirs.Stage2Compilation, "forPackaging"); FS.Mkdirp(Dirs.PackagesIntermediate); FS.Mkdirp(Dirs.Packages); foreach (var projectName in ProjectsToPack) { var projectFile = Path.Combine(Dirs.RepoRoot, "src", projectName, "project.json"); dotnet.Pack( projectFile, "--no-build", "--build-base-path", packagingBuildBasePath, "--output", Dirs.PackagesIntermediate, "--configuration", configuration, "--version-suffix", versionSuffix) .Execute() .EnsureSuccessful(); } var packageFiles = Directory.EnumerateFiles(Dirs.PackagesIntermediate, "*.nupkg"); foreach (var packageFile in packageFiles) { if (!packageFile.EndsWith(".symbols.nupkg")) { var destinationPath = Path.Combine(Dirs.Packages, Path.GetFileName(packageFile)); File.Copy(packageFile, destinationPath, overwrite: true); } } return c.Success(); } internal static Dictionary<string, string> GetCommonEnvVars(BuildTargetContext c) { // Set up the environment variables previously defined by common.sh/ps1 // This is overkill, but I want to cover all the variables used in all OSes (including where some have the same names) var buildVersion = c.BuildContext.Get<BuildVersion>("BuildVersion"); var configuration = c.BuildContext.Get<string>("Configuration"); var architecture = PlatformServices.Default.Runtime.RuntimeArchitecture; var env = new Dictionary<string, string>() { { "RID", PlatformServices.Default.Runtime.GetRuntimeIdentifier() }, { "OSNAME", PlatformServices.Default.Runtime.OperatingSystem }, { "TFM", "dnxcore50" }, { "REPOROOT", Dirs.RepoRoot }, { "OutputDir", Dirs.Output }, { "Stage1Dir", Dirs.Stage1 }, { "Stage1CompilationDir", Dirs.Stage1Compilation }, { "Stage2Dir", Dirs.Stage2 }, { "STAGE2_DIR", Dirs.Stage2 }, { "Stage2CompilationDir", Dirs.Stage2Compilation }, { "HostDir", Dirs.Corehost }, { "PackageDir", Path.Combine(Dirs.Packages) }, // Legacy name { "TestBinRoot", Dirs.TestOutput }, { "TestPackageDir", Dirs.TestPackages }, { "MajorVersion", buildVersion.Major.ToString() }, { "MinorVersion", buildVersion.Minor.ToString() }, { "PatchVersion", buildVersion.Patch.ToString() }, { "CommitCountVersion", buildVersion.CommitCountString }, { "COMMIT_COUNT_VERSION", buildVersion.CommitCountString }, { "DOTNET_CLI_VERSION", buildVersion.SimpleVersion }, { "DOTNET_MSI_VERSION", buildVersion.GenerateMsiVersion() }, { "VersionSuffix", buildVersion.VersionSuffix }, { "CONFIGURATION", configuration }, { "ARCHITECTURE", architecture } }; return env; } private static void CreateZipFromDirectory(string directory, string artifactPath) { if (File.Exists(artifactPath)) { File.Delete(artifactPath); } ZipFile.CreateFromDirectory(directory, artifactPath, CompressionLevel.Optimal, false); } private static void CreateTarBallFromDirectory(string directory, string artifactPath) { if (File.Exists(artifactPath)) { File.Delete(artifactPath); } Cmd("tar", "-czf", artifactPath, "-C", directory, ".") .Execute() .EnsureSuccessful(); } private static void FixPermissions(string directory) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Reset everything to user readable/writeable and group and world readable. FS.ChmodAll(directory, "*", "644"); // Now make things that should be executable, executable. FS.FixModeFlags(directory); } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Utils; using osu.Framework.Platform; using osu.Framework.Screens; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Overlays.Settings; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays.AccountCreation { public class ScreenEntry : AccountCreationScreen { private ErrorTextFlowContainer usernameDescription; private ErrorTextFlowContainer emailAddressDescription; private ErrorTextFlowContainer passwordDescription; private OsuTextBox usernameTextBox; private OsuTextBox emailTextBox; private OsuPasswordTextBox passwordTextBox; [Resolved] private IAPIProvider api { get; set; } private ShakeContainer registerShake; private IEnumerable<Drawable> characterCheckText; private OsuTextBox[] textboxes; private LoadingLayer loadingLayer; [Resolved] private GameHost host { get; set; } [BackgroundDependencyLoader] private void load(OsuColour colours) { FillFlowContainer mainContent; InternalChildren = new Drawable[] { mainContent = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Padding = new MarginPadding(20), Spacing = new Vector2(0, 10), Children = new Drawable[] { new OsuSpriteText { Margin = new MarginPadding { Vertical = 10 }, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Font = OsuFont.GetFont(size: 20), Text = "Let's create an account!", }, usernameTextBox = new OsuTextBox { PlaceholderText = "username", RelativeSizeAxes = Axes.X, TabbableContentContainer = this }, usernameDescription = new ErrorTextFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y }, emailTextBox = new OsuTextBox { PlaceholderText = "email address", RelativeSizeAxes = Axes.X, TabbableContentContainer = this }, emailAddressDescription = new ErrorTextFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y }, passwordTextBox = new OsuPasswordTextBox { PlaceholderText = "password", RelativeSizeAxes = Axes.X, TabbableContentContainer = this, }, passwordDescription = new ErrorTextFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y }, new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { registerShake = new ShakeContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Child = new SettingsButton { Text = "Register", Margin = new MarginPadding { Vertical = 20 }, Action = performRegistration } } } }, }, }, loadingLayer = new LoadingLayer(mainContent) }; textboxes = new[] { usernameTextBox, emailTextBox, passwordTextBox }; usernameDescription.AddText("This will be your public presence. No profanity, no impersonation. Avoid exposing your own personal details, too!"); emailAddressDescription.AddText("Will be used for notifications, account verification and in the case you forget your password. No spam, ever."); emailAddressDescription.AddText(" Make sure to get it right!", cp => cp.Font = cp.Font.With(Typeface.Torus, weight: FontWeight.Bold)); passwordDescription.AddText("At least "); characterCheckText = passwordDescription.AddText("8 characters long"); passwordDescription.AddText(". Choose something long but also something you will remember, like a line from your favourite song."); passwordTextBox.Current.ValueChanged += password => { characterCheckText.ForEach(s => s.Colour = password.NewValue.Length == 0 ? Color4.White : Interpolation.ValueAt(password.NewValue.Length, Color4.OrangeRed, Color4.YellowGreen, 0, 8, Easing.In)); }; } public override void OnEntering(IScreen last) { base.OnEntering(last); loadingLayer.Hide(); if (host?.OnScreenKeyboardOverlapsGameWindow != true) focusNextTextbox(); } private void performRegistration() { if (focusNextTextbox()) { registerShake.Shake(); return; } usernameDescription.ClearErrors(); emailAddressDescription.ClearErrors(); passwordDescription.ClearErrors(); loadingLayer.Show(); Task.Run(() => { bool success; RegistrationRequest.RegistrationRequestErrors errors = null; try { errors = api.CreateAccount(emailTextBox.Text, usernameTextBox.Text, passwordTextBox.Text); success = errors == null; } catch (Exception) { success = false; } Schedule(() => { if (!success) { if (errors != null) { usernameDescription.AddErrors(errors.User.Username); emailAddressDescription.AddErrors(errors.User.Email); passwordDescription.AddErrors(errors.User.Password); } else { passwordDescription.AddErrors(new[] { "Something happened... but we're not sure what." }); } registerShake.Shake(); loadingLayer.Hide(); return; } api.Login(usernameTextBox.Text, passwordTextBox.Text); }); }); } private bool focusNextTextbox() { var nextTextbox = nextUnfilledTextbox(); if (nextTextbox != null) { Schedule(() => GetContainingInputManager().ChangeFocus(nextTextbox)); return true; } return false; } private OsuTextBox nextUnfilledTextbox() => textboxes.FirstOrDefault(t => string.IsNullOrEmpty(t.Text)); } }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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.Runtime.InteropServices; using VSLangProj; using VSLangProj80; namespace Microsoft.VisualStudioTools.Project.Automation { /// <summary> /// Represents the automation equivalent of ReferenceNode /// </summary> /// <typeparam name="RefType"></typeparam> [ComVisible(true)] public abstract class OAReferenceBase : Reference3 { #region fields private ReferenceNode referenceNode; #endregion #region ctors internal OAReferenceBase(ReferenceNode referenceNode) { this.referenceNode = referenceNode; } #endregion #region properties internal ReferenceNode BaseReferenceNode { get { return referenceNode; } } #endregion #region Reference Members public virtual int BuildNumber { get { return 0; } } public virtual References Collection { get { return BaseReferenceNode.Parent.Object as References; } } public virtual EnvDTE.Project ContainingProject { get { return BaseReferenceNode.ProjectMgr.GetAutomationObject() as EnvDTE.Project; } } public virtual bool CopyLocal { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual string Culture { get { throw new NotImplementedException(); } } public virtual EnvDTE.DTE DTE { get { return BaseReferenceNode.ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; } } public virtual string Description { get { return this.Name; } } public virtual string ExtenderCATID { get { throw new NotImplementedException(); } } public virtual object ExtenderNames { get { throw new NotImplementedException(); } } public virtual string Identity { get { throw new NotImplementedException(); } } public virtual int MajorVersion { get { return 0; } } public virtual int MinorVersion { get { return 0; } } public virtual string Name { get { throw new NotImplementedException(); } } public virtual string Path { get { return BaseReferenceNode.Url; } } public virtual string PublicKeyToken { get { throw new NotImplementedException(); } } public virtual void Remove() { BaseReferenceNode.Remove(false); } public virtual int RevisionNumber { get { return 0; } } public virtual EnvDTE.Project SourceProject { get { return null; } } public virtual bool StrongName { get { return false; } } public virtual prjReferenceType Type { get { throw new NotImplementedException(); } } public virtual string Version { get { return new Version().ToString(); } } public virtual object get_Extender(string ExtenderName) { throw new NotImplementedException(); } #endregion public string Aliases { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool AutoReferenced { get { throw new NotImplementedException(); } } public virtual bool Isolated { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public uint RefType { get { throw new NotImplementedException(); } } public virtual bool Resolved { get { throw new NotImplementedException(); } } public string RuntimeVersion { get { throw new NotImplementedException(); } } public virtual bool SpecificVersion { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual string SubType { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } }
//Copyright 2015 Esri //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License.? using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using ESRI.ArcGIS.DataSourcesFile; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geoprocessing; using ESRI.ArcGIS.JTX; namespace WorkflowManagerAdministrationUtilities { public class UploadTaskAssistantWorkbook : WmauAbstractGpFunction { #region Constants private const string C_PARAM_XML_FILE_PATH = "in_file_tamWorkbookXml"; private const string C_PARAM_TARGET_NAME = "in_string_targetName"; private const string C_PARAM_OVERWRITE_EXISTING = "in_boolean_overwriteExisting"; private const string C_PARAM_OUT_TARGET_NAME = "out_string_targetName"; private const string C_OPT_OVERWRITE = "OVERWRITE"; private const string C_OPT_NO_OVERWRITE = "NO_OVERWRITE"; private const bool C_DEFAULT_OVERWRITE_EXISTING = true; #endregion #region MemberVariables private string m_xmlFilePath = string.Empty; private string m_targetName = string.Empty; private bool m_overwriteExisting = C_DEFAULT_OVERWRITE_EXISTING; #endregion #region SimpleAccessors public override string Name { get { return "UploadTaskAssistantWorkbook"; } } public override string DisplayName { get { return Properties.Resources.TOOL_UPLOAD_TASK_ASSISTANT_WORKBOOK; } } public override string DisplayToolset { get { return Properties.Resources.CAT_TAM_UTILS; } } #endregion #region Private helper functions /// <summary> /// Helper function to build a ".TMStyle" file name given a ".xml" workflow file name /// </summary> /// <param name="workbookFileName"></param> /// <returns></returns> private string DetermineStyleFileName(string workbookFileName) { string styleFileName = System.IO.Path.GetDirectoryName(workbookFileName) + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileNameWithoutExtension(workbookFileName) + ".TMStyle"; return styleFileName; } /// <summary> /// Updates the internal values used by this tool based on the parameters from an input array /// </summary> /// <param name="paramValues"></param> protected override void ExtractParameters(IArray paramValues) { // Get the values for any parameters common to all GP tools ExtractParametersCommon(paramValues); WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameter3 param = null; // Update the internal values of whatever parameters we're maintaining param = paramMap.GetParam(C_PARAM_XML_FILE_PATH); m_xmlFilePath = param.Value.GetAsText(); param = paramMap.GetParam(C_PARAM_TARGET_NAME); m_targetName = param.Value.GetAsText(); param = paramMap.GetParam(C_PARAM_OVERWRITE_EXISTING); m_overwriteExisting = bool.Parse(param.Value.GetAsText()); } #endregion /// <summary> /// Required by IGPFunction2 interface. /// </summary> public override IArray ParameterInfo { get { m_parameters = new ArrayClass(); IGPParameterEdit3 paramEdit = null; IGPCodedValueDomain cvDomain = null; // TAM file parameter (path to source XML file) IGPFileDomain xmlFileDomain = new GPFileDomainClass(); xmlFileDomain.AddType("xml"); paramEdit = BuildParameter( esriGPParameterDirection.esriGPParameterDirectionInput, esriGPParameterType.esriGPParameterTypeRequired, Properties.Resources.DESC_UTAM_XML_FILE_PATH, C_PARAM_XML_FILE_PATH, new DEFileTypeClass() as IGPDataType, null); paramEdit.Domain = xmlFileDomain as IGPDomain; m_parameters.Add(paramEdit); // Target name paramEdit = BuildParameter( esriGPParameterDirection.esriGPParameterDirectionInput, esriGPParameterType.esriGPParameterTypeRequired, Properties.Resources.DESC_UTAM_TARGET_NAME, C_PARAM_TARGET_NAME, new GPStringTypeClass(), null); m_parameters.Add(paramEdit); // Optional parameter indicating whether existing TAM workbooks of the same name should // be overwritten cvDomain = new GPCodedValueDomainClass(); cvDomain.AddCode(GpTrue, C_OPT_OVERWRITE); cvDomain.AddCode(GpFalse, C_OPT_NO_OVERWRITE); paramEdit = BuildParameter( esriGPParameterDirection.esriGPParameterDirectionInput, esriGPParameterType.esriGPParameterTypeOptional, Properties.Resources.DESC_UTAM_OVERWRITE_EXISTING, C_PARAM_OVERWRITE_EXISTING, GpBooleanType, ToGpBoolean(C_DEFAULT_OVERWRITE_EXISTING)); paramEdit.Domain = cvDomain as IGPDomain; m_parameters.Add(paramEdit); // Parameter for specifying the WMX database m_parameters.Add(BuildWmxDbParameter()); // Output parameter (echoing the uploaded workbook's name in the database) paramEdit = BuildParameter( esriGPParameterDirection.esriGPParameterDirectionOutput, esriGPParameterType.esriGPParameterTypeDerived, Properties.Resources.DESC_UTAM_OUT_TARGET_NAME, C_PARAM_OUT_TARGET_NAME, new GPStringTypeClass(), null); m_parameters.Add(paramEdit); return m_parameters; } } /// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } // Retrieve the TA workbook IJTXConfiguration3 defaultDbReadonly = WmxDatabase.ConfigurationManager as IJTXConfiguration3; IJTXTaskAssistantWorkflowRecord tamRecord = defaultDbReadonly.GetTaskAssistantWorkflowRecord(this.m_targetName); string styleFileName = this.DetermineStyleFileName(this.m_xmlFilePath); // If we're not allowed to overwrite an existing TA record, then do some error checking if (!this.m_overwriteExisting && tamRecord != null) { msgs.AddWarning("Did not overwrite Task Assistant workbook: " + this.m_targetName); return; } else if (tamRecord != null) { msgs.AddMessage("Replacing Task Assistant workbook '" + m_targetName + "' in database..."); defaultDbReadonly.ReplaceTaskAssistantWorkflowRecord(this.m_targetName, this.m_targetName, this.m_xmlFilePath, styleFileName); } else // tamRecord == null { msgs.AddMessage("Adding Task Assistant workbook '" + m_targetName + "' to database..."); defaultDbReadonly.AddTaskAssistantWorkflowRecord(this.m_targetName, this.m_xmlFilePath, styleFileName); } // Update the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_TARGET_NAME); IGPString outValue = new GPStringClass(); outValue.Value = m_targetName; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_TAM_UPLOAD_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } } } }