context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class ImportAllTapesSpectraS3Request : Ds3Request { private ImportConflictResolutionMode? _conflictResolutionMode; public ImportConflictResolutionMode? ConflictResolutionMode { get { return _conflictResolutionMode; } set { WithConflictResolutionMode(value); } } private string _dataPolicyId; public string DataPolicyId { get { return _dataPolicyId; } set { WithDataPolicyId(value); } } private Priority? _priority; public Priority? Priority { get { return _priority; } set { WithPriority(value); } } private string _storageDomainId; public string StorageDomainId { get { return _storageDomainId; } set { WithStorageDomainId(value); } } private string _userId; public string UserId { get { return _userId; } set { WithUserId(value); } } private Priority? _verifyDataAfterImport; public Priority? VerifyDataAfterImport { get { return _verifyDataAfterImport; } set { WithVerifyDataAfterImport(value); } } private bool? _verifyDataPriorToImport; public bool? VerifyDataPriorToImport { get { return _verifyDataPriorToImport; } set { WithVerifyDataPriorToImport(value); } } public ImportAllTapesSpectraS3Request WithConflictResolutionMode(ImportConflictResolutionMode? conflictResolutionMode) { this._conflictResolutionMode = conflictResolutionMode; if (conflictResolutionMode != null) { this.QueryParams.Add("conflict_resolution_mode", conflictResolutionMode.ToString()); } else { this.QueryParams.Remove("conflict_resolution_mode"); } return this; } public ImportAllTapesSpectraS3Request WithDataPolicyId(Guid? dataPolicyId) { this._dataPolicyId = dataPolicyId.ToString(); if (dataPolicyId != null) { this.QueryParams.Add("data_policy_id", dataPolicyId.ToString()); } else { this.QueryParams.Remove("data_policy_id"); } return this; } public ImportAllTapesSpectraS3Request WithDataPolicyId(string dataPolicyId) { this._dataPolicyId = dataPolicyId; if (dataPolicyId != null) { this.QueryParams.Add("data_policy_id", dataPolicyId); } else { this.QueryParams.Remove("data_policy_id"); } return this; } public ImportAllTapesSpectraS3Request WithPriority(Priority? priority) { this._priority = priority; if (priority != null) { this.QueryParams.Add("priority", priority.ToString()); } else { this.QueryParams.Remove("priority"); } return this; } public ImportAllTapesSpectraS3Request WithStorageDomainId(Guid? storageDomainId) { this._storageDomainId = storageDomainId.ToString(); if (storageDomainId != null) { this.QueryParams.Add("storage_domain_id", storageDomainId.ToString()); } else { this.QueryParams.Remove("storage_domain_id"); } return this; } public ImportAllTapesSpectraS3Request WithStorageDomainId(string storageDomainId) { this._storageDomainId = storageDomainId; if (storageDomainId != null) { this.QueryParams.Add("storage_domain_id", storageDomainId); } else { this.QueryParams.Remove("storage_domain_id"); } return this; } public ImportAllTapesSpectraS3Request WithUserId(Guid? userId) { this._userId = userId.ToString(); if (userId != null) { this.QueryParams.Add("user_id", userId.ToString()); } else { this.QueryParams.Remove("user_id"); } return this; } public ImportAllTapesSpectraS3Request WithUserId(string userId) { this._userId = userId; if (userId != null) { this.QueryParams.Add("user_id", userId); } else { this.QueryParams.Remove("user_id"); } return this; } public ImportAllTapesSpectraS3Request WithVerifyDataAfterImport(Priority? verifyDataAfterImport) { this._verifyDataAfterImport = verifyDataAfterImport; if (verifyDataAfterImport != null) { this.QueryParams.Add("verify_data_after_import", verifyDataAfterImport.ToString()); } else { this.QueryParams.Remove("verify_data_after_import"); } return this; } public ImportAllTapesSpectraS3Request WithVerifyDataPriorToImport(bool? verifyDataPriorToImport) { this._verifyDataPriorToImport = verifyDataPriorToImport; if (verifyDataPriorToImport != null) { this.QueryParams.Add("verify_data_prior_to_import", verifyDataPriorToImport.ToString()); } else { this.QueryParams.Remove("verify_data_prior_to_import"); } return this; } public ImportAllTapesSpectraS3Request() { this.QueryParams.Add("operation", "import"); } internal override HttpVerb Verb { get { return HttpVerb.PUT; } } internal override string Path { get { return "/_rest_/tape"; } } } }
/* * Exchange Web Services Managed API * * 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. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Text; /// <summary> /// Represents a custom time zone time change. /// </summary> internal sealed class LegacyAvailabilityTimeZoneTime : ComplexProperty { private TimeSpan delta; private int year; private int month; private int dayOrder; private DayOfTheWeek dayOfTheWeek; private TimeSpan timeOfDay; /// <summary> /// Initializes a new instance of the <see cref="LegacyAvailabilityTimeZoneTime"/> class. /// </summary> internal LegacyAvailabilityTimeZoneTime() : base() { } /// <summary> /// Initializes a new instance of the <see cref="LegacyAvailabilityTimeZoneTime"/> class. /// </summary> /// <param name="transitionTime">The transition time used to initialize this instance.</param> /// <param name="delta">The offset used to initialize this instance.</param> internal LegacyAvailabilityTimeZoneTime(TimeZoneInfo.TransitionTime transitionTime, TimeSpan delta) : this() { this.delta = delta; if (transitionTime.IsFixedDateRule) { // TimeZoneInfo doesn't support an actual year. Fixed date transitions occur at the same // date every year the adjustment rule the transition belongs to applies. The best thing // we can do here is use the current year. this.year = DateTime.Today.Year; this.month = transitionTime.Month; this.dayOrder = transitionTime.Day; this.timeOfDay = transitionTime.TimeOfDay.TimeOfDay; } else { // For floating rules, the mapping is direct. this.year = 0; this.month = transitionTime.Month; this.dayOfTheWeek = EwsUtilities.SystemToEwsDayOfTheWeek(transitionTime.DayOfWeek); this.dayOrder = transitionTime.Week; this.timeOfDay = transitionTime.TimeOfDay.TimeOfDay; } } /// <summary> /// Converts this instance to TimeZoneInfo.TransitionTime. /// </summary> /// <returns>A TimeZoneInfo.TransitionTime</returns> internal TimeZoneInfo.TransitionTime ToTransitionTime() { if (this.year == 0) { return TimeZoneInfo.TransitionTime.CreateFloatingDateRule( new DateTime( DateTime.MinValue.Year, DateTime.MinValue.Month, DateTime.MinValue.Day, this.timeOfDay.Hours, this.timeOfDay.Minutes, this.timeOfDay.Seconds), this.month, this.dayOrder, EwsUtilities.EwsToSystemDayOfWeek(this.dayOfTheWeek)); } else { return TimeZoneInfo.TransitionTime.CreateFixedDateRule( new DateTime(this.timeOfDay.Ticks), this.month, this.dayOrder); } } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.Bias: this.delta = TimeSpan.FromMinutes(reader.ReadElementValue<int>()); return true; case XmlElementNames.Time: this.timeOfDay = TimeSpan.Parse(reader.ReadElementValue()); return true; case XmlElementNames.DayOrder: this.dayOrder = reader.ReadElementValue<int>(); return true; case XmlElementNames.DayOfWeek: this.dayOfTheWeek = reader.ReadElementValue<DayOfTheWeek>(); return true; case XmlElementNames.Month: this.month = reader.ReadElementValue<int>(); return true; case XmlElementNames.Year: this.year = reader.ReadElementValue<int>(); return true; default: return false; } } /// <summary> /// Writes the elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Bias, (int)this.delta.TotalMinutes); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Time, EwsUtilities.TimeSpanToXSTime(this.timeOfDay)); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DayOrder, this.dayOrder); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Month, (int)this.month); // Only write DayOfWeek if this is a recurring time change if (this.Year == 0) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DayOfWeek, this.dayOfTheWeek); } // Only emit year if it's non zero, otherwise AS returns "Request is invalid" if (this.Year != 0) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Year, this.Year); } } /// <summary> /// Gets if current time presents DST transition time /// </summary> internal bool HasTransitionTime { get { return this.month >= 1 && this.month <= 12; } } /// <summary> /// Gets or sets the delta. /// </summary> internal TimeSpan Delta { get { return this.delta; } set { this.delta = value; } } /// <summary> /// Gets or sets the time of day. /// </summary> internal TimeSpan TimeOfDay { get { return this.timeOfDay; } set { this.timeOfDay = value; } } /// <summary> /// Gets or sets a value that represents: /// - The day of the month when Year is non zero, /// - The index of the week in the month if Year is equal to zero. /// </summary> internal int DayOrder { get { return this.dayOrder; } set { this.dayOrder = value; } } /// <summary> /// Gets or sets the month. /// </summary> internal int Month { get { return this.month; } set { this.month = value; } } /// <summary> /// Gets or sets the day of the week. /// </summary> internal DayOfTheWeek DayOfTheWeek { get { return this.dayOfTheWeek; } set { this.dayOfTheWeek = value; } } /// <summary> /// Gets or sets the year. If Year is 0, the time change occurs every year according to a recurring pattern; /// otherwise, the time change occurs at the date specified by Day, Month, Year. /// </summary> internal int Year { get { return this.year; } set { this.year = value; } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// Aquarium. /// </summary> public class Aquarium_Core : TypeCore, ICivicStructure { public Aquarium_Core() { this._TypeId = 18; this._Id = "Aquarium"; this._Schema_Org_Url = "http://schema.org/Aquarium"; string label = ""; GetLabel(out label, "Aquarium", typeof(Aquarium_Core)); this._Label = label; this._Ancestors = new int[]{266,206,62}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{62}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
/* Copyright (c) 2006 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. */ #define USE_TRACING using System; using System.Xml; using System.IO; using System.Collections; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.Extensions.MediaRss; using Google.GData.Extensions.Exif; using Google.GData.Extensions.Location; namespace Google.GData.Photos { ////////////////////////////////////////////////////////////////////// /// <summary> /// Entry API customization class for defining entries in an Event feed. /// </summary> ////////////////////////////////////////////////////////////////////// public class PicasaEntry : AbstractEntry { /// <summary> /// Category used to label entries that contain photo extension data. /// </summary> public static AtomCategory PHOTO_CATEGORY = new AtomCategory(GPhotoNameTable.PhotoKind, new AtomUri(BaseNameTable.gKind)); /// <summary> /// Category used to label entries that contain photo extension data. /// </summary> public static AtomCategory ALBUM_CATEGORY = new AtomCategory(GPhotoNameTable.AlbumKind, new AtomUri(BaseNameTable.gKind)); /// <summary> /// Category used to label entries that contain comment extension data. /// </summary> public static AtomCategory COMMENT_CATEGORY = new AtomCategory(GPhotoNameTable.CommentKind, new AtomUri(BaseNameTable.gKind)); /// <summary> /// Category used to label entries that contain photo extension data. /// </summary> public static AtomCategory TAG_CATEGORY = new AtomCategory(GPhotoNameTable.TagKind, new AtomUri(BaseNameTable.gKind)); /// <summary> /// Constructs a new PicasaEntry instance /// </summary> public PicasaEntry() : base() { Tracing.TraceMsg("Created PicasaEntry"); GPhotoExtensions.AddExtension(this); MediaRssExtensions.AddExtension(this); ExifExtensions.AddExtension(this); GeoRssExtensions.AddExtension(this); } /// <summary> /// getter/setter for the GeoRssWhere extension element /// </summary> public GeoRssWhere Location { get { return FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere; } set { ReplaceExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss, value); } } /// <summary> /// getter/setter for the ExifTags extension element /// </summary> public ExifTags Exif { get { return FindExtension(ExifNameTable.ExifTags, ExifNameTable.NSExif) as ExifTags; } set { ReplaceExtension(ExifNameTable.ExifTags, ExifNameTable.NSExif, value); } } /// <summary> /// returns the media:rss group container element /// </summary> public MediaGroup Media { get { return FindExtension(MediaRssNameTable.MediaRssGroup, MediaRssNameTable.NSMediaRss) as MediaGroup; } set { ReplaceExtension(MediaRssNameTable.MediaRssGroup, MediaRssNameTable.NSMediaRss, value); } } /// <summary> /// instead of having 20 extension elements /// we have one string based getter /// usage is: entry.getPhotoExtension("albumid") to get the element /// </summary> /// <param name="extension">the name of the extension to look for</param> /// <returns>SimpleElement, or NULL if the extension was not found</returns> public SimpleElement GetPhotoExtension(string extension) { return FindExtension(extension, GPhotoNameTable.NSGPhotos) as SimpleElement; } /// <summary> /// instead of having 20 extension elements /// we have one string based getter /// usage is: entry.GetPhotoExtensionValue("albumid") to get the elements value /// </summary> /// <param name="extension">the name of the extension to look for</param> /// <returns>value as string, or NULL if the extension was not found</returns> public string GetPhotoExtensionValue(string extension) { return GetExtensionValue(extension, GPhotoNameTable.NSGPhotos); } /// <summary> /// instead of having 20 extension elements /// we have one string based setter /// usage is: entry.SetPhotoExtensionValue("albumid") to set the element /// this will create the extension if it's not there /// note, you can ofcourse, just get an existing one and work with that /// object: /// SimpleElement e = entry.getPhotoExtension("albumid"); /// e.Value = "new value"; /// /// or /// entry.SetPhotoExtensionValue("albumid", "new Value"); /// </summary> /// <param name="extension">the name of the extension to look for</param> /// <param name="newValue">the new value for this extension element</param> /// <returns>SimpleElement, either a brand new one, or the one /// returned by the service</returns> public SimpleElement SetPhotoExtensionValue(string extension, string newValue) { return SetExtensionValue(extension, GPhotoNameTable.NSGPhotos, newValue); } /// <summary> /// returns true if the entry is a photo entry /// </summary> public bool IsPhoto { get { return (this.Categories.Contains(PHOTO_CATEGORY)); } set { ToggleCategory(PHOTO_CATEGORY, value); } } /// <summary> /// returns true if the entry is a comment entry /// </summary> public bool IsComment { get { return (this.Categories.Contains(COMMENT_CATEGORY)); } set { ToggleCategory(COMMENT_CATEGORY, value); } } /// <summary> /// returns true if the entry is an album entry /// </summary> public bool IsAlbum { get { return (this.Categories.Contains(ALBUM_CATEGORY)); } set { ToggleCategory(ALBUM_CATEGORY, value); } } /// <summary> /// returns true if the entry is a tag entry /// </summary> public bool IsTag { get { return (this.Categories.Contains(TAG_CATEGORY)); } set { ToggleCategory(TAG_CATEGORY, 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; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Xml; using System.Security; namespace System.Runtime.Serialization { #if NET_NATIVE public class DataMember #else internal class DataMember #endif { [SecurityCritical] /// <SecurityNote> /// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization. /// Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// </SecurityNote> private CriticalHelper _helper; /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> [SecuritySafeCritical] public DataMember() { _helper = new CriticalHelper(); } /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> [SecuritySafeCritical] internal DataMember(MemberInfo memberInfo) { _helper = new CriticalHelper(memberInfo); } /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> [SecuritySafeCritical] internal DataMember(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order) { _helper = new CriticalHelper(memberTypeContract, name, isNullable, isRequired, emitDefaultValue, order); } internal MemberInfo MemberInfo { [SecuritySafeCritical] get { return _helper.MemberInfo; } } public string Name { [SecuritySafeCritical] get { return _helper.Name; } [SecurityCritical] set { _helper.Name = value; } } public int Order { [SecuritySafeCritical] get { return _helper.Order; } [SecurityCritical] set { _helper.Order = value; } } public bool IsRequired { [SecuritySafeCritical] get { return _helper.IsRequired; } [SecurityCritical] set { _helper.IsRequired = value; } } public bool EmitDefaultValue { [SecuritySafeCritical] get { return _helper.EmitDefaultValue; } [SecurityCritical] set { _helper.EmitDefaultValue = value; } } public bool IsNullable { [SecuritySafeCritical] get { return _helper.IsNullable; } [SecurityCritical] set { _helper.IsNullable = value; } } public bool IsGetOnlyCollection { [SecuritySafeCritical] get { return _helper.IsGetOnlyCollection; } [SecurityCritical] set { _helper.IsGetOnlyCollection = value; } } internal Type MemberType { [SecuritySafeCritical] get { return _helper.MemberType; } } internal DataContract MemberTypeContract { [SecuritySafeCritical] get { return _helper.MemberTypeContract; } } public bool HasConflictingNameAndType { [SecuritySafeCritical] get { return _helper.HasConflictingNameAndType; } [SecurityCritical] set { _helper.HasConflictingNameAndType = value; } } internal DataMember ConflictingMember { [SecuritySafeCritical] get { return _helper.ConflictingMember; } [SecurityCritical] set { _helper.ConflictingMember = value; } } [SecurityCritical] /// <SecurityNote> /// Critical /// </SecurityNote> private class CriticalHelper { private DataContract _memberTypeContract; private string _name; private int _order; private bool _isRequired; private bool _emitDefaultValue; private bool _isNullable; private bool _isGetOnlyCollection = false; private MemberInfo _memberInfo; private bool _hasConflictingNameAndType; private DataMember _conflictingMember; internal CriticalHelper() { _emitDefaultValue = Globals.DefaultEmitDefaultValue; } internal CriticalHelper(MemberInfo memberInfo) { _emitDefaultValue = Globals.DefaultEmitDefaultValue; _memberInfo = memberInfo; } internal CriticalHelper(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order) { this.MemberTypeContract = memberTypeContract; this.Name = name; this.IsNullable = isNullable; this.IsRequired = isRequired; this.EmitDefaultValue = emitDefaultValue; this.Order = order; } internal MemberInfo MemberInfo { get { return _memberInfo; } } internal string Name { get { return _name; } set { _name = value; } } internal int Order { get { return _order; } set { _order = value; } } internal bool IsRequired { get { return _isRequired; } set { _isRequired = value; } } internal bool EmitDefaultValue { get { return _emitDefaultValue; } set { _emitDefaultValue = value; } } internal bool IsNullable { get { return _isNullable; } set { _isNullable = value; } } internal bool IsGetOnlyCollection { get { return _isGetOnlyCollection; } set { _isGetOnlyCollection = value; } } internal Type MemberType { get { FieldInfo field = MemberInfo as FieldInfo; if (field != null) return field.FieldType; return ((PropertyInfo)MemberInfo).PropertyType; } } internal DataContract MemberTypeContract { get { if (_memberTypeContract == null) { if (MemberInfo != null) { if (this.IsGetOnlyCollection) { _memberTypeContract = DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(MemberType.TypeHandle), MemberType.TypeHandle, MemberType, SerializationMode.SharedContract); } else { _memberTypeContract = DataContract.GetDataContract(MemberType); } } } return _memberTypeContract; } set { _memberTypeContract = value; } } internal bool HasConflictingNameAndType { get { return _hasConflictingNameAndType; } set { _hasConflictingNameAndType = value; } } internal DataMember ConflictingMember { get { return _conflictingMember; } set { _conflictingMember = value; } } } /// <SecurityNote> /// Review - checks member visibility to calculate if access to it 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 RequiresMemberAccessForGet() { MemberInfo memberInfo = MemberInfo; FieldInfo field = memberInfo as FieldInfo; if (field != null) { return DataContract.FieldRequiresMemberAccess(field); } else { PropertyInfo property = (PropertyInfo)memberInfo; MethodInfo getMethod = property.GetMethod; if (getMethod != null) { return DataContract.MethodRequiresMemberAccess(getMethod) || !DataContract.IsTypeVisible(property.PropertyType); } } return false; } /// <SecurityNote> /// Review - checks member visibility to calculate if access to it 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 RequiresMemberAccessForSet() { MemberInfo memberInfo = MemberInfo; FieldInfo field = memberInfo as FieldInfo; if (field != null) { return DataContract.FieldRequiresMemberAccess(field); } else { PropertyInfo property = (PropertyInfo)memberInfo; MethodInfo setMethod = property.SetMethod; if (setMethod != null) { return DataContract.MethodRequiresMemberAccess(setMethod) || !DataContract.IsTypeVisible(property.PropertyType); } } return false; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>FeedItemTarget</c> resource.</summary> public sealed partial class FeedItemTargetName : gax::IResourceName, sys::IEquatable<FeedItemTargetName> { /// <summary>The possible contents of <see cref="FeedItemTargetName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c> /// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c> /// . /// </summary> CustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget = 1, } private static gax::PathTemplate s_customerFeedFeedItemFeedItemTargetTypeFeedItemTarget = new gax::PathTemplate("customers/{customer_id}/feedItemTargets/{feed_id_feed_item_id_feed_item_target_type_feed_item_target_id}"); /// <summary>Creates a <see cref="FeedItemTargetName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="FeedItemTargetName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static FeedItemTargetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new FeedItemTargetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="FeedItemTargetName"/> with the pattern /// <c> /// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemTargetTypeId"> /// The <c>FeedItemTargetType</c> ID. Must not be <c>null</c> or empty. /// </param> /// <param name="feedItemTargetId">The <c>FeedItemTarget</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="FeedItemTargetName"/> constructed from the provided ids.</returns> public static FeedItemTargetName FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget(string customerId, string feedId, string feedItemId, string feedItemTargetTypeId, string feedItemTargetId) => new FeedItemTargetName(ResourceNameType.CustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId)), feedItemTargetTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetTypeId, nameof(feedItemTargetTypeId)), feedItemTargetId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetId, nameof(feedItemTargetId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedItemTargetName"/> with pattern /// <c> /// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemTargetTypeId"> /// The <c>FeedItemTargetType</c> ID. Must not be <c>null</c> or empty. /// </param> /// <param name="feedItemTargetId">The <c>FeedItemTarget</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedItemTargetName"/> with pattern /// <c> /// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c> /// . /// </returns> public static string Format(string customerId, string feedId, string feedItemId, string feedItemTargetTypeId, string feedItemTargetId) => FormatCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget(customerId, feedId, feedItemId, feedItemTargetTypeId, feedItemTargetId); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedItemTargetName"/> with pattern /// <c> /// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemTargetTypeId"> /// The <c>FeedItemTargetType</c> ID. Must not be <c>null</c> or empty. /// </param> /// <param name="feedItemTargetId">The <c>FeedItemTarget</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedItemTargetName"/> with pattern /// <c> /// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c> /// . /// </returns> public static string FormatCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget(string customerId, string feedId, string feedItemId, string feedItemTargetTypeId, string feedItemTargetId) => s_customerFeedFeedItemFeedItemTargetTypeFeedItemTarget.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetTypeId, nameof(feedItemTargetTypeId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetId, nameof(feedItemTargetId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="FeedItemTargetName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="feedItemTargetName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="FeedItemTargetName"/> if successful.</returns> public static FeedItemTargetName Parse(string feedItemTargetName) => Parse(feedItemTargetName, false); /// <summary> /// Parses the given resource name string into a new <see cref="FeedItemTargetName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedItemTargetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="FeedItemTargetName"/> if successful.</returns> public static FeedItemTargetName Parse(string feedItemTargetName, bool allowUnparsed) => TryParse(feedItemTargetName, allowUnparsed, out FeedItemTargetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FeedItemTargetName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="feedItemTargetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="FeedItemTargetName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string feedItemTargetName, out FeedItemTargetName result) => TryParse(feedItemTargetName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FeedItemTargetName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedItemTargetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="FeedItemTargetName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string feedItemTargetName, bool allowUnparsed, out FeedItemTargetName result) { gax::GaxPreconditions.CheckNotNull(feedItemTargetName, nameof(feedItemTargetName)); gax::TemplatedResourceName resourceName; if (s_customerFeedFeedItemFeedItemTargetTypeFeedItemTarget.TryParseName(feedItemTargetName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget(resourceName[0], split1[0], split1[1], split1[2], split1[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(feedItemTargetName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private FeedItemTargetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string feedId = null, string feedItemId = null, string feedItemTargetId = null, string feedItemTargetTypeId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; FeedId = feedId; FeedItemId = feedItemId; FeedItemTargetId = feedItemTargetId; FeedItemTargetTypeId = feedItemTargetTypeId; } /// <summary> /// Constructs a new instance of a <see cref="FeedItemTargetName"/> class from the component parts of pattern /// <c> /// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemTargetTypeId"> /// The <c>FeedItemTargetType</c> ID. Must not be <c>null</c> or empty. /// </param> /// <param name="feedItemTargetId">The <c>FeedItemTarget</c> ID. Must not be <c>null</c> or empty.</param> public FeedItemTargetName(string customerId, string feedId, string feedItemId, string feedItemTargetTypeId, string feedItemTargetId) : this(ResourceNameType.CustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId)), feedItemTargetTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetTypeId, nameof(feedItemTargetTypeId)), feedItemTargetId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetId, nameof(feedItemTargetId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedId { get; } /// <summary> /// The <c>FeedItem</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedItemId { get; } /// <summary> /// The <c>FeedItemTarget</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string FeedItemTargetId { get; } /// <summary> /// The <c>FeedItemTargetType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string FeedItemTargetTypeId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget: return s_customerFeedFeedItemFeedItemTargetTypeFeedItemTarget.Expand(CustomerId, $"{FeedId}~{FeedItemId}~{FeedItemTargetTypeId}~{FeedItemTargetId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as FeedItemTargetName); /// <inheritdoc/> public bool Equals(FeedItemTargetName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(FeedItemTargetName a, FeedItemTargetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(FeedItemTargetName a, FeedItemTargetName b) => !(a == b); } public partial class FeedItemTarget { /// <summary> /// <see cref="FeedItemTargetName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal FeedItemTargetName ResourceNameAsFeedItemTargetName { get => string.IsNullOrEmpty(ResourceName) ? null : FeedItemTargetName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="FeedItemName"/>-typed view over the <see cref="FeedItem"/> resource name property. /// </summary> internal FeedItemName FeedItemAsFeedItemName { get => string.IsNullOrEmpty(FeedItem) ? null : FeedItemName.Parse(FeedItem, allowUnparsed: true); set => FeedItem = value?.ToString() ?? ""; } /// <summary> /// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property. /// </summary> internal CampaignName CampaignAsCampaignName { get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true); set => Campaign = value?.ToString() ?? ""; } /// <summary> /// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property. /// </summary> internal AdGroupName AdGroupAsAdGroupName { get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true); set => AdGroup = value?.ToString() ?? ""; } /// <summary> /// <see cref="GeoTargetConstantName"/>-typed view over the <see cref="GeoTargetConstant"/> resource name /// property. /// </summary> internal GeoTargetConstantName GeoTargetConstantAsGeoTargetConstantName { get => string.IsNullOrEmpty(GeoTargetConstant) ? null : GeoTargetConstantName.Parse(GeoTargetConstant, allowUnparsed: true); set => GeoTargetConstant = value?.ToString() ?? ""; } } }
// // Copyright (c) XSharp B.V. All Rights Reserved. // Licensed under the Apache License, Version 2.0. // See License.txt in the project root for license information. // namespace Microsoft.VisualStudio.Project { using Community.VisualStudio.Toolkit; using Microsoft.VisualStudio.Shell; using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Windows.Forms; using XSharp.Project; /// <summary> /// Property page contents for the Project Build Settings page. /// </summary> public partial class XPropertyPagePanel : XColorUserControl { // ========================================================================================= // Member Variables // ========================================================================================= private XPropertyPage parentPropertyPage; // ========================================================================================= // Constructors // ========================================================================================= /// <summary> /// Initializes a new instance of the <see cref="XPropertyPagePanel"/> class. /// </summary> public XPropertyPagePanel() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="XPropertyPagePanel"/> class. /// </summary> /// <param name="parentPropertyPage">The parent property page to which this is bound.</param> public XPropertyPagePanel(XPropertyPage parentPropertyPage) { this.parentPropertyPage = parentPropertyPage; this.InitializeComponent(); this.Font = XHelperMethods.GetDialogFont(); this.ForeColor = XHelperMethods.GetVsColor(XHelperMethods.Vs2010Color.VSCOLOR_BUTTONTEXT); } // ========================================================================================= // Properties // ========================================================================================= /// <summary> /// Gets or sets the parent property page to which this is bound. /// </summary> internal XPropertyPage ParentPropertyPage { get { return this.parentPropertyPage; } set { this.parentPropertyPage = value; } } // ========================================================================================= // Methods // ========================================================================================= /// <summary> /// Called before saving to make sure there aren't any unapplied changes. /// </summary> internal void Apply() { TextBox textBox = this.ActiveControl as TextBox; if (textBox == null) { FolderBrowserTextBox folderBrowser = this.ActiveControl as FolderBrowserTextBox; if (folderBrowser != null) { textBox = folderBrowser.TextBox; } } if (textBox == null) { XBuildEventEditor buildEventEditor = this.ActiveControl as XBuildEventEditor; if (buildEventEditor != null) { textBox = buildEventEditor.TextBox; } } ThreadHelper.ThrowIfNotOnUIThread(); if (textBox != null && textBox.Modified) { this.HandleTextBoxLostFocus(textBox, null); } } /// <summary> /// Called once after the page is created to hook up default property events. /// </summary> internal void HookupEvents() { this.HookupEvents(this); } /// <summary> /// Binds the properties from the MSBuild project file to the controls on the property page. /// </summary> protected internal virtual void BindProperties() { this.BindProperties(this); } /// <summary> /// Called when a control has been successfully validated. /// </summary> /// <param name="sender">The control that was validated.</param> /// <param name="e">Parameters for the event.</param> protected virtual void HandleControlValidated(object sender, EventArgs e) { Control control = (Control)sender; string propertyName = (string)control.Tag; string propertyValue = ""; string value = null; var textBox = control as TextBox; if (textBox != null && !textBox.Modified) { return; } var checkBox = control as CheckBox; var comboBox = control as ComboBox; var radioButton = control as RadioButton; if (propertyName.Contains("|")) { var items = propertyName.Split('|'); propertyValue = items[1]; } string currentValue = this.ParentPropertyPage.GetProperty(propertyName); if (checkBox != null) { if (checkBox.CheckState == CheckState.Indeterminate) { value = null; } else { value = checkBox.Checked.ToString(CultureInfo.InvariantCulture); } CheckState currentCheckState = this.ParentPropertyPage.GetPropertyCheckState(propertyName); if (currentCheckState == CheckState.Indeterminate) { currentValue = null; } else { currentValue = (currentCheckState == CheckState.Checked).ToString(); } } else if (comboBox != null) { if (comboBox.SelectedItem != null) value = comboBox.SelectedItem.ToString(); else value = ""; } else if (textBox != null) { value = this.ParentPropertyPage.Normalize(propertyName, control.Text); } else if (radioButton != null) { value = radioButton.Checked ? propertyValue : currentValue; } ThreadHelper.ThrowIfNotOnUIThread(); if (value != null && !String.Equals(value, currentValue, StringComparison.Ordinal)) { // Note query-edit for TextBoxes was already done on the ModifiedChanged event. if (textBox != null || this.ParentPropertyPage.ProjectMgr.QueryEditProjectFile(false)) { this.ParentPropertyPage.SetProperty(propertyName, value); } else { if (checkBox != null) { checkBox.CheckState = this.ParentPropertyPage.GetPropertyCheckState(propertyName); } else if (comboBox != null) { comboBox.SelectedItem = currentValue; } else if (radioButton != null) { // do nothing } else { control.Text = currentValue; } } } if (textBox != null) { // Set to normalized text. textBox.Text = value; textBox.Modified = false; } } private void BindProperties(Control control) { string propertyBinding = control.Tag as string; if (!String.IsNullOrEmpty(propertyBinding)) { string value = this.ParentPropertyPage.GetProperty(propertyBinding); switch (control) { case CheckBox checkBox: checkBox.CheckState = this.ParentPropertyPage.GetPropertyCheckState(propertyBinding); break; case ComboBox comboBox: int index = 0; comboBox.SelectedIndex = -1; foreach (string item in comboBox.Items) { if (item == value) { comboBox.SelectedIndex = index; break; } index++; } break; case RadioButton radioButton: var items = propertyBinding.Split('|'); if (items.Length == 2) { value = this.ParentPropertyPage.GetProperty(items[0]); radioButton.Checked = string.Equals(value, items[1], StringComparison.OrdinalIgnoreCase); } break; default: control.Text = (value != null ? value : String.Empty); break; } } foreach (Control child in control.Controls) { this.BindProperties(child); } } private void HookupEvents(Control control) { string propertyBinding = control.Tag as string; if (propertyBinding != null) { switch (control) { case TextBox textBox: textBox.LostFocus += this.HandleTextBoxLostFocus; textBox.ModifiedChanged += this.HandleTextBoxModifiedChanged; break; case CheckBox checkBox: checkBox.CheckStateChanged += this.HandleControlValidated; break; case ComboBox comboBox: comboBox.SelectedValueChanged += this.HandleControlValidated; break; case FoldersSelector selector: selector.FolderValidating += this.HandleControlValidating; selector.FoldersChanged += this.HandleControlValidated; break; case RadioButton radioButton: radioButton.CheckedChanged += this.HandleControlValidated; break; } } foreach (Control child in control.Controls) { this.HookupEvents(child); } } /// <summary> /// Called when text in a text box changed. Ensures the project file is editable and sets the page dirty flag. /// </summary> /// <param name="sender">The control whose text changed.</param> /// <param name="e">Parameters for the event.</param> private void HandleTextBoxModifiedChanged(object sender, EventArgs e) { ThreadHelper.ThrowIfNotOnUIThread(); TextBox textBox = (TextBox)sender; if (textBox.Modified && !this.ParentPropertyPage.IsDirty) { // We may be about to show a query-edit dialog. Prevent the focus change from triggering validation. textBox.Modified = false; if (this.ParentPropertyPage.ProjectMgr.QueryEditProjectFile(false)) { this.ParentPropertyPage.IsDirty = true; textBox.Modified = true; } else { // Revert to the saved property value. string propertyName = (string)textBox.Tag; textBox.Text = this.ParentPropertyPage.GetProperty(propertyName); } } } /// <summary> /// Called when a control is being validated. Set e.Cancel to true to cause the validation to fail. /// </summary> /// <param name="sender">The control being validated.</param> /// <param name="e">Parameters for the event.</param> private void HandleControlValidating(object sender, System.ComponentModel.CancelEventArgs e) { Control control = (Control)sender; string propertyName = (string)control.Tag; string value = control.Text; TextBox textBox = control as TextBox; if (textBox != null) { if (!textBox.Modified) { return; } value = this.ParentPropertyPage.Normalize(propertyName, value); } else { FoldersSelector foldesSelector = control as FoldersSelector; if (foldesSelector != null) { value = foldesSelector.TextBox.Text; } } string currentValue = this.ParentPropertyPage.GetProperty(propertyName); ThreadHelper.ThrowIfNotOnUIThread(); if (!String.Equals(value, currentValue, StringComparison.Ordinal)) { try { PropertyValidator.ValidateProperty(propertyName, value); } catch (ProjectPropertyArgumentException ex) { if (textBox != null) { // Don't retrigger Validation when losing focus due to the message box. textBox.Modified = false; } VS.MessageBox.ShowError(null, ex.Message); e.Cancel = true; if (textBox != null) { textBox.Text = currentValue; textBox.Modified = false; // Clear the page dirty flag if it was only this textbox that was modified. int isDirty; if (this.ParentPropertyPage.ProjectMgr.IsDirty(out isDirty) == 0 && isDirty == 0) { this.ParentPropertyPage.IsDirty = false; } } } } else if (textBox != null && textBox.Modified) { // The text wasn't significantly changed, but might need to be adjusted to the trimmed value. textBox.Text = value; textBox.Modified = false; // Clear the page dirty flag if it was only this textbox that was modified. int isDirty; if (this.ParentPropertyPage.ProjectMgr.IsDirty(out isDirty) == 0 && isDirty == 0) { this.ParentPropertyPage.IsDirty = false; } } } /// <summary> /// The "Validating" events don't fire in all cases when textboxes lose focus. So we use the LostFocus event instead. /// </summary> /// <param name="sender">The control that lost focus.</param> /// <param name="e">Parameters for the event.</param> private void HandleTextBoxLostFocus(object sender, EventArgs e) { TextBox textBox = sender as TextBox; ThreadHelper.ThrowIfNotOnUIThread(); if (textBox != null && textBox.Modified) { CancelEventArgs ce = new CancelEventArgs(); this.HandleControlValidating(sender, ce); if (!ce.Cancel) { this.HandleControlValidated(sender, e); } } } protected void FillCombo(TypeConverter converter, System.Windows.Forms.ComboBox combo) { foreach (var enumvalue in converter.GetStandardValues(null)) { var name = converter.ConvertTo(enumvalue, typeof(System.String)); combo.Items.Add(name); // new comboItem ((int) enumvalue, name)); } } protected void ShowOpenFileDialog(TextBox tb, string description, string filters) { ThreadHelper.ThrowIfNotOnUIThread(); var openFileDialog = new OpenFileDialog(); openFileDialog.FileName = tb.Text; openFileDialog.Filter = filters; openFileDialog.FilterIndex = 0; openFileDialog.Title = description; var result = openFileDialog.ShowDialog(); if (result == DialogResult.OK) { ParentPropertyPage.SetProperty((string)tb.Tag, openFileDialog.FileName); tb.Text = openFileDialog.FileName; } } protected void showMacroDialog(TextBox tb, string caption, string filter = "") { ThreadHelper.ThrowIfNotOnUIThread(); var form = new XSharpSLEPropertyForm(); if (! string.IsNullOrEmpty(filter)) { form.Filter = filter; } XBuildMacroCollection mc = new XBuildMacroCollection((ProjectNode)this.ParentPropertyPage.ProjectMgr); form.SetMacros(mc); form.PropertyText.Text = tb.Text; form.Text = caption; var result = form.ShowDialog(); if (result == DialogResult.OK) { tb.Text = form.PropertyText.Text; this.ParentPropertyPage.SetProperty((string)tb.Tag, tb.Text); } } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Threading; using System.Diagnostics; using System.Collections; using System.Net; using MyDownloader.Core.Concurrency; using MyDownloader.Core.Common; namespace MyDownloader.Core { public class Downloader { private string localFile; private int requestedSegmentCount; private ResourceLocation resourceLocation; private List<ResourceLocation> mirrors; private List<Segment> segments; private Thread mainThread; private List<Thread> threads; private RemoteFileInfo remoteFileInfo; private DownloaderState state; private DateTime createdDateTime; private Exception lastError; private Dictionary<string, object> extentedProperties = new Dictionary<string, object>(); private IProtocolProvider defaultDownloadProvider; private ISegmentCalculator segmentCalculator; private IMirrorSelector mirrorSelector; private string statusMessage; private Downloader( ResourceLocation rl, ResourceLocation[] mirrors, string localFile) { this.threads = new List<Thread>(); this.resourceLocation = rl; if (mirrors == null) { this.mirrors = new List<ResourceLocation>(); } else { this.mirrors = new List<ResourceLocation>(mirrors); } this.localFile = localFile; extentedProperties = new Dictionary<string, object>(); defaultDownloadProvider = rl.BindProtocolProviderInstance(this); segmentCalculator = new MinSizeSegmentCalculator(); this.MirrorSelector = new SequentialMirrorSelector(); } public Downloader( ResourceLocation rl, ResourceLocation[] mirrors, string localFile, int segmentCount): this(rl, mirrors, localFile) { SetState(DownloaderState.NeedToPrepare); this.createdDateTime = DateTime.Now; this.requestedSegmentCount = segmentCount; this.segments = new List<Segment>(); } public Downloader( ResourceLocation rl, ResourceLocation[] mirrors, string localFile, List<Segment> segments, RemoteFileInfo remoteInfo, int requestedSegmentCount, DateTime createdDateTime): this(rl, mirrors, localFile) { if (segments.Count > 0) { SetState(DownloaderState.Prepared); } else { SetState(DownloaderState.NeedToPrepare); } this.createdDateTime = createdDateTime; this.remoteFileInfo = remoteInfo; this.requestedSegmentCount = requestedSegmentCount; this.segments = segments; } #region Properties public event EventHandler Ending; public event EventHandler InfoReceived; public event EventHandler StateChanged; public event EventHandler<SegmentEventArgs> RestartingSegment; public event EventHandler<SegmentEventArgs> SegmentStoped; public event EventHandler<SegmentEventArgs> SegmentStarting; public event EventHandler<SegmentEventArgs> SegmentStarted; public event EventHandler<SegmentEventArgs> SegmentFailed; public Dictionary<string, object> ExtendedProperties { get { return extentedProperties; } } public ResourceLocation ResourceLocation { get { return this.resourceLocation; } } public List<ResourceLocation> Mirrors { get { return this.mirrors; } } public long FileSize { get { if (remoteFileInfo == null) { return 0; } return remoteFileInfo.FileSize; } } public DateTime CreatedDateTime { get { return createdDateTime; } } public int RequestedSegments { get { return requestedSegmentCount; } } public string LocalFile { get { return this.localFile; } } public double Progress { get { int count = segments.Count; if (count > 0) { double progress = 0; for (int i = 0; i < count; i++) { progress += segments[i].Progress; } return progress / count; } else { return 0; } } } public double Rate { get { double rate = 0; for (int i = 0; i < segments.Count; i++) { rate += segments[i].Rate; } return rate; } } public long Transfered { get { long transfered = 0; for (int i = 0; i < segments.Count; i++) { transfered += segments[i].Transfered; } return transfered; } } public TimeSpan Left { get { if (this.Rate == 0) { return TimeSpan.MaxValue; } double missingTransfer = 0; for (int i = 0; i < segments.Count; i++) { missingTransfer += segments[i].MissingTransfer; } return TimeSpan.FromSeconds(missingTransfer / this.Rate); } } public List<Segment> Segments { get { return segments; } } public Exception LastError { get { return lastError; } set { lastError = value; } } public DownloaderState State { get { return state; } } public bool IsWorking() { DownloaderState state = this.State; return (state == DownloaderState.Preparing || state == DownloaderState.WaitingForReconnect || state == DownloaderState.Working); } public RemoteFileInfo RemoteFileInfo { get { return remoteFileInfo; } } public string StatusMessage { get { return statusMessage; } set { statusMessage = value; } } public ISegmentCalculator SegmentCalculator { get { return segmentCalculator; } set { if (value == null) { throw new ArgumentNullException("value"); } segmentCalculator = value; } } public IMirrorSelector MirrorSelector { get { return mirrorSelector; } set { if (value == null) { throw new ArgumentNullException("value"); } mirrorSelector = value; mirrorSelector.Init(this); } } public int MaxRetries = Settings.Default.MaxRetries; #endregion private void SetState(DownloaderState value) { state = value; OnStateChanged(); } private void StartToPrepare() { mainThread = new Thread(new ParameterizedThreadStart(StartDownloadThreadProc)); mainThread.Start(requestedSegmentCount); } private void StartPrepared() { mainThread = new Thread(new ThreadStart(RestartDownload)); mainThread.Start(); } protected virtual void OnRestartingSegment(Segment segment) { if (RestartingSegment != null) { RestartingSegment(this, new SegmentEventArgs(this, segment)); } } protected virtual void OnSegmentStoped(Segment segment) { if (SegmentStoped != null) { SegmentStoped(this, new SegmentEventArgs(this, segment)); } } protected virtual void OnSegmentFailed(Segment segment) { if (SegmentFailed != null) { SegmentFailed(this, new SegmentEventArgs(this, segment)); } } protected virtual void OnSegmentStarting(Segment segment) { if (SegmentStarting != null) { SegmentStarting(this, new SegmentEventArgs(this, segment)); } } protected virtual void OnSegmentStarted(Segment segment) { if (SegmentStarted != null) { SegmentStarted(this, new SegmentEventArgs(this, segment)); } } protected virtual void OnStateChanged() { if (StateChanged != null) { StateChanged(this, EventArgs.Empty); } } protected virtual void OnEnding() { if (Ending != null) { Ending(this, EventArgs.Empty); } } protected virtual void OnInfoReceived() { if (InfoReceived != null) { InfoReceived(this, EventArgs.Empty); } } public IDisposable LockSegments() { return new ObjectLocker(this.segments); } public void WaitForConclusion() { if (! IsWorking()) { if (mainThread != null && mainThread.IsAlive) { mainThread.Join(TimeSpan.FromSeconds(1)); } } while (IsWorking()) { Thread.Sleep(100); } Debug.WriteLine(this.State.ToString()); } public void Pause() { if (state == DownloaderState.Preparing || state == DownloaderState.WaitingForReconnect) { Segments.Clear(); mainThread.Abort(); mainThread = null; SetState(DownloaderState.NeedToPrepare); return; } if (state == DownloaderState.Working) { SetState(DownloaderState.Pausing); while (!AllWorkersStopped(5)) ; lock (threads) { threads.Clear(); } mainThread.Abort(); mainThread = null; if (RemoteFileInfo != null && !RemoteFileInfo.AcceptRanges) { // reset the segment Segments[0].StartPosition = 0; } SetState(DownloaderState.Paused); } } public void Start() { if (state == DownloaderState.NeedToPrepare) { SetState(DownloaderState.Preparing); StartToPrepare(); } else if ( state != DownloaderState.Preparing && state != DownloaderState.Pausing && state != DownloaderState.Working && state != DownloaderState.WaitingForReconnect) { SetState(DownloaderState.Preparing); StartPrepared(); } } private void AllocLocalFile() { FileInfo fileInfo = new FileInfo(this.LocalFile); if (!Directory.Exists(fileInfo.DirectoryName)) { Directory.CreateDirectory(fileInfo.DirectoryName); } if (fileInfo.Exists) { // auto rename the file... int count = 1; string fileExitWithoutExt = Path.GetFileNameWithoutExtension(this.LocalFile); string ext = Path.GetExtension(this.LocalFile); string newFileName; do { newFileName = PathHelper.GetWithBackslash(fileInfo.DirectoryName) + fileExitWithoutExt + String.Format("({0})", count++) + ext; } while (File.Exists(newFileName)); this.localFile = newFileName; } using (FileStream fs = new FileStream(this.LocalFile, FileMode.Create, FileAccess.Write)) { fs.SetLength(Math.Max(this.FileSize, 0)); } } private void StartDownloadThreadProc(object objSegmentCount) { SetState(DownloaderState.Preparing); int segmentCount = Math.Min((int)objSegmentCount, Settings.Default.MaxSegments); Stream inputStream = null; int currentTry = 0; do { lastError = null; if (state == DownloaderState.Pausing) { SetState(DownloaderState.NeedToPrepare); return; } SetState(DownloaderState.Preparing); currentTry++; try { remoteFileInfo = defaultDownloadProvider.GetFileInfo(this.ResourceLocation, out inputStream); break; } catch (ThreadAbortException) { SetState(DownloaderState.NeedToPrepare); return; } catch (Exception ex) { lastError = ex; if (currentTry < MaxRetries) { SetState(DownloaderState.WaitingForReconnect); Thread.Sleep(TimeSpan.FromSeconds(Settings.Default.RetryDelay)); } else { SetState(DownloaderState.NeedToPrepare); return; } } } while (true); try { lastError = null; StartSegments(segmentCount, inputStream); } catch (ThreadAbortException) { throw; } catch (Exception ex) { lastError = ex; SetState(DownloaderState.EndedWithError); } } private void StartSegments(int segmentCount, Stream inputStream) { // notifies OnInfoReceived(); // allocs the file on disk AllocLocalFile(); long segmentSize; CalculatedSegment[] calculatedSegments; if (!remoteFileInfo.AcceptRanges) { calculatedSegments = new CalculatedSegment[] { new CalculatedSegment(0, remoteFileInfo.FileSize) }; } else { calculatedSegments = this.SegmentCalculator.GetSegments(segmentCount, remoteFileInfo); } lock (threads) threads.Clear(); lock (segments) segments.Clear(); for (int i = 0; i < calculatedSegments.Length; i++) { Segment segment = new Segment(); if (i == 0) { segment.InputStream = inputStream; } segment.Index = i; segment.InitialStartPosition = calculatedSegments[i].StartPosition; segment.StartPosition = calculatedSegments[i].StartPosition; segment.EndPosition = calculatedSegments[i].EndPosition; segments.Add(segment); } RunSegments(); } private void RestartDownload() { int currentTry = 0; Stream stream; RemoteFileInfo newInfo; try { do { lastError = null; SetState(DownloaderState.Preparing); currentTry++; try { newInfo = defaultDownloadProvider.GetFileInfo(this.ResourceLocation, out stream); break; } catch (Exception ex) { lastError = ex; if (currentTry < MaxRetries) { SetState(DownloaderState.WaitingForReconnect); Thread.Sleep(TimeSpan.FromSeconds(Settings.Default.RetryDelay)); } else { return; } } } while (true); } finally { SetState(DownloaderState.Prepared); } try { // check if the file changed on the server if (!newInfo.AcceptRanges || newInfo.LastModified > RemoteFileInfo.LastModified || newInfo.FileSize != RemoteFileInfo.FileSize) { this.remoteFileInfo = newInfo; StartSegments(this.RequestedSegments, stream); } else { if (stream != null) { stream.Dispose(); } RunSegments(); } } catch (ThreadAbortException) { throw; } catch (Exception ex) { lastError = ex; SetState(DownloaderState.EndedWithError); } } private void RunSegments() { SetState(DownloaderState.Working); // TODO comparar o remote file Info se esta igual, se o download saiu de paused/prepared // e nao veio da thread que le o fileinfo using (FileStream fs = new FileStream(this.LocalFile, FileMode.Open, FileAccess.Write)) { for (int i = 0; i < this.Segments.Count; i++) { Segments[i].OutputStream = fs; StartSegment(Segments[i]); } do { while (!AllWorkersStopped(1000)) ; } while (RestartFailedSegments()); } for (int i = 0; i < this.Segments.Count; i++) { if (Segments[i].State == SegmentState.Error) { SetState(DownloaderState.EndedWithError); return; } } if (this.State != DownloaderState.Pausing) { OnEnding(); } SetState(DownloaderState.Ended); } private bool RestartFailedSegments() { bool hasErrors = false; double delay = 0; for (int i = 0; i < this.Segments.Count; i++) { if (Segments[i].State == SegmentState.Error && Segments[i].LastErrorDateTime != DateTime.MinValue && (MaxRetries == 0 || Segments[i].CurrentTry < MaxRetries)) { hasErrors = true; TimeSpan ts = DateTime.Now - Segments[i].LastErrorDateTime; if (ts.TotalSeconds >= Settings.Default.RetryDelay) { Segments[i].CurrentTry++; StartSegment(Segments[i]); OnRestartingSegment(Segments[i]); } else { delay = Math.Max(delay, Settings.Default.RetryDelay * 1000 - ts.TotalMilliseconds); } } } Thread.Sleep((int)delay); return hasErrors; } private void StartSegment(Segment newSegment) { Thread segmentThread = new Thread(new ParameterizedThreadStart(SegmentThreadProc)); segmentThread.Start(newSegment); lock (threads) { threads.Add(segmentThread); } } private bool AllWorkersStopped(int timeOut) { bool allFinished = true; Thread[] workers; lock (threads) { workers = threads.ToArray(); } foreach (Thread t in workers) { bool finished = t.Join(timeOut); allFinished = allFinished & finished; if (finished) { lock (threads) { threads.Remove(t); } } } return allFinished; } private void SegmentThreadProc(object objSegment) { Segment segment = (Segment)objSegment; segment.LastError = null; try { if (segment.EndPosition > 0 && segment.StartPosition >= segment.EndPosition) { segment.State = SegmentState.Finished; // raise the event OnSegmentStoped(segment); return; } int buffSize = 8192; byte[] buffer = new byte[buffSize]; segment.State = SegmentState.Connecting; // raise the event OnSegmentStarting(segment); if (segment.InputStream == null) { // get the next URL (It can the the main url or some mirror) ResourceLocation location = this.MirrorSelector.GetNextResourceLocation(); // get the protocol provider for that mirror IProtocolProvider provider = location.BindProtocolProviderInstance(this); while (location != this.ResourceLocation) { Stream tempStream; // get the remote file info on mirror RemoteFileInfo tempRemoteInfo = provider.GetFileInfo(location, out tempStream); if (tempStream != null) tempStream.Dispose(); // check if the file on mirror is the same if (tempRemoteInfo.FileSize == remoteFileInfo.FileSize && tempRemoteInfo.AcceptRanges == remoteFileInfo.AcceptRanges) { // if yes, stop looking for the mirror break; } lock (mirrors) { // the file on the mirror is not the same, so remove from the mirror list mirrors.Remove(location); } // the file on the mirror is different // so get other mirror to use in the segment location = this.MirrorSelector.GetNextResourceLocation(); provider = location.BindProtocolProviderInstance(this); } // get the input stream from start position segment.InputStream = provider.CreateStream(location, segment.StartPosition, segment.EndPosition); // change the segment URL to the mirror URL segment.CurrentURL = location.URL; } else { // change the segment URL to the main URL segment.CurrentURL = this.resourceLocation.URL; } using (segment.InputStream) { // raise the event OnSegmentStarted(segment); // change the segment state segment.State = SegmentState.Downloading; segment.CurrentTry = 0; long readSize; do { // reads the buffer from input stream readSize = segment.InputStream.Read(buffer, 0, buffSize); // check if the segment has reached the end if (segment.EndPosition > 0 && segment.StartPosition + readSize > segment.EndPosition) { // adjust the 'readSize' to write only necessary bytes readSize = (segment.EndPosition - segment.StartPosition); if (readSize <= 0) { segment.StartPosition = segment.EndPosition; break; } } // locks the stream to avoid that other threads changes // the position of stream while this thread is writing into the stream lock (segment.OutputStream) { segment.OutputStream.Position = segment.StartPosition; segment.OutputStream.Write(buffer, 0, (int)readSize); } // increse the start position of the segment and also calculates the rate segment.IncreaseStartPosition(readSize); // check if the stream has reached its end if (segment.EndPosition > 0 && segment.StartPosition >= segment.EndPosition) { segment.StartPosition = segment.EndPosition; break; } // check if the user have requested to pause the download if (state == DownloaderState.Pausing) { segment.State = SegmentState.Paused; break; } //Thread.Sleep(1500); } while (readSize > 0); if (segment.State == SegmentState.Downloading) { segment.State = SegmentState.Finished; // try to create other segment, // spliting the missing bytes from one existing segment AddNewSegmentIfNeeded(); } } // raise the event OnSegmentStoped(segment); } catch (Exception ex) { // store the error information segment.State = SegmentState.Error; segment.LastError = ex; Debug.WriteLine(ex.ToString()); // raise the event OnSegmentFailed(segment); } finally { // clean up the segment segment.InputStream = null; } } private void AddNewSegmentIfNeeded() { lock (segments) { for (int i = 0; i < this.segments.Count; i++) { Segment oldSegment = this.segments[i]; if (oldSegment.State == SegmentState.Downloading && oldSegment.Left.TotalSeconds > Settings.Default.MinSegmentLeftToStartNewSegment && oldSegment.MissingTransfer / 2 >= Settings.Default.MinSegmentSize) { // get the half of missing size of oldSegment long newSize = oldSegment.MissingTransfer / 2; // create a new segment allocation the half old segment Segment newSegment = new Segment(); newSegment.Index = this.segments.Count; newSegment.StartPosition = oldSegment.StartPosition + newSize; newSegment.InitialStartPosition = newSegment.StartPosition; newSegment.EndPosition = oldSegment.EndPosition; newSegment.OutputStream = oldSegment.OutputStream; // removes bytes from old segments oldSegment.EndPosition = oldSegment.EndPosition - newSize; // add the new segment to the list segments.Add(newSegment); StartSegment(newSegment); break; } } } } } }
using UnityEngine; using System.Collections; using Pathfinding; /** Moves a grid graph to follow a target. * * Attach this to some object in the scene and assign the target to e.g the player. * Then the graph will follow that object around as it moves. * * This is useful if pathfinding is only necessary in a small region around an object (for example the player). * It makes it possible to have vast open worlds (maybe procedurally generated) and still be able to use pathfinding on them. * * When the graph is moved you may notice an fps drop. * If this grows too large you can try a few things: * - Reduce the #updateDistance. This will make the updates smaller but more frequent. * This only works to some degree however since an update has an inherent overhead. * - Reduce the grid size. * - Turn on multithreading (A* Inspector -> Settings) * - Disable the #floodFill field. However note the restrictions on when this can be done. * - Disable Height Testing or Collision Testing in the grid graph. This can give a performance boost * since fewer calls to the physics engine need to be done. * * Make sure you have 'Show Graphs' disabled in the A* inspector since gizmos in the scene view can take some * time to update when the graph moves and thus make it seem like this script is slower than it actually is. * * \see Take a look at the example scene called "Procedural" for an example of how to use this script * * \note This class does not support the erosion setting on grid graphs. You can instead try to * increase the 'diameter' setting under the Grid Graph Settings -> Collision Testing header to achieve a similar effect. * However even if it did support erosion you would most likely not want to use it with this script * since erosion would increase the number of nodes that had to be updated when the graph moved by a large amount. * * \version Since 3.6.8 this class can handle graph rotation other options such as isometric angle and aspect ratio. * \version After 3.6.8 this class can also handle layered grid graphs. */ [HelpURL("http://arongranberg.com/astar/docs/class_procedural_grid_mover.php")] public class ProceduralGridMover : VersionedMonoBehaviour { /** Graph will be updated if the target is more than this number of nodes from the graph center. * Note that this is in nodes, not world units. * * \version The unit was changed to nodes instead of world units in 3.6.8. */ public float updateDistance = 10; /** Graph will be moved to follow this target */ public Transform target; /** Flood fill the graph after updating. * If this is set to false, areas of the graph will not be recalculated. * Disable this only if the graph will only have a single area (i.e * from all walkable nodes there is a valid path to every other walkable * node). One case where this might be appropriate is a large * outdoor area such as a forrest. * If there are multiple areas in the graph and this * is not enabled, pathfinding could fail later on. * * Disabling flood fills will make the graph updates faster. */ public bool floodFill = true; /** Grid graph to update */ GridGraph graph; /** Temporary buffer */ GridNodeBase[] buffer; /** True while the graph is being updated by this script */ public bool updatingGraph { get; private set; } void Start () { if (AstarPath.active == null) throw new System.Exception("There is no AstarPath object in the scene"); graph = AstarPath.active.data.gridGraph; if (graph == null) throw new System.Exception("The AstarPath object has no GridGraph or LayeredGridGraph"); UpdateGraph(); } /** Update is called once per frame */ void Update () { if (graph == null) return; // Calculate where the graph center and the target position is in graph space var graphCenterInGraphSpace = PointToGraphSpace(graph.center); var targetPositionInGraphSpace = PointToGraphSpace(target.position); // Check the distance in graph space // We only care about the X and Z axes since the Y axis is the "height" coordinate of the nodes (in graph space) // We only care about the plane that the nodes are placed in if (VectorMath.SqrDistanceXZ(graphCenterInGraphSpace, targetPositionInGraphSpace) > updateDistance*updateDistance) { UpdateGraph(); } } /** Transforms a point from world space to graph space. * In graph space, (0,0,0) is bottom left corner of the graph * and one unit along the X and Z axes equals distance between two nodes * the Y axis still uses world units */ Vector3 PointToGraphSpace (Vector3 p) { // Multiply with the inverse matrix of the graph // to get the point in graph space return graph.transform.InverseTransform(p); } /** Updates the graph asynchronously. * This will move the graph so that the target's position is the center of the graph. * If the graph is already being updated, the call will be ignored. * * The image below shows which nodes will be updated when the graph moves. * The whole graph is not recalculated each time it is moved, but only those * nodes that have to be updated, the rest will keep their old values. * The image is a bit simplified but it shows the main idea. * \shadowimage{grid_graph_mover.png} * * If you want to move the graph synchronously then call * \code AstarPath.active.FlushGraphUpdates(); \endcode * Immediately after you have called this method. */ public void UpdateGraph () { if (updatingGraph) { // We are already updating the graph // so ignore this call return; } updatingGraph = true; // Start a work item for updating the graph // This will pause the pathfinding threads // so that it is safe to update the graph // and then do it over several frames // (hence the IEnumerator coroutine) // to avoid too large FPS drops IEnumerator ie = UpdateGraphCoroutine(); AstarPath.active.AddWorkItem(new AstarWorkItem( (context, force) => { // Make sure the areas for the graph // have been recalculated // not doing this can cause pathfinding to fail // This will be done after all work items // have been completed if (floodFill) context.QueueFloodFill(); // If force is true we need to calculate all steps at once if (force) while (ie.MoveNext()) {} // Calculate one step. False will be returned when there are no more steps bool done; try { done = !ie.MoveNext(); } catch (System.Exception e) { // The code MAY throw an exception in rare circumstances if for example the user // changes the width of the graph in the inspector while an update is being performed // at the same time. So lets just fail in that case and retry later. Debug.LogException(e, this); done = true; } if (done) { updatingGraph = false; } return done; })); } /** Async method for moving the graph */ IEnumerator UpdateGraphCoroutine () { // Find the direction that we want to move the graph in. // Calcuculate this in graph space (where a distance of one is the size of one node) Vector3 dir = PointToGraphSpace(target.position) - PointToGraphSpace(graph.center); // Snap to a whole number of nodes dir.x = Mathf.Round(dir.x); dir.z = Mathf.Round(dir.z); dir.y = 0; // Nothing do to if (dir == Vector3.zero) yield break; // Number of nodes to offset in each direction Int2 offset = new Int2(-Mathf.RoundToInt(dir.x), -Mathf.RoundToInt(dir.z)); // Move the center (this is in world units, so we need to convert it back from graph space) graph.center += graph.transform.TransformVector(dir); graph.UpdateTransform(); // Cache some variables for easier access int width = graph.width; int depth = graph.depth; GridNodeBase[] nodes; // Layers are required when handling LayeredGridGraphs int layers = graph.LayerCount; nodes = graph.nodes; // Create a temporary buffer required for the calculations if (buffer == null || buffer.Length != width*depth) { buffer = new GridNodeBase[width*depth]; } // Check if we have moved less than a whole graph width all directions // If we have moved more than this we can just as well recalculate the whole graph if (Mathf.Abs(offset.x) <= width && Mathf.Abs(offset.y) <= depth) { IntRect recalculateRect = new IntRect(0, 0, offset.x, offset.y); // If offset.x < 0, adjust the rect if (recalculateRect.xmin > recalculateRect.xmax) { int tmp2 = recalculateRect.xmax; recalculateRect.xmax = width + recalculateRect.xmin; recalculateRect.xmin = width + tmp2; } // If offset.y < 0, adjust the rect if (recalculateRect.ymin > recalculateRect.ymax) { int tmp2 = recalculateRect.ymax; recalculateRect.ymax = depth + recalculateRect.ymin; recalculateRect.ymin = depth + tmp2; } // Connections need to be recalculated for the neighbours as well, so we need to expand the rect by 1 var connectionRect = recalculateRect.Expand(1); // Makes sure the rect stays inside the grid connectionRect = IntRect.Intersection(connectionRect, new IntRect(0, 0, width, depth)); // Offset each node by the #offset variable // nodes which would end up outside the graph // will wrap around to the other side of it for (int l = 0; l < layers; l++) { int layerOffset = l*width*depth; for (int z = 0; z < depth; z++) { int pz = z*width; int tz = ((z+offset.y + depth)%depth)*width; for (int x = 0; x < width; x++) { buffer[tz + ((x+offset.x + width) % width)] = nodes[layerOffset + pz + x]; } } yield return null; // Copy the nodes back to the graph // and set the correct indices for (int z = 0; z < depth; z++) { int pz = z*width; for (int x = 0; x < width; x++) { int newIndex = pz + x; var node = buffer[newIndex]; if (node != null) node.NodeInGridIndex = newIndex; nodes[layerOffset + newIndex] = node; } // Calculate the limits for the region that has been wrapped // to the other side of the graph int xmin, xmax; if (z >= recalculateRect.ymin && z < recalculateRect.ymax) { xmin = 0; xmax = depth; } else { xmin = recalculateRect.xmin; xmax = recalculateRect.xmax; } for (int x = xmin; x < xmax; x++) { var node = buffer[pz + x]; if (node != null) { // Clear connections on all nodes that are wrapped and placed on the other side of the graph. // This is both to clear any custom connections (which do not really make sense after moving the node) // and to prevent possible exceptions when the node will later (possibly) be destroyed because it was // not needed anymore (only for layered grid graphs). node.ClearConnections(false); } } } yield return null; } // The calculation will only update approximately this number of // nodes per frame. This is used to keep CPU load per frame low int yieldEvery = 1000; // To avoid the update taking too long, make yieldEvery somewhat proportional to the number of nodes that we are going to update int approxNumNodesToUpdate = Mathf.Max(Mathf.Abs(offset.x), Mathf.Abs(offset.y)) * Mathf.Max(width, depth); yieldEvery = Mathf.Max(yieldEvery, approxNumNodesToUpdate/10); int counter = 0; // Recalculate the nodes // Take a look at the image in the docs for the UpdateGraph method // to see which nodes are being recalculated. for (int z = 0; z < depth; z++) { int xmin, xmax; if (z >= recalculateRect.ymin && z < recalculateRect.ymax) { xmin = 0; xmax = width; } else { xmin = recalculateRect.xmin; xmax = recalculateRect.xmax; } for (int x = xmin; x < xmax; x++) { graph.RecalculateCell(x, z, false, false); } counter += (xmax - xmin); if (counter > yieldEvery) { counter = 0; yield return null; } } for (int z = 0; z < depth; z++) { int xmin, xmax; if (z >= connectionRect.ymin && z < connectionRect.ymax) { xmin = 0; xmax = width; } else { xmin = connectionRect.xmin; xmax = connectionRect.xmax; } for (int x = xmin; x < xmax; x++) { graph.CalculateConnections(x, z); } counter += (xmax - xmin); if (counter > yieldEvery) { counter = 0; yield return null; } } yield return null; // Calculate all connections for the nodes along the boundary // of the graph, these always need to be updated /** \todo Optimize to not traverse all nodes in the graph, only those at the edges */ for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { if (x == 0 || z == 0 || x == width-1 || z == depth-1) graph.CalculateConnections(x, z); } } // We need to clear the Area if we are not using flood filling. // This will make pathfinding always work, but it may be slow // to figure out that no path exists if none does. // (of course, if there are regions between which no valid // paths exist, then the #floodFill field should not // be set to false anyway). if (!floodFill) { graph.GetNodes(node => node.Area = 1); } } else { // The calculation will only update approximately this number of // nodes per frame. This is used to keep CPU load per frame low int yieldEvery = Mathf.Max(depth*width / 20, 1000); int counter = 0; // Just update all nodes for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { graph.RecalculateCell(x, z); } counter += width; if (counter > yieldEvery) { counter = 0; yield return null; } } // Recalculate the connections of all nodes for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { graph.CalculateConnections(x, z); } counter += width; if (counter > yieldEvery) { counter = 0; yield return null; } } } } }
// // XmlLicenseTransformTest.cs - Test Cases for XmlLicenseTransform // // Author: // original: // Sebastien Pouliot <[email protected]> // Aleksey Sanin ([email protected]) // this file: // Gert Driesen <[email protected]> // // (C) 2003 Aleksey Sanin ([email protected]) // (C) 2004 Novell (http://www.novell.com) // (C) 2008 Gert Driesen // // Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.IO; using System.Xml; using Xunit; namespace System.Security.Cryptography.Xml.Tests { public class UnprotectedXmlLicenseTransform : XmlLicenseTransform { public XmlNodeList UnprotectedGetInnerXml() { return base.GetInnerXml(); } } public class DummyDecryptor : IRelDecryptor { public string ContentToReturn { get; set; } public Stream Decrypt(EncryptionMethod encryptionMethod, KeyInfo keyInfo, Stream toDecrypt) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(ContentToReturn); writer.Flush(); stream.Position = 0; return stream; } } public class XmlLicenseTransformTest { public const string LicenseTransformNsUrl = "urn:mpeg:mpeg21:2003:01-REL-R-NS"; public const string LicenseTransformUrl = LicenseTransformNsUrl + ":licenseTransform"; private UnprotectedXmlLicenseTransform transform; public XmlLicenseTransformTest() { transform = new UnprotectedXmlLicenseTransform(); } [Fact] // ctor () public void Constructor1() { Assert.Equal(LicenseTransformUrl, transform.Algorithm); Assert.Null(transform.Decryptor); Type[] input = transform.InputTypes; Assert.Equal(1, input.Length); Assert.Equal(typeof(XmlDocument), input[0]); Type[] output = transform.OutputTypes; Assert.Equal(1, output.Length); Assert.Equal(typeof(XmlDocument), output[0]); } [Fact] public void InputTypes() { // property does not return a clone transform.InputTypes[0] = null; Assert.Null(transform.InputTypes[0]); // it's not a static array transform = new UnprotectedXmlLicenseTransform(); Assert.NotNull(transform.InputTypes[0]); } [Fact] public void GetInnerXml() { XmlNodeList xnl = transform.UnprotectedGetInnerXml(); Assert.Null(xnl); } [Fact] public void OutputTypes() { // property does not return a clone transform.OutputTypes[0] = null; Assert.Null(transform.OutputTypes[0]); // it's not a static array transform = new UnprotectedXmlLicenseTransform(); Assert.NotNull(transform.OutputTypes[0]); } [Fact] public void Context_Null() { XmlDocument doc = GetDocumentFromResource("System.Security.Cryptography.Xml.Tests.XmlLicenseSample.xml"); Assert.Throws<CryptographicException>(() => transform.LoadInput(doc)); } [Fact] public void NoLicenseXml() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<root />"); transform.Context = doc.DocumentElement; Assert.Throws<CryptographicException>(() => transform.LoadInput(doc)); } [Fact] public void Decryptor_Null() { XmlDocument doc = GetDocumentFromResource("System.Security.Cryptography.Xml.Tests.XmlLicenseSample.xml"); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable); namespaceManager.AddNamespace("r", "urn:mpeg:mpeg21:2003:01-REL-R-NS"); transform.Context = doc.DocumentElement.SelectSingleNode("//r:issuer[1]", namespaceManager) as XmlElement; Assert.Throws<CryptographicException>(() => transform.LoadInput(doc)); } [Fact] public void ValidLicense() { XmlDocument doc = GetDocumentFromResource("System.Security.Cryptography.Xml.Tests.XmlLicenseSample.xml"); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable); namespaceManager.AddNamespace("r", "urn:mpeg:mpeg21:2003:01-REL-R-NS"); transform.Context = doc.DocumentElement.SelectSingleNode("//r:issuer[1]", namespaceManager) as XmlElement; DummyDecryptor decryptor = new DummyDecryptor { ContentToReturn = "Encrypted Content" }; transform.Decryptor = decryptor; transform.LoadInput(doc); XmlDocument output = transform.GetOutput(typeof(XmlDocument)) as XmlDocument; string decodedXml = @"<r:license xmlns:r=""urn:mpeg:mpeg21:2003:01-REL-R-NS"" licenseId=""{00000000-0000-0000-0000-123456789012}"">"; decodedXml += "<r:title>Test License</r:title><r:grant>Encrypted Content</r:grant>"; decodedXml += "<r:issuer><r:details><r:timeOfIssue>2017-01-71T00:00:00Z</r:timeOfIssue></r:details></r:issuer></r:license>"; Assert.NotNull(output); Assert.Equal(decodedXml, output.OuterXml); } [Fact] public void GetOutput_InvalidType() { Assert.Throws<ArgumentException>(() => transform.GetOutput(typeof(string))); } [Fact] public static void ItDecryptsLicense() { using (var key = RSA.Create()) { string expected; string encryptedLicenseWithGrants = GenerateLicenseXmlWithEncryptedGrants(key, out expected); Assert.Contains("hello", expected); Assert.DoesNotContain("hello", encryptedLicenseWithGrants); XmlNamespaceManager nsManager; XmlDocument toDecrypt = LoadXmlWithLicenseNs(encryptedLicenseWithGrants, out nsManager); var decryptor = new XmlLicenseEncryptedRef(); var transform = new XmlLicenseTransform() { Decryptor = decryptor, Context = FindLicenseTransformContext(toDecrypt, nsManager) }; decryptor.AddAsymmetricKey(key); // Context is the input for this transform, argument is always ignored transform.LoadInput(null); XmlDocument decryptedDoc = transform.GetOutput() as XmlDocument; Assert.NotNull(decryptedDoc); string decrypted = decryptedDoc.OuterXml; Assert.Equal(expected, decrypted); } } private XmlDocument GetDocumentFromResource(string resourceName) { XmlDocument doc = new XmlDocument(); using (Stream stream = TestHelpers.LoadResourceStream(resourceName)) using (StreamReader streamReader = new StreamReader(stream)) { string originalXml = streamReader.ReadToEnd(); doc.LoadXml(originalXml); } return doc; } private static string GenerateLicenseXmlWithEncryptedGrants(RSA key, out string plainTextLicense) { plainTextLicense = @"<r:license xmlns:r=""urn:mpeg:mpeg21:2003:01-REL-R-NS""> <r:title>Test License</r:title> <r:grant> <r:forAll varName=""licensor"" /> <r:forAll varName=""property"" /> <r:forAll varName=""p0""> <r:propertyPossessor> <r:propertyAbstract varRef=""property"" /> </r:propertyPossessor> </r:forAll> <r:keyHolder varRef=""licensor"" /> <r:issue /> <r:grant> <r:principal varRef=""p0"" /> <x:bar xmlns:x=""urn:foo"" /> <r:digitalResource> <testItem>hello</testItem> </r:digitalResource> <renderer xmlns=""urn:mpeg:mpeg21:2003:01-REL-MX-NS""> <mx:wildcard xmlns:mx=""urn:mpeg:mpeg21:2003:01-REL-MX-NS""> <r:anXmlExpression>some-xpath-expression</r:anXmlExpression> </mx:wildcard> <mx:wildcard xmlns:mx=""urn:mpeg:mpeg21:2003:01-REL-MX-NS""> <r:anXmlExpression>some-other-xpath-expression</r:anXmlExpression> </mx:wildcard> </renderer> </r:grant> <validityIntervalFloating xmlns=""urn:mpeg:mpeg21:2003:01-REL-SX-NS""> <sx:duration xmlns:sx=""urn:mpeg:mpeg21:2003:01-REL-SX-NS"">P2D</sx:duration> </validityIntervalFloating> </r:grant> <r:grant> <r:possessProperty /> <emailName xmlns=""urn:mpeg:mpeg21:2003:01-REL-SX-NS"">test@test</emailName> </r:grant> <r:issuer xmlns:r=""urn:mpeg:mpeg21:2003:01-REL-R-NS""> <r:details> <r:timeOfIssue>2099-11-11T11:11:11Z</r:timeOfIssue> </r:details> </r:issuer> </r:license>".Replace("\r\n", "\n"); XmlNamespaceManager nsManager; XmlDocument doc = LoadXmlWithLicenseNs(plainTextLicense, out nsManager); EncryptLicense(FindLicenseTransformContext(doc, nsManager), key); return doc.OuterXml; } private static XmlElement FindLicenseTransformContext(XmlDocument doc, XmlNamespaceManager nsManager) { XmlNodeList issuerList = doc.SelectNodes("//r:issuer", nsManager); return issuerList[0] as XmlElement; } private static XmlDocument LoadXmlWithLicenseNs(string xml, out XmlNamespaceManager nsManager) { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace("r", LicenseTransformNsUrl); doc.LoadXml(xml); return doc; } private static void EncryptGrant(XmlNode grant, RSA key, XmlNamespaceManager nsMgr) { using (var ms = new MemoryStream()) using (var sw = new StreamWriter(ms)) { sw.Write(grant.InnerXml); sw.Flush(); ms.Position = 0; KeyInfo keyInfo; EncryptionMethod encryptionMethod; CipherData cipherData; XmlLicenseEncryptedRef.Encrypt(ms, key, out keyInfo, out encryptionMethod, out cipherData); grant.RemoveAll(); XmlDocument doc = grant.OwnerDocument; XmlElement encryptedGrant = doc.CreateElement("encryptedGrant", LicenseTransformNsUrl); grant.AppendChild(encryptedGrant); encryptedGrant.AppendChild(doc.ImportNode(keyInfo.GetXml(), true)); encryptedGrant.AppendChild(doc.ImportNode(encryptionMethod.GetXml(), true)); encryptedGrant.AppendChild(doc.ImportNode(cipherData.GetXml(), true)); } } private static void EncryptLicense(XmlElement context, RSA key) { XmlDocument doc = context.OwnerDocument; var nsMgr = new XmlNamespaceManager(doc.NameTable); nsMgr.AddNamespace("dsig", SignedXml.XmlDsigNamespaceUrl); nsMgr.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); nsMgr.AddNamespace("r", LicenseTransformNsUrl); XmlElement currentIssuerContext = context.SelectSingleNode("ancestor-or-self::r:issuer[1]", nsMgr) as XmlElement; Assert.NotEqual(currentIssuerContext, null); XmlElement signatureNode = currentIssuerContext.SelectSingleNode("descendant-or-self::dsig:Signature[1]", nsMgr) as XmlElement; if (signatureNode != null) { signatureNode.ParentNode.RemoveChild(signatureNode); } XmlElement currentLicenseContext = currentIssuerContext.SelectSingleNode("ancestor-or-self::r:license[1]", nsMgr) as XmlElement; Assert.NotEqual(currentLicenseContext, null); XmlNodeList issuerList = currentLicenseContext.SelectNodes("descendant-or-self::r:license[1]/r:issuer", nsMgr); for (int i = 0; i < issuerList.Count; i++) { XmlNode issuer = issuerList[i]; if (issuer == currentIssuerContext) { continue; } if (issuer.LocalName == "issuer" && issuer.NamespaceURI == LicenseTransformNsUrl) { issuer.ParentNode.RemoveChild(issuer); } } XmlNodeList encryptedGrantList = currentLicenseContext.SelectNodes("/r:license/r:grant", nsMgr); for (int i = 0; i < encryptedGrantList.Count; i++) { EncryptGrant(encryptedGrantList[i], key, nsMgr); } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // 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 { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Threading; using System.Runtime.CompilerServices; using System.Linq; using Internal.Fakeables; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// Creates and manages instances of <see cref="T:NLog.Logger" /> objects. /// </summary> public sealed class LogManager { private static readonly LogFactory factory = new LogFactory(); private static IAppDomain currentAppDomain; private static ICollection<Assembly> _hiddenAssemblies; private static readonly object lockObject = new object(); /// <summary> /// Delegate used to set/get the culture in use. /// </summary> [Obsolete] public delegate CultureInfo GetCultureInfo(); #if !SILVERLIGHT && !MONO /// <summary> /// Initializes static members of the LogManager class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")] static LogManager() { SetupTerminationEvents(); } #endif /// <summary> /// Prevents a default instance of the LogManager class from being created. /// </summary> private LogManager() { } /// <summary> /// Occurs when logging <see cref="Configuration" /> changes. /// </summary> public static event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged { add { factory.ConfigurationChanged += value; } remove { factory.ConfigurationChanged -= value; } } #if !SILVERLIGHT /// <summary> /// Occurs when logging <see cref="Configuration" /> gets reloaded. /// </summary> public static event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded { add { factory.ConfigurationReloaded += value; } remove { factory.ConfigurationReloaded -= value; } } #endif /// <summary> /// Gets or sets a value indicating whether NLog should throw exceptions. /// By default exceptions are not thrown under any circumstances. /// </summary> public static bool ThrowExceptions { get { return factory.ThrowExceptions; } set { factory.ThrowExceptions = value; } } internal static IAppDomain CurrentAppDomain { get { return currentAppDomain ?? (currentAppDomain = AppDomainWrapper.CurrentDomain); } set { #if !SILVERLIGHT && !MONO currentAppDomain.DomainUnload -= TurnOffLogging; currentAppDomain.ProcessExit -= TurnOffLogging; #endif currentAppDomain = value; } } /// <summary> /// Gets or sets the current logging configuration. /// <see cref="LogFactory.Configuration" /> /// </summary> public static LoggingConfiguration Configuration { get { return factory.Configuration; } set { factory.Configuration = value; } } /// <summary> /// Gets or sets the global log threshold. Log events below this threshold are not logged. /// </summary> public static LogLevel GlobalThreshold { get { return factory.GlobalThreshold; } set { factory.GlobalThreshold = value; } } /// <summary> /// Gets or sets the default culture to use. /// </summary> [Obsolete("Use Configuration.DefaultCultureInfo property instead")] public static GetCultureInfo DefaultCultureInfo { get { return () => factory.DefaultCultureInfo ?? CultureInfo.CurrentCulture; } set { throw new NotSupportedException("Setting the DefaultCultureInfo delegate is no longer supported. Use the Configuration.DefaultCultureInfo property to change the default CultureInfo."); } } /// <summary> /// Gets the logger named after the currently-being-initialized class. /// </summary> /// <returns>The logger.</returns> /// <remarks>This is a slow-running method. /// Make sure you're not doing this in a loop.</remarks> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.NoInlining)] public static Logger GetCurrentClassLogger() { return factory.GetLogger(GetClassFullName()); } internal static bool IsHiddenAssembly(Assembly assembly) { return _hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly); } /// <summary> /// Adds the given assembly which will be skipped /// when NLog is trying to find the calling method on stack trace. /// </summary> /// <param name="assembly">The assembly to skip.</param> [MethodImpl(MethodImplOptions.NoInlining)] public static void AddHiddenAssembly(Assembly assembly) { lock (lockObject) { if (_hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly)) return; _hiddenAssemblies = new HashSet<Assembly>(_hiddenAssemblies ?? Enumerable.Empty<Assembly>()) { assembly }; } } /// <summary> /// Gets the logger named after the currently-being-initialized class. /// </summary> /// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param> /// <returns>The logger.</returns> /// <remarks>This is a slow-running method. /// Make sure you're not doing this in a loop.</remarks> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.NoInlining)] public static Logger GetCurrentClassLogger(Type loggerType) { return factory.GetLogger(GetClassFullName(), loggerType); } /// <summary> /// Creates a logger that discards all log messages. /// </summary> /// <returns>Null logger which discards all log messages.</returns> [CLSCompliant(false)] public static Logger CreateNullLogger() { return factory.CreateNullLogger(); } /// <summary> /// Gets the specified named logger. /// </summary> /// <param name="name">Name of the logger.</param> /// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns> [CLSCompliant(false)] public static Logger GetLogger(string name) { return factory.GetLogger(name); } /// <summary> /// Gets the specified named logger. /// </summary> /// <param name="name">Name of the logger.</param> /// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param> /// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns> [CLSCompliant(false)] public static Logger GetLogger(string name, Type loggerType) { return factory.GetLogger(name, loggerType); } /// <summary> /// Loops through all loggers previously returned by GetLogger. /// and recalculates their target and filter list. Useful after modifying the configuration programmatically /// to ensure that all loggers have been properly configured. /// </summary> public static void ReconfigExistingLoggers() { factory.ReconfigExistingLoggers(); } #if !SILVERLIGHT /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> public static void Flush() { factory.Flush(); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(TimeSpan timeout) { factory.Flush(timeout); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(int timeoutMilliseconds) { factory.Flush(timeoutMilliseconds); } #endif /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public static void Flush(AsyncContinuation asyncContinuation) { factory.Flush(asyncContinuation); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout) { factory.Flush(asyncContinuation, timeout); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds) { factory.Flush(asyncContinuation, timeoutMilliseconds); } /// <summary> /// Decreases the log enable counter and if it reaches -1 the logs are disabled. /// </summary> /// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater /// than or equal to <see cref="DisableLogging"/> calls.</remarks> /// <returns>An object that implements IDisposable whose Dispose() method reenables logging. /// To be used with C# <c>using ()</c> statement.</returns> public static IDisposable DisableLogging() { return factory.SuspendLogging(); } /// <summary> /// Increases the log enable counter and if it reaches 0 the logs are disabled. /// </summary> /// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater /// than or equal to <see cref="DisableLogging"/> calls.</remarks> public static void EnableLogging() { factory.ResumeLogging(); } /// <summary> /// Checks if logging is currently enabled. /// </summary> /// <returns><see langword="true" /> if logging is currently enabled, <see langword="false"/> /// otherwise.</returns> /// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater /// than or equal to <see cref="DisableLogging"/> calls.</remarks> public static bool IsLoggingEnabled() { return factory.IsLoggingEnabled(); } /// <summary> /// Dispose all targets, and shutdown logging. /// </summary> public static void Shutdown() { foreach (var target in Configuration.AllTargets) { target.Dispose(); } } #if !SILVERLIGHT && !MONO private static void SetupTerminationEvents() { try { CurrentAppDomain.ProcessExit += TurnOffLogging; CurrentAppDomain.DomainUnload += TurnOffLogging; } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Warn("Error setting up termination events: {0}", exception); } } #endif /// <summary> /// Gets the fully qualified name of the class invoking the LogManager, including the /// namespace but not the assembly. /// </summary> private static string GetClassFullName() { string className; Type declaringType; int framesToSkip = 2; do { #if SILVERLIGHT StackFrame frame = new StackTrace().GetFrame(framesToSkip); #else StackFrame frame = new StackFrame(framesToSkip, false); #endif MethodBase method = frame.GetMethod(); declaringType = method.DeclaringType; if (declaringType == null) { className = method.Name; break; } framesToSkip++; className = declaringType.FullName; } while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase)); return className; } private static void TurnOffLogging(object sender, EventArgs args) { // Reset logging configuration to null; this causes old configuration (if any) to be // closed. InternalLogger.Info("Shutting down logging..."); Configuration = null; InternalLogger.Info("Logger has been shut down."); } } }
namespace Loon.Core.Geom { using System; using System.Collections.Generic; using Loon.Utils; public sealed class Matrix { internal float[] matrixs; public Matrix() { this.result = new float[16]; this.Idt(); } public Matrix(Matrix m) { this.result = new float[16]; matrixs = new float[9]; System.Array.Copy(m.matrixs, 0, matrixs, 0, 9); } public Matrix(Matrix t1, Matrix t2): this(t1) { Concatenate(t2); } public Matrix(float[] matrixs_0) { this.result = new float[16]; if (matrixs_0.Length != 9) { throw new Exception("matrixs.length != 9"); } this.matrixs = new float[] { matrixs_0[0], matrixs_0[1], matrixs_0[2], matrixs_0[3], matrixs_0[4], matrixs_0[5], matrixs_0[6], matrixs_0[7], matrixs_0[8] }; } public void Set(float x1, float y1, float x2, float y2) { Set(x1, y1, 1, x2, y2, 1); } public Matrix(float a1, float a2, float a3, float b1, float b2, float b3) { this.result = new float[16]; Set(a1, a2, a3, b1, b2, b3); } public void Set(float a1, float a2, float a3, float b1, float b2, float b3) { Set(a1, a2, a3, b1, b2, b3, 0, 0, 1); } public void Set(float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3) { matrixs = new float[] { a1, a2, a3, b1, b2, b3, c1, c2, c3 }; } public void Transform(float[] source, int sourceOffset, float[] destination, int destOffset, int numberOfPoints) { float[] result = (source == destination) ? new float[numberOfPoints * 2] : destination; for (int i = 0; i < numberOfPoints * 2; i += 2) { for (int j = 0; j < 6; j += 3) { result[i + (j / 3)] = source[i + sourceOffset] * matrixs[j] + source[i + sourceOffset + 1] * matrixs[j + 1] + 1 * matrixs[j + 2]; } } if (source == destination) { for (int i_0 = 0; i_0 < numberOfPoints * 2; i_0 += 2) { destination[i_0 + destOffset] = result[i_0]; destination[i_0 + destOffset + 1] = result[i_0 + 1]; } } } public Matrix Concatenate(Matrix m) { float[] mp = new float[9]; float n00 = matrixs[0] * m.matrixs[0] + matrixs[1] * m.matrixs[3]; float n01 = matrixs[0] * m.matrixs[1] + matrixs[1] * m.matrixs[4]; float n02 = matrixs[0] * m.matrixs[2] + matrixs[1] * m.matrixs[5] + matrixs[2]; float n10 = matrixs[3] * m.matrixs[0] + matrixs[4] * m.matrixs[3]; float n11 = matrixs[3] * m.matrixs[1] + matrixs[4] * m.matrixs[4]; float n12 = matrixs[3] * m.matrixs[2] + matrixs[4] * m.matrixs[5] + matrixs[5]; mp[0] = n00; mp[1] = n01; mp[2] = n02; mp[3] = n10; mp[4] = n11; mp[5] = n12; matrixs = mp; return this; } public static Matrix CreateRotateTransform(float angle) { return new Matrix(MathUtils.Cos(angle), -MathUtils.Sin(angle), 0, MathUtils.Sin(angle), MathUtils.Cos(angle), 0); } public static Matrix CreateRotateTransform(float angle, float x, float y) { Matrix temp = Matrix.CreateRotateTransform(angle); float sinAngle = temp.matrixs[3]; float oneMinusCosAngle = 1.0f - temp.matrixs[4]; temp.matrixs[2] = x * oneMinusCosAngle + y * sinAngle; temp.matrixs[5] = y * oneMinusCosAngle - x * sinAngle; return temp; } public static Matrix CreateTranslateTransform(float xOffset, float yOffset) { return new Matrix(1, 0, xOffset, 0, 1, yOffset); } public static Matrix CreateScaleTransform(float scalex, float scaley) { return new Matrix(scalex, 0, 0, 0, scaley, 0); } public float Get(int x, int y) { try { return matrixs[x * 3 + y]; } catch (Exception) { throw new ArgumentException("Invalid indices into matrix !"); } } public void Set(int x, int y, float v) { try { this.matrixs[x * 3 + y] = v; } catch (Exception) { throw new ArgumentException("Invalid indices into matrix !"); } } public Matrix Set(Matrix m) { matrixs[0] = m.matrixs[0]; matrixs[1] = m.matrixs[1]; matrixs[2] = m.matrixs[2]; matrixs[3] = m.matrixs[3]; matrixs[4] = m.matrixs[4]; matrixs[5] = m.matrixs[5]; matrixs[6] = m.matrixs[6]; matrixs[7] = m.matrixs[7]; matrixs[8] = m.matrixs[8]; return this; } public Matrix From(float[] source, bool rowMajor) { Matrix m = new Matrix(); if (rowMajor) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { m.Set(i, j, source[i * 3 + j]); } } } else { for (int j_0 = 0; j_0 < 3; j_0++) { for (int i_1 = 0; i_1 < 3; i_1++) { m.Set(i_1, j_0, source[j_0 * 3 + i_1]); } } } return this; } public void Translation(float x, float y) { this.matrixs[0] = 1; this.matrixs[1] = 0; this.matrixs[2] = 0; this.matrixs[3] = 0; this.matrixs[4] = 1; this.matrixs[5] = 0; this.matrixs[6] = x; this.matrixs[7] = y; this.matrixs[8] = 1; } public void Rotation(float angle) { angle = MathUtils.DEG_TO_RAD * angle; float cos = MathUtils.Cos(angle); float sin = MathUtils.Sin(angle); this.matrixs[0] = cos; this.matrixs[1] = sin; this.matrixs[2] = 0; this.matrixs[3] = -sin; this.matrixs[4] = cos; this.matrixs[5] = 0; this.matrixs[6] = 0; this.matrixs[7] = 0; this.matrixs[8] = 1; } private float[] result; public float[] Get() { result[0] = matrixs[0]; result[1] = matrixs[1]; result[2] = matrixs[2]; result[3] = 0; result[4] = matrixs[3]; result[5] = matrixs[4]; result[6] = matrixs[5]; result[7] = 0; result[8] = 0; result[9] = 0; result[10] = 1; result[11] = 0; result[12] = matrixs[6]; result[13] = matrixs[7]; result[14] = 0; result[15] = matrixs[8]; return result; } public void RotationX(float angleX) { angleX = MathUtils.PI / 180 * angleX; Set(1f, 0f, 0f, 0f, MathUtils.Cos(angleX), -MathUtils.Sin(angleX), 0f, MathUtils.Sin(angleX), MathUtils.Cos(angleX)); } public void RotationY(float angleY) { angleY = MathUtils.PI / 180 * angleY; Set(MathUtils.Cos(angleY), 0f, MathUtils.Sin(angleY), 0f, 1f, 0f, -MathUtils.Sin(angleY), 0f, MathUtils.Cos(angleY)); } public void RotationZ(float angleZ) { angleZ = MathUtils.PI / 180 * angleZ; Set(MathUtils.Cos(angleZ), -MathUtils.Sin(angleZ), 0f, MathUtils.Sin(angleZ), MathUtils.Cos(angleZ), 0f, 0f, 0f, 1f); } public void Scale(float sx, float sy) { this.matrixs[0] = sx; this.matrixs[1] = 0; this.matrixs[2] = 0; this.matrixs[3] = 0; this.matrixs[4] = sy; this.matrixs[5] = 0; this.matrixs[6] = 0; this.matrixs[7] = 0; this.matrixs[8] = 1; } public void Idt() { if (matrixs == null) { matrixs = new float[] { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; } else { this.matrixs[0] = 1; this.matrixs[1] = 0; this.matrixs[2] = 0; this.matrixs[3] = 0; this.matrixs[4] = 1; this.matrixs[5] = 0; this.matrixs[6] = 0; this.matrixs[7] = 0; this.matrixs[8] = 1; } } public bool IsIdt() { return (matrixs[0] == 1 && matrixs[1] == 0 && matrixs[2] == 0) && (matrixs[3] == 0 && matrixs[4] == 1 && matrixs[5] == 0) && (matrixs[6] == 0 && matrixs[7] == 0 && matrixs[8] == 1); } public float Det() { return matrixs[0] * matrixs[4] * matrixs[8] + matrixs[3] * matrixs[7] * matrixs[2] + matrixs[6] * matrixs[1] * matrixs[5] - matrixs[0] * matrixs[7] * matrixs[5] - matrixs[3] * matrixs[1] * matrixs[8] - matrixs[6] * matrixs[4] * matrixs[2]; } private static float Detd(float a, float b, float c, float d) { return (a * d) - (b * c); } public void Adj() { float a11 = this.matrixs[0]; float a12 = this.matrixs[1]; float a13 = this.matrixs[2]; float a21 = this.matrixs[3]; float a22 = this.matrixs[4]; float a23 = this.matrixs[5]; float a31 = this.matrixs[6]; float a32 = this.matrixs[7]; float a33 = this.matrixs[8]; this.matrixs[0] = Detd(a22, a23, a32, a33); this.matrixs[1] = Detd(a13, a12, a33, a32); this.matrixs[2] = Detd(a12, a13, a22, a23); this.matrixs[3] = Detd(a23, a21, a33, a31); this.matrixs[4] = Detd(a11, a13, a31, a33); this.matrixs[5] = Detd(a13, a11, a23, a21); this.matrixs[6] = Detd(a21, a22, a31, a32); this.matrixs[7] = Detd(a12, a11, a32, a31); this.matrixs[8] = Detd(a11, a12, a21, a22); } public void Add(Matrix m) { float a1 = this.matrixs[0]; float a2 = this.matrixs[1]; float a3 = this.matrixs[2]; float b1 = this.matrixs[3]; float b2 = this.matrixs[4]; float b3 = this.matrixs[5]; float c1 = this.matrixs[6]; float c2 = this.matrixs[7]; float c3 = this.matrixs[8]; a1 += m.matrixs[0]; a2 += m.matrixs[1]; a3 += m.matrixs[2]; b1 += m.matrixs[3]; b2 += m.matrixs[4]; b3 += m.matrixs[5]; c1 += m.matrixs[6]; c2 += m.matrixs[7]; c3 += m.matrixs[8]; this.matrixs[0] = a1; this.matrixs[1] = a2; this.matrixs[2] = a3; this.matrixs[3] = b1; this.matrixs[4] = b2; this.matrixs[5] = b3; this.matrixs[6] = c1; this.matrixs[7] = c2; this.matrixs[8] = c3; } public Matrix AddEqual(Matrix m) { Matrix newMatrix = new Matrix(this.matrixs); newMatrix.Add(m); return newMatrix; } public void Mul(float c) { float a1 = this.matrixs[0]; float a2 = this.matrixs[1]; float a3 = this.matrixs[2]; float b1 = this.matrixs[3]; float b2 = this.matrixs[4]; float b3 = this.matrixs[5]; float c1 = this.matrixs[6]; float c2 = this.matrixs[7]; float c3 = this.matrixs[8]; this.matrixs[0] = a1 * c; this.matrixs[1] = a2 * c; this.matrixs[2] = a3 * c; this.matrixs[3] = b1 * c; this.matrixs[4] = b2 * c; this.matrixs[5] = b3 * c; this.matrixs[6] = c1 * c; this.matrixs[7] = c2 * c; this.matrixs[8] = c3 * c; } public void Mul(Matrix m) { float a1 = matrixs[0] * m.matrixs[0] + matrixs[3] * m.matrixs[1] + matrixs[6] * m.matrixs[2]; float a2 = matrixs[0] * m.matrixs[3] + matrixs[3] * m.matrixs[4] + matrixs[6] * m.matrixs[5]; float a3 = matrixs[0] * m.matrixs[6] + matrixs[3] * m.matrixs[7] + matrixs[6] * m.matrixs[8]; float b1 = matrixs[1] * m.matrixs[0] + matrixs[4] * m.matrixs[1] + matrixs[7] * m.matrixs[2]; float b2 = matrixs[1] * m.matrixs[3] + matrixs[4] * m.matrixs[4] + matrixs[7] * m.matrixs[5]; float b3 = matrixs[1] * m.matrixs[6] + matrixs[4] * m.matrixs[7] + matrixs[7] * m.matrixs[8]; float c1 = matrixs[2] * m.matrixs[0] + matrixs[5] * m.matrixs[1] + matrixs[8] * m.matrixs[2]; float c2 = matrixs[2] * m.matrixs[3] + matrixs[5] * m.matrixs[4] + matrixs[8] * m.matrixs[5]; float c3 = matrixs[2] * m.matrixs[6] + matrixs[5] * m.matrixs[7] + matrixs[8] * m.matrixs[8]; this.matrixs[0] = a1; this.matrixs[1] = a2; this.matrixs[2] = a3; this.matrixs[3] = b1; this.matrixs[4] = b2; this.matrixs[5] = b3; this.matrixs[6] = c1; this.matrixs[7] = c2; this.matrixs[8] = c3; } public Matrix MulEqual(Matrix m) { if (m == null) { m = new Matrix(); } Matrix result_0 = new Matrix(this.matrixs); result_0.Mul(m); return result_0; } public Matrix Invert(Matrix m) { Matrix result_0 = m; if (result_0 == null) { result_0 = new Matrix(); } float det = Det(); if (Math.Abs(det) <= MathUtils.EPSILON) { throw new ArithmeticException("This matrix cannot be inverted !"); } float temp00 = matrixs[4] * matrixs[8] - matrixs[5] * matrixs[7]; float temp01 = matrixs[2] * matrixs[7] - matrixs[1] * matrixs[8]; float temp02 = matrixs[1] * matrixs[5] - matrixs[2] * matrixs[4]; float temp10 = matrixs[5] * matrixs[6] - matrixs[3] * matrixs[8]; float temp11 = matrixs[0] * matrixs[8] - matrixs[2] * matrixs[6]; float temp12 = matrixs[2] * matrixs[3] - matrixs[0] * matrixs[5]; float temp20 = matrixs[3] * matrixs[7] - matrixs[4] * matrixs[6]; float temp21 = matrixs[1] * matrixs[6] - matrixs[0] * matrixs[7]; float temp22 = matrixs[0] * matrixs[4] - matrixs[1] * matrixs[3]; result_0.Set(temp00, temp01, temp02, temp10, temp11, temp12, temp20, temp21, temp22); result_0.Mul(1.0f / det); return result_0; } public bool IsFloatValid() { bool valid = true; valid &= !Single.IsNaN(matrixs[0]); valid &= !Single.IsNaN(matrixs[1]); valid &= !Single.IsNaN(matrixs[2]); valid &= !Single.IsNaN(matrixs[3]); valid &= !Single.IsNaN(matrixs[4]); valid &= !Single.IsNaN(matrixs[5]); valid &= !Single.IsNaN(matrixs[6]); valid &= !Single.IsNaN(matrixs[7]); valid &= !Single.IsNaN(matrixs[8]); return valid; } public static Matrix Avg(ICollection<Matrix> set) { Matrix average = new Matrix(); average.Set(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f); float hist = 0; foreach (Matrix matrix3d in set) { if (matrix3d.IsFloatValid()) { average.Add(matrix3d); hist++; } } average.Mul(1f / hist); return average; } public void Copy(Matrix m) { if (m == null) { Idt(); } else { Set(m); } } public override bool Equals(object o) { if (!(o is Matrix) || o == null) { return false; } if ((object)this == o) { return true; } Matrix comp = (Matrix)o; if (matrixs[0].CompareTo(comp.matrixs[0]) != 0) { return false; } if (matrixs[1].CompareTo(comp.matrixs[1]) != 0) { return false; } if (matrixs[2].CompareTo(comp.matrixs[2]) != 0) { return false; } if (matrixs[3].CompareTo(comp.matrixs[3]) != 0) { return false; } if (matrixs[4].CompareTo(comp.matrixs[4]) != 0) { return false; } if (matrixs[5].CompareTo(comp.matrixs[5]) != 0) { return false; } if (matrixs[6].CompareTo(comp.matrixs[6]) != 0) { return false; } if (matrixs[7].CompareTo(comp.matrixs[7]) != 0) { return false; } if (matrixs[8].CompareTo(comp.matrixs[8]) != 0) { return false; } return true; } public override int GetHashCode() { int result = 17; for (int j = 0; j < 9; j++) { long val = (long)matrixs[j]; result += 31 * result + (int)(val ^ ((long)(((ulong)val) >> 32))); } return result; } public Vector2f Transform(Vector2f pt) { float[] ins0 = new float[] { pt.x, pt.y }; float[] xout = new float[2]; Transform(ins0, 0, xout, 0, 1); return new Vector2f(xout[0], xout[1]); } public Matrix Clone() { return new Matrix(this.matrixs); } public float[] GetValues() { return matrixs; } } }
using System; using System.Collections.Generic; using System.Linq; using Inforigami.Regalo.Interfaces; using Moq; using NUnit.Framework; using Raven.Abstractions.Data; using Raven.Client; using Raven.Client.Document; using Raven.Client.Embedded; using Inforigami.Regalo.Core; using Inforigami.Regalo.EventSourcing; using Inforigami.Regalo.RavenDB.Tests.Unit.DomainModel.Customers; using Inforigami.Regalo.Testing; namespace Inforigami.Regalo.RavenDB.Tests.Unit { [TestFixture] public class PersistenceTests { private IDocumentStore _documentStore; [SetUp] public void SetUp() { //_documentStore = new EmbeddableDocumentStore { RunInMemory = true }; _documentStore = new DocumentStore { Url = "http://localhost:8080/", DefaultDatabase = GetType().FullName }; _documentStore.Initialize(); Resolver.Configure(type => { if (type == typeof(ILogger)) return new ConsoleLogger(); throw new InvalidOperationException(string.Format("No type of {0} registered.", type)); }, type => null, o => { }); } [TearDown] public void TearDown() { Conventions.SetFindAggregateTypeForEventType(null); Resolver.Reset(); _documentStore.Dispose(); _documentStore = null; } [Test] public void Loading_GivenEmptyStore_ShouldReturnNull() { // Arrange IEventStore store = new RavenEventStore(_documentStore); // Act EventStream<Customer> stream = store.Load<Customer>(Guid.NewGuid().ToString()); // Assert CollectionAssert.IsEmpty(stream.Events); } [Test] public void Saving_GivenSingleEvent_ShouldAllowReloading() { // Arrange IEventStore store = new RavenEventStore(_documentStore); // Act var id = Guid.NewGuid(); var evt = new CustomerSignedUp(id); store.Save<Customer>(id.ToString(), 0, new[] { evt }); var stream = store.Load<Customer>(id.ToString()); // Assert Assert.NotNull(stream); CollectionAssert.AreEqual( new object[] { evt }, stream.Events, "Events reloaded from store do not match those generated by aggregate."); } [Test] public void Saving_GivenEventWithGuidProperty_ShouldAllowReloadingToGuidType() { // Arrange IEventStore store = new RavenEventStore(_documentStore); var customer = new Customer(); customer.Signup(); var accountManager = new AccountManager(); var startDate = new DateTime(2012, 4, 28); accountManager.Employ(startDate); customer.AssignAccountManager(accountManager.Id, startDate); store.Save<Customer>(customer.Id.ToString(), 0, customer.GetUncommittedEvents()); // Act var acctMgrAssignedEvent = (AssignedAccountManager)store.Load<Customer>(customer.Id.ToString()) .Events .LastOrDefault(); // Assert Assert.NotNull(acctMgrAssignedEvent); Assert.AreEqual(accountManager.Id, acctMgrAssignedEvent.AccountManagerId); } [Test] public void Saving_GivenEvents_ShouldAllowReloading() { // Arrange IEventStore store = new RavenEventStore(_documentStore); // Act var customer = new Customer(); customer.Signup(); store.Save<Customer>(customer.Id.ToString(), 0, customer.GetUncommittedEvents()); var stream = store.Load<Customer>(customer.Id.ToString()); // Assert Assert.NotNull(stream); CollectionAssert.AreEqual(customer.GetUncommittedEvents(), stream.Events, "Events reloaded from store do not match those generated by aggregate."); } [Test] public void Saving_GivenNoEvents_ShouldDoNothing() { // Arrange IEventStore store = new RavenEventStore(_documentStore); // Act var id = Guid.NewGuid(); store.Save<Customer>(id.ToString(), 0, Enumerable.Empty<IEvent>()); var stream = store.Load<Customer>(id.ToString()); // Assert CollectionAssert.IsEmpty(stream.Events); } [Test] public void GivenAggregateWithMultipleEvents_WhenLoadingSpecificVersion_ThenShouldOnlyReturnRequestedEvents() { // Arrange IEventStore store = new RavenEventStore(_documentStore); var customerId = Guid.NewGuid(); var storedEvents = new EventChain().Add(new CustomerSignedUp(customerId)) .Add(new SubscribedToNewsletter("latest")) .Add(new SubscribedToNewsletter("top")); store.Save<Customer>(customerId.ToString(), 0, storedEvents); // Act var stream = store.Load<Customer>(customerId.ToString(), storedEvents[1].Version); // Assert CollectionAssert.AreEqual(storedEvents.Take(2), stream.Events, "Events loaded from store do not match version requested."); } [Test] public void GivenAggregateWithMultipleEvents_WhenLoadingSpecificVersionThatNoEventHas_ThenShouldFail() { // Arrange IEventStore store = new RavenEventStore(_documentStore); var customerId = Guid.NewGuid(); var storedEvents = new IEvent[] { new CustomerSignedUp(customerId), new SubscribedToNewsletter("latest"), new SubscribedToNewsletter("top") }; store.Save<Customer>(customerId.ToString(), 0, storedEvents); // Act / Assert Assert.Throws<ArgumentOutOfRangeException>(() => store.Load<Customer>(customerId.ToString(), 4)); } [Test] public void Saving_GivenEventMappedToAggregateType_ThenShouldSetRavenCollectionName() { var customerId = Guid.NewGuid(); using (var eventStore = new RavenEventStore(_documentStore)) { Conventions.SetFindAggregateTypeForEventType( type => { if (type == typeof(CustomerSignedUp)) { return typeof(Customer); } return typeof(EventStream); }); var storedEvents = new IEvent[] { new CustomerSignedUp(customerId), new SubscribedToNewsletter("latest"), new SubscribedToNewsletter("top") }; eventStore.Save<Customer>(customerId.ToString(), 0, storedEvents); eventStore.Flush(); } using (var session = _documentStore.OpenSession()) { var eventStream = session.Load<EventStream>(customerId.ToString()); var entityName = session.Advanced.GetMetadataFor(eventStream)[Constants.RavenEntityName].ToString(); Assert.That(entityName, Is.EqualTo("Customers")); } } } }
// 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.Text; using System.IO; using System.Xml; using Microsoft.Test.ModuleCore; using XmlCoreTest.Common; public enum NodeFlags { None = 0, EmptyElement = 1, HasValue = 2, SingleQuote = 4, DefaultAttribute = 8, UnparsedEntities = 16, IsWhitespace = 32, DocumentRoot = 64, AttributeTextNode = 128, MixedContent = 256, Indent = 512 } public abstract class CXmlBase { protected XmlNodeType pnType; protected string pstrName; protected string pstrLocalName; protected string pstrPrefix; protected string pstrNamespace; internal int pnDepth; internal NodeFlags peFlags = NodeFlags.None; internal CXmlBase prNextNode = null; internal CXmlBase prParentNode = null; internal CXmlBase prFirstChildNode = null; internal CXmlBase prLastChildNode = null; internal int pnChildNodes = 0; // // Constructors // public CXmlBase(string strPrefix, string strName, string strLocalName, XmlNodeType NodeType, string strNamespace) { pstrPrefix = strPrefix; pstrName = strName; pstrLocalName = strLocalName; pnType = NodeType; pstrNamespace = strNamespace; } public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType, string strNamespace) : this(strPrefix, strName, strName, NodeType, strNamespace) { } public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType) : this(strPrefix, strName, strName, NodeType, "") { } public CXmlBase(string strName, XmlNodeType NodeType) : this("", strName, strName, NodeType, "") { } // // Virtual Methods and Properties // public abstract void Write(XmlWriter rXmlWriter); public abstract string Xml { get; } public abstract void WriteXml(TextWriter rTW); public abstract string Value { get; } // // Public Methods and Properties // public string Name { get { return pstrName; } } public string LocalName { get { return pstrLocalName; } } public string Prefix { get { return pstrPrefix; } } public string Namespace { get { return pstrNamespace; } } public int Depth { get { return pnDepth; } } public XmlNodeType NodeType { get { return pnType; } } public NodeFlags Flags { get { return peFlags; } } public int ChildNodeCount { get { return pnChildNodes; } } public void InsertNode(CXmlBase rNode) { if (prFirstChildNode == null) { prFirstChildNode = prLastChildNode = rNode; } else { prLastChildNode.prNextNode = rNode; prLastChildNode = rNode; } if ((this.peFlags & NodeFlags.IsWhitespace) == 0) pnChildNodes++; rNode.prParentNode = this; } // // Internal Methods and Properties // internal CXmlBase _Child(int n) { int i; int j; CXmlBase rChild = prFirstChildNode; for (i = 0, j = 0; rChild != null; i++, rChild = rChild.prNextNode) { if ((rChild.peFlags & NodeFlags.IsWhitespace) == 0) { if (j++ == n) break; } } return rChild; } internal CXmlBase _Child(string str) { CXmlBase rChild; for (rChild = prFirstChildNode; rChild != null; rChild = rChild.prNextNode) if (rChild.Name == str) break; return rChild; } } public class CXmlAttribute : CXmlBase { // // Constructor // public CXmlAttribute(XmlReader rXmlReader) : base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI) { if (rXmlReader.IsDefault) peFlags |= NodeFlags.DefaultAttribute; } // // Public Methods and Properties (Override) // public override void Write(XmlWriter rXmlWriter) { CXmlBase rNode; if ((this.peFlags & NodeFlags.DefaultAttribute) == 0) { rXmlWriter.WriteStartAttribute(this.Prefix, this.LocalName, this.Namespace); for (rNode = this.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) { rNode.Write(rXmlWriter); } rXmlWriter.WriteEndAttribute(); } } public override string Xml { get { CXmlCache._rBufferWriter.Dispose(); WriteXml(CXmlCache._rBufferWriter); return CXmlCache._rBufferWriter.ToString(); } } public override void WriteXml(TextWriter rTW) { if ((this.peFlags & NodeFlags.DefaultAttribute) == 0) { CXmlBase rNode; rTW.Write(' ' + this.Name + '=' + this.Quote); for (rNode = this.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) { rNode.WriteXml(rTW); } rTW.Write(this.Quote); } } // // Public Methods and Properties // public override string Value { get { CXmlNode rNode; string strValue = string.Empty; for (rNode = (CXmlNode)this.prFirstChildNode; rNode != null; rNode = rNode.NextNode) strValue += rNode.Value; return strValue; } } public CXmlAttribute NextAttribute { get { return (CXmlAttribute)this.prNextNode; } } public char Quote { get { return ((base.peFlags & NodeFlags.SingleQuote) != 0 ? '\'' : '"'); } set { if (value == '\'') base.peFlags |= NodeFlags.SingleQuote; else base.peFlags &= ~NodeFlags.SingleQuote; } } public CXmlNode FirstChild { get { return (CXmlNode)base.prFirstChildNode; } } public CXmlNode Child(int n) { return (CXmlNode)base._Child(n); } public CXmlNode Child(string str) { return (CXmlNode)base._Child(str); } } public class CXmlNode : CXmlBase { internal string _strValue = null; private CXmlAttribute _rFirstAttribute = null; private CXmlAttribute _rLastAttribute = null; private int _nAttributeCount = 0; // // Constructors // public CXmlNode(string strPrefix, string strName, XmlNodeType NodeType) : base(strPrefix, strName, NodeType) { } public CXmlNode(XmlReader rXmlReader) : base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI) { peFlags |= CXmlCache._eDefaultFlags; if (NodeType == XmlNodeType.Whitespace || NodeType == XmlNodeType.SignificantWhitespace) { peFlags |= NodeFlags.IsWhitespace; } if (rXmlReader.IsEmptyElement) { peFlags |= NodeFlags.EmptyElement; } if (rXmlReader.HasValue) { peFlags |= NodeFlags.HasValue; _strValue = rXmlReader.Value; } } // // Public Methods and Properties (Override) // public override void Write(XmlWriter rXmlWriter) { CXmlBase rNode; CXmlAttribute rAttribute; string DocTypePublic = null; string DocTypeSystem = null; switch (this.NodeType) { case XmlNodeType.CDATA: rXmlWriter.WriteCData(_strValue); break; case XmlNodeType.Comment: rXmlWriter.WriteComment(_strValue); break; case XmlNodeType.DocumentType: for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { if (rAttribute.Name == "PUBLIC") { DocTypePublic = rAttribute.Value; } if (rAttribute.Name == "SYSTEM") { DocTypeSystem = rAttribute.Value; } } rXmlWriter.WriteDocType(this.Name, DocTypePublic, DocTypeSystem, _strValue); break; case XmlNodeType.EntityReference: rXmlWriter.WriteEntityRef(this.Name); break; case XmlNodeType.ProcessingInstruction: rXmlWriter.WriteProcessingInstruction(this.Name, _strValue); break; case XmlNodeType.Text: if (this.Name == string.Empty) { if ((this.Flags & NodeFlags.UnparsedEntities) == 0) { rXmlWriter.WriteString(_strValue); } else { rXmlWriter.WriteRaw(_strValue.ToCharArray(), 0, _strValue.Length); } } else { if (this.pstrName[0] == '#') rXmlWriter.WriteCharEntity(_strValue[0]); else rXmlWriter.WriteEntityRef(this.Name); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if ((this.prParentNode.peFlags & NodeFlags.DocumentRoot) != 0) rXmlWriter.WriteRaw(_strValue.ToCharArray(), 0, _strValue.Length); else rXmlWriter.WriteString(_strValue); break; case XmlNodeType.Element: rXmlWriter.WriteStartElement(this.Prefix, this.LocalName, null); for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { rAttribute.Write(rXmlWriter); } if ((this.Flags & NodeFlags.EmptyElement) == 0) rXmlWriter.WriteString(string.Empty); for (rNode = base.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) { rNode.Write(rXmlWriter); } // Should only produce empty tag if the original document used empty tag if ((this.Flags & NodeFlags.EmptyElement) == 0) rXmlWriter.WriteFullEndElement(); else rXmlWriter.WriteEndElement(); break; case XmlNodeType.XmlDeclaration: rXmlWriter.WriteRaw("<?xml " + _strValue + "?>"); break; default: throw (new Exception("Node.Write: Unhandled node type " + this.NodeType.ToString())); } } public override string Xml { get { CXmlCache._rBufferWriter.Dispose(); WriteXml(CXmlCache._rBufferWriter); return CXmlCache._rBufferWriter.ToString(); } } public override void WriteXml(TextWriter rTW) { string strXml; CXmlAttribute rAttribute; CXmlBase rNode; switch (this.pnType) { case XmlNodeType.Text: if (this.pstrName == "") { rTW.Write(_strValue); } else { if (this.pstrName.StartsWith("#")) { rTW.Write("&" + Convert.ToString(Convert.ToInt32(_strValue[0])) + ";"); } else { rTW.Write("&" + this.Name + ";"); } } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.DocumentType: rTW.Write(_strValue); break; case XmlNodeType.Element: strXml = this.Name; rTW.Write('<' + strXml); //Put in all the Attributes for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { rAttribute.WriteXml(rTW); } //If there is children, put those in, otherwise close the tag. if ((base.peFlags & NodeFlags.EmptyElement) == 0) { rTW.Write('>'); for (rNode = base.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) { rNode.WriteXml(rTW); } rTW.Write("</" + strXml + ">"); } else { rTW.Write(" />"); } break; case XmlNodeType.EntityReference: rTW.Write("&" + this.pstrName + ";"); break; case XmlNodeType.Notation: rTW.Write("<!NOTATION " + _strValue + ">"); break; case XmlNodeType.CDATA: rTW.Write("<![CDATA[" + _strValue + "]]>"); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: rTW.Write("<?" + this.pstrName + " " + _strValue + "?>"); break; case XmlNodeType.Comment: rTW.Write("<!--" + _strValue + "-->"); break; default: throw (new Exception("Unhandled NodeType " + this.pnType.ToString())); } } // // Public Methods and Properties // public string NodeValue { get { return _strValue; } } public override string Value { get { string strValue = ""; CXmlNode rChild; if ((this.peFlags & NodeFlags.HasValue) != 0) { char chEnt; int nIndexAmp = 0; int nIndexSem = 0; if ((this.peFlags & NodeFlags.UnparsedEntities) == 0) return _strValue; strValue = _strValue; while ((nIndexAmp = strValue.IndexOf('&', nIndexAmp)) != -1) { nIndexSem = strValue.IndexOf(';', nIndexAmp); chEnt = ResolveCharEntity(strValue.Substring(nIndexAmp + 1, nIndexSem - nIndexAmp - 1)); if (chEnt != char.MinValue) { strValue = strValue.Substring(0, nIndexAmp) + chEnt + strValue.Substring(nIndexSem + 1); nIndexAmp++; } else nIndexAmp = nIndexSem; } return strValue; } for (rChild = (CXmlNode)this.prFirstChildNode; rChild != null; rChild = (CXmlNode)rChild.prNextNode) { strValue = strValue + rChild.Value; } return strValue; } } public CXmlNode NextNode { get { CXmlBase rNode = this.prNextNode; while (rNode != null && (rNode.Flags & NodeFlags.IsWhitespace) != 0) rNode = rNode.prNextNode; return (CXmlNode)rNode; } } public CXmlNode FirstChild { get { CXmlBase rNode = this.prFirstChildNode; while (rNode != null && (rNode.Flags & NodeFlags.IsWhitespace) != 0) rNode = rNode.prNextNode; return (CXmlNode)rNode; } } public CXmlNode Child(int n) { int i; CXmlNode rChild; i = 0; for (rChild = FirstChild; rChild != null; rChild = rChild.NextNode) if (i++ == n) break; return rChild; } public CXmlNode Child(string str) { return (CXmlNode)base._Child(str); } public int Type { get { return Convert.ToInt32(base.pnType); } } public CXmlAttribute FirstAttribute { get { return _rFirstAttribute; } } public int AttributeCount { get { return _nAttributeCount; } } public CXmlAttribute Attribute(int n) { int i; CXmlAttribute rAttribute; i = 0; for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) if (i++ == n) break; return rAttribute; } public CXmlAttribute Attribute(string str) { CXmlAttribute rAttribute; for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { if (rAttribute.Name == str) break; } return rAttribute; } public void AddAttribute(CXmlAttribute rAttribute) { if (_rFirstAttribute == null) { _rFirstAttribute = rAttribute; } else { _rLastAttribute.prNextNode = rAttribute; } _rLastAttribute = rAttribute; _nAttributeCount++; } private char ResolveCharEntity(string strName) { if (strName[0] == '#') if (strName[1] == 'x') return Convert.ToChar(Convert.ToInt32(strName.Substring(2), 16)); else return Convert.ToChar(Convert.ToInt32(strName.Substring(1))); if (strName == "lt") return '<'; if (strName == "gt") return '>'; if (strName == "amp") return '&'; if (strName == "apos") return '\''; if (strName == "quot") return '"'; return char.MinValue; } } public class CXmlCache { //CXmlCache Properties private bool _fTrace = false; private bool _fThrow = true; private bool _fReadNode = true; private int _hr = 0; private Encoding _eEncoding = System.Text.Encoding.UTF8; private string _strParseError = ""; //XmlReader Properties private bool _fNamespaces = true; private bool _fValidationCallback = false; private bool _fExpandAttributeValues = false; //Internal stuff protected XmlReader prXmlReader = null; protected CXmlNode prDocumentRootNode; protected CXmlNode prRootNode = null; internal static NodeFlags _eDefaultFlags = NodeFlags.None; internal static BufferWriter _rBufferWriter = new BufferWriter(); // // Constructor // public CXmlCache() { } // // Public Methods and Properties // public virtual bool Load(XmlReader rXmlReader) { //Hook up your reader as my reader prXmlReader = rXmlReader; //Process the Document try { prDocumentRootNode = new CXmlNode("", "", XmlNodeType.Element); prDocumentRootNode.peFlags = NodeFlags.DocumentRoot | NodeFlags.Indent; Process(prDocumentRootNode); for (prRootNode = prDocumentRootNode.FirstChild; prRootNode != null && prRootNode.NodeType != XmlNodeType.Element; prRootNode = prRootNode.NextNode) ; } catch (Exception e) { //Unhook your reader prXmlReader = null; _strParseError = e.ToString(); if (_fThrow) { throw (e); } if (_hr == 0) _hr = -1; return false; } //Unhook your reader prXmlReader = null; return true; } public bool Load(string strFileName) { XmlReader rXmlTextReader; bool fRet; rXmlTextReader = XmlReader.Create(FilePathUtil.getStream(strFileName)); fRet = Load(rXmlTextReader); return fRet; } public void Save(string strName) { Save(strName, false, _eEncoding); } public void Save(string strName, bool fOverWrite) { Save(strName, fOverWrite, _eEncoding); } public void Save(string strName, bool fOverWrite, System.Text.Encoding Encoding) { CXmlBase rNode; XmlWriter rXmlTextWriter = null; try { rXmlTextWriter = XmlWriter.Create(FilePathUtil.getStream(strName)); for (rNode = prDocumentRootNode.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) { rNode.Write(rXmlTextWriter); } rXmlTextWriter.Dispose(); } catch (Exception e) { DebugTrace(e.ToString()); if (rXmlTextWriter != null) rXmlTextWriter.Dispose(); throw (e); } } public virtual string Xml { get { _rBufferWriter.Dispose(); WriteXml(_rBufferWriter); return _rBufferWriter.ToString(); } } public void WriteXml(TextWriter rTW) { CXmlBase rNode; //Spit out the document for (rNode = prDocumentRootNode.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) rNode.WriteXml(rTW); } public CXmlNode RootNode { get { return prRootNode; } } public string ParseError { get { return _strParseError; } } public int ParseErrorCode { get { return _hr; } } // // XmlReader Properties // public bool Namespaces { set { _fNamespaces = value; } get { return _fNamespaces; } } public bool UseValidationCallback { set { _fValidationCallback = value; } get { return _fValidationCallback; } } public bool ExpandAttributeValues { set { _fExpandAttributeValues = value; } get { return _fExpandAttributeValues; } } // // Internal Properties // public bool Throw { get { return _fThrow; } set { _fThrow = value; } } public bool Trace { set { _fTrace = value; } get { return _fTrace; } } // //Private Methods // private void DebugTrace(string str) { DebugTrace(str, 0); } private void DebugTrace(string str, int nDepth) { if (_fTrace) { int i; for (i = 0; i < nDepth; i++) TestLog.Write(" "); TestLog.WriteLine(str); } } private void DebugTrace(XmlReader rXmlReader) { if (_fTrace) { string str; str = rXmlReader.NodeType.ToString() + ", Depth=" + rXmlReader.Depth + " Name="; if (rXmlReader.Prefix != "") { str += rXmlReader.Prefix + ":"; } str += rXmlReader.LocalName; if (rXmlReader.HasValue) str += " Value=" + rXmlReader.Value; DebugTrace(str, rXmlReader.Depth); } } protected void Process(CXmlBase rParentNode) { CXmlNode rNewNode; while (true) { //We want to pop if Read() returns false, aka EOF if (_fReadNode) { if (!prXmlReader.Read()) { DebugTrace("Read() == false"); return; } } else { if (!prXmlReader.ReadAttributeValue()) { DebugTrace("ReadAttributeValue() == false"); return; } } DebugTrace(prXmlReader); //We also want to pop if we get an EndElement or EndEntity if (prXmlReader.NodeType == XmlNodeType.EndElement || prXmlReader.NodeType == XmlNodeType.EndEntity) { DebugTrace("NodeType == EndElement or EndEntity"); return; } rNewNode = GetNewNode(prXmlReader); rNewNode.pnDepth = prXmlReader.Depth; // Test for MixedContent and set Indent if necessary if ((rParentNode.Flags & NodeFlags.MixedContent) != 0) { rNewNode.peFlags |= NodeFlags.MixedContent; // Indent is off for all new nodes } else { rNewNode.peFlags |= NodeFlags.Indent; // Turn on Indent for current Node } // Set all Depth 0 nodes to No Mixed Content and Indent True if (prXmlReader.Depth == 0) { rNewNode.peFlags |= NodeFlags.Indent; // Turn on Indent rNewNode.peFlags &= ~NodeFlags.MixedContent; // Turn off MixedContent } rParentNode.InsertNode(rNewNode); //Do some special stuff based on NodeType switch (prXmlReader.NodeType) { case XmlNodeType.Element: if (prXmlReader.MoveToFirstAttribute()) { do { CXmlAttribute rNewAttribute = new CXmlAttribute(prXmlReader); rNewNode.AddAttribute(rNewAttribute); if (_fExpandAttributeValues) { DebugTrace("Attribute: " + prXmlReader.Name); _fReadNode = false; Process(rNewAttribute); _fReadNode = true; } else { CXmlNode rValueNode = new CXmlNode("", "", XmlNodeType.Text); rValueNode.peFlags = _eDefaultFlags | NodeFlags.HasValue; rValueNode._strValue = prXmlReader.Value; DebugTrace(" Value=" + rValueNode.Value, prXmlReader.Depth + 1); rNewAttribute.InsertNode(rValueNode); } } while (prXmlReader.MoveToNextAttribute()); } if ((rNewNode.Flags & NodeFlags.EmptyElement) == 0) Process(rNewNode); break; case XmlNodeType.XmlDeclaration: string strValue = rNewNode.NodeValue; int nPos = strValue.IndexOf("encoding"); if (nPos != -1) { int nEnd; nPos = strValue.IndexOf("=", nPos); //Find the = sign nEnd = strValue.IndexOf("\"", nPos) + 1; //Find the next " character nPos = strValue.IndexOf("'", nPos) + 1; //Find the next ' character if (nEnd == 0 || (nPos < nEnd && nPos > 0)) //Pick the one that's closer to the = sign { nEnd = strValue.IndexOf("'", nPos); } else { nPos = nEnd; nEnd = strValue.IndexOf("\"", nPos); } string sEncodeName = strValue.Substring(nPos, nEnd - nPos); DebugTrace("XMLDecl contains encoding " + sEncodeName); if (sEncodeName.ToUpper() == "UCS-2") { sEncodeName = "unicode"; } _eEncoding = System.Text.Encoding.GetEncoding(sEncodeName); } break; case XmlNodeType.ProcessingInstruction: break; case XmlNodeType.Text: if (!_fReadNode) { rNewNode.peFlags = _eDefaultFlags | NodeFlags.AttributeTextNode; } rNewNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node rNewNode.peFlags &= ~NodeFlags.Indent; // turn off Indent for current node rParentNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: rNewNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node rNewNode.peFlags &= ~NodeFlags.Indent; // turn off Indent for current node rParentNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node break; case XmlNodeType.Comment: case XmlNodeType.Notation: break; case XmlNodeType.DocumentType: if (prXmlReader.MoveToFirstAttribute()) { do { CXmlAttribute rNewAttribute = new CXmlAttribute(prXmlReader); rNewNode.AddAttribute(rNewAttribute); CXmlNode rValueNode = new CXmlNode(prXmlReader); rValueNode._strValue = prXmlReader.Value; rNewAttribute.InsertNode(rValueNode); } while (prXmlReader.MoveToNextAttribute()); } break; default: TestLog.WriteLine("UNHANDLED TYPE, " + prXmlReader.NodeType.ToString() + " IN Process()!"); break; } } } protected virtual CXmlNode GetNewNode(XmlReader rXmlReader) { return new CXmlNode(rXmlReader); } } public class ChecksumWriter : TextWriter { private int _nPosition = 0; private decimal _dResult = 0; private Encoding _encoding; // -------------------------------------------------------------------------------------------------- // Constructor // -------------------------------------------------------------------------------------------------- public ChecksumWriter() { _encoding = Encoding.UTF8; } // -------------------------------------------------------------------------------------------------- // Properties // -------------------------------------------------------------------------------------------------- public decimal CheckSum { get { return _dResult; } } public override Encoding Encoding { get { return _encoding; } } // -------------------------------------------------------------------------------------------------- // Public methods // -------------------------------------------------------------------------------------------------- public override void Write(string str) { int i; int m; m = str.Length; for (i = 0; i < m; i++) { Write(str[i]); } } public override void Write(char[] rgch) { int i; int m; m = rgch.Length; for (i = 0; i < m; i++) { Write(rgch[i]); } } public override void Write(char[] rgch, int iOffset, int iCount) { int i; int m; m = iOffset + iCount; for (i = iOffset; i < m; i++) { Write(rgch[i]); } } public override void Write(char ch) { _dResult += Math.Round((decimal)(ch / (_nPosition + 1.0)), 10); _nPosition++; } public new void Dispose() { _nPosition = 0; _dResult = 0; } } public class BufferWriter : TextWriter { private int _nBufferSize = 0; private int _nBufferUsed = 0; private int _nBufferGrow = 1024; private char[] _rgchBuffer = null; private Encoding _encoding; // -------------------------------------------------------------------------------------------------- // Constructor // -------------------------------------------------------------------------------------------------- public BufferWriter() { _encoding = Encoding.UTF8; } // -------------------------------------------------------------------------------------------------- // Properties // -------------------------------------------------------------------------------------------------- public override string ToString() { return new string(_rgchBuffer, 0, _nBufferUsed); } public override Encoding Encoding { get { return _encoding; } } // -------------------------------------------------------------------------------------------------- // Public methods // -------------------------------------------------------------------------------------------------- public override void Write(string str) { int i; int m; m = str.Length; for (i = 0; i < m; i++) { Write(str[i]); } } public override void Write(char[] rgch) { int i; int m; m = rgch.Length; for (i = 0; i < m; i++) { Write(rgch[i]); } } public override void Write(char[] rgch, int iOffset, int iCount) { int i; int m; m = iOffset + iCount; for (i = iOffset; i < m; i++) { Write(rgch[i]); } } public override void Write(char ch) { if (_nBufferUsed == _nBufferSize) { char[] rgchTemp = new char[_nBufferSize + _nBufferGrow]; for (_nBufferUsed = 0; _nBufferUsed < _nBufferSize; _nBufferUsed++) rgchTemp[_nBufferUsed] = _rgchBuffer[_nBufferUsed]; _rgchBuffer = rgchTemp; _nBufferSize += _nBufferGrow; if (_nBufferGrow < (1024 * 1024)) _nBufferGrow *= 2; } _rgchBuffer[_nBufferUsed++] = ch; } public new void Dispose() { //Set nBufferUsed to 0, so we start writing from the beginning of the buffer. _nBufferUsed = 0; } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using ESRI.ArcGIS.ADF.BaseClasses; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.Animation; using ESRI.ArcGIS.ADF; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.SystemUI; using ESRI.ArcGIS.Geometry; namespace AnimationDeveloperSamples { public class AnimationUtils { public static void CreateMapGraphicTrack(ICreateGraphicTrackOptions pOptions, IAGAnimationTracks tracks, IAGAnimationContainer pContainer) { pOptions.PathGeometry=SimplifyPath2D(pOptions.PathGeometry,pOptions.ReverseOrder,pOptions.SimplificationFactor); IAGAnimationType animType = new AnimationTypeMapGraphic(); //remove tracks with the same name if overwrite is true if (pOptions.OverwriteTrack == true) { IArray trackArray = new ArrayClass(); trackArray = tracks.get_TracksOfType(animType); int count = trackArray.Count; for (int i = 0; i < count; i++) { IAGAnimationTrack temp = (IAGAnimationTrack)trackArray.get_Element(i); if (temp.Name == pOptions.TrackName) tracks.RemoveTrack(temp); } } //create the new track IAGAnimationTrack animTrack = tracks.CreateTrack(animType); IAGAnimationTrackKeyframes animTrackKeyframes = (IAGAnimationTrackKeyframes)animTrack; animTrackKeyframes.EvenTimeStamps = false; animTrack.Name = pOptions.TrackName; IGeometry path = pOptions.PathGeometry; IPointCollection pointCollection = (IPointCollection)path; ICurve curve = (ICurve)path; double length = curve.Length; double accuLength = 0; //loop through all points to create the keyframes int pointCount = pointCollection.PointCount; if (pointCount <= 1) return; for (int i = 0; i < pointCount; i++) { IPoint currentPoint = pointCollection.get_Point(i); IPoint nextPoint = new PointClass(); if (i < pointCount-1) nextPoint = pointCollection.get_Point(i + 1); IPoint lastPoint = new PointClass(); if (i == 0) lastPoint = currentPoint; else lastPoint = pointCollection.get_Point(i-1); IAGKeyframe tempKeyframe = animTrackKeyframes.CreateKeyframe(i); //set keyframe properties double x; double y; currentPoint.QueryCoords(out x, out y); tempKeyframe.set_PropertyValue(0, currentPoint); tempKeyframe.Name = "Map Graphic keyframe " + i.ToString(); //set keyframe timestamp accuLength += CalculateDistance(lastPoint, currentPoint); double timeStamp = accuLength / length; tempKeyframe.TimeStamp = timeStamp; double x1; double y1; double angle; if (i < pointCount - 1) { nextPoint.QueryCoords(out x1, out y1); if ((y1 - y) > 0) angle = Math.Acos((x1 - x) / Math.Sqrt((x1 - x) * (x1 - x) + (y1 - y) * (y1 - y))); else { angle = 6.2832 - Math.Acos((x1 - x) / Math.Sqrt((x1 - x) * (x1 - x) + (y1 - y) * (y1 - y))); } tempKeyframe.set_PropertyValue(1, angle); } else { IAGKeyframe lastKeyframe = animTrackKeyframes.get_Keyframe(i-1); tempKeyframe.set_PropertyValue(1, lastKeyframe.get_PropertyValue(1)); } } //attach the point element if(pOptions.PointElement != null) animTrack.AttachObject(pOptions.PointElement); //attach the track extension, which contains a line element for trace IMapGraphicTrackExtension graphicTrackExtension = new MapGraphicTrackExtension(); graphicTrackExtension.ShowTrace = pOptions.AnimatePath; IAGAnimationTrackExtensions trackExtensions = (IAGAnimationTrackExtensions)animTrack; trackExtensions.AddExtension(graphicTrackExtension); } private static double CalculateDistance(IPoint FromPoint, IPoint ToPoint) { double distance; distance = Math.Sqrt((ToPoint.X - FromPoint.X) * (ToPoint.X - FromPoint.X) + (ToPoint.Y - FromPoint.Y) * (ToPoint.Y - FromPoint.Y)); return distance; } private static IGeometry SimplifyPath2D(IGeometry path, bool bReverse, double simpFactor) { IGeometry oldPath = path; IPointCollection oldPointCollection = oldPath as IPointCollection; IPolyline newPath = new PolylineClass(); IPointCollection newPointCollection = newPath as IPointCollection; ISpatialReference sr = oldPath.SpatialReference; int pointCount; pointCount = oldPointCollection.PointCount; double[] lastCoord = new double[2]; IPoint beginningPoint = new PointClass(); oldPointCollection.QueryPoint(bReverse ? (pointCount - 1) : 0, beginningPoint); beginningPoint.QueryCoords(out lastCoord[0], out lastCoord[1]); bool bKeep = true; IPolyline oldLine = oldPath as IPolyline; double length = oldLine.Length; object Missing = Type.Missing; newPointCollection.AddPoint(beginningPoint, ref Missing, ref Missing); for (int i = 1; i < pointCount - 1; i++) //simplify 2D path { double[] coord = new double[2]; IPoint currentPoint = new PointClass(); oldPointCollection.QueryPoint(bReverse ? (pointCount - i - 1) : i, currentPoint); currentPoint.QueryCoords(out coord[0], out coord[1]); double[] d = new double[2]; d[0] = coord[0] - lastCoord[0]; d[1] = coord[1] - lastCoord[1]; double distance; distance = Math.Sqrt(d[0] * d[0] + d[1] * d[1]); if (distance < (0.25 * simpFactor * length)) { bKeep = false; } else { bKeep = true; } if (bKeep) { newPointCollection.AddPoint(currentPoint, ref Missing, ref Missing); lastCoord[0] = coord[0]; lastCoord[1] = coord[1]; } } IPoint finalPoint = new PointClass(); oldPointCollection.QueryPoint(bReverse ? 0 : (pointCount - 1), finalPoint); newPointCollection.AddPoint(finalPoint, ref Missing, ref Missing); newPath.SpatialReference = sr; return (IGeometry)newPath; } } }
using System; using System.ComponentModel.Composition; using System.Linq; using EnvDTE; using Microsoft.VisualStudio.Shell.Interop; namespace NuGet.VisualStudio { [PartCreationPolicy(CreationPolicy.Shared)] [Export(typeof(IVsPackageManagerFactory))] public class VsPackageManagerFactory : IVsPackageManagerFactory { private readonly IPackageRepositoryFactory _repositoryFactory; private readonly ISolutionManager _solutionManager; private readonly IFileSystemProvider _fileSystemProvider; private readonly IRepositorySettings _repositorySettings; private readonly IVsPackageSourceProvider _packageSourceProvider; private readonly VsPackageInstallerEvents _packageEvents; private readonly IPackageRepository _activePackageSourceRepository; private readonly IVsFrameworkMultiTargeting _frameworkMultiTargeting; private RepositoryInfo _repositoryInfo; private readonly IMachineWideSettings _machineWideSettings; [ImportingConstructor] public VsPackageManagerFactory(ISolutionManager solutionManager, IPackageRepositoryFactory repositoryFactory, IVsPackageSourceProvider packageSourceProvider, IFileSystemProvider fileSystemProvider, IRepositorySettings repositorySettings, VsPackageInstallerEvents packageEvents, IPackageRepository activePackageSourceRepository, IMachineWideSettings machineWideSettings) : this(solutionManager, repositoryFactory, packageSourceProvider, fileSystemProvider, repositorySettings, packageEvents, activePackageSourceRepository, ServiceLocator.GetGlobalService<SVsFrameworkMultiTargeting, IVsFrameworkMultiTargeting>(), machineWideSettings) { } public VsPackageManagerFactory(ISolutionManager solutionManager, IPackageRepositoryFactory repositoryFactory, IVsPackageSourceProvider packageSourceProvider, IFileSystemProvider fileSystemProvider, IRepositorySettings repositorySettings, VsPackageInstallerEvents packageEvents, IPackageRepository activePackageSourceRepository, IVsFrameworkMultiTargeting frameworkMultiTargeting, IMachineWideSettings machineWideSettings) { if (solutionManager == null) { throw new ArgumentNullException("solutionManager"); } if (repositoryFactory == null) { throw new ArgumentNullException("repositoryFactory"); } if (packageSourceProvider == null) { throw new ArgumentNullException("packageSourceProvider"); } if (fileSystemProvider == null) { throw new ArgumentNullException("fileSystemProvider"); } if (repositorySettings == null) { throw new ArgumentNullException("repositorySettings"); } if (packageEvents == null) { throw new ArgumentNullException("packageEvents"); } if (activePackageSourceRepository == null) { throw new ArgumentNullException("activePackageSourceRepository"); } _fileSystemProvider = fileSystemProvider; _repositorySettings = repositorySettings; _solutionManager = solutionManager; _repositoryFactory = repositoryFactory; _packageSourceProvider = packageSourceProvider; _packageEvents = packageEvents; _activePackageSourceRepository = activePackageSourceRepository; _frameworkMultiTargeting = frameworkMultiTargeting; _machineWideSettings = machineWideSettings; _solutionManager.SolutionClosing += (sender, e) => { _repositoryInfo = null; }; } /// <summary> /// Creates an VsPackageManagerInstance that uses the Active Repository (the repository selected in the console drop down) and uses a fallback repository for dependencies. /// </summary> public IVsPackageManager CreatePackageManager() { return CreatePackageManager(_activePackageSourceRepository, useFallbackForDependencies: true); } /// <summary> /// Creates a VsPackageManager that is used to manage install packages. /// The local repository is used as the primary source, and other active sources are /// used as fall back repository. When all needed packages are available in the local /// repository, which is the normal case, this package manager will not need to query /// any remote sources at all. Other active sources are /// used as fall back repository so that it still works even if user has used /// install-package -IgnoreDependencies. /// </summary> /// <returns>The VsPackageManager created.</returns> public IVsPackageManager CreatePackageManagerToManageInstalledPackages() { RepositoryInfo info = GetRepositoryInfo(); var aggregateRepository = _packageSourceProvider.CreateAggregateRepository( _repositoryFactory, ignoreFailingRepositories: true); aggregateRepository.ResolveDependenciesVertically = true; var fallbackRepository = new FallbackRepository(info.Repository, aggregateRepository); return CreatePackageManager(fallbackRepository, useFallbackForDependencies: false); } public IVsPackageManager CreatePackageManager(IPackageRepository repository, bool useFallbackForDependencies) { if (useFallbackForDependencies) { repository = CreateFallbackRepository(repository); } RepositoryInfo info = GetRepositoryInfo(); var packageManager = new VsPackageManager(_solutionManager, repository, _fileSystemProvider, info.FileSystem, info.Repository, // We ensure DeleteOnRestartManager is initialized with a PhysicalFileSystem so the // .deleteme marker files that get created don't get checked into version control new DeleteOnRestartManager(() => new PhysicalFileSystem(info.FileSystem.Root)), _packageEvents, _frameworkMultiTargeting); packageManager.DependencyVersion = GetDependencyVersion(); return packageManager; } public IVsPackageManager CreatePackageManagerWithAllPackageSources() { return CreatePackageManagerWithAllPackageSources(_activePackageSourceRepository); } internal IVsPackageManager CreatePackageManagerWithAllPackageSources(IPackageRepository repository) { if (IsAggregateRepository(repository)) { return CreatePackageManager(repository, false); } var priorityRepository = _packageSourceProvider.CreatePriorityPackageRepository(_repositoryFactory, repository); return CreatePackageManager(priorityRepository, useFallbackForDependencies: false); } /// <summary> /// Creates a FallbackRepository with an aggregate repository that also contains the primaryRepository. /// </summary> internal IPackageRepository CreateFallbackRepository(IPackageRepository primaryRepository) { if (IsAggregateRepository(primaryRepository)) { // If we're using the aggregate repository, we don't need to create a fall back repo. return primaryRepository; } var aggregateRepository = _packageSourceProvider.CreateAggregateRepository(_repositoryFactory, ignoreFailingRepositories: true); aggregateRepository.ResolveDependenciesVertically = true; return new FallbackRepository(primaryRepository, aggregateRepository); } private static bool IsAggregateRepository(IPackageRepository repository) { if (repository is AggregateRepository) { // This test should be ok as long as any aggregate repository that we encounter here means the true Aggregate repository // of all repositories in the package source. // Since the repository created here comes from the UI, this holds true. return true; } var vsPackageSourceRepository = repository as VsPackageSourceRepository; if (vsPackageSourceRepository != null) { return IsAggregateRepository(vsPackageSourceRepository.GetActiveRepository()); } return false; } private RepositoryInfo GetRepositoryInfo() { // Update the path if it needs updating string path = _repositorySettings.RepositoryPath; string configFolderPath = _repositorySettings.ConfigFolderPath; if (_repositoryInfo == null || !_repositoryInfo.Path.Equals(path, StringComparison.OrdinalIgnoreCase) || !_repositoryInfo.ConfigFolderPath.Equals(configFolderPath, StringComparison.OrdinalIgnoreCase) || _solutionManager.IsSourceControlBound != _repositoryInfo.IsSourceControlBound) { IFileSystem fileSystem = _fileSystemProvider.GetFileSystem(path); IFileSystem configSettingsFileSystem = GetConfigSettingsFileSystem(configFolderPath); // this file system is used to access the repositories.config file. We want to use Source Control-bound // file system to access it even if the 'disableSourceControlIntegration' setting is set. IFileSystem storeFileSystem = _fileSystemProvider.GetFileSystem(path, ignoreSourceControlSetting: true); ISharedPackageRepository repository = new SharedPackageRepository( new DefaultPackagePathResolver(fileSystem), fileSystem, storeFileSystem, configSettingsFileSystem); var settings = Settings.LoadDefaultSettings( configSettingsFileSystem, configFileName: null, machineWideSettings: _machineWideSettings); repository.PackageSaveMode = CalculatePackageSaveMode(settings); _repositoryInfo = new RepositoryInfo(path, configFolderPath, fileSystem, repository); } return _repositoryInfo; } /// <summary> /// Returns the user specified DependencyVersion in nuget.config. /// </summary> /// <returns>The user specified DependencyVersion value in nuget.config.</returns> private DependencyVersion GetDependencyVersion() { string configFolderPath = _repositorySettings.ConfigFolderPath; IFileSystem configSettingsFileSystem = GetConfigSettingsFileSystem(configFolderPath); var settings = Settings.LoadDefaultSettings( configSettingsFileSystem, configFileName: null, machineWideSettings: _machineWideSettings); string dependencyVersionValue = settings.GetConfigValue("DependencyVersion"); DependencyVersion dependencyVersion; if (Enum.TryParse(dependencyVersionValue, ignoreCase: true, result:out dependencyVersion)) { return dependencyVersion; } else { return DependencyVersion.Lowest; } } private PackageSaveModes CalculatePackageSaveMode(ISettings settings) { PackageSaveModes retValue = PackageSaveModes.None; if (settings != null) { string packageSaveModeValue = settings.GetConfigValue("PackageSaveMode"); // TODO: remove following block of code when shipping NuGet version post 2.8 if (string.IsNullOrEmpty(packageSaveModeValue)) { packageSaveModeValue = settings.GetConfigValue("SaveOnExpand"); } // end of block of code to remove when shipping NuGet version post 2.8 if (!string.IsNullOrEmpty(packageSaveModeValue)) { foreach (var v in packageSaveModeValue.Split(';')) { if (v.Equals(PackageSaveModes.Nupkg.ToString(), StringComparison.OrdinalIgnoreCase)) { retValue |= PackageSaveModes.Nupkg; } else if (v.Equals(PackageSaveModes.Nuspec.ToString(), StringComparison.OrdinalIgnoreCase)) { retValue |= PackageSaveModes.Nuspec; } } } } if (retValue == PackageSaveModes.None) { retValue = PackageSaveModes.Nupkg; } return retValue; } protected internal virtual IFileSystem GetConfigSettingsFileSystem(string configFolderPath) { return new SolutionFolderFileSystem(ServiceLocator.GetInstance<DTE>().Solution, VsConstants.NuGetSolutionSettingsFolder, configFolderPath); } private class RepositoryInfo { public RepositoryInfo(string path, string configFolderPath, IFileSystem fileSystem, ISharedPackageRepository repository) { Path = path; FileSystem = fileSystem; Repository = repository; ConfigFolderPath = configFolderPath; } public bool IsSourceControlBound { get { return FileSystem is ISourceControlFileSystem; } } public IFileSystem FileSystem { get; private set; } public string Path { get; private set; } public string ConfigFolderPath { get; private set; } public ISharedPackageRepository Repository { get; private set; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.BackupServices; using Microsoft.Azure.Management.BackupServices.Models; namespace Microsoft.Azure.Management.BackupServices { public static partial class VaultOperationsExtensions { /// <summary> /// Creates a new Azure backup vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of resource group to which vault belongs /// </param> /// <param name='vaultName'> /// Required. The name of the vault /// </param> /// <param name='parameters'> /// Required. Parameters to create or update the vault /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// Vault information. /// </returns> public static AzureBackupVaultGetResponse CreateOrUpdate(this IVaultOperations operations, string resourceGroupName, string vaultName, AzureBackupVaultCreateOrUpdateParameters parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultOperations)s).CreateOrUpdateAsync(resourceGroupName, vaultName, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure backup vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of resource group to which vault belongs /// </param> /// <param name='vaultName'> /// Required. The name of the vault /// </param> /// <param name='parameters'> /// Required. Parameters to create or update the vault /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// Vault information. /// </returns> public static Task<AzureBackupVaultGetResponse> CreateOrUpdateAsync(this IVaultOperations operations, string resourceGroupName, string vaultName, AzureBackupVaultCreateOrUpdateParameters parameters, CustomRequestHeaders customRequestHeaders) { return operations.CreateOrUpdateAsync(resourceGroupName, vaultName, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Deletes the specified Azure backup vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of resource group to which vault belongs /// </param> /// <param name='vaultName'> /// Required. The name of the vault /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// Vault information. /// </returns> public static AzureBackupVaultGetResponse Delete(this IVaultOperations operations, string resourceGroupName, string vaultName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultOperations)s).DeleteAsync(resourceGroupName, vaultName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified Azure backup vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of resource group to which vault belongs /// </param> /// <param name='vaultName'> /// Required. The name of the vault /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// Vault information. /// </returns> public static Task<AzureBackupVaultGetResponse> DeleteAsync(this IVaultOperations operations, string resourceGroupName, string vaultName, CustomRequestHeaders customRequestHeaders) { return operations.DeleteAsync(resourceGroupName, vaultName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Gets the specified Azure key vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of resource group to which vault belongs /// </param> /// <param name='vaultName'> /// Required. The name of the vault /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// Vault information. /// </returns> public static AzureBackupVaultGetResponse Get(this IVaultOperations operations, string resourceGroupName, string vaultName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultOperations)s).GetAsync(resourceGroupName, vaultName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the specified Azure key vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of resource group to which vault belongs /// </param> /// <param name='vaultName'> /// Required. The name of the vault /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// Vault information. /// </returns> public static Task<AzureBackupVaultGetResponse> GetAsync(this IVaultOperations operations, string resourceGroupName, string vaultName, CustomRequestHeaders customRequestHeaders) { return operations.GetAsync(resourceGroupName, vaultName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Fetches resource storage config. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of resource group to which vault belongs /// </param> /// <param name='vaultName'> /// Required. The name of the vault /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a get resource storage config response. /// </returns> public static GetResourceStorageConfigResponse GetResourceStorageConfig(this IVaultOperations operations, string resourceGroupName, string vaultName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultOperations)s).GetResourceStorageConfigAsync(resourceGroupName, vaultName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Fetches resource storage config. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of resource group to which vault belongs /// </param> /// <param name='vaultName'> /// Required. The name of the vault /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a get resource storage config response. /// </returns> public static Task<GetResourceStorageConfigResponse> GetResourceStorageConfigAsync(this IVaultOperations operations, string resourceGroupName, string vaultName, CustomRequestHeaders customRequestHeaders) { return operations.GetResourceStorageConfigAsync(resourceGroupName, vaultName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Gets information of the backup vaults associated with subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='top'> /// Required. Maximum number of results to return. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// List of vaults /// </returns> public static AzureBackupVaultListResponse List(this IVaultOperations operations, int top, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultOperations)s).ListAsync(top, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets information of the backup vaults associated with subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='top'> /// Required. Maximum number of results to return. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// List of vaults /// </returns> public static Task<AzureBackupVaultListResponse> ListAsync(this IVaultOperations operations, int top, CustomRequestHeaders customRequestHeaders) { return operations.ListAsync(top, customRequestHeaders, CancellationToken.None); } /// <summary> /// Gets information of the backup vaults associated with resource /// group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. An optional argument which specifies the name of the /// resource group that constrains the set of vaults that are returned. /// </param> /// <param name='top'> /// Required. Maximum number of results to return. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// List of vaults /// </returns> public static AzureBackupVaultListResponse ListByResourceGroup(this IVaultOperations operations, string resourceGroupName, int top, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultOperations)s).ListByResourceGroupAsync(resourceGroupName, top, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets information of the backup vaults associated with resource /// group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. An optional argument which specifies the name of the /// resource group that constrains the set of vaults that are returned. /// </param> /// <param name='top'> /// Required. Maximum number of results to return. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// List of vaults /// </returns> public static Task<AzureBackupVaultListResponse> ListByResourceGroupAsync(this IVaultOperations operations, string resourceGroupName, int top, CustomRequestHeaders customRequestHeaders) { return operations.ListByResourceGroupAsync(resourceGroupName, top, customRequestHeaders, CancellationToken.None); } /// <summary> /// Updates vault storage model type. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='updateVaultStorageTypeRequest'> /// Required. Update Vault Storage Type Request /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a Operation Response. /// </returns> public static OperationResponse UpdateStorageType(this IVaultOperations operations, UpdateVaultStorageTypeRequest updateVaultStorageTypeRequest, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultOperations)s).UpdateStorageTypeAsync(updateVaultStorageTypeRequest, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates vault storage model type. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='updateVaultStorageTypeRequest'> /// Required. Update Vault Storage Type Request /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a Operation Response. /// </returns> public static Task<OperationResponse> UpdateStorageTypeAsync(this IVaultOperations operations, UpdateVaultStorageTypeRequest updateVaultStorageTypeRequest, CustomRequestHeaders customRequestHeaders) { return operations.UpdateStorageTypeAsync(updateVaultStorageTypeRequest, customRequestHeaders, CancellationToken.None); } /// <summary> /// Uploads vault credential certificate. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='certificateName'> /// Required. Name of the certificate. /// </param> /// <param name='vaultCredUploadCertRequest'> /// Required. Certificate parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a certificate response. /// </returns> public static VaultCredUploadCertResponse UploadCertificate(this IVaultOperations operations, string certificateName, VaultCredUploadCertRequest vaultCredUploadCertRequest, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultOperations)s).UploadCertificateAsync(certificateName, vaultCredUploadCertRequest, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Uploads vault credential certificate. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IVaultOperations. /// </param> /// <param name='certificateName'> /// Required. Name of the certificate. /// </param> /// <param name='vaultCredUploadCertRequest'> /// Required. Certificate parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a certificate response. /// </returns> public static Task<VaultCredUploadCertResponse> UploadCertificateAsync(this IVaultOperations operations, string certificateName, VaultCredUploadCertRequest vaultCredUploadCertRequest, CustomRequestHeaders customRequestHeaders) { return operations.UploadCertificateAsync(certificateName, vaultCredUploadCertRequest, customRequestHeaders, CancellationToken.None); } } }
#region License /* * AuthenticationResponse.cs * * ParseBasicCredentials is derived from System.Net.HttpListenerContext.cs of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2013-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Collections.Specialized; using System.Security.Cryptography; using System.Security.Principal; using System.Text; namespace CustomWebSocketSharp.Net { internal class AuthenticationResponse : AuthenticationBase { #region Private Fields private uint _nonceCount; #endregion #region Private Constructors private AuthenticationResponse (AuthenticationSchemes scheme, NameValueCollection parameters) : base (scheme, parameters) { } #endregion #region Internal Constructors internal AuthenticationResponse (NetworkCredential credentials) : this (AuthenticationSchemes.Basic, new NameValueCollection (), credentials, 0) { } internal AuthenticationResponse ( AuthenticationChallenge challenge, NetworkCredential credentials, uint nonceCount) : this (challenge.Scheme, challenge.Parameters, credentials, nonceCount) { } internal AuthenticationResponse ( AuthenticationSchemes scheme, NameValueCollection parameters, NetworkCredential credentials, uint nonceCount) : base (scheme, parameters) { Parameters["username"] = credentials.UserName; Parameters["password"] = credentials.Password; Parameters["uri"] = credentials.Domain; _nonceCount = nonceCount; if (scheme == AuthenticationSchemes.Digest) initAsDigest (); } #endregion #region Internal Properties internal uint NonceCount { get { return _nonceCount < UInt32.MaxValue ? _nonceCount : 0; } } #endregion #region Public Properties public string Cnonce { get { return Parameters["cnonce"]; } } public string Nc { get { return Parameters["nc"]; } } public string Password { get { return Parameters["password"]; } } public string Response { get { return Parameters["response"]; } } public string Uri { get { return Parameters["uri"]; } } public string UserName { get { return Parameters["username"]; } } #endregion #region Private Methods private static string createA1 (string username, string password, string realm) { return String.Format ("{0}:{1}:{2}", username, realm, password); } private static string createA1 ( string username, string password, string realm, string nonce, string cnonce) { return String.Format ( "{0}:{1}:{2}", hash (createA1 (username, password, realm)), nonce, cnonce); } private static string createA2 (string method, string uri) { return String.Format ("{0}:{1}", method, uri); } private static string createA2 (string method, string uri, string entity) { return String.Format ("{0}:{1}:{2}", method, uri, hash (entity)); } private static string hash (string value) { var src = Encoding.UTF8.GetBytes (value); var md5 = MD5.Create (); var hashed = md5.ComputeHash (src); var res = new StringBuilder (64); foreach (var b in hashed) res.Append (b.ToString ("x2")); return res.ToString (); } private void initAsDigest () { var qops = Parameters["qop"]; if (qops != null) { if (qops.Split (',').Contains (qop => qop.Trim ().ToLower () == "auth")) { Parameters["qop"] = "auth"; Parameters["cnonce"] = CreateNonceValue (); Parameters["nc"] = String.Format ("{0:x8}", ++_nonceCount); } else { Parameters["qop"] = null; } } Parameters["method"] = "GET"; Parameters["response"] = CreateRequestDigest (Parameters); } #endregion #region Internal Methods internal static string CreateRequestDigest (NameValueCollection parameters) { var user = parameters["username"]; var pass = parameters["password"]; var realm = parameters["realm"]; var nonce = parameters["nonce"]; var uri = parameters["uri"]; var algo = parameters["algorithm"]; var qop = parameters["qop"]; var cnonce = parameters["cnonce"]; var nc = parameters["nc"]; var method = parameters["method"]; var a1 = algo != null && algo.ToLower () == "md5-sess" ? createA1 (user, pass, realm, nonce, cnonce) : createA1 (user, pass, realm); var a2 = qop != null && qop.ToLower () == "auth-int" ? createA2 (method, uri, parameters["entity"]) : createA2 (method, uri); var secret = hash (a1); var data = qop != null ? String.Format ("{0}:{1}:{2}:{3}:{4}", nonce, nc, cnonce, qop, hash (a2)) : String.Format ("{0}:{1}", nonce, hash (a2)); return hash (String.Format ("{0}:{1}", secret, data)); } internal static AuthenticationResponse Parse (string value) { try { var cred = value.Split (new[] { ' ' }, 2); if (cred.Length != 2) return null; var schm = cred[0].ToLower (); return schm == "basic" ? new AuthenticationResponse ( AuthenticationSchemes.Basic, ParseBasicCredentials (cred[1])) : schm == "digest" ? new AuthenticationResponse ( AuthenticationSchemes.Digest, ParseParameters (cred[1])) : null; } catch { } return null; } internal static NameValueCollection ParseBasicCredentials (string value) { // Decode the basic-credentials (a Base64 encoded string). var userPass = Encoding.Default.GetString (Convert.FromBase64String (value)); // The format is [<domain>\]<username>:<password>. var i = userPass.IndexOf (':'); var user = userPass.Substring (0, i); var pass = i < userPass.Length - 1 ? userPass.Substring (i + 1) : String.Empty; // Check if 'domain' exists. i = user.IndexOf ('\\'); if (i > -1) user = user.Substring (i + 1); var res = new NameValueCollection (); res["username"] = user; res["password"] = pass; return res; } internal override string ToBasicString () { var userPass = String.Format ("{0}:{1}", Parameters["username"], Parameters["password"]); var cred = Convert.ToBase64String (Encoding.UTF8.GetBytes (userPass)); return "Basic " + cred; } internal override string ToDigestString () { var output = new StringBuilder (256); output.AppendFormat ( "Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", response=\"{4}\"", Parameters["username"], Parameters["realm"], Parameters["nonce"], Parameters["uri"], Parameters["response"]); var opaque = Parameters["opaque"]; if (opaque != null) output.AppendFormat (", opaque=\"{0}\"", opaque); var algo = Parameters["algorithm"]; if (algo != null) output.AppendFormat (", algorithm={0}", algo); var qop = Parameters["qop"]; if (qop != null) output.AppendFormat ( ", qop={0}, cnonce=\"{1}\", nc={2}", qop, Parameters["cnonce"], Parameters["nc"]); return output.ToString (); } #endregion #region Public Methods public IIdentity ToIdentity () { var schm = Scheme; return schm == AuthenticationSchemes.Basic ? new HttpBasicIdentity (Parameters["username"], Parameters["password"]) as IIdentity : schm == AuthenticationSchemes.Digest ? new HttpDigestIdentity (Parameters) : null; } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using Directory = Lucene.Net.Store.Directory; using IndexInput = Lucene.Net.Store.IndexInput; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using PhraseQuery = Lucene.Net.Search.PhraseQuery; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using Searcher = Lucene.Net.Search.Searcher; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Index { /// <summary> Tests lazy skipping on the proximity file. /// /// </summary> [TestFixture] public class TestLazyProxSkipping:LuceneTestCase { private Searcher searcher; private int seeksCounter = 0; private System.String field = "tokens"; private System.String term1 = "xx"; private System.String term2 = "yy"; private System.String term3 = "zz"; [Serializable] private class SeekCountingDirectory:RAMDirectory { public SeekCountingDirectory(TestLazyProxSkipping enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestLazyProxSkipping enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestLazyProxSkipping enclosingInstance; public TestLazyProxSkipping Enclosing_Instance { get { return enclosingInstance; } } public override IndexInput OpenInput(System.String name) { IndexInput ii = base.OpenInput(name); if (name.EndsWith(".prx")) { // we decorate the proxStream with a wrapper class that allows to count the number of calls of seek() ii = new SeeksCountingStream(enclosingInstance, ii); } return ii; } } private void CreateIndex(int numHits) { int numDocs = 500; Directory directory = new SeekCountingDirectory(this); IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); writer.UseCompoundFile = false; writer.SetMaxBufferedDocs(10); for (int i = 0; i < numDocs; i++) { Document doc = new Document(); System.String content; if (i % (numDocs / numHits) == 0) { // add a document that matches the query "term1 term2" content = this.term1 + " " + this.term2; } else if (i % 15 == 0) { // add a document that only contains term1 content = this.term1 + " " + this.term1; } else { // add a document that contains term2 but not term 1 content = this.term3 + " " + this.term2; } doc.Add(new Field(this.field, content, Field.Store.YES, Field.Index.ANALYZED)); writer.AddDocument(doc); } // make sure the index has only a single segment writer.Optimize(); writer.Close(); SegmentReader reader = SegmentReader.GetOnlySegmentReader(directory); this.searcher = new IndexSearcher(reader); } private ScoreDoc[] Search() { // create PhraseQuery "term1 term2" and search PhraseQuery pq = new PhraseQuery(); pq.Add(new Term(this.field, this.term1)); pq.Add(new Term(this.field, this.term2)); return this.searcher.Search(pq, null, 1000).ScoreDocs; } private void PerformTest(int numHits) { CreateIndex(numHits); this.seeksCounter = 0; ScoreDoc[] hits = Search(); // verify that the right number of docs was found Assert.AreEqual(numHits, hits.Length); // check if the number of calls of seek() does not exceed the number of hits Assert.IsTrue(this.seeksCounter > 0); Assert.IsTrue(this.seeksCounter <= numHits + 1); } [Test] public virtual void TestLazySkipping() { // test whether only the minimum amount of seeks() are performed PerformTest(5); PerformTest(10); } [Test] public virtual void TestSeek() { Directory directory = new RAMDirectory(); IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); for (int i = 0; i < 10; i++) { Document doc = new Document(); doc.Add(new Field(this.field, "a b", Field.Store.YES, Field.Index.ANALYZED)); writer.AddDocument(doc); } writer.Close(); IndexReader reader = IndexReader.Open(directory, true); TermPositions tp = reader.TermPositions(); tp.Seek(new Term(this.field, "b")); for (int i = 0; i < 10; i++) { tp.Next(); Assert.AreEqual(tp.Doc, i); Assert.AreEqual(tp.NextPosition(), 1); } tp.Seek(new Term(this.field, "a")); for (int i = 0; i < 10; i++) { tp.Next(); Assert.AreEqual(tp.Doc, i); Assert.AreEqual(tp.NextPosition(), 0); } } // Simply extends IndexInput in a way that we are able to count the number // of invocations of seek() internal class SeeksCountingStream:IndexInput, System.ICloneable { private void InitBlock(TestLazyProxSkipping enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestLazyProxSkipping enclosingInstance; public TestLazyProxSkipping Enclosing_Instance { get { return enclosingInstance; } } private IndexInput input; private bool isDisposed; internal SeeksCountingStream(TestLazyProxSkipping enclosingInstance, IndexInput input) { InitBlock(enclosingInstance); this.input = input; } public override byte ReadByte() { return this.input.ReadByte(); } public override void ReadBytes(byte[] b, int offset, int len) { this.input.ReadBytes(b, offset, len); } protected override void Dispose(bool disposing) { if (isDisposed) return; if (disposing) { this.input.Close(); } isDisposed = true; } public override long FilePointer { get { return this.input.FilePointer; } } public override void Seek(long pos) { Enclosing_Instance.seeksCounter++; this.input.Seek(pos); } public override long Length() { return this.input.Length(); } public override System.Object Clone() { return new SeeksCountingStream(enclosingInstance, (IndexInput) this.input.Clone()); } } } }
using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Runtime.Serialization; namespace Alchemy4Tridion.Plugins.Clients.CoreService { [GeneratedCode("System.Runtime.Serialization", "4.0.0.0"), DebuggerStepThrough, DataContract(Name = "RepositoryData", Namespace = "http://www.sdltridion.com/ContentManager/R6"), KnownType(typeof(PublicationData)), KnownType(typeof(BluePrintNodeData))] public class RepositoryData : SystemWideObjectData { private AccessControlListData AccessControlListField; private string CategoriesXsdField; private LinkToSchemaData DefaultMultimediaSchemaField; private bool? HasChildrenField; private string KeyField; private LocationInfo LocationInfoField; private string MetadataField; private LinkToSchemaData MetadataSchemaField; private LinkToRepositoryData[] ParentsField; private LinkToFolderData RootFolderField; private LinkToProcessDefinitionData TaskProcessField; private LinkToBusinessProcessTypeData BusinessProcessTypeField; private LinkToApprovalStatusData MinimalLocalizeApprovalStatusField; [DataMember(EmitDefaultValue = false)] public AccessControlListData AccessControlList { get { return this.AccessControlListField; } set { this.AccessControlListField = value; } } [DataMember(EmitDefaultValue = false)] public string CategoriesXsd { get { return this.CategoriesXsdField; } set { this.CategoriesXsdField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToSchemaData DefaultMultimediaSchema { get { return this.DefaultMultimediaSchemaField; } set { this.DefaultMultimediaSchemaField = value; } } [DataMember(EmitDefaultValue = false)] public bool? HasChildren { get { return this.HasChildrenField; } set { this.HasChildrenField = value; } } [DataMember(EmitDefaultValue = false)] public string Key { get { return this.KeyField; } set { this.KeyField = value; } } [DataMember(EmitDefaultValue = false)] public LocationInfo LocationInfo { get { return this.LocationInfoField; } set { this.LocationInfoField = value; } } [DataMember(EmitDefaultValue = false)] public string Metadata { get { return this.MetadataField; } set { this.MetadataField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToSchemaData MetadataSchema { get { return this.MetadataSchemaField; } set { this.MetadataSchemaField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToRepositoryData[] Parents { get { return this.ParentsField; } set { this.ParentsField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToFolderData RootFolder { get { return this.RootFolderField; } set { this.RootFolderField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToProcessDefinitionData TaskProcess { get { return this.TaskProcessField; } set { this.TaskProcessField = value; } } [DataMember(EmitDefaultValue = false, Order = 11)] public LinkToBusinessProcessTypeData BusinessProcessType { get { return this.BusinessProcessTypeField; } set { this.BusinessProcessTypeField = value; } } [DataMember(EmitDefaultValue = false, Order = 12)] public LinkToApprovalStatusData MinimalLocalizeApprovalStatus { get { return this.MinimalLocalizeApprovalStatusField; } set { this.MinimalLocalizeApprovalStatusField = 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 Microsoft.Win32.SafeHandles; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Security.Authentication; namespace System.Net.Security { // SecureChannel - a wrapper on SSPI based functionality. // Provides an additional abstraction layer over SSPI for SslStream. internal class SecureChannel { // When reading a frame from the wire first read this many bytes for the header. internal const int ReadHeaderSize = 5; private SafeFreeCredentials _credentialsHandle; private SafeDeleteContext _securityContext; private readonly string _destination; private readonly string _hostName; private readonly bool _serverMode; private readonly bool _remoteCertRequired; private readonly SslProtocols _sslProtocols; private readonly EncryptionPolicy _encryptionPolicy; private SslConnectionInfo _connectionInfo; private X509Certificate _serverCertificate; private X509Certificate _selectedClientCertificate; private bool _isRemoteCertificateAvailable; private readonly X509CertificateCollection _clientCertificates; private LocalCertSelectionCallback _certSelectionDelegate; // These are the MAX encrypt buffer output sizes, not the actual sizes. private int _headerSize = 5; //ATTN must be set to at least 5 by default private int _trailerSize = 16; private int _maxDataSize = 16354; private bool _checkCertRevocation; private bool _checkCertName; private bool _refreshCredentialNeeded; internal SecureChannel(string hostname, bool serverMode, SslProtocols sslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate) { if (GlobalLog.IsEnabled) { GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::.ctor", "hostname:" + hostname + " #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo))); } if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.SecureChannelCtor(this, hostname, clientCertificates, encryptionPolicy); } SslStreamPal.VerifyPackageInfo(); _destination = hostname; if (hostname == null) { if (GlobalLog.IsEnabled) { GlobalLog.AssertFormat("SecureChannel#{0}::.ctor()|hostname == null", LoggingHash.HashString(this)); } Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::.ctor()|hostname == null"); } _hostName = hostname; _serverMode = serverMode; _sslProtocols = sslProtocols; _serverCertificate = serverCertificate; _clientCertificates = clientCertificates; _remoteCertRequired = remoteCertRequired; _securityContext = null; _checkCertRevocation = checkCertRevocationStatus; _checkCertName = checkCertName; _certSelectionDelegate = certSelectionDelegate; _refreshCredentialNeeded = true; _encryptionPolicy = encryptionPolicy; if (GlobalLog.IsEnabled) { GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::.ctor"); } } // // SecureChannel properties // // LocalServerCertificate - local certificate for server mode channel // LocalClientCertificate - selected certificated used in the client channel mode otherwise null // IsRemoteCertificateAvailable - true if the remote side has provided a certificate // HeaderSize - Header & trailer sizes used in the TLS stream // TrailerSize - // internal X509Certificate LocalServerCertificate { get { return _serverCertificate; } } internal X509Certificate LocalClientCertificate { get { return _selectedClientCertificate; } } internal bool IsRemoteCertificateAvailable { get { return _isRemoteCertificateAvailable; } } internal ChannelBinding GetChannelBinding(ChannelBindingKind kind) { if (GlobalLog.IsEnabled) { GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::GetChannelBindingToken", kind.ToString()); } ChannelBinding result = null; if (_securityContext != null) { result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind); } if (GlobalLog.IsEnabled) { GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::GetChannelBindingToken", LoggingHash.HashString(result)); } return result; } internal bool CheckCertRevocationStatus { get { return _checkCertRevocation; } } internal X509CertificateCollection ClientCertificates { get { return _clientCertificates; } } internal int HeaderSize { get { return _headerSize; } } internal int MaxDataSize { get { return _maxDataSize; } } internal SslConnectionInfo ConnectionInfo { get { return _connectionInfo; } } internal bool IsValidContext { get { return !(_securityContext == null || _securityContext.IsInvalid); } } internal bool IsServer { get { return _serverMode; } } internal bool RemoteCertRequired { get { return _remoteCertRequired; } } internal void SetRefreshCredentialNeeded() { _refreshCredentialNeeded = true; } internal void Close() { if (_securityContext != null) { _securityContext.Dispose(); } if (_credentialsHandle != null) { _credentialsHandle.Dispose(); } } // // SECURITY: we open a private key container on behalf of the caller // and we require the caller to have permission associated with that operation. // private X509Certificate2 EnsurePrivateKey(X509Certificate certificate) { if (certificate == null) { return null; } if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.LocatingPrivateKey(certificate.ToString(true), LoggingHash.HashInt(this)); } try { string certHash = null; // Protecting from X509Certificate2 derived classes. X509Certificate2 certEx = MakeEx(certificate); certHash = certEx.Thumbprint; if (certEx != null) { if (certEx.HasPrivateKey) { if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.CertIsType2(LoggingHash.HashInt(this)); } return certEx; } if ((object)certificate != (object)certEx) { certEx.Dispose(); } } X509Certificate2Collection collectionEx; // ELSE Try the MY user and machine stores for private key check. // For server side mode MY machine store takes priority. X509Store store = CertificateValidationPal.EnsureStoreOpened(_serverMode); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.FoundCertInStore((_serverMode ? "LocalMachine" : "CurrentUser"), LoggingHash.HashInt(this)); } return collectionEx[0]; } } store = CertificateValidationPal.EnsureStoreOpened(!_serverMode); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.FoundCertInStore((_serverMode ? "LocalMachine" : "CurrentUser"), LoggingHash.HashInt(this)); } return collectionEx[0]; } } } catch (CryptographicException) { } if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.NotFoundCertInStore(LoggingHash.HashInt(this)); } return null; } private static X509Certificate2 MakeEx(X509Certificate certificate) { Debug.Assert(certificate != null, "certificate != null"); if (certificate.GetType() == typeof(X509Certificate2)) { return (X509Certificate2)certificate; } X509Certificate2 certificateEx = null; try { if (certificate.Handle != IntPtr.Zero) { certificateEx = new X509Certificate2(certificate.Handle); } } catch (SecurityException) { } catch (CryptographicException) { } return certificateEx; } // // Get certificate_authorities list, according to RFC 5246, Section 7.4.4. // Used only by client SSL code, never returns null. // private string[] GetRequestCertificateAuthorities() { string[] issuers = Array.Empty<string>(); if (IsValidContext) { issuers = CertificateValidationPal.GetRequestCertificateAuthorities(_securityContext); } return issuers; } /*++ AcquireCredentials - Attempts to find Client Credential Information, that can be sent to the server. In our case, this is only Client Certificates, that we have Credential Info. How it works: case 0: Cert Selection delegate is present Always use its result as the client cert answer. Try to use cached credential handle whenever feasible. Do not use cached anonymous creds if the delegate has returned null and the collection is not empty (allow responding with the cert later). case 1: Certs collection is empty Always use the same statically acquired anonymous SSL Credential case 2: Before our Connection with the Server If we have a cached credential handle keyed by first X509Certificate **content** in the passed collection, then we use that cached credential and hoping to restart a session. Otherwise create a new anonymous (allow responding with the cert later). case 3: After our Connection with the Server (i.e. during handshake or re-handshake) The server has requested that we send it a Certificate then we Enumerate a list of server sent Issuers trying to match against our list of Certificates, the first match is sent to the server. Once we got a cert we again try to match cached credential handle if possible. This will not restart a session but helps minimizing the number of handles we create. In the case of an error getting a Certificate or checking its private Key we fall back to the behavior of having no certs, case 1. Returns: True if cached creds were used, false otherwise. --*/ private bool AcquireClientCredentials(ref byte[] thumbPrint) { if (GlobalLog.IsEnabled) { GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials"); } // Acquire possible Client Certificate information and set it on the handle. X509Certificate clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart. ArrayList filteredCerts = new ArrayList(); // This is an intermediate client certs collection that try to use if no selectedCert is available yet. string[] issuers = null; // This is a list of issuers sent by the server, only valid is we do know what the server cert is. bool sessionRestartAttempt = false; // If true and no cached creds we will use anonymous creds. if (_certSelectionDelegate != null) { issuers = GetRequestCertificateAuthorities(); if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() calling CertificateSelectionCallback"); } X509Certificate2 remoteCert = null; try { X509Certificate2Collection dummyCollection; remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext, out dummyCollection); clientCertificate = _certSelectionDelegate(_hostName, ClientCertificates, remoteCert, issuers); } finally { if (remoteCert != null) { remoteCert.Dispose(); } } if (clientCertificate != null) { if (_credentialsHandle == null) { sessionRestartAttempt = true; } filteredCerts.Add(clientCertificate); if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.CertificateFromDelegate(LoggingHash.HashInt(this)); } } else { if (ClientCertificates.Count == 0) { if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.NoDelegateNoClientCert(LoggingHash.HashInt(this)); } sessionRestartAttempt = true; } else { if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.NoDelegateButClientCert(LoggingHash.HashInt(this)); } } } } else if (_credentialsHandle == null && _clientCertificates != null && _clientCertificates.Count > 0) { // This is where we attempt to restart a session by picking the FIRST cert from the collection. // Otherwise it is either server sending a client cert request or the session is renegotiated. clientCertificate = ClientCertificates[0]; sessionRestartAttempt = true; if (clientCertificate != null) { filteredCerts.Add(clientCertificate); } if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.AttemptingRestartUsingCert(clientCertificate == null ? "null" : clientCertificate.ToString(true), LoggingHash.HashInt(this)); } } else if (_clientCertificates != null && _clientCertificates.Count > 0) { // // This should be a server request for the client cert sent over currently anonymous sessions. // issuers = GetRequestCertificateAuthorities(); if (SecurityEventSource.Log.IsEnabled()) { if (issuers == null || issuers.Length == 0) { SecurityEventSource.Log.NoIssuersTryAllCerts(LoggingHash.HashInt(this)); } else { SecurityEventSource.Log.LookForMatchingCerts(issuers.Length, LoggingHash.HashInt(this)); } } for (int i = 0; i < _clientCertificates.Count; ++i) { // // Make sure we add only if the cert matches one of the issuers. // If no issuers were sent and then try all client certs starting with the first one. // if (issuers != null && issuers.Length != 0) { X509Certificate2 certificateEx = null; X509Chain chain = null; try { certificateEx = MakeEx(_clientCertificates[i]); if (certificateEx == null) { continue; } if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() root cert:" + certificateEx.Issuer); } chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName; chain.Build(certificateEx); bool found = false; // // We ignore any errors happened with chain. // if (chain.ChainElements.Count > 0) { for (int ii = 0; ii < chain.ChainElements.Count; ++ii) { string issuer = chain.ChainElements[ii].Certificate.Issuer; found = Array.IndexOf(issuers, issuer) != -1; if (found) { if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() matched:" + issuer); } break; } if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() no match:" + issuer); } } } if (!found) { continue; } } finally { if (chain != null) { chain.Dispose(); } if (certificateEx != null && (object)certificateEx != (object)_clientCertificates[i]) { certificateEx.Dispose(); } } } if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.SelectedCert(_clientCertificates[i].ToString(true), LoggingHash.HashInt(this)); } filteredCerts.Add(_clientCertificates[i]); } } bool cachedCred = false; // This is a return result from this method. X509Certificate2 selectedCert = null; // This is a final selected cert (ensured that it does have private key with it). clientCertificate = null; if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.CertsAfterFiltering(filteredCerts.Count, LoggingHash.HashInt(this)); if (filteredCerts.Count != 0) { SecurityEventSource.Log.FindingMatchingCerts(LoggingHash.HashInt(this)); } } // // ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key, // THEN anonymous (no client cert) credential will be used. // // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // EnsurePrivateKey should do the right demand for us. for (int i = 0; i < filteredCerts.Count; ++i) { clientCertificate = filteredCerts[i] as X509Certificate; if ((selectedCert = EnsurePrivateKey(clientCertificate)) != null) { break; } clientCertificate = null; selectedCert = null; } if ((object)clientCertificate != (object)selectedCert && !clientCertificate.Equals(selectedCert)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("AcquireClientCredentials()|'selectedCert' does not match 'clientCertificate'."); } Debug.Fail("AcquireClientCredentials()|'selectedCert' does not match 'clientCertificate'."); } if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() Selected Cert = " + (selectedCert == null ? "null" : selectedCert.Subject)); } try { // Try to locate cached creds first. // // SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type. // byte[] guessedThumbPrint = selectedCert == null ? null : selectedCert.GetCertHash(); SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy); // We can probably do some optimization here. If the selectedCert is returned by the delegate // we can always go ahead and use the certificate to create our credential // (instead of going anonymous as we do here). if (sessionRestartAttempt && cachedCredentialHandle == null && selectedCert != null && SslStreamPal.StartMutualAuthAsAnonymous) { if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() Reset to anonymous session."); } // IIS does not renegotiate a restarted session if client cert is needed. // So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate. // The following block happens if client did specify a certificate but no cached creds were found in the cache. // Since we don't restart a session the server side can still challenge for a client cert. if ((object)clientCertificate != (object)selectedCert) { selectedCert.Dispose(); } guessedThumbPrint = null; selectedCert = null; clientCertificate = null; } if (cachedCredentialHandle != null) { if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.UsingCachedCredential(LoggingHash.HashInt(this)); } _credentialsHandle = cachedCredentialHandle; _selectedClientCertificate = clientCertificate; cachedCred = true; } else { _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslProtocols, _encryptionPolicy, _serverMode); thumbPrint = guessedThumbPrint; // Delay until here in case something above threw. _selectedClientCertificate = clientCertificate; } } finally { // An extra cert could have been created, dispose it now. if (selectedCert != null && (object)clientCertificate != (object)selectedCert) { selectedCert.Dispose(); } } if (GlobalLog.IsEnabled) { GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials, cachedCreds = " + cachedCred.ToString(), LoggingHash.ObjectToString(_credentialsHandle)); } return cachedCred; } // // Acquire Server Side Certificate information and set it on the class. // private bool AcquireServerCredentials(ref byte[] thumbPrint) { if (GlobalLog.IsEnabled) { GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireServerCredentials"); } X509Certificate localCertificate = null; bool cachedCred = false; if (_certSelectionDelegate != null) { X509CertificateCollection tempCollection = new X509CertificateCollection(); tempCollection.Add(_serverCertificate); localCertificate = _certSelectionDelegate(string.Empty, tempCollection, null, Array.Empty<string>()); if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireServerCredentials() Use delegate selected Cert"); } } else { localCertificate = _serverCertificate; } if (localCertificate == null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // EnsurePrivateKey should do the right demand for us. X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate); if (selectedCert == null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } if (!localCertificate.Equals(selectedCert)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("AcquireServerCredentials()|'selectedCert' does not match 'localCertificate'."); } Debug.Fail("AcquireServerCredentials()|'selectedCert' does not match 'localCertificate'."); } // // Note selectedCert is a safe ref possibly cloned from the user passed Cert object // byte[] guessedThumbPrint = selectedCert.GetCertHash(); try { SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy); if (cachedCredentialHandle != null) { _credentialsHandle = cachedCredentialHandle; _serverCertificate = localCertificate; cachedCred = true; } else { _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslProtocols, _encryptionPolicy, _serverMode); thumbPrint = guessedThumbPrint; _serverCertificate = localCertificate; } } finally { // An extra cert could have been created, dispose it now. if ((object)localCertificate != (object)selectedCert) { selectedCert.Dispose(); } } if (GlobalLog.IsEnabled) { GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireServerCredentials, cachedCreds = " + cachedCred.ToString(), LoggingHash.ObjectToString(_credentialsHandle)); } return cachedCred; } // internal ProtocolToken NextMessage(byte[] incoming, int offset, int count) { if (GlobalLog.IsEnabled) { GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::NextMessage"); } byte[] nextmsg = null; SecurityStatusPal errorCode = GenerateToken(incoming, offset, count, ref nextmsg); if (!_serverMode && errorCode == SecurityStatusPal.CredentialsNeeded) { if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::NextMessage() returned SecurityStatusPal.CredentialsNeeded"); } SetRefreshCredentialNeeded(); errorCode = GenerateToken(incoming, offset, count, ref nextmsg); } ProtocolToken token = new ProtocolToken(nextmsg, errorCode); if (GlobalLog.IsEnabled) { GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::NextMessage", token.ToString()); } return token; } /*++ GenerateToken - Called after each successive state in the Client - Server handshake. This function generates a set of bytes that will be sent next to the server. The server responds, each response, is pass then into this function, again, and the cycle repeats until successful connection, or failure. Input: input - bytes from the wire output - ref to byte [], what we will send to the server in response Return: errorCode - an SSPI error code --*/ private SecurityStatusPal GenerateToken(byte[] input, int offset, int count, ref byte[] output) { #if TRACE_VERBOSE if (GlobalLog.IsEnabled) { GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken, _refreshCredentialNeeded = " + _refreshCredentialNeeded); } #endif if (offset < 0 || offset > (input == null ? 0 : input.Length)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'offset' out of range."); } Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0 || count > (input == null ? 0 : input.Length - offset)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'count' out of range."); } Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); } SecurityBuffer incomingSecurity = null; SecurityBuffer[] incomingSecurityBuffers = null; if (input != null) { incomingSecurity = new SecurityBuffer(input, offset, count, SecurityBufferType.Token); incomingSecurityBuffers = new SecurityBuffer[] { incomingSecurity, new SecurityBuffer(null, 0, 0, SecurityBufferType.Empty) }; } SecurityBuffer outgoingSecurity = new SecurityBuffer(null, SecurityBufferType.Token); SecurityStatusPal errorCode = 0; bool cachedCreds = false; byte[] thumbPrint = null; // // Looping through ASC or ISC with potentially cached credential that could have been // already disposed from a different thread before ISC or ASC dir increment a cred ref count. // try { do { thumbPrint = null; if (_refreshCredentialNeeded) { cachedCreds = _serverMode ? AcquireServerCredentials(ref thumbPrint) : AcquireClientCredentials(ref thumbPrint); } if (_serverMode) { errorCode = SslStreamPal.AcceptSecurityContext( ref _credentialsHandle, ref _securityContext, incomingSecurity, outgoingSecurity, _remoteCertRequired); } else { if (incomingSecurity == null) { errorCode = SslStreamPal.InitializeSecurityContext( ref _credentialsHandle, ref _securityContext, _destination, incomingSecurity, outgoingSecurity); } else { errorCode = SslStreamPal.InitializeSecurityContext( _credentialsHandle, ref _securityContext, _destination, incomingSecurityBuffers, outgoingSecurity); } } } while (cachedCreds && _credentialsHandle == null); } finally { if (_refreshCredentialNeeded) { _refreshCredentialNeeded = false; // // Assuming the ISC or ASC has referenced the credential, // we want to call dispose so to decrement the effective ref count. // if (_credentialsHandle != null) { _credentialsHandle.Dispose(); } // // This call may bump up the credential reference count further. // Note that thumbPrint is retrieved from a safe cert object that was possible cloned from the user passed cert. // if (!cachedCreds && _securityContext != null && !_securityContext.IsInvalid && _credentialsHandle != null && !_credentialsHandle.IsInvalid) { SslSessionsCache.CacheCredential(_credentialsHandle, thumbPrint, _sslProtocols, _serverMode, _encryptionPolicy); } } } output = outgoingSecurity.token; #if TRACE_VERBOSE if (GlobalLog.IsEnabled) { GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken()", Interop.MapSecurityStatus((uint)errorCode)); } #endif return (SecurityStatusPal)errorCode; } /*++ ProcessHandshakeSuccess - Called on successful completion of Handshake - used to set header/trailer sizes for encryption use Fills in the information about established protocol --*/ internal void ProcessHandshakeSuccess() { if (GlobalLog.IsEnabled) { GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess"); } StreamSizes streamSizes; SslStreamPal.QueryContextStreamSizes(_securityContext, out streamSizes); if (streamSizes != null) { try { _headerSize = streamSizes.header; _trailerSize = streamSizes.trailer; _maxDataSize = checked(streamSizes.maximumMessage - (_headerSize + _trailerSize)); } catch (Exception e) { if (!ExceptionCheck.IsFatal(e)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess", "StreamSizes out of range."); } Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess", "StreamSizes out of range."); } throw; } } SslStreamPal.QueryContextConnectionInfo(_securityContext, out _connectionInfo); if (GlobalLog.IsEnabled) { GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess"); } } /*++ Encrypt - Encrypts our bytes before we send them over the wire PERF: make more efficient, this does an extra copy when the offset is non-zero. Input: buffer - bytes for sending offset - size - output - Encrypted bytes --*/ internal SecurityStatusPal Encrypt(byte[] buffer, int offset, int size, ref byte[] output, out int resultSize) { if (GlobalLog.IsEnabled) { GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt"); GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt() - offset: " + offset.ToString() + " size: " + size.ToString() + " buffersize: " + buffer.Length.ToString()); GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt() buffer:"); GlobalLog.Dump(buffer, Math.Min(buffer.Length, 128)); } byte[] writeBuffer; try { if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length)) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > (buffer == null ? 0 : buffer.Length - offset)) { throw new ArgumentOutOfRangeException(nameof(size)); } resultSize = 0; int bufferSizeNeeded = checked(size + _headerSize + _trailerSize); if (output != null && bufferSizeNeeded <= output.Length) { writeBuffer = output; } else { writeBuffer = new byte[bufferSizeNeeded]; } Buffer.BlockCopy(buffer, offset, writeBuffer, _headerSize, size); } catch (Exception e) { if (!ExceptionCheck.IsFatal(e)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Arguments out of range."); } Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Arguments out of range."); } throw; } SecurityStatusPal secStatus = SslStreamPal.EncryptMessage(_securityContext, writeBuffer, size, _headerSize, _trailerSize, out resultSize); if (secStatus != SecurityStatusPal.OK) { if (GlobalLog.IsEnabled) { GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt ERROR", secStatus.ToString()); } } else { output = writeBuffer; if (GlobalLog.IsEnabled) { GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt OK", "data size:" + resultSize.ToString()); } } return secStatus; } internal SecurityStatusPal Decrypt(byte[] payload, ref int offset, ref int count) { if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::Decrypt() - offset: " + offset.ToString() + " size: " + count.ToString() + " buffersize: " + payload.Length.ToString()); } if (offset < 0 || offset > (payload == null ? 0 : payload.Length)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'offset' out of range."); } Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0 || count > (payload == null ? 0 : payload.Length - offset)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'count' out of range."); } Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); } SecurityStatusPal secStatus = SslStreamPal.DecryptMessage(_securityContext, payload, ref offset, ref count); return secStatus; } /*++ VerifyRemoteCertificate - Validates the content of a Remote Certificate checkCRL if true, checks the certificate revocation list for validity. checkCertName, if true checks the CN field of the certificate --*/ //This method validates a remote certificate. //SECURITY: The scenario is allowed in semitrust StorePermission is asserted for Chain.Build // A user callback has unique signature so it is safe to call it under permission assert. // internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback) { if (GlobalLog.IsEnabled) { GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::VerifyRemoteCertificate"); } SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; // We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true. bool success = false; X509Chain chain = null; X509Certificate2 remoteCertificateEx = null; try { X509Certificate2Collection remoteCertificateStore; remoteCertificateEx = CertificateValidationPal.GetRemoteCertificate(_securityContext, out remoteCertificateStore); _isRemoteCertificateAvailable = remoteCertificateEx != null; if (remoteCertificateEx == null) { if (GlobalLog.IsEnabled) { GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::VerifyRemoteCertificate (no remote cert)", (!_remoteCertRequired).ToString()); } sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable; } else { chain = new X509Chain(); chain.ChainPolicy.RevocationMode = _checkCertRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; if (remoteCertificateStore != null) { chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore); } sslPolicyErrors |= CertificateValidationPal.VerifyCertificateProperties( chain, remoteCertificateEx, _checkCertName, _serverMode, _hostName); } if (remoteCertValidationCallback != null) { success = remoteCertValidationCallback(_hostName, remoteCertificateEx, chain, sslPolicyErrors); } else { if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable && !_remoteCertRequired) { success = true; } else { success = (sslPolicyErrors == SslPolicyErrors.None); } } if (SecurityEventSource.Log.IsEnabled()) { if (sslPolicyErrors != SslPolicyErrors.None) { SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), SR.net_log_remote_cert_has_errors); if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) { SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), SR.net_log_remote_cert_not_available); } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) { SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), SR.net_log_remote_cert_name_mismatch); } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0) { string chainStatusString = "ChainStatus: "; foreach (X509ChainStatus chainStatus in chain.ChainStatus) { chainStatusString += "\t" + chainStatus.StatusInformation; } SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), chainStatusString); } } if (success) { if (remoteCertValidationCallback != null) { SecurityEventSource.Log.RemoteCertDeclaredValid(LoggingHash.HashInt(this)); } else { SecurityEventSource.Log.RemoteCertHasNoErrors(LoggingHash.HashInt(this)); } } else { if (remoteCertValidationCallback != null) { SecurityEventSource.Log.RemoteCertUserDeclaredInvalid(LoggingHash.HashInt(this)); } } } if (GlobalLog.IsEnabled) { GlobalLog.Print("Cert Validation, remote cert = " + (remoteCertificateEx == null ? "<null>" : remoteCertificateEx.ToString(true))); } } finally { // At least on Win2k server the chain is found to have dependencies on the original cert context. // So it should be closed first. if (chain != null) { chain.Dispose(); } if (remoteCertificateEx != null) { remoteCertificateEx.Dispose(); } } if (GlobalLog.IsEnabled) { GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::VerifyRemoteCertificate", success.ToString()); } return success; } } // ProtocolToken - used to process and handle the return codes from the SSPI wrapper internal class ProtocolToken { internal SecurityStatusPal Status; internal byte[] Payload; internal int Size; internal bool Failed { get { return ((Status != SecurityStatusPal.OK) && (Status != SecurityStatusPal.ContinueNeeded)); } } internal bool Done { get { return (Status == SecurityStatusPal.OK); } } internal bool Renegotiate { get { return (Status == SecurityStatusPal.Renegotiate); } } internal bool CloseConnection { get { return (Status == SecurityStatusPal.ContextExpired); } } internal ProtocolToken(byte[] data, SecurityStatusPal errorCode) { Status = errorCode; Payload = data; Size = data != null ? data.Length : 0; } internal Exception GetException() { // If it's not done, then there's got to be an error, even if it's // a Handshake message up, and we only have a Warning message. return this.Done ? null : SslStreamPal.GetException(Status); } #if TRACE_VERBOSE public override string ToString() { return "Status=" + Status.ToString() + ", data size=" + Size; } #endif } }
using System; using System.IO; using System.Collections.Generic; using System.Reflection; using System.Linq; using System.Text.RegularExpressions; using NLua; using Oxide.Core; using Oxide.Core.Plugins; using Oxide.Core.Plugins.Watchers; using Oxide.Core.Libraries.Covalence; namespace Oxide.Ext.Lua.Plugins { /// <summary> /// Represents a Lua plugin /// </summary> public class LuaPlugin : Plugin { /// <summary> /// Gets the Lua environment /// </summary> internal NLua.Lua LuaEnvironment { get; } /// <summary> /// Gets this plugin's Lua table /// </summary> private LuaTable Table { get; set; } /// <summary> /// Gets the object associated with this plugin /// </summary> public override object Object => Table; // All functions in this plugin private IDictionary<string, LuaFunction> functions; // The plugin change watcher private FSWatcher watcher; // The Lua extension private LuaExtension luaExt; /// <summary> /// Initializes a new instance of the LuaPlugin class /// </summary> /// <param name="filename"></param> /// <param name="luaExt"></param> /// <param name="watcher"></param> internal LuaPlugin(string filename, LuaExtension luaExt, FSWatcher watcher) { // Store filename Filename = filename; Name = Core.Utility.GetFileNameWithoutExtension(Filename); this.luaExt = luaExt; LuaEnvironment = luaExt.LuaEnvironment; this.watcher = watcher; } #region Config /// <summary> /// Populates the config with default settings /// </summary> protected override void LoadDefaultConfig() { LuaEnvironment.NewTable("tmp"); var tmp = LuaEnvironment["tmp"] as LuaTable; Table["Config"] = tmp; LuaEnvironment["tmp"] = null; CallHook("LoadDefaultConfig", null); Utility.SetConfigFromTable(Config, tmp); } /// <summary> /// Loads the config file for this plugin /// </summary> protected override void LoadConfig() { base.LoadConfig(); if (Table != null) Table["Config"] = Utility.TableFromConfig(Config, LuaEnvironment); } /// <summary> /// Saves the config file for this plugin /// </summary> protected override void SaveConfig() { if (Config == null) return; if (Table == null) return; var configtable = Table["Config"] as LuaTable; if (configtable != null) Utility.SetConfigFromTable(Config, configtable); base.SaveConfig(); } #endregion /// <summary> /// Loads this plugin /// </summary> public override void Load() { // Load the plugin into a table var source = File.ReadAllText(Filename); if (Regex.IsMatch(source, @"PLUGIN\.Version\s*=\s*[\'|""]", RegexOptions.IgnoreCase)) throw new Exception("Plugin version is a string, Oxide 1.18 plugins are not compatible with Oxide 2"); var pluginfunc = LuaEnvironment.LoadString(source, Path.GetFileName(Filename)); if (pluginfunc == null) throw new Exception("LoadString returned null for some reason"); LuaEnvironment.NewTable("PLUGIN"); Table = (LuaTable) LuaEnvironment["PLUGIN"]; ((LuaFunction) LuaEnvironment["setmetatable"]).Call(Table, luaExt.PluginMetatable); Table["Name"] = Name; pluginfunc.Call(); // Read plugin attributes if (!(Table["Title"] is string)) throw new Exception("Plugin is missing title"); if (!(Table["Author"] is string)) throw new Exception("Plugin is missing author"); if (!(Table["Version"] is VersionNumber)) throw new Exception("Plugin is missing version"); Title = (string)Table["Title"]; Author = (string)Table["Author"]; Version = (VersionNumber)Table["Version"]; if (Table["Description"] is string) Description = (string)Table["Description"]; if (Table["ResourceId"] is double) ResourceId = (int)(double)Table["ResourceId"]; if (Table["HasConfig"] is bool) HasConfig = (bool)Table["HasConfig"]; // Set attributes Table["Object"] = this; Table["Plugin"] = this; // Get all functions and hook them functions = new Dictionary<string, LuaFunction>(); foreach (var keyobj in Table.Keys) { var key = keyobj as string; if (key == null) continue; var value = Table[key]; var func = value as LuaFunction; if (func != null) functions.Add(key, func); } if (!HasConfig) HasConfig = functions.ContainsKey("LoadDefaultConfig"); // Bind any base methods (we do it here because we don't want them to be hooked) BindBaseMethods(); // Deal with any attributes var attribs = Table["_attribArr"] as LuaTable; if (attribs != null) { var i = 0; while (attribs[++i] != null) { var attrib = attribs[i] as LuaTable; var attribName = attrib["_attribName"] as string; var attribFunc = attrib["_func"] as LuaFunction; if (attribFunc != null && !string.IsNullOrEmpty(attribName)) { HandleAttribute(attribName, attribFunc, attrib); } } } // Clean up LuaEnvironment["PLUGIN"] = null; } /// <summary> /// Handles a method attribute /// </summary> /// <param name="name"></param> /// <param name="method"></param> /// <param name="data"></param> private void HandleAttribute(string name, LuaFunction method, LuaTable data) { // What type of attribute is it? switch (name) { case "Command": // Parse data out of it var cmdNames = new List<string>(); var i = 0; while (data[++i] != null) cmdNames.Add(data[i] as string); var cmdNamesArr = cmdNames.Where(s => !string.IsNullOrEmpty(s)).ToArray(); string[] cmdPermsArr; if (data["permission"] is string) { cmdPermsArr = new[] { data["permission"] as string }; } else if (data["permission"] is LuaTable || data["permissions"] is LuaTable) { var permsTable = (data["permission"] as LuaTable) ?? (data["permissions"] as LuaTable); var cmdPerms = new List<string>(); i = 0; while (permsTable[++i] != null) cmdPerms.Add(permsTable[i] as string); cmdPermsArr = cmdPerms.Where(s => !string.IsNullOrEmpty(s)).ToArray(); } else cmdPermsArr = new string[0]; // Register it AddCovalenceCommand(cmdNamesArr, cmdPermsArr, (caller, cmd, args) => { HandleCommandCallback(method, caller, cmd, args); return true; }); break; } } private void HandleCommandCallback(LuaFunction func, IPlayer caller, string cmd, string[] args) { LuaEnvironment.NewTable("tmp"); var argsTable = LuaEnvironment["tmp"] as LuaTable; LuaEnvironment["tmp"] = null; for (var i = 0; i < args.Length; i++) { argsTable[i + 1] = args[i]; } try { func.Call(Table, caller, cmd, argsTable); } catch (Exception) { // TODO: Error handling and stuff throw; } } /// <summary> /// Binds base methods to the PLUGIN table /// </summary> private void BindBaseMethods() => BindBaseMethod("lua_SaveConfig", "SaveConfig"); /// <summary> /// Binds the specified base method to the PLUGIN table /// </summary> /// <param name="methodname"></param> /// <param name="luaname"></param> private void BindBaseMethod(string methodname, string luaname) { var method = GetType().GetMethod(methodname, BindingFlags.Static | BindingFlags.NonPublic); LuaEnvironment.RegisterFunction($"PLUGIN.{luaname}", method); } #region Base Methods /// <summary> /// Saves the config file for the specified plugin /// </summary> /// <param name="plugintable"></param> private static void lua_SaveConfig(LuaTable plugintable) { var plugin = plugintable["Object"] as LuaPlugin; plugin?.SaveConfig(); } #endregion /// <summary> /// Called when this plugin has been added to the specified manager /// </summary> /// <param name="manager"></param> public override void HandleAddedToManager(PluginManager manager) { // Call base base.HandleAddedToManager(manager); // Subscribe all our hooks foreach (var key in functions.Keys) Subscribe(key); // Add us to the watcher watcher.AddMapping(Name); // Let the plugin know that it's loading OnCallHook("Init", null); } /// <summary> /// Called when this plugin has been removed from the specified manager /// </summary> /// <param name="manager"></param> public override void HandleRemovedFromManager(PluginManager manager) { // Let plugin know that it's unloading OnCallHook("Unload", null); // Remove us from the watcher watcher.RemoveMapping(Name); // Call base base.HandleRemovedFromManager(manager); Table.Dispose(); LuaEnvironment.DeleteObject(this); LuaEnvironment.DoString("collectgarbage()"); } /// <summary> /// Called when it's time to call a hook /// </summary> /// <param name="hookname"></param> /// <param name="args"></param> /// <returns></returns> protected override object OnCallHook(string hookname, object[] args) { LuaFunction func; if (!functions.TryGetValue(hookname, out func)) return null; try { object[] returnvalues; if (args != null && args.Length > 0) { var realargs = new object[args.Length + 1]; realargs[0] = Table; Array.Copy(args, 0, realargs, 1, args.Length); returnvalues = func.Call(realargs); } else returnvalues = func.Call(Table); if (returnvalues == null || returnvalues.Length == 0) return null; return returnvalues[0]; } catch (TargetInvocationException ex) { throw ex.InnerException; } } } }
using System; using System.Collections.Generic; using UnityEngine; public class AdaptiveRenderQueue : MonoBehaviour { private GameObject mGameObject; private UIPanel mPanel; public int mEffectDepth; private int mDrawCalls; private int mRenderQueue; private List<Renderer> rendererList = new List<Renderer>(); private ModelLoadEffect[] effects; public int GetDrawCalls { get { return this.rendererList.Count; } } private void Awake() { this.mGameObject = base.gameObject; } private void OnEnable() { this.Start(); } private void Start() { this.effects = this.mGameObject.GetComponentsInChildren<ModelLoadEffect>(true); this.Init(); } private void OnDisable() { if (this.mPanel != null) { this.mPanel.RemoveRenderQuene(this); this.rendererList.Clear(); this.mPanel = null; } if (this.effects != null) { int num = this.effects.Length; for (int i = 0; i < num; i++) { if (this.effects[i] != null) { this.effects[i].gameObjectActiveCallBack = null; } } } this.rendererList.Clear(); } private void Init() { if (this.mPanel != null) { this.mPanel.RemoveRenderQuene(this); } this.mPanel = this.GetRootPanel(this.mGameObject); if (this.mPanel != null) { this.mPanel.AddRenderQuene(this); this.RefreshRenderer(); } if (this.effects != null) { int num = this.effects.Length; for (int i = 0; i < num; i++) { if (this.effects[i] != null) { this.effects[i].gameObjectActiveCallBack = new Action(this.RefreshRenderer); } } } } public void RefreshRenderer() { if (this.mPanel != null) { this.rendererList.Clear(); Renderer[] componentsInChildren = this.mGameObject.GetComponentsInChildren<Renderer>(true); int num = componentsInChildren.Length; for (int i = 0; i < num; i++) { if (componentsInChildren[i] != null && componentsInChildren[i].material != null && !this.rendererList.Contains(componentsInChildren[i])) { this.rendererList.Add(componentsInChildren[i]); } } ParticleSystem[] componentsInChildren2 = this.mGameObject.GetComponentsInChildren<ParticleSystem>(true); num = componentsInChildren2.Length; for (int j = 0; j < num; j++) { if (componentsInChildren2[j].GetComponent<Renderer>() != null && componentsInChildren2[j].GetComponent<Renderer>().material != null && !this.rendererList.Contains(componentsInChildren2[j].GetComponent<Renderer>())) { this.rendererList.Add(componentsInChildren2[j].GetComponent<Renderer>()); } } this.rendererList.Sort(new Comparison<Renderer>(this.RendererCompareFunc)); this.OnUpdate(this.mPanel.startingRenderQueue, this.mPanel.drawCalls.size, true); } } public void OnUpdate(int renderQuene, int drawCalls, bool bnow = false) { if (bnow) { this.mRenderQueue = renderQuene; this.mDrawCalls = drawCalls; this.SetRenderQuene(); } else if (renderQuene != this.mRenderQueue || drawCalls != this.mDrawCalls) { this.mRenderQueue = renderQuene; this.mDrawCalls = drawCalls; this.SetRenderQuene(); } } private void OnDestroy() { if (this.mPanel != null) { this.mPanel.RemoveRenderQuene(this); this.rendererList.Clear(); } if (this.effects != null) { int num = this.effects.Length; if (num <= 0) { return; } for (int i = num - 1; i >= 0; i--) { if (this.effects[i] != null) { this.effects[i].gameObjectActiveCallBack = null; } } } } private UIPanel GetRootPanel(GameObject root) { if (root == null) { return null; } UIPanel component = root.GetComponent<UIPanel>(); if (!(component == null)) { return component; } Transform parent = root.transform.parent; if (parent == null) { return null; } if (parent.tag == "UIEvent") { return parent.GetComponent<UIPanel>(); } return this.GetRootPanel(parent.gameObject); } private void SetRenderQuene() { if (this.rendererList != null && this.rendererList.Count > 0) { int num = 3000; int num2 = 0; for (int i = 0; i < this.rendererList.Count; i++) { if (this.rendererList[i].material.renderQueue >= 3000) { if (this.rendererList[i].material.renderQueue > num) { num = this.rendererList[i].material.renderQueue; num2++; } this.rendererList[i].material.renderQueue = this.mRenderQueue + this.mDrawCalls + this.mEffectDepth + num2 + 1; } } } } public static int RenderQueueCompareFunc(AdaptiveRenderQueue left, AdaptiveRenderQueue right) { if (left.mEffectDepth < right.mEffectDepth) { return -1; } if (left.mEffectDepth > right.mEffectDepth) { return 1; } return 0; } private int RendererCompareFunc(Renderer renA, Renderer renB) { return renA.material.shader.renderQueue.CompareTo(renB.material.shader.renderQueue); } }
//------------------------------------------------------------------------------ // <copyright file="DataFieldConverter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.Design.MobileControls.Converters { using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using System.Data; using System.Diagnostics; using System.Runtime.InteropServices; using System.Globalization; using System.Web.UI.Design; using System.Web.UI.MobileControls; using System.Security.Permissions; /// <include file='doc\DataFieldConverter.uex' path='docs/doc[@for="DataFieldConverter"]/*' /> /// <devdoc> /// <para> /// Provides design-time support for a component's data field properties. /// </para> /// </devdoc> [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class DataFieldConverter : TypeConverter { private const String _dataMemberPropertyName = "DataMember"; private const String _dataSourcePropertyName = "DataSource"; /// <include file='doc\DataFieldConverter.uex' path='docs/doc[@for="DataFieldConverter.DataFieldConverter"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of <see cref='System.Web.UI.Design.DataFieldConverter'/>. /// </para> /// </devdoc> public DataFieldConverter() { } /// <include file='doc\DataFieldConverter.uex' path='docs/doc[@for="DataFieldConverter.CanConvertFrom"]/*' /> /// <devdoc> /// <para> /// Gets a value indicating whether this converter can /// convert an object in the given source type to the native type of the converter /// using the context. /// </para> /// </devdoc> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return false; } /// <include file='doc\DataFieldConverter.uex' path='docs/doc[@for="DataFieldConverter.ConvertFrom"]/*' /> /// <devdoc> /// <para> /// Converts the given object to the converter's native type. /// </para> /// </devdoc> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value == null) { return String.Empty; } else if (value.GetType() == typeof(string)) { return (string)value; } throw GetConvertFromException(value); } /// <include file='doc\DataFieldConverter.uex' path='docs/doc[@for="DataFieldConverter.GetStandardValues"]/*' /> /// <devdoc> /// <para> /// Gets the fields present within the selected data source if information about them is available. /// </para> /// </devdoc> public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { object[] names = null; String dataMember = null; bool autoGenerateFields = false; bool autoGenerateFieldsSet = false; ObjectList objectList = null; if (context != null) { ArrayList list = new ArrayList(); PropertyDescriptorCollection props = null; IComponent component = context.Instance as IComponent; if (component is IDeviceSpecificChoiceDesigner) { Object owner = ((ChoicePropertyFilter)component).Owner; PropertyDescriptor pd = ((ICustomTypeDescriptor)component).GetProperties()[_dataMemberPropertyName]; Debug.Assert(pd != null, "Cannot get DataMember"); if (owner is ObjectList) { autoGenerateFields = ((ObjectList)owner).AutoGenerateFields; autoGenerateFieldsSet = true; } component = ((IDeviceSpecificChoiceDesigner)component).UnderlyingControl; // See if owner already has a DataMember dataMember = (String)pd.GetValue(owner); Debug.Assert(dataMember != null); if (dataMember != null && dataMember.Length == 0) { // Get it from underlying object. dataMember = (String)pd.GetValue(component); Debug.Assert(dataMember != null); } } if (component != null) { objectList = component as ObjectList; if (objectList != null) { foreach(ObjectListField field in objectList.Fields) { list.Add(field.Name); } if (!autoGenerateFieldsSet) { autoGenerateFields = objectList.AutoGenerateFields; } } if (objectList == null || autoGenerateFields) { ISite componentSite = component.Site; if (componentSite != null) { IDesignerHost designerHost = (IDesignerHost)componentSite.GetService(typeof(IDesignerHost)); if (designerHost != null) { IDesigner designer = designerHost.GetDesigner(component); if (designer is IDataSourceProvider) { IEnumerable dataSource = null; if (!String.IsNullOrEmpty(dataMember)) { DataBindingCollection dataBindings = ((HtmlControlDesigner)designer).DataBindings; DataBinding binding = dataBindings[_dataSourcePropertyName]; if (binding != null) { dataSource = DesignTimeData.GetSelectedDataSource( component, binding.Expression, dataMember); } } else { dataSource = ((IDataSourceProvider)designer).GetResolvedSelectedDataSource(); } if (dataSource != null) { props = DesignTimeData.GetDataFields(dataSource); } } } } } } if (props != null) { foreach (PropertyDescriptor propDesc in props) { list.Add(propDesc.Name); } } names = list.ToArray(); Array.Sort(names); } return new StandardValuesCollection(names); } /// <include file='doc\DataFieldConverter.uex' path='docs/doc[@for="DataFieldConverter.GetStandardValuesExclusive"]/*' /> /// <devdoc> /// <para> /// Gets a value indicating whether the collection of standard values returned from /// <see cref='System.ComponentModel.TypeConverter.GetStandardValues'/> is an exclusive /// list of possible values, using the specified context. /// </para> /// </devdoc> public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } /// <include file='doc\DataFieldConverter.uex' path='docs/doc[@for="DataFieldConverter.GetStandardValuesSupported"]/*' /> /// <devdoc> /// <para> /// Gets a value indicating whether this object supports a standard set of values /// that can be picked from a list. /// </para> /// </devdoc> public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { if (context.Instance is IComponent) { // We only support the dropdown in single-select mode. return true; } return false; } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.ArcMapUI; using ESRI.ArcGIS.Framework; using ESRI.ArcGIS.Carto; using System.Runtime.InteropServices; using ESRI.ArcGIS.esriSystem; namespace TOCLayerFilterCS { [Guid("aede0664-ef97-4c6c-94e6-b3c6216eedc5")] [ClassInterface(ClassInterfaceType.None)] [ProgId("TOCLayerFilterCS.TOCLayerFilter")] public partial class TOCLayerFilter : UserControl, IContentsView3 { private IApplication m_application; private bool m_visible; private object m_contextItem; private bool m_isProcessEvents; #region COM Registration Function(s) [ComRegisterFunction()] [ComVisible(false)] static void RegisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType); // // TODO: Add any COM registration code here // } [ComUnregisterFunction()] [ComVisible(false)] static void UnregisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType); // // TODO: Add any COM unregistration code here // } #region ArcGIS Component Category Registrar generated code /// <summary> /// Required method for ArcGIS Component Category registration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryRegistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ContentsViews.Register(regKey); } /// <summary> /// Required method for ArcGIS Component Category unregistration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryUnregistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ContentsViews.Unregister(regKey); } #endregion #endregion public TOCLayerFilter() { InitializeComponent(); } #region "IContentsView3 Implementations" public int Bitmap { get { string bitmapResourceName = GetType().Name + ".bmp"; System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(GetType(), bitmapResourceName); bmp.MakeTransparent(bmp.GetPixel(1, 1)); //alternatively use a .png with transparency return bmp.GetHbitmap().ToInt32(); } } public string Tooltip { get { return "Layer Types (C#)"; } } public bool Visible { get { return m_visible; } set { m_visible = value; } } string IContentsView3.Name { get { return "Layer Types (C#)"; } } public int hWnd { get { return this.Handle.ToInt32(); } } public object ContextItem //last right-clicked item { get { return m_contextItem; } set { }//Not implemented } public void Activate(int parentHWnd, IMxDocument Document) { if (m_application == null) { m_application = ((IDocument)Document).Parent; if (cboLayerType.SelectedIndex < 0) cboLayerType.SelectedIndex = 0; //this should refresh the list automatically else RefreshList(); SetUpDocumentEvent(Document as IDocument); } } public void BasicActivate(int parentHWnd, IDocument Document) { } public void Refresh(object item) { if (item != this) { //when items are added, removed, reordered tvwLayer.SuspendLayout(); RefreshList(); tvwLayer.ResumeLayout(); } } public void Deactivate() { //Any clean up? } public void AddToSelectedItems(object item) { } public object SelectedItem { get { //No Multiselect so return selected node if (tvwLayer.SelectedNode != null) return tvwLayer.SelectedNode.Tag; //Layer return null; } set { //Not implemented } } public bool ProcessEvents { set { m_isProcessEvents = value; } } public void RemoveFromSelectedItems(object item) { } public bool ShowLines { get { return tvwLayer.ShowLines; } set { tvwLayer.ShowLines = value; } } #endregion private void RefreshList() { tvwLayer.Nodes.Clear(); UID layerFilter = null; if (cboLayerType.SelectedItem.Equals("Feature Layers")) { layerFilter = new UIDClass(); layerFilter.Value = "{40A9E885-5533-11d0-98BE-00805F7CED21}"; //typeof(IFeatureLayer).GUID.ToString("B"); } else if (cboLayerType.SelectedItem.Equals("Raster Layers")) { layerFilter = new UIDClass(); layerFilter.Value = typeof(IRasterLayer).GUID.ToString("B"); } else if (cboLayerType.SelectedItem.Equals("Data Layers")) { layerFilter = new UIDClass(); layerFilter.Value = "{6CA416B1-E160-11D2-9F4E-00C04F6BC78E}"; //typeof(IDataLayer).GUID.ToString("B"); } IMxDocument document = (IMxDocument)m_application.Document; IMaps maps = document.Maps; for (int i = 0; i < maps.Count; i++) { IMap map = maps.get_Item(i); TreeNode mapNode = tvwLayer.Nodes.Add(map.Name); mapNode.Tag = map; if (map.LayerCount > 0) { IEnumLayer layers = map.get_Layers(layerFilter, true); layers.Reset(); ILayer lyr; while ((lyr = layers.Next()) != null) { TreeNode lyrNode = mapNode.Nodes.Add(lyr.Name); lyrNode.Tag = lyr; } mapNode.ExpandAll(); } } } private void cboLayerType_SelectedIndexChanged(object sender, EventArgs e) { tvwLayer.SuspendLayout(); RefreshList(); tvwLayer.ResumeLayout(); } private void tvwLayer_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Button == MouseButtons.Right) { //Set item for context menu commands to work with m_contextItem = e.Node.Tag; //Show context menu UID menuID = new UIDClass(); if (e.Node.Tag is IMap) //data frame { menuID.Value = "{F42891B5-2C92-11D2-AE07-080009EC732A}"; //Data Frame Context Menu (TOC) } else //Layer - custom menu { menuID.Value = "{30cb4a78-6eba-4f60-b52e-38bc02bacc89}"; } ICommandBar cmdBar = (ICommandBar)m_application.Document.CommandBars.Find(menuID, false, false); cmdBar.Popup(0, 0); } } #region "Add Event Wiring for New/Open Documents" // Event member variables private IDocumentEvents_Event m_docEvents; // Wiring private void SetUpDocumentEvent(IDocument myDocument) { m_docEvents = myDocument as IDocumentEvents_Event; m_docEvents.OpenDocument += new IDocumentEvents_OpenDocumentEventHandler(RefreshList); m_docEvents.NewDocument += new IDocumentEvents_NewDocumentEventHandler(RefreshList); } #endregion } }
// Outline Object Copy|Highlighters|40030 namespace VRTK.Highlighters { using UnityEngine; using System; using System.Collections.Generic; /// <summary> /// The Outline Object Copy Highlighter works by making a copy of a mesh and adding an outline shader to it and toggling the appearance of the highlighted object. /// </summary> /// <example> /// `VRTK/Examples/005_Controller_BasicObjectGrabbing` demonstrates the outline highlighting on the green sphere when the controller touches it. /// /// `VRTK/Examples/035_Controller_OpacityAndHighlighting` demonstrates the outline highlighting if the left controller collides with the green box. /// </example> public class VRTK_OutlineObjectCopyHighlighter : VRTK_BaseHighlighter { [Tooltip("The thickness of the outline effect")] public float thickness = 1f; [Tooltip("The GameObjects to use as the model to outline. If one isn't provided then the first GameObject with a valid Renderer in the current GameObject hierarchy will be used.")] public GameObject[] customOutlineModels; [Tooltip("A path to a GameObject to find at runtime, if the GameObject doesn't exist at edit time.")] public string[] customOutlineModelPaths; [Tooltip("If the mesh has multiple sub-meshes to highlight then this should be checked, otherwise only the first mesh will be highlighted.")] public bool enableSubmeshHighlight = false; protected Material stencilOutline; protected GameObject[] highlightModels; protected string[] copyComponents = new string[] { "UnityEngine.MeshFilter", "UnityEngine.MeshRenderer" }; /// <summary> /// The Initialise method sets up the highlighter for use. /// </summary> /// <param name="color">Not used.</param> /// <param name="options">A dictionary array containing the highlighter options:\r * `&lt;'thickness', float&gt;` - Same as `thickness` inspector parameter.\r * `&lt;'customOutlineModels', GameObject[]&gt;` - Same as `customOutlineModels` inspector parameter.\r * `&lt;'customOutlineModelPaths', string[]&gt;` - Same as `customOutlineModelPaths` inspector parameter.</param> public override void Initialise(Color? color = null, Dictionary<string, object> options = null) { usesClonedObject = true; if (stencilOutline == null) { stencilOutline = Instantiate((Material)Resources.Load("OutlineBasic")); } SetOptions(options); ResetHighlighter(); } /// <summary> /// The ResetHighlighter method creates the additional model to use as the outline highlighted object. /// </summary> public override void ResetHighlighter() { DeleteExistingHighlightModels(); //First try and use the paths if they have been set ResetHighlighterWithCustomModelPaths(); //If the custom models have been set then use these to override any set paths. ResetHighlighterWithCustomModels(); //if no highlights set then try falling back ResetHighlightersWithCurrentGameObject(); } /// <summary> /// The Highlight method initiates the outline object to be enabled and display the outline colour. /// </summary> /// <param name="color">The colour to outline with.</param> /// <param name="duration">Not used.</param> public override void Highlight(Color? color, float duration = 0f) { if (highlightModels != null && highlightModels.Length > 0) { stencilOutline.SetFloat("_Thickness", thickness); stencilOutline.SetColor("_OutlineColor", (Color)color); for (int i = 0; i < highlightModels.Length; i++) { if (highlightModels[i]) { highlightModels[i].SetActive(true); } } } } /// <summary> /// The Unhighlight method hides the outline object and removes the outline colour. /// </summary> /// <param name="color">Not used.</param> /// <param name="duration">Not used.</param> public override void Unhighlight(Color? color = null, float duration = 0f) { if (highlightModels != null) { for (int i = 0; i < highlightModels.Length; i++) { if (highlightModels[i]) { highlightModels[i].SetActive(false); } } } } protected virtual void OnEnable() { if (customOutlineModels == null) { customOutlineModels = new GameObject[0]; } if (customOutlineModelPaths == null) { customOutlineModelPaths = new string[0]; } } protected virtual void OnDestroy() { if (highlightModels != null) { for (int i = 0; i < highlightModels.Length; i++) { if (highlightModels[i]) { Destroy(highlightModels[i]); } } } Destroy(stencilOutline); } protected virtual void ResetHighlighterWithCustomModels() { if (customOutlineModels != null && customOutlineModels.Length > 0) { highlightModels = new GameObject[customOutlineModels.Length]; for (int i = 0; i < customOutlineModels.Length; i++) { highlightModels[i] = CreateHighlightModel(customOutlineModels[i], ""); } } } protected virtual void ResetHighlighterWithCustomModelPaths() { if (customOutlineModelPaths != null && customOutlineModelPaths.Length > 0) { highlightModels = new GameObject[customOutlineModels.Length]; for (int i = 0; i < customOutlineModelPaths.Length; i++) { highlightModels[i] = CreateHighlightModel(null, customOutlineModelPaths[i]); } } } protected virtual void ResetHighlightersWithCurrentGameObject() { if (highlightModels == null || highlightModels.Length == 0) { highlightModels = new GameObject[1]; highlightModels[0] = CreateHighlightModel(null, ""); } } protected virtual void SetOptions(Dictionary<string, object> options = null) { var tmpThickness = GetOption<float>(options, "thickness"); if (tmpThickness > 0f) { thickness = tmpThickness; } var tmpCustomModels = GetOption<GameObject[]>(options, "customOutlineModels"); if (tmpCustomModels != null) { customOutlineModels = tmpCustomModels; } var tmpCustomModelPaths = GetOption<string[]>(options, "customOutlineModelPaths"); if (tmpCustomModelPaths != null) { customOutlineModelPaths = tmpCustomModelPaths; } } protected virtual void DeleteExistingHighlightModels() { var existingHighlighterObjects = GetComponentsInChildren<VRTK_PlayerObject>(true); for (int i = 0; i < existingHighlighterObjects.Length; i++) { if (existingHighlighterObjects[i].objectType == VRTK_PlayerObject.ObjectTypes.Highlighter) { Destroy(existingHighlighterObjects[i].gameObject); } } } protected virtual GameObject CreateHighlightModel(GameObject givenOutlineModel, string givenOutlineModelPath) { if (givenOutlineModel != null) { givenOutlineModel = (givenOutlineModel.GetComponent<Renderer>() ? givenOutlineModel : givenOutlineModel.GetComponentInChildren<Renderer>().gameObject); } else if (givenOutlineModelPath != "") { var getChildModel = transform.FindChild(givenOutlineModelPath); givenOutlineModel = (getChildModel ? getChildModel.gameObject : null); } GameObject copyModel = givenOutlineModel; if (copyModel == null) { copyModel = (GetComponent<Renderer>() ? gameObject : GetComponentInChildren<Renderer>().gameObject); } if (copyModel == null) { VRTK_Logger.Error(VRTK_Logger.GetCommonMessage(VRTK_Logger.CommonMessageKeys.REQUIRED_COMPONENT_MISSING_FROM_GAMEOBJECT, "VRTK_OutlineObjectCopyHighlighter", "Renderer", "the same or child", " to add the highlighter to")); return null; } GameObject highlightModel = new GameObject(name + "_HighlightModel"); highlightModel.transform.SetParent(copyModel.transform.parent, false); highlightModel.transform.localPosition = copyModel.transform.localPosition; highlightModel.transform.localRotation = copyModel.transform.localRotation; highlightModel.transform.localScale = copyModel.transform.localScale; highlightModel.transform.SetParent(transform); foreach (var component in copyModel.GetComponents<Component>()) { if (Array.IndexOf(copyComponents, component.GetType().ToString()) >= 0) { VRTK_SharedMethods.CloneComponent(component, highlightModel); } } var copyMesh = copyModel.GetComponent<MeshFilter>(); var highlightMesh = highlightModel.GetComponent<MeshFilter>(); if (highlightMesh) { if (enableSubmeshHighlight) { List<CombineInstance> combine = new List<CombineInstance>(); for (int i = 0; i < copyMesh.mesh.subMeshCount; i++) { CombineInstance ci = new CombineInstance(); ci.mesh = copyMesh.mesh; ci.subMeshIndex = i; ci.transform = copyMesh.transform.localToWorldMatrix; combine.Add(ci); } highlightMesh.mesh = new Mesh(); highlightMesh.mesh.CombineMeshes(combine.ToArray(), true, false); } else { highlightMesh.mesh = copyMesh.mesh; } highlightModel.GetComponent<Renderer>().material = stencilOutline; } highlightModel.SetActive(false); VRTK_PlayerObject.SetPlayerObject(highlightModel, VRTK_PlayerObject.ObjectTypes.Highlighter); return highlightModel; } } }
//============================================================================= // System : Sandcastle Help File Builder // File : EditorActions.cs // Author : Eric Woodruff ([email protected]) // Updated : 12/06/2009 // Note : Copyright 2008-2009, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains various custom actions for the topic editor. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.6.0.7 05/24/2008 EFW Created the code //============================================================================= using System; using System.ComponentModel; using System.Globalization; using System.IO; using System.Web; using System.Windows.Forms; using SandcastleBuilder.Utils; using SandcastleBuilder.Utils.ConceptualContent; using SandcastleBuilder.Utils.Design; using ICSharpCode.TextEditor; using ICSharpCode.TextEditor.Actions; using ICSharpCode.TextEditor.Document; using WeifenLuo.WinFormsUI.Docking; namespace SandcastleBuilder.Gui.ContentEditors { #region Goto line //===================================================================== /// <summary> /// Get a line number and position the cursor on it /// </summary> internal sealed class GotoLine : AbstractEditAction { /// <summary> /// Execute the Goto Line action /// </summary> /// <param name="textArea">The text area in which to perform the /// action</param> public override void Execute(TextArea textArea) { using(GotoLineDlg dlg = new GotoLineDlg()) { if(dlg.ShowDialog() == DialogResult.OK) textArea.Caret.Line = dlg.LineNumber - 1; } } } #endregion #region Fire the find text event //===================================================================== /// <summary> /// Fire the PerformFindText event /// </summary> internal sealed class FindText : AbstractEditAction { private ContentEditorControl editor; /// <summary> /// Constructor /// </summary> /// <param name="parent">The parent editor control</param> public FindText(ContentEditorControl parent) { editor = parent; } /// <summary> /// Execute the Find Text action /// </summary> /// <param name="textArea">The text area in which to perform the /// action</param> public override void Execute(TextArea textArea) { editor.OnPerformFindText(EventArgs.Empty); } } #endregion #region Fire the replace text event //===================================================================== /// <summary> /// Fire the PerformReplaceText event /// </summary> internal sealed class ReplaceText : AbstractEditAction { private ContentEditorControl editor; /// <summary> /// Constructor /// </summary> /// <param name="parent">The parent editor control</param> public ReplaceText(ContentEditorControl parent) { editor = parent; } /// <summary> /// Execute the Find Text action /// </summary> /// <param name="textArea">The text area in which to perform the /// action</param> public override void Execute(TextArea textArea) { editor.OnPerformReplaceText(EventArgs.Empty); } } #endregion #region Paste Special //===================================================================== /// <summary> /// This handles pasting data from <see cref="BaseContentEditor.ClipboardDataHandler" /> /// objects if present. /// </summary> internal sealed class PasteSpecial : Paste { private ContentEditorControl editor; /// <summary> /// Constructor /// </summary> /// <param name="parent">The parent editor control</param> public PasteSpecial(ContentEditorControl parent) { editor = parent; } /// <summary> /// Handle the paste operation /// </summary> /// <param name="textArea">The text area in which to perform the /// action</param> public override void Execute(TextArea textArea) { BaseContentEditor.ClipboardDataHandler getData = (BaseContentEditor.ClipboardDataHandler)Clipboard.GetDataObject().GetData( typeof(BaseContentEditor.ClipboardDataHandler)); object pasteData = null; DataObject data; if(getData != null) pasteData = getData(); if(pasteData != null) { data = new DataObject(); data.SetData(pasteData.GetType(), pasteData); editor.PasteSpecial(data); } else base.Execute(textArea); } } #endregion #region HTML encode the selected text //===================================================================== /// <summary> /// This will HTML encode the currently selected block of text. /// </summary> /// <remarks>If no text is selected, nothing will happen.</remarks> internal sealed class HtmlEncode : AbstractEditAction { /// <summary> /// Execute the HTML Encode action /// </summary> /// <param name="textArea">The text area in which to perform the /// action</param> public override void Execute(TextArea textArea) { int offset = textArea.Caret.Offset; string selectedText; if(textArea.SelectionManager.HasSomethingSelected && textArea.SelectionManager.SelectionCollection[0].ContainsOffset(offset)) { selectedText = textArea.SelectionManager.SelectionCollection[0].SelectedText; ContentEditorControl.InsertString(textArea, HttpUtility.HtmlEncode(selectedText)); } } } #endregion #region Insert closing element action //===================================================================== /// <summary> /// This is used to insert a closing element when Tab is hit and the cursor /// is within an opening tag. /// </summary> /// <remarks>This is a really simple form of auto-completion. This may be /// replaced in a later release with real auto-completion support that /// includes a pop-up with available options.</remarks> internal sealed class InsertClosingElement : AbstractEditAction { private IEditAction defaultAction; /// <summary> /// Constructor /// </summary> /// <param name="oldAction">The old action to call if this action /// doesn't do anything.</param> public InsertClosingElement(IEditAction oldAction) { defaultAction = oldAction; } /// <summary> /// Execute the Inser Closing Element action /// </summary> /// <param name="textArea">The text area in which to perform the /// action</param> public override void Execute(TextArea textArea) { IDocument doc = textArea.Document; int endTag = -1, open = -1, close = -1, offset = textArea.Caret.Offset; char c; if(offset > 0 && doc.GetCharAt(offset - 1) == '>') offset--; // Find end of the element for(int i = offset; i < doc.TextLength; i++) { c = doc.GetCharAt(i); if(c == '<' || c== '>') { if(c == '>') { endTag = close = i; // Find start of tag for(int j = close - 1; j >= 0; j--) { c = doc.GetCharAt(j); if(c == '<' || c == '>') { if(c == '<') open = j; break; } // On whitespace, assume we just moved past // an attribute. if(Char.IsWhiteSpace(c)) endTag = j; } } break; } } // Execute the default action if we couldn't find an element // or it's a comment. if(open < 0 || close < 0 || doc.GetText(open + 1, 3) == "!--") { if(defaultAction != null) defaultAction.Execute(textArea); else textArea.InsertChar('\t'); } else { open++; string tag = doc.GetText(open, endTag - open); close++; doc.Insert(close, "</" + tag + ">"); textArea.Caret.Position = doc.OffsetToPosition(close); } } } #endregion #region Insert element //===================================================================== /// <summary> /// Insert an element of the given type optionally wrapping any selected /// text in which the cursor is located. /// </summary> internal sealed class InsertElement : AbstractEditAction { string elementName; /// <summary> /// Constructor /// </summary> /// <param name="element">The element name to insert</param> public InsertElement(string element) { if(String.IsNullOrEmpty(element)) throw new ArgumentException("An element name must be specified", "element"); elementName = element; } /// <summary> /// Execute the Insert Element action /// </summary> /// <param name="textArea">The text area in which to perform the /// action</param> public override void Execute(TextArea textArea) { int offset = textArea.Caret.Offset; string selectedText; if(textArea.SelectionManager.HasSomethingSelected && textArea.SelectionManager.SelectionCollection[0].ContainsOffset(offset)) selectedText = textArea.SelectionManager.SelectionCollection[0].SelectedText; else selectedText = String.Empty; ContentEditorControl.InsertString(textArea, String.Format( CultureInfo.CurrentCulture, "<{0}>{1}</{0}>", elementName, selectedText)); textArea.Caret.Column -= elementName.Length + 3; } } #endregion #region Insert matching character //===================================================================== /// <summary> /// Insert a matching character when the first of the pair is entered /// </summary> internal sealed class InsertMatchingCharacter : AbstractEditAction { string matchedChars; /// <summary> /// Constructor /// </summary> /// <param name="match">The character(s) to insert</param> public InsertMatchingCharacter(string match) { if(String.IsNullOrEmpty(match)) throw new ArgumentException("Character(s) to insert cannot " + "be null or empty", "match"); matchedChars = match; } /// <summary> /// Execute the Insert Matching action /// </summary> /// <param name="textArea">The text area in which to perform the /// action</param> public override void Execute(TextArea textArea) { int col = textArea.Caret.Column; textArea.InsertString(matchedChars); textArea.Caret.Column = col + 1; } } #endregion }
using System.Collections.Generic; using GraphQL.Types; using GraphQL.Validation.Errors; using GraphQL.Validation.Rules; using Xunit; namespace GraphQL.Tests.Validation { public class OverlappingFieldsCanBeMergedTest : ValidationTestBase<OverlappingFieldsCanBeMerged, ValidationSchema> { [Fact] public void Unique_fields_should_pass() { const string query = @" fragment uniqueFields on Dog { name nickname } "; ShouldPassRule(query); } [Fact] public void Identical_fields_should_pass() { const string query = @" fragment mergeIdenticalFields on Dog { name name } "; ShouldPassRule(query); } [Fact] public void Identical_fields_with_identical_args_should_pass() { const string query = @" fragment mergeIdenticalFieldsWithIdenticalArgs on Dog { doesKnowCommand(dogCommand: SIT) doesKnowCommand(dogCommand: SIT) } "; ShouldPassRule(query); } [Fact] public void Identical_fields_with_identical_directives_should_pass() { const string query = @" fragment mergeSameFieldsWithSameDirectives on Dog { name @include(if: true) name @include(if: true) } "; ShouldPassRule(query); } [Fact] public void Different_args_with_different_aliases_should_pass() { const string query = @" fragment differentArgsWithDifferentAliases on Dog { knowsSit: doesKnowCommand(dogCommand: SIT) knowsDown: doesKnowCommand(dogCommand: DOWN) } "; ShouldPassRule(query); } [Fact] public void Different_directives_with_different_aliases_should_pass() { const string query = @" fragment differentDirectivesWithDifferentAliases on Dog { nameIfTrue: name @include(if: true) nameIfFalse: name @include(if: false) } "; ShouldPassRule(query); } [Fact] public void Different_skip_or_include_directives_accepted_should_pass() { const string query = @" fragment differentDirectivesWithDifferentAliases on Dog { name @include(if: true) name @include(if: false) } "; ShouldPassRule(query); } [Fact] public void Same_aliases_allowed_on_non_overlapping_fields_should_pass() { const string query = @" fragment sameAliasesWithDifferentFieldTargets on Pet { ... on Dog { name } ... on Cat { name: nickname } } "; ShouldPassRule(query); } [Fact] public void Same_aliases_with_different_field_targets_should_fail() { const string query = @" fragment sameAliasesWithDifferentFieldTargets on Dog { fido: name fido: nickname } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("fido", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "name and nickname are different fields" } }); e.Locations.Add(new ErrorLocation(3, 21)); e.Locations.Add(new ErrorLocation(4, 21)); }); }); } [Fact] public void Alias_masking_direct_field_access_should_fail() { const string query = @" fragment aliasMaskingDirectFieldAccess on Dog { name: nickname name } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("name", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "nickname and name are different fields" } }); e.Locations.Add(new ErrorLocation(3, 21)); e.Locations.Add(new ErrorLocation(4, 21)); }); }); } [Fact] public void Different_args_second_adds_an_argument_should_fail() { const string query = @" fragment conflictingArgs on Dog { doesKnowCommand doesKnowCommand(dogCommand: HEEL) } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("doesKnowCommand", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "they have differing arguments" } }); e.Locations.Add(new ErrorLocation(3, 21)); e.Locations.Add(new ErrorLocation(4, 21)); }); }); } [Fact] public void Different_args_second_missing_an_argument_should_fail() { const string query = @" fragment conflictingArgs on Dog { doesKnowCommand(dogCommand: SIT) doesKnowCommand } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("doesKnowCommand", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "they have differing arguments" } }); e.Locations.Add(new ErrorLocation(3, 21)); e.Locations.Add(new ErrorLocation(4, 21)); }); }); } [Fact] public void Conflicting_args_should_fail() { const string query = @" fragment conflictingArgs on Dog { doesKnowCommand(dogCommand: SIT) doesKnowCommand(dogCommand: HEEL) } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("doesKnowCommand", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "they have differing arguments" } }); e.Locations.Add(new ErrorLocation(3, 21)); e.Locations.Add(new ErrorLocation(4, 21)); }); }); } /// <summary> /// This is valid since no object can be both a "Dog" and a "Cat", thus /// these fields can never overlap. /// </summary> [Fact] public void Allows_different_args_where_no_conflict_is_possible_should_pass() { const string query = @" fragment conflictingArgs on Pet { ... on Dog { name(surname: true) } ... on Cat { name } } "; ShouldPassRule(query); } [Fact] public void Encounters_conflict_in_fragments_should_fail() { const string query = @" { ...A ...B } fragment A on Type { x: a } fragment B on Type { x: b } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("x", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "a and b are different fields" } }); e.Locations.Add(new ErrorLocation(7, 21)); e.Locations.Add(new ErrorLocation(10, 21)); }); }); } [Fact] public void Reports_each_conflict_once_should_fail() { const string query = @" { f1 { ...A ...B } f2 { ...B ...A } f3 { ...A ...B x: c } } fragment A on Type { x: a } fragment B on Type { x: b } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("x", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "a and b are different fields" } }); e.Locations.Add(new ErrorLocation(18, 21)); e.Locations.Add(new ErrorLocation(21, 21)); }); config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("x", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "c and a are different fields" } }); e.Locations.Add(new ErrorLocation(14, 25)); e.Locations.Add(new ErrorLocation(18, 21)); }); config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("x", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "c and b are different fields" } }); e.Locations.Add(new ErrorLocation(14, 25)); e.Locations.Add(new ErrorLocation(21, 21)); }); }); } [Fact] public void Deep_conflict() { const string query = @" { field { x: a }, field { x: b } } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("field", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msgs = new List<OverlappingFieldsCanBeMerged.ConflictReason> { new OverlappingFieldsCanBeMerged.ConflictReason { Name = "x", Message = new OverlappingFieldsCanBeMerged.Message { Msg = "a and b are different fields" } } } } }); e.Locations.Add(new ErrorLocation(3, 21)); e.Locations.Add(new ErrorLocation(4, 25)); e.Locations.Add(new ErrorLocation(6, 21)); e.Locations.Add(new ErrorLocation(7, 25)); }); }); } [Fact] public void Deep_conflict_with_multiple_issues_should_fail() { const string query = @" { field { x: a y: c }, field { x: b y: d } } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("field", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msgs = new List<OverlappingFieldsCanBeMerged.ConflictReason> { new OverlappingFieldsCanBeMerged.ConflictReason { Name = "x", Message = new OverlappingFieldsCanBeMerged.Message { Msg = "a and b are different fields" } }, new OverlappingFieldsCanBeMerged.ConflictReason { Name = "y", Message = new OverlappingFieldsCanBeMerged.Message { Msg = "c and d are different fields" } } } } }); e.Locations.Add(new ErrorLocation(3, 21)); e.Locations.Add(new ErrorLocation(4, 25)); e.Locations.Add(new ErrorLocation(5, 25)); e.Locations.Add(new ErrorLocation(7, 21)); e.Locations.Add(new ErrorLocation(8, 25)); e.Locations.Add(new ErrorLocation(9, 25)); }); }); } [Fact] public void Very_deep_conflict_should_fail() { const string query = @" { field { deepField { x: a } }, field { deepField { x: b } } } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("field", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msgs = new List<OverlappingFieldsCanBeMerged.ConflictReason> { new OverlappingFieldsCanBeMerged.ConflictReason { Name = "deepField", Message = new OverlappingFieldsCanBeMerged.Message { Msgs = new List<OverlappingFieldsCanBeMerged.ConflictReason> { new OverlappingFieldsCanBeMerged.ConflictReason { Name = "x", Message = new OverlappingFieldsCanBeMerged.Message { Msg = "a and b are different fields" } } } } } } } }); e.Locations.Add(new ErrorLocation(3, 21)); e.Locations.Add(new ErrorLocation(4, 25)); e.Locations.Add(new ErrorLocation(5, 29)); e.Locations.Add(new ErrorLocation(8, 21)); e.Locations.Add(new ErrorLocation(9, 25)); e.Locations.Add(new ErrorLocation(10, 29)); }); }); } [Fact] public void Reports_deep_conflict_to_nearest_common_ancestor_should_fail() { const string query = @" { field { deepField { x: a } deepField { x: b } }, field { deepField { y } } } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("deepField", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msgs = new List<OverlappingFieldsCanBeMerged.ConflictReason> { new OverlappingFieldsCanBeMerged.ConflictReason { Name = "x", Message = new OverlappingFieldsCanBeMerged.Message { Msg = "a and b are different fields" } } } } }); e.Locations.Add(new ErrorLocation(4, 25)); e.Locations.Add(new ErrorLocation(5, 29)); e.Locations.Add(new ErrorLocation(7, 25)); e.Locations.Add(new ErrorLocation(8, 29)); }); }); } [Fact] public void Reports_deep_conflict_to_nearest_common_ancestor_in_fragments() { const string query = @" { field { ...F } field { ...F } } fragment F on T { deepField { deeperField { x: a } deeperField { x: b } }, deepField { deeperField { y } } } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("deeperField", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msgs = new List<OverlappingFieldsCanBeMerged.ConflictReason> { new OverlappingFieldsCanBeMerged.ConflictReason { Name = "x", Message = new OverlappingFieldsCanBeMerged.Message { Msg = "a and b are different fields" } } } } }); e.Locations.Add(new ErrorLocation(12, 25)); e.Locations.Add(new ErrorLocation(13, 29)); e.Locations.Add(new ErrorLocation(15, 25)); e.Locations.Add(new ErrorLocation(16, 29)); }); }); } [Fact] public void Reports_deep_conflict_in_nested_fragments() { const string query = @" { field { ...F } field { ...I } } fragment F on T { x: a ...G } fragment G on T { y: c } fragment I on T { y: d ...J } fragment J on T { x: b } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("field", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msgs = new List<OverlappingFieldsCanBeMerged.ConflictReason> { new OverlappingFieldsCanBeMerged.ConflictReason { Name = "x", Message = new OverlappingFieldsCanBeMerged.Message { Msg = "a and b are different fields" } }, new OverlappingFieldsCanBeMerged.ConflictReason { Name = "y", Message = new OverlappingFieldsCanBeMerged.Message { Msg = "c and d are different fields" } } } } }); e.Locations.Add(new ErrorLocation(3, 21)); e.Locations.Add(new ErrorLocation(11, 21)); e.Locations.Add(new ErrorLocation(15, 21)); e.Locations.Add(new ErrorLocation(6, 21)); e.Locations.Add(new ErrorLocation(22, 21)); e.Locations.Add(new ErrorLocation(18, 21)); }); }); } [Fact] public void Ignores_unknown_fragments() { const string query = @" { field ...Unknown ...Known } fragment Known on T { field ...OtherUnknown } "; ShouldPassRule(query); } [Fact] public void Does_not_infinite_loop_on_recursive_fragment() { const string query = @" fragment fragA on Human { name, relatives { name, ...fragA } } "; ShouldPassRule(query); } [Fact] public void Does_not_infinite_loop_on_immediately_recursive_fragment() { const string query = @" fragment fragA on Human { name, ...fragA } "; ShouldPassRule(query); } [Fact] public void Does_not_infinite_loop_on_transitively_recursive_fragment() { const string query = @" fragment fragA on Human { name, ...fragB } fragment fragB on Human { name, ...fragC } fragment fragC on Human { name, ...fragA } "; ShouldPassRule(query); } [Fact] public void Finds_invalid_case_even_with_immediately_recursive_fragment() { const string query = @" fragment sameAliasesWithDifferentFieldTargets on Dog { ...sameAliasesWithDifferentFieldTargets fido: name fido: nickname } "; ShouldFailRule(config => { config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("fido", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "name and nickname are different fields" } }); e.Locations.Add(new ErrorLocation(4, 21)); e.Locations.Add(new ErrorLocation(5, 21)); }); }); } [Fact] public void Conflicting_return_types_which_potentially_overlap() { ISchema schema = new ResultTypeValidationSchema(); const string query = @" { someBox { ...on IntBox { scalar } ...on NonNullStringBox1 { scalar } } } "; ShouldFailRule(config => { config.Schema = schema; config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("scalar", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "they return conflicting types Int and String!" } }); e.Locations.Add(new ErrorLocation(5, 29)); e.Locations.Add(new ErrorLocation(8, 29)); }); }); } [Fact] public void Compatible_return_shapes_on_different_return_types() { ISchema schema = new ResultTypeValidationSchema(); const string query = @" { someBox { ... on SomeBox { deepBox { unrelatedField } } ... on StringBox { deepBox { unrelatedField } } } } "; ShouldPassRule(config => { config.Schema = schema; config.Query = query; }); } [Fact] public void Disallows_differing_return_types_despite_no_overlap() { ISchema schema = new ResultTypeValidationSchema(); const string query = @" { someBox { ... on IntBox { scalar } ... on StringBox { scalar } } } "; ShouldFailRule(config => { config.Schema = schema; config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("scalar", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "they return conflicting types Int and String" } }); e.Locations.Add(new ErrorLocation(5, 29)); e.Locations.Add(new ErrorLocation(8, 29)); }); }); } [Fact] public void Reports_correctly_when_a_non_exclusive_follows_an_exclusive() { ISchema schema = new ResultTypeValidationSchema(); const string query = @" { someBox { ... on IntBox { deepBox { ...X } } } someBox { ... on StringBox { deepBox { ...Y } } } memoed: someBox { ... on IntBox { deepBox { ...X } } } memoed: someBox { ... on StringBox { deepBox { ...Y } } } other: someBox { ...X } other: someBox { ...Y } } fragment X on SomeBox { scalar } fragment Y on SomeBox { scalar: unrelatedField } "; ShouldFailRule(config => { config.Schema = schema; config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("other", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msgs = new List<OverlappingFieldsCanBeMerged.ConflictReason> { new OverlappingFieldsCanBeMerged.ConflictReason { Name = "scalar", Message = new OverlappingFieldsCanBeMerged.Message { Msg = "scalar and unrelatedField are different fields" } } } } }); e.Locations.Add(new ErrorLocation(31, 21)); e.Locations.Add(new ErrorLocation(39, 21)); e.Locations.Add(new ErrorLocation(34, 21)); e.Locations.Add(new ErrorLocation(42, 21)); }); }); } [Fact] public void Disallows_differing_return_type_nullability_despite_no_overlap() { ISchema schema = new ResultTypeValidationSchema(); const string query = @" { someBox { ... on NonNullStringBox1 { scalar } ... on StringBox { scalar } } } "; ShouldFailRule(config => { config.Schema = schema; config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("scalar", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "they return conflicting types String! and String" } }); e.Locations.Add(new ErrorLocation(5, 29)); e.Locations.Add(new ErrorLocation(8, 29)); }); }); } [Fact] public void Disallows_differing_return_type_list_despite_no_overlap() { ISchema schema = new ResultTypeValidationSchema(); string query = @" { someBox { ... on IntBox { box: listStringBox { scalar } } ... on StringBox { box: stringBox { scalar } } } } "; ShouldFailRule(config => { config.Schema = schema; config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("box", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "they return conflicting types [StringBox] and StringBox" } }); e.Locations.Add(new ErrorLocation(5, 29)); e.Locations.Add(new ErrorLocation(10, 29)); }); }); query = @" { someBox { ... on IntBox { box: stringBox { scalar } } ... on StringBox { box: listStringBox { scalar } } } } "; ShouldFailRule(config => { config.Schema = schema; config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("box", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "they return conflicting types StringBox and [StringBox]" } }); e.Locations.Add(new ErrorLocation(5, 29)); e.Locations.Add(new ErrorLocation(10, 29)); }); }); } [Fact] public void Disallows_differing_subfields() { ISchema schema = new ResultTypeValidationSchema(); const string query = @" { someBox { ... on IntBox { box: stringBox { val: scalar val: unrelatedField } } ... on StringBox { box: stringBox { val: scalar } } } } "; ShouldFailRule(config => { config.Schema = schema; config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("val", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msg = "scalar and unrelatedField are different fields" } }); e.Locations.Add(new ErrorLocation(6, 33)); e.Locations.Add(new ErrorLocation(7, 33)); }); }); } [Fact] public void Disallows_differing_deep_return_types_despite_no_overlap() { ISchema schema = new ResultTypeValidationSchema(); const string query = @" { someBox { ... on IntBox { box: stringBox { scalar } } ... on StringBox { box: intBox { scalar } } } } "; ShouldFailRule(config => { config.Schema = schema; config.Query = query; config.Error(e => { e.Message = OverlappingFieldsCanBeMergedError.FieldsConflictMessage("box", new OverlappingFieldsCanBeMerged.ConflictReason { Message = new OverlappingFieldsCanBeMerged.Message { Msgs = new List<OverlappingFieldsCanBeMerged.ConflictReason> { new OverlappingFieldsCanBeMerged.ConflictReason { Name = "scalar", Message = new OverlappingFieldsCanBeMerged.Message { Msg = "they return conflicting types String and Int" } } } } }); e.Locations.Add(new ErrorLocation(5, 29)); e.Locations.Add(new ErrorLocation(6, 33)); e.Locations.Add(new ErrorLocation(10, 29)); e.Locations.Add(new ErrorLocation(11, 33)); }); }); } [Fact] public void Allows_non_conflicting_overlapping_types() { ISchema schema = new ResultTypeValidationSchema(); const string query = @" { someBox { ... on IntBox { scalar: unrelatedField } ... on StringBox { scalar } } } "; ShouldPassRule(config => { config.Schema = schema; config.Query = query; }); } [Fact] public void Same_wrapped_scalar_return_types() { ISchema schema = new ResultTypeValidationSchema(); const string query = @" { someBox { ...on NonNullStringBox1 { scalar } ...on NonNullStringBox2 { scalar } } } "; ShouldPassRule(config => { config.Schema = schema; config.Query = query; }); } [Fact] public void Allows_inline_typeless_fragments() { ISchema schema = new ResultTypeValidationSchema(); const string query = @" { a ... { a } } "; ShouldPassRule(config => { config.Schema = schema; config.Query = query; }); } [Fact] public void Ignores_unknown_types() { ISchema schema = new ResultTypeValidationSchema(); const string query = @" { someBox { ...on UnknownType { scalar } ...on NonNullStringBox2 { scalar } } } "; ShouldPassRule(config => { config.Schema = schema; config.Query = query; }); } } }
// ----------------------------------------------------------------------- // <copyright file="DependencyObject.cs" company="Steven Kirk"> // Copyright 2013 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Avalonia { using System; using System.Collections.Generic; using System.Linq; using Avalonia.Data; using Avalonia.Media; using Avalonia.Threading; public class DependencyObject : DispatcherObject, IObservableDependencyObject { private static Dictionary<Type, Dictionary<string, DependencyProperty>> propertyDeclarations = new Dictionary<Type, Dictionary<string, DependencyProperty>>(); private Dictionary<DependencyProperty, object> properties = new Dictionary<DependencyProperty, object>(); private Dictionary<DependencyProperty, BindingExpressionBase> propertyBindings = new Dictionary<DependencyProperty, BindingExpressionBase>(); private Dictionary<string, List<DependencyPropertyChangedEventHandler>> propertyChangedHandlers = new Dictionary<string, List<DependencyPropertyChangedEventHandler>>(); private DependencyObject dependencyParent; public bool IsSealed { get { return false; } } public DependencyObjectType DependencyObjectType { get { return DependencyObjectType.FromSystemType(this.GetType()); } } internal DependencyObject DependencyParent { get { return this.dependencyParent; } set { if (this.dependencyParent != value) { DependencyProperty[] inheriting = this.GetInheritingProperties().ToArray(); Dictionary<DependencyProperty, object> oldValues = new Dictionary<DependencyProperty, object>(); foreach (DependencyProperty dp in inheriting) { oldValues[dp] = this.GetValue(dp); } this.dependencyParent = value; foreach (DependencyProperty dp in inheriting) { object oldValue = oldValues[dp]; object newValue = this.GetValue(dp); if (!this.AreEqual(oldValues[dp], newValue)) { DependencyPropertyChangedEventArgs e = new DependencyPropertyChangedEventArgs( dp, oldValue, newValue); this.OnPropertyChanged(e); } } } } } void IObservableDependencyObject.AttachPropertyChangedHandler( string propertyName, DependencyPropertyChangedEventHandler handler) { List<DependencyPropertyChangedEventHandler> handlers; if (!this.propertyChangedHandlers.TryGetValue(propertyName, out handlers)) { handlers = new List<DependencyPropertyChangedEventHandler>(); this.propertyChangedHandlers.Add(propertyName, handlers); } handlers.Add(handler); } void IObservableDependencyObject.RemovePropertyChangedHandler( string propertyName, DependencyPropertyChangedEventHandler handler) { List<DependencyPropertyChangedEventHandler> handlers; if (this.propertyChangedHandlers.TryGetValue(propertyName, out handlers)) { handlers.Remove(handler); } } public void ClearValue(DependencyProperty dp) { if (this.IsSealed) { throw new InvalidOperationException("Cannot manipulate property values on a sealed DependencyObject"); } this.properties[dp] = null; } public void ClearValue(DependencyPropertyKey key) { this.ClearValue(key.DependencyProperty); } public void CoerceValue(DependencyProperty dp) { PropertyMetadata pm = dp.GetMetadata(this); if (pm.CoerceValueCallback != null) { pm.CoerceValueCallback(this, this.GetValue(dp)); } } public LocalValueEnumerator GetLocalValueEnumerator() { return new LocalValueEnumerator(this.properties); } public object GetValue(DependencyProperty dp) { object val; if (!this.properties.TryGetValue(dp, out val)) { val = this.GetDefaultValue(dp); if (val == null && dp.PropertyType.IsValueType) { val = Activator.CreateInstance(dp.PropertyType); } } return val; } public void InvalidateProperty(DependencyProperty dp) { BindingExpressionBase binding; if (this.propertyBindings.TryGetValue(dp, out binding)) { object oldValue = this.GetValue(dp); object newValue = binding.GetValue(); this.SetValueInternal(dp, oldValue, newValue); } } public object ReadLocalValue(DependencyProperty dp) { object val = this.properties[dp]; return val == null ? DependencyProperty.UnsetValue : val; } public void SetBinding(DependencyProperty dp, string path) { this.SetBinding(dp, new Binding(path)); } public void SetBinding(DependencyProperty dp, BindingBase binding) { Binding b = binding as Binding; if (b == null) { throw new NotSupportedException("Unsupported binding type."); } this.SetBinding(dp, b); } [AvaloniaSpecific] public BindingExpression SetBinding(DependencyProperty dp, Binding binding) { PropertyPathParser pathParser = new PropertyPathParser(); BindingExpression expression = new BindingExpression(pathParser, this, dp, binding); object oldValue = this.GetValue(dp); object newValue = expression.GetValue(); this.propertyBindings.Add(dp, expression); this.SetValueInternal(dp, oldValue, newValue); return expression; } public void SetValue(DependencyProperty dp, object value) { if (this.IsSealed) { throw new InvalidOperationException("Cannot manipulate property values on a sealed DependencyObject."); } if (value != DependencyProperty.UnsetValue && !dp.IsValidType(value)) { throw new ArgumentException("Value is not of the correct type for this DependencyProperty."); } if (dp.ValidateValueCallback != null && !dp.ValidateValueCallback(value)) { throw new Exception("Value does not validate."); } object oldValue = this.GetValue(dp); this.propertyBindings.Remove(dp); this.SetValueInternal(dp, oldValue, value); } public void SetValue(DependencyPropertyKey key, object value) { this.SetValue(key.DependencyProperty, value); } internal static IEnumerable<DependencyProperty> GetAllProperties(Type type) { Type t = type; while (t != null) { Dictionary<string, DependencyProperty> list; if (propertyDeclarations.TryGetValue(t, out list)) { foreach (DependencyProperty dp in list.Values) { yield return dp; } } t = t.BaseType; } } internal static DependencyProperty GetPropertyFromName(Type type, string name) { Dictionary<string, DependencyProperty> list; DependencyProperty result; Type t = type; while (t != null) { if (propertyDeclarations.TryGetValue(t, out list)) { if (list.TryGetValue(name, out result)) { return result; } } t = t.BaseType; } throw new KeyNotFoundException(string.Format( "Dependency property '{0}' could not be found on type '{1}'.", name, type.FullName)); } internal static void Register(Type t, DependencyProperty dp) { Dictionary<string, DependencyProperty> typeDeclarations; if (!propertyDeclarations.TryGetValue(t, out typeDeclarations)) { typeDeclarations = new Dictionary<string, DependencyProperty>(); propertyDeclarations.Add(t, typeDeclarations); } if (!typeDeclarations.ContainsKey(dp.Name)) { typeDeclarations[dp.Name] = dp; } else { throw new ArgumentException("A property named " + dp.Name + " already exists on " + t.Name); } } internal bool IsRegistered(Type t, DependencyProperty dp) { return GetAllProperties(t).Contains(dp); } internal bool IsUnset(DependencyProperty dependencyProperty) { return !this.properties.ContainsKey(dependencyProperty); } protected virtual void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { PropertyMetadata pm = e.Property.GetMetadata(this); if (pm != null) { if (pm.PropertyChangedCallback != null) { pm.PropertyChangedCallback(this, e); } } List<DependencyPropertyChangedEventHandler> handlers; if (this.propertyChangedHandlers.TryGetValue(e.Property.Name, out handlers)) { foreach (var handler in handlers.ToArray()) { handler(this, e); } } FrameworkPropertyMetadata metadata = e.Property.GetMetadata(this) as FrameworkPropertyMetadata; UIElement uiElement = this as UIElement; if (metadata != null && uiElement != null) { if (metadata.AffectsArrange) { uiElement.InvalidateArrange(); } if (metadata.AffectsMeasure) { uiElement.InvalidateMeasure(); } if (metadata.AffectsRender) { uiElement.InvalidateVisual(); } if (metadata.Inherits) { foreach (DependencyObject child in VisualTreeHelper.GetChildren(this)) { child.InheritedValueChanged(e); } } } } protected virtual bool ShouldSerializeProperty(DependencyProperty dp) { throw new NotImplementedException(); } private bool AreEqual(object a, object b) { return object.Equals(a, b); } private object GetDefaultValue(DependencyProperty dp) { PropertyMetadata metadata = dp.GetMetadata(this); FrameworkPropertyMetadata frameworkMetadata = metadata as FrameworkPropertyMetadata; object result = metadata.DefaultValue; if (frameworkMetadata != null && frameworkMetadata.Inherits) { if (this.dependencyParent != null) { result = this.dependencyParent.GetValue(dp); } } return result; } private IEnumerable<DependencyProperty> GetInheritingProperties() { foreach (DependencyProperty dp in GetAllProperties(this.GetType())) { FrameworkPropertyMetadata metadata = dp.GetMetadata(this.GetType()) as FrameworkPropertyMetadata; if (metadata != null && metadata.Inherits) { yield return dp; } } } private void InheritedValueChanged(DependencyPropertyChangedEventArgs e) { if (this.IsRegistered(this.GetType(), e.Property) && !this.properties.ContainsKey(e.Property)) { this.OnPropertyChanged(e); } else { foreach (DependencyObject child in VisualTreeHelper.GetChildren(this)) { child.InheritedValueChanged(e); } } } private void SetValueInternal(DependencyProperty dp, object oldValue, object newValue) { if (newValue != DependencyProperty.UnsetValue && dp.IsValidValue(newValue)) { this.properties[dp] = newValue; } else { this.properties.Remove(dp); newValue = this.GetValue(dp); } if (!this.AreEqual(oldValue, newValue)) { this.OnPropertyChanged(new DependencyPropertyChangedEventArgs(dp, oldValue, newValue)); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// Options for creating and running scripts. /// </summary> public sealed class ScriptOptions { public static readonly ScriptOptions Default = new ScriptOptions( path: "", references: ImmutableArray<MetadataReference>.Empty, namespaces: ImmutableArray<string>.Empty, metadataResolver: RuntimeMetadataReferenceResolver.Default, sourceResolver: SourceFileResolver.Default, isInteractive: true); /// <summary> /// An array of <see cref="MetadataReference"/>s to be added to the script. /// </summary> /// <remarks> /// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>). /// Unresolved references are resolved when the script is about to be executed /// (<see cref="Script.RunAsync(object, CancellationToken)"/>. /// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>. /// </remarks> public ImmutableArray<MetadataReference> MetadataReferences { get; private set; } /// <summary> /// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives. /// </summary> public MetadataReferenceResolver MetadataResolver { get; private set; } /// <summary> /// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive. /// </summary> public SourceReferenceResolver SourceResolver { get; private set; } /// <summary> /// The namespaces automatically imported by the script. /// </summary> public ImmutableArray<string> Namespaces { get; private set; } /// <summary> /// The path to the script source if it originated from a file, empty otherwise. /// </summary> public string Path { get; private set; } /// <summary> /// True if the script is interactive. /// Interactive scripts may contain a final expression whose value is returned when the script is run. /// </summary> public bool IsInteractive { get; private set; } private ScriptOptions( string path, ImmutableArray<MetadataReference> references, ImmutableArray<string> namespaces, MetadataReferenceResolver metadataResolver, SourceReferenceResolver sourceResolver, bool isInteractive) { Debug.Assert(path != null); Debug.Assert(!references.IsDefault); Debug.Assert(!namespaces.IsDefault); Debug.Assert(metadataResolver != null); Debug.Assert(sourceResolver != null); Path = path; MetadataReferences = references; Namespaces = namespaces; MetadataResolver = metadataResolver; SourceResolver = sourceResolver; IsInteractive = isInteractive; } private ScriptOptions(ScriptOptions other) : this(path: other.Path, references: other.MetadataReferences, namespaces: other.Namespaces, metadataResolver: other.MetadataResolver, sourceResolver: other.SourceResolver, isInteractive: other.IsInteractive) { } /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Path"/> changed. /// </summary> public ScriptOptions WithPath(string path) => (Path == path) ? this : new ScriptOptions(this) { Path = path ?? "" }; private static MetadataReference CreateUnresolvedReference(string reference) => new UnresolvedMetadataReference(reference, MetadataReferenceProperties.Assembly); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) => MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) => WithReferences(ToImmutableArrayChecked(references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params MetadataReference[] references) => WithReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) => WithReferences(ConcatChecked(MetadataReferences, references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params MetadataReference[] references) => AddReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<Assembly> references) => WithReferences(SelectChecked(references, nameof(references), MetadataReference.CreateFromAssemblyInternal)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params Assembly[] references) => WithReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<Assembly> references) => AddReferences(SelectChecked(references, nameof(references), MetadataReference.CreateFromAssemblyInternal)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(params Assembly[] references) => AddReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<string> references) => WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params string[] references) => WithReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<string> references) => AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params string[] references) => AddReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="MetadataResolver"/> set to the default metadata resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving assembly file names.</param> /// <remarks> /// The default resolver looks up references in specified <paramref name="searchPaths"/>, in NuGet packages and in Global Assembly Cache (if available on the current platform). /// </remarks> public ScriptOptions WithDefaultMetadataResolution(ImmutableArray<string> searchPaths) { var resolver = new RuntimeMetadataReferenceResolver( ToImmutableArrayChecked(searchPaths, nameof(searchPaths)), baseDirectory: null); return new ScriptOptions(this) { MetadataResolver = resolver }; } /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="MetadataResolver"/> set to the default metadata resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving assembly file names.</param> /// <remarks> /// The default resolver looks up references in specified <paramref name="searchPaths"/>, in NuGet packages and in Global Assembly Cache (if available on the current platform). /// </remarks> public ScriptOptions WithDefaultMetadataResolution(IEnumerable<string> searchPaths) => WithDefaultMetadataResolution(searchPaths.AsImmutableOrEmpty()); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="MetadataResolver"/> set to the default metadata resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving assembly file names.</param> /// <remarks> /// The default resolver looks up references in specified <paramref name="searchPaths"/>, in NuGet packages and in Global Assembly Cache (if available on the current platform). /// </remarks> public ScriptOptions WithDefaultMetadataResolution(params string[] searchPaths) => WithDefaultMetadataResolution(searchPaths.AsImmutableOrEmpty()); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>. /// </summary> public ScriptOptions WithCustomMetadataResolution(MetadataReferenceResolver resolver) => MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="SourceResolver"/> set to the default source resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving script file names.</param> /// <remarks> /// The default resolver looks up scripts in specified <paramref name="searchPaths"/> and in NuGet packages. /// </remarks> public ScriptOptions WithDefaultSourceResolution(ImmutableArray<string> searchPaths) { var resolver = new SourceFileResolver( ToImmutableArrayChecked(searchPaths, nameof(searchPaths)), baseDirectory: null); return new ScriptOptions(this) { SourceResolver = resolver }; } /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="SourceResolver"/> set to the default source resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving script file names.</param> /// <remarks> /// The default resolver looks up scripts in specified <paramref name="searchPaths"/> and in NuGet packages. /// </remarks> public ScriptOptions WithDefaultSourceResolution(IEnumerable<string> searchPaths) => WithDefaultSourceResolution(searchPaths.AsImmutableOrEmpty()); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="SourceResolver"/> set to the default source resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving script file names.</param> /// <remarks> /// The default resolver looks up scripts in specified <paramref name="searchPaths"/> and in NuGet packages. /// </remarks> public ScriptOptions WithDefaultSourceResolution(params string[] searchPaths) => WithDefaultSourceResolution(searchPaths.AsImmutableOrEmpty()); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>. /// </summary> public ScriptOptions WithCustomSourceResolution(SourceReferenceResolver resolver) => SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the namespaces changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="namespaces"/> is null or contains a null reference.</exception> public ScriptOptions WithNamespaces(ImmutableArray<string> namespaces) => Namespaces.Equals(namespaces) ? this : new ScriptOptions(this) { Namespaces = CheckImmutableArray(namespaces, nameof(namespaces)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the namespaces changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="namespaces"/> is null or contains a null reference.</exception> public ScriptOptions WithNamespaces(IEnumerable<string> namespaces) => WithNamespaces(ToImmutableArrayChecked(namespaces, nameof(namespaces))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the namespaces changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="namespaces"/> is null or contains a null reference.</exception> public ScriptOptions WithNamespaces(params string[] namespaces) => WithNamespaces((IEnumerable<string>)namespaces); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with namespaces added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="namespaces"/> is null or contains a null reference.</exception> public ScriptOptions AddNamespaces(IEnumerable<string> namespaces) => WithNamespaces(ConcatChecked(Namespaces, namespaces, nameof(namespaces))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with namespaces added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="namespaces"/> is null or contains a null reference.</exception> public ScriptOptions AddNamespaces(params string[] namespaces) => AddNamespaces((IEnumerable<string>)namespaces); /// <summary> /// Create a new <see cref="ScriptOptions"/> with the interactive state specified. /// Interactive scripts may contain a final expression whose value is returned when the script is run. /// </summary> public ScriptOptions WithIsInteractive(bool isInteractive) => IsInteractive == isInteractive ? this : new ScriptOptions(this) { IsInteractive = isInteractive }; #region Parameter Validation private static ImmutableArray<T> CheckImmutableArray<T>(ImmutableArray<T> items, string parameterName) { if (items.IsDefault) { throw new ArgumentNullException(parameterName); } for (int i = 0; i < items.Length; i++) { if (items[i] == null) { throw new ArgumentNullException($"{parameterName}[{i}]"); } } return items; } private static ImmutableArray<T> ToImmutableArrayChecked<T>(IEnumerable<T> items, string parameterName) where T : class { var builder = ArrayBuilder<T>.GetInstance(); AddRangeChecked(builder, items, parameterName); return builder.ToImmutableAndFree(); } private static ImmutableArray<T> ConcatChecked<T>(ImmutableArray<T> existing, IEnumerable<T> items, string parameterName) where T : class { var builder = ArrayBuilder<T>.GetInstance(); builder.AddRange(existing); AddRangeChecked(builder, items, parameterName); return builder.ToImmutableAndFree(); } private static void AddRangeChecked<T>(ArrayBuilder<T> builder, IEnumerable<T> items, string parameterName) where T : class { RequireNonNull(items, parameterName); foreach (var item in items) { if (item == null) { throw new ArgumentNullException($"{parameterName}[{builder.Count}]"); } builder.Add(item); } } private static IEnumerable<S> SelectChecked<T, S>(IEnumerable<T> items, string parameterName, Func<T, S> selector) where T : class where S : class { RequireNonNull(items, parameterName); return items.Select(item => (item != null) ? selector(item) : null); } private static void RequireNonNull<T>(IEnumerable<T> items, string parameterName) { if (items == null || items is ImmutableArray<T> && ((ImmutableArray<T>)items).IsDefault) { throw new ArgumentNullException(parameterName); } } #endregion } }
using MatterHackers.Agg.Image.ThresholdFunctions; using MatterHackers.Agg.RasterizerScanline; using MatterHackers.VectorMath; //---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# port by: Lars Brubaker // [email protected] // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: [email protected] // [email protected] // http://www.antigrain.com //---------------------------------------------------------------------------- using System; using System.Collections.Generic; namespace MatterHackers.Agg.Image { public class ImageBuffer : IImageByte { public const int OrderB = 0; public const int OrderG = 1; public const int OrderR = 2; public const int OrderA = 3; internal class InternalImageGraphics2D : ImageGraphics2D { internal InternalImageGraphics2D(ImageBuffer owner) : base() { ScanlineRasterizer rasterizer = new ScanlineRasterizer(); ImageClippingProxy imageClippingProxy = new ImageClippingProxy(owner); Initialize(imageClippingProxy, rasterizer); ScanlineCache = new ScanlineCachePacked8(); } } bool? _hasTransparency = null; public bool HasTransparency { get { if(_hasTransparency == null) { _hasTransparency = false; var buffer = GetBuffer(); // check if the image has any alpha set to something other than 255 for (int y=0; y<Height; y++) { var yOffset = GetBufferOffsetY(y); for (int x=0; x<Width; x++) { // get the alpha at this pixel if(buffer[yOffset + x + 3] < 255) { _hasTransparency = true; x = Width; y = Height; } } } } return _hasTransparency.Value; } } protected int[] yTableArray; protected int[] xTableArray; private byte[] m_ByteBuffer; private int bufferOffset; // the beginning of the image in this buffer private int bufferFirstPixel; // Pointer to first pixel depending on strideInBytes and image position private int strideInBytes; // Number of bytes per row. Can be < 0 private int m_DistanceInBytesBetweenPixelsInclusive; private IRecieveBlenderByte recieveBlender; private const int base_mask = 255; public event EventHandler ImageChanged; public int ChangedCount { get; private set; } public void MarkImageChanged() { // mark this unchecked as we don't want to throw an exception if this rolls over. unchecked { ChangedCount++; _hasTransparency = null; ImageChanged?.Invoke(this, null); } } public ImageBuffer() { } public ImageBuffer(IRecieveBlenderByte recieveBlender) { SetRecieveBlender(recieveBlender); } public ImageBuffer(IImageByte sourceImage, IRecieveBlenderByte recieveBlender) { SetDimmensionAndFormat(sourceImage.Width, sourceImage.Height, sourceImage.StrideInBytes(), sourceImage.BitDepth, sourceImage.GetBytesBetweenPixelsInclusive(), true); int offset = sourceImage.GetBufferOffsetXY(0, 0); byte[] buffer = sourceImage.GetBuffer(); byte[] newBuffer = new byte[buffer.Length]; agg_basics.memcpy(newBuffer, offset, buffer, offset, buffer.Length - offset); SetBuffer(newBuffer, offset); SetRecieveBlender(recieveBlender); } public ImageBuffer(ImageBuffer sourceImage) { SetDimmensionAndFormat(sourceImage.Width, sourceImage.Height, sourceImage.StrideInBytes(), sourceImage.BitDepth, sourceImage.GetBytesBetweenPixelsInclusive(), true); int offset = sourceImage.GetBufferOffsetXY(0, 0); byte[] buffer = sourceImage.GetBuffer(); byte[] newBuffer = new byte[buffer.Length]; agg_basics.memcpy(newBuffer, offset, buffer, offset, buffer.Length - offset); SetBuffer(newBuffer, offset); SetRecieveBlender(sourceImage.GetRecieveBlender()); } public ImageBuffer(int width, int height, int bitsPerPixel = 32) { Allocate(width, height, width* (bitsPerPixel / 8), bitsPerPixel); SetRecieveBlender(new BlenderBGRA()); } public ImageBuffer(int width, int height, int bitsPerPixel, IRecieveBlenderByte recieveBlender) { Allocate(width, height, width * (bitsPerPixel / 8), bitsPerPixel); SetRecieveBlender(recieveBlender); } public void Allocate(int width, int height, int bitsPerPixel, IRecieveBlenderByte recieveBlender) { Allocate(width, height, width * (bitsPerPixel / 8), bitsPerPixel); SetRecieveBlender(recieveBlender); } #if false public ImageBuffer(IImage image, IBlender blender, GammaLookUpTable gammaTable) { unsafe { AttachBuffer(image.GetBuffer(), image.Width(), image.Height(), image.StrideInBytes(), image.BitDepth, image.GetDistanceBetweenPixelsInclusive()); } SetRecieveBlender(blender); } #endif public ImageBuffer(IImageByte sourceImageToCopy, IRecieveBlenderByte blender, int distanceBetweenPixelsInclusive, int bufferOffset, int bitsPerPixel) { SetDimmensionAndFormat(sourceImageToCopy.Width, sourceImageToCopy.Height, sourceImageToCopy.StrideInBytes(), bitsPerPixel, distanceBetweenPixelsInclusive, true); int offset = sourceImageToCopy.GetBufferOffsetXY(0, 0); byte[] buffer = sourceImageToCopy.GetBuffer(); byte[] newBuffer = new byte[buffer.Length]; agg_basics.memcpy(newBuffer, offset, buffer, offset, buffer.Length - offset); SetBuffer(newBuffer, offset + bufferOffset); SetRecieveBlender(blender); } /// <summary> /// This will create a new ImageBuffer that references the same memory as the image that you took the sub image from. /// It will modify the original main image when you draw to it. /// </summary> /// <param name="imageContainingSubImage"></param> /// <param name="subImageBounds"></param> /// <returns></returns> public static ImageBuffer NewSubImageReference(IImageByte imageContainingSubImage, RectangleDouble subImageBounds) { ImageBuffer subImage = new ImageBuffer(); if (subImageBounds.Left < 0 || subImageBounds.Bottom < 0 || subImageBounds.Right > imageContainingSubImage.Width || subImageBounds.Top > imageContainingSubImage.Height || subImageBounds.Left >= subImageBounds.Right || subImageBounds.Bottom >= subImageBounds.Top) { throw new ArgumentException("The subImageBounds must be on the image and valid."); } int left = Math.Max(0, (int)Math.Floor(subImageBounds.Left)); int bottom = Math.Max(0, (int)Math.Floor(subImageBounds.Bottom)); int width = Math.Min(imageContainingSubImage.Width - left, (int)subImageBounds.Width); int height = Math.Min(imageContainingSubImage.Height - bottom, (int)subImageBounds.Height); int bufferOffsetToFirstPixel = imageContainingSubImage.GetBufferOffsetXY(left, bottom); subImage.AttachBuffer(imageContainingSubImage.GetBuffer(), bufferOffsetToFirstPixel, width, height, imageContainingSubImage.StrideInBytes(), imageContainingSubImage.BitDepth, imageContainingSubImage.GetBytesBetweenPixelsInclusive()); subImage.SetRecieveBlender(imageContainingSubImage.GetRecieveBlender()); return subImage; } public void AttachBuffer(byte[] buffer, int bufferOffset, int width, int height, int strideInBytes, int bitDepth, int distanceInBytesBetweenPixelsInclusive) { m_ByteBuffer = null; SetDimmensionAndFormat(width, height, strideInBytes, bitDepth, distanceInBytesBetweenPixelsInclusive, false); SetBuffer(buffer, bufferOffset); } public void Attach(IImageByte sourceImage, IRecieveBlenderByte recieveBlender, int distanceBetweenPixelsInclusive, int bufferOffset, int bitsPerPixel) { SetDimmensionAndFormat(sourceImage.Width, sourceImage.Height, sourceImage.StrideInBytes(), bitsPerPixel, distanceBetweenPixelsInclusive, false); int offset = sourceImage.GetBufferOffsetXY(0, 0); byte[] buffer = sourceImage.GetBuffer(); SetBuffer(buffer, offset + bufferOffset); SetRecieveBlender(recieveBlender); } public void Attach(IImageByte sourceImage, IRecieveBlenderByte recieveBlender) { Attach(sourceImage, recieveBlender, sourceImage.GetBytesBetweenPixelsInclusive(), 0, sourceImage.BitDepth); } public bool Attach(IImageByte sourceImage, int x1, int y1, int x2, int y2) { m_ByteBuffer = null; DettachBuffer(); if (x1 > x2 || y1 > y2) { throw new Exception("You need to have your x1 and y1 be the lower left corner of your sub image."); } RectangleInt boundsRect = new RectangleInt(x1, y1, x2, y2); if (boundsRect.clip(new RectangleInt(0, 0, (int)sourceImage.Width - 1, (int)sourceImage.Height - 1))) { SetDimmensionAndFormat(boundsRect.Width, boundsRect.Height, sourceImage.StrideInBytes(), sourceImage.BitDepth, sourceImage.GetBytesBetweenPixelsInclusive(), false); int bufferOffset = sourceImage.GetBufferOffsetXY(boundsRect.Left, boundsRect.Bottom); byte[] buffer = sourceImage.GetBuffer(); SetBuffer(buffer, bufferOffset); return true; } return false; } public void SetAlpha(byte value) { if (BitDepth != 32) { throw new Exception("You don't have alpha channel to set. Your image has a bit depth of " + BitDepth.ToString() + "."); } int numPixels = Width * Height; int offset; byte[] buffer = GetBuffer(out offset); for (int i = 0; i < numPixels; i++) { buffer[offset + i * 4 + 3] = value; } } private void Deallocate() { if (m_ByteBuffer != null) { m_ByteBuffer = null; SetDimmensionAndFormat(0, 0, 0, 32, 4, true); } } public void Allocate(int inWidth, int inHeight, int inScanWidthInBytes, int bitsPerPixel) { if (bitsPerPixel != 32 && bitsPerPixel != 24 && bitsPerPixel != 8) { throw new Exception("Unsupported bits per pixel."); } if (inScanWidthInBytes < inWidth * (bitsPerPixel / 8)) { throw new Exception("Your scan width is not big enough to hold your width and height."); } SetDimmensionAndFormat(inWidth, inHeight, inScanWidthInBytes, bitsPerPixel, bitsPerPixel / 8, true); if (m_ByteBuffer == null || m_ByteBuffer.Length != strideInBytes * Height) { m_ByteBuffer = new byte[strideInBytes * Height]; SetUpLookupTables(); } if (yTableArray.Length != inHeight || xTableArray.Length != inWidth) { throw new Exception("The yTable and xTable should be allocated correctly at this point. Figure out what happened."); // LBB, don't fix this if you don't understand what it's trying to do. } } public MatterHackers.Agg.Graphics2D NewGraphics2D() { InternalImageGraphics2D imageRenderer = new InternalImageGraphics2D(this); imageRenderer.Rasterizer.SetVectorClipBox(0, 0, Width, Height); return imageRenderer; } public void CopyFrom(IImageByte sourceImage) { Allocate(sourceImage.Width, sourceImage.Height, sourceImage.StrideInBytesAbs(), sourceImage.BitDepth); // make sure we make an exact copy SetRecieveBlender(new BlenderBGRAExactCopy()); CopyFrom(sourceImage, sourceImage.GetBounds(), 0, 0); // then set the blender to what we expect SetRecieveBlender(sourceImage.GetRecieveBlender()); } protected void CopyFromNoClipping(IImageByte sourceImage, RectangleInt clippedSourceImageRect, int destXOffset, int destYOffset) { if (GetBytesBetweenPixelsInclusive() != BitDepth / 8 || sourceImage.GetBytesBetweenPixelsInclusive() != sourceImage.BitDepth / 8) { throw new Exception("WIP we only support packed pixel formats at this time."); } if (BitDepth == sourceImage.BitDepth) { int lengthInBytes = clippedSourceImageRect.Width * GetBytesBetweenPixelsInclusive(); int sourceOffset = sourceImage.GetBufferOffsetXY(clippedSourceImageRect.Left, clippedSourceImageRect.Bottom); byte[] sourceBuffer = sourceImage.GetBuffer(); int destOffset; byte[] destBuffer = GetPixelPointerXY(clippedSourceImageRect.Left + destXOffset, clippedSourceImageRect.Bottom + destYOffset, out destOffset); for (int i = 0; i < clippedSourceImageRect.Height; i++) { agg_basics.memmove(destBuffer, destOffset, sourceBuffer, sourceOffset, lengthInBytes); sourceOffset += sourceImage.StrideInBytes(); destOffset += StrideInBytes(); } } else { bool haveConversion = true; switch (sourceImage.BitDepth) { case 24: switch (BitDepth) { case 32: { int numPixelsToCopy = clippedSourceImageRect.Width; for (int i = clippedSourceImageRect.Bottom; i < clippedSourceImageRect.Top; i++) { int sourceOffset = sourceImage.GetBufferOffsetXY(clippedSourceImageRect.Left, clippedSourceImageRect.Bottom + i); byte[] sourceBuffer = sourceImage.GetBuffer(); int destOffset; byte[] destBuffer = GetPixelPointerXY( clippedSourceImageRect.Left + destXOffset, clippedSourceImageRect.Bottom + i + destYOffset, out destOffset); for (int x = 0; x < numPixelsToCopy; x++) { destBuffer[destOffset++] = sourceBuffer[sourceOffset++]; destBuffer[destOffset++] = sourceBuffer[sourceOffset++]; destBuffer[destOffset++] = sourceBuffer[sourceOffset++]; destBuffer[destOffset++] = 255; } } } break; default: haveConversion = false; break; } break; default: haveConversion = false; break; } if (!haveConversion) { throw new NotImplementedException("You need to write the " + sourceImage.BitDepth.ToString() + " to " + BitDepth.ToString() + " conversion"); } } } public void CopyFrom(IImageByte sourceImage, RectangleInt sourceImageRect, int destXOffset, int destYOffset) { RectangleInt sourceImageBounds = sourceImage.GetBounds(); RectangleInt clippedSourceImageRect = new RectangleInt(); if (clippedSourceImageRect.IntersectRectangles(sourceImageRect, sourceImageBounds)) { RectangleInt destImageRect = clippedSourceImageRect; destImageRect.Offset(destXOffset, destYOffset); RectangleInt destImageBounds = GetBounds(); RectangleInt clippedDestImageRect = new RectangleInt(); if (clippedDestImageRect.IntersectRectangles(destImageRect, destImageBounds)) { // we need to make sure the source is also clipped to the dest. So, we'll copy this back to source and offset it. clippedSourceImageRect = clippedDestImageRect; clippedSourceImageRect.Offset(-destXOffset, -destYOffset); CopyFromNoClipping(sourceImage, clippedSourceImageRect, destXOffset, destYOffset); } } } public Vector2 OriginOffset { get; set; } /// <summary> /// Width in pixels /// </summary> public int Width { get; private set; } /// <summary> /// Height in pixels /// </summary> public int Height { get; private set; } public int StrideInBytes() { return strideInBytes; } public int StrideInBytesAbs() { return System.Math.Abs(strideInBytes); } public int GetBytesBetweenPixelsInclusive() { return m_DistanceInBytesBetweenPixelsInclusive; } public int BitDepth { get; private set; } public virtual RectangleInt GetBounds() { return new RectangleInt(-(int)OriginOffset.X, -(int)OriginOffset.Y, Width - (int)OriginOffset.X, Height - (int)OriginOffset.Y); } public IRecieveBlenderByte GetRecieveBlender() { return recieveBlender; } public void SetRecieveBlender(IRecieveBlenderByte value) { if (BitDepth != 0 && value != null && value.NumPixelBits != BitDepth) { throw new NotSupportedException("The blender has to support the bit depth of this image."); } recieveBlender = value; } private void SetUpLookupTables() { yTableArray = new int[Height]; for (int i = 0; i < Height; i++) { yTableArray[i] = i * strideInBytes; } xTableArray = new int[Width]; for (int i = 0; i < Width; i++) { xTableArray[i] = i * m_DistanceInBytesBetweenPixelsInclusive; } } public void InvertYLookupTable() { strideInBytes *= -1; bufferFirstPixel = bufferOffset; if (strideInBytes < 0) { int addAmount = -((int)((int)Height - 1) * strideInBytes); bufferFirstPixel = addAmount + bufferOffset; } SetUpLookupTables(); } /// <summary> /// Flip pixels in the Y axis /// </summary> public void FlipY() { byte[] buffer = GetBuffer(); for (int y = 0; y < Height / 2; y++) { int bottomBuffer = GetBufferOffsetY(y); int topBuffer = GetBufferOffsetY(Height - y - 1); for (int x = 0; x < StrideInBytes(); x++) { byte hold = buffer[bottomBuffer + x]; buffer[bottomBuffer + x] = buffer[topBuffer + x]; buffer[topBuffer + x] = hold; } } } /// <summary> /// Flip pixels in the X axis /// </summary> public void FlipX() { byte[] buffer = GetBuffer(); // Iterate each row, swapping pixels in x from outer to midpoint for (int y = 0; y < this.Height; y++) { for (int x = 0; x < this.Width / 2; x++) { int leftOffset = GetBufferOffsetXY(x, y); int rightOffset = GetBufferOffsetXY(this.Width - x - 1, y); // Hold byte leftBuffer0 = buffer[leftOffset + 0]; byte leftBuffer1 = buffer[leftOffset + 1]; byte leftBuffer2 = buffer[leftOffset + 2]; byte leftBuffer3 = buffer[leftOffset + 3]; // Swap buffer[leftOffset + 0] = buffer[rightOffset + 0]; buffer[leftOffset + 1] = buffer[rightOffset + 1]; buffer[leftOffset + 2] = buffer[rightOffset + 2]; buffer[leftOffset + 3] = buffer[rightOffset + 3]; buffer[rightOffset + 0] = leftBuffer0; buffer[rightOffset + 1] = leftBuffer1; buffer[rightOffset + 2] = leftBuffer2; buffer[rightOffset + 3] = leftBuffer3; } } } public void SetBuffer(byte[] byteBuffer, int bufferOffset) { if (byteBuffer.Length < Height * strideInBytes) { throw new Exception("Your buffer does not have enough room for your height and strideInBytes."); } m_ByteBuffer = byteBuffer; this.bufferOffset = bufferFirstPixel = bufferOffset; if (strideInBytes < 0) { int addAmount = -((int)((int)Height - 1) * strideInBytes); bufferFirstPixel = addAmount + bufferOffset; } SetUpLookupTables(); } private void DeallocateOrClearBuffer(int width, int height, int strideInBytes, int bitDepth, int distanceInBytesBetweenPixelsInclusive) { if (this.Width == width && this.Height == height && this.strideInBytes == strideInBytes && this.BitDepth == bitDepth && m_DistanceInBytesBetweenPixelsInclusive == distanceInBytesBetweenPixelsInclusive && m_ByteBuffer != null) { for (int i = 0; i < m_ByteBuffer.Length; i++) { m_ByteBuffer[i] = 0; } return; } else { Deallocate(); } } private void SetDimmensionAndFormat(int width, int height, int strideInBytes, int bitDepth, int distanceInBytesBetweenPixelsInclusive, bool doDeallocateOrClearBuffer) { if (doDeallocateOrClearBuffer) { DeallocateOrClearBuffer(width, height, strideInBytes, bitDepth, distanceInBytesBetweenPixelsInclusive); } this.Width = width; this.Height = height; this.strideInBytes = strideInBytes; this.BitDepth = bitDepth; if (distanceInBytesBetweenPixelsInclusive > 4) { throw new System.Exception("It looks like you are passing bits per pixel rather than distance in bytes."); } if (distanceInBytesBetweenPixelsInclusive < (bitDepth / 8)) { throw new Exception("You do not have enough room between pixels to support your bit depth."); } m_DistanceInBytesBetweenPixelsInclusive = distanceInBytesBetweenPixelsInclusive; if (strideInBytes < distanceInBytesBetweenPixelsInclusive * width) { throw new Exception("You do not have enough strideInBytes to hold the width and pixel distance you have described."); } } public void DettachBuffer() { m_ByteBuffer = null; Width = Height = strideInBytes = m_DistanceInBytesBetweenPixelsInclusive = 0; } public byte[] GetBuffer() { return m_ByteBuffer; } public byte[] GetBuffer(out int bufferOffset) { bufferOffset = this.bufferOffset; return m_ByteBuffer; } public byte[] GetPixelPointerY(int y, out int bufferOffset) { bufferOffset = bufferFirstPixel + yTableArray[y]; //bufferOffset = GetBufferOffsetXY(0, y); return m_ByteBuffer; } public byte[] GetPixelPointerXY(int x, int y, out int bufferOffset) { bufferOffset = GetBufferOffsetXY(x, y); return m_ByteBuffer; } public Color GetPixel(int x, int y) { return recieveBlender.PixelToColor(m_ByteBuffer, GetBufferOffsetXY(x, y)); } public int GetBufferOffsetY(int y) { return bufferFirstPixel + yTableArray[y] + xTableArray[0]; } public int GetBufferOffsetXY(int x, int y) { return bufferFirstPixel + yTableArray[y] + xTableArray[x]; } public void copy_pixel(int x, int y, byte[] c, int ByteOffset) { throw new System.NotImplementedException(); //byte* p = GetPixelPointerXY(x, y); //((int*)p)[0] = ((int*)c)[0]; //p[OrderR] = c.r; //p[OrderG] = c.g; //p[OrderB] = c.b; //p[OrderA] = c.a; } public void BlendPixel(int x, int y, Color c, byte cover) { throw new System.NotImplementedException(); /* cob_type::copy_or_blend_pix( (value_type*)m_rbuf->row_ptr(x, y, 1) + x + x + x, c.r, c.g, c.b, c.a, cover);*/ } public void SetPixel(int x, int y, Color color) { x -= (int)OriginOffset.X; y -= (int)OriginOffset.Y; recieveBlender.CopyPixels(GetBuffer(), GetBufferOffsetXY(x, y), color, 1); } public void copy_hline(int x, int y, int len, Color sourceColor) { int bufferOffset; byte[] buffer = GetPixelPointerXY(x, y, out bufferOffset); recieveBlender.CopyPixels(buffer, bufferOffset, sourceColor, len); } public void copy_vline(int x, int y, int len, Color sourceColor) { throw new NotImplementedException(); #if false int scanWidth = StrideInBytes(); byte* pDestBuffer = GetPixelPointerXY(x, y); do { m_Blender.CopyPixel(pDestBuffer, sourceColor); pDestBuffer = &pDestBuffer[scanWidth]; } while (--len != 0); #endif } public void blend_hline(int x1, int y, int x2, Color sourceColor, byte cover) { if (sourceColor.alpha != 0) { int len = x2 - x1 + 1; int bufferOffset; byte[] buffer = GetPixelPointerXY(x1, y, out bufferOffset); int alpha = (((int)(sourceColor.alpha) * (cover + 1)) >> 8); if (alpha == base_mask) { recieveBlender.CopyPixels(buffer, bufferOffset, sourceColor, len); } else { do { recieveBlender.BlendPixel(buffer, bufferOffset, new Color(sourceColor.red, sourceColor.green, sourceColor.blue, alpha)); bufferOffset += m_DistanceInBytesBetweenPixelsInclusive; } while (--len != 0); } } } public void blend_vline(int x, int y1, int y2, Color sourceColor, byte cover) { throw new NotImplementedException(); #if false int ScanWidth = StrideInBytes(); if (sourceColor.m_A != 0) { unsafe { int len = y2 - y1 + 1; byte* p = GetPixelPointerXY(x, y1); sourceColor.m_A = (byte)(((int)(sourceColor.m_A) * (cover + 1)) >> 8); if (sourceColor.m_A == base_mask) { byte cr = sourceColor.m_R; byte cg = sourceColor.m_G; byte cb = sourceColor.m_B; do { m_Blender.CopyPixel(p, sourceColor); p = &p[ScanWidth]; } while (--len != 0); } else { if (cover == 255) { do { m_Blender.BlendPixel(p, sourceColor); p = &p[ScanWidth]; } while (--len != 0); } else { do { m_Blender.BlendPixel(p, sourceColor); p = &p[ScanWidth]; } while (--len != 0); } } } } #endif } public void blend_solid_hspan(int x, int y, int len, Color sourceColor, byte[] covers, int coversIndex) { int colorAlpha = sourceColor.alpha; if (colorAlpha != 0) { unchecked { int bufferOffset; byte[] buffer = GetPixelPointerXY(x, y, out bufferOffset); do { int alpha = ((colorAlpha) * ((covers[coversIndex]) + 1)) >> 8; if (alpha == base_mask) { recieveBlender.CopyPixels(buffer, bufferOffset, sourceColor, 1); } else { recieveBlender.BlendPixel(buffer, bufferOffset, new Color(sourceColor.red, sourceColor.green, sourceColor.blue, alpha)); } bufferOffset += m_DistanceInBytesBetweenPixelsInclusive; coversIndex++; } while (--len != 0); } } } public void blend_solid_vspan(int x, int y, int len, Color sourceColor, byte[] covers, int coversIndex) { if (sourceColor.alpha != 0) { int ScanWidthInBytes = StrideInBytes(); unchecked { int bufferOffset = GetBufferOffsetXY(x, y); do { byte oldAlpha = sourceColor.alpha; sourceColor.alpha = (byte)(((int)(sourceColor.alpha) * ((int)(covers[coversIndex++]) + 1)) >> 8); if (sourceColor.alpha == base_mask) { recieveBlender.CopyPixels(m_ByteBuffer, bufferOffset, sourceColor, 1); } else { recieveBlender.BlendPixel(m_ByteBuffer, bufferOffset, sourceColor); } bufferOffset += ScanWidthInBytes; sourceColor.alpha = oldAlpha; } while (--len != 0); } } } public void copy_color_hspan(int x, int y, int len, Color[] colors, int colorsIndex) { int bufferOffset = GetBufferOffsetXY(x, y); do { recieveBlender.CopyPixels(m_ByteBuffer, bufferOffset, colors[colorsIndex], 1); ++colorsIndex; bufferOffset += m_DistanceInBytesBetweenPixelsInclusive; } while (--len != 0); } public void copy_color_vspan(int x, int y, int len, Color[] colors, int colorsIndex) { int bufferOffset = GetBufferOffsetXY(x, y); do { recieveBlender.CopyPixels(m_ByteBuffer, bufferOffset, colors[colorsIndex], 1); ++colorsIndex; bufferOffset += strideInBytes; } while (--len != 0); } public void blend_color_hspan(int x, int y, int len, Color[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { int bufferOffset = GetBufferOffsetXY(x, y); recieveBlender.BlendPixels(m_ByteBuffer, bufferOffset, colors, colorsIndex, covers, coversIndex, firstCoverForAll, len); } public void blend_color_vspan(int x, int y, int len, Color[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { int bufferOffset = GetBufferOffsetXY(x, y); int ScanWidth = StrideInBytesAbs(); if (!firstCoverForAll) { do { DoCopyOrBlend.BasedOnAlphaAndCover(recieveBlender, m_ByteBuffer, bufferOffset, colors[colorsIndex], covers[coversIndex++]); bufferOffset += ScanWidth; ++colorsIndex; } while (--len != 0); } else { if (covers[coversIndex] == 255) { do { DoCopyOrBlend.BasedOnAlpha(recieveBlender, m_ByteBuffer, bufferOffset, colors[colorsIndex]); bufferOffset += ScanWidth; ++colorsIndex; } while (--len != 0); } else { do { DoCopyOrBlend.BasedOnAlphaAndCover(recieveBlender, m_ByteBuffer, bufferOffset, colors[colorsIndex], covers[coversIndex]); bufferOffset += ScanWidth; ++colorsIndex; } while (--len != 0); } } } public void apply_gamma_inv(GammaLookUpTable g) { throw new System.NotImplementedException(); //for_each_pixel(apply_gamma_inv_rgba<color_type, order_type, GammaLut>(g)); } private bool IsPixelVisible(int x, int y) { Color pixelValue = GetRecieveBlender().PixelToColor(m_ByteBuffer, GetBufferOffsetXY(x, y)); return (pixelValue.Alpha0To255 != 0 || pixelValue.Red0To255 != 0 || pixelValue.Green0To255 != 0 || pixelValue.Blue0To255 != 0); } public void GetVisibleBounds(out RectangleInt visibleBounds) { visibleBounds = new RectangleInt(0, 0, Width, Height); // trim the bottom bool aPixelsIsVisible = false; for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { if (IsPixelVisible(x, y)) { visibleBounds.Bottom = y; y = Height; x = Width; aPixelsIsVisible = true; } } } // if we don't run into any pixels set for the top trim than there are no pixels set at all if (!aPixelsIsVisible) { visibleBounds.SetRect(0, 0, 0, 0); return; } // trim the bottom for (int y = Height - 1; y >= 0; y--) { for (int x = 0; x < Width; x++) { if (IsPixelVisible(x, y)) { visibleBounds.Top = y + 1; y = -1; x = Width; } } } // trim the left for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { if (IsPixelVisible(x, y)) { visibleBounds.Left = x; y = Height; x = Width; } } } // trim the right for (int x = Width - 1; x >= 0; x--) { for (int y = 0; y < Height; y++) { if (IsPixelVisible(x, y)) { visibleBounds.Right = x + 1; y = Height; x = -1; } } } } public void CropToVisible() { Vector2 OldOriginOffset = OriginOffset; //Move the HotSpot to 0, 0 so PPoint will work the way we want OriginOffset = new Vector2(0, 0); RectangleInt visibleBounds; GetVisibleBounds(out visibleBounds); if (visibleBounds.Width == Width && visibleBounds.Height == Height) { OriginOffset = OldOriginOffset; return; } // check if the Not0Rect has any size if (visibleBounds.Width > 0) { ImageBuffer TempImage = new ImageBuffer(); // set TempImage equal to the Not0Rect TempImage.Initialize(this, visibleBounds); // set the frame equal to the TempImage Initialize(TempImage); OriginOffset = new Vector2(-visibleBounds.Left + OldOriginOffset.X, -visibleBounds.Bottom + OldOriginOffset.Y); } else { Deallocate(); } } public static bool operator ==(ImageBuffer a, ImageBuffer b) { if ((object)a == null || (object)b == null) { if ((object)a == null && (object)b == null) { return true; } return false; } return a.Equals(b, 0); } public static bool operator !=(ImageBuffer a, ImageBuffer b) { bool areEqual = a == b; return !areEqual; } public override bool Equals(object obj) { if (obj.GetType() == typeof(ImageBuffer)) { return this == (ImageBuffer)obj; } return false; } public bool Equals(ImageBuffer b, int maxError) { if (Width == b.Width && Height == b.Height && BitDepth == b.BitDepth && StrideInBytes() == b.StrideInBytes() && OriginOffset == b.OriginOffset) { int bytesPerPixel = BitDepth / 8; int aDistanceBetweenPixels = GetBytesBetweenPixelsInclusive(); int bDistanceBetweenPixels = b.GetBytesBetweenPixelsInclusive(); byte[] aBuffer = GetBuffer(); byte[] bBuffer = b.GetBuffer(); for (int y = 0; y < Height; y++) { int aBufferOffset = GetBufferOffsetY(y); int bBufferOffset = b.GetBufferOffsetY(y); for (int x = 0; x < Width; x++) { for (int byteIndex = 0; byteIndex < bytesPerPixel; byteIndex++) { byte aByte = aBuffer[aBufferOffset + byteIndex]; byte bByte = bBuffer[bBufferOffset + byteIndex]; if (aByte < (bByte - maxError) || aByte > (bByte + maxError)) { return false; } } aBufferOffset += aDistanceBetweenPixels; bBufferOffset += bDistanceBetweenPixels; } } return true; } return false; } public bool Contains(ImageBuffer imageToFind, int maxError = 0) { int matchX; int matchY; return Contains(imageToFind, out matchX, out matchY, maxError); } public bool Contains(ImageBuffer imageToFind, out int matchX, out int matchY, int maxError = 0) { matchX = 0; matchY = 0; if (Width >= imageToFind.Width && Height >= imageToFind.Height && BitDepth == imageToFind.BitDepth) { int bytesPerPixel = BitDepth / 8; int aDistanceBetweenPixels = GetBytesBetweenPixelsInclusive(); int bDistanceBetweenPixels = imageToFind.GetBytesBetweenPixelsInclusive(); byte[] thisBuffer = GetBuffer(); byte[] containedBuffer = imageToFind.GetBuffer(); for (matchY = 0; matchY <= Height - imageToFind.Height; matchY++) { for (matchX = 0; matchX <= Width - imageToFind.Width; matchX++) { bool foundBadMatch = false; for (int imageToFindY = 0; imageToFindY < imageToFind.Height; imageToFindY++) { int thisBufferOffset = GetBufferOffsetXY(matchX, matchY + imageToFindY); int imageToFindBufferOffset = imageToFind.GetBufferOffsetY(imageToFindY); for (int imageToFindX = 0; imageToFindX < imageToFind.Width; imageToFindX++) { for (int byteIndex = 0; byteIndex < bytesPerPixel; byteIndex++) { byte aByte = thisBuffer[thisBufferOffset + byteIndex]; byte bByte = containedBuffer[imageToFindBufferOffset + byteIndex]; if (aByte < (bByte - maxError) || aByte > (bByte + maxError)) { foundBadMatch = true; byteIndex = bytesPerPixel; imageToFindX = imageToFind.Width; imageToFindY = imageToFind.Height; } } thisBufferOffset += aDistanceBetweenPixels; imageToFindBufferOffset += bDistanceBetweenPixels; } } if (!foundBadMatch) { return true; } } } } return false; } public bool FindLeastSquaresMatch(ImageBuffer imageToFind, double maxError) { Vector2 bestPosition; double bestLeastSquares; return FindLeastSquaresMatch(imageToFind, out bestPosition, out bestLeastSquares, maxError); } public bool FindLeastSquaresMatch(ImageBuffer imageToFind, out Vector2 bestPosition, out double bestLeastSquares, double maxError = double.MaxValue) { bestPosition = Vector2.Zero; bestLeastSquares = double.MaxValue; if (Width >= imageToFind.Width && Height >= imageToFind.Height && BitDepth == imageToFind.BitDepth) { int bytesPerPixel = BitDepth / 8; int aDistanceBetweenPixels = GetBytesBetweenPixelsInclusive(); int bDistanceBetweenPixels = imageToFind.GetBytesBetweenPixelsInclusive(); byte[] thisBuffer = GetBuffer(); byte[] containedBuffer = imageToFind.GetBuffer(); for (int matchY = 0; matchY <= Height - imageToFind.Height; matchY++) { for (int matchX = 0; matchX <= Width - imageToFind.Width; matchX++) { double currentLeastSquares = 0; for (int imageToFindY = 0; imageToFindY < imageToFind.Height; imageToFindY++) { int thisBufferOffset = GetBufferOffsetXY(matchX, matchY + imageToFindY); int imageToFindBufferOffset = imageToFind.GetBufferOffsetY(imageToFindY); for (int imageToFindX = 0; imageToFindX < imageToFind.Width; imageToFindX++) { for (int byteIndex = 0; byteIndex < bytesPerPixel; byteIndex++) { byte aByte = thisBuffer[thisBufferOffset + byteIndex]; byte bByte = containedBuffer[imageToFindBufferOffset + byteIndex]; int difference = (int)aByte - (int)bByte; currentLeastSquares += difference * difference; } thisBufferOffset += aDistanceBetweenPixels; imageToFindBufferOffset += bDistanceBetweenPixels; if (currentLeastSquares > maxError) { // stop checking we have too much error. imageToFindX = imageToFind.Width; imageToFindY = imageToFind.Height; } } } if (currentLeastSquares < bestLeastSquares) { bestPosition = new Vector2(matchX, matchY); bestLeastSquares = currentLeastSquares; if (maxError > currentLeastSquares) { maxError = currentLeastSquares; if (currentLeastSquares == 0) { return true; } } } } } } return bestLeastSquares <= maxError; } public override int GetHashCode() { // This might be hard to make fast and useful. return m_ByteBuffer.GetHashCode() ^ bufferOffset.GetHashCode() ^ bufferFirstPixel.GetHashCode(); } public RectangleInt GetBoundingRect() { RectangleInt boundingRect = new RectangleInt(0, 0, Width, Height); boundingRect.Offset((int)OriginOffset.X, (int)OriginOffset.Y); return boundingRect; } private void Initialize(ImageBuffer sourceImage) { RectangleInt sourceBoundingRect = sourceImage.GetBoundingRect(); Initialize(sourceImage, sourceBoundingRect); OriginOffset = sourceImage.OriginOffset; } private void Initialize(ImageBuffer sourceImage, RectangleInt boundsToCopyFrom) { if (sourceImage == this) { throw new Exception("We do not create a temp buffer for this to work. You must have a source distinct from the dest."); } Deallocate(); Allocate(boundsToCopyFrom.Width, boundsToCopyFrom.Height, boundsToCopyFrom.Width * sourceImage.BitDepth / 8, sourceImage.BitDepth); SetRecieveBlender(sourceImage.GetRecieveBlender()); if (Width != 0 && Height != 0) { RectangleInt DestRect = new RectangleInt(0, 0, boundsToCopyFrom.Width, boundsToCopyFrom.Height); RectangleInt AbsoluteSourceRect = boundsToCopyFrom; // The first thing we need to do is make sure the frame is cleared. LBB [3/15/2004] MatterHackers.Agg.Graphics2D graphics2D = NewGraphics2D(); graphics2D.Clear(new Color(0, 0, 0, 0)); int x = -boundsToCopyFrom.Left - (int)sourceImage.OriginOffset.X; int y = -boundsToCopyFrom.Bottom - (int)sourceImage.OriginOffset.Y; graphics2D.Render(sourceImage, x, y, 0, 1, 1); } } public void SetPixel32(int p, int p_2, uint p_3) { throw new NotImplementedException(); } public uint GetPixel32(double p, double p_2) { throw new NotImplementedException(); } } public static class ImageBufferExtensionMethods { public static ImageBuffer CreateScaledImage(this ImageBuffer unscaledSourceImage, double width, double height) { return CreateScaledImage(unscaledSourceImage, (int)Math.Round(width), (int)Math.Round(height)); } /// <summary> /// Get the weighted center (considering the amount that pixels are set) of the image /// </summary> /// <param name="imageBuffer"></param> /// <returns></returns> public static Vector2 GetWeightedCenter(this ImageBuffer imageBuffer, IThresholdFunction thresholdFunction) { double accumulatedCount = 0; Vector2 accumulatedPosition = Vector2.Zero; for (int y = 0; y < imageBuffer.Height; y++) { for (int x = 0; x < imageBuffer.Width; x++) { Color color = imageBuffer.GetPixel(x, y); if (thresholdFunction.Threshold(color) > .5) { accumulatedCount++; double px = x; double py = y; accumulatedPosition += new Vector2(px, py); } } } return accumulatedPosition / accumulatedCount; } public static Circle GetCircleBounds(this ImageBuffer image) { var outsidePoints = new List<Vector2>(); // get the first pixel position for each y // get the last pixel position for each y return SmallestEnclosingCircle.MakeCircle(outsidePoints); } /// <summary> /// Find the image content and scale it to the output size in consideration of the /// Material Design icon scaling rules /// </summary> /// <param name="sourceImage"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public static ImageBuffer MaterialDesignScaledIcon(this ImageBuffer sourceImage, int width, int height) { // these are the sizes defined by Material Design var iconGridSize = 192; var squareWidth = 152; var circleDiameter = 176; var verticalRectangle = new Vector2(128, 176); var horizontalRectangle = new Vector2(176, 128); // the first thing we will do is discover the icon shape that minimizes scaling // now figure out the scaling that needs to happen to the source to make our image fit // the correct icon bounds at the new size var circle = sourceImage.GetCircleBounds(); var bounds = sourceImage.GetBounds(); // create the new scaled image var scaledImage = new ImageBuffer(sourceImage); // return it return scaledImage; } public static ImageBuffer CreateScaledImage(this ImageBuffer sourceImage, int width, int height) { ImageBuffer destImage = new ImageBuffer(width, height, 32, sourceImage.GetRecieveBlender()); // If the source image is more than twice as big as our dest image. while (sourceImage.Width >= destImage.Width * 2) { // The image sampler we use is a 2x2 filter so we need to scale by a max of 1/2 if we want to get good results. // So we scale as many times as we need to get the Image to be the right size. // If this were going to be a non-uniform scale we could do the x and y separately to get better results. ImageBuffer halfImage = new ImageBuffer(sourceImage.Width / 2, sourceImage.Height / 2, 32, sourceImage.GetRecieveBlender()); halfImage.NewGraphics2D().Render(sourceImage, 0, 0, 0, halfImage.Width / (double)sourceImage.Width, halfImage.Height / (double)sourceImage.Height); sourceImage = halfImage; if (sourceImage.Width == width) { return sourceImage; } } Graphics2D renderGraphics = destImage.NewGraphics2D(); renderGraphics.ImageRenderQuality = Graphics2D.TransformQuality.Best; renderGraphics.Render(sourceImage, 0, 0, 0, destImage.Width / (double)sourceImage.Width, destImage.Height / (double)sourceImage.Height); return destImage; } public static ImageBuffer CreateScaledImage(this ImageBuffer image, double ratio) { return CreateScaledImage(image, image.Width * ratio, image.Height * ratio); } public static ImageBuffer ToGrayscale(this ImageBuffer sourceImage) { var outputImage = new ImageBuffer(sourceImage.Width, sourceImage.Height, 8, new blender_gray(1)); outputImage.NewGraphics2D().Render(sourceImage, 0, 0); return outputImage; } } public static class DoCopyOrBlend { private const byte base_mask = 255; public static void BasedOnAlpha(IRecieveBlenderByte recieveBlender, byte[] destBuffer, int bufferOffset, Color sourceColor) { //if (sourceColor.m_A != 0) { #if false // we blend regardless of the alpha so that we can get Light Opacity working (used this way we have additive and faster blending in one blender) LBB if (sourceColor.m_A == base_mask) { Blender.CopyPixel(pDestBuffer, sourceColor); } else #endif { recieveBlender.BlendPixel(destBuffer, bufferOffset, sourceColor); } } } public static void BasedOnAlphaAndCover(IRecieveBlenderByte recieveBlender, byte[] destBuffer, int bufferOffset, Color sourceColor, int cover) { if (cover == 255) { BasedOnAlpha(recieveBlender, destBuffer, bufferOffset, sourceColor); } else { //if (sourceColor.m_A != 0) { sourceColor.alpha = (byte)((sourceColor.alpha * (cover + 1)) >> 8); #if false // we blend regardless of the alpha so that we can get Light Opacity working (used this way we have additive and faster blending in one blender) LBB if (sourceColor.m_A == base_mask) { Blender.CopyPixel(pDestBuffer, sourceColor); } else #endif { recieveBlender.BlendPixel(destBuffer, bufferOffset, sourceColor); } } } } }; }
// // AudioCdRipper.cs // // Author: // Olivier Dufour <[email protected]> // // Copyright (c) 2011 Olivier Dufour // // 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.Runtime.InteropServices; using Mono.Unix; using Hyena; using Banshee.Base; using Banshee.Collection; using Banshee.ServiceStack; using Banshee.MediaEngine; using Banshee.MediaProfiles; using Banshee.Configuration.Schema; using Gst; using Banshee.Streaming; using System.Collections; namespace Banshee.GStreamerSharp { public class AudioCdRipper : IAudioCdRipper { private string encoder_pipeline; private string output_extension; private string output_path; private TrackInfo current_track; private string device; private int paranoia_mode; private System.Timers.Timer timer; Gst.Pipeline pipeline; Element cddasrc; Bin encoder; Element filesink; public event AudioCdRipperProgressHandler Progress; public event AudioCdRipperTrackFinishedHandler TrackFinished; public event AudioCdRipperErrorHandler Error; public void Begin (string device, bool enableErrorCorrection) { try { this.device = device; this.paranoia_mode = enableErrorCorrection ? 255 : 0; Profile profile = null; ProfileConfiguration config = ServiceManager.MediaProfileManager.GetActiveProfileConfiguration ("cd-importing"); if (config != null) { profile = config.Profile; } else { profile = ServiceManager.MediaProfileManager.GetProfileForMimeType ("audio/vorbis") ?? ServiceManager.MediaProfileManager.GetProfileForMimeType ("audio/flac"); if (profile != null) { Log.InformationFormat ("Using default/fallback encoding profile: {0}", profile.Name); ProfileConfiguration.SaveActiveProfile (profile, "cd-importing"); } } if (profile != null) { encoder_pipeline = profile.Pipeline.GetProcessById ("gstreamer"); output_extension = profile.OutputFileExtension; } if (String.IsNullOrEmpty (encoder_pipeline)) { throw new ApplicationException (); } timer = new System.Timers.Timer (); timer.Interval = 200; timer.AutoReset = true; timer.Elapsed += OnTick; Hyena.Log.InformationFormat ("Ripping using encoder profile `{0}' with pipeline: {1}", profile.Name, encoder_pipeline); } catch (Exception e) { throw new ApplicationException (Catalog.GetString ("Could not find an encoder for ripping."), e); } } void OnTick (object o, System.Timers.ElapsedEventArgs args) { Format format = Format.Time; State state; long position; pipeline.GetState (out state, 0); if (state != State.Playing) { return; } if (!cddasrc.QueryPosition (ref format, out position)) { return; } RaiseProgress (current_track, TimeSpan.FromSeconds (position / (long)Clock.Second)); } public void Finish () { if (output_path != null) { Banshee.IO.File.Delete (new SafeUri (output_path)); } TrackReset (); encoder_pipeline = null; output_extension = null; if (timer != null) { timer.Stop (); } if (pipeline != null && pipeline is Element) { pipeline.SetState (State.Null); pipeline = null; } } public void Cancel () { Finish (); } private void TrackReset () { current_track = null; output_path = null; } private TagList MakeTagList (TrackInfo track) { TagList tags = new TagList (); tags.Add (TagMergeMode.Replace, CommonTags.Artist, track.ArtistName); tags.Add (TagMergeMode.Replace, CommonTags.Album, track.AlbumTitle); tags.Add (TagMergeMode.Replace, CommonTags.Title, track.TrackTitle); tags.Add (TagMergeMode.Replace, CommonTags.Genre, track.Genre); tags.Add (TagMergeMode.Replace, CommonTags.TrackNumber, (uint)track.TrackNumber); tags.Add (TagMergeMode.Replace, CommonTags.TrackCount, (uint)track.TrackCount); tags.Add (TagMergeMode.Replace, CommonTags.AlbumDiscNumber, (uint)track.DiscNumber); tags.Add (TagMergeMode.Replace, CommonTags.AlbumDiscCount, (uint)track.DiscCount); tags.Add (TagMergeMode.Replace, Gst.Tag.Date, track.Year); tags.Add (TagMergeMode.Replace, Gst.Tag.Date, track.ReleaseDate); tags.Add (TagMergeMode.Replace, CommonTags.Composer, track.Composer); tags.Add (TagMergeMode.Replace, CommonTags.Copyright, track.Copyright); tags.Add (TagMergeMode.Replace, CommonTags.Comment, track.Comment); tags.Add (TagMergeMode.Replace, CommonTags.MusicBrainzTrackId, track.MusicBrainzId); tags.Add (TagMergeMode.Replace, CommonTags.MusicBrainzArtistId, track.ArtistMusicBrainzId); tags.Add (TagMergeMode.Replace, CommonTags.MusicBrainzAlbumId, track.AlbumMusicBrainzId); return tags; } public void RipTrack (int trackIndex, TrackInfo track, SafeUri outputUri, out bool taggingSupported) { taggingSupported = false; TrackReset (); current_track = track; using (TagList tags = MakeTagList (track)) { output_path = String.Format ("{0}.{1}", outputUri.LocalPath, output_extension); // Avoid overwriting an existing file int i = 1; while (Banshee.IO.File.Exists (new SafeUri (output_path))) { output_path = String.Format ("{0} ({1}).{2}", outputUri.LocalPath, i++, output_extension); } Log.DebugFormat ("GStreamer ripping track {0} to {1}", trackIndex, output_path); if (!ConstructPipeline ()) { return; } // initialize the pipeline, set the sink output location filesink.SetState (State.Null); filesink ["location"] = output_path; var version = new System.Version (Banshee.ServiceStack.Application.Version); // find an element to do the tagging and set tag data foreach (Element element in encoder.GetAllByInterface (typeof (TagSetter))) { TagSetter tag_setter = element as TagSetter; if (tag_setter != null) { tag_setter.AddTag (TagMergeMode.ReplaceAll, Tag.Encoder, new Gst.GLib.Value (String.Format ("Banshee {0}", Banshee.ServiceStack.Application.Version))); tag_setter.AddTag (TagMergeMode.ReplaceAll, Tag.EncoderVersion, new Gst.GLib.Value ( (version.Major << 16) | (version.Minor << 8) | version.Build)); if (tags != null) { tag_setter.AddTag (tags, TagMergeMode.Append); } /*if (banshee_is_debugging ()) { bt_tag_list_dump (gst_tag_setter_get_tag_list (tag_setter)); }*/ // We'll warn the user in the UI if we can't tag the encoded audio files taggingSupported = true; } } // Begin the rip cddasrc ["track"] = trackIndex + 1; pipeline.SetState (State.Playing); timer.Start (); } } bool ConstructPipeline () { Element queue; pipeline = new Gst.Pipeline ("pipeline"); if (pipeline == null) { RaiseError (current_track, Catalog.GetString ("Could not create pipeline")); return false; } cddasrc = ElementFactory.MakeFromUri (URIType.Src, "cdda://1", "cddasrc"); if (cddasrc == null) { RaiseError (current_track, Catalog.GetString ("Could not initialize element from cdda URI")); return false; } cddasrc ["device"] = device; if (cddasrc.HasProperty ("paranoia-mode")) { cddasrc ["paranoia-mode"] = paranoia_mode; } try { encoder = (Bin)Parse.BinFromDescription (encoder_pipeline, true); } catch (Exception e) { string err = Catalog.GetString ("Could not create encoder pipeline : {0}"); RaiseError (current_track, String.Format (err, e.Message)); return false; } queue = ElementFactory.Make ("queue", "queue"); if (queue == null) { RaiseError (current_track, Catalog.GetString ("Could not create queue plugin")); return false; } queue ["max-size-time"] = 120 * Gst.Clock.Second; filesink = ElementFactory.Make ("filesink", "filesink"); if (filesink == null) { RaiseError (current_track, Catalog.GetString ("Could not create filesink plugin")); return false; } pipeline.Add (cddasrc, queue, encoder, filesink); if (!Element.Link (cddasrc, queue, encoder, filesink)) { RaiseError (current_track, Catalog.GetString ("Could not link pipeline elements")); } pipeline.Bus.AddWatch (OnBusMessage); return true; } private string ProbeMimeType () { Iterator elem_iter = ((Bin)encoder).ElementsRecurse; string preferred_mimetype = null; IEnumerator en = elem_iter.GetEnumerator (); while (en.MoveNext ()) { Element element = (Element)en.Current; Iterator pad_iter = element.SrcPads; IEnumerator enu = pad_iter.GetEnumerator (); while (enu.MoveNext ()) { Pad pad = (Pad)enu.Current; Caps caps = pad.Caps; Structure str = (caps != null ? caps [0] : null); if (str != null) { string mimetype = str.Name; int mpeg_layer; Gst.GLib.Value val = str.GetValue ("mpegversion"); // Prefer and adjust audio/mpeg, leaving MP3 as audio/mpeg if (mimetype.StartsWith ("audio/mpeg")) { mpeg_layer = (Int32)val.Val; switch (mpeg_layer) { case 2: mimetype = "audio/mp2"; break; case 4: mimetype = "audio/mp4"; break; default: break; } preferred_mimetype = mimetype; // If no preferred type set and it's not RAW, prefer it } else if (preferred_mimetype == null && !mimetype.StartsWith ("audio/x-raw")) { preferred_mimetype = mimetype; // Always prefer application containers } else if (mimetype.StartsWith ("application/")) { preferred_mimetype = mimetype; } } } } return preferred_mimetype; } private void RefreshTrackMimeType (string mimetype) { if (current_track == null) return; if (mimetype != null) { string [] split = mimetype.Split (';', '.', ' ', '\t'); if (split != null && split.Length > 0) { current_track.MimeType = split[0].Trim (); } else { current_track.MimeType = mimetype.Trim (); } } } private bool OnBusMessage (Bus bus, Message msg) { switch (msg.Type) { case MessageType.Eos: pipeline.SetState (State.Null); timer.Stop (); OnNativeFinished (); break; case MessageType.StateChanged: State old_state, new_state, pending_state; msg.ParseStateChanged (out old_state, out new_state, out pending_state); if (old_state == State.Ready && new_state == State.Paused && pending_state == State.Playing) { string mimetype = ProbeMimeType (); if (mimetype == null) return true; Log.Information ("Ripper : Found Mime Type for encoded content: {0}", mimetype); RefreshTrackMimeType (mimetype); } break; case MessageType.Error: Enum error_type; string err_msg, debug; msg.ParseError (out error_type, out err_msg, out debug); RaiseError (current_track, String.Format ("{0} : {1}", err_msg, debug)); timer.Stop (); break; } return true; } protected virtual void RaiseProgress (TrackInfo track, TimeSpan ellapsedTime) { AudioCdRipperProgressHandler handler = Progress; if (handler != null) { handler (this, new AudioCdRipperProgressArgs (track, ellapsedTime, track.Duration)); } } protected virtual void RaiseTrackFinished (TrackInfo track, SafeUri outputUri) { AudioCdRipperTrackFinishedHandler handler = TrackFinished; if (handler != null) { handler (this, new AudioCdRipperTrackFinishedArgs (track, outputUri)); } } protected virtual void RaiseError (TrackInfo track, string message) { AudioCdRipperErrorHandler handler = Error; if (handler != null) { handler (this, new AudioCdRipperErrorArgs (track, message)); } } private void OnNativeMimeType (IntPtr ripper, IntPtr mimetype) { if (mimetype != IntPtr.Zero && current_track != null) { string type = GLib.Marshaller.Utf8PtrToString (mimetype); if (type != null) { string [] split = type.Split (';', '.', ' ', '\t'); if (split != null && split.Length > 0) { current_track.MimeType = split[0].Trim (); } else { current_track.MimeType = type.Trim (); } } } } private void OnNativeFinished () { SafeUri uri = new SafeUri (output_path); TrackInfo track = current_track; TrackReset (); RaiseTrackFinished (track, uri); } } }
using System; using System.Linq; using System.Collections.Generic; using UnityEngine; namespace VesCat { public sealed class DataStorage { static readonly DataStorage _instance = new DataStorage(); public static Guid ROOT_GUID = new Guid("142599e6-0f50-4994-a7f8-6474e9893acc"); private Dictionary<Guid,Guid> vessels = new Dictionary<Guid, Guid>(); // A dictionary of all known vessels private Dictionary<Guid,String> categories = new Dictionary<Guid,String>(); // all categories the player has created private Dictionary<Guid,Guid> categoryParents = new Dictionary<Guid,Guid>(); // the parenthood of each category. private List<Vessel> allKnownVessels = new List<Vessel>(); //private CommonTools Tools = CommonTools.Instance; private bool needUpdate = true; public static DataStorage Instance { get { return _instance; } } public DataStorage () { } public bool NeedUpdate { get { return needUpdate; } set { needUpdate = value; } } public Dictionary<Guid, Guid> Vessels { get { return this.vessels; //.OrderBy (v => Tools.GetVesselName (v.Key)).ToDictionary (v => v.Key, v => v.Value); } set { vessels = value; } } public Dictionary<Guid, string> Categories { get { return this.categories; //.OrderBy( c => GetCategoryName(c.Key)).ToDictionary(c => c.Key, c => c.Value); } set { categories = value; } } public Dictionary<Guid, Guid> CategoryParents { get { return this.categoryParents; } set { categoryParents = value; } } public List<Vessel> AllKnownVessels { get { return this.allKnownVessels; } } /* This function adds a vessel to the known vessels list. It also makes certain the vessel has a pairing */ public void AddVessel(Vessel v) { if (v.DiscoveryInfo.Level != DiscoveryLevels.Owned) { return; // bail out if the vessel isn't owned } // add it to known vessels if (!allKnownVessels.Contains(v)) { allKnownVessels.Add (v); } // and add it to our list of vessels to if (!vessels.ContainsKey(v.id)) { vessels.Add (v.id, ROOT_GUID); } } /* This function removes a vessel from the known vessels list. It also forgets about pairing. */ public void RemoveVessel(Vessel v) { if (allKnownVessels.Contains(v)) { allKnownVessels.Remove (v); } if (vessels.ContainsKey(v.id)) { vessels.Remove (v.id); } } public void UpdateVessels() { foreach (Vessel v in FlightGlobals.Vessels.Where(vs => vs.DiscoveryInfo.Level == DiscoveryLevels.Owned)) { AddVessel (v); } // now we check if all the vessels in vessels exist List<Guid> toRemove = new List<Guid> (); foreach (Guid id in Vessels.Keys) { if (!FlightGlobals.Vessels.Exists(vS => vS.id == id)) { toRemove.Add (id); } } // finally, remove those that no longer exist from the vessels dictionary. foreach(Guid id in toRemove) { Vessels.Remove (id); } } public void AddCategory(string category) { Guid id = Guid.NewGuid (); // add the category, and set its parent to root Categories.Add (id, category); CategoryParents.Add (id, ROOT_GUID); } public string GetCategoryName(Guid id) { if (!Categories.ContainsKey(id)) { return "BUG: " + id + " has no entry."; } return Categories [id]; } // returns the parent of the given Guid public Guid GetParent(Guid id) { if (CategoryParents.ContainsKey(id)) { return CategoryParents[id]; } else if (Vessels.ContainsKey(id)) { return Vessels [id]; } return ROOT_GUID; } public void SetParent(Guid id, Guid parent) { if ((!Categories.ContainsKey (parent) && parent != ROOT_GUID) || id == parent) { // we can't assign to unknown categories, or other vessels return; } else { if (Categories.ContainsKey (id)) { if (!ValidCategoryParent(id, parent)) { Debug.Log ("Tried assigning " + id + " to " + parent + " which is invalid."); return; } Debug.Log ("Assigning parent category " + parent + " to category " + id); CategoryParents [id] = parent; } else if (Vessels.ContainsKey (id)) { Debug.Log ("Assigning parent category " + parent + " to vessel " + id); Vessels [id] = parent; } } } public bool ValidCategoryParent(Guid id, Guid parent) { // It has to be a valid category. ROOT can't be moved, sorry if (!Categories.ContainsKey(id)) { return false; } // It has to be a known category, or the ROOT as the parent. if (!Categories.ContainsKey (parent) && parent != ROOT_GUID) { return false; } // we can't assign yourself to yourself, sorry. if (id == parent) { return false; } List<Guid> visitedParents = new List<Guid> (); Guid oldParent = GetParent (id); // we store the old parent. CategoryParents [id] = parent; // set it temporarily. Guid step = GetParent (id); int maxStep = 0; do { if (visitedParents.Contains(step)) { Debug.Log("[VesCat] Found loop in category assignment."); CategoryParents[id] = oldParent; // Reset return false; // We have a loop here! } visitedParents.Add(step); maxStep += 1; step = GetParent(step); } while(step != ROOT_GUID || maxStep == 100); CategoryParents[id] = oldParent; // we reset here, in case we didn't actually want to assign. if (maxStep == 100) { Debug.Log("[VesCat] maxStep hit 100 in ValidCategoryParent()!"); return false; } // we got through? Excellent! return true; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using ProtoBuf; using System.IO; using Newtonsoft.Json; using QuantConnect.Util; using QuantConnect.Logging; using System.Globalization; using System.Runtime.CompilerServices; namespace QuantConnect.Data.Market { /// <summary> /// Tick class is the base representation for tick data. It is grouped into a Ticks object /// which implements IDictionary and passed into an OnData event handler. /// </summary> [ProtoContract(SkipConstructor = true)] [ProtoInclude(1000, typeof(OpenInterest))] public class Tick : BaseData { private Exchange _exchange = QuantConnect.Exchange.UNKNOWN; private string _exchangeValue; private uint? _parsedSaleCondition; /// <summary> /// Type of the Tick: Trade or Quote. /// </summary> [ProtoMember(10)] public TickType TickType = TickType.Trade; /// <summary> /// Quantity exchanged in a trade. /// </summary> [ProtoMember(11)] public decimal Quantity = 0; /// <summary> /// Exchange code this tick came from <see cref="Exchanges"/> /// </summary> public string ExchangeCode { get { if (_exchange == null) { _exchange = Symbol != null ? _exchangeValue.GetPrimaryExchange(Symbol.SecurityType, Symbol.ID.Market) : _exchangeValue.GetPrimaryExchange(); } return _exchange.Code; } set { _exchangeValue = value; _exchange = null; } } /// <summary> /// Exchange name this tick came from <see cref="Exchanges"/> /// </summary> [ProtoMember(12)] public string Exchange { get { if (_exchange == null) { _exchange = Symbol != null ? _exchangeValue.GetPrimaryExchange(Symbol.SecurityType, Symbol.ID.Market) : _exchangeValue.GetPrimaryExchange(); } return _exchange; } set { _exchangeValue = value; _exchange = null; } } /// <summary> /// Sale condition for the tick. /// </summary> public string SaleCondition = ""; /// <summary> /// For performance parsed sale condition for the tick. /// </summary> [JsonIgnore] public uint ParsedSaleCondition { get { if (!_parsedSaleCondition.HasValue) { _parsedSaleCondition = uint.Parse(SaleCondition, NumberStyles.HexNumber, CultureInfo.InvariantCulture); } return _parsedSaleCondition.Value; } set { _parsedSaleCondition = value; } } /// <summary> /// Bool whether this is a suspicious tick /// </summary> [ProtoMember(14)] public bool Suspicious = false; /// <summary> /// Bid Price for Tick /// </summary> [ProtoMember(15)] public decimal BidPrice = 0; /// <summary> /// Asking price for the Tick quote. /// </summary> [ProtoMember(16)] public decimal AskPrice = 0; /// <summary> /// Alias for "Value" - the last sale for this asset. /// </summary> public decimal LastPrice { get { return Value; } } /// <summary> /// Size of bid quote. /// </summary> [ProtoMember(17)] public decimal BidSize = 0; /// <summary> /// Size of ask quote. /// </summary> [ProtoMember(18)] public decimal AskSize = 0; //In Base Class: Alias of Closing: //public decimal Price; //Symbol of Asset. //In Base Class: public Symbol Symbol; //In Base Class: DateTime Of this TradeBar //public DateTime Time; /// <summary> /// Initialize tick class with a default constructor. /// </summary> public Tick() { Value = 0; Time = new DateTime(); DataType = MarketDataType.Tick; Symbol = Symbol.Empty; TickType = TickType.Trade; Quantity = 0; _exchange = QuantConnect.Exchange.UNKNOWN; SaleCondition = string.Empty; Suspicious = false; BidSize = 0; AskSize = 0; } /// <summary> /// Cloner constructor for fill forward engine implementation. Clone the original tick into this new tick: /// </summary> /// <param name="original">Original tick we're cloning</param> public Tick(Tick original) { Symbol = original.Symbol; Time = new DateTime(original.Time.Ticks); Value = original.Value; BidPrice = original.BidPrice; AskPrice = original.AskPrice; // directly set privates so we don't parse the exchange _exchange = original._exchange; _exchangeValue = original._exchangeValue; SaleCondition = original.SaleCondition; Quantity = original.Quantity; Suspicious = original.Suspicious; DataType = MarketDataType.Tick; TickType = original.TickType; BidSize = original.BidSize; AskSize = original.AskSize; } /// <summary> /// Constructor for a FOREX tick where there is no last sale price. The volume in FX is so high its rare to find FX trade data. /// To fake this the tick contains bid-ask prices and the last price is the midpoint. /// </summary> /// <param name="time">Full date and time</param> /// <param name="symbol">Underlying currency pair we're trading</param> /// <param name="bid">FX tick bid value</param> /// <param name="ask">FX tick ask value</param> public Tick(DateTime time, Symbol symbol, decimal bid, decimal ask) { DataType = MarketDataType.Tick; Time = time; Symbol = symbol; Value = (bid + ask) / 2; TickType = TickType.Quote; BidPrice = bid; AskPrice = ask; } /// <summary> /// Initializer for a last-trade equity tick with bid or ask prices. /// </summary> /// <param name="time">Full date and time</param> /// <param name="symbol">Underlying equity security symbol</param> /// <param name="bid">Bid value</param> /// <param name="ask">Ask value</param> /// <param name="last">Last trade price</param> public Tick(DateTime time, Symbol symbol, decimal last, decimal bid, decimal ask) { DataType = MarketDataType.Tick; Time = time; Symbol = symbol; Value = last; TickType = TickType.Quote; BidPrice = bid; AskPrice = ask; } /// <summary> /// Trade tick type constructor /// </summary> /// <param name="time">Full date and time</param> /// <param name="symbol">Underlying equity security symbol</param> /// <param name="saleCondition">The ticks sale condition</param> /// <param name="exchange">The ticks exchange</param> /// <param name="quantity">The quantity traded</param> /// <param name="price">The price of the trade</param> public Tick(DateTime time, Symbol symbol, string saleCondition, string exchange, decimal quantity, decimal price) { Value = price; Time = time; DataType = MarketDataType.Tick; Symbol = symbol; TickType = TickType.Trade; Quantity = quantity; Exchange = exchange; SaleCondition = saleCondition; Suspicious = false; } /// <summary> /// Quote tick type constructor /// </summary> /// <param name="time">Full date and time</param> /// <param name="symbol">Underlying equity security symbol</param> /// <param name="saleCondition">The ticks sale condition</param> /// <param name="exchange">The ticks exchange</param> /// <param name="bidSize">The bid size</param> /// <param name="bidPrice">The bid price</param> /// <param name="askSize">The ask size</param> /// <param name="askPrice">The ask price</param> public Tick(DateTime time, Symbol symbol, string saleCondition, string exchange, decimal bidSize, decimal bidPrice, decimal askSize, decimal askPrice) { Time = time; DataType = MarketDataType.Tick; Symbol = symbol; TickType = TickType.Quote; Exchange = exchange; SaleCondition = saleCondition; Suspicious = false; AskPrice = askPrice; AskSize = askSize; BidPrice = bidPrice; BidSize = bidSize; } /// <summary> /// Constructor for QuantConnect FXCM Data source: /// </summary> /// <param name="symbol">Symbol for underlying asset</param> /// <param name="line">CSV line of data from FXCM</param> public Tick(Symbol symbol, string line) { var csv = line.Split(','); DataType = MarketDataType.Tick; Symbol = symbol; Time = DateTime.ParseExact(csv[0], DateFormat.Forex, CultureInfo.InvariantCulture); Value = (BidPrice + AskPrice) / 2; TickType = TickType.Quote; BidPrice = Convert.ToDecimal(csv[1], CultureInfo.InvariantCulture); AskPrice = Convert.ToDecimal(csv[2], CultureInfo.InvariantCulture); } /// <summary> /// Constructor for QuantConnect tick data /// </summary> /// <param name="symbol">Symbol for underlying asset</param> /// <param name="line">CSV line of data from QC tick csv</param> /// <param name="baseDate">The base date of the tick</param> public Tick(Symbol symbol, string line, DateTime baseDate) { var csv = line.Split(','); DataType = MarketDataType.Tick; Symbol = symbol; Time = baseDate.Date.AddMilliseconds(csv[0].ToInt32()); Value = csv[1].ToDecimal() / GetScaleFactor(symbol); TickType = TickType.Trade; Quantity = csv[2].ToDecimal(); Exchange = csv[3].Trim(); SaleCondition = csv[4]; Suspicious = csv[5].ToInt32() == 1; } /// <summary> /// Parse a tick data line from quantconnect zip source files. /// </summary> /// <param name="reader">The source stream reader</param> /// <param name="date">Base date for the tick (ticks date is stored as int milliseconds since midnight)</param> /// <param name="config">Subscription configuration object</param> public Tick(SubscriptionDataConfig config, StreamReader reader, DateTime date) { try { DataType = MarketDataType.Tick; Symbol = config.Symbol; // Which security type is this data feed: var scaleFactor = GetScaleFactor(config.Symbol); switch (config.SecurityType) { case SecurityType.Equity: { TickType = config.TickType; Time = date.Date.AddMilliseconds((double)reader.GetDecimal()).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone); bool pastLineEnd; if (TickType == TickType.Trade) { Value = reader.GetDecimal() / scaleFactor; Quantity = reader.GetDecimal(out pastLineEnd); if (!pastLineEnd) { Exchange = reader.GetString(); SaleCondition = reader.GetString(); Suspicious = reader.GetInt32() == 1; } } else if (TickType == TickType.Quote) { BidPrice = reader.GetDecimal() / scaleFactor; BidSize = reader.GetDecimal(); AskPrice = reader.GetDecimal() / scaleFactor; AskSize = reader.GetDecimal(out pastLineEnd); SetValue(); if (!pastLineEnd) { Exchange = reader.GetString(); SaleCondition = reader.GetString(); Suspicious = reader.GetInt32() == 1; } } else { throw new InvalidOperationException($"Tick(): Unexpected tick type {TickType}"); } break; } case SecurityType.Forex: case SecurityType.Cfd: { TickType = TickType.Quote; Time = date.Date.AddMilliseconds((double) reader.GetDecimal()) .ConvertTo(config.DataTimeZone, config.ExchangeTimeZone); BidPrice = reader.GetDecimal(); AskPrice = reader.GetDecimal(); SetValue(); break; } case SecurityType.Crypto: { TickType = config.TickType; Exchange = config.Market; if (TickType == TickType.Trade) { Time = date.Date.AddMilliseconds((double)reader.GetDecimal()) .ConvertTo(config.DataTimeZone, config.ExchangeTimeZone); Value = reader.GetDecimal(); Quantity = reader.GetDecimal(out var endOfLine); Suspicious = !endOfLine && reader.GetInt32() == 1; } if (TickType == TickType.Quote) { Time = date.Date.AddMilliseconds((double)reader.GetDecimal()) .ConvertTo(config.DataTimeZone, config.ExchangeTimeZone); BidPrice = reader.GetDecimal(); BidSize = reader.GetDecimal(); AskPrice = reader.GetDecimal(); AskSize = reader.GetDecimal(out var endOfLine); Suspicious = !endOfLine && reader.GetInt32() == 1; SetValue(); } break; } case SecurityType.Future: case SecurityType.Option: case SecurityType.FutureOption: case SecurityType.IndexOption: { TickType = config.TickType; Time = date.Date.AddMilliseconds((double)reader.GetDecimal()) .ConvertTo(config.DataTimeZone, config.ExchangeTimeZone); if (TickType == TickType.Trade) { Value = reader.GetDecimal() / scaleFactor; Quantity = reader.GetDecimal(); Exchange = reader.GetString(); SaleCondition = reader.GetString(); Suspicious = reader.GetInt32() == 1; } else if (TickType == TickType.OpenInterest) { Value = reader.GetDecimal(); } else { BidPrice = reader.GetDecimal() / scaleFactor; BidSize = reader.GetDecimal(); AskPrice = reader.GetDecimal() / scaleFactor; AskSize = reader.GetDecimal(); Exchange = reader.GetString(); Suspicious = reader.GetInt32() == 1; SetValue(); } break; } } } catch (Exception err) { Log.Error(err); } } /// <summary> /// Parse a tick data line from quantconnect zip source files. /// </summary> /// <param name="line">CSV source line of the compressed source</param> /// <param name="date">Base date for the tick (ticks date is stored as int milliseconds since midnight)</param> /// <param name="config">Subscription configuration object</param> public Tick(SubscriptionDataConfig config, string line, DateTime date) { try { DataType = MarketDataType.Tick; Symbol = config.Symbol; // Which security type is this data feed: var scaleFactor = GetScaleFactor(config.Symbol); switch (config.SecurityType) { case SecurityType.Equity: { var index = 0; TickType = config.TickType; var csv = line.ToCsv(TickType == TickType.Trade ? 6 : 8); Time = date.Date.AddMilliseconds(csv[index++].ToInt64()).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone); if (TickType == TickType.Trade) { Value = csv[index++].ToDecimal() / scaleFactor; Quantity = csv[index++].ToDecimal(); if (csv.Count > index) { Exchange = csv[index++]; SaleCondition = csv[index++]; Suspicious = (csv[index++] == "1"); } } else if (TickType == TickType.Quote) { BidPrice = csv[index++].ToDecimal() / scaleFactor; BidSize = csv[index++].ToDecimal(); AskPrice = csv[index++].ToDecimal() / scaleFactor; AskSize = csv[index++].ToDecimal(); SetValue(); if (csv.Count > index) { Exchange = csv[index++]; SaleCondition = csv[index++]; Suspicious = (csv[index++] == "1"); } } else { throw new InvalidOperationException($"Tick(): Unexpected tick type {TickType}"); } break; } case SecurityType.Forex: case SecurityType.Cfd: { var csv = line.ToCsv(3); TickType = TickType.Quote; var ticks = (long)(csv[0].ToDecimal() * TimeSpan.TicksPerMillisecond); Time = date.Date.AddTicks(ticks) .ConvertTo(config.DataTimeZone, config.ExchangeTimeZone); BidPrice = csv[1].ToDecimal(); AskPrice = csv[2].ToDecimal(); SetValue(); break; } case SecurityType.Crypto: { TickType = config.TickType; Exchange = config.Market; if (TickType == TickType.Trade) { var csv = line.ToCsv(3); Time = date.Date.AddMilliseconds((double)csv[0].ToDecimal()) .ConvertTo(config.DataTimeZone, config.ExchangeTimeZone); Value = csv[1].ToDecimal(); Quantity = csv[2].ToDecimal(); Suspicious = csv.Count >= 4 && csv[3] == "1"; } if (TickType == TickType.Quote) { var csv = line.ToCsv(6); Time = date.Date.AddMilliseconds((double)csv[0].ToDecimal()) .ConvertTo(config.DataTimeZone, config.ExchangeTimeZone); BidPrice = csv[1].ToDecimal(); BidSize = csv[2].ToDecimal(); AskPrice = csv[3].ToDecimal(); AskSize = csv[4].ToDecimal(); Suspicious = csv.Count >= 6 && csv[5] == "1"; SetValue(); } break; } case SecurityType.Future: case SecurityType.Option: case SecurityType.FutureOption: case SecurityType.IndexOption: { var csv = line.ToCsv(7); TickType = config.TickType; Time = date.Date.AddMilliseconds(csv[0].ToInt64()) .ConvertTo(config.DataTimeZone, config.ExchangeTimeZone); if (TickType == TickType.Trade) { Value = csv[1].ToDecimal()/scaleFactor; Quantity = csv[2].ToDecimal(); Exchange = csv[3]; SaleCondition = csv[4]; Suspicious = csv[5] == "1"; } else if (TickType == TickType.OpenInterest) { Value = csv[1].ToDecimal(); } else { if (csv[1].Length != 0) { BidPrice = csv[1].ToDecimal()/scaleFactor; BidSize = csv[2].ToDecimal(); } if (csv[3].Length != 0) { AskPrice = csv[3].ToDecimal()/scaleFactor; AskSize = csv[4].ToDecimal(); } Exchange = csv[5]; Suspicious = csv[6] == "1"; SetValue(); } break; } } } catch (Exception err) { Log.Error(err); } } /// <summary> /// Tick implementation of reader method: read a line of data from the source and convert it to a tick object. /// </summary> /// <param name="config">Subscription configuration object for algorithm</param> /// <param name="line">Line from the datafeed source</param> /// <param name="date">Date of this reader request</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>New Initialized tick</returns> public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode) { if (isLiveMode) { // currently ticks don't come through the reader function return new Tick(); } return new Tick(config, line, date); } /// <summary> /// Tick implementation of reader method: read a line of data from the source and convert it to a tick object. /// </summary> /// <param name="config">Subscription configuration object for algorithm</param> /// <param name="reader">The source stream reader</param> /// <param name="date">Date of this reader request</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>New Initialized tick</returns> public override BaseData Reader(SubscriptionDataConfig config, StreamReader reader, DateTime date, bool isLiveMode) { if (isLiveMode) { // currently ticks don't come through the reader function return new Tick(); } return new Tick(config, reader, date); } /// <summary> /// Get source for tick data feed - not used with QuantConnect data sources implementation. /// </summary> /// <param name="config">Configuration object</param> /// <param name="date">Date of this source request if source spread across multiple files</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>String source location of the file to be opened with a stream</returns> public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode) { if (isLiveMode) { // this data type is streamed in live mode return new SubscriptionDataSource(string.Empty, SubscriptionTransportMedium.Streaming); } var source = LeanData.GenerateZipFilePath(Globals.DataFolder, config.Symbol, date, config.Resolution, config.TickType); if (config.SecurityType == SecurityType.Future || config.SecurityType.IsOption()) { source += "#" + LeanData.GenerateZipEntryName(config.Symbol, date, config.Resolution, config.TickType); } return new SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile, FileFormat.Csv); } /// <summary> /// Update the tick price information - not used. /// </summary> /// <param name="lastTrade">This trade price</param> /// <param name="bidPrice">Current bid price</param> /// <param name="askPrice">Current asking price</param> /// <param name="volume">Volume of this trade</param> /// <param name="bidSize">The size of the current bid, if available</param> /// <param name="askSize">The size of the current ask, if available</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override void Update(decimal lastTrade, decimal bidPrice, decimal askPrice, decimal volume, decimal bidSize, decimal askSize) { Value = lastTrade; BidPrice = bidPrice; AskPrice = askPrice; BidSize = bidSize; AskSize = askSize; Quantity = Convert.ToDecimal(volume); } /// <summary> /// Check if tick contains valid data (either a trade, or a bid or ask) /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsValid() { // Indexes have zero volume in live trading, but is still a valid tick. return (TickType == TickType.Trade && (LastPrice > 0.0m && (Quantity > 0 || Symbol.SecurityType == SecurityType.Index))) || (TickType == TickType.Quote && AskPrice > 0.0m && AskSize > 0) || (TickType == TickType.Quote && BidPrice > 0.0m && BidSize > 0) || (TickType == TickType.OpenInterest && Value > 0); } /// <summary> /// Clone implementation for tick class: /// </summary> /// <returns>New tick object clone of the current class values.</returns> public override BaseData Clone() { return new Tick(this); } /// <summary> /// Formats a string with the symbol and value. /// </summary> /// <returns>string - a string formatted as SPY: 167.753</returns> public override string ToString() { switch (TickType) { case TickType.Trade: return $"{Symbol}: Price: {Price} Quantity: {Quantity}"; case TickType.Quote: return $"{Symbol}: Bid: {BidSize}@{BidPrice} Ask: {AskSize}@{AskPrice}"; case TickType.OpenInterest: return $"{Symbol}: OpenInterest: {Value}"; default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Sets the tick Value based on ask and bid price /// </summary> public void SetValue() { Value = BidPrice + AskPrice; if (BidPrice * AskPrice != 0) { Value /= 2m; } } /// <summary> /// Gets the scaling factor according to the <see cref="SecurityType"/> of the <see cref="Symbol"/> provided. /// Non-equity data will not be scaled, including options with an underlying non-equity asset class. /// </summary> /// <param name="symbol">Symbol to get scaling factor for</param> /// <returns>Scaling factor</returns> private static decimal GetScaleFactor(Symbol symbol) { return symbol.SecurityType == SecurityType.Equity || symbol.SecurityType == SecurityType.Option ? 10000m : 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. using Microsoft.Win32.SafeHandles; using System.Threading; using System.Threading.Tasks; namespace System.IO.IsolatedStorage { public class IsolatedStorageFileStream : FileStream { private const string BackSlash = "\\"; private const int DefaultBufferSize = 1024; private FileStream _fs; private IsolatedStorageFile _isf; private string _givenPath; private string _fullPath; public IsolatedStorageFileStream(string path, FileMode mode) : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, null) { } public IsolatedStorageFileStream(string path, FileMode mode, IsolatedStorageFile isf) : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, isf) { } public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access) : this(path, mode, access, access == FileAccess.Read ? FileShare.Read : FileShare.None, DefaultBufferSize, null) { } public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, IsolatedStorageFile isf) : this(path, mode, access, access == FileAccess.Read ? FileShare.Read : FileShare.None, DefaultBufferSize, isf) { } public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, DefaultBufferSize, null) { } public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, IsolatedStorageFile isf) : this(path, mode, access, share, DefaultBufferSize, isf) { } public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) : this(path, mode, access, share, bufferSize, null) { } public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf) : this(path, mode, access, share, bufferSize, InitializeFileStream(path, mode, access, share, bufferSize, isf)) { } // On NetFX FileStream has an internal no arg constructor that we utilize to provide the facade. We don't have access // to internals in CoreFX so we'll do the next best thing and contort ourselves into the SafeFileHandle constructor. // (A path constructor would try and create the requested file and give us two open handles.) // // We only expose our own nested FileStream so the base class having a handle doesn't matter. Passing a new SafeFileHandle // with ownsHandle: false avoids the parent class closing without our knowledge. private IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, InitialiationData initializationData) : base(new SafeFileHandle(initializationData.NestedStream.SafeFileHandle.DangerousGetHandle(), ownsHandle: false), access, bufferSize) { _isf = initializationData.StorageFile; _givenPath = path; _fullPath = initializationData.FullPath; _fs = initializationData.NestedStream; } private struct InitialiationData { public FileStream NestedStream; public IsolatedStorageFile StorageFile; public string FullPath; } // If IsolatedStorageFile is null, then we default to using a file that is scoped by user, appdomain, and assembly. private static InitialiationData InitializeFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf) { if (path == null) throw new ArgumentNullException(nameof(path)); if ((path.Length == 0) || path.Equals(BackSlash)) throw new ArgumentException( SR.IsolatedStorage_Path); bool createdStore = false; if (isf == null) { isf = IsolatedStorageFile.GetUserStoreForDomain(); createdStore = true; } if (isf.Disposed) throw new ObjectDisposedException(null, SR.IsolatedStorage_StoreNotOpen); switch (mode) { case FileMode.CreateNew: // Assume new file case FileMode.Create: // Check for New file & Unreserve case FileMode.OpenOrCreate: // Check for new file case FileMode.Truncate: // Unreserve old file size case FileMode.Append: // Check for new file case FileMode.Open: // Open existing, else exception break; default: throw new ArgumentException(SR.IsolatedStorage_FileOpenMode); } InitialiationData data = new InitialiationData { FullPath = isf.GetFullPath(path), StorageFile = isf }; try { data.NestedStream = new FileStream(data.FullPath, mode, access, share, bufferSize, FileOptions.None); } catch (Exception e) { // Make an attempt to clean up the StorageFile if we created it try { if (createdStore) { data.StorageFile?.Dispose(); } } catch { } // Exception message might leak the IsolatedStorage path. The desktop prevented this by calling an // internal API which made sure that the exception message was scrubbed. However since the innerException // is never returned to the user(GetIsolatedStorageException() does not populate the innerexception // in retail bits we leak the path only under the debugger via IsolatedStorageException._underlyingException which // they can any way look at via IsolatedStorageFile instance as well. throw IsolatedStorageFile.GetIsolatedStorageException(SR.IsolatedStorage_Operation_ISFS, e); } return data; } public override bool CanRead { get { return _fs.CanRead; } } public override bool CanWrite { get { return _fs.CanWrite; } } public override bool CanSeek { get { return _fs.CanSeek; } } public override long Length { get { return _fs.Length; } } public override long Position { get { return _fs.Position; } set { _fs.Position = value; } } public override bool IsAsync { get { return _fs.IsAsync; } } protected override void Dispose(bool disposing) { try { if (disposing) { if (_fs != null) _fs.Dispose(); } } finally { base.Dispose(disposing); } } public override ValueTask DisposeAsync() { return GetType() != typeof(IsolatedStorageFileStream) ? base.DisposeAsync() : _fs != null ? _fs.DisposeAsync() : default; } public override void Flush() { _fs.Flush(); } public override void Flush(bool flushToDisk) { _fs.Flush(flushToDisk); } public override Task FlushAsync(CancellationToken cancellationToken) { return _fs.FlushAsync(); } public override void SetLength(long value) { _fs.SetLength(value); } public override int Read(byte[] buffer, int offset, int count) { return _fs.Read(buffer, offset, count); } public override int Read(System.Span<byte> buffer) { return _fs.Read(buffer); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, Threading.CancellationToken cancellationToken) { return _fs.ReadAsync(buffer, offset, count, cancellationToken); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) { return _fs.ReadAsync(buffer, cancellationToken); } public override int ReadByte() { return _fs.ReadByte(); } public override long Seek(long offset, SeekOrigin origin) { // Desktop implementation of IsolatedStorage ensures that in case the size is increased the new memory is zero'ed out. // However in this implementation we simply call the FileStream.Seek APIs which have an undefined behavior. return _fs.Seek(offset, origin); } public override void Write(byte[] buffer, int offset, int count) { _fs.Write(buffer, offset, count); } public override void Write(System.ReadOnlySpan<byte> buffer) { _fs.Write(buffer); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _fs.WriteAsync(buffer, offset, count, cancellationToken); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { return _fs.WriteAsync(buffer, cancellationToken); } public override void WriteByte(byte value) { _fs.WriteByte(value); } public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject) { return _fs.BeginRead(array, offset, numBytes, userCallback, stateObject); } public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject) { return _fs.BeginWrite(array, offset, numBytes, userCallback, stateObject); } public override int EndRead(IAsyncResult asyncResult) { return _fs.EndRead(asyncResult); } public override void EndWrite(IAsyncResult asyncResult) { _fs.EndWrite(asyncResult); } [Obsolete("This property has been deprecated. Please use IsolatedStorageFileStream's SafeFileHandle property instead. https://go.microsoft.com/fwlink/?linkid=14202")] public override IntPtr Handle { get { return _fs.Handle; } } public override void Unlock(long position, long length) { _fs.Unlock(position, length); } public override void Lock(long position, long length) { _fs.Lock(position, length); } public override SafeFileHandle SafeFileHandle { get { throw new IsolatedStorageException(SR.IsolatedStorage_Operation_ISFS); } } } }
using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using FluentNHibernate.Automapping.TestFixtures; using FluentNHibernate.Conventions; using FluentNHibernate.Conventions.Inspections; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.ClassBased; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.Utils; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.Inspection { [TestFixture, Category("Inspection DSL")] public class DynamicComponentInspectorMapsToDynamicComponentMapping { private DynamicComponentMapping mapping; private IDynamicComponentInspector inspector; [SetUp] public void CreateDsl() { mapping = new DynamicComponentMapping(); inspector = new DynamicComponentInspector(mapping); } [Test] public void AccessMapped() { mapping.Access = "field"; inspector.Access.ShouldEqual(Access.Field); } [Test] public void AccessIsSet() { mapping.Access = "field"; inspector.IsSet(Prop(x => x.Access)) .ShouldBeTrue(); } [Test] public void AccessIsNotSet() { inspector.IsSet(Prop(x => x.Access)) .ShouldBeFalse(); } [Test] public void AnysCollectionHasSameCountAsMapping() { mapping.AddAny(new AnyMapping()); inspector.Anys.Count().ShouldEqual(1); } [Test] public void AnysCollectionOfInspectors() { mapping.AddAny(new AnyMapping()); inspector.Anys.First().ShouldBeOfType<IAnyInspector>(); } [Test] public void AnysCollectionIsEmpty() { inspector.Anys.IsEmpty().ShouldBeTrue(); } [Test] public void CollectionsCollectionHasSameCountAsMapping() { mapping.AddCollection(new BagMapping()); inspector.Collections.Count().ShouldEqual(1); } [Test] public void CollectionsCollectionOfInspectors() { mapping.AddCollection(new BagMapping()); inspector.Collections.First().ShouldBeOfType<ICollectionInspector>(); } [Test] public void CollectionsCollectionIsEmpty() { inspector.Collections.IsEmpty().ShouldBeTrue(); } [Test] public void ComponentsCollectionHasSameCountAsMapping() { mapping.AddComponent(new ComponentMapping()); inspector.Components.Count().ShouldEqual(1); } [Test] public void ComponentsCollectionOfInspectors() { mapping.AddComponent(new ComponentMapping()); inspector.Components.First().ShouldBeOfType<IComponentBaseInspector>(); } [Test] public void ComponentsCollectionIsEmpty() { inspector.Components.IsEmpty().ShouldBeTrue(); } [Test] public void InsertMapped() { mapping.Insert = true; inspector.Insert.ShouldEqual(true); } [Test] public void InsertIsSet() { mapping.Insert = true; inspector.IsSet(Prop(x => x.Insert)) .ShouldBeTrue(); } [Test] public void InsertIsNotSet() { inspector.IsSet(Prop(x => x.Insert)) .ShouldBeFalse(); } [Test] public void OptimisticLockMapped() { mapping.OptimisticLock = true; inspector.OptimisticLock.ShouldEqual(true); } [Test] public void OptimisticLockIsSet() { mapping.OptimisticLock = true; inspector.IsSet(Prop(x => x.OptimisticLock)) .ShouldBeTrue(); } [Test] public void OptimisticLockIsNotSet() { inspector.IsSet(Prop(x => x.OptimisticLock)) .ShouldBeFalse(); } [Test] public void NameMapped() { mapping.Name = "name"; inspector.Name.ShouldEqual("name"); } [Test] public void NameIsSet() { mapping.Name = "name"; inspector.IsSet(Prop(x => x.Name)) .ShouldBeTrue(); } [Test] public void NameIsNotSet() { inspector.IsSet(Prop(x => x.Name)) .ShouldBeFalse(); } [Test] public void OneToOnesCollectionHasSameCountAsMapping() { mapping.AddOneToOne(new OneToOneMapping()); inspector.OneToOnes.Count().ShouldEqual(1); } [Test] public void OneToOnesCollectionOfInspectors() { mapping.AddOneToOne(new OneToOneMapping()); inspector.OneToOnes.First().ShouldBeOfType<IOneToOneInspector>(); } [Test] public void OneToOnesCollectionIsEmpty() { inspector.OneToOnes.IsEmpty().ShouldBeTrue(); } [Test] public void ParentMapped() { mapping.Parent = new ParentMapping(); mapping.Parent.Name = "name"; inspector.Parent.Name.ShouldEqual("name"); } [Test] public void ParentIsSet() { mapping.Parent = new ParentMapping(); mapping.Parent.Name = "name"; inspector.IsSet(Prop(x => x.Parent)) .ShouldBeTrue(); } [Test] public void ParentIsNotSet() { inspector.IsSet(Prop(x => x.Parent)) .ShouldBeFalse(); } [Test] public void UniqueMapped() { mapping.Unique = true; inspector.Unique.ShouldEqual(true); } [Test] public void UniqueIsSet() { mapping.Unique = true; inspector.IsSet(Prop(x => x.Unique)) .ShouldBeTrue(); } [Test] public void UniqueIsNotSet() { inspector.IsSet(Prop(x => x.Unique)) .ShouldBeFalse(); } [Test] public void PropertiesCollectionHasSameCountAsMapping() { mapping.AddProperty(new PropertyMapping()); inspector.Properties.Count().ShouldEqual(1); } [Test] public void PropertiesCollectionOfInspectors() { mapping.AddProperty(new PropertyMapping()); inspector.Properties.First().ShouldBeOfType<IPropertyInspector>(); } [Test] public void PropertiesCollectionIsEmpty() { inspector.Properties.IsEmpty().ShouldBeTrue(); } [Test] public void ReferencesCollectionHasSameCountAsMapping() { mapping.AddReference(new ManyToOneMapping()); inspector.References.Count().ShouldEqual(1); } [Test] public void ReferencesCollectionOfInspectors() { mapping.AddReference(new ManyToOneMapping()); inspector.References.First().ShouldBeOfType<IManyToOneInspector>(); } [Test] public void ReferencesCollectionIsEmpty() { inspector.References.IsEmpty().ShouldBeTrue(); } [Test] public void TypeMapped() { mapping.Type = typeof(ExampleClass); inspector.Type.ShouldEqual(typeof(ExampleClass)); } [Test] public void TypeIsSet() { mapping.Type = typeof(ExampleClass); inspector.IsSet(Prop(x => x.Type)) .ShouldBeTrue(); } [Test] public void TypeIsNotSet() { inspector.IsSet(Prop(x => x.Type)) .ShouldBeFalse(); } [Test] public void UpdateMapped() { mapping.Update = true; inspector.Update.ShouldEqual(true); } [Test] public void UpdateIsSet() { mapping.Update = true; inspector.IsSet(Prop(x => x.Update)) .ShouldBeTrue(); } [Test] public void UpdateIsNotSet() { inspector.IsSet(Prop(x => x.Update)) .ShouldBeFalse(); } #region Helpers private PropertyInfo Prop(Expression<Func<IComponentInspector, object>> propertyExpression) { return ReflectionHelper.GetProperty(propertyExpression); } #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 MaxDouble() { var test = new SimpleBinaryOpTest__MaxDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.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 (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.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 (Avx.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 (Avx.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 (Avx.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__MaxDouble { 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(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); 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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, 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 Vector256<Double> _fld1; public Vector256<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MaxDouble testClass) { var result = Avx.Max(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MaxDouble testClass) { fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) { var result = Avx.Max( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MaxDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public SimpleBinaryOpTest__MaxDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.Max( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_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 = Avx.Max( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_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 = Avx.Max( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_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(Avx).GetMethod(nameof(Avx.Max), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.Max), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.Max), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.Max( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Double>* pClsVar1 = &_clsVar1) fixed (Vector256<Double>* pClsVar2 = &_clsVar2) { var result = Avx.Max( Avx.LoadVector256((Double*)(pClsVar1)), Avx.LoadVector256((Double*)(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<Vector256<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MaxDouble(); var result = Avx.Max(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__MaxDouble(); fixed (Vector256<Double>* pFld1 = &test._fld1) fixed (Vector256<Double>* pFld2 = &test._fld2) { var result = Avx.Max( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.Max(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) { var result = Avx.Max( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(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 = Avx.Max(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 = Avx.Max( Avx.LoadVector256((Double*)(&test._fld1)), Avx.LoadVector256((Double*)(&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(Vector256<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(Math.Max(left[0], right[0])) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Math.Max(left[i], right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Max)}<Double>(Vector256<Double>, Vector256<Double>): {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; } } } }
// Copyright 2010-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 // // 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. // [START program] // [START import] using System; using System.Collections.Generic; using System.Linq; using Google.OrTools.Sat; // [END import] public class NursesSat { // [START solution_printer] public class SolutionPrinter : CpSolverSolutionCallback { public SolutionPrinter(int[] allNurses, int[] allDays, int[] allShifts, Dictionary<Tuple<int, int, int>, IntVar> shifts, int limit) { solutionCount_ = 0; allNurses_ = allNurses; allDays_ = allDays; allShifts_ = allShifts; shifts_ = shifts; solutionLimit_ = limit; } public override void OnSolutionCallback() { Console.WriteLine($"Solution #{solutionCount_}:"); foreach (int d in allDays_) { Console.WriteLine($"Day {d}"); foreach (int n in allNurses_) { bool isWorking = false; foreach (int s in allShifts_) { var key = Tuple.Create(n, d, s); if (Value(shifts_[key]) == 1L) { isWorking = true; Console.WriteLine($" Nurse {n} work shift {s}"); } } if (!isWorking) { Console.WriteLine($" Nurse {d} does not work"); } } } solutionCount_++; if (solutionCount_ >= solutionLimit_) { Console.WriteLine($"Stop search after {solutionLimit_} solutions"); StopSearch(); } } public int SolutionCount() { return solutionCount_; } private int solutionCount_; private int[] allNurses_; private int[] allDays_; private int[] allShifts_; private Dictionary<Tuple<int, int, int>, IntVar> shifts_; private int solutionLimit_; } // [END solution_printer] public static void Main(String[] args) { // [START data] const int numNurses = 4; const int numDays = 3; const int numShifts = 3; int[] allNurses = Enumerable.Range(0, numNurses).ToArray(); int[] allDays = Enumerable.Range(0, numDays).ToArray(); int[] allShifts = Enumerable.Range(0, numShifts).ToArray(); // [END data] // Creates the model. // [START model] CpModel model = new CpModel(); // [END model] // Creates shift variables. // shifts[(n, d, s)]: nurse 'n' works shift 's' on day 'd'. // [START variables] Dictionary<Tuple<int, int, int>, IntVar> shifts = new Dictionary<Tuple<int, int, int>, IntVar>(); foreach (int n in allNurses) { foreach (int d in allDays) { foreach (int s in allShifts) { shifts.Add(Tuple.Create(n, d, s), model.NewBoolVar($"shifts_n{n}d{d}s{s}")); } } } // [END variables] // Each shift is assigned to exactly one nurse in the schedule period. // [START exactly_one_nurse] foreach (int d in allDays) { foreach (int s in allShifts) { IntVar[] x = new IntVar[numNurses]; foreach (int n in allNurses) { var key = Tuple.Create(n, d, s); x[n] = shifts[key]; } model.Add(LinearExpr.Sum(x) == 1); } } // [END exactly_one_nurse] // Each nurse works at most one shift per day. // [START at_most_one_shift] foreach (int n in allNurses) { foreach (int d in allDays) { IntVar[] x = new IntVar[numShifts]; foreach (int s in allShifts) { var key = Tuple.Create(n, d, s); x[s] = shifts[key]; } model.Add(LinearExpr.Sum(x) <= 1); } } // [END at_most_one_shift] // [START assign_nurses_evenly] // Try to distribute the shifts evenly, so that each nurse works // minShiftsPerNurse shifts. If this is not possible, because the total // number of shifts is not divisible by the number of nurses, some nurses will // be assigned one more shift. int minShiftsPerNurse = (numShifts * numDays) / numNurses; int maxShiftsPerNurse; if ((numShifts * numDays) % numNurses == 0) { maxShiftsPerNurse = minShiftsPerNurse; } else { maxShiftsPerNurse = minShiftsPerNurse + 1; } foreach (int n in allNurses) { IntVar[] numShiftsWorked = new IntVar[numDays * numShifts]; foreach (int d in allDays) { foreach (int s in allShifts) { var key = Tuple.Create(n, d, s); numShiftsWorked[d * numShifts + s] = shifts[key]; } } model.AddLinearConstraint(LinearExpr.Sum(numShiftsWorked), minShiftsPerNurse, maxShiftsPerNurse); } // [END assign_nurses_evenly] // [START parameters] CpSolver solver = new CpSolver(); solver.StringParameters += "linearization_level:0 "; // Tell the solver to enumerate all solutions. solver.StringParameters += "enumerate_all_solutions:true "; // [END parameters] // Display the first five solutions. // [START solution_printer_instantiate] const int solutionLimit = 5; SolutionPrinter cb = new SolutionPrinter(allNurses, allDays, allShifts, shifts, solutionLimit); // [END solution_printer_instantiate] // Solve // [START solve] CpSolverStatus status = solver.Solve(model, cb); Console.WriteLine($"Solve status: {status}"); // [END solve] // [START statistics] Console.WriteLine("Statistics"); Console.WriteLine($" conflicts: {solver.NumConflicts()}"); Console.WriteLine($" branches : {solver.NumBranches()}"); Console.WriteLine($" wall time: {solver.WallTime()}s"); // [END statistics] } } // [END program]
// // SearchSource.cs // // Authors: // Gabriel Burt <[email protected]> // // Copyright (C) 2009 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.Generic; using System.Linq; using Mono.Unix; using Hyena; using Hyena.Collections; using Hyena.Data; using Banshee.Base; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration; using Banshee.Database; using Banshee.Gui; using Banshee.Library; using Banshee.MediaEngine; using Banshee.PlaybackController; using Banshee.Playlist; using Banshee.ServiceStack; using Banshee.Sources; using IA=InternetArchive; namespace Banshee.InternetArchive { public class SearchSource : Banshee.Sources.Source { private static string name = Catalog.GetString ("Search Results"); private MemoryListModel<IA.SearchResult> model = new MemoryListModel<IA.SearchResult> (); private Gtk.Widget header_widget; private IA.Search search; private string status_text = ""; private int total_results = 0; public int TotalResults { get { return total_results; } } public IA.Search Search { get { return search; } } public SearchDescription SearchDescription { get; private set; } public IListModel<IA.SearchResult> Model { get { return model; } } public IA.SearchResult FocusedItem { get { int focus = model.Selection.FocusedIndex; if (focus >= 0 && focus < model.Count) { return model[focus]; } return null; } } public SearchSource () : base (name, name, 190, "internet-archive-search") { IA.Search.UserAgent = Banshee.Web.Browser.UserAgent; IA.Search.TimeoutMs = 12*1000; search = new IA.Search () { NumResults = 100 }; Properties.SetStringList ("Icon.Name", "search", "gtk-search"); Properties.SetString ("ActiveSourceUIResource", "SearchSourceActiveUI.xml"); Properties.SetString ("GtkActionPath", "/IaSearchSourcePopup"); if (header_widget == null) { header_widget = new HeaderFilters (this); header_widget.ShowAll (); Properties.Set<Gtk.Widget> ("Nereid.SourceContents.HeaderWidget", header_widget); } Properties.Set<Banshee.Sources.Gui.ISourceContents> ("Nereid.SourceContents", new Banshee.Sources.Gui.LazyLoadSourceContents<SearchView> (this)); } public void SetSearch (SearchDescription settings) { SearchDescription = settings; settings.ApplyTo (Search); Reload (); OnUpdated (); ServiceManager.SourceManager.SetActiveSource (this); } public void Reload () { model.Clear (); ThreadAssist.SpawnFromMain (delegate { ThreadedFetch (0); }); } public void FetchMore () { ThreadAssist.SpawnFromMain (delegate { ThreadedFetch (search.Page + 1); }); } private void ThreadedFetch (int page) { bool success = false; total_results = 0; status_text = ""; Exception err = null; int old_page = search.Page; search.Page = page; ThreadAssist.ProxyToMain (delegate { SetStatus (Catalog.GetString ("Searching the Internet Archive"), false, true, "gtk-find"); }); IA.SearchResults results = null; try { results = search.GetResults (); total_results = results.TotalResults; } catch (System.Net.WebException e) { Log.Error ("Error searching the Internet Archive", e); results = null; err = e; } if (results != null) { try { foreach (var result in results) { model.Add (result); // HACK to remove ugly empty description //if (track.Comment == "There is currently no description for this item.") //track.Comment = null; } success = true; } catch (Exception e) { err = e; Log.Error ("Error searching the Internet Archive", e); } } if (success) { int count = model.Count; if (total_results == 0) { ThreadAssist.ProxyToMain (delegate { SetStatus (Catalog.GetString ("No matches."), false, false, "gtk-info"); }); } else { ThreadAssist.ProxyToMain (ClearMessages); status_text = String.Format (Catalog.GetPluralString ( "Showing 1 match", "Showing 1 to {0:N0} of {1:N0} total matches", total_results), count, total_results ); } } else { search.Page = old_page; ThreadAssist.ProxyToMain (delegate { var web_e = err as System.Net.WebException; if (web_e != null && web_e.Status == System.Net.WebExceptionStatus.Timeout) { SetStatus (Catalog.GetString ("Timed out searching the Internet Archive"), true); CurrentMessage.AddAction (new MessageAction (Catalog.GetString ("Try Again"), (o, a) => { if (page == 0) Reload (); else FetchMore (); })); } else { SetStatus (Catalog.GetString ("Error searching the Internet Archive"), true); } }); } ThreadAssist.ProxyToMain (delegate { model.Reload (); OnUpdated (); }); } public override string PreferencesPageId { get { return Parent.PreferencesPageId; } } public override int Count { get { return 0; } } protected override int StatusFormatsCount { get { return 1; } } public override string GetStatusText () { return status_text; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.Text; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using fyiReporting.RDL; namespace fyiReporting.RDL { /// <summary> /// Different elements in the pdf file /// </summary> internal class PdfElements { private PdfPageSize pSize; private StringBuilder elements; private PdfPage p; // Below are used when rotating text 90% - numbers are odd but by experimentation PDF readers liked them best const double rads = -283.0/180.0; static readonly double radsCos = Math.Cos(rads); static readonly double radsSin = Math.Sin(rads); internal PdfElements(PdfPage pg, PdfPageSize pageSize) { p = pg; pSize=pageSize; elements = new StringBuilder(); } internal PdfPageSize PageSize { get { return pSize; } } /// <summary> /// Page line element at the X Y to X2 Y2 position /// </summary> /// <returns></returns> internal void AddLine(float x,float y, float x2, float y2, StyleInfo si) { AddLine(x, y, x2, y2, si.BWidthTop, si.BColorTop, si.BStyleTop); } /// <summary> /// Page line element at the X Y to X2 Y2 position /// </summary> /// <returns></returns> internal void AddLine(float x,float y, float x2, float y2, float width, System.Drawing.Color c, BorderStyleEnum ls) { // Get the line color double red=c.R; double green=c.G; double blue=c.B; red = Math.Round((red/255),3); green = Math.Round((green/255),3); blue = Math.Round((blue/255),3); // Get the line style Dotted - Dashed - Solid string linestyle; switch (ls) { case BorderStyleEnum.Dashed: linestyle="[3 2] 0 d"; break; case BorderStyleEnum.Dotted: linestyle="[2] 0 d"; break; case BorderStyleEnum.Solid: default: linestyle="[] 0 d"; break; } elements.AppendFormat(NumberFormatInfo.InvariantInfo, "\r\nq\t{0} w\t{1} {2} {3} RG\t{4}\t{5} {6} m\t{7} {8} l\tS\tQ\t", width, // line width red, green, blue, // line color linestyle, // line style x, pSize.yHeight-y, x2, pSize.yHeight-y2); // positioning } /// <summary> /// Add a filled rectangle /// </summary> /// <returns></returns> internal void AddFillRect(float x,float y, float width, float height, Color c) { // Get the fill color double red=c.R; double green=c.G; double blue=c.B; red = Math.Round((red/255),3); green = Math.Round((green/255),3); blue = Math.Round((blue/255),3); elements.AppendFormat(NumberFormatInfo.InvariantInfo, "\r\nq\t{0} {1} {2} RG\t{0} {1} {2} rg\t{3} {4} {5} {6} re\tf\tQ\t", red, green, blue, // color x, pSize.yHeight-y-height, width, height); // positioning } internal void AddFillRect(float x,float y, float width, float height,StyleInfo si,PdfPattern patterns) { // Get the fill color - could be a gradient or pattern etc... Color c = si.BackgroundColor; double red=c.R; double green=c.G; double blue=c.B; red = Math.Round((red/255),3); green = Math.Round((green/255),3); blue = Math.Round((blue/255),3); //Fill the rectangle with the background color first... elements.AppendFormat(NumberFormatInfo.InvariantInfo, "\r\nq\t{0} {1} {2} RG\t{0} {1} {2} rg\t{3} {4} {5} {6} re\tf\tQ\t", red, green, blue, // color x, pSize.yHeight-y-height, width, height); // positioning //if we have a pattern paint it now... if (si.PatternType != patternTypeEnum.None) { string p = patterns.GetPdfPattern(si.PatternType.ToString()); c = si.Color; red = Math.Round((c.R/255.0),3); green = Math.Round((c.G/255.0),3); blue = Math.Round((c.B/255.0),3); elements.AppendFormat("\r\nq"); elements.AppendFormat("\r\n /CS1 cs"); elements.AppendFormat("\r\n {0} {1} {2} /{3} scn",red,green,blue,p); elements.AppendFormat("\r\n {0} {1} {2} RG",red,green,blue); elements.AppendFormat("\r\n {0} {1} {2} {3} re\tf",x, pSize.yHeight-y-height, width, height); elements.AppendFormat("\tQ"); } } /// <summary> /// Add image to the page. Adds a new XObject Image and a reference to it. /// </summary> /// <returns>string Image name</returns> internal string AddImage(PdfImages images, string name, int contentRef, StyleInfo si, ImageFormat imf, float x, float y, float width, float height, RectangleF clipRect, byte[] im, int samplesW, int samplesH, string url,string tooltip) { //MITEK:START---------------------------------- //Duc Phan added 20 Dec, 2007 clip image if (!clipRect.IsEmpty) { elements.AppendFormat(NumberFormatInfo.InvariantInfo, "\r\nq\t{0} {1} {2} {3} re W n", clipRect.X + pSize.leftMargin, pSize.yHeight - clipRect.Y - clipRect.Height - pSize.topMargin, clipRect.Width, clipRect.Height); } //MITEK:END---------------------------------- string imgname = images.GetPdfImage(this.p, name, contentRef, imf, im, samplesW, samplesH); elements.AppendFormat(NumberFormatInfo.InvariantInfo, "\r\nq\t{2} 0 0 {3} {0} {1} cm\t", x, pSize.yHeight-y-height, width, height); // push graphics state, positioning elements.AppendFormat(NumberFormatInfo.InvariantInfo, "\t/{0} Do\tQ\t", imgname); // do the image then pop graphics state //MITEK:START---------------------------------- //Duc Phan added 20 Dec, 2007 clip image if (!clipRect.IsEmpty) { elements.AppendFormat("\tQ\t"); //pop graphics state } //MITEK:END---------------------------------- if (url != null) // p.AddHyperlink(x, pSize.yHeight-y, height, width, url); p.AddHyperlink(x + pSize.leftMargin, pSize.yHeight - y - pSize.topMargin, height, width, url);// Duc Phan modified 4 Sep, 2007 to account for the page margin if(tooltip != null) p.AddToolTip(x + pSize.leftMargin, pSize.yHeight - y - pSize.topMargin, height, width, tooltip); // Border goes around the image padding AddBorder(si, x-si.PaddingLeft, y-si.PaddingTop, height + si.PaddingTop+ si.PaddingBottom, width + si.PaddingLeft + si.PaddingRight); // add any required border return imgname; } /// <summary> /// Page Polygon /// </summary> /// <param name="pts"></param> /// <param name="si"></param> /// <param name="url"></param> /// <param name="patterns"></param> internal void AddPolygon(PointF[] pts, StyleInfo si, string url, PdfPattern patterns) { if (si.BackgroundColor.IsEmpty) return; // nothing to do // Get the fill color - could be a gradient or pattern etc... Color c = si.BackgroundColor; double red = c.R; double green = c.G; double blue = c.B; red = Math.Round((red / 255), 3); green = Math.Round((green / 255), 3); blue = Math.Round((blue / 255), 3); //Fill the polygon with the background color first... elements.AppendFormat(NumberFormatInfo.InvariantInfo, "\r\nq\t{0} {1} {2} RG\t{0} {1} {2} rg\t", red, green, blue); // color AddPoints(elements, pts); //if we have a pattern paint it now... if (si.PatternType != patternTypeEnum.None) { string p = patterns.GetPdfPattern(si.PatternType.ToString()); c = si.Color; red = Math.Round((c.R / 255.0), 3); green = Math.Round((c.G / 255.0), 3); blue = Math.Round((c.B / 255.0), 3); elements.AppendFormat("\r\nq"); elements.AppendFormat("\r\n /CS1 cs"); elements.AppendFormat("\r\n {0} {1} {2} /{3} scn", red, green, blue, p); elements.AppendFormat("\r\n {0} {1} {2} RG", red, green, blue); AddPoints(elements, pts); } elements.AppendFormat("\tQ"); } private void AddPoints(StringBuilder elements, PointF[] pts) { for (int pi = 0; pi < pts.Length; pi++) { elements.AppendFormat("\t{0} {1} {2}", pts[pi].X, pSize.yHeight - pts[pi].Y, pi == 0 ? "m" : "l"); } elements.Append("\th\tf"); return; } /// <summary> /// Page Rectangle element at the X Y position /// </summary> /// <returns></returns> internal void AddRectangle(float x, float y, float height, float width, StyleInfo si, string url, PdfPattern patterns, string tooltip) { // Draw background rectangle if needed if (!si.BackgroundColor.IsEmpty && height > 0 && width > 0) { // background color, height and width are specified AddFillRect(x, y, width, height, si,patterns); } AddBorder(si, x, y, height, width); // add any required border if (url != null) p.AddHyperlink(x, pSize.yHeight-y, height, width, url); if (!string.IsNullOrEmpty(tooltip)) p.AddToolTip(x, pSize.yHeight - y, height, width, tooltip); return; } //25072008 GJL Draw a pie internal void AddPie(float x, float y, float height, float width, StyleInfo si, string url, PdfPattern patterns, string tooltip) { // Draw background rectangle if needed if (!si.BackgroundColor.IsEmpty && height > 0 && width > 0) { // background color, height and width are specified AddFillRect(x, y, width, height, si, patterns); } AddBorder(si, x, y, height, width); // add any required border //Do something... if (url != null) p.AddHyperlink(x, pSize.yHeight - y, height, width, url); if (!string.IsNullOrEmpty(tooltip)) p.AddToolTip(x, pSize.yHeight - y, height, width, tooltip); return; } // internal void AddCurve(PointF[] pts, StyleInfo si) { if (pts.Length > 2) { // do a spline curve PointF[] tangents = GetCurveTangents(pts); DoCurve(pts, tangents, si); } else { // we only have two points; just do a line segment AddLine(pts[0].X, pts[0].Y, pts[1].X, pts[1].Y, si); } } void DoCurve(PointF[] points, PointF[] tangents, StyleInfo si) { int i; for (i = 0; i < points.Length - 1; i++) { int j = i + 1; float x0 = points[i].X; float y0 = points[i].Y; float x1 = points[i].X + tangents[i].X; float y1 = points[i].Y + tangents[i].Y; float x2 = points[j].X - tangents[j].X; float y2 = points[j].Y - tangents[j].Y; float x3 = points[j].X; float y3 = points[j].Y; AddCurve(x0,y0,x1,y1,x2,y2,x3,y3, si, null); } } PointF[] GetCurveTangents(PointF[] points) { float tension = .5f; // This is the tension used on the DrawCurve GDI call. float coefficient = tension / 3.0f; int i; PointF[] tangents = new PointF[points.Length]; // initialize everything to zero to begin with for (i = 0; i < tangents.Length; i++) { tangents[i].X = 0; tangents[i].Y = 0; } if (tangents.Length <= 2) return tangents; int count = tangents.Length; for (i = 0; i < count; i++) { int r = i + 1; int s = i - 1; if (r >= points.Length) r = points.Length - 1; if (s < 0) s = 0; tangents[i].X += (coefficient * (points[r].X - points[s].X)); tangents[i].Y += (coefficient * (points[r].Y - points[s].Y)); } return tangents; } //25072008 GJL Draw a bezier curve internal void AddCurve(float X1, float Y1, float X2, float Y2, float X3, float Y3, float X4, float Y4,StyleInfo si, string url) { string linestyle; switch (si.BStyleTop) { case BorderStyleEnum.Dashed: linestyle="[3 2] 0 d"; break; case BorderStyleEnum.Dotted: linestyle="[2] 0 d"; break; case BorderStyleEnum.Solid: default: linestyle="[] 0 d"; break; } elements.AppendFormat("\r\nq\t"); if (si.BStyleTop != BorderStyleEnum.None) { elements.AppendFormat("{0} w\t {1} \t",si.BWidthTop,linestyle); elements.AppendFormat("{0} {1} {2} RG\t", Math.Round(si.BColorTop.R / 255.0, 3), Math.Round(si.BColorTop.G / 255.0, 3), Math.Round(si.BColorTop.B / 255.0, 3)); //Set Stroking colours } if (!si.BackgroundColor.IsEmpty) { elements.AppendFormat("{0} {1} {2} rg\t", Math.Round(si.BackgroundColor.R / 255.0, 3), Math.Round(si.BackgroundColor.G / 255.0, 3), Math.Round(si.BackgroundColor.B / 255.0, 3)); //Set Non Stroking colours } elements.AppendFormat("{0} {1} m\t", X1, pSize.yHeight-Y1);//FirstPoint.. elements.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X2, pSize.yHeight -Y2, X3,pSize.yHeight-Y3, X4,pSize.yHeight- Y4); if (!si.BackgroundColor.IsEmpty && si.BStyleTop != BorderStyleEnum.None) { //Line and fill elements.AppendFormat("B\t"); } else if (si.BStyleTop != BorderStyleEnum.None) { //Line elements.AppendFormat("S\t"); } else if (!si.BackgroundColor.IsEmpty) { //fill elements.AppendFormat("f\t"); } elements.AppendFormat("Q\t"); } //25072008 GJL Draw 4 bezier curves to approximate a circle internal void AddEllipse(float x, float y, float height,float width, StyleInfo si, string url) { //Ok we need to draw 4 bezier curves - Unfortunately we cant call drawcurve 4 times because of the fill - we would end up drawing 4 filled arcs with an empty diamond in the middle //but we will still include a drawcurve function - it may be usefull one day float k = 0.5522847498f; float RadiusX = (width / 2.0f) ; float RadiusY = (height / 2.0f) ; float kRy = k * RadiusY; float kRx = k * RadiusX; float Y4 = y; float X1 = x; float Y1 = Y4 + RadiusY; float X4 = X1 + RadiusX; //Control Point 1 will be on the same X as point 1 and be -kRy Y float X2 = X1; float Y2 = Y1 - kRy; float X3 = X4 - kRx; float Y3 = Y4; elements.AppendFormat("\r\nq\t"); elements.AppendFormat("{0} {1} m\t", X1, pSize.yHeight-Y1);//FirstPoint.. if (si.BStyleTop != BorderStyleEnum.None) { string linestyle; switch (si.BStyleTop) { case BorderStyleEnum.Dashed: linestyle="[3 2] 0 d"; break; case BorderStyleEnum.Dotted: linestyle="[2] 0 d"; break; case BorderStyleEnum.Solid: default: linestyle="[] 0 d"; break; } elements.AppendFormat("{0} w\t {1} \t",si.BWidthTop,linestyle); elements.AppendFormat("{0} {1} {2} RG\t", Math.Round(si.BColorTop.R / 255.0, 3), Math.Round(si.BColorTop.G / 255.0, 3), Math.Round(si.BColorTop.B / 255.0, 3)); //Set Stroking colours } if (!si.BackgroundColor.IsEmpty) { elements.AppendFormat("{0} {1} {2} rg\t", Math.Round(si.BackgroundColor.R / 255.0, 3), Math.Round(si.BackgroundColor.G / 255.0, 3), Math.Round(si.BackgroundColor.B / 255.0, 3)); //Set Non Stroking colours } elements.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X2, pSize.yHeight -Y2, X3,pSize.yHeight-Y3, X4,pSize.yHeight- Y4); X1 += 2 * RadiusX; X2 = X1; X3 += 2 * kRx; elements.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X3, pSize.yHeight -Y3, X2,pSize.yHeight-Y2, X1,pSize.yHeight- Y1); Y2 += 2 * kRy; Y3 += 2 * RadiusY; Y4 = Y3; elements.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X2, pSize.yHeight -Y2, X3,pSize.yHeight-Y3, X4,pSize.yHeight- Y4); X1 -= 2 * RadiusX; X2 = X1; X3 -= 2 * kRx; elements.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X3, pSize.yHeight -Y3, X2,pSize.yHeight-Y2, X1,pSize.yHeight- Y1); if (!si.BackgroundColor.IsEmpty && si.BStyleTop != BorderStyleEnum.None) { //Line and fill elements.AppendFormat("B\t"); } else if (si.BStyleTop != BorderStyleEnum.None) { //Line elements.AppendFormat("S\t"); } else if (!si.BackgroundColor.IsEmpty) { //fill elements.AppendFormat("f\t"); } elements.AppendFormat("Q\t"); } /// <summary> /// Page Text element at the X Y position; multiple lines handled /// </summary> /// <returns></returns> internal void AddText(float x, float y, float height, float width, string[] sa, StyleInfo si, PdfFonts fonts, float[] tw, bool bWrap, string url, bool bNoClip,string tooltip) { // Calculate the RGB colors e.g. RGB(255, 0, 0) = red = 1 0 0 rg double r = si.Color.R; double g = si.Color.G; double b = si.Color.B; r = Math.Round((r/255),3); g = Math.Round((g/255),3); b = Math.Round((b/255),3); string pdfFont = fonts.GetPdfFont(si); // get the pdf font resource name // Loop thru the lines of text for (int i=0; i < sa.Length; i++) { string text = sa[i]; float textwidth = tw[i]; // Calculate the x position float startX = x + si.PaddingLeft; // TODO: handle tb_rl float startY = y + si.PaddingTop + (i * si.FontSize); // TODO: handle tb_rl if (si.WritingMode == WritingModeEnum.lr_tb) { // TODO: not sure what alignment means with tb_lr so I'll leave it out for now switch(si.TextAlign) { case TextAlignEnum.Center: if (width > 0) startX = x + si.PaddingLeft + (width - si.PaddingLeft - si.PaddingRight)/2 - textwidth/2; break; case TextAlignEnum.Right: if (width > 0) startX = x + width - textwidth - si.PaddingRight; break; case TextAlignEnum.Left: default: break; } // Calculate the y position switch(si.VerticalAlign) { case VerticalAlignEnum.Middle: if (height <= 0) break; // calculate the middle of the region startY = y + si.PaddingTop + (height - si.PaddingTop - si.PaddingBottom)/2 - si.FontSize/2; // now go up or down depending on which line if (sa.Length == 1) break; if (sa.Length % 2 == 0) // even number { startY = startY - ((sa.Length/2 - i) * si.FontSize) + si.FontSize/2; } else { startY = startY - ((sa.Length/2 - i) * si.FontSize); } break; case VerticalAlignEnum.Bottom: if (height <= 0) break; startY = y + height - si.PaddingBottom - (si.FontSize * (sa.Length-i)); break; case VerticalAlignEnum.Top: default: break; } } else { //25072008 GJL - Move x in a little - it draws to close to the edge of the rectangle (25% of the font size seems to work!) and Center or right align vertical text startX += si.FontSize / 4; switch (si.TextAlign) { case TextAlignEnum.Center: if (height > 0) startY = y + si.PaddingLeft + (height - si.PaddingLeft - si.PaddingRight) / 2 - textwidth / 2; break; case TextAlignEnum.Right: if (width > 0) startY = y + height - textwidth - si.PaddingRight; break; case TextAlignEnum.Left: default: break; } } // Draw background rectangle if needed (only put out on the first line, since we do whole rectangle) if (!si.BackgroundColor.IsEmpty && height > 0 && width > 0 && i == 0) { // background color, height and width are specified AddFillRect(x, y, width, height, si.BackgroundColor); } // Set the clipping path if (height > 0 && width > 0) { if (bNoClip) // no clipping but we still want URL checking elements.Append("\r\nq\t"); else elements.AppendFormat(NumberFormatInfo.InvariantInfo, "\r\nq\t{0} {1} {2} {3} re W n", x, pSize.yHeight-y-height, width, height); if (url != null) p.AddHyperlink(x, pSize.yHeight-y, height, width, url); if (tooltip != null) p.AddToolTip(x, pSize.yHeight - y, height, width, tooltip); } else elements.Append("\r\nq\t"); // Escape the text string newtext = PdfUtility.UTF16StringQuoter(text); //string newtext = text.Replace("\\", "\\\\"); //newtext = newtext.Replace("(", "\\("); //newtext = newtext.Replace(")", "\\)"); if (si.WritingMode == WritingModeEnum.lr_tb) { elements.AppendFormat(NumberFormatInfo.InvariantInfo, "\r\nBT/{0} {1} Tf\t{5} {6} {7} rg\t{2} {3} Td \t({4}) Tj\tET\tQ\t", pdfFont,si.FontSize,startX,(pSize.yHeight-startY-si.FontSize),newtext, r, g, b); } else { // Rotate text -90 degrees=-.5 radians (this works for english don't know about true tb-rl language) // had to play with reader to find best approximation for this rotation; didn't do what I expected // see pdf spec section 4.2.2 pg 141 "Common Transformations" elements.AppendFormat(NumberFormatInfo.InvariantInfo, "\r\nBT/{0} {1} Tf\t{5} {6} {7} rg\t{8} {9} {10} {11} {2} {3} Tm \t({4}) Tj\tET\tQ\t", pdfFont,si.FontSize,startX,(pSize.yHeight-startY),newtext, r, g, b, radsCos, radsSin, -radsSin, radsCos); } // Handle underlining etc. float maxX; switch (si.TextDecoration) { case TextDecorationEnum.Underline: maxX = width > 0? Math.Min(x + width, startX+textwidth): startX+textwidth; AddLine(startX, startY+si.FontSize+1, maxX, startY+si.FontSize+1, 1, si.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.LineThrough: maxX = width > 0? Math.Min(x + width, startX+textwidth): startX+textwidth; AddLine(startX, startY+(si.FontSize/2)+1, maxX, startY+(si.FontSize/2)+1, 1, si.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.Overline: maxX = width > 0? Math.Min(x + width, startX+textwidth): startX+textwidth; AddLine(startX, startY+1, maxX, startY+1, 1, si.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.None: default: break; } } AddBorder(si, x, y, height, width); // add any required border return; } void AddBorder(StyleInfo si, float x, float y, float height, float width) { // Handle any border required TODO: optimize border by drawing a rect when possible if (height <= 0 || width <= 0) // no bounding box to use return; float ybottom = (y + height); float xright = x + width; if (si.BStyleTop != BorderStyleEnum.None && si.BWidthTop > 0) AddLine(x, y, xright, y, si.BWidthTop, si.BColorTop, si.BStyleTop); if (si.BStyleRight != BorderStyleEnum.None && si.BWidthRight > 0) AddLine(xright, y, xright, ybottom, si.BWidthRight, si.BColorRight, si.BStyleRight); if (si.BStyleLeft != BorderStyleEnum.None && si.BWidthLeft > 0) AddLine(x, y, x, ybottom, si.BWidthLeft, si.BColorLeft, si.BStyleLeft); if (si.BStyleBottom != BorderStyleEnum.None && si.BWidthBottom > 0) AddLine(x, ybottom, xright, ybottom, si.BWidthBottom, si.BColorBottom, si.BStyleBottom); return; } /// <summary> /// No more elements on the page. /// </summary> /// <returns></returns> internal string EndElements() { string r = elements.ToString(); elements = new StringBuilder(); // restart it return r; } } }
using System; using CommandLineParser.Compatibility; using CommandLineParser.Exceptions; namespace CommandLineParser.Arguments { /// <summary> /// Use BoundedValueArgument for an argument whose value must belong to an interval. /// </summary> /// <typeparam name="TValue">Type of the value, must support comparison</typeparam> /// <include file='..\Doc\CommandLineParser.xml' path='CommandLineParser/Arguments/BoundedValueArgument/*'/> public class BoundedValueArgument<TValue> : CertifiedValueArgument<TValue> where TValue : IComparable { #region min and max values private TValue _minValue; private TValue _maxValue; /// <summary> /// Minimal allowed value (inclusive) /// </summary> public TValue MinValue { get { return _minValue; } set { _minValue = value; UseMinValue = true; } } /// <summary> /// Maximal allowed value (inclusive) /// </summary> public TValue MaxValue { get { return _maxValue; } set { _maxValue = value; UseMaxValue = true; } } /// <summary> /// When set to true, value is checked for being greater than or equal to <see cref="MinValue"/> /// </summary> public bool UseMinValue { get; set; } /// <summary> /// When set to true, value is checked for being lesser than or equal to <see cref="MaxValue"/> /// </summary> public bool UseMaxValue { get; set; } #endregion #region constructor /// <summary> /// Creates new value argument with a <see cref="Argument.ShortName">short name</see>. /// Without any value bounds. /// </summary> /// <param name="shortName">Short name of the argument</param> public BoundedValueArgument(char shortName) : base(shortName) { } /// <summary> /// Creates new value argument with a <see cref="Argument.LongName">long name</see>. /// </summary> /// <param name="longName">Long name of the argument</param> public BoundedValueArgument(string longName) : base(longName) { } /// <summary> /// Creates new value argument with a <see cref="Argument.ShortName">short name</see> /// and <see cref="Argument.LongName">long name</see>. Without any value bounds. /// </summary> /// <param name="shortName">Short name of the argument</param> /// <param name="longName">Long name of the argument </param> public BoundedValueArgument(char shortName, string longName) : base(shortName, longName) { } /// <summary> /// Creates new value argument with a <see cref="Argument.ShortName">short name</see> /// and specified maximal value. /// </summary> /// <param name="shortName">Short name of the argument</param> /// <param name="maxValue">Maximal value of the argument</param> public BoundedValueArgument(char shortName, TValue maxValue) : base(shortName) { _maxValue = maxValue; UseMaxValue = true; } /// <summary> /// Creates new value argument with a <see cref="Argument.ShortName">short name</see> /// and specified minimal value. /// </summary> /// <param name="shortName">Short name of the argument</param> /// <param name="minValue">Minimal value of the argument</param> public BoundedValueArgument(TValue minValue, char shortName) : base(shortName) { _minValue = minValue; UseMinValue = true; } /// <summary> /// Creates new value argument with a <see cref="Argument.ShortName">short name</see> /// and specified minimal value and maximal value. /// </summary> /// <param name="shortName">Short name of the argument</param> /// <param name="minValue">Minimal value of the argument</param> /// <param name="maxValue">Maximal value of the argument</param> public BoundedValueArgument(char shortName, TValue minValue, TValue maxValue) : base(shortName) { _maxValue = maxValue; UseMaxValue = true; _minValue = minValue; UseMinValue = true; } /// <summary> /// Creates new value argument with a <see cref="Argument.ShortName">short name</see>and <see cref="Argument.LongName">long name</see> and specified maximal value. /// </summary> /// <param name="shortName">Short name of the argument</param> /// <param name="longName">Long name of the argument </param> /// <param name="maxValue">Maximal value of the argument</param> public BoundedValueArgument(char shortName, string longName, TValue maxValue) : base(shortName, longName) { _maxValue = maxValue; UseMaxValue = true; } /// <summary> /// Creates new value argument with a <see cref="Argument.ShortName">short name</see>and <see cref="Argument.LongName">long name</see> and specified minimal value. /// </summary> /// <param name="shortName">Short name of the argument</param> /// <param name="longName">Long name of the argument </param> /// <param name="minValue">minimal value of the argument</param> public BoundedValueArgument(TValue minValue, char shortName, string longName) : base(shortName, longName) { _minValue = minValue; UseMinValue = true; } /// <summary> /// Creates new value argument with a <see cref="Argument.ShortName">short name</see>and <see cref="Argument.LongName">long name</see> and specified minimal and maximal value. /// </summary> /// <param name="shortName">Short name of the argument</param> /// <param name="longName">Long name of the argument </param> /// <param name="maxValue">Maximal value of the argument</param> /// <param name="minValue">minimal value of the argument</param> public BoundedValueArgument(char shortName, string longName, TValue minValue, TValue maxValue) : base(shortName, longName) { _maxValue = maxValue; UseMaxValue = true; _minValue = minValue; UseMinValue = true; } /// <summary> /// Creates new value argument with a <see cref="Argument.ShortName">short name</see>, /// <see cref="Argument.LongName">long name</see> and <see cref="Argument.Description">description</see> and specified maximal value. /// </summary> /// <param name="shortName">Short name of the argument</param> /// <param name="longName">Long name of the argument </param> /// <param name="description">Description of the argument</param> /// <param name="maxValue">Maximal value of the argument</param> public BoundedValueArgument(char shortName, string longName, string description, TValue maxValue) : base(shortName, longName, description) { _maxValue = maxValue; UseMaxValue = true; } /// <summary> /// Creates new value argument with a <see cref="Argument.ShortName">short name</see>, /// <see cref="Argument.LongName">long name</see> and <see cref="Argument.Description">description</see> and specified minimal value. /// </summary> /// <param name="shortName">Short name of the argument</param> /// <param name="longName">Long name of the argument </param> /// <param name="description">Description of the argument</param> /// <param name="minValue">Minimal value of the argument</param> public BoundedValueArgument(TValue minValue, char shortName, string longName, string description) : base(shortName, longName, description) { _minValue = minValue; UseMinValue = true; } /// <summary> /// Creates new value argument with a <see cref="Argument.ShortName">short name</see>, /// <see cref="Argument.LongName">long name</see> and <see cref="Argument.Description">description</see> and specified minimal and maximal value. /// </summary> /// <param name="shortName">Short name of the argument</param> /// <param name="longName">Long name of the argument </param> /// <param name="description">Description of the argument</param> /// <param name="minValue">Minimal value of the argument</param> /// <param name="maxValue">Maximal value of the argument</param> public BoundedValueArgument(char shortName, string longName, string description, TValue minValue, TValue maxValue) : base(shortName, longName, description) { _maxValue = maxValue; UseMaxValue = true; _minValue = minValue; UseMinValue = true; } #endregion /// <summary> /// Checks whether the value belongs to the [<see cref="MinValue"/>, <see cref="MaxValue"/>] interval /// (when <see cref="UseMinValue"/> and <see cref="UseMaxValue"/> are set). /// </summary> /// <param name="value">value to certify</param> /// <exception cref="CommandLineArgumentOutOfRangeException">Thrown when <paramref name="value"/> lies outside the interval. </exception> protected override void Certify(TValue value) { if (UseMinValue && MinValue.CompareTo(value) == 1) { throw new CommandLineArgumentOutOfRangeException( string.Format(Messages.EXC_ARG_BOUNDED_LESSER_THAN_MIN, value, _minValue), Name); } if (UseMaxValue && MaxValue.CompareTo(value) == -1) { throw new CommandLineArgumentOutOfRangeException( string.Format(Messages.EXC_ARG_BOUNDED_GREATER_THAN_MAX, value, _maxValue), Name); } } } /// <summary> /// <para> /// Attribute for declaring a class' field a <see cref="BoundedValueArgument{TValue}"/> and /// thus binding a field's value to a certain command line switch argument. /// </para> /// <para> /// Instead of creating an argument explicitly, you can assign a class' field an argument /// attribute and let the CommandLineParse take care of binding the attribute to the field. /// </para> /// </summary> /// <remarks>Appliable to fields and properties (public).</remarks> /// <remarks>Use <see cref="CommandLineParser.ExtractArgumentAttributes"/> for each object /// you where you have delcared argument attributes.</remarks> public class BoundedValueArgumentAttribute : ArgumentAttribute { private readonly Type _argumentType; /// <summary> /// Creates proper generic <see cref="BoundedValueArgument{TValue}"/> type for <paramref name="type"/>. /// </summary> /// <param name="type">type of the argument value</param> /// <returns>generic type</returns> private static Type CreateProperValueArgumentType(Type type) { Type genericType = typeof(BoundedValueArgument<>); Type constructedType = genericType.MakeGenericType(type); return constructedType; } /// <summary> /// Creates new instance of BoundedValueArgument. BoundedValueArgument /// uses underlying <see cref="BoundedValueArgument{TValue}"/>. /// </summary> /// <param name="type">Type of the generic parameter of <see cref="BoundedValueArgument{TValue}"/>.</param> /// <param name="shortName"><see cref="Argument.ShortName">short name</see> of the underlying argument</param> /// <remarks> /// Parameter <paramref name="type"/> has to be either built-in /// type or has to define a static Parse(String, CultureInfo) /// method for reading the value from string. /// </remarks> public BoundedValueArgumentAttribute(Type type, char shortName) : base(CreateProperValueArgumentType(type), shortName) { _argumentType = CreateProperValueArgumentType(type); } /// <summary> /// Creates new instance of BoundedValueArgument. BoundedValueArgument /// uses underlying <see cref="BoundedValueArgument{TValue}"/>. /// </summary> /// <param name="type">Type of the generic parameter of <see cref="BoundedValueArgument{TValue}"/>.</param> /// <param name="longName"><see cref="Argument.LongName">long name</see> of the underlying argument</param> /// <remarks> /// Parameter <paramref name="type"/> has to be either built-in /// type or has to define a static Parse(String, CultureInfo) /// method for reading the value from string. /// </remarks> public BoundedValueArgumentAttribute(Type type, string longName) : base(CreateProperValueArgumentType(type), longName) { _argumentType = CreateProperValueArgumentType(type); } /// <summary> /// Creates new instance of BoundedValueArgument. BoundedValueArgument /// uses underlying <see cref="BoundedValueArgument{TValue}"/>. /// </summary> /// <param name="type">Type of the generic parameter of <see cref="BoundedValueArgument{TValue}"/>.</param> /// <param name="shortName"><see cref="Argument.ShortName">short name</see> of the underlying argument</param> /// <param name="longName"><see cref="Argument.LongName">long name</see> of the underlying argument</param> /// <remarks> /// Parameter <paramref name="type"/> has to be either built-in /// type or has to define a static Parse(String, CultureInfo) /// method for reading the value from string. /// </remarks> public BoundedValueArgumentAttribute(Type type, char shortName, string longName) : base(CreateProperValueArgumentType(type), shortName, longName) { _argumentType = CreateProperValueArgumentType(type); } /// <summary> /// Maximal allowed value (inclusive) /// </summary> public object MaxValue { get { return _argumentType.GetPropertyValue<object>("MaxValue", Argument); } set { _argumentType.SetPropertyValue("MaxValue", Argument, value); } } /// <summary> /// Minimal allowed value (inclusive) /// </summary> public object MinValue { get { return _argumentType.GetPropertyValue<object>("MinValue", Argument); } set { _argumentType.SetPropertyValue("MinValue", Argument, value); } } /// <summary> /// When set to true, value is checked for being lesser than or equal to <see cref="MaxValue"/> /// </summary> public bool UseMaxValue { get { return _argumentType.GetPropertyValue<bool>("UseMaxValue", Argument); } set { _argumentType.SetPropertyValue("UseMaxValue", Argument, value); } } /// <summary> /// When set to true, value is checked for being greater than or equal to <see cref="MinValue"/> /// </summary> public bool UseMinValue { get { return _argumentType.GetPropertyValue<bool>("UseMinValue", Argument); } set { _argumentType.SetPropertyValue("UseMinValue", Argument, value); } } /// <summary> /// Default value /// </summary> public object DefaultValue { get { return _argumentType.GetPropertyValue<object>("DefaultValue", Argument); } set { _argumentType.SetPropertyValue("DefaultValue", Argument, value); } } /// <summary> /// When set to true, argument can appear on the command line with or without value, e.g. both is allowed: /// <code> /// myexe.exe -Arg Value /// OR /// myexe.exe -Arg /// </code> /// </summary> public bool ValueOptional { get { return _argumentType.GetPropertyValue<bool>("ValueOptional", Argument); } set { _argumentType.SetPropertyValue("ValueOptional", Argument, 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. /*============================================================ ** ** ** ** Purpose: Capture execution context for a thread ** ** ===========================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.Serialization; namespace System.Threading { public delegate void ContextCallback(object? state); internal delegate void ContextCallback<TState>(ref TState state); public sealed class ExecutionContext : IDisposable, ISerializable { internal static readonly ExecutionContext Default = new ExecutionContext(isDefault: true); internal static readonly ExecutionContext DefaultFlowSuppressed = new ExecutionContext(AsyncLocalValueMap.Empty, Array.Empty<IAsyncLocal>(), isFlowSuppressed: true); private readonly IAsyncLocalValueMap? m_localValues; private readonly IAsyncLocal[]? m_localChangeNotifications; private readonly bool m_isFlowSuppressed; private readonly bool m_isDefault; private ExecutionContext(bool isDefault) { m_isDefault = isDefault; } private ExecutionContext( IAsyncLocalValueMap localValues, IAsyncLocal[]? localChangeNotifications, bool isFlowSuppressed) { m_localValues = localValues; m_localChangeNotifications = localChangeNotifications; m_isFlowSuppressed = isFlowSuppressed; } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public static ExecutionContext? Capture() { ExecutionContext? executionContext = Thread.CurrentThread._executionContext; if (executionContext == null) { executionContext = Default; } else if (executionContext.m_isFlowSuppressed) { executionContext = null; } return executionContext; } private ExecutionContext? ShallowClone(bool isFlowSuppressed) { Debug.Assert(isFlowSuppressed != m_isFlowSuppressed); if (m_localValues == null || AsyncLocalValueMap.IsEmpty(m_localValues)) { return isFlowSuppressed ? DefaultFlowSuppressed : null; // implies the default context } return new ExecutionContext(m_localValues, m_localChangeNotifications, isFlowSuppressed); } public static AsyncFlowControl SuppressFlow() { Thread currentThread = Thread.CurrentThread; ExecutionContext? executionContext = currentThread._executionContext ?? Default; if (executionContext.m_isFlowSuppressed) { throw new InvalidOperationException(SR.InvalidOperation_CannotSupressFlowMultipleTimes); } executionContext = executionContext.ShallowClone(isFlowSuppressed: true); var asyncFlowControl = new AsyncFlowControl(); currentThread._executionContext = executionContext; asyncFlowControl.Initialize(currentThread); return asyncFlowControl; } public static void RestoreFlow() { Thread currentThread = Thread.CurrentThread; ExecutionContext? executionContext = currentThread._executionContext; if (executionContext == null || !executionContext.m_isFlowSuppressed) { throw new InvalidOperationException(SR.InvalidOperation_CannotRestoreUnsupressedFlow); } currentThread._executionContext = executionContext.ShallowClone(isFlowSuppressed: false); } public static bool IsFlowSuppressed() { ExecutionContext? executionContext = Thread.CurrentThread._executionContext; return executionContext != null && executionContext.m_isFlowSuppressed; } internal bool HasChangeNotifications => m_localChangeNotifications != null; internal bool IsDefault => m_isDefault; public static void Run(ExecutionContext executionContext, ContextCallback callback, object? state) { // Note: ExecutionContext.Run is an extremely hot function and used by every await, ThreadPool execution, etc. if (executionContext == null) { ThrowNullContext(); } RunInternal(executionContext, callback, state); } internal static void RunInternal(ExecutionContext? executionContext, ContextCallback callback, object? state) { // Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc. // Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization" // https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/eh-writethru.md // Enregister variables with 0 post-fix so they can be used in registers without EH forcing them to stack // Capture references to Thread Contexts Thread currentThread0 = Thread.CurrentThread; Thread currentThread = currentThread0; ExecutionContext? previousExecutionCtx0 = currentThread0._executionContext; if (previousExecutionCtx0 != null && previousExecutionCtx0.m_isDefault) { // Default is a null ExecutionContext internally previousExecutionCtx0 = null; } // Store current ExecutionContext and SynchronizationContext as "previousXxx". // This allows us to restore them and undo any Context changes made in callback.Invoke // so that they won't "leak" back into caller. // These variables will cross EH so be forced to stack ExecutionContext? previousExecutionCtx = previousExecutionCtx0; SynchronizationContext? previousSyncCtx = currentThread0._synchronizationContext; if (executionContext != null && executionContext.m_isDefault) { // Default is a null ExecutionContext internally executionContext = null; } if (previousExecutionCtx0 != executionContext) { RestoreChangedContextToThread(currentThread0, executionContext, previousExecutionCtx0); } ExceptionDispatchInfo? edi = null; try { callback.Invoke(state); } catch (Exception ex) { // Note: we have a "catch" rather than a "finally" because we want // to stop the first pass of EH here. That way we can restore the previous // context before any of our callers' EH filters run. edi = ExceptionDispatchInfo.Capture(ex); } // Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack SynchronizationContext? previousSyncCtx1 = previousSyncCtx; Thread currentThread1 = currentThread; // The common case is that these have not changed, so avoid the cost of a write barrier if not needed. if (currentThread1._synchronizationContext != previousSyncCtx1) { // Restore changed SynchronizationContext back to previous currentThread1._synchronizationContext = previousSyncCtx1; } ExecutionContext? previousExecutionCtx1 = previousExecutionCtx; ExecutionContext? currentExecutionCtx1 = currentThread1._executionContext; if (currentExecutionCtx1 != previousExecutionCtx1) { RestoreChangedContextToThread(currentThread1, previousExecutionCtx1, currentExecutionCtx1); } // If exception was thrown by callback, rethrow it now original contexts are restored edi?.Throw(); } // Direct copy of the above RunInternal overload, except that it passes the state into the callback strongly-typed and by ref. internal static void RunInternal<TState>(ExecutionContext? executionContext, ContextCallback<TState> callback, ref TState state) { // Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc. // Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization" // https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/eh-writethru.md // Enregister variables with 0 post-fix so they can be used in registers without EH forcing them to stack // Capture references to Thread Contexts Thread currentThread0 = Thread.CurrentThread; Thread currentThread = currentThread0; ExecutionContext? previousExecutionCtx0 = currentThread0._executionContext; if (previousExecutionCtx0 != null && previousExecutionCtx0.m_isDefault) { // Default is a null ExecutionContext internally previousExecutionCtx0 = null; } // Store current ExecutionContext and SynchronizationContext as "previousXxx". // This allows us to restore them and undo any Context changes made in callback.Invoke // so that they won't "leak" back into caller. // These variables will cross EH so be forced to stack ExecutionContext? previousExecutionCtx = previousExecutionCtx0; SynchronizationContext? previousSyncCtx = currentThread0._synchronizationContext; if (executionContext != null && executionContext.m_isDefault) { // Default is a null ExecutionContext internally executionContext = null; } if (previousExecutionCtx0 != executionContext) { RestoreChangedContextToThread(currentThread0, executionContext, previousExecutionCtx0); } ExceptionDispatchInfo? edi = null; try { callback.Invoke(ref state); } catch (Exception ex) { // Note: we have a "catch" rather than a "finally" because we want // to stop the first pass of EH here. That way we can restore the previous // context before any of our callers' EH filters run. edi = ExceptionDispatchInfo.Capture(ex); } // Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack SynchronizationContext? previousSyncCtx1 = previousSyncCtx; Thread currentThread1 = currentThread; // The common case is that these have not changed, so avoid the cost of a write barrier if not needed. if (currentThread1._synchronizationContext != previousSyncCtx1) { // Restore changed SynchronizationContext back to previous currentThread1._synchronizationContext = previousSyncCtx1; } ExecutionContext? previousExecutionCtx1 = previousExecutionCtx; ExecutionContext? currentExecutionCtx1 = currentThread1._executionContext; if (currentExecutionCtx1 != previousExecutionCtx1) { RestoreChangedContextToThread(currentThread1, previousExecutionCtx1, currentExecutionCtx1); } // If exception was thrown by callback, rethrow it now original contexts are restored edi?.Throw(); } internal static void RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, object state) { Debug.Assert(threadPoolThread == Thread.CurrentThread); CheckThreadPoolAndContextsAreDefault(); // ThreadPool starts on Default Context so we don't need to save the "previous" state as we know it is Default (null) // Default is a null ExecutionContext internally if (executionContext != null && !executionContext.m_isDefault) { // Non-Default context to restore RestoreChangedContextToThread(threadPoolThread, contextToRestore: executionContext, currentContext: null); } ExceptionDispatchInfo? edi = null; try { callback.Invoke(state); } catch (Exception ex) { // Note: we have a "catch" rather than a "finally" because we want // to stop the first pass of EH here. That way we can restore the previous // context before any of our callers' EH filters run. edi = ExceptionDispatchInfo.Capture(ex); } // Enregister threadPoolThread as it crossed EH, and use enregistered variable Thread currentThread = threadPoolThread; ExecutionContext? currentExecutionCtx = currentThread._executionContext; // Restore changed SynchronizationContext back to Default currentThread._synchronizationContext = null; if (currentExecutionCtx != null) { // The EC always needs to be reset for this overload, as it will flow back to the caller if it performs // extra work prior to returning to the Dispatch loop. For example for Task-likes it will flow out of await points RestoreChangedContextToThread(currentThread, contextToRestore: null, currentExecutionCtx); } // If exception was thrown by callback, rethrow it now original contexts are restored edi?.Throw(); } internal static void RunForThreadPoolUnsafe<TState>(ExecutionContext executionContext, Action<TState> callback, in TState state) { // We aren't running in try/catch as if an exception is directly thrown on the ThreadPool either process // will crash or its a ThreadAbortException. CheckThreadPoolAndContextsAreDefault(); Debug.Assert(executionContext != null && !executionContext.m_isDefault, "ExecutionContext argument is Default."); // Restore Non-Default context Thread.CurrentThread._executionContext = executionContext; if (executionContext.HasChangeNotifications) { OnValuesChanged(previousExecutionCtx: null, executionContext); } callback.Invoke(state); // ThreadPoolWorkQueue.Dispatch will handle notifications and reset EC and SyncCtx back to default } internal static void RestoreChangedContextToThread(Thread currentThread, ExecutionContext? contextToRestore, ExecutionContext? currentContext) { Debug.Assert(currentThread == Thread.CurrentThread); Debug.Assert(contextToRestore != currentContext); // Restore changed ExecutionContext back to previous currentThread._executionContext = contextToRestore; if ((currentContext != null && currentContext.HasChangeNotifications) || (contextToRestore != null && contextToRestore.HasChangeNotifications)) { // There are change notifications; trigger any affected OnValuesChanged(currentContext, contextToRestore); } } // Inline as only called in one place and always called [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ResetThreadPoolThread(Thread currentThread) { ExecutionContext? currentExecutionCtx = currentThread._executionContext; // Reset to defaults currentThread._synchronizationContext = null; currentThread._executionContext = null; if (currentExecutionCtx != null && currentExecutionCtx.HasChangeNotifications) { OnValuesChanged(currentExecutionCtx, nextExecutionCtx: null); // Reset to defaults again without change notifications in case the Change handler changed the contexts currentThread._synchronizationContext = null; currentThread._executionContext = null; } } [System.Diagnostics.Conditional("DEBUG")] internal static void CheckThreadPoolAndContextsAreDefault() { Debug.Assert(Thread.CurrentThread.IsThreadPoolThread); Debug.Assert(Thread.CurrentThread._executionContext == null, "ThreadPool thread not on Default ExecutionContext."); Debug.Assert(Thread.CurrentThread._synchronizationContext == null, "ThreadPool thread not on Default SynchronizationContext."); } internal static void OnValuesChanged(ExecutionContext? previousExecutionCtx, ExecutionContext? nextExecutionCtx) { Debug.Assert(previousExecutionCtx != nextExecutionCtx); // Collect Change Notifications IAsyncLocal[]? previousChangeNotifications = previousExecutionCtx?.m_localChangeNotifications; IAsyncLocal[]? nextChangeNotifications = nextExecutionCtx?.m_localChangeNotifications; // At least one side must have notifications Debug.Assert(previousChangeNotifications != null || nextChangeNotifications != null); // Fire Change Notifications try { if (previousChangeNotifications != null && nextChangeNotifications != null) { // Notifications can't exist without values Debug.Assert(previousExecutionCtx!.m_localValues != null); Debug.Assert(nextExecutionCtx!.m_localValues != null); // Both contexts have change notifications, check previousExecutionCtx first foreach (IAsyncLocal local in previousChangeNotifications) { previousExecutionCtx.m_localValues.TryGetValue(local, out object? previousValue); nextExecutionCtx.m_localValues.TryGetValue(local, out object? currentValue); if (previousValue != currentValue) { local.OnValueChanged(previousValue, currentValue, contextChanged: true); } } if (nextChangeNotifications != previousChangeNotifications) { // Check for additional notifications in nextExecutionCtx foreach (IAsyncLocal local in nextChangeNotifications) { // If the local has a value in the previous context, we already fired the event // for that local in the code above. if (!previousExecutionCtx.m_localValues.TryGetValue(local, out object? previousValue)) { nextExecutionCtx.m_localValues.TryGetValue(local, out object? currentValue); if (previousValue != currentValue) { local.OnValueChanged(previousValue, currentValue, contextChanged: true); } } } } } else if (previousChangeNotifications != null) { // Notifications can't exist without values Debug.Assert(previousExecutionCtx!.m_localValues != null); // No current values, so just check previous against null foreach (IAsyncLocal local in previousChangeNotifications) { previousExecutionCtx.m_localValues.TryGetValue(local, out object? previousValue); if (previousValue != null) { local.OnValueChanged(previousValue, null, contextChanged: true); } } } else // Implied: nextChangeNotifications != null { // Notifications can't exist without values Debug.Assert(nextExecutionCtx!.m_localValues != null); // No previous values, so just check current against null foreach (IAsyncLocal local in nextChangeNotifications!) { nextExecutionCtx.m_localValues.TryGetValue(local, out object? currentValue); if (currentValue != null) { local.OnValueChanged(null, currentValue, contextChanged: true); } } } } catch (Exception ex) { Environment.FailFast( SR.ExecutionContext_ExceptionInAsyncLocalNotification, ex); } } [DoesNotReturn] [StackTraceHidden] private static void ThrowNullContext() { throw new InvalidOperationException(SR.InvalidOperation_NullContext); } internal static object? GetLocalValue(IAsyncLocal local) { ExecutionContext? current = Thread.CurrentThread._executionContext; if (current == null) { return null; } Debug.Assert(!current.IsDefault); Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context"); current.m_localValues.TryGetValue(local, out object? value); return value; } internal static void SetLocalValue(IAsyncLocal local, object? newValue, bool needChangeNotifications) { ExecutionContext? current = Thread.CurrentThread._executionContext; object? previousValue = null; bool hadPreviousValue = false; if (current != null) { Debug.Assert(!current.IsDefault); Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context"); hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue); } if (previousValue == newValue) { return; } // Regarding 'treatNullValueAsNonexistent: !needChangeNotifications' below: // - When change notifications are not necessary for this IAsyncLocal, there is no observable difference between // storing a null value and removing the IAsyncLocal from 'm_localValues' // - When change notifications are necessary for this IAsyncLocal, the IAsyncLocal's absence in 'm_localValues' // indicates that this is the first value change for the IAsyncLocal and it needs to be registered for change // notifications. So in this case, a null value must be stored in 'm_localValues' to indicate that the IAsyncLocal // is already registered for change notifications. IAsyncLocal[]? newChangeNotifications = null; IAsyncLocalValueMap newValues; bool isFlowSuppressed = false; if (current != null) { Debug.Assert(!current.IsDefault); Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context"); isFlowSuppressed = current.m_isFlowSuppressed; newValues = current.m_localValues.Set(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications); newChangeNotifications = current.m_localChangeNotifications; } else { // First AsyncLocal newValues = AsyncLocalValueMap.Create(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications); } // // Either copy the change notification array, or create a new one, depending on whether we need to add a new item. // if (needChangeNotifications) { if (hadPreviousValue) { Debug.Assert(newChangeNotifications != null); Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0); } else if (newChangeNotifications == null) { newChangeNotifications = new IAsyncLocal[1] { local }; } else { int newNotificationIndex = newChangeNotifications.Length; Array.Resize(ref newChangeNotifications, newNotificationIndex + 1); newChangeNotifications[newNotificationIndex] = local; } } Thread.CurrentThread._executionContext = (!isFlowSuppressed && AsyncLocalValueMap.IsEmpty(newValues)) ? null : // No values, return to Default context new ExecutionContext(newValues, newChangeNotifications, isFlowSuppressed); if (needChangeNotifications) { local.OnValueChanged(previousValue, newValue, contextChanged: false); } } public ExecutionContext CreateCopy() { return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies. } public void Dispose() { // For CLR compat only } } public struct AsyncFlowControl : IDisposable { private Thread? _thread; internal void Initialize(Thread currentThread) { Debug.Assert(currentThread == Thread.CurrentThread); _thread = currentThread; } public void Undo() { if (_thread == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCMultiple); } if (Thread.CurrentThread != _thread) { throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCOtherThread); } // An async flow control cannot be undone when a different execution context is applied. The desktop framework // mutates the execution context when its state changes, and only changes the instance when an execution context // is applied (for instance, through ExecutionContext.Run). The framework prevents a suppressed-flow execution // context from being applied by returning null from ExecutionContext.Capture, so the only type of execution // context that can be applied is one whose flow is not suppressed. After suppressing flow and changing an async // local's value, the desktop framework verifies that a different execution context has not been applied by // checking the execution context instance against the one saved from when flow was suppressed. In .NET Core, // since the execution context instance will change after changing the async local's value, it verifies that a // different execution context has not been applied, by instead ensuring that the current execution context's // flow is suppressed. if (!ExecutionContext.IsFlowSuppressed()) { throw new InvalidOperationException(SR.InvalidOperation_AsyncFlowCtrlCtxMismatch); } _thread = null; ExecutionContext.RestoreFlow(); } public void Dispose() { Undo(); } public override bool Equals(object? obj) { return obj is AsyncFlowControl && Equals((AsyncFlowControl)obj); } public bool Equals(AsyncFlowControl obj) { return _thread == obj._thread; } public override int GetHashCode() { return _thread?.GetHashCode() ?? 0; } public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b) { return a.Equals(b); } public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b) { return !(a == b); } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// User Provisioning Config ///<para>SObject Name: UserProvisioningConfig</para> ///<para>Custom Object: False</para> ///</summary> public class SfUserProvisioningConfig : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "UserProvisioningConfig"; } } ///<summary> /// UserProvisioningConfig ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Name /// <para>Name: DeveloperName</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "developerName")] public string DeveloperName { get; set; } ///<summary> /// Master Language /// <para>Name: Language</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "language")] public string Language { get; set; } ///<summary> /// Label /// <para>Name: MasterLabel</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "masterLabel")] public string MasterLabel { get; set; } ///<summary> /// Namespace Prefix /// <para>Name: NamespacePrefix</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "namespacePrefix")] [Updateable(false), Createable(false)] public string NamespacePrefix { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Connected App ID /// <para>Name: ConnectedAppId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "connectedAppId")] public string ConnectedAppId { get; set; } ///<summary> /// ReferenceTo: ConnectedApplication /// <para>RelationshipName: ConnectedApp</para> ///</summary> [JsonProperty(PropertyName = "connectedApp")] [Updateable(false), Createable(false)] public SfConnectedApplication ConnectedApp { get; set; } ///<summary> /// Notes /// <para>Name: Notes</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "notes")] public string Notes { get; set; } ///<summary> /// Enabled /// <para>Name: Enabled</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "enabled")] public bool? Enabled { get; set; } ///<summary> /// Approval Required /// <para>Name: ApprovalRequired</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "approvalRequired")] public string ApprovalRequired { get; set; } ///<summary> /// User Account Mapping /// <para>Name: UserAccountMapping</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "userAccountMapping")] public string UserAccountMapping { get; set; } ///<summary> /// Enabled Operations /// <para>Name: EnabledOperations</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "enabledOperations")] public string EnabledOperations { get; set; } ///<summary> /// On Update Attributes /// <para>Name: OnUpdateAttributes</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "onUpdateAttributes")] public string OnUpdateAttributes { get; set; } ///<summary> /// Last Recon Date /// <para>Name: LastReconDateTime</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastReconDateTime")] public DateTimeOffset? LastReconDateTime { get; set; } ///<summary> /// Named Credential ID /// <para>Name: NamedCredentialId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "namedCredentialId")] public string NamedCredentialId { get; set; } ///<summary> /// ReferenceTo: NamedCredential /// <para>RelationshipName: NamedCredential</para> ///</summary> [JsonProperty(PropertyName = "namedCredential")] [Updateable(false), Createable(false)] public SfNamedCredential NamedCredential { get; set; } ///<summary> /// Recon Filter /// <para>Name: ReconFilter</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "reconFilter")] public string ReconFilter { get; set; } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup { internal sealed partial class EventHookupSessionManager { /// <summary> /// A session begins when an '=' is typed after a '+' and requires determining whether the /// += is being used to add an event handler to an event. If it is, then we also determine /// a candidate name for the event handler. /// </summary> internal class EventHookupSession : ForegroundThreadAffinitizedObject { public readonly Task<string> GetEventNameTask; private readonly CancellationTokenSource _cancellationTokenSource; private readonly ITrackingPoint _trackingPoint; private readonly ITrackingSpan _trackingSpan; private readonly ITextView _textView; private readonly ITextBuffer _subjectBuffer; public event Action Dismissed = () => { }; // For testing purposes only! Should always be null except in tests. internal Mutex TESTSessionHookupMutex = null; public ITrackingPoint TrackingPoint { get { AssertIsForeground(); return _trackingPoint; } } public ITrackingSpan TrackingSpan { get { AssertIsForeground(); return _trackingSpan; } } public ITextView TextView { get { AssertIsForeground(); return _textView; } } public ITextBuffer SubjectBuffer { get { AssertIsForeground(); return _subjectBuffer; } } public void Cancel() { AssertIsForeground(); _cancellationTokenSource.Cancel(); } public EventHookupSession( EventHookupSessionManager eventHookupSessionManager, EventHookupCommandHandler commandHandler, ITextView textView, ITextBuffer subjectBuffer, IAsynchronousOperationListener asyncListener, Mutex testSessionHookupMutex) { AssertIsForeground(); _cancellationTokenSource = new CancellationTokenSource(); _textView = textView; _subjectBuffer = subjectBuffer; this.TESTSessionHookupMutex = testSessionHookupMutex; var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null && document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { var position = textView.GetCaretPoint(subjectBuffer).Value.Position; _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(position, PointTrackingMode.Negative); _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(position, 1), SpanTrackingMode.EdgeInclusive); var asyncToken = asyncListener.BeginAsyncOperation(GetType().Name + ".Start"); this.GetEventNameTask = Task.Factory.SafeStartNewFromAsync( () => DetermineIfEventHookupAndGetHandlerNameAsync(document, position, _cancellationTokenSource.Token), _cancellationTokenSource.Token, TaskScheduler.Default); var continuedTask = this.GetEventNameTask.SafeContinueWith(t => { AssertIsForeground(); if (t.Result != null) { commandHandler.EventHookupSessionManager.EventHookupFoundInSession(this); } }, _cancellationTokenSource.Token, TaskContinuationOptions.OnlyOnRanToCompletion, ForegroundThreadAffinitizedObject.ForegroundTaskScheduler); continuedTask.CompletesAsyncOperation(asyncToken); } else { _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(0, PointTrackingMode.Negative); _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(), SpanTrackingMode.EdgeInclusive); this.GetEventNameTask = SpecializedTasks.Default<string>(); eventHookupSessionManager.CancelAndDismissExistingSessions(); } } private async Task<string> DetermineIfEventHookupAndGetHandlerNameAsync(Document document, int position, CancellationToken cancellationToken) { AssertIsBackground(); // For test purposes only! if (TESTSessionHookupMutex != null) { TESTSessionHookupMutex.WaitOne(); TESTSessionHookupMutex.ReleaseMutex(); } using (Logger.LogBlock(FunctionId.EventHookup_Determine_If_Event_Hookup, cancellationToken)) { var plusEqualsToken = await GetPlusEqualsTokenInsideAddAssignExpressionAsync(document, position, cancellationToken).ConfigureAwait(false); if (plusEqualsToken == null) { return null; } var semanticModel = await document.GetCSharpSemanticModelAsync(cancellationToken).ConfigureAwait(false); var eventSymbol = GetEventSymbol(semanticModel, plusEqualsToken.Value, cancellationToken); if (eventSymbol == null) { return null; } return GetEventHandlerName(eventSymbol, plusEqualsToken.Value, semanticModel, document.GetLanguageService<ISyntaxFactsService>()); } } private async Task<SyntaxToken?> GetPlusEqualsTokenInsideAddAssignExpressionAsync(Document document, int position, CancellationToken cancellationToken) { AssertIsBackground(); var syntaxTree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (token.Kind() != SyntaxKind.PlusEqualsToken) { return null; } if (!token.Parent.IsKind(SyntaxKind.AddAssignmentExpression)) { return null; } return token; } private IEventSymbol GetEventSymbol(SemanticModel semanticModel, SyntaxToken plusEqualsToken, CancellationToken cancellationToken) { AssertIsBackground(); var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax; if (parentToken == null) { return null; } var symbol = semanticModel.GetSymbolInfo(parentToken.Left, cancellationToken).Symbol; if (symbol == null) { return null; } return symbol as IEventSymbol; } private string GetEventHandlerName(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService) { AssertIsBackground(); var basename = string.Format("{0}_{1}", GetNameObjectPart(eventSymbol, plusEqualsToken, semanticModel, syntaxFactsService), eventSymbol.Name); basename = basename.ToPascalCase(trimLeadingTypePrefix: false); var reservedNames = semanticModel.LookupSymbols(plusEqualsToken.SpanStart).Select(m => m.Name); return NameGenerator.EnsureUniqueness(basename, reservedNames); } /// <summary> /// Take another look at the LHS of the += node -- we need to figure out a default name /// for the event handler, and that's usually based on the object (which is usually a /// field of 'this', but not always) to which the event belongs. So, if the event is /// something like 'button1.Click' or 'this.listBox1.Select', we want the names /// 'button1' and 'listBox1' respectively. If the field belongs to 'this', then we use /// the name of this class, as we do if we can't make any sense out of the parse tree. /// </summary> private string GetNameObjectPart(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService) { AssertIsBackground(); var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax; var memberAccessExpression = parentToken.Left as MemberAccessExpressionSyntax; if (memberAccessExpression != null) { // This is expected -- it means the last thing is(probably) the event name. We // already have that in eventSymbol. What we need is the LHS of that dot. var lhs = memberAccessExpression.Expression; var lhsMemberAccessExpression = lhs as MemberAccessExpressionSyntax; if (lhsMemberAccessExpression != null) { // Okay, cool. The name we're after is in the RHS of this dot. return lhsMemberAccessExpression.Name.ToString(); } var lhsNameSyntax = lhs as NameSyntax; if (lhsNameSyntax != null) { // Even easier -- the LHS of the dot is the name itself return lhsNameSyntax.ToString(); } } // If we didn't find an object name above, then the object name is the name of this class. // Note: For generic, it's ok(it's even a good idea) to exclude type variables, // because the name is only used as a prefix for the method name. var typeDeclaration = syntaxFactsService.GetContainingTypeDeclaration( semanticModel.SyntaxTree.GetRoot(), plusEqualsToken.SpanStart) as BaseTypeDeclarationSyntax; return typeDeclaration != null ? typeDeclaration.Identifier.Text : eventSymbol.ContainingType.Name; } } } }
// 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 PermuteVarSingle() { var test = new SimpleBinaryOpTest__PermuteVarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.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 (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.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 (Avx.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 (Avx.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 (Avx.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__PermuteVarSingle { 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(Single[] inArray1, Int32[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); 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<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, 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<Single> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 1; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__PermuteVarSingle testClass) { var result = Avx.PermuteVar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__PermuteVarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = Avx.PermuteVar( Avx.LoadVector128((Single*)(pFld1)), Avx.LoadVector128((Int32*)(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<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Single> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__PermuteVarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 1; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public SimpleBinaryOpTest__PermuteVarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 1; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 1; } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.PermuteVar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_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 = Avx.PermuteVar( Avx.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector128((Int32*)(_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 = Avx.PermuteVar( Avx.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector128((Int32*)(_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(Avx).GetMethod(nameof(Avx.PermuteVar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.PermuteVar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Avx.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.PermuteVar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.PermuteVar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = Avx.PermuteVar( Avx.LoadVector128((Single*)(pClsVar1)), Avx.LoadVector128((Int32*)(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<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Avx.PermuteVar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Avx.PermuteVar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Avx.PermuteVar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__PermuteVarSingle(); var result = Avx.PermuteVar(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__PermuteVarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = Avx.PermuteVar( Avx.LoadVector128((Single*)(pFld1)), Avx.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.PermuteVar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = Avx.PermuteVar( Avx.LoadVector128((Single*)(pFld1)), Avx.LoadVector128((Int32*)(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 = Avx.PermuteVar(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 = Avx.PermuteVar( Avx.LoadVector128((Single*)(&test._fld1)), Avx.LoadVector128((Int32*)(&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<Single> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Int32[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(left[1]) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[1]) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.PermuteVar)}<Single>(Vector128<Single>, Vector128<Int32>): {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; } } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <[email protected]> */ using System; using System.IO; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI81; using NUnit.Framework; namespace Net.Pkcs11Interop.Tests.LowLevelAPI81 { /// <summary> /// C_SignInit, C_Sign, C_SignUpdate, C_SignFinal, C_VerifyInit, C_Verify, C_VerifyUpdate and C_VerifyFinal tests. /// </summary> [TestFixture()] public class _21_SignAndVerifyTest { /// <summary> /// C_SignInit, C_Sign, C_VerifyInit and C_Verify test with CKM_RSA_PKCS mechanism. /// </summary> [Test()] public void _01_SignAndVerifySinglePartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs81); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate asymetric key pair ulong pubKeyId = CK.CK_INVALID_HANDLE; ulong privKeyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify signing mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS); // Initialize signing operation rv = pkcs11.C_SignInit(session, ref mechanism, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Get length of signature in first call ulong signatureLen = 0; rv = pkcs11.C_Sign(session, sourceData, Convert.ToUInt64(sourceData.Length), null, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(signatureLen > 0); // Allocate array for signature byte[] signature = new byte[signatureLen]; // Get signature in second call rv = pkcs11.C_Sign(session, sourceData, Convert.ToUInt64(sourceData.Length), signature, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with signature // Initialize verification operation rv = pkcs11.C_VerifyInit(session, ref mechanism, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Verify signature rv = pkcs11.C_Verify(session, sourceData, Convert.ToUInt64(sourceData.Length), signature, Convert.ToUInt64(signature.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with verification result rv = pkcs11.C_DestroyObject(session, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_DestroyObject(session, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_SignInit, C_SignUpdate, C_SignFinal, C_VerifyInit, C_VerifyUpdate and C_VerifyFinal test. /// </summary> [Test()] public void _02_SignAndVerifyMultiPartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs81); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate asymetric key pair ulong pubKeyId = CK.CK_INVALID_HANDLE; ulong privKeyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify signing mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); byte[] signature = null; // Multipart signature functions C_SignUpdate and C_SignFinal can be used i.e. for signing of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Initialize signing operation rv = pkcs11.C_SignInit(session, ref mechanism, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Process each individual source data part rv = pkcs11.C_SignUpdate(session, part, Convert.ToUInt64(bytesRead)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Get the length of signature in first call ulong signatureLen = 0; rv = pkcs11.C_SignFinal(session, null, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(signatureLen > 0); // Allocate array for signature signature = new byte[signatureLen]; // Get signature in second call rv = pkcs11.C_SignFinal(session, signature, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Do something interesting with signature // Multipart verification functions C_VerifyUpdate and C_VerifyFinal can be used i.e. for signature verification of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Initialize verification operation rv = pkcs11.C_VerifyInit(session, ref mechanism, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Process each individual source data part rv = pkcs11.C_VerifyUpdate(session, part, Convert.ToUInt64(bytesRead)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Verify signature rv = pkcs11.C_VerifyFinal(session, signature, Convert.ToUInt64(signature.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Do something interesting with verification result rv = pkcs11.C_DestroyObject(session, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_DestroyObject(session, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
using System; namespace Greatbone.Db { /// <summary> /// A specialized string builder for generating SQL commands. /// </summary> public class DbSql : DynamicContent, ISink { // contexts const sbyte CtxColumnList = 1, CtxParamList = 2, CtxSetList = 3; // the putting context internal sbyte ctx; // used when generating a list internal int ordinal; internal DbSql(string str) : base(false, 1024) { Add(str); } public override string Type { get; set; } = "text/plain"; internal void Clear() { count = 0; ctx = 0; ordinal = 0; } public DbSql T(short v, bool cond = true) { if (cond) { Add(v); } return this; } public DbSql T(int v, bool cond = true) { if (cond) { Add(v); } return this; } public DbSql T(string v, bool cond = true) { if (cond) { Add(v); } return this; } public DbSql TT(string v, bool cond = true) { if (cond) { Add('\''); Add(v); Add('\''); } return this; } public DbSql T(short[] vals) { for (int i = 0; i < vals.Length; i++) { if (i > 0) Add(','); Add(vals[i]); } return this; } public DbSql T(int[] vals) { for (int i = 0; i < vals.Length; i++) { if (i > 0) Add(','); Add(vals[i]); } return this; } public DbSql T(long[] vals) { for (int i = 0; i < vals.Length; i++) { if (i > 0) Add(','); Add(vals[i]); } return this; } public DbSql T(string[] vals) { Add(" IN ("); for (int i = 0; i < vals.Length; i++) { if (i > 0) Add(','); Add('\''); Add(vals[i]); Add('\''); } Add(')'); return this; } public DbSql setlst(IData obj, byte proj = 0x0f) { ctx = CtxSetList; ordinal = 1; obj.Write(this, proj); return this; } public DbSql collst(IData obj, byte proj = 0x0f) { ctx = CtxColumnList; ordinal = 1; obj.Write(this, proj); return this; } public DbSql paramlst(IData obj, byte proj = 0x0f) { ctx = CtxParamList; ordinal = 1; obj.Write(this, proj); return this; } public DbSql _(IData obj, byte proj = 0x0f, string extra = null) { Add(" ("); collst(obj, proj); if (extra != null) { Add(","); Add(extra); } Add(")"); return this; } public DbSql _VALUES_(short n) { Add(" VALUES ("); for (short i = 1; i <= n; i++) { if (i > 1) { Add(','); Add(' '); } Add('@'); Add(i); } Add(")"); return this; } public DbSql _VALUES_(IData obj, byte proj = 0x0f, string extra = null) { Add(" VALUES ("); paramlst(obj, proj); if (extra != null) { Add(","); Add(extra); } Add(")"); return this; } public DbSql _SET_(IData obj, byte proj = 0x0f, string extra = null) { Add(" SET "); setlst(obj, proj); if (extra != null) { Add(","); Add(extra); } return this; } public DbSql _IN_(short[] vals) { Add(" IN ("); for (int i = 1; i <= vals.Length; i++) { if (i > 1) Add(','); Add('@'); Add('v'); Add(i); } Add(')'); return this; } public DbSql _IN_(int[] vals) { Add(" IN ("); T(vals); Add(')'); return this; } public DbSql _IN_(long[] vals) { Add(" IN ("); for (int i = 1; i <= vals.Length; i++) { if (i > 1) Add(','); Add('@'); Add('v'); Add(i); } Add(')'); return this; } public DbSql _IN_(string[] vals) { Add(" IN ("); for (int i = 1; i <= vals.Length; i++) { if (i > 1) Add(','); Add('@'); Add('v'); Add(i); } Add(')'); return this; } void Build(string name) { if (ordinal > 1) Add(", "); switch (ctx) { case CtxColumnList: Add('"'); Add(name); Add('"'); break; case CtxParamList: Add("@"); Add(name); break; case CtxSetList: Add('"'); Add(name); Add('"'); Add("=@"); Add(name); break; } ordinal++; } // // SINK // public void PutNull(string name) { Build(name); } public void Put(string name, JNumber v) { if (name != null) { Build(name); } else { Add(v); } } public void Put(string name, bool v) { if (name != null) { Build(name); } else { Add(v ? "TRUE" : "FALSE"); } } public void Put(string name, char v) { if (name != null) { Build(name); } else { Add('\''); Add(v); Add('\''); } } public void Put(string name, short v) { if (name != null) { Build(name); } else { Add(v); } } public void Put(string name, int v) { if (name != null) { Build(name); } else { Add(v); } } public void Put(string name, long v) { if (name != null) { Build(name); } else { Add(v); } } public void Put(string name, double v) { if (name != null) { Build(name); } else { Add(v); } } public void Put(string name, decimal v) { if (name != null) { Build(name); } else { Add(v); } } public void Put(string name, DateTime v) { if (name != null) { Build(name); } else { Add(v); } } public void Put(string name, string v) { if (name != null) { Build(name); } else { Add('\''); Add(v); Add('\''); } } public void Put(string name, ArraySegment<byte> v) { Build(name); } public void Put(string name, byte[] v) { Build(name); } public void Put(string name, short[] v) { if (name != null) { Build(name); } else { if (v == null) { Add("NULL"); } else { Add("ARRAY["); for (int i = 0; i < v.Length; i++) { if (i > 0) Add(','); Add(v[i]); } Add(']'); if (v.Length == 0) { Add("::smallint[]"); } } } } public void Put(string name, int[] v) { if (name != null) { Build(name); } else { if (v == null) { Add("NULL"); } else { Add("ARRAY["); for (int i = 0; i < v.Length; i++) { if (i > 0) Add(','); Add(v[i]); } Add(']'); if (v.Length == 0) { Add("::integer[]"); } } } } public void Put(string name, long[] v) { if (name != null) { Build(name); } else { if (v == null) { Add("NULL"); } else { Add("ARRAY["); for (int i = 0; i < v.Length; i++) { if (i > 0) Add(','); Add(v[i]); } Add(']'); if (v.Length == 0) { Add("::bigint[]"); } } } } public void Put(string name, string[] v) { if (name != null) { Build(name); } else { if (v == null) { Add("NULL"); } else { Add("ARRAY["); for (int i = 0; i < v.Length; i++) { if (i > 0) Add(','); Add('\''); Add(v[i]); Add('\''); } Add(']'); if (v.Length == 0) { Add("::varchar[]"); } } } } public void Put(string name, JObj v) { if (name != null) { Build(name); } else { throw new NotImplementedException(); } } public void Put(string name, JArr v) { if (name != null) { Build(name); } else { throw new NotImplementedException(); } } public void Put(string name, IData v, byte proj = 0x0f) { if (name != null) { Build(name); } else { if (v == null) { Add("NULL"); } } } public void Put<D>(string name, D[] v, byte proj = 0x0f) where D : IData { Build(name); } public void PutFrom(ISource s) { throw new NotImplementedException(); } public override string ToString() { return new string(charbuf, 0, count); } } }
// Copyright 2009 Auxilium B.V. - http://www.auxilium.nl/ // // 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. namespace JelloScrum.Web.Components { using System; using System.Collections; using System.Collections.Generic; using System.Text; using Castle.MonoRail.Framework; using Helpers; using Model.Entities; using Model.Enumerations; /// <summary> /// Viewcomponent voor het registreren van uren aan taken /// </summary> [ViewComponentDetails("UrenRegistratieComponent")] public class UrenRegistratieComponent : ViewComponent { private Sprint sprint; private SprintUser sprintGebruiker; private DateTime maandag; private DateTime dinsdag; private DateTime woensdag; private DateTime donderdag; private DateTime vrijdag; private string formaction = string.Empty; private readonly StringBuilder component = new StringBuilder(); public override void Initialize() { maandag = ((DateTime) ComponentParams["maandag"]); sprint = ((Sprint) ComponentParams["sprint"]); sprintGebruiker = ((SprintUser) ComponentParams["sprintGebruiker"]); formaction = ((string)ComponentParams["formaction"]); dinsdag = maandag.AddDays(1); woensdag = maandag.AddDays(2); donderdag = maandag.AddDays(3); vrijdag = maandag.AddDays(4); base.Initialize(); } public override void Render() { //eerst een scriptje toevoegen component.Append("<script type='text/javascript' charset='utf-8' src='/Content/Javascript/urenregistratiecomponent.js'></script>"); //daarna de formtag met gespecificeerde action plus wat hidden fields component.Append("<form id='urenregistratieform' action='" + formaction + "' method='post'>"); component.Append("<input type='hidden' name='sprintId' value='" + sprint.Id + "'/>"); component.Append("<input type='hidden' name='maandag' value='" + maandag.ToString("dd-MM-yyyy") + "'/>"); //de header component.Append("<div id='weekSelector' style='float:left;'>"); component.Append("<a href='urenregistreren.rails?sprintId=" + sprint.Id + "&maandag=" + maandag.AddDays(-7).ToString("dd-MM-yy") + "'>Vorige week</a>&nbsp;"); component.Append("<span id='weekNr'>Huidige week " + DateHelper.GetWeekNumber(maandag) + "</span>&nbsp;"); component.Append("<a href='urenregistreren.rails?sprintId=" +sprint.Id + "&maandag=" + maandag.AddDays(7).ToString("dd-MM-yy") + "'>Volgende week</a>&nbsp;"); component.Append("</div>"); RenderSaveButton(); //het component zelf is een table waar je uren in kunt vullen component.Append("<table class='tablesorter' id='urenregistratie' style='float: left;'>"); //daarna de table header, deze bestaat uit 3 rijen, 1 met de dagaanduiding en 2 met totalen component.Append("<thead>"); component.Append("<tr>"); component.Append("<th>Story</th>"); //nu de dagen, van ma t/m vr component.Append("<th class='header_dag" + HighlightVandaag(maandag) + "'>Ma " + maandag.ToString("dd-MM-yy") + "</th>"); component.Append("<th class='header_dag" + HighlightVandaag(dinsdag) + "'>Di " + dinsdag.ToString("dd-MM-yy") + "</th>"); component.Append("<th class='header_dag" + HighlightVandaag(woensdag) + "'>Wo " + woensdag.ToString("dd-MM-yy") + "</th>"); component.Append("<th class='header_dag" + HighlightVandaag(donderdag) + "'>Do " + donderdag.ToString("dd-MM-yy") + "</th>"); component.Append("<th class='header_dag" + HighlightVandaag(vrijdag) + "'>Vr " + vrijdag.ToString("dd-MM-yy") + "</th>"); component.Append("</tr>"); //de tweede rij bevat het totaal aantal geboekte uren component.Append("<tr>"); component.Append("<th style='padding:4px;'>Totaal</th>"); component.Append("<th class='header_totaal" + HighlightVandaag(maandag) + "'>" + BerekenTotaalGeregistreerdeTijd(maandag) + "</th>"); component.Append("<th class='header_totaal" + HighlightVandaag(dinsdag) + "'>" + BerekenTotaalGeregistreerdeTijd(dinsdag) + "</th>"); component.Append("<th class='header_totaal" + HighlightVandaag(woensdag) + "'>" + BerekenTotaalGeregistreerdeTijd(woensdag) + "</th>"); component.Append("<th class='header_totaal" + HighlightVandaag(donderdag) + "'>" + BerekenTotaalGeregistreerdeTijd(donderdag) + "</th>"); component.Append("<th class='header_totaal" + HighlightVandaag(vrijdag) + "'>" + BerekenTotaalGeregistreerdeTijd(vrijdag) + "</th>"); component.Append("</tr>"); //de derde rij bevat het totaal aantal zelf geboekte uren component.Append("<tr>"); component.Append("<th style='padding:4px;'>Eigen uren</th>"); component.Append("<th class='header_totaal" + HighlightVandaag(maandag) + "'>" + BerekenTotaalGeregistreerdeTijd(maandag, sprintGebruiker) + "</th>"); component.Append("<th class='header_totaal" + HighlightVandaag(dinsdag) + "'>" + BerekenTotaalGeregistreerdeTijd(dinsdag, sprintGebruiker) + "</th>"); component.Append("<th class='header_totaal" + HighlightVandaag(woensdag) + "'>" + BerekenTotaalGeregistreerdeTijd(woensdag, sprintGebruiker) + "</th>"); component.Append("<th class='header_totaal" + HighlightVandaag(donderdag) + "'>" + BerekenTotaalGeregistreerdeTijd(donderdag, sprintGebruiker) + "</th>"); component.Append("<th class='header_totaal" + HighlightVandaag(vrijdag) + "'>" + BerekenTotaalGeregistreerdeTijd(vrijdag, sprintGebruiker) + "</th>"); component.Append("</tr>"); component.Append("</thead>"); //nu de inhoud van de tabel component.Append("<tbody>"); //we gaan de taken per userstory groeperen foreach (SprintStory sprintStory in sprint.SprintStories) { RenderSprintStory(sprintStory); } component.Append("</tbody>"); component.Append("</table>"); RenderSaveButton(); component.Append("</form>"); RenderText(component.ToString()); } private void RenderSaveButton() { this.component.Append("<div id='opslaan' style='float:right;'>"); this.component.Append("<button class='button'><img src='/content/images/save.png' alt='Save' />Opslaan</button>"); this.component.Append("</div>"); } /// <summary> /// Geeft de css class terug voor het highlighten van de huidige dag /// </summary> /// <param name="dag"></param> /// <returns></returns> private static string HighlightVandaag(DateTime dag) { if (dag.Date == DateTime.Today) return " today"; return string.Empty; } /// <summary> /// /// </summary> /// <param name="sprintStory"></param> private void RenderSprintStory(SprintStory sprintStory) { //de eerste row bevat de sprintstory this.component.Append("<tr>"); this.component.Append("<td class='story'><span style='font-weight: bold;padding-right: 10px;'>" + sprintStory.Story.Title + "</span>" + new OpmaakHelper().UrenStatus(sprintStory.Story) + " status: " + sprintStory.State + "</td>"); //aantal zelf geboekte uren op story per dag this.component.Append("<td class='story" + HighlightVandaag(maandag) + "'>&nbsp;</td>"); this.component.Append("<td class='story" + HighlightVandaag(dinsdag) + "'>&nbsp;</td>"); this.component.Append("<td class='story" + HighlightVandaag(woensdag) + "'>&nbsp;</td>"); this.component.Append("<td class='story" + HighlightVandaag(donderdag) + "'>&nbsp;</td>"); this.component.Append("<td class='story" + HighlightVandaag(vrijdag) + "'>&nbsp;</td>"); this.component.Append("</tr>"); foreach (Task task in sprintStory.Story.Tasks) { RenderTaskRow(task); } } private void RenderTaskRow(Task task) { this.component.Append("<tr class='expand-child'>"); this.component.Append("<td class='" + HighlightEigenTaak(task) + "'><span style='padding-right: 10px;padding-left:20px;'>Taak: <a href='/CommentaarBericht/TaakCommentaar.rails?Id=" + task.Id + "&height=800&width=600' class='thickbox' style='color: #000000;'>" + task.Title + "</a> status: " + task.State + "</td>"); RenderTaskRegistrationInput(task, maandag); RenderTaskRegistrationInput(task, dinsdag); RenderTaskRegistrationInput(task, woensdag); RenderTaskRegistrationInput(task, donderdag); RenderTaskRegistrationInput(task, vrijdag); this.component.Append("</tr>"); } private string HighlightEigenTaak(Task task) { if (task.AssignedUser == sprintGebruiker && task.State != State.Closed) return " owntask"; return string.Empty; } private void RenderTaskRegistrationInput(Task task, DateTime dag) { Guid index = Guid.NewGuid(); this.component.Append("<td class='task_registration" + HighlightVandaag(dag) + HighlightEigenTaak(task) + "'>"); if (dag <= DateTime.Today) { //this.component.Append("<div class='uren_readonly " + HighlightVandaag(dag) + "'>" + TimeSpanHelper.TimeSpanInMinuten(task.TotaalBestedeTijd(this.sprintGebruiker.Gebruiker, dag)) + "</div>"); this.component.Append("<div class='uren_input" + HighlightVandaag(dag) + HighlightEigenTaak(task) + "'>"); this.component.Append("<input type='text' name='urenregistratie[" + index + "].AantalUren' id='urenregistratie[" + index + "]_AantalUren' value='" + TimeSpanHelper.TimeSpanInMinuten(task.TotaalBestedeTijd(this.sprintGebruiker.User, dag)) + "'/>"); this.component.Append("<input type='hidden' name='urenregistratie[" + index + "].Dag' id='urenregistratie[" + index + "]_Dag' value='" + dag.ToString("dd-MM-yyyy") + "'/>"); this.component.Append("<input type='hidden' name='urenregistratie[" + index + "].Task.Id' id='urenregistratie[" + index + "]_Task.Id' value='" + task.Id + "'/>"); this.component.Append("<input type='hidden' name='urenregistratie[" + index + "].SprintGebruiker.Id' id='urenregistratie[" + index + "]_SprintGebruiker_Id' value='" + this.sprintGebruiker.Id + "'/>"); this.component.Append("</div>"); } else { this.component.Append("&nbsp;"); } this.component.Append("</td>"); } /// <summary> /// Bereken de totaal geregistreerde tijd op de gespecificeerde dag van de gespecificeerde gebruiker /// </summary> /// <param name="dag"></param> /// <param name="gebruiker"></param> /// <returns></returns> private string BerekenTotaalGeregistreerdeTijd(DateTime dag, SprintUser gebruiker) { double total = 0; foreach (Task task in sprint.GetAllTasks()) { total += TimeSpanHelper.TimeSpanInMinuten(task.TotaalBestedeTijd(gebruiker.User, dag)); } return total.ToString(); } /// <summary> /// /// </summary> /// <param name="dag"></param> /// <returns></returns> private string BerekenTotaalGeregistreerdeTijd(DateTime dag) { double total = 0; foreach (Task task in sprint.GetAllTasks()) { total += TimeSpanHelper.TimeSpanInMinuten(task.TotalTimeSpent(dag)); } return total.ToString(); } } }
/*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.Text; using System.Collections.Generic; using System.Runtime.InteropServices; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.JTX; using ESRI.ArcGIS.JTX.Utilities; namespace JTXSamples { [Guid("63774aaa-5849-4b9e-a519-6728377fa104")] public class CreateVersion : IJTXCustomStep { //////////////////////////////////////////////////////////////////////// // INFO // Return Codes: // -1 : Unsuccessful // 0 : Successful #region Registration Code [ComRegisterFunction()] static void Reg(String regKey) { ESRI.ArcGIS.JTX.Utilities.JTXUtilities.RegisterJTXCustomStep(regKey); } [ComUnregisterFunction()] static void Unreg(String regKey) { ESRI.ArcGIS.JTX.Utilities.JTXUtilities.UnregisterJTXCustomStep(regKey); } #endregion //////////////////////////////////////////////////////////////////////// // DECLARE: Data Members private IJTXDatabase m_ipDatabase = null; private readonly string[] m_expectedArgs = { "scope", "name" }; #region IJTXCustomStep Members /// <summary> /// A description of the expected arguments for the step type. This should /// include the syntax of the argument, whether or not it is required/optional, /// and any return codes coming from the step type. /// </summary> public string ArgumentDescriptions { get { StringBuilder sb = new StringBuilder(); sb.AppendLine(@"Version Access Scope:"); sb.AppendFormat("\t/{0}:<public|private|protected> (optional)\r\n", m_expectedArgs[0]); sb.AppendLine(@"Version Name Override (overrides default version name assignment):"); sb.AppendFormat("\t/{0}:<version name> (optional)\r\n", m_expectedArgs[1]); return sb.ToString(); } } /// <summary> /// Called when a step of this type is executed in the workflow. /// </summary> /// <param name="JobID">ID of the job being executed</param> /// <param name="StepID">ID of the step being executed</param> /// <param name="argv">Array of arguments passed into the step's execution</param> /// <param name="ipFeedback">Feedback object to return status messages and files</param> /// <returns>Return code of execution for workflow path traversal</returns> public int Execute(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback) { if (jobID <= 0) { throw (new ArgumentOutOfRangeException("JobID", jobID, "Job ID must be a positive value")); } System.Diagnostics.Debug.Assert(m_ipDatabase != null); IJTXJobManager pJobMan = m_ipDatabase.JobManager; IJTXJob2 pJob = pJobMan.GetJob(jobID) as IJTXJob2; // Make sure all the information exists to create this verion if (pJob.ActiveDatabase == null) { System.Windows.Forms.MessageBox.Show("Job does not have a data workspace"); return -1; } if (pJob.ParentVersion == "") { System.Windows.Forms.MessageBox.Show("Job does not have a parent version"); return -1; } string strVersionNameOverride; bool bVNOverride = StepUtilities.GetArgument(ref argv, m_expectedArgs[1], true, out strVersionNameOverride); if (pJob.VersionName == "" & !bVNOverride) { System.Windows.Forms.MessageBox.Show("The job does not have a version name"); return -1; } IVersion pNewVersion; string strVersionName; if (bVNOverride) strVersionName = strVersionNameOverride; else strVersionName = pJob.VersionName; int index = strVersionName.IndexOf(".", 0); if (index >= 0) { strVersionName = strVersionName.Substring(index + 1); } esriVersionAccess verAccess = esriVersionAccess.esriVersionAccessPrivate; string strVerScope = ""; if (StepUtilities.GetArgument(ref argv, m_expectedArgs[0], true, out strVerScope)) { strVerScope = strVerScope.ToLower().Trim(); if (strVerScope == "public") { verAccess = esriVersionAccess.esriVersionAccessPublic; } else if (strVerScope == "protected") { verAccess = esriVersionAccess.esriVersionAccessProtected; } } pJob.VersionName = strVersionName; pNewVersion = pJob.CreateVersion(verAccess); if (pNewVersion == null) { throw (new System.SystemException("Unable to create version")); } IPropertySet pOverrides = new PropertySetClass(); pOverrides.SetProperty("[VERSION]", pNewVersion.VersionName); IJTXActivityType pActType = m_ipDatabase.ConfigurationManager.GetActivityType(Constants.ACTTYPE_CREATE_VERSION); if (pActType != null) pJob.LogJobAction(pActType, pOverrides, ""); JTXUtilities.SendNotification(Constants.NOTIF_VERSION_CREATED, m_ipDatabase, pJob, pOverrides); System.Runtime.InteropServices.Marshal.ReleaseComObject(pNewVersion); return 0; } /// <summary> /// Invoke an editor tool for managing custom step arguments. This is /// an optional feature of the custom step and may not be implemented. /// </summary> /// <param name="hWndParent">Handle to the parent application window</param> /// <param name="argsIn">Array of arguments already configured for this custom step</param> /// <returns>Returns a list of newely configured arguments as specified via the editor tool</returns> public object[] InvokeEditor(int hWndParent, object[] argsIn) { throw new NotImplementedException("No edit dialog available for this step type"); } /// <summary> /// Called when the step is instantiated in the workflow. /// </summary> /// <param name="ipDatabase">Database connection to the JTX repository.</param> public void OnCreate(IJTXDatabase ipDatabase) { m_ipDatabase = ipDatabase; } /// <summary> /// Method to validate the configured arguments for the step type. The /// logic of this method depends on the implementation of the custom step /// but typically checks for proper argument names and syntax. /// </summary> /// <param name="argv">Array of arguments configured for the step type</param> /// <returns>Returns 'true' if arguments are valid, 'false' if otherwise</returns> public bool ValidateArguments(ref object[] argv) { return StepUtilities.AreArgumentNamesValid(ref argv, m_expectedArgs); } #endregion } // End Class } // End Namespace
using RootSystem = System; using System.Linq; using System.Collections.Generic; namespace Windows.Kinect { // // Windows.Kinect.ColorFrameReader // public sealed partial class ColorFrameReader : RootSystem.IDisposable, Helper.INativeWrapper { internal RootSystem.IntPtr _pNative; RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } } // Constructors and Finalizers internal ColorFrameReader(RootSystem.IntPtr pNative) { _pNative = pNative; Windows_Kinect_ColorFrameReader_AddRefObject(ref _pNative); } ~ColorFrameReader() { Dispose(false); } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_ColorFrameReader_ReleaseObject(ref RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_ColorFrameReader_AddRefObject(ref RootSystem.IntPtr pNative); private void Dispose(bool disposing) { if (_pNative == RootSystem.IntPtr.Zero) { return; } __EventCleanup(); Helper.NativeObjectCache.RemoveObject<ColorFrameReader>(_pNative); if (disposing) { Windows_Kinect_ColorFrameReader_Dispose(_pNative); } Windows_Kinect_ColorFrameReader_ReleaseObject(ref _pNative); _pNative = RootSystem.IntPtr.Zero; } // Public Properties [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_ColorFrameReader_get_ColorFrameSource(RootSystem.IntPtr pNative); public Windows.Kinect.ColorFrameSource ColorFrameSource { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrameReader"); } RootSystem.IntPtr objectPointer = Windows_Kinect_ColorFrameReader_get_ColorFrameSource(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.ColorFrameSource>(objectPointer, n => new Windows.Kinect.ColorFrameSource(n)); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern bool Windows_Kinect_ColorFrameReader_get_IsPaused(RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_ColorFrameReader_put_IsPaused(RootSystem.IntPtr pNative, bool isPaused); public bool IsPaused { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrameReader"); } return Windows_Kinect_ColorFrameReader_get_IsPaused(_pNative); } set { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrameReader"); } Windows_Kinect_ColorFrameReader_put_IsPaused(_pNative, value); Helper.ExceptionHelper.CheckLastError(); } } // Events private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Kinect_ColorFrameArrivedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.ColorFrameArrivedEventArgs>>> Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.ColorFrameArrivedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Kinect_ColorFrameArrivedEventArgs_Delegate))] private static void Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Kinect.ColorFrameArrivedEventArgs>> callbackList = null; Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<ColorFrameReader>(pNative); var args = new Windows.Kinect.ColorFrameArrivedEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_ColorFrameReader_add_FrameArrived(RootSystem.IntPtr pNative, _Windows_Kinect_ColorFrameArrivedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Kinect.ColorFrameArrivedEventArgs> FrameArrived { add { Helper.EventPump.EnsureInitialized(); Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Kinect_ColorFrameArrivedEventArgs_Delegate(Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_Handler); _Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Windows_Kinect_ColorFrameReader_add_FrameArrived(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Windows_Kinect_ColorFrameReader_add_FrameArrived(_pNative, Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_Handler, true); _Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_Handle.Free(); } } } } private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))] private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null; Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<ColorFrameReader>(pNative); var args = new Windows.Data.PropertyChangedEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_ColorFrameReader_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged { add { Helper.EventPump.EnsureInitialized(); Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Windows_Kinect_ColorFrameReader_add_PropertyChanged(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Windows_Kinect_ColorFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } // Public Methods [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_ColorFrameReader_AcquireLatestFrame(RootSystem.IntPtr pNative); public Windows.Kinect.ColorFrame AcquireLatestFrame() { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrameReader"); } RootSystem.IntPtr objectPointer = Windows_Kinect_ColorFrameReader_AcquireLatestFrame(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.ColorFrame>(objectPointer, n => new Windows.Kinect.ColorFrame(n)); } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_ColorFrameReader_Dispose(RootSystem.IntPtr pNative); public void Dispose() { if (_pNative == RootSystem.IntPtr.Zero) { return; } Dispose(true); RootSystem.GC.SuppressFinalize(this); } private void __EventCleanup() { { Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Windows_Kinect_ColorFrameReader_add_FrameArrived(_pNative, Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_Handler, true); } _Windows_Kinect_ColorFrameArrivedEventArgs_Delegate_Handle.Free(); } } } { Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Windows_Kinect_ColorFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); } _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using ProtoCore.BuildData; using ProtoCore.DSASM; using ProtoCore.Utils; namespace ProtoCore { public struct Type { public string Name; public int UID; public bool IsIndexable; public int rank; /// <summary> /// Comment Jun: Initialize a type to the default values /// </summary> public void Initialize() { Name = string.Empty; UID = ProtoCore.DSASM.Constants.kInvalidIndex; IsIndexable = false; rank = DSASM.Constants.kArbitraryRank; } public override string ToString() { string retName = (Name == "" ? UID.ToString() : Name); string rankText = ""; if (IsIndexable) { if (rank == DSASM.Constants.kArbitraryRank) rankText = "[]..[]"; else { for (int i = 0; i < rank; i++) rankText += "[]"; } } return retName + rankText; } public bool Equals(Type type) { return this.Name == type.Name && this.UID == type.UID && this.rank == type.rank; } } public enum PrimitiveType { kInvalidType = -1, kTypeNull, kTypeArray, kTypeDouble, kTypeInt, kTypeDynamic, kTypeBool, kTypeChar, kTypeString, kTypeVar, kTypeVoid, kTypeHostEntityID, kTypePointer, kTypeFunctionPointer, kTypeReturn, kMaxPrimitives } public class TypeSystem { public ProtoCore.DSASM.ClassTable classTable { get; private set; } public Dictionary<ProtoCore.DSASM.AddressType, int> addressTypeClassMap { get; set; } private static Dictionary<PrimitiveType, string> primitiveTypeNames; public TypeSystem() { SetTypeSystem(); BuildAddressTypeMap(); } public static string GetPrimitTypeName(PrimitiveType type) { if (type == PrimitiveType.kInvalidType || type == PrimitiveType.kMaxPrimitives) { return null; } if (null == primitiveTypeNames) { primitiveTypeNames = new Dictionary<PrimitiveType,string>(); primitiveTypeNames[PrimitiveType.kTypeArray] = DSDefinitions.Keyword.Array; primitiveTypeNames[PrimitiveType.kTypeDouble] = DSDefinitions.Keyword.Double; primitiveTypeNames[PrimitiveType.kTypeInt] = DSDefinitions.Keyword.Int; primitiveTypeNames[PrimitiveType.kTypeBool] = DSDefinitions.Keyword.Bool; primitiveTypeNames[PrimitiveType.kTypeChar] = DSDefinitions.Keyword.Char; primitiveTypeNames[PrimitiveType.kTypeString] = DSDefinitions.Keyword.String; primitiveTypeNames[PrimitiveType.kTypeVar] = DSDefinitions.Keyword.Var; primitiveTypeNames[PrimitiveType.kTypeNull] = DSDefinitions.Keyword.Null; primitiveTypeNames[PrimitiveType.kTypeVoid] = DSDefinitions.Keyword.Void; primitiveTypeNames[PrimitiveType.kTypeArray] = DSDefinitions.Keyword.Array; primitiveTypeNames[PrimitiveType.kTypeHostEntityID] = "hostentityid"; primitiveTypeNames[PrimitiveType.kTypePointer] = "pointer_reserved"; primitiveTypeNames[PrimitiveType.kTypeFunctionPointer] = DSDefinitions.Keyword.FunctionPointer; primitiveTypeNames[PrimitiveType.kTypeReturn] = "return_reserved"; } return primitiveTypeNames[type]; } public void SetClassTable(ProtoCore.DSASM.ClassTable table) { Debug.Assert(null != table); Debug.Assert(0 == table.ClassNodes.Count); if (0 != table.ClassNodes.Count) { return; } for (int i = 0; i < classTable.ClassNodes.Count; ++i) { table.Append(classTable.ClassNodes[i]); } classTable = table; } public void BuildAddressTypeMap() { addressTypeClassMap = new Dictionary<DSASM.AddressType, int>(); addressTypeClassMap.Add(ProtoCore.DSASM.AddressType.Null, (int)PrimitiveType.kTypeNull); addressTypeClassMap.Add(ProtoCore.DSASM.AddressType.ArrayPointer, (int)PrimitiveType.kTypeArray); addressTypeClassMap.Add(ProtoCore.DSASM.AddressType.Double, (int)PrimitiveType.kTypeDouble); addressTypeClassMap.Add(ProtoCore.DSASM.AddressType.Char, (int)PrimitiveType.kTypeChar); addressTypeClassMap.Add(ProtoCore.DSASM.AddressType.String, (int)PrimitiveType.kTypeString); addressTypeClassMap.Add(ProtoCore.DSASM.AddressType.Int, (int)PrimitiveType.kTypeInt); addressTypeClassMap.Add(ProtoCore.DSASM.AddressType.Boolean, (int)PrimitiveType.kTypeBool); addressTypeClassMap.Add(ProtoCore.DSASM.AddressType.Pointer, (int)PrimitiveType.kTypePointer); addressTypeClassMap.Add(ProtoCore.DSASM.AddressType.FunctionPointer, (int)PrimitiveType.kTypeFunctionPointer); addressTypeClassMap.Add(ProtoCore.DSASM.AddressType.DefaultArg, (int)PrimitiveType.kTypeVar); } public void SetTypeSystem() { Debug.Assert(null == classTable); if (null != classTable) { return; } classTable = new DSASM.ClassTable(); classTable.Reserve((int)PrimitiveType.kMaxPrimitives); ProtoCore.DSASM.ClassNode cnode; cnode = new ProtoCore.DSASM.ClassNode { name = DSDefinitions.Keyword.Array, size = 0, rank = 5, symbols = null, vtable = null, typeSystem = this }; /*cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeChar, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); */ cnode.classId = (int)PrimitiveType.kTypeArray; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeArray); // // cnode = new ProtoCore.DSASM.ClassNode { name = DSDefinitions.Keyword.Double, size = 0, rank = 4, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceDoubleToIntScore); cnode.classId = (int)PrimitiveType.kTypeDouble; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeDouble); // // cnode = new ProtoCore.DSASM.ClassNode { name = DSDefinitions.Keyword.Int, size = 0, rank = 3, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceIntToDoubleScore); cnode.classId = (int)PrimitiveType.kTypeInt; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeInt); // // cnode = new ProtoCore.DSASM.ClassNode { name = DSDefinitions.Keyword.Bool, size = 0, rank = 2, symbols = null, vtable = null, typeSystem = this }; // if convert operator to method call, without the following statement // a = true + 1 will fail, because _add expects two integers //cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypeBool; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeBool); // // cnode = new ProtoCore.DSASM.ClassNode { name = DSDefinitions.Keyword.Char, size = 0, rank = 1, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypeChar; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeChar); // // cnode = new ProtoCore.DSASM.ClassNode { name = DSDefinitions.Keyword.String, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypeString; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeString); // // cnode = new ProtoCore.DSASM.ClassNode { name = DSDefinitions.Keyword.Var, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; /*cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeChar, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);*/ cnode.classId = (int)PrimitiveType.kTypeVar; classTable.SetClassNodeAt(cnode,(int)PrimitiveType.kTypeVar); // // cnode = new ProtoCore.DSASM.ClassNode { name = DSDefinitions.Keyword.Null, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeChar, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypeNull; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeNull); // // cnode = new ProtoCore.DSASM.ClassNode { name = DSDefinitions.Keyword.Void, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.classId = (int)PrimitiveType.kTypeVoid; classTable.SetClassNodeAt(cnode,(int)PrimitiveType.kTypeVoid); // // cnode = new ProtoCore.DSASM.ClassNode { name = "hostentityid", size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.classId = (int)PrimitiveType.kTypeHostEntityID; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeHostEntityID); // // cnode = new ProtoCore.DSASM.ClassNode { name = "pointer_reserved", size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; // if convert operator to method call, without the following statement, // a = b.c + d.e will fail, b.c and d.e are resolved as pointer and _add method requires two integer cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypePointer; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypePointer); // // cnode = new ProtoCore.DSASM.ClassNode { name = DSDefinitions.Keyword.FunctionPointer, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypeFunctionPointer; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeFunctionPointer); // // cnode = new ProtoCore.DSASM.ClassNode { name = "return_reserved", size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.classId = (int)PrimitiveType.kTypeReturn; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeReturn); } public bool IsHigherRank(int t1, int t2) { // TODO Jun: Refactor this when we implement operator overloading Debug.Assert(null != classTable); Debug.Assert(null != classTable.ClassNodes); if (t1 == (int)PrimitiveType.kInvalidType || t1 >= classTable.ClassNodes.Count) { return true; } else if (t2 == (int)PrimitiveType.kInvalidType || t2 >= classTable.ClassNodes.Count) { return false; } return classTable.ClassNodes[t1].rank >= classTable.ClassNodes[t2].rank; } public static Type BuildPrimitiveTypeObject(PrimitiveType pType, bool isArray, int rank = Constants.kUndefinedRank) { Type type = new Type(); type.Name = GetPrimitTypeName(pType); type.UID = (int)pType; ; type.IsIndexable = isArray; type.rank = rank; return type; } //@TODO(Luke): Once the type system has been refactored, get rid of this public Type BuildTypeObject(int UID, bool isArray, int rank = Constants.kUndefinedRank) { Type type = new Type(); type.Name = GetType(UID); type.UID = UID; type.IsIndexable = isArray; type.rank = rank; return type; } public string GetType(int UID) { Debug.Assert(null != classTable); return classTable.GetTypeName(UID); } public string GetType(Type type) { Validity.Assert(null != classTable); return classTable.GetTypeName(type.UID); } public int GetType(string ident) { Debug.Assert(null != classTable); return classTable.IndexOf(ident); } public int GetType(ProtoCore.DSASM.StackValue sv) { int type = (int)ProtoCore.DSASM.Constants.kInvalidIndex; if (sv.IsReferenceType()) { type = (int)sv.metaData.type; } else { if (!addressTypeClassMap.TryGetValue(sv.optype, out type)) { type = (int)PrimitiveType.kInvalidType; } } return type; } public static bool IsConvertibleTo(int fromType, int toType, Core core) { if (ProtoCore.DSASM.Constants.kInvalidIndex != fromType && ProtoCore.DSASM.Constants.kInvalidIndex != toType) { if (fromType == toType) { return true; } return core.DSExecutable.classTable.ClassNodes[fromType].ConvertibleTo(toType); } return false; } //@TODO: Factor this into the type system public static StackValue ClassCoerece(StackValue sv, Type targetType, Core core) { //@TODO: Add proper coersion testing here. if (targetType.UID == (int)PrimitiveType.kTypeBool) return StackUtils.BuildBoolean(true); return sv.ShallowClone(); } public static StackValue Coerce(StackValue sv, int UID, int rank, Core core) { Type t = new Type(); t.UID = UID; if (rank == Constants.kUndefinedRank) { rank = DSASM.Constants.kArbitraryRank; } t.rank = rank; t.IsIndexable = (t.rank != 0); return Coerce(sv, t, core); } public static StackValue Coerce(StackValue sv, Type targetType, Core core) { //@TODO(Jun): FIX ME - abort coersion for default args if (sv.optype == AddressType.DefaultArg) return sv; if ( !( (int)sv.metaData.type == targetType.UID || (core.DSExecutable.classTable.ClassNodes[(int)sv.metaData.type].ConvertibleTo(targetType.UID)) || sv.optype == AddressType.ArrayPointer)) { core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kConversionNotPossible, ProtoCore.RuntimeData.WarningMessage.kConvertNonConvertibleTypes); return StackUtils.BuildNull(); } //if it's an array if (sv.optype == AddressType.ArrayPointer && !targetType.IsIndexable && targetType.rank != DSASM.Constants.kUndefinedRank)// && targetType.UID != (int)PrimitiveType.kTypeVar) { //This is an array rank reduction //this may only be performed in recursion and is illegal here string errorMessage = String.Format(ProtoCore.RuntimeData.WarningMessage.kConvertArrayToNonArray, core.TypeSystem.GetType(targetType.UID)); core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kConversionNotPossible, errorMessage); return StackUtils.BuildNull(); } if (sv.optype == AddressType.ArrayPointer && targetType.IsIndexable) { Validity.Assert(StackUtils.IsArray(sv)); //We're being asked to convert an array into an array //walk over the structure converting each othe elements if (targetType.UID == (int)PrimitiveType.kTypeVar && targetType.rank == DSASM.Constants.kArbitraryRank && core.Heap.IsTemporaryPointer(sv)) { return sv; } //Validity.Assert(targetType.rank != -1, "Arbitrary rank array conversion not yet implemented {2EAF557F-62DE-48F0-9BFA-F750BBCDF2CB}"); //Decrease level of reductions by one Type newTargetType = new Type(); newTargetType.UID = targetType.UID; if (targetType.rank != ProtoCore.DSASM.Constants.kArbitraryRank) { newTargetType.rank = targetType.rank - 1; newTargetType.IsIndexable = newTargetType.rank > 0; } else { if (ArrayUtils.GetMaxRankForArray(sv, core) == 1) { //Last unpacking newTargetType.rank = 0; newTargetType.IsIndexable = false; } else { newTargetType.rank = ProtoCore.DSASM.Constants.kArbitraryRank; newTargetType.IsIndexable = true; } } return ArrayUtils.CopyArray(sv, newTargetType, core); } if (sv.optype != AddressType.ArrayPointer && sv.optype != AddressType.Null && targetType.IsIndexable && targetType.rank != DSASM.Constants.kArbitraryRank) { //We're being asked to promote the value into an array if (targetType.rank == 1) { Type newTargetType = new Type(); newTargetType.UID = targetType.UID; newTargetType.IsIndexable = false; newTargetType.Name = targetType.Name; newTargetType.rank = 0; //Upcast once StackValue coercedValue = Coerce(sv, newTargetType, core); GCUtils.GCRetain(coercedValue, core); StackValue newSv = HeapUtils.StoreArray(new StackValue[] { coercedValue }, null, core); return newSv; } else { Validity.Assert(targetType.rank > 1, "Target rank should be greater than one for this clause"); Type newTargetType = new Type(); newTargetType.UID = targetType.UID; newTargetType.IsIndexable = true; newTargetType.Name = targetType.Name; newTargetType.rank = targetType.rank -1; //Upcast once StackValue coercedValue = Coerce(sv, newTargetType, core); GCUtils.GCRetain(coercedValue, core); StackValue newSv = HeapUtils.StoreArray(new StackValue[] { coercedValue }, null, core); return newSv; } } if (sv.optype == AddressType.Pointer) { StackValue ret = ClassCoerece(sv, targetType, core); return ret; } //If it's anything other than array, just create a new copy switch (targetType.UID) { case (int)PrimitiveType.kInvalidType: Validity.Assert(false, "Can't convert invalid type"); break; case (int)PrimitiveType.kTypeBool: return sv.AsBoolean(core); case (int)PrimitiveType.kTypeChar: { StackValue newSV = sv.ShallowClone(); newSV.metaData = new MetaData { type = (int)PrimitiveType.kTypeChar }; return newSV; } case (int)PrimitiveType.kTypeDouble: return sv.AsDouble(); case (int)PrimitiveType.kTypeFunctionPointer: if (sv.metaData.type != (int)PrimitiveType.kTypeFunctionPointer) { core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kTypeMismatch, ProtoCore.RuntimeData.WarningMessage.kFailToConverToFunction); return StackUtils.BuildNull(); } return sv.ShallowClone(); case (int)PrimitiveType.kTypeHostEntityID: { StackValue newSV = sv.ShallowClone(); newSV.metaData = new MetaData { type = (int)PrimitiveType.kTypeHostEntityID }; return newSV; } case (int)PrimitiveType.kTypeInt: { if (sv.metaData.type == (int)PrimitiveType.kTypeDouble) { core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kTypeConvertionCauseInfoLoss, ProtoCore.RuntimeData.WarningMessage.kConvertDoubleToInt); } return sv.AsInt(); } case (int)PrimitiveType.kTypeNull: { if (sv.metaData.type != (int)PrimitiveType.kTypeNull) { core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kTypeMismatch, ProtoCore.RuntimeData.WarningMessage.kFailToConverToNull); return StackUtils.BuildNull(); } return sv.ShallowClone(); } case (int)PrimitiveType.kTypePointer: { if (sv.metaData.type != (int)PrimitiveType.kTypeNull) { core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kTypeMismatch, ProtoCore.RuntimeData.WarningMessage.kFailToConverToPointer); return StackUtils.BuildNull(); } StackValue ret = sv.ShallowClone(); return ret; } case (int)PrimitiveType.kTypeString: { StackValue newSV = sv.ShallowClone(); newSV.metaData = new MetaData { type = (int)PrimitiveType.kTypeString }; if (sv.metaData.type == (int)PrimitiveType.kTypeChar) { char ch = ProtoCore.Utils.EncodingUtils.ConvertInt64ToCharacter(newSV.opdata); newSV = StackUtils.BuildString(ch.ToString(), core.Heap); } return newSV; } case (int)PrimitiveType.kTypeVar: { return sv; } case (int)PrimitiveType.kTypeArray: { return ArrayUtils.CopyArray(sv, targetType, core); } default: if (sv.optype == AddressType.Null) return StackUtils.BuildNull(); else throw new NotImplementedException("Requested coercion not implemented"); } throw new NotImplementedException("Requested coercion not implemented"); } } }
using System; using System.Collections; using System.Collections.Specialized; using System.Configuration; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Appleseed.Framework.Security; using Appleseed.Framework.Settings; using Appleseed.Framework.Site.Configuration; namespace Appleseed.Framework.Web.UI.WebControls { /// <summary> /// ZenLayout is an ASP.NET WebControl which opens up a whole new way of specifying and building Appleseeds pages and sites. It is the principal element used to construct /// a Design Layout for a Appleseed web site. It accepts up to five templates, only one of which (CenterColTemplate) is effectively required. Since /// the other four (HeaderTemplate, LeftColTemplate, RightColTemplate and FooterTemplate) are optional, this gives tremendous flexibility /// in page layout. A page can consist of just a CenterColTemplate, plus optionally any combination of the other templates. /// For example:<br/> /// <code> /// &lt;zen:ZenLayout&gt; /// &lt;LeftColTemplate&gt;...&lt;/LeftColTemplate&gt; /// &lt;CenterColTemplate&gt;...&lt;/CenterColTemplate&gt; /// &lt;/zen:ZenLayout&gt; /// </code> /// would produce a page with just two columns, with no header and no footer.<br/> /// To produce a 'classic Appleseed' page with header, three columns and footer, you would use:<br/> /// <code> /// &lt;zen:ZenLayout&gt; /// &lt;HeaderTemplate&gt;...&lt;/HeaderTemplate&gt; /// &lt;LeftColTemplate&gt;...&lt;/LeftColTemplate&gt; /// &lt;CenterColTemplate&gt;...&lt;/CenterColTemplate&gt; /// &lt;RightColTemplate&gt;...&lt;/RightColTemplate&gt; /// &lt;FooterTemplate&gt;...&lt;/FooterTemplate&gt; /// &lt;/zen:ZenLayout&gt; /// </code> /// Each template can contain any number of Zen, Appleseed, ASP.NET or third-party WebControls or even 'fixed' HTML elements and text. /// There are currently four new WebControls provided with Zen: /// <list type="table"> /// <item> /// <term>ZenContent</term> /// <description> /// The ZenContent control is used to fill it's containing Template area with Appleseed Modules. The 'Content' /// attribute tells Zen which PaneName to look for. For example, if the 'Content' attribute is set to 'RightPane' then the parent /// template will receive any modules that are marked 'RightPane' in the Appleseed configuration for the current tab. It stands to reason that /// this ZenContent control should be enclosed within the RightColTemplate. This would be so for current 'normal' Appleseed behaviour. Nevertheless, /// the pane names used by Zen are not hard-coded. Zen reads through the current tab configuration and simply creates a list of PaneName values /// that it finds (with a count for each). Currently it is only ever going to find LeftPane, ContentPane and RightPane since those are the only values that Appleseed /// can currently assign. But Zen will keep up with Appleseed's development automatically: as soon as there is a way to assign other values to PaneName (e.g. 'Header', 'Footer' or even /// 'LowerRightAdvertisingPanel') then Zen will 'detect' the new value and allow you to fill a template area with those modules by specifying: Content=&quot;LowerRightAdvertisingPanel&quot;. /// Until that is possible, the only valid values for the 'Content' attribute are: LeftPane, ContentPane or RightPane. /// </description> /// </item> /// <item> /// <term>ZenHeaderTitle</term> /// <description> /// The ZenHeaderTitle control replaces both HeaderTitle and HeaderImage controls. It creates a specific HTML /// structure: /// <code>&lt;h1 id=&quot;portaltitle&quot; class=&quot;portaltitle&quot;&gt;Appleseed Portal&lt;span&gt;&lt;/span&gt;&lt;/h1&gt;</code> /// This HTML is intended to be 'worked on' by a specific CSS technique called 'Levin Image Replacement'. You'll notice that /// there is no reference to the HeaderImage in the HTML output: the image is specified in the current Theme's CSS and effectively /// 'overlays' the text, thus hiding it. See details of this elsewhere in the Zen documentation. /// </description> /// </item> /// <item> /// <term>ZenHeaderMenu</term> /// <description> /// The ZenHeaderMenu control inherits from the regular Appleseed.HeaderMenu and overrides its Render to produce a Zen-specific HTML /// output: /// <code> /// &lt;div class=&quot;...&quot;&gt; /// &lt;ul class=&quot;zen-hdrmenu-btns&quot;&gt; /// &lt;li&gt;&lt;a href='...'&gt;...&lt;/a&gt;&lt;/li&gt; /// &lt;li&gt;&lt;a href='...'&gt;...&lt;/a&gt;&lt;/li&gt; /// &lt;/ul&gt; /// &lt;/div&gt; /// &lt;div class=&quot;...&quot;&gt; /// &lt;ul class=&quot;zen-hdrmenu-labels&quot;&gt; /// &lt;li&gt;...&lt;/li&gt; /// &lt;/ul&gt; /// &lt;/div&gt; /// </code> /// Notice that link items and plain-text items are separated so they can be treated individually by the CSS. The CSS Class /// for each &lt;div&gt; can be set using the ButtonsCssClass and LabelsCssClass attributes of ZenHeaderMenu. Through inheritance, the /// normal range of Appleseed attributes can also be set (e.g. ShowLogon, ShowSaveDesktop, etc.). /// </description> /// </item> /// <item> /// <term>ZenNavigation</term> /// <description> /// The ZenNavigation control implements the Appleseed INavigation interface to produce horizontal or vertical menus. The actual output is a nested /// &lt;ul&gt; (unordered list). Through the magic of CSS, this can be displayed as a drop-down or pull-out menu. This feature is still a little experimental and may change /// in the near future: I'm experimenting with CSS techniques and may need to add more 'class' attributes within the output structure. /// </description> /// </item> /// </list> /// The output of the ZenLayout control is a complex hierarchy of &lt;div&gt; elements, within which will be contained any other controls specified in the Layout. The &lt;div&gt; hierarchy has a number /// of specific features: /// <list type="bullet"> /// <item> /// <description> /// Rather obviously it doesn't contain any &lt;table&gt; structures: the final appearance of the page is entirely /// determined by the CSS applied to it. /// </description> /// </item> /// <item> /// <description> /// The 'source order' of the template areas in the output HTML is: Header, CenterColumn, LeftColumn, RightColumn, Footer. This has obvious benefits /// for Search Engine Optimization (SEO), since a spider will read the main content (assumed to be in the center column) before it encounters the left column content. It also greatly /// improves the 'accessibility' of the page by presenting the page contents in an order which is more logical to ScreenReaders and browsers without CSS capability or with such capability /// disabled. Much of the apparent complexity of the structure is specifically to enable this 'trick'. /// </description> /// </item> /// <item> /// <description> /// The HTML elements used to create the page are 'semantically meaningful' (e.g. &lt;h1&gt; for the PortaTitle, &lt;ul&gt; for navigation lists, etc) or 'semantically neutral' when their sole purpose is /// layout (e.g. &lt;div&gt;). This is essential for true Section 508 or Accessibility Guidelines compliance. /// </description> /// </item> /// <item> /// <description> /// The various CSS classes which are assigned within the hierarchy are always prefixed with 'zen-' in order to ease the process of designing a site /// with CSS alone. Each 'area' of the layout is 'marked' with a specific CSS class name which makes it easy to control the appearance of elements within that area. For example, if you /// want the default paragraph text color in the left column to be 'red' then you'd add the CSS rule: /// <code>.zen-col-left p { color: red }</code> /// </description> /// </item> /// </list> /// By combining these four controls with the ZenLayout control you have a flexible, extensible means for specifying the structure of a Appleseed page. The page's appearance is entirely controlled through the /// application of CSS rules. The page is compact, fast, Search Engine friendly and highly accessible. The only challenge is to learn a new programming language (CSS) in order to make full use of it! /// </summary> /// <remarks> /// But wait! There's more!<br/> /// A Zenlayout control may also contain, within any one of its templates, another ZenLayout control. Each ZenLayout has an identifier assigned to it, so each one is individually addressable in the Theme CSS. For example, combine the two examples given earlier: /// <code> /// &lt;zen:ZenLayout CssID=&quot;myMainLayout&quot;&gt; /// &lt;HeaderTemplate&gt;...&lt;/HeaderTemplate&gt; /// &lt;LeftColTemplate&gt;...&lt;/LeftColTemplate&gt; /// &lt;CenterColTemplate&gt; /// &lt;zen:ZenLayout CssID=&quot;mySubLayout&quot;&gt; /// &lt;LeftColTemplate&gt;...&lt;/LeftColTemplate&gt; /// &lt;CenterColTemplate&gt;...&lt;/CenterColTemplate&gt; /// &lt;/zen:ZenLayout&gt; /// &lt;/CenterColTemplate&gt; /// &lt;RightColTemplate&gt;...&lt;/RightColTemplate&gt; /// &lt;FooterTemplate&gt;...&lt;/FooterTemplate&gt; /// &lt;/zen:ZenLayout&gt; /// </code> /// would give you a Header, FOUR columns and a footer plus the means to control it all with CSS. /// Embed one 'classic' Appleseed layout in the center column of another, like this: /// <code> /// &lt;zen:ZenLayout&gt; /// &lt;HeaderTemplate&gt;...&lt;/HeaderTemplate&gt; /// &lt;LeftColTemplate&gt;...&lt;/LeftColTemplate&gt; /// &lt;CenterColTemplate&gt; /// &lt;zen:ZenLayout&gt; /// &lt;HeaderTemplate&gt;...&lt;/HeaderTemplate&gt; /// &lt;LeftColTemplate&gt;...&lt;/LeftColTemplate&gt; /// &lt;CenterColTemplate&gt;...&lt;/CenterColTemplate&gt; /// &lt;RightColTemplate&gt;...&lt;/RightColTemplate&gt; /// &lt;FooterTemplate&gt;...&lt;/FooterTemplate&gt; /// &lt;/zen:ZenLayout&gt; /// &lt;/CenterColTemplate&gt; /// &lt;RightColTemplate&gt;...&lt;/RightColTemplate&gt; /// &lt;FooterTemplate&gt;...&lt;/FooterTemplate&gt; /// &lt;/zen:ZenLayout&gt; /// </code> /// and you've got a page with Header, LeftColumn, RightColumn and Footer as normal, but now the CenterColumn contains a header and footer /// of it's own plus one, two or three 'sub columns'(according to what modules are inserted).<br/> /// Of course, Appleseed's admin can't support this yet, but you could poke around in the database and achieve this today. Makes you think, doesn't it? /// </remarks> public class ZenLayout : WebControl, INamingContainer { #region private members private ITemplate headerTemplate; private ITemplate leftColTemplate; private ITemplate centerColTemplate; private ITemplate rightColTemplate; private ITemplate footerTemplate; private HtmlGenericControl zenMain; private HtmlGenericControl zenHdr; private HtmlGenericControl zenCols; private HtmlGenericControl zenColsWrapper; private HtmlGenericControl zenFloatWrapper; private HtmlGenericControl zenLeftCol; private HtmlGenericControl zenCenterCol; private HtmlGenericControl zenRightCol; private HtmlGenericControl zenMiddleCol; private HtmlGenericControl zenFtr; private HtmlGenericControl zenColClear; private string cssID = string.Empty; private string headerContent = string.Empty; private string leftContent = "LeftPane"; private string centerContent = "ContentPane"; private string rightContent = "RightPane"; private string footerContent = string.Empty; private bool forceLeft = false; private bool forceRight = false; private bool showLeft = false; private bool showRight = false; private const string ZEN_MAIN_CSS = "zen-main"; private const string ZEN_HDR_CSS = "zen-hdr"; private const string ZEN_COLS_CSS = "zen-cols"; private const string ZEN_FTR_CSS = "zen-ftr"; private const string ZEN_SHOW_ALL_CSS = "zen-show-all"; private const string ZEN_HIDE_LEFT_CSS = "zen-hide-left"; private const string ZEN_HIDE_RIGHT_CSS = "zen-hide-right"; private const string ZEN_HIDE_BOTH_CSS = "zen-hide-both"; private const string ZEN_COLS_WRAPPER_CSS = "zen-cols-wrapper"; private const string ZEN_FLOAT_WRAPPER_CSS = "zen-float-wrapper"; private const string ZEN_LEFT_COL_CSS = "zen-col-left"; private const string ZEN_CENTER_COL_CSS = "zen-col-center"; private const string ZEN_RIGHT_COL_CSS = "zen-col-right"; private const string ZEN_MIDDLE_COL_CSS = "zen-col-middle"; private const string ZEN_COL_CLEAR_CSS = "zen-clear"; private const string ZEN_COL_CLEAR_ID = "zen-em"; #endregion #region properties /// <summary> /// A string which will be added as the element ID of the outer DIV of this layout. /// The ID can then be used as a selector by the Theme CSS to limit the scope of a /// CSS rule to only this layout. /// </summary> /// <value>The CSS ID.</value> /// <remarks> /// Remember that CSS is CASE SENSITIVE (contrary to popular belief!), so use the exact case /// of whatever value you set here when constructing CSS rules.<br/> /// OPTIONAL: If no value is set then no ID attribute will be added and the elements within this layout /// cannot be addressed exclusively. This is the default behaviour. /// </remarks> /// <example> /// Set CssID to 'myLayout1'. Then a CSS rule like: <br/> /// <code>#myLayout1 p{color:red}</code> /// <br/> /// would make 'red' the default paragraph text color within that layout.<br/> /// </example> public string CssID { get { return cssID; } set { cssID = value.Trim(); } } /// <summary> /// Tells the layout which PaneName to expect as Header content within this layout /// </summary> /// <value>The content of the header.</value> /// <remarks> /// There is no default value. Value is case insensitive. /// </remarks> public string HeaderContent { get { return headerContent; } set { headerContent = value.Trim().ToLower(); } } /// <summary> /// Tells the layout which PaneName to expect as LeftColumn content within this layout /// </summary> /// <value>The content of the left.</value> /// <remarks> /// Defaults to 'LeftPane' (the Duemetri.ThreePanes value for left column). Value is case insensitive. /// </remarks> public string LeftContent { get { return leftContent; } set { leftContent = value.Trim().ToLower(); } } /// <summary> /// Tells the layout which PaneName to expect as CenterColumn content within this layout /// </summary> /// <value>The content of the center.</value> /// <remarks> /// Defaults to 'ContentPane' (the Duemetri.ThreePanes value for center column). Value is case insensitive. /// </remarks> public string CenterContent { get { return centerContent; } set { centerContent = value.Trim().ToLower(); } } /// <summary> /// Tells the layout which PaneName to expect as RightColumn content within this layout /// </summary> /// <value>The content of the right.</value> /// <remarks> /// Defaults to 'RightPane' (the Duemetri.ThreePanes value for right column). Value is case insensitive. /// </remarks> public string RightContent { get { return rightContent; } set { rightContent = value.Trim().ToLower(); } } /// <summary> /// Tells the layout which PaneName to expect as Footer content within this layout /// </summary> /// <value>The content of the footer.</value> /// <remarks> /// There is no default value. Value is case insensitive. /// </remarks> public string FooterContent { get { return footerContent; } set { footerContent = value.Trim().ToLower(); } } /// <summary> /// By default, Zen will 'hide' the left column if it is empty. Set ForceLeft to 'true' to force Zen to display an empty column. /// </summary> /// <value><c>true</c> if [force left]; otherwise, <c>false</c>.</value> /// <remarks> /// Default value is 'false'. /// </remarks> public bool ForceLeft { get { return forceLeft; } set { forceLeft = value; } } /// <summary> /// By default, Zen will 'hide' the right column if it is empty. Set ForceRight to 'true' to force Zen to display an empty column. /// </summary> /// <value><c>true</c> if [force right]; otherwise, <c>false</c>.</value> /// <remarks> /// Default value is 'false'. /// </remarks> public bool ForceRight { get { return forceRight; } set { forceRight = value; } } #endregion #region controls /// <summary> /// ZenMain control /// </summary> /// <value>The zen main.</value> public HtmlGenericControl ZenMain { get { if (zenMain == null) { zenMain = new HtmlGenericControl("div"); zenMain.Attributes.Add("class", ZEN_MAIN_CSS); if (CssID != string.Empty) zenMain.Attributes.Add("id", CssID); } return zenMain; } } /// <summary> /// ZenHdr control /// </summary> /// <value>The zen HDR.</value> public HtmlGenericControl ZenHdr { get { if (zenHdr == null && HeaderTemplate != null) { zenHdr = new HtmlGenericControl("div"); zenHdr.Attributes.Add("class", ZEN_HDR_CSS); } return zenHdr; } } /// <summary> /// ZenCols control /// </summary> /// <value>The zen cols.</value> public HtmlGenericControl ZenCols { get { if (zenCols == null) { zenCols = new HtmlGenericControl("div"); zenCols.Attributes.Add("class", ZEN_COLS_CSS); } return zenCols; } } /// <summary> /// ZenColsWrapper control /// </summary> /// <value>The zen cols wrapper.</value> public HtmlGenericControl ZenColsWrapper { get { if (zenColsWrapper == null) { zenColsWrapper = new HtmlGenericControl("div"); zenColsWrapper.Attributes.Add("class", ZEN_COLS_WRAPPER_CSS); } return zenColsWrapper; } } /// <summary> /// ZenFloatWrapper control /// </summary> /// <value>The zen float wrapper.</value> public HtmlGenericControl ZenFloatWrapper { get { if (zenFloatWrapper == null) { zenFloatWrapper = new HtmlGenericControl("div"); zenFloatWrapper.Attributes.Add("class", ZEN_FLOAT_WRAPPER_CSS); } return zenFloatWrapper; } } /// <summary> /// ZenLeftCol control /// </summary> /// <value>The zen left col.</value> public HtmlGenericControl ZenLeftCol { get { if (zenLeftCol == null) { zenLeftCol = new HtmlGenericControl("div"); zenLeftCol.Attributes.Add("class", ZEN_LEFT_COL_CSS); } return zenLeftCol; } } /// <summary> /// ZenCenterCol control /// </summary> /// <value>The zen center col.</value> public HtmlGenericControl ZenCenterCol { get { if (zenCenterCol == null) { zenCenterCol = new HtmlGenericControl("div"); zenCenterCol.Attributes.Add("class", ZEN_CENTER_COL_CSS); } return zenCenterCol; } } /// <summary> /// ZenRightCol control /// </summary> /// <value>The zen right col.</value> public HtmlGenericControl ZenRightCol { get { if (zenRightCol == null) { zenRightCol = new HtmlGenericControl("div"); zenRightCol.Attributes.Add("class", ZEN_RIGHT_COL_CSS); } return zenRightCol; } } /// <summary> /// ZenMiddleCol control /// </summary> /// <value>The zen middle col.</value> public HtmlGenericControl ZenMiddleCol { get { if (zenMiddleCol == null) { zenMiddleCol = new HtmlGenericControl("div"); zenMiddleCol.Attributes.Add("class", ZEN_MIDDLE_COL_CSS); } return zenMiddleCol; } } /// <summary> /// ZenFtr control /// </summary> /// <value>The zen FTR.</value> public HtmlGenericControl ZenFtr { get { if (zenFtr == null) { zenFtr = new HtmlGenericControl("div"); zenFtr.Attributes.Add("class", ZEN_FTR_CSS); } return zenFtr; } } /// <summary> /// ZenColClear control /// </summary> /// <value>The zen col clear.</value> public HtmlGenericControl ZenColClear { get { if (zenColClear == null) { zenColClear = new HtmlGenericControl("div"); zenColClear.Attributes.Add("class", ZEN_COL_CLEAR_CSS); zenColClear.Attributes.Add("id", ZEN_COL_CLEAR_ID); } return zenColClear; } } #endregion #region templates /// <summary> /// Left Column Template /// </summary> /// <value>The left col template.</value> public virtual ITemplate LeftColTemplate { get { return leftColTemplate; } set { leftColTemplate = value; } } /// <summary> /// Center Column Template /// </summary> /// <value>The center col template.</value> public virtual ITemplate CenterColTemplate { get { return centerColTemplate; } set { centerColTemplate = value; } } /// <summary> /// Right Column Template /// </summary> /// <value>The right col template.</value> public virtual ITemplate RightColTemplate { get { return rightColTemplate; } set { rightColTemplate = value; } } /// <summary> /// Header Template /// </summary> /// <value>The header template.</value> public virtual ITemplate HeaderTemplate { get { return headerTemplate; } set { headerTemplate = value; } } /// <summary> /// Footer Template /// </summary> /// <value>The footer template.</value> public virtual ITemplate FooterTemplate { get { return footerTemplate; } set { footerTemplate = value; } } #endregion #region methods /// <summary> /// Creates the Control Hierarchy /// </summary> private void CreateControlHierarchy() { //this.Controls.Clear(); if (HeaderTemplate != null) HeaderTemplate.InstantiateIn(ZenHdr); if (LeftColTemplate != null) LeftColTemplate.InstantiateIn(ZenLeftCol); if (CenterColTemplate != null) CenterColTemplate.InstantiateIn(ZenCenterCol); if (RightColTemplate != null) RightColTemplate.InstantiateIn(ZenRightCol); if (FooterTemplate != null) FooterTemplate.InstantiateIn(ZenFtr); HybridDictionary counts = GetModuleCount(); foreach (DictionaryEntry myArea in counts) { if (myArea.Key.ToString() == LeftContent) showLeft = true; if (myArea.Key.ToString() == RightContent) showRight = true; } if (ForceLeft) showLeft = true; if (ForceRight) showRight = true; // adjust CSS to match column count if (showLeft && showRight) ZenCols.Attributes.Add("class", string.Concat(ZEN_COLS_CSS, " ", ZEN_SHOW_ALL_CSS)); else if (showLeft && !showRight) ZenCols.Attributes.Add("class", string.Concat(ZEN_COLS_CSS, " ", ZEN_HIDE_RIGHT_CSS)); else if (!showLeft && showRight) ZenCols.Attributes.Add("class", string.Concat(ZEN_COLS_CSS, " ", ZEN_HIDE_LEFT_CSS)); else if (!showLeft && !showRight) ZenCols.Attributes.Add("class", string.Concat(ZEN_COLS_CSS, " ", ZEN_HIDE_BOTH_CSS)); // build the control structure ZenMiddleCol.Controls.Add(ZenCenterCol); ZenFloatWrapper.Controls.Add(ZenMiddleCol); ZenFloatWrapper.Controls.Add(ZenLeftCol); ZenColsWrapper.Controls.Add(ZenFloatWrapper); ZenColsWrapper.Controls.Add(ZenRightCol); ZenColsWrapper.Controls.Add(ZenColClear); ZenCols.Controls.Add(ZenColsWrapper); // if ( this.ZenHdr != null ) // this.ZenMain.Controls.Add(this.ZenHdr); // this.ZenMain.Controls.Add(this.ZenCols); // if ( this.ZenFtr != null ) // this.ZenMain.Controls.Add(this.ZenFtr); if (HeaderTemplate != null) ZenMain.Controls.Add(ZenHdr); if (CenterColTemplate != null && LeftColTemplate != null && RightColTemplate != null) ZenMain.Controls.Add(ZenCols); if (FooterTemplate != null) ZenMain.Controls.Add(ZenFtr); Controls.Add(ZenMain); } /// <summary> /// Counts the number of modules to be displayed by PaneName /// </summary> /// <returns> /// HybridDictionary containing counts for all PaneNames found /// </returns> /// <remarks> /// Method does not check Cultures setting, so could be fooled into displaying /// a column even though it is empty. This needs further investigation. /// </remarks> private HybridDictionary GetModuleCount() { //TODO: check Cultures setting? HybridDictionary counts = new HybridDictionary(3); string _key; PortalSettings PortalSettings = (PortalSettings) HttpContext.Current.Items["PortalSettings"]; if (PortalSettings.ActivePage.Modules.Count > 0) { // Loop through each entry in the configuration system for this tab foreach (ModuleSettings _moduleSettings in PortalSettings.ActivePage.Modules) { // Ensure that the visiting user has access to view the current module if (PortalSecurity.IsInRoles(_moduleSettings.AuthorizedViewRoles) == true) { _key = _moduleSettings.PaneName.ToLower(); if (counts.Contains(_key)) counts[_key] = ((int) counts[_key]) + 1; else counts.Add(_key, 1); } } } return counts; } #endregion #region overrides /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.DataBinding"></see> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"></see> object that contains the event data.</param> protected override void OnDataBinding(EventArgs e) { EnsureChildControls(); base.OnDataBinding(e); } // /// <summary> // /// Override OnLoad so we can force EnsureChildControls(). // /// Note: this is essential so that modules are processed before the Page itself, // /// and each module can contribute to the &lt;head&gt; element (e.g. CSS references). // /// </summary> // /// <param name="e"></param> // protected override void OnLoad(EventArgs e) // { // EnsureChildControls(); // base.OnLoad(e); // } /// <summary> /// Gets or sets the ie7 script. /// </summary> /// <value>The ie7 script.</value> public string Ie7Script { get { if (ie7Script == string.Empty) { if (ConfigurationManager.AppSettings["Ie7Script"] != null && ConfigurationManager.AppSettings["Ie7Script"].ToString() != string.Empty) { ie7Script = ConfigurationManager.AppSettings["Ie7Script"].ToString(); } } return ie7Script; } set { ie7Script = value; } } private string ie7Script = string.Empty; /// <summary> /// This member overrides Control.CreateChildControls /// </summary> protected override void CreateChildControls() { Controls.Clear(); if (Ie7Script != string.Empty) { // TODO: need to check registration for this if (!((Page) Page).IsAdditionalMetaElementRegistered("ie7")) { string _ie7 = string.Empty; string _ie7Part = string.Empty; foreach (string _script in Ie7Script.Split(new char[] {';'})) { _ie7Part = Path.WebPathCombine(Path.ApplicationRoot, _script); _ie7Part = string.Format( "<!--[if lt IE 7]><script src=\"{0}\" type=\"text/javascript\"></script><![endif]-->", _ie7Part); _ie7 += _ie7Part + "\n"; } ((Page) Page).RegisterAdditionalMetaElement("ie7", _ie7); } } CreateControlHierarchy(); } /// <summary> /// This member overrides Control.Render so we can exclude the useless outer &lt;span&gt; element that /// ASP.NET insists on adding. /// </summary> /// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter"></see> object that receives the control content.</param> protected override void Render(HtmlTextWriter writer) { RenderContents(writer); } #endregion } }
#region License /* Copyright (c) 2003-2015 Llewellyn Pritchard * All rights reserved. * This source code is subject to terms and conditions of the BSD License. * See license.txt. */ #endregion using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using IronScheme.Editor.ComponentModel; namespace IronScheme.Editor.Controls { class PictureComboBox : System.Windows.Forms.ComboBox { public PictureComboBox() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer, true); InitializeComponent(); this.ItemHeight = SystemInformation.MenuHeight - 1; } private void InitializeComponent() { this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.DropDownStyle = ComboBoxStyle.DropDownList; } GraphicsPath gp = null; int radius = 1; Pen borderpen = null; Brush selbg; Brush gradb; static Font font = SystemInformation.MenuFont; protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs e) { if (e.Index < 0) { return; } if (gp == null) { Rectangle r = e.Bounds; int angle = 180; r.Width--; r.Height--; //r.Inflate(-1, - radius/2); //r.Offset(0, (radius/2)); gp = new GraphicsPath(); // top left gp.AddArc(r.X, r.Y, radius, radius, angle, 90); angle += 90; // top right gp.AddArc(r.Right - radius, r.Y,radius, radius, angle, 90); angle += 90; // bottom right gp.AddArc(r.Right - radius, r.Bottom - radius, radius, radius, angle, 90); angle += 90; // bottom left gp.AddArc(r.X, r.Bottom - radius, radius, radius, angle, 90); gp.CloseAllFigures(); } if (borderpen == null) { borderpen = new Pen(SystemColors.Highlight, 1); //borderpen.Alignment = PenAlignment.Center; } bool selected = (e.State & DrawItemState.Selected) != 0; //normal AA looks bad e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; //e.Graphics.PixelOffsetMode = PixelOffsetMode.None; string word1 = Text; Rectangle r2 = e.Bounds; r2.Width = r2.Height + 2; r2.X--; r2.Height += 2; r2.Y--; Rectangle r4 = e.Bounds; r4.Inflate(1,1); //r4.Offset(-1,-1); e.Graphics.FillRectangle(SystemBrushes.Window, r4); //e.DrawBackground(); if (!(Items[e.Index] is CodeModel.ICodeElement)) { if (gradb == null) { LinearGradientBrush gb = new LinearGradientBrush(r2, SystemColors.ButtonFace, SystemColors.ButtonFace, 0f); gb.SetSigmaBellShape(0.9f, 0.2f); gradb = gb; } e.Graphics.FillRectangle(gradb, r2); } int h = SystemInformation.MenuHeight; Brush b = SystemBrushes.ControlText; if (selected) { Rectangle r = e.Bounds; //Console.WriteLine(r); r.Width -= 1; r.Height -= 1; Rectangle r3 = r; r3.Width -= SystemInformation.MenuHeight; r3.X += SystemInformation.MenuHeight + 1; if (selbg == null) { selbg = new SolidBrush(Color.FromArgb(196, 225, 255)); //r2.X -= r.Height/2; //r2.Height *= 2; //LinearGradientBrush gb = new LinearGradientBrush(r2, // Color.FromArgb(120, SystemColors.ControlLightLight), // Color.FromArgb(120, SystemColors.Highlight), 90f); //gb.SetSigmaBellShape(0.6f,0.9f); //selbg = SystemBrushes.Highlight; } e.Graphics.FillPath(selbg, gp); //e.Graphics.DrawPath(borderpen, gp); } { Rectangle r = e.Bounds; r.Width = r.Height; r.X++;r.X++; r.Y++;r.Y++; if (!selected) { //r.X++; //r.Y++; } IImageListProviderService ips = ServiceHost.ImageListProvider; if (ips != null) { int i = ips[Items[e.Index]]; if (i >= 0) { int f = (int)((e.Bounds.Height - 16)/2f); if ((e.State & DrawItemState.Focus) != 0) { ips.ImageList.Draw(e.Graphics, f+3, e.Bounds.Top + f + 1, i); } else { ips.ImageList.Draw(e.Graphics, f+3, e.Bounds.Top + f + 1, i); } } } if (!selected) { //r.X--; //r.Y--; } float fh = (float)font.FontFamily.GetCellAscent(0)/font.FontFamily.GetEmHeight(0); float bh = (float)font.FontFamily.GetCellDescent(0)/font.FontFamily.GetEmHeight(0); int hh = ((int)(float)(e.Bounds.Height - (fh - bh/2)*font.Height)/2); Type t = Items[e.Index] as Type; if (t == null) { t = Items[e.Index].GetType(); } Build.Project p = Items[e.Index] as Build.Project; if (p != null) { e.Graphics.DrawString(p.ProjectName, SystemInformation.MenuFont, b, r.Right + 1, e.Bounds.Top + hh); } else { Languages.Language l = Items[e.Index] as Languages.Language; if (l != null) { e.Graphics.DrawString(l.Name, SystemInformation.MenuFont, b, r.Right + 1, e.Bounds.Top + hh); } else { CodeModel.ICodeElement cl = Items[e.Index] as CodeModel.ICodeElement; if (cl != null) { e.Graphics.DrawString(cl is CodeModel.ICodeType ? cl.Fullname : ((cl is CodeModel.ICodeMethod || cl is CodeModel.ICodeField || cl is CodeModel.ICodeProperty) ? cl.ToString() : cl.Name), SystemInformation.MenuFont, b, r.Right + 1, e.Bounds.Top + hh); } else { e.Graphics.DrawString(NameAttribute.GetName(t), SystemInformation.MenuFont, b, r.Right + 1, e.Bounds.Top + hh); } } } gp.Dispose(); gp = null; if (gradb != null) { gradb.Dispose(); gradb = null; } if (selbg != null) { selbg.Dispose(); selbg = null; } } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.Cx.V3.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedExperimentsClientSnippets { /// <summary>Snippet for ListExperiments</summary> public void ListExperimentsRequestObject() { // Snippet: ListExperiments(ListExperimentsRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) ListExperimentsRequest request = new ListExperimentsRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), }; // Make the request PagedEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperiments(request); // Iterate over all response items, lazily performing RPCs as required foreach (Experiment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListExperimentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExperimentsAsync</summary> public async Task ListExperimentsRequestObjectAsync() { // Snippet: ListExperimentsAsync(ListExperimentsRequest, CallSettings) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) ListExperimentsRequest request = new ListExperimentsRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), }; // Make the request PagedAsyncEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperimentsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Experiment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListExperimentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExperiments</summary> public void ListExperiments() { // Snippet: ListExperiments(string, string, int?, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; // Make the request PagedEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperiments(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Experiment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListExperimentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExperimentsAsync</summary> public async Task ListExperimentsAsync() { // Snippet: ListExperimentsAsync(string, string, int?, CallSettings) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; // Make the request PagedAsyncEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperimentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Experiment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListExperimentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExperiments</summary> public void ListExperimentsResourceNames() { // Snippet: ListExperiments(EnvironmentName, string, int?, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); // Make the request PagedEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperiments(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Experiment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListExperimentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExperimentsAsync</summary> public async Task ListExperimentsResourceNamesAsync() { // Snippet: ListExperimentsAsync(EnvironmentName, string, int?, CallSettings) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); // Make the request PagedAsyncEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperimentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Experiment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListExperimentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetExperiment</summary> public void GetExperimentRequestObject() { // Snippet: GetExperiment(GetExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) GetExperimentRequest request = new GetExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = experimentsClient.GetExperiment(request); // End snippet } /// <summary>Snippet for GetExperimentAsync</summary> public async Task GetExperimentRequestObjectAsync() { // Snippet: GetExperimentAsync(GetExperimentRequest, CallSettings) // Additional: GetExperimentAsync(GetExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) GetExperimentRequest request = new GetExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = await experimentsClient.GetExperimentAsync(request); // End snippet } /// <summary>Snippet for GetExperiment</summary> public void GetExperiment() { // Snippet: GetExperiment(string, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = experimentsClient.GetExperiment(name); // End snippet } /// <summary>Snippet for GetExperimentAsync</summary> public async Task GetExperimentAsync() { // Snippet: GetExperimentAsync(string, CallSettings) // Additional: GetExperimentAsync(string, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = await experimentsClient.GetExperimentAsync(name); // End snippet } /// <summary>Snippet for GetExperiment</summary> public void GetExperimentResourceNames() { // Snippet: GetExperiment(ExperimentName, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = experimentsClient.GetExperiment(name); // End snippet } /// <summary>Snippet for GetExperimentAsync</summary> public async Task GetExperimentResourceNamesAsync() { // Snippet: GetExperimentAsync(ExperimentName, CallSettings) // Additional: GetExperimentAsync(ExperimentName, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = await experimentsClient.GetExperimentAsync(name); // End snippet } /// <summary>Snippet for CreateExperiment</summary> public void CreateExperimentRequestObject() { // Snippet: CreateExperiment(CreateExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) CreateExperimentRequest request = new CreateExperimentRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), Experiment = new Experiment(), }; // Make the request Experiment response = experimentsClient.CreateExperiment(request); // End snippet } /// <summary>Snippet for CreateExperimentAsync</summary> public async Task CreateExperimentRequestObjectAsync() { // Snippet: CreateExperimentAsync(CreateExperimentRequest, CallSettings) // Additional: CreateExperimentAsync(CreateExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) CreateExperimentRequest request = new CreateExperimentRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), Experiment = new Experiment(), }; // Make the request Experiment response = await experimentsClient.CreateExperimentAsync(request); // End snippet } /// <summary>Snippet for CreateExperiment</summary> public void CreateExperiment() { // Snippet: CreateExperiment(string, Experiment, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; Experiment experiment = new Experiment(); // Make the request Experiment response = experimentsClient.CreateExperiment(parent, experiment); // End snippet } /// <summary>Snippet for CreateExperimentAsync</summary> public async Task CreateExperimentAsync() { // Snippet: CreateExperimentAsync(string, Experiment, CallSettings) // Additional: CreateExperimentAsync(string, Experiment, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; Experiment experiment = new Experiment(); // Make the request Experiment response = await experimentsClient.CreateExperimentAsync(parent, experiment); // End snippet } /// <summary>Snippet for CreateExperiment</summary> public void CreateExperimentResourceNames() { // Snippet: CreateExperiment(EnvironmentName, Experiment, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); Experiment experiment = new Experiment(); // Make the request Experiment response = experimentsClient.CreateExperiment(parent, experiment); // End snippet } /// <summary>Snippet for CreateExperimentAsync</summary> public async Task CreateExperimentResourceNamesAsync() { // Snippet: CreateExperimentAsync(EnvironmentName, Experiment, CallSettings) // Additional: CreateExperimentAsync(EnvironmentName, Experiment, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); Experiment experiment = new Experiment(); // Make the request Experiment response = await experimentsClient.CreateExperimentAsync(parent, experiment); // End snippet } /// <summary>Snippet for UpdateExperiment</summary> public void UpdateExperimentRequestObject() { // Snippet: UpdateExperiment(UpdateExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) UpdateExperimentRequest request = new UpdateExperimentRequest { Experiment = new Experiment(), UpdateMask = new FieldMask(), }; // Make the request Experiment response = experimentsClient.UpdateExperiment(request); // End snippet } /// <summary>Snippet for UpdateExperimentAsync</summary> public async Task UpdateExperimentRequestObjectAsync() { // Snippet: UpdateExperimentAsync(UpdateExperimentRequest, CallSettings) // Additional: UpdateExperimentAsync(UpdateExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) UpdateExperimentRequest request = new UpdateExperimentRequest { Experiment = new Experiment(), UpdateMask = new FieldMask(), }; // Make the request Experiment response = await experimentsClient.UpdateExperimentAsync(request); // End snippet } /// <summary>Snippet for UpdateExperiment</summary> public void UpdateExperiment() { // Snippet: UpdateExperiment(Experiment, FieldMask, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) Experiment experiment = new Experiment(); FieldMask updateMask = new FieldMask(); // Make the request Experiment response = experimentsClient.UpdateExperiment(experiment, updateMask); // End snippet } /// <summary>Snippet for UpdateExperimentAsync</summary> public async Task UpdateExperimentAsync() { // Snippet: UpdateExperimentAsync(Experiment, FieldMask, CallSettings) // Additional: UpdateExperimentAsync(Experiment, FieldMask, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) Experiment experiment = new Experiment(); FieldMask updateMask = new FieldMask(); // Make the request Experiment response = await experimentsClient.UpdateExperimentAsync(experiment, updateMask); // End snippet } /// <summary>Snippet for DeleteExperiment</summary> public void DeleteExperimentRequestObject() { // Snippet: DeleteExperiment(DeleteExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) DeleteExperimentRequest request = new DeleteExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request experimentsClient.DeleteExperiment(request); // End snippet } /// <summary>Snippet for DeleteExperimentAsync</summary> public async Task DeleteExperimentRequestObjectAsync() { // Snippet: DeleteExperimentAsync(DeleteExperimentRequest, CallSettings) // Additional: DeleteExperimentAsync(DeleteExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) DeleteExperimentRequest request = new DeleteExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request await experimentsClient.DeleteExperimentAsync(request); // End snippet } /// <summary>Snippet for DeleteExperiment</summary> public void DeleteExperiment() { // Snippet: DeleteExperiment(string, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request experimentsClient.DeleteExperiment(name); // End snippet } /// <summary>Snippet for DeleteExperimentAsync</summary> public async Task DeleteExperimentAsync() { // Snippet: DeleteExperimentAsync(string, CallSettings) // Additional: DeleteExperimentAsync(string, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request await experimentsClient.DeleteExperimentAsync(name); // End snippet } /// <summary>Snippet for DeleteExperiment</summary> public void DeleteExperimentResourceNames() { // Snippet: DeleteExperiment(ExperimentName, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request experimentsClient.DeleteExperiment(name); // End snippet } /// <summary>Snippet for DeleteExperimentAsync</summary> public async Task DeleteExperimentResourceNamesAsync() { // Snippet: DeleteExperimentAsync(ExperimentName, CallSettings) // Additional: DeleteExperimentAsync(ExperimentName, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request await experimentsClient.DeleteExperimentAsync(name); // End snippet } /// <summary>Snippet for StartExperiment</summary> public void StartExperimentRequestObject() { // Snippet: StartExperiment(StartExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) StartExperimentRequest request = new StartExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = experimentsClient.StartExperiment(request); // End snippet } /// <summary>Snippet for StartExperimentAsync</summary> public async Task StartExperimentRequestObjectAsync() { // Snippet: StartExperimentAsync(StartExperimentRequest, CallSettings) // Additional: StartExperimentAsync(StartExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) StartExperimentRequest request = new StartExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = await experimentsClient.StartExperimentAsync(request); // End snippet } /// <summary>Snippet for StartExperiment</summary> public void StartExperiment() { // Snippet: StartExperiment(string, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = experimentsClient.StartExperiment(name); // End snippet } /// <summary>Snippet for StartExperimentAsync</summary> public async Task StartExperimentAsync() { // Snippet: StartExperimentAsync(string, CallSettings) // Additional: StartExperimentAsync(string, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = await experimentsClient.StartExperimentAsync(name); // End snippet } /// <summary>Snippet for StartExperiment</summary> public void StartExperimentResourceNames() { // Snippet: StartExperiment(ExperimentName, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = experimentsClient.StartExperiment(name); // End snippet } /// <summary>Snippet for StartExperimentAsync</summary> public async Task StartExperimentResourceNamesAsync() { // Snippet: StartExperimentAsync(ExperimentName, CallSettings) // Additional: StartExperimentAsync(ExperimentName, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = await experimentsClient.StartExperimentAsync(name); // End snippet } /// <summary>Snippet for StopExperiment</summary> public void StopExperimentRequestObject() { // Snippet: StopExperiment(StopExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) StopExperimentRequest request = new StopExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = experimentsClient.StopExperiment(request); // End snippet } /// <summary>Snippet for StopExperimentAsync</summary> public async Task StopExperimentRequestObjectAsync() { // Snippet: StopExperimentAsync(StopExperimentRequest, CallSettings) // Additional: StopExperimentAsync(StopExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) StopExperimentRequest request = new StopExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = await experimentsClient.StopExperimentAsync(request); // End snippet } /// <summary>Snippet for StopExperiment</summary> public void StopExperiment() { // Snippet: StopExperiment(string, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = experimentsClient.StopExperiment(name); // End snippet } /// <summary>Snippet for StopExperimentAsync</summary> public async Task StopExperimentAsync() { // Snippet: StopExperimentAsync(string, CallSettings) // Additional: StopExperimentAsync(string, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = await experimentsClient.StopExperimentAsync(name); // End snippet } /// <summary>Snippet for StopExperiment</summary> public void StopExperimentResourceNames() { // Snippet: StopExperiment(ExperimentName, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = experimentsClient.StopExperiment(name); // End snippet } /// <summary>Snippet for StopExperimentAsync</summary> public async Task StopExperimentResourceNamesAsync() { // Snippet: StopExperimentAsync(ExperimentName, CallSettings) // Additional: StopExperimentAsync(ExperimentName, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = await experimentsClient.StopExperimentAsync(name); // End snippet } } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using UnityEngine.UI; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] private int maxRunStamina = 100; [SerializeField] private int staminaDecay = 10; [SerializeField] private int staminJumpDecay = 25; private int m_StaminaDecay; [SerializeField] private int staminaRegenMultiplier = 3; [SerializeField] private float runStamina; public GameObject staminaBar; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); runStamina = maxRunStamina; m_StaminaDecay = staminaDecay; } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump && runStamina > staminJumpDecay) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; m_StaminaDecay = staminaDecay; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump && runStamina > staminJumpDecay) { runStamina -= 25; m_StaminaDecay = 0; m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !(Input.GetKey(KeyCode.LeftShift) && (Input.GetButton("Horizontal") || Input.GetButton("Vertical"))); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); if (!m_IsWalking && runStamina>=0) { runStamina = Mathf.Clamp(runStamina - Time.deltaTime * m_StaminaDecay, 0, maxRunStamina); float stamina = runStamina/maxRunStamina; staminaBar.transform.localScale = new Vector3(stamina, 1, 1); } else { if (runStamina <= maxRunStamina && !Input.GetKey(KeyCode.LeftShift)) { runStamina = Mathf.Clamp(runStamina + Time.deltaTime * m_StaminaDecay * staminaRegenMultiplier, 0, maxRunStamina); float stamina = runStamina/maxRunStamina; staminaBar.transform.localScale = new Vector3(stamina, 1, 1); } } if (runStamina <= 0) { speed = m_WalkSpeed; } // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
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 SuperGrouper.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using OpenMetaverse; using OpenMetaverse.Packets; using System; using System.Collections.Generic; using System.Reflection; namespace OpenSim.Region.ClientStack.LindenUDP { public sealed class PacketPool { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly PacketPool instance = new PacketPool(); /// <summary> /// Pool of packets available for reuse. /// </summary> private readonly Dictionary<PacketType, Stack<Packet>> pool = new Dictionary<PacketType, Stack<Packet>>(); private static Dictionary<Type, Stack<Object>> DataBlocks = new Dictionary<Type, Stack<Object>>(); public static PacketPool Instance { get { return instance; } } public bool RecyclePackets { get; set; } public bool RecycleDataBlocks { get; set; } /// <summary> /// The number of packets pooled /// </summary> public int PacketsPooled { get { lock (pool) return pool.Count; } } /// <summary> /// The number of blocks pooled. /// </summary> public int BlocksPooled { get { lock (DataBlocks) return DataBlocks.Count; } } /// <summary> /// Number of packets requested. /// </summary> public long PacketsRequested { get; private set; } /// <summary> /// Number of packets reused. /// </summary> public long PacketsReused { get; private set; } /// <summary> /// Number of packet blocks requested. /// </summary> public long BlocksRequested { get; private set; } /// <summary> /// Number of packet blocks reused. /// </summary> public long BlocksReused { get; private set; } private PacketPool() { // defaults RecyclePackets = true; RecycleDataBlocks = true; } /// <summary> /// Gets a packet of the given type. /// </summary> /// <param name='type'></param> /// <returns>Guaranteed to always return a packet, whether from the pool or newly constructed.</returns> public Packet GetPacket(PacketType type) { PacketsRequested++; Packet packet; if (!RecyclePackets) return Packet.BuildPacket(type); lock (pool) { if (!pool.ContainsKey(type) || pool[type] == null || (pool[type]).Count == 0) { // m_log.DebugFormat("[PACKETPOOL]: Building {0} packet", type); // Creating a new packet if we cannot reuse an old package packet = Packet.BuildPacket(type); } else { // m_log.DebugFormat("[PACKETPOOL]: Pulling {0} packet", type); // Recycle old packages PacketsReused++; packet = pool[type].Pop(); } } return packet; } private static PacketType GetType(byte[] bytes) { ushort id; PacketFrequency freq; bool isZeroCoded = (bytes[0] & Helpers.MSG_ZEROCODED) != 0; if (bytes[6] == 0xFF) { if (bytes[7] == 0xFF) { freq = PacketFrequency.Low; if (isZeroCoded && bytes[8] == 0) id = bytes[10]; else id = (ushort)((bytes[8] << 8) + bytes[9]); } else { freq = PacketFrequency.Medium; id = bytes[7]; } } else { freq = PacketFrequency.High; id = bytes[6]; } return Packet.GetType(id, freq); } public Packet GetPacket(byte[] bytes, ref int packetEnd, byte[] zeroBuffer) { PacketType type = GetType(bytes); // Array.Clear(zeroBuffer, 0, zeroBuffer.Length); int i = 0; Packet packet = GetPacket(type); if (packet == null) m_log.WarnFormat("[PACKETPOOL]: Failed to get packet of type {0}", type); else packet.FromBytes(bytes, ref i, ref packetEnd, zeroBuffer); return packet; } /// <summary> /// Return a packet to the packet pool /// </summary> /// <param name="packet"></param> public void ReturnPacket(Packet packet) { if (RecycleDataBlocks) { switch (packet.Type) { case PacketType.ObjectUpdate: ObjectUpdatePacket oup = (ObjectUpdatePacket)packet; foreach (ObjectUpdatePacket.ObjectDataBlock oupod in oup.ObjectData) ReturnDataBlock<ObjectUpdatePacket.ObjectDataBlock>(oupod); oup.ObjectData = null; break; case PacketType.ImprovedTerseObjectUpdate: ImprovedTerseObjectUpdatePacket itoup = (ImprovedTerseObjectUpdatePacket)packet; foreach (ImprovedTerseObjectUpdatePacket.ObjectDataBlock itoupod in itoup.ObjectData) ReturnDataBlock<ImprovedTerseObjectUpdatePacket.ObjectDataBlock>(itoupod); itoup.ObjectData = null; break; } } if (RecyclePackets) { switch (packet.Type) { // List pooling packets here case PacketType.AgentUpdate: case PacketType.PacketAck: case PacketType.ObjectUpdate: case PacketType.ImprovedTerseObjectUpdate: lock (pool) { PacketType type = packet.Type; if (!pool.ContainsKey(type)) { pool[type] = new Stack<Packet>(); } if ((pool[type]).Count < 50) { // m_log.DebugFormat("[PACKETPOOL]: Pushing {0} packet", type); pool[type].Push(packet); } } break; // Other packets wont pool default: return; } } } public T GetDataBlock<T>() where T: new() { lock (DataBlocks) { BlocksRequested++; Stack<Object> s; if (DataBlocks.TryGetValue(typeof(T), out s)) { if (s.Count > 0) { BlocksReused++; return (T)s.Pop(); } } else { DataBlocks[typeof(T)] = new Stack<Object>(); } return new T(); } } public void ReturnDataBlock<T>(T block) where T: new() { if (block == null) return; lock (DataBlocks) { if (!DataBlocks.ContainsKey(typeof(T))) DataBlocks[typeof(T)] = new Stack<Object>(); if (DataBlocks[typeof(T)].Count < 50) DataBlocks[typeof(T)].Push(block); } } } }
using System; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Steamworks.Data; namespace Steamworks { internal unsafe class ISteamMatchmaking : SteamInterface { internal ISteamMatchmaking( bool IsGameServer ) { SetupInterface( IsGameServer ); } [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_SteamMatchmaking_v009", CallingConvention = Platform.CC)] internal static extern IntPtr SteamAPI_SteamMatchmaking_v009(); public override IntPtr GetUserInterfacePointer() => SteamAPI_SteamMatchmaking_v009(); #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetFavoriteGameCount", CallingConvention = Platform.CC)] private static extern int _GetFavoriteGameCount( IntPtr self ); #endregion internal int GetFavoriteGameCount() { var returnValue = _GetFavoriteGameCount( Self ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetFavoriteGame", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetFavoriteGame( IntPtr self, int iGame, ref AppId pnAppID, ref uint pnIP, ref ushort pnConnPort, ref ushort pnQueryPort, ref uint punFlags, ref uint pRTime32LastPlayedOnServer ); #endregion internal bool GetFavoriteGame( int iGame, ref AppId pnAppID, ref uint pnIP, ref ushort pnConnPort, ref ushort pnQueryPort, ref uint punFlags, ref uint pRTime32LastPlayedOnServer ) { var returnValue = _GetFavoriteGame( Self, iGame, ref pnAppID, ref pnIP, ref pnConnPort, ref pnQueryPort, ref punFlags, ref pRTime32LastPlayedOnServer ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_AddFavoriteGame", CallingConvention = Platform.CC)] private static extern int _AddFavoriteGame( IntPtr self, AppId nAppID, uint nIP, ushort nConnPort, ushort nQueryPort, uint unFlags, uint rTime32LastPlayedOnServer ); #endregion internal int AddFavoriteGame( AppId nAppID, uint nIP, ushort nConnPort, ushort nQueryPort, uint unFlags, uint rTime32LastPlayedOnServer ) { var returnValue = _AddFavoriteGame( Self, nAppID, nIP, nConnPort, nQueryPort, unFlags, rTime32LastPlayedOnServer ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_RemoveFavoriteGame", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _RemoveFavoriteGame( IntPtr self, AppId nAppID, uint nIP, ushort nConnPort, ushort nQueryPort, uint unFlags ); #endregion internal bool RemoveFavoriteGame( AppId nAppID, uint nIP, ushort nConnPort, ushort nQueryPort, uint unFlags ) { var returnValue = _RemoveFavoriteGame( Self, nAppID, nIP, nConnPort, nQueryPort, unFlags ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_RequestLobbyList", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _RequestLobbyList( IntPtr self ); #endregion internal CallResult<LobbyMatchList_t> RequestLobbyList() { var returnValue = _RequestLobbyList( Self ); return new CallResult<LobbyMatchList_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_AddRequestLobbyListStringFilter", CallingConvention = Platform.CC)] private static extern void _AddRequestLobbyListStringFilter( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKeyToMatch, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValueToMatch, LobbyComparison eComparisonType ); #endregion internal void AddRequestLobbyListStringFilter( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKeyToMatch, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValueToMatch, LobbyComparison eComparisonType ) { _AddRequestLobbyListStringFilter( Self, pchKeyToMatch, pchValueToMatch, eComparisonType ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_AddRequestLobbyListNumericalFilter", CallingConvention = Platform.CC)] private static extern void _AddRequestLobbyListNumericalFilter( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKeyToMatch, int nValueToMatch, LobbyComparison eComparisonType ); #endregion internal void AddRequestLobbyListNumericalFilter( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKeyToMatch, int nValueToMatch, LobbyComparison eComparisonType ) { _AddRequestLobbyListNumericalFilter( Self, pchKeyToMatch, nValueToMatch, eComparisonType ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_AddRequestLobbyListNearValueFilter", CallingConvention = Platform.CC)] private static extern void _AddRequestLobbyListNearValueFilter( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKeyToMatch, int nValueToBeCloseTo ); #endregion internal void AddRequestLobbyListNearValueFilter( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKeyToMatch, int nValueToBeCloseTo ) { _AddRequestLobbyListNearValueFilter( Self, pchKeyToMatch, nValueToBeCloseTo ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_AddRequestLobbyListFilterSlotsAvailable", CallingConvention = Platform.CC)] private static extern void _AddRequestLobbyListFilterSlotsAvailable( IntPtr self, int nSlotsAvailable ); #endregion internal void AddRequestLobbyListFilterSlotsAvailable( int nSlotsAvailable ) { _AddRequestLobbyListFilterSlotsAvailable( Self, nSlotsAvailable ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_AddRequestLobbyListDistanceFilter", CallingConvention = Platform.CC)] private static extern void _AddRequestLobbyListDistanceFilter( IntPtr self, LobbyDistanceFilter eLobbyDistanceFilter ); #endregion internal void AddRequestLobbyListDistanceFilter( LobbyDistanceFilter eLobbyDistanceFilter ) { _AddRequestLobbyListDistanceFilter( Self, eLobbyDistanceFilter ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_AddRequestLobbyListResultCountFilter", CallingConvention = Platform.CC)] private static extern void _AddRequestLobbyListResultCountFilter( IntPtr self, int cMaxResults ); #endregion internal void AddRequestLobbyListResultCountFilter( int cMaxResults ) { _AddRequestLobbyListResultCountFilter( Self, cMaxResults ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_AddRequestLobbyListCompatibleMembersFilter", CallingConvention = Platform.CC)] private static extern void _AddRequestLobbyListCompatibleMembersFilter( IntPtr self, SteamId steamIDLobby ); #endregion internal void AddRequestLobbyListCompatibleMembersFilter( SteamId steamIDLobby ) { _AddRequestLobbyListCompatibleMembersFilter( Self, steamIDLobby ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetLobbyByIndex", CallingConvention = Platform.CC)] private static extern SteamId _GetLobbyByIndex( IntPtr self, int iLobby ); #endregion internal SteamId GetLobbyByIndex( int iLobby ) { var returnValue = _GetLobbyByIndex( Self, iLobby ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_CreateLobby", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _CreateLobby( IntPtr self, LobbyType eLobbyType, int cMaxMembers ); #endregion internal CallResult<LobbyCreated_t> CreateLobby( LobbyType eLobbyType, int cMaxMembers ) { var returnValue = _CreateLobby( Self, eLobbyType, cMaxMembers ); return new CallResult<LobbyCreated_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_JoinLobby", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _JoinLobby( IntPtr self, SteamId steamIDLobby ); #endregion internal CallResult<LobbyEnter_t> JoinLobby( SteamId steamIDLobby ) { var returnValue = _JoinLobby( Self, steamIDLobby ); return new CallResult<LobbyEnter_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_LeaveLobby", CallingConvention = Platform.CC)] private static extern void _LeaveLobby( IntPtr self, SteamId steamIDLobby ); #endregion internal void LeaveLobby( SteamId steamIDLobby ) { _LeaveLobby( Self, steamIDLobby ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_InviteUserToLobby", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _InviteUserToLobby( IntPtr self, SteamId steamIDLobby, SteamId steamIDInvitee ); #endregion internal bool InviteUserToLobby( SteamId steamIDLobby, SteamId steamIDInvitee ) { var returnValue = _InviteUserToLobby( Self, steamIDLobby, steamIDInvitee ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetNumLobbyMembers", CallingConvention = Platform.CC)] private static extern int _GetNumLobbyMembers( IntPtr self, SteamId steamIDLobby ); #endregion internal int GetNumLobbyMembers( SteamId steamIDLobby ) { var returnValue = _GetNumLobbyMembers( Self, steamIDLobby ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetLobbyMemberByIndex", CallingConvention = Platform.CC)] private static extern SteamId _GetLobbyMemberByIndex( IntPtr self, SteamId steamIDLobby, int iMember ); #endregion internal SteamId GetLobbyMemberByIndex( SteamId steamIDLobby, int iMember ) { var returnValue = _GetLobbyMemberByIndex( Self, steamIDLobby, iMember ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetLobbyData", CallingConvention = Platform.CC)] private static extern Utf8StringPointer _GetLobbyData( IntPtr self, SteamId steamIDLobby, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey ); #endregion internal string GetLobbyData( SteamId steamIDLobby, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey ) { var returnValue = _GetLobbyData( Self, steamIDLobby, pchKey ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_SetLobbyData", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _SetLobbyData( IntPtr self, SteamId steamIDLobby, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValue ); #endregion internal bool SetLobbyData( SteamId steamIDLobby, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValue ) { var returnValue = _SetLobbyData( Self, steamIDLobby, pchKey, pchValue ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetLobbyDataCount", CallingConvention = Platform.CC)] private static extern int _GetLobbyDataCount( IntPtr self, SteamId steamIDLobby ); #endregion internal int GetLobbyDataCount( SteamId steamIDLobby ) { var returnValue = _GetLobbyDataCount( Self, steamIDLobby ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetLobbyDataByIndex", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetLobbyDataByIndex( IntPtr self, SteamId steamIDLobby, int iLobbyData, IntPtr pchKey, int cchKeyBufferSize, IntPtr pchValue, int cchValueBufferSize ); #endregion internal bool GetLobbyDataByIndex( SteamId steamIDLobby, int iLobbyData, out string pchKey, out string pchValue ) { using var mempchKey = Helpers.TakeMemory(); using var mempchValue = Helpers.TakeMemory(); var returnValue = _GetLobbyDataByIndex( Self, steamIDLobby, iLobbyData, mempchKey, (1024 * 32), mempchValue, (1024 * 32) ); pchKey = Helpers.MemoryToString( mempchKey ); pchValue = Helpers.MemoryToString( mempchValue ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_DeleteLobbyData", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _DeleteLobbyData( IntPtr self, SteamId steamIDLobby, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey ); #endregion internal bool DeleteLobbyData( SteamId steamIDLobby, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey ) { var returnValue = _DeleteLobbyData( Self, steamIDLobby, pchKey ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetLobbyMemberData", CallingConvention = Platform.CC)] private static extern Utf8StringPointer _GetLobbyMemberData( IntPtr self, SteamId steamIDLobby, SteamId steamIDUser, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey ); #endregion internal string GetLobbyMemberData( SteamId steamIDLobby, SteamId steamIDUser, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey ) { var returnValue = _GetLobbyMemberData( Self, steamIDLobby, steamIDUser, pchKey ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_SetLobbyMemberData", CallingConvention = Platform.CC)] private static extern void _SetLobbyMemberData( IntPtr self, SteamId steamIDLobby, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValue ); #endregion internal void SetLobbyMemberData( SteamId steamIDLobby, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValue ) { _SetLobbyMemberData( Self, steamIDLobby, pchKey, pchValue ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_SendLobbyChatMsg", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _SendLobbyChatMsg( IntPtr self, SteamId steamIDLobby, IntPtr pvMsgBody, int cubMsgBody ); #endregion internal bool SendLobbyChatMsg( SteamId steamIDLobby, IntPtr pvMsgBody, int cubMsgBody ) { var returnValue = _SendLobbyChatMsg( Self, steamIDLobby, pvMsgBody, cubMsgBody ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetLobbyChatEntry", CallingConvention = Platform.CC)] private static extern int _GetLobbyChatEntry( IntPtr self, SteamId steamIDLobby, int iChatID, ref SteamId pSteamIDUser, IntPtr pvData, int cubData, ref ChatEntryType peChatEntryType ); #endregion internal int GetLobbyChatEntry( SteamId steamIDLobby, int iChatID, ref SteamId pSteamIDUser, IntPtr pvData, int cubData, ref ChatEntryType peChatEntryType ) { var returnValue = _GetLobbyChatEntry( Self, steamIDLobby, iChatID, ref pSteamIDUser, pvData, cubData, ref peChatEntryType ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_RequestLobbyData", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _RequestLobbyData( IntPtr self, SteamId steamIDLobby ); #endregion internal bool RequestLobbyData( SteamId steamIDLobby ) { var returnValue = _RequestLobbyData( Self, steamIDLobby ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_SetLobbyGameServer", CallingConvention = Platform.CC)] private static extern void _SetLobbyGameServer( IntPtr self, SteamId steamIDLobby, uint unGameServerIP, ushort unGameServerPort, SteamId steamIDGameServer ); #endregion internal void SetLobbyGameServer( SteamId steamIDLobby, uint unGameServerIP, ushort unGameServerPort, SteamId steamIDGameServer ) { _SetLobbyGameServer( Self, steamIDLobby, unGameServerIP, unGameServerPort, steamIDGameServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetLobbyGameServer", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetLobbyGameServer( IntPtr self, SteamId steamIDLobby, ref uint punGameServerIP, ref ushort punGameServerPort, ref SteamId psteamIDGameServer ); #endregion internal bool GetLobbyGameServer( SteamId steamIDLobby, ref uint punGameServerIP, ref ushort punGameServerPort, ref SteamId psteamIDGameServer ) { var returnValue = _GetLobbyGameServer( Self, steamIDLobby, ref punGameServerIP, ref punGameServerPort, ref psteamIDGameServer ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_SetLobbyMemberLimit", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _SetLobbyMemberLimit( IntPtr self, SteamId steamIDLobby, int cMaxMembers ); #endregion internal bool SetLobbyMemberLimit( SteamId steamIDLobby, int cMaxMembers ) { var returnValue = _SetLobbyMemberLimit( Self, steamIDLobby, cMaxMembers ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetLobbyMemberLimit", CallingConvention = Platform.CC)] private static extern int _GetLobbyMemberLimit( IntPtr self, SteamId steamIDLobby ); #endregion internal int GetLobbyMemberLimit( SteamId steamIDLobby ) { var returnValue = _GetLobbyMemberLimit( Self, steamIDLobby ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_SetLobbyType", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _SetLobbyType( IntPtr self, SteamId steamIDLobby, LobbyType eLobbyType ); #endregion internal bool SetLobbyType( SteamId steamIDLobby, LobbyType eLobbyType ) { var returnValue = _SetLobbyType( Self, steamIDLobby, eLobbyType ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_SetLobbyJoinable", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _SetLobbyJoinable( IntPtr self, SteamId steamIDLobby, [MarshalAs( UnmanagedType.U1 )] bool bLobbyJoinable ); #endregion internal bool SetLobbyJoinable( SteamId steamIDLobby, [MarshalAs( UnmanagedType.U1 )] bool bLobbyJoinable ) { var returnValue = _SetLobbyJoinable( Self, steamIDLobby, bLobbyJoinable ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_GetLobbyOwner", CallingConvention = Platform.CC)] private static extern SteamId _GetLobbyOwner( IntPtr self, SteamId steamIDLobby ); #endregion internal SteamId GetLobbyOwner( SteamId steamIDLobby ) { var returnValue = _GetLobbyOwner( Self, steamIDLobby ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_SetLobbyOwner", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _SetLobbyOwner( IntPtr self, SteamId steamIDLobby, SteamId steamIDNewOwner ); #endregion internal bool SetLobbyOwner( SteamId steamIDLobby, SteamId steamIDNewOwner ) { var returnValue = _SetLobbyOwner( Self, steamIDLobby, steamIDNewOwner ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMatchmaking_SetLinkedLobby", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _SetLinkedLobby( IntPtr self, SteamId steamIDLobby, SteamId steamIDLobbyDependent ); #endregion internal bool SetLinkedLobby( SteamId steamIDLobby, SteamId steamIDLobbyDependent ) { var returnValue = _SetLinkedLobby( Self, steamIDLobby, steamIDLobbyDependent ); return returnValue; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim 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.Globalization; using System.IO; using System.Security.Cryptography; using System.Text; using System.Xml; using OpenMetaverse; namespace OpenSim.Framework.Communications.Capabilities { /// <summary> /// Borrowed from (a older version of) libsl for now, as their new llsd code doesn't work we our decoding code. /// </summary> public static class LLSD { /// <summary> /// /// </summary> public class LLSDParseException : Exception { public LLSDParseException(string message) : base(message) { } } /// <summary> /// /// </summary> public class LLSDSerializeException : Exception { public LLSDSerializeException(string message) : base(message) { } } /// <summary> /// /// </summary> /// <param name="b"></param> /// <returns></returns> public static object LLSDDeserialize(byte[] b) { return LLSDDeserialize(new MemoryStream(b, false)); } /// <summary> /// /// </summary> /// <param name="st"></param> /// <returns></returns> public static object LLSDDeserialize(Stream st) { XmlTextReader reader = new XmlTextReader(st); reader.Read(); SkipWS(reader); if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "llsd") throw new LLSDParseException("Expected <llsd>"); reader.Read(); object ret = LLSDParseOne(reader); SkipWS(reader); if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "llsd") throw new LLSDParseException("Expected </llsd>"); return ret; } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public static byte[] LLSDSerialize(object obj) { StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); writer.Formatting = Formatting.None; writer.WriteStartElement(String.Empty, "llsd", String.Empty); LLSDWriteOne(writer, obj); writer.WriteEndElement(); writer.Close(); return Encoding.UTF8.GetBytes(sw.ToString()); } /// <summary> /// /// </summary> /// <param name="writer"></param> /// <param name="obj"></param> public static void LLSDWriteOne(XmlTextWriter writer, object obj) { if (obj == null) { writer.WriteStartElement(String.Empty, "undef", String.Empty); writer.WriteEndElement(); return; } if (obj is string) { writer.WriteStartElement(String.Empty, "string", String.Empty); writer.WriteString((string) obj); writer.WriteEndElement(); } else if (obj is int) { writer.WriteStartElement(String.Empty, "integer", String.Empty); writer.WriteString(obj.ToString()); writer.WriteEndElement(); } else if (obj is double) { writer.WriteStartElement(String.Empty, "real", String.Empty); writer.WriteString(obj.ToString()); writer.WriteEndElement(); } else if (obj is bool) { bool b = (bool) obj; writer.WriteStartElement(String.Empty, "boolean", String.Empty); writer.WriteString(b ? "1" : "0"); writer.WriteEndElement(); } else if (obj is ulong) { throw new Exception("ulong in LLSD is currently not implemented, fix me!"); } else if (obj is UUID) { UUID u = (UUID) obj; writer.WriteStartElement(String.Empty, "uuid", String.Empty); writer.WriteString(u.ToString()); writer.WriteEndElement(); } else if (obj is Hashtable) { Hashtable h = obj as Hashtable; writer.WriteStartElement(String.Empty, "map", String.Empty); foreach (string key in h.Keys) { writer.WriteStartElement(String.Empty, "key", String.Empty); writer.WriteString(key); writer.WriteEndElement(); LLSDWriteOne(writer, h[key]); } writer.WriteEndElement(); } else if (obj is ArrayList) { ArrayList a = obj as ArrayList; writer.WriteStartElement(String.Empty, "array", String.Empty); foreach (object item in a) { LLSDWriteOne(writer, item); } writer.WriteEndElement(); } else if (obj is byte[]) { byte[] b = obj as byte[]; writer.WriteStartElement(String.Empty, "binary", String.Empty); writer.WriteStartAttribute(String.Empty, "encoding", String.Empty); writer.WriteString("base64"); writer.WriteEndAttribute(); //// Calculate the length of the base64 output //long length = (long)(4.0d * b.Length / 3.0d); //if (length % 4 != 0) length += 4 - (length % 4); //// Create the char[] for base64 output and fill it //char[] tmp = new char[length]; //int i = Convert.ToBase64CharArray(b, 0, b.Length, tmp, 0); //writer.WriteString(new String(tmp)); writer.WriteString(Convert.ToBase64String(b)); writer.WriteEndElement(); } else { throw new LLSDSerializeException("Unknown type " + obj.GetType().Name); } } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static object LLSDParseOne(XmlTextReader reader) { SkipWS(reader); if (reader.NodeType != XmlNodeType.Element) throw new LLSDParseException("Expected an element"); string dtype = reader.LocalName; object ret = null; switch (dtype) { case "undef": { if (reader.IsEmptyElement) { reader.Read(); return null; } reader.Read(); SkipWS(reader); ret = null; break; } case "boolean": { if (reader.IsEmptyElement) { reader.Read(); return false; } reader.Read(); string s = reader.ReadString().Trim(); if (s == String.Empty || s == "false" || s == "0") ret = false; else if (s == "true" || s == "1") ret = true; else throw new LLSDParseException("Bad boolean value " + s); break; } case "integer": { if (reader.IsEmptyElement) { reader.Read(); return 0; } reader.Read(); ret = Convert.ToInt32(reader.ReadString().Trim()); break; } case "real": { if (reader.IsEmptyElement) { reader.Read(); return 0.0f; } reader.Read(); ret = Convert.ToDouble(reader.ReadString().Trim()); break; } case "uuid": { if (reader.IsEmptyElement) { reader.Read(); return UUID.Zero; } reader.Read(); ret = new UUID(reader.ReadString().Trim()); break; } case "string": { if (reader.IsEmptyElement) { reader.Read(); return String.Empty; } reader.Read(); ret = reader.ReadString(); break; } case "binary": { if (reader.IsEmptyElement) { reader.Read(); return new byte[0]; } if (reader.GetAttribute("encoding") != null && reader.GetAttribute("encoding") != "base64") { throw new LLSDParseException("Unknown encoding: " + reader.GetAttribute("encoding")); } reader.Read(); FromBase64Transform b64 = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces); byte[] inp = Encoding.UTF8.GetBytes(reader.ReadString()); ret = b64.TransformFinalBlock(inp, 0, inp.Length); break; } case "date": { reader.Read(); throw new Exception("LLSD TODO: date"); } case "map": { return LLSDParseMap(reader); } case "array": { return LLSDParseArray(reader); } default: throw new LLSDParseException("Unknown element <" + dtype + ">"); } if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != dtype) { throw new LLSDParseException("Expected </" + dtype + ">"); } reader.Read(); return ret; } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static Hashtable LLSDParseMap(XmlTextReader reader) { Hashtable ret = new Hashtable(); if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "map") throw new LLSDParseException("Expected <map>"); if (reader.IsEmptyElement) { reader.Read(); return ret; } reader.Read(); while (true) { SkipWS(reader); if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "map") { reader.Read(); break; } if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "key") throw new LLSDParseException("Expected <key>"); string key = reader.ReadString(); if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "key") throw new LLSDParseException("Expected </key>"); reader.Read(); object val = LLSDParseOne(reader); ret[key] = val; } return ret; // TODO } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static ArrayList LLSDParseArray(XmlTextReader reader) { ArrayList ret = new ArrayList(); if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "array") throw new LLSDParseException("Expected <array>"); if (reader.IsEmptyElement) { reader.Read(); return ret; } reader.Read(); while (true) { SkipWS(reader); if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "array") { reader.Read(); break; } ret.Insert(ret.Count, LLSDParseOne(reader)); } return ret; // TODO } /// <summary> /// /// </summary> /// <param name="count"></param> /// <returns></returns> private static string GetSpaces(int count) { StringBuilder b = new StringBuilder(); for (int i = 0; i < count; i++) b.Append(" "); return b.ToString(); } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="indent"></param> /// <returns></returns> public static String LLSDDump(object obj, int indent) { if (obj == null) { return GetSpaces(indent) + "- undef\n"; } else if (obj is string) { return GetSpaces(indent) + "- string \"" + (string) obj + "\"\n"; } else if (obj is int) { return GetSpaces(indent) + "- integer " + obj.ToString() + "\n"; } else if (obj is double) { return GetSpaces(indent) + "- float " + obj.ToString() + "\n"; } else if (obj is UUID) { return GetSpaces(indent) + "- uuid " + ((UUID) obj).ToString() + Environment.NewLine; } else if (obj is Hashtable) { StringBuilder ret = new StringBuilder(); ret.Append(GetSpaces(indent) + "- map" + Environment.NewLine); Hashtable map = (Hashtable) obj; foreach (string key in map.Keys) { ret.Append(GetSpaces(indent + 2) + "- key \"" + key + "\"" + Environment.NewLine); ret.Append(LLSDDump(map[key], indent + 3)); } return ret.ToString(); } else if (obj is ArrayList) { StringBuilder ret = new StringBuilder(); ret.Append(GetSpaces(indent) + "- array\n"); ArrayList list = (ArrayList) obj; foreach (object item in list) { ret.Append(LLSDDump(item, indent + 2)); } return ret.ToString(); } else if (obj is byte[]) { return GetSpaces(indent) + "- binary\n" + Utils.BytesToHexString((byte[]) obj, GetSpaces(indent)) + Environment.NewLine; } else { return GetSpaces(indent) + "- unknown type " + obj.GetType().Name + Environment.NewLine; } } public static object ParseTerseLLSD(string llsd) { int notused; return ParseTerseLLSD(llsd, out notused); } public static object ParseTerseLLSD(string llsd, out int endPos) { if (llsd.Length == 0) { endPos = 0; return null; } // Identify what type of object this is switch (llsd[0]) { case '!': throw new LLSDParseException("Undefined value type encountered"); case '1': endPos = 1; return true; case '0': endPos = 1; return false; case 'i': { if (llsd.Length < 2) throw new LLSDParseException("Integer value type with no value"); int value; endPos = FindEnd(llsd, 1); if (Int32.TryParse(llsd.Substring(1, endPos - 1), out value)) return value; else throw new LLSDParseException("Failed to parse integer value type"); } case 'r': { if (llsd.Length < 2) throw new LLSDParseException("Real value type with no value"); double value; endPos = FindEnd(llsd, 1); if (Double.TryParse(llsd.Substring(1, endPos - 1), NumberStyles.Float, Utils.EnUsCulture.NumberFormat, out value)) return value; else throw new LLSDParseException("Failed to parse double value type"); } case 'u': { if (llsd.Length < 17) throw new LLSDParseException("UUID value type with no value"); UUID value; endPos = FindEnd(llsd, 1); if (UUID.TryParse(llsd.Substring(1, endPos - 1), out value)) return value; else throw new LLSDParseException("Failed to parse UUID value type"); } case 'b': //byte[] value = new byte[llsd.Length - 1]; // This isn't the actual binary LLSD format, just the terse format sent // at login so I don't even know if there is a binary type throw new LLSDParseException("Binary value type is unimplemented"); case 's': case 'l': if (llsd.Length < 2) throw new LLSDParseException("String value type with no value"); endPos = FindEnd(llsd, 1); return llsd.Substring(1, endPos - 1); case 'd': // Never seen one before, don't know what the format is throw new LLSDParseException("Date value type is unimplemented"); case '[': { if (llsd.IndexOf(']') == -1) throw new LLSDParseException("Invalid array"); int pos = 0; ArrayList array = new ArrayList(); while (llsd[pos] != ']') { ++pos; // Advance past comma if need be if (llsd[pos] == ',') ++pos; // Allow a single whitespace character if (pos < llsd.Length && llsd[pos] == ' ') ++pos; int end; array.Add(ParseTerseLLSD(llsd.Substring(pos), out end)); pos += end; } endPos = pos + 1; return array; } case '{': { if (llsd.IndexOf('}') == -1) throw new LLSDParseException("Invalid map"); int pos = 0; Hashtable hashtable = new Hashtable(); while (llsd[pos] != '}') { ++pos; // Advance past comma if need be if (llsd[pos] == ',') ++pos; // Allow a single whitespace character if (pos < llsd.Length && llsd[pos] == ' ') ++pos; if (llsd[pos] != '\'') throw new LLSDParseException("Expected a map key"); int endquote = llsd.IndexOf('\'', pos + 1); if (endquote == -1 || (endquote + 1) >= llsd.Length || llsd[endquote + 1] != ':') throw new LLSDParseException("Invalid map format"); string key = llsd.Substring(pos, endquote - pos); key = key.Replace("'", String.Empty); pos += (endquote - pos) + 2; int end; hashtable.Add(key, ParseTerseLLSD(llsd.Substring(pos), out end)); pos += end; } endPos = pos + 1; return hashtable; } default: throw new Exception("Unknown value type"); } } private static int FindEnd(string llsd, int start) { int end = llsd.IndexOfAny(new char[] {',', ']', '}'}); if (end == -1) end = llsd.Length - 1; return end; } /// <summary> /// /// </summary> /// <param name="reader"></param> private static void SkipWS(XmlTextReader reader) { while ( reader.NodeType == XmlNodeType.Comment || reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.SignificantWhitespace || reader.NodeType == XmlNodeType.XmlDeclaration) { reader.Read(); } } } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_272 : MapLoop { public M_272() : base(null) { Content.AddRange(new MapBaseEntity[] { new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_N9(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LID(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 }, }); } //1000 public class L_N9 : MapLoop { public L_N9(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1100 public class L_NM1 : MapLoop { public L_NM1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } //2000 public class L_LID : MapLoop { public L_LID(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LID() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new BCI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new L_LIE(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new L_N9_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_PWK(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_NM1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_REF(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2100 public class L_LIE : MapLoop { public L_LIE(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LIE() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2200 public class L_N9_1 : MapLoop { public L_N9_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2300 public class L_PWK : MapLoop { public L_PWK(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PWK() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2400 public class L_NM1_1 : MapLoop { public L_NM1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new L_LIE_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2410 public class L_LIE_1 : MapLoop { public L_LIE_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LIE() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2500 public class L_REF : MapLoop { public L_REF(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new REF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new L_VEH(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_NX1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_PIN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } //2503 public class L_VEH : MapLoop { public L_VEH(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new VEH() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new VAT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DVI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new VRC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DAM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LIE_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2510 public class L_LIE_2 : MapLoop { public L_LIE_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LIE() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2515 public class L_LX : MapLoop { public L_LX(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PDR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PDP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new K2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new LIE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new EM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new SD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PKD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new K1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new V1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new R1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new R4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_K2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2518 public class L_K2 : MapLoop { public L_K2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new K2() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new LIE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2520 public class L_NX1 : MapLoop { public L_NX1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NX1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new ICH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CRC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new BCI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_LQ(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_NM1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2525 public class L_LQ : MapLoop { public L_LQ(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LQ() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_LQ_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2528 public class L_LQ_1 : MapLoop { public L_LQ_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LQ() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } //2600 public class L_NM1_2 : MapLoop { public L_NM1_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new ICH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CRC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new BCI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_III(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2610 public class L_III : MapLoop { public L_III(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new III() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new L_LQ_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2615 public class L_LQ_2 : MapLoop { public L_LQ_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LQ() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } //2700 public class L_PIN : MapLoop { public L_PIN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PIN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new BCI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_PWK_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2710 public class L_PWK_1 : MapLoop { public L_PWK_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PWK() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } } }
using System.Globalization; namespace NQuery.Tests.Symbols { public class BuiltInFunctionsTests : BuiltInSymbolsTests { private static void AssertEvaluatesToDouble(string text, double expectedValue) { var untypedActualValue = Compute(text); var actualValue = Convert.ToDouble(untypedActualValue); var expectedRounded = Math.Round(actualValue, 6); var actualRounded = Math.Round(expectedValue, 6); Assert.Equal(expectedRounded, actualRounded); } private static void AssertEvaluatesTo(string text, DateTime expectedValue) { var untypedActualValue = Compute(text); var actualValue = Convert.ToDateTime(untypedActualValue); var expectedRounded = TruncateSeconds(expectedValue); var actualRounded = TruncateSeconds(actualValue); Assert.Equal(expectedRounded, actualRounded); } private static DateTime TruncateSeconds(DateTime value) { return new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, 0); } [Fact] public void BuiltInFunctions_Abs() { AssertEvaluatesToDouble("ABS(-2)", 2); AssertEvaluatesToDouble("ABS(0)", 0); AssertEvaluatesToDouble("ABS(+3)", 3); } [Fact] public void BuiltInFunctions_Acos() { AssertEvaluatesToDouble("ACOS(0)", Math.PI / 2); AssertEvaluatesToDouble("ACOS(1)", 0); } [Fact] public void BuiltInFunctions_Asin() { AssertEvaluatesToDouble("ASIN(0)", 0.0); AssertEvaluatesToDouble("ASIN(1)", Math.PI / 2); } [Fact] public void BuiltInFunctions_Atan() { AssertEvaluatesToDouble("ATAN(0)", 0.0); AssertEvaluatesToDouble("ATAN(1)", Math.PI / 4); } [Fact] public void BuiltInFunctions_Atan2() { AssertEvaluatesToDouble("ATAN2(0, 0)", 0.0); AssertEvaluatesToDouble("ATAN2(1, 1)", Math.PI / 4); } [Fact] public void BuiltInFunctions_Ceiling() { AssertEvaluatesToDouble("CEILING(-3.1)", -3.0); AssertEvaluatesToDouble("CEILING(-3.9)", -3.0); AssertEvaluatesToDouble("CEILING(2.1)", 3.0); AssertEvaluatesToDouble("CEILING(2.9)", 3.0); } [Fact] public void BuiltInFunctions_Charindex() { AssertEvaluatesTo("CHARINDEX('el', 'hello')", 2); AssertEvaluatesTo("CHARINDEX('test', 'hello')", 0); } [Fact] public void BuiltInFunctions_Cos() { AssertEvaluatesToDouble("COS(0)", 1.0); AssertEvaluatesToDouble("COS(1)", 0.54030230586814); } [Fact] public void BuiltInFunctions_Cosh() { AssertEvaluatesToDouble("COSH(0)", 1); AssertEvaluatesToDouble("COSH(1)", 1.54308063481524); } [Fact] public void BuiltInFunctions_Day() { AssertEvaluatesTo("DAY(TO_DATETIME('2010-1-1'))", 1); AssertEvaluatesTo("DAY(TO_DATETIME('2011-3-2'))", 2); AssertEvaluatesTo("DAY(TO_DATETIME('2012-12-31'))", 31); } [Fact] public void BuiltInFunctions_Exp() { AssertEvaluatesToDouble("EXP(0)", 1); AssertEvaluatesToDouble("EXP(1)", Math.E); AssertEvaluatesToDouble("EXP(2)", Math.E * Math.E); } [Fact] public void BuiltInFunctions_Floor() { AssertEvaluatesToDouble("FLOOR(-3.1)", -4.0); AssertEvaluatesToDouble("FLOOR(-3.9)", -4.0); AssertEvaluatesToDouble("FLOOR(2.1)", 2.0); AssertEvaluatesToDouble("FLOOR(2.9)", 2.0); } [Fact] public void BuiltInFunctions_Format() { var oldCulture = Thread.CurrentThread.CurrentCulture; try { var newCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); newCulture.NumberFormat.PercentSymbol = "#"; Thread.CurrentThread.CurrentCulture = newCulture; AssertEvaluatesTo("FORMAT(.123, 'P2')", "12.30 #"); } finally { Thread.CurrentThread.CurrentCulture = oldCulture; } } [Fact] public void BuiltInFunctions_GetDate() { AssertEvaluatesTo("GETDATE()", DateTime.Now); } [Fact] public void BuiltInFunctions_GetUtcDate() { AssertEvaluatesTo("GETUTCDATE()", DateTime.UtcNow); } [Fact] public void BuiltInFunctions_Left() { AssertEvaluatesTo("LEFT('test', 0)", ""); AssertEvaluatesTo("LEFT('test', 2)", "te"); AssertEvaluatesTo("LEFT('test', 4)", "test"); AssertEvaluatesTo("LEFT('test', 10)", "test"); } [Fact] public void BuiltInFunctions_Len() { AssertEvaluatesTo("LEN('')", 0); AssertEvaluatesTo("LEN('hello')", 5); } [Fact] public void BuiltInFunctions_Log() { AssertEvaluatesToDouble("LOG(0)", double.NegativeInfinity); AssertEvaluatesToDouble("LOG(1)", 0.0); AssertEvaluatesToDouble("LOG(3)", 1.09861228866811); } [Fact] public void BuiltInFunctions_Log10() { AssertEvaluatesToDouble("LOG10(0)", double.NegativeInfinity); AssertEvaluatesToDouble("LOG10(1)", 0.0); AssertEvaluatesToDouble("LOG10(10)", 1); } [Fact] public void BuiltInFunctions_Lower() { AssertEvaluatesTo("LOWER('Hello')", "hello"); } [Fact] public void BuiltInFunctions_LPad() { AssertEvaluatesTo("LPAD('test', 10)", " test"); } [Fact] public void BuiltInFunctions_LTrim() { AssertEvaluatesTo("LTRIM(' test ')", "test "); } [Fact] public void BuiltInFunctions_Month() { AssertEvaluatesTo("MONTH(TO_DATETIME('2010-1-1'))", 1); AssertEvaluatesTo("MONTH(TO_DATETIME('2011-3-2'))", 3); AssertEvaluatesTo("MONTH(TO_DATETIME('2012-12-31'))", 12); } [Fact] public void BuiltInFunctions_Pow() { AssertEvaluatesToDouble("POW(2, 0)", 1); AssertEvaluatesToDouble("POW(2, 1)", 2); AssertEvaluatesToDouble("POW(2, 2)", 4); } [Fact] public void BuiltInFunctions_RegexEscape() { AssertEvaluatesTo("REGEX_ESCAPE('')", ""); AssertEvaluatesTo("REGEX_ESCAPE('test')", "test"); AssertEvaluatesTo("REGEX_ESCAPE('.*')", @"\.\*"); } [Fact] public void BuiltInFunctions_RegexMatch() { AssertEvaluatesTo("REGEX_MATCH('', 'v\\d+\\.\\d+')", false); AssertEvaluatesTo("REGEX_MATCH('v12.2', '^v\\d+\\.\\d+$')", true); AssertEvaluatesTo("REGEX_MATCH('v12.2', '^\\d+\\.\\d+$')", false); } [Fact] public void BuiltInFunctions_RegexReplace() { AssertEvaluatesTo("REGEX_REPLACE('', '([a-z]+) = ([a-z]+)', '$2 = $1')", ""); AssertEvaluatesTo("REGEX_REPLACE('var = value', '([a-z]+) = ([a-z]+)', '$2 = $1')", "value = var"); AssertEvaluatesTo("REGEX_REPLACE('var != value', '([a-z]+) = ([a-z]+)', '$2 = $1')", "var != value"); } [Fact] public void BuiltInFunctions_RegexUnescape() { AssertEvaluatesTo("REGEX_UNESCAPE('')", ""); AssertEvaluatesTo("REGEX_UNESCAPE('test')", "test"); AssertEvaluatesTo("REGEX_UNESCAPE('\\.\\*')", ".*"); } [Fact] public void BuiltInFunctions_Replace() { AssertEvaluatesTo("REPLACE('', ',', '_')", ""); AssertEvaluatesTo("REPLACE('hello, world', ', ', '_')", "hello_world"); } [Fact] public void BuiltInFunctions_Replicate() { AssertEvaluatesTo("REPLICATE('', 0)", ""); AssertEvaluatesTo("REPLICATE('', 1)", ""); AssertEvaluatesTo("REPLICATE('', 2)", ""); AssertEvaluatesTo("REPLICATE('a', 0)", ""); AssertEvaluatesTo("REPLICATE('a', 1)", "a"); AssertEvaluatesTo("REPLICATE('a', 2)", "aa"); AssertEvaluatesTo("REPLICATE('hello', 0)", ""); AssertEvaluatesTo("REPLICATE('hello', 1)", "hello"); AssertEvaluatesTo("REPLICATE('hello', 2)", "hellohello"); } [Fact] public void BuiltInFunctions_Reverse() { AssertEvaluatesTo("REVERSE('')", ""); AssertEvaluatesTo("REVERSE('a')", "a"); AssertEvaluatesTo("REVERSE('hello')", "olleh"); } [Fact] public void BuiltInFunctions_Right() { AssertEvaluatesTo("RIGHT('test', 0)", ""); AssertEvaluatesTo("RIGHT('test', 2)", "st"); AssertEvaluatesTo("RIGHT('test', 4)", "test"); AssertEvaluatesTo("RIGHT('test', 10)", "test"); } [Fact] public void BuiltInFunctions_Round() { AssertEvaluatesToDouble("ROUND(1.1)", 1.0); AssertEvaluatesToDouble("ROUND(1.2)", 1.0); AssertEvaluatesToDouble("ROUND(1.5)", 2.0); AssertEvaluatesToDouble("ROUND(1.6)", 2.0); AssertEvaluatesToDouble("ROUND(TO_DECIMAL(1.001), 2)", 1.00); AssertEvaluatesToDouble("ROUND(TO_DECIMAL(1.002), 2)", 1.00); AssertEvaluatesToDouble("ROUND(TO_DECIMAL(1.005), 2)", 1.01); AssertEvaluatesToDouble("ROUND(TO_DECIMAL(1.006), 2)", 1.01); } [Fact] public void BuiltInFunctions_RPad() { AssertEvaluatesTo("RPAD('test', 10)", "test "); } [Fact] public void BuiltInFunctions_RTrim() { AssertEvaluatesTo("RTRIM(' test ')", " test"); } [Fact] public void BuiltInFunctions_Sign() { AssertEvaluatesTo("SIGN(-3)", -1); AssertEvaluatesTo("SIGN(0)", 0); AssertEvaluatesTo("SIGN(+2)", +1); } [Fact] public void BuiltInFunctions_Sin() { AssertEvaluatesToDouble("SIN(0)", 0.0); AssertEvaluatesToDouble("SIN(1)", 0.841470984807897); } [Fact] public void BuiltInFunctions_Sinh() { AssertEvaluatesToDouble("SINH(0)", 0); AssertEvaluatesToDouble("SINH(1)", 1.1752011936438); } [Fact] public void BuiltInFunctions_Soundex() { AssertEvaluatesTo("SOUNDEX('Robert')", "R163"); } [Fact] public void BuiltInFunctions_Space() { AssertEvaluatesTo("SPACE(0)", ""); AssertEvaluatesTo("SPACE(1)", " "); AssertEvaluatesTo("SPACE(4)", " "); } [Fact] public void BuiltInFunctions_Sqrt() { AssertEvaluatesToDouble("SQRT(0)", 0.0); AssertEvaluatesToDouble("SQRT(2)", Math.Sqrt(2.0)); AssertEvaluatesToDouble("SQRT(4)", 2.0); AssertEvaluatesToDouble("SQRT(9)", 3.0); } [Fact] public void BuiltInFunctions_Substring() { AssertEvaluatesTo("SUBSTRING('hello', 0)", ""); AssertEvaluatesTo("SUBSTRING('hello', 1)", "hello"); AssertEvaluatesTo("SUBSTRING('hello', 3)", "llo"); AssertEvaluatesTo("SUBSTRING('hello', 0, 0)", ""); AssertEvaluatesTo("SUBSTRING('hello', 0, 1)", ""); AssertEvaluatesTo("SUBSTRING('hello', 1, 5)", "hello"); AssertEvaluatesTo("SUBSTRING('hello', 1, 10)", "hello"); AssertEvaluatesTo("SUBSTRING('hello', 1, 3)", "hel"); AssertEvaluatesTo("SUBSTRING('hello', 3, 2)", "ll"); AssertEvaluatesTo("SUBSTRING('hello', 3, 3)", "llo"); AssertEvaluatesTo("SUBSTRING('hello', 3, 4)", "llo"); } [Fact] public void BuiltInFunctions_Tan() { AssertEvaluatesToDouble("TAN(0)", 0.0); AssertEvaluatesToDouble("TAN(1)", 1.5574077246549); } [Fact] public void BuiltInFunctions_Tanh() { AssertEvaluatesToDouble("TANH(0)", 0); AssertEvaluatesToDouble("TANH(1)", 0.761594155955765); } [Fact] public void BuiltInFunctions_ToBoolean() { AssertEvaluatesTo("TO_BOOLEAN(0)", false); AssertEvaluatesTo("TO_BOOLEAN(1)", true); AssertEvaluatesTo("TO_BOOLEAN('True')", true); AssertEvaluatesTo("TO_BOOLEAN('False')", false); AssertEvaluatesTo("TO_BOOLEAN('true')", true); AssertEvaluatesTo("TO_BOOLEAN('false')", false); } [Fact] public void BuiltInFunctions_ToByte() { AssertEvaluatesTo("TO_BYTE(0)", (byte)0); AssertEvaluatesTo("TO_BYTE(255)", (byte)255); } [Fact] public void BuiltInFunctions_ToChar() { AssertEvaluatesTo("TO_CHAR(32)", ' '); AssertEvaluatesTo("TO_CHAR(' ')", ' '); } [Fact] public void BuiltInFunctions_ToDateTime() { AssertEvaluatesTo("TO_DATETIME('2015-12-31')", new DateTime(2015, 12, 31)); } [Fact] public void BuiltInFunctions_ToDecimal() { AssertEvaluatesTo("TO_DECIMAL(-123.456)", -123.456m); AssertEvaluatesTo("TO_DECIMAL(0)", 0m); AssertEvaluatesTo("TO_DECIMAL(123.456)", 123.456m); AssertEvaluatesTo("TO_DECIMAL('-123.456')", -123.456m); AssertEvaluatesTo("TO_DECIMAL('0')", 0m); AssertEvaluatesTo("TO_DECIMAL('123.456')", 123.456m); } [Fact] public void BuiltInFunctions_ToDouble() { AssertEvaluatesTo("TO_DOUBLE(0)", 0d); AssertEvaluatesTo("TO_DOUBLE(123e4)", 123e4d); AssertEvaluatesTo("TO_DOUBLE(123e-4)", 123e-4d); AssertEvaluatesTo("TO_DOUBLE('0')", 0d); AssertEvaluatesTo("TO_DOUBLE('123e4')", 123e4d); AssertEvaluatesTo("TO_DOUBLE('123e-4')", 123e-4d); } [Fact] public void BuiltInFunctions_ToInt16() { AssertEvaluatesTo("TO_INT16(-32000)", (short)-32000); AssertEvaluatesTo("TO_INT16(0)", (short)0); AssertEvaluatesTo("TO_INT16(32000)", (short)32000); AssertEvaluatesTo("TO_INT16('-32000')", (short)-32000); AssertEvaluatesTo("TO_INT16('0')", (short)0); AssertEvaluatesTo("TO_INT16('32000')", (short)32000); } [Fact] public void BuiltInFunctions_ToInt32() { AssertEvaluatesTo("TO_INT32(-123456789)", -123456789); AssertEvaluatesTo("TO_INT32(0)", 0); AssertEvaluatesTo("TO_INT32(123456789)", 123456789); AssertEvaluatesTo("TO_INT32('-123456789')", -123456789); AssertEvaluatesTo("TO_INT32('0')", 0); AssertEvaluatesTo("TO_INT32('123456789')", 123456789); } [Fact] public void BuiltInFunctions_ToInt64() { AssertEvaluatesTo("TO_INT64(-12345678912)", -12345678912); AssertEvaluatesTo("TO_INT64(0)", (long)0); AssertEvaluatesTo("TO_INT64(12345678912)", 12345678912); AssertEvaluatesTo("TO_INT64('-12345678912')", -12345678912); AssertEvaluatesTo("TO_INT64('0')", (long)0); AssertEvaluatesTo("TO_INT64('12345678912')", 12345678912); } [Fact] public void BuiltInFunctions_ToSbyte() { AssertEvaluatesTo("TO_SBYTE(-127)", (sbyte)-127); AssertEvaluatesTo("TO_SBYTE(0)", (sbyte)0); AssertEvaluatesTo("TO_SBYTE(127)", (sbyte)127); AssertEvaluatesTo("TO_SBYTE('-127')", (sbyte)-127); AssertEvaluatesTo("TO_SBYTE('0')", (sbyte)0); AssertEvaluatesTo("TO_SBYTE('127')", (sbyte)127); } [Fact] public void BuiltInFunctions_ToSingle() { AssertEvaluatesTo("TO_SINGLE(0)", 0f); AssertEvaluatesTo("TO_SINGLE(123e4)", 123e4f); AssertEvaluatesTo("TO_SINGLE(123e-4)", 123e-4f); AssertEvaluatesTo("TO_SINGLE('0')", 0f); AssertEvaluatesTo("TO_SINGLE('123e4')", 123e4f); AssertEvaluatesTo("TO_SINGLE('123e-4')", 123e-4f); } [Fact] public void BuiltInFunctions_ToString() { AssertEvaluatesTo("TO_STRING(0)", "0"); AssertEvaluatesTo("TO_STRING(1)", "1"); AssertEvaluatesTo("TO_STRING(FALSE)", "False"); AssertEvaluatesTo("TO_STRING(TRUE)", "True"); } [Fact] public void BuiltInFunctions_ToUInt16() { AssertEvaluatesTo("TO_UINT16(0)", (ushort)0); AssertEvaluatesTo("TO_UINT16(65000)", (ushort)65000); AssertEvaluatesTo("TO_UINT16('0')", (ushort)0); AssertEvaluatesTo("TO_UINT16('65000')", (ushort)65000); } [Fact] public void BuiltInFunctions_ToUInt32() { AssertEvaluatesTo("TO_UINT32(0)", (uint)0); AssertEvaluatesTo("TO_UINT32(4123456789)", 4123456789); AssertEvaluatesTo("TO_UINT32('0')", (uint)0); AssertEvaluatesTo("TO_UINT32('4123456789')", 4123456789); } [Fact] public void BuiltInFunctions_ToUInt64() { AssertEvaluatesTo("TO_UINT64(0)", (ulong)0); AssertEvaluatesTo("TO_UINT64(123456789)", (ulong)123456789); AssertEvaluatesTo("TO_UINT64('0')", (ulong)0); AssertEvaluatesTo("TO_UINT64('9999999999123456789')", 9999999999123456789); } [Fact] public void BuiltInFunctions_Trim() { AssertEvaluatesTo("TRIM(' test ')", "test"); } [Fact] public void BuiltInFunctions_Upper() { AssertEvaluatesTo("UPPER('Hello')", "HELLO"); } [Fact] public void BuiltInFunctions_Year() { AssertEvaluatesTo("YEAR(TO_DATETIME('2010-1-1'))", 2010); AssertEvaluatesTo("YEAR(TO_DATETIME('2011-3-2'))", 2011); AssertEvaluatesTo("YEAR(TO_DATETIME('2012-12-31'))", 2012); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public class SqlBulkCopyTest { private string srcConstr = null; private string dstConstr = null; private static bool IsAzureServer() => DataTestUtility.IsAzureSqlServer(new SqlConnectionStringBuilder((DataTestUtility.TcpConnStr)).DataSource); private static bool AreConnectionStringsSetup() => DataTestUtility.AreConnStringsSetup(); public SqlBulkCopyTest() { srcConstr = DataTestUtility.TcpConnStr; dstConstr = (new SqlConnectionStringBuilder(srcConstr) { InitialCatalog = "tempdb" }).ConnectionString; } public string AddGuid(string stringin) { stringin += "_" + Guid.NewGuid().ToString().Replace('-', '_'); return stringin; } [ConditionalFact(nameof(AreConnectionStringsSetup), nameof(IsAzureServer))] public void AzureDistributedTransactionTest() { AzureDistributedTransaction.Test(); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopyAllFromReaderTest() { CopyAllFromReader.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyAllFromReader")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopyAllFromReader1Test() { CopyAllFromReader1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyAllFromReader1")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopyMultipleReadersTest() { CopyMultipleReaders.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyMultipleReaders")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopySomeFromReaderTest() { CopySomeFromReader.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromReader")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopySomeFromDataTableTest() { CopySomeFromDataTable.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromDataTable")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopySomeFromRowArrayTest() { CopySomeFromRowArray.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromRowArray")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopyWithEventTest() { CopyWithEvent.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyWithEvent")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopyWithEvent1Test() { CopyWithEvent1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyWithEvent1")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void InvalidAccessFromEventTest() { InvalidAccessFromEvent.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_InvalidAccessFromEvent")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void Bug84548Test() { Bug84548.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Bug84548")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void MissingTargetTableTest() { MissingTargetTable.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_MissingTargetTable")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void MissingTargetColumnTest() { MissingTargetColumn.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_MissingTargetColumn")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void Bug85007Test() { Bug85007.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Bug85007")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CheckConstraintsTest() { CheckConstraints.Test(dstConstr, AddGuid("SqlBulkCopyTest_Extensionsrc"), AddGuid("SqlBulkCopyTest_Extensiondst")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void TransactionTest() { Transaction.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction0")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void Transaction1Test() { Transaction1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction1")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void Transaction2Test() { Transaction2.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction2")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void Transaction3Test() { Transaction3.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction3")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void Transaction4Test() { Transaction4.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction4")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopyVariantsTest() { CopyVariants.Test(dstConstr, AddGuid("SqlBulkCopyTest_Variants")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void Bug98182Test() { Bug98182.Test(dstConstr, AddGuid("SqlBulkCopyTest_Bug98182 ")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void FireTriggerTest() { FireTrigger.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_FireTrigger")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void ErrorOnRowsMarkedAsDeletedTest() { ErrorOnRowsMarkedAsDeleted.Test(dstConstr, AddGuid("SqlBulkCopyTest_ErrorOnRowsMarkedAsDeleted")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void SpecialCharacterNamesTest() { SpecialCharacterNames.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_SpecialCharacterNames")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void Bug903514Test() { Bug903514.Test(dstConstr, AddGuid("SqlBulkCopyTest_Bug903514")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void ColumnCollationTest() { ColumnCollation.Test(dstConstr, AddGuid("SqlBulkCopyTest_ColumnCollation")); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopyAllFromReaderAsyncTest() { CopyAllFromReaderAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest1")); //Async + Reader } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopySomeFromRowArrayAsyncTest() { CopySomeFromRowArrayAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest2")); //Async + Some Rows } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopySomeFromDataTableAsyncTest() { CopySomeFromDataTableAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest3")); //Async + Some Table } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopyWithEventAsyncTest() { CopyWithEventAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest4")); //Async + Rows + Notification } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopyAllFromReaderCancelAsyncTest() { CopyAllFromReaderCancelAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest5")); //Async + Reader + cancellation token } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopyAllFromReaderConnectionClosedAsyncTest() { CopyAllFromReaderConnectionClosedAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest6")); //Async + Reader + Connection closed } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void CopyAllFromReaderConnectionClosedOnEventAsyncTest() { CopyAllFromReaderConnectionClosedOnEventAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest7")); //Async + Reader + Connection closed during the event } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public void TransactionTestAsyncTest() { TransactionTestAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_TransactionTestAsync")); //Async + Transaction rollback } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans; using Orleans.CodeGenerator; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Compatibility; using Orleans.Runtime; using Orleans.Utilities; using Xunit; using Xunit.Abstractions; using Orleans.CodeGenerator.Model; using System.Text; using Orleans.Serialization; namespace CodeGenerator.Tests { /// <summary> /// Tests for <see cref="RoslynTypeNameFormatter"/>. /// </summary> [Trait("Category", "BVT")] public class RoslynTypeNameFormatterTests { private readonly ITestOutputHelper output; private static readonly Type[] Types = { typeof(int), typeof(int[]), typeof(int**[]), typeof(List<>), typeof(Dictionary<string, Dictionary<int, bool>>), typeof(Dictionary<,>), typeof(List<int>), typeof(List<int*[]>), typeof(List<int*[]>.Enumerator), typeof(List<>.Enumerator), typeof(Generic<>), typeof(Generic<>.Nested), typeof(Generic<>.NestedGeneric<>), typeof(Generic<>.NestedMultiGeneric<,>), typeof(Generic<int>.Nested), typeof(Generic<int>.NestedGeneric<bool>), typeof(Generic<int>.NestedMultiGeneric<Generic<int>.NestedGeneric<bool>, double>) }; private static readonly Type[] Grains = { typeof(IMyGenericGrainInterface2<>), typeof(IMyGenericGrainInterface2<int>), typeof(IMyGrainInterface), typeof(IMyGenericGrainInterface<int>), typeof(IMyGrainInterfaceWithTypeCodeOverride), typeof(MyGrainClass), typeof(MyGenericGrainClass<int>), typeof(MyGrainClassWithTypeCodeOverride), typeof(NotNested.IMyGrainInterface), typeof(NotNested.IMyGenericGrainInterface<int>), typeof(NotNested.MyGrainClass), typeof(NotNested.MyGenericGrainClass<int>), typeof(NotNested.IMyGenericGrainInterface<>), typeof(NotNested.MyGenericGrainClass<>), }; private readonly CSharpCompilation compilation; public RoslynTypeNameFormatterTests(ITestOutputHelper output) { this.output = output; // Read the source code of this file and parse that with Roslyn. var testCode = GetSource(); var metas = new[] { typeof(int).Assembly, typeof(IGrain).Assembly, typeof(Attribute).Assembly, typeof(System.Net.IPAddress).Assembly, typeof(ExcludeFromCodeCoverageAttribute).Assembly, }.Select(a => MetadataReference.CreateFromFile(a.Location, MetadataReferenceProperties.Assembly)); var metadataReferences = metas.Concat(GetGlobalReferences()).ToArray(); var syntaxTrees = new[] { CSharpSyntaxTree.ParseText(testCode, path: "TestProgram.cs") }; var assemblyName = typeof(RoslynTypeNameFormatterTests).Assembly.GetName().Name; var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithMetadataImportOptions(MetadataImportOptions.All); this.compilation = CSharpCompilation.Create(assemblyName, syntaxTrees, metadataReferences, options); IEnumerable<MetadataReference> GetGlobalReferences() { // The location of the .NET assemblies var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); return new List<MetadataReference> { MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "netstandard.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")) }; } } private string GetSource() { var type = typeof(RoslynTypeNameFormatterTests); using (var stream = type.Assembly.GetManifestResourceStream($"{type.Namespace}.{type.Name}.cs")) using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } /// <summary> /// Tests that various strings formatted with <see cref="RoslynTypeNameFormatter"/> match their corresponding <see cref="Type.FullName"/> values. /// </summary> [Fact] public void FullNameMatchesClr() { foreach (var (type, symbol) in GetTypeSymbolPairs(nameof(Types))) { this.output.WriteLine($"Type: {RuntimeTypeNameFormatter.Format(type)}"); var expected = type.FullName; var actual = RoslynTypeNameFormatter.Format(symbol, RoslynTypeNameFormatter.Style.FullName); this.output.WriteLine($"Expected FullName: {expected}\nActual FullName: {actual}"); Assert.Equal(expected, actual); } } [Fact] public void TypeKeyMatchesRuntimeTypeKey() { foreach (var (type, symbol) in GetTypeSymbolPairs(nameof(Types))) { var expectedTypeKey = TypeUtilities.OrleansTypeKeyString(type); var actualTypeKey = OrleansLegacyCompat.OrleansTypeKeyString(symbol); this.output.WriteLine($"Type: {RuntimeTypeNameFormatter.Format(type)}"); Assert.Equal(expectedTypeKey, actualTypeKey); } } /// <summary> /// Tests that the ITypeSymbol id generation algorithm generates ids which match the Type-based generator. /// </summary> [Fact] public void TypeCodesMatch() { var wellKnownTypes = WellKnownTypes.FromCompilation(this.compilation); foreach (var (type, symbol) in GetTypeSymbolPairs(nameof(Grains))) { this.output.WriteLine($"Type: {RuntimeTypeNameFormatter.Format(type)}"); { // First check Type.FullName matches. var expected = type.FullName; var actual = RoslynTypeNameFormatter.Format(symbol, RoslynTypeNameFormatter.Style.FullName); this.output.WriteLine($"Expected FullName: {expected}\nActual FullName: {actual}"); Assert.Equal(expected, actual); } { var expected = TypeUtils.GetTemplatedName( TypeUtils.GetFullName(type), type, type.GetGenericArguments(), t => false); var named = Assert.IsAssignableFrom<INamedTypeSymbol>(symbol); var actual = OrleansLegacyCompat.FormatTypeForIdComputation(named); this.output.WriteLine($"Expected format: {expected}\nActual format: {actual}"); Assert.Equal(expected, actual); } { var expected = GrainInterfaceUtils.GetGrainInterfaceId(type); var named = Assert.IsAssignableFrom<INamedTypeSymbol>(symbol); var actual = wellKnownTypes.GetTypeId(named); this.output.WriteLine($"Expected Id: 0x{expected:X}\nActual Id: 0x{actual:X}"); Assert.Equal(expected, actual); } } } /// <summary> /// Tests that the IMethodSymbol id generation algorithm generates ids which match the MethodInfo-based generator. /// </summary> [Fact] public void MethodIdsMatch() { var wellKnownTypes = WellKnownTypes.FromCompilation(this.compilation); foreach (var (type, typeSymbol) in GetTypeSymbolPairs(nameof(Grains))) { this.output.WriteLine($"Type: {RuntimeTypeNameFormatter.Format(type)}"); var methods = type.GetMethods(); var methodSymbols = methods.Select(m => typeSymbol.GetMembers(m.Name).SingleOrDefault()).OfType<IMethodSymbol>(); foreach (var (method, methodSymbol) in methods.Zip(methodSymbols, ValueTuple.Create)) { this.output.WriteLine($"IMethodSymbol: {methodSymbol}, MethodInfo: {method}"); Assert.NotNull(methodSymbol); { var expected = GrainInterfaceUtils.FormatMethodForIdComputation(method); var actual = OrleansLegacyCompat.FormatMethodForMethodIdComputation(methodSymbol); this.output.WriteLine($"Expected format: {expected}\nActual format: {actual}"); Assert.Equal(expected, actual); } { var expected = GrainInterfaceUtils.ComputeMethodId(method); var actual = wellKnownTypes.GetMethodId(methodSymbol); this.output.WriteLine($"Expected Id: 0x{expected:X}\nActual Id: 0x{actual:X}"); Assert.Equal(expected, actual); } } } } private IEnumerable<(Type, ITypeSymbol)> GetTypeSymbolPairs(string fieldName) { var typesMember = compilation.Assembly.GlobalNamespace .GetMembers("CodeGenerator") .First() .GetMembers("Tests") .Cast<INamespaceOrTypeSymbol>() .First() .GetTypeMembers("RoslynTypeNameFormatterTests") .First() .GetMembers(fieldName) .First(); var declaratorSyntax = Assert.IsType<VariableDeclaratorSyntax>(typesMember.DeclaringSyntaxReferences.First().GetSyntax()); var creationExpressionSyntax = Assert.IsType<InitializerExpressionSyntax>(declaratorSyntax.Initializer.Value); var expressions = creationExpressionSyntax.Expressions; var typeSymbols = new List<ITypeSymbol>(); var model = compilation.GetSemanticModel(declaratorSyntax.SyntaxTree); foreach (var expr in expressions.ToList().OfType<TypeOfExpressionSyntax>()) { var info = model.GetTypeInfo(expr.Type); Assert.NotNull(info.Type); typeSymbols.Add(info.Type); } var types = (Type[])this.GetType().GetField(fieldName, BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); var pairs = types.Zip(typeSymbols, ValueTuple.Create); return pairs; } public interface IMyGrainInterface : IGrainWithGuidKey { Task One(int a, int b, int c); Task<int> Two(); } public class MyGrainClass : Grain, IMyGrainInterface { public Task One(int a, int b, int c) => throw new NotImplementedException(); public Task<int> Two() => throw new NotImplementedException(); } public interface IMyGenericGrainInterface<T> : IGrainWithGuidKey { Task One(T a, int b, int c); Task<T> Two(); } public interface IMyGenericGrainInterface2<in T> : IGrainWithGuidKey { Task One(T a, int b, int c); } public class MyGenericGrainClass<T> : Grain, IMyGenericGrainInterface<T> { public Task One(T a, int b, int c) => throw new NotImplementedException(); public Task<T> Two() => throw new NotImplementedException(); } [TypeCodeOverride(1)] public interface IMyGrainInterfaceWithTypeCodeOverride : IGrainWithGuidKey { [MethodId(1)] Task One(int a, int b, int c); [MethodId(2)] Task<int> Two(); } [TypeCodeOverride(2)] public class MyGrainClassWithTypeCodeOverride : Grain, IMyGrainInterfaceWithTypeCodeOverride { [MethodId(12234)] public Task One(int a, int b, int c) => throw new NotImplementedException(); [MethodId(-41243)] public Task<int> Two() => throw new NotImplementedException(); } } namespace NotNested { public interface IMyGrainInterface : IGrainWithGuidKey { Task One(int a, int b, int c); Task<int> Two(); } public class MyGrainClass : Grain, IMyGrainInterface { public Task One(int a, int b, int c) => throw new NotImplementedException(); public Task<int> Two() => throw new NotImplementedException(); } public interface IMyGenericGrainInterface<T> : IGrainWithGuidKey { Task One(T a, int b, int c); Task<T> Two(); Task<TU> Three<TU>(); } public class MyGenericGrainClass<T> : Grain, IMyGenericGrainInterface<T> { public Task One(T a, int b, int c) => throw new NotImplementedException(); public Task<T> Two() => throw new NotImplementedException(); public Task<TU> Three<TU>() => throw new NotImplementedException(); } } } namespace System { public class Generic<T> { public class Nested { } public class NestedGeneric<TU> { } public class NestedMultiGeneric<TU, TV> { } } }
using System; using TestLibrary; /// <summary> /// SByte.ToString(String) /// </summary> public class SByteToString3 { public static int Main() { SByteToString3 sbyteTS3 = new SByteToString3(); TestLibrary.TestFramework.BeginTestCase("SByteToString3"); if (sbyteTS3.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:The SByte MaxValue ToString 1"); try { sbyte SByteVal = sbyte.MaxValue; string format1 = null; string format2 = string.Empty; string desStr1 = SByteVal.ToString(format1); string desStr2 = SByteVal.ToString(format2); if (desStr1 != GlobLocHelper.OSSByteToString(SByteVal, format1) || desStr2 != GlobLocHelper.OSSByteToString(SByteVal, format2)) { TestLibrary.TestFramework.LogError("001", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:The SByte MaxValue ToString 2"); try { sbyte SByteVal = sbyte.MaxValue; string format = "X"; string desStr = SByteVal.ToString(format); if (desStr != "7F") { TestLibrary.TestFramework.LogError("003", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3:The SByte MaxValue ToString 3"); try { sbyte SByteVal = sbyte.MaxValue; string format = "D"; string desStr = SByteVal.ToString(format); if (desStr != GlobLocHelper.OSSByteToString(SByteVal, format)) { TestLibrary.TestFramework.LogError("005", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4:The SByte MinValue ToString 1"); try { sbyte SByteVal = sbyte.MinValue; string format = "X"; string desStr = SByteVal.ToString(format); if (desStr != "80") { TestLibrary.TestFramework.LogError("007", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5:The SByte MinValue ToString 2"); try { sbyte SByteVal = sbyte.MinValue; string format = "D"; string desStr = SByteVal.ToString(format); if (desStr != GlobLocHelper.OSSByteToString(SByteVal, format)) { TestLibrary.TestFramework.LogError("009", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6:The random SByte ToString 1"); try { sbyte SByteVal = 123; string format = "D"; string desStr = SByteVal.ToString(format); if (desStr != GlobLocHelper.OSSByteToString(SByteVal, format)) { TestLibrary.TestFramework.LogError("011", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7:The random SByte ToString 2"); try { sbyte SByteVal = -99; string format = "X"; string desStr = SByteVal.ToString(format); if (desStr != "9D") { TestLibrary.TestFramework.LogError("013", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1:the format is Invalid"); try { sbyte SByteVal = (sbyte)(this.GetInt32(0, 128) + this.GetInt32(0, 129) * (-1)); string format = "W"; string desStr = SByteVal.ToString(format); TestLibrary.TestFramework.LogError("N001", "the format is Invalid but not throw exception"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region HelpMethod private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Collections; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Serialization { /// <summary> /// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public class JsonArrayContract : JsonContainerContract { /// <summary> /// Gets the <see cref="System.Type"/> of the collection items. /// </summary> /// <value>The <see cref="System.Type"/> of the collection items.</value> public Type CollectionItemType { get; } /// <summary> /// Gets a value indicating whether the collection type is a multidimensional array. /// </summary> /// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value> public bool IsMultidimensionalArray { get; } private readonly Type _genericCollectionDefinitionType; private Type _genericWrapperType; private ObjectConstructor<object> _genericWrapperCreator; private Func<object> _genericTemporaryCollectionCreator; internal bool IsArray { get; } internal bool ShouldCreateWrapper { get; } internal bool CanDeserialize { get; private set; } private readonly ConstructorInfo _parameterizedConstructor; private ObjectConstructor<object> _parameterizedCreator; private ObjectConstructor<object> _overrideCreator; internal ObjectConstructor<object> ParameterizedCreator { get { if (_parameterizedCreator == null) { _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); } return _parameterizedCreator; } } /// <summary> /// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>. /// </summary> /// <value>The function used to create the object.</value> public ObjectConstructor<object> OverrideCreator { get => _overrideCreator; set { _overrideCreator = value; // hacky CanDeserialize = true; } } /// <summary> /// Gets a value indicating whether the creator has a parameter with the collection values. /// </summary> /// <value><c>true</c> if the creator has a parameter with the collection values; otherwise, <c>false</c>.</value> public bool HasParameterizedCreator { get; set; } internal bool HasParameterizedCreatorInternal => (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); /// <summary> /// Initializes a new instance of the <see cref="JsonArrayContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonArrayContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Array; IsArray = CreatedType.IsArray; bool canDeserialize; Type tempCollectionType; if (IsArray) { CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); IsReadOnlyOrFixedSize = true; _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); canDeserialize = true; IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1); } else if (typeof(IList).IsAssignableFrom(NonNullableUnderlyingType)) { if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; } else { CollectionItemType = ReflectionUtils.GetCollectionItemType(NonNullableUnderlyingType); } if (NonNullableUnderlyingType == typeof(IList)) { CreatedType = typeof(List<object>); } if (CollectionItemType != null) { _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(NonNullableUnderlyingType, CollectionItemType); } IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(NonNullableUnderlyingType, typeof(ReadOnlyCollection<>)); canDeserialize = true; } else if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(ICollection<>)) || ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IList<>))) { CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); } #if HAVE_ISET if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(ISet<>))) { CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType); } #endif _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(NonNullableUnderlyingType, CollectionItemType); canDeserialize = true; ShouldCreateWrapper = true; } #if HAVE_READ_ONLY_COLLECTIONS else if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyCollection<>)) || ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyList<>))) { CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType); } _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType); #if HAVE_FSHARP_TYPES StoreFSharpListCreatorIfNecessary(NonNullableUnderlyingType); #endif IsReadOnlyOrFixedSize = true; canDeserialize = HasParameterizedCreatorInternal; } #endif else if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(IEnumerable<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>))) { CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); } _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(NonNullableUnderlyingType, CollectionItemType); #if HAVE_FSHARP_TYPES StoreFSharpListCreatorIfNecessary(NonNullableUnderlyingType); #endif if (NonNullableUnderlyingType.IsGenericType() && NonNullableUnderlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { _genericCollectionDefinitionType = tempCollectionType; IsReadOnlyOrFixedSize = false; ShouldCreateWrapper = false; canDeserialize = true; } else { _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); IsReadOnlyOrFixedSize = true; ShouldCreateWrapper = true; canDeserialize = HasParameterizedCreatorInternal; } } else { // types that implement IEnumerable and nothing else canDeserialize = false; ShouldCreateWrapper = true; } CanDeserialize = canDeserialize; #if (NET20 || NET35) if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType)) { // bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object) // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType) || (IsArray && !IsMultidimensionalArray)) { ShouldCreateWrapper = true; } } #endif if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract( NonNullableUnderlyingType, CollectionItemType, out Type immutableCreatedType, out ObjectConstructor<object> immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; CanDeserialize = true; } } internal IWrappedCollection CreateWrapper(object list) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType); Type constructorArgument; if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>)) || _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType); } else { constructorArgument = _genericCollectionDefinitionType; } ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } return (IWrappedCollection)_genericWrapperCreator(list); } internal IList CreateTemporaryCollection() { if (_genericTemporaryCollectionCreator == null) { // multidimensional array will also have array instances in it Type collectionItemType = (IsMultidimensionalArray || CollectionItemType == null) ? typeof(object) : CollectionItemType; Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType); _genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType); } return (IList)_genericTemporaryCollectionCreator(); } #if HAVE_FSHARP_TYPES private void StoreFSharpListCreatorIfNecessary(Type underlyingType) { if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parameterizedCreator = FSharpUtils.CreateSeq(CollectionItemType); } } #endif } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Emit; using Chutzpah.Models; using Chutzpah.Wrappers; namespace Chutzpah { public interface IChutzpahTestSettingsService { /// <summary> /// Find and reads a chutzpah test settings file given a directory. If none is found a default settings object is created /// </summary> /// <param name="directory"></param> /// <returns></returns> ChutzpahTestSettingsFile FindSettingsFileFromDirectory(string directory, ChutzpahSettingsFileEnvironments environments = null); /// <summary> /// Find and reads a chutzpah test settings file given a path to a the file. If none is found a default settings object is created /// </summary> /// <param name="filePath"></param> /// <returns></returns> ChutzpahTestSettingsFile FindSettingsFile(string filePath, ChutzpahSettingsFileEnvironments environments = null); void ClearCache(); } public class ChutzpahTestSettingsService : IChutzpahTestSettingsService { /// <summary> /// Cache settings file /// </summary> private readonly ConcurrentDictionary<string, ChutzpahTestSettingsFile> ChutzpahSettingsFileCache = new ConcurrentDictionary<string, ChutzpahTestSettingsFile>(StringComparer.OrdinalIgnoreCase); private readonly IFileProbe fileProbe; private readonly IJsonSerializer serializer; private readonly IFileSystemWrapper fileSystem; public ChutzpahTestSettingsService(IFileProbe fileProbe, IJsonSerializer serializer, IFileSystemWrapper fileSystem) { this.fileProbe = fileProbe; this.serializer = serializer; this.fileSystem = fileSystem; } public ChutzpahTestSettingsFile FindSettingsFile(string filePath, ChutzpahSettingsFileEnvironments environments = null) { if (string.IsNullOrEmpty(filePath)) return ChutzpahTestSettingsFile.Default; var directory = Path.GetDirectoryName(filePath); return FindSettingsFileFromDirectory(directory, environments); } /// <summary> /// Find and reads a chutzpah test settings file given a directory. If none is found a default settings object is created /// </summary> /// <param name="directory"></param> /// <returns></returns> /// public ChutzpahTestSettingsFile FindSettingsFileFromDirectory(string directory, ChutzpahSettingsFileEnvironments environments = null) { if (string.IsNullOrEmpty(directory)) return ChutzpahTestSettingsFile.Default; directory = directory.TrimEnd('/', '\\'); ChutzpahTestSettingsFile settings; if (!ChutzpahSettingsFileCache.TryGetValue(directory, out settings)) { ChutzpahSettingsFileEnvironment environment = null; if (environments != null) { environment = environments.GetSettingsFileEnvironment(directory); } return ProcessSettingsFile(directory, environment).InheritFromDefault(); } else { return settings; } } private ChutzpahTestSettingsFile ProcessSettingsFile(string directory, ChutzpahSettingsFileEnvironment environment, bool forceFresh = false) { if (string.IsNullOrEmpty(directory)) return ChutzpahTestSettingsFile.Default; directory = directory.TrimEnd('/', '\\'); ChutzpahTestSettingsFile settings; if (!ChutzpahSettingsFileCache.TryGetValue(directory, out settings) || forceFresh) { var testSettingsFilePath = fileProbe.FindTestSettingsFile(directory); if (string.IsNullOrEmpty(testSettingsFilePath)) { ChutzpahTracer.TraceInformation("Chutzpah.json file not found given starting directory {0}", directory); settings = ChutzpahTestSettingsFile.Default; } else if (!ChutzpahSettingsFileCache.TryGetValue(Path.GetDirectoryName(testSettingsFilePath), out settings) || forceFresh) { ChutzpahTracer.TraceInformation("Chutzpah.json file found at {0} given starting directory {1}", testSettingsFilePath, directory); settings = serializer.DeserializeFromFile<ChutzpahTestSettingsFile>(testSettingsFilePath); if (settings == null) { settings = ChutzpahTestSettingsFile.Default; } else { settings.IsDefaultSettings = false; } settings.SettingsFileDirectory = Path.GetDirectoryName(testSettingsFilePath); var chutzpahVariables = BuildChutzpahReplacementVariables(testSettingsFilePath, environment, settings); ResolveTestHarnessDirectory(settings, chutzpahVariables); ResolveAMDBaseUrl(settings, chutzpahVariables); ResolveBatchCompileConfiguration(settings, chutzpahVariables); ProcessPathSettings(settings, chutzpahVariables); ProcessTraceFilePath(settings, chutzpahVariables); ProcessServerSettings(settings, chutzpahVariables); ProcessInheritance(environment, settings, chutzpahVariables); if (!forceFresh) { // Add a mapping in the cache for the directory that contains the test settings file ChutzpahSettingsFileCache.TryAdd(settings.SettingsFileDirectory, settings); } } if (!forceFresh) { // Add mapping in the cache for the original directory tried to skip needing to traverse the tree again ChutzpahSettingsFileCache.TryAdd(directory, settings); } } return settings; } private void ProcessServerSettings(ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables) { if (settings.Server != null) { settings.Server.FileCachingEnabled = settings.Server.FileCachingEnabled ?? true; settings.Server.DefaultPort = settings.Server.DefaultPort ?? Constants.DefaultWebServerPort; string rootPath = null; if (!string.IsNullOrEmpty(settings.Server.RootPath)) { rootPath = settings.Server.RootPath; } else { ChutzpahTracer.TraceInformation("Defaulting the RootPath to the drive root of the chutzpah.json file"); rootPath = Path.GetPathRoot(settings.SettingsFileDirectory); } settings.Server.RootPath = ResolveFolderPath(settings, ExpandVariable(chutzpahVariables, rootPath)); } } private void ProcessTraceFilePath(ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables) { if (!string.IsNullOrEmpty(settings.TraceFilePath)) { var path = Path.Combine(settings.SettingsFileDirectory, ExpandVariable(chutzpahVariables, settings.TraceFilePath)); settings.TraceFilePath = path; } } private void ProcessInheritance(ChutzpahSettingsFileEnvironment environment, ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables) { if (settings.InheritFromParent || !string.IsNullOrEmpty(settings.InheritFromPath)) { if (string.IsNullOrEmpty(settings.InheritFromPath)) { ChutzpahTracer.TraceInformation("Searching for parent Chutzpah.json to inherit from"); settings.InheritFromPath = Path.GetDirectoryName(settings.SettingsFileDirectory); } else { ChutzpahTracer.TraceInformation("Searching for Chutzpah.json to inherit from at {0}", settings.InheritFromPath); string settingsToInherit = ExpandVariable(chutzpahVariables, settings.InheritFromPath); if (settingsToInherit.EndsWith(Constants.SettingsFileName, StringComparison.OrdinalIgnoreCase)) { settingsToInherit = Path.GetDirectoryName(settingsToInherit); } settingsToInherit = ResolveFolderPath(settings, settingsToInherit); settings.InheritFromPath = settingsToInherit; } // If we have any environment properties do not use cached // parents and re-evaluate using current environment var forceFresh = environment != null && environment.Properties.Any(); var parentSettingsFile = ProcessSettingsFile(settings.InheritFromPath, environment, forceFresh); if (!parentSettingsFile.IsDefaultSettings) { ChutzpahTracer.TraceInformation("Found parent Chutzpah.json in directory {0}", parentSettingsFile.SettingsFileDirectory); settings.InheritFrom(parentSettingsFile); } else { ChutzpahTracer.TraceInformation("Could not find a parent Chutzpah.json"); } } } public void ClearCache() { ChutzpahTracer.TraceInformation("Chutzpah.json file cache cleared"); ChutzpahSettingsFileCache.Clear(); } private void ResolveTestHarnessDirectory(ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables) { if (settings.TestHarnessLocationMode == TestHarnessLocationMode.Custom) { if (settings.TestHarnessDirectory != null) { string absoluteFilePath = ResolveFolderPath(settings, ExpandVariable(chutzpahVariables, settings.TestHarnessDirectory)); settings.TestHarnessDirectory = absoluteFilePath; } if (settings.TestHarnessDirectory == null) { settings.TestHarnessLocationMode = TestHarnessLocationMode.TestFileAdjacent; ChutzpahTracer.TraceWarning("Unable to find custom test harness directory at {0}", settings.TestHarnessDirectory); } } } private void ResolveAMDBaseUrl(ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables) { if (!string.IsNullOrEmpty(settings.AMDBaseUrl)) { string absoluteFilePath = ResolveFolderPath(settings, ExpandVariable(chutzpahVariables, settings.AMDBaseUrl)); settings.AMDBaseUrl = absoluteFilePath; if (string.IsNullOrEmpty(settings.AMDBaseUrl)) { ChutzpahTracer.TraceWarning("Unable to find AMDBaseUrl at {0}", settings.AMDBaseUrl); } } if (!string.IsNullOrEmpty(settings.AMDAppDirectory)) { string absoluteFilePath = ResolveFolderPath(settings, ExpandVariable(chutzpahVariables, settings.AMDAppDirectory)); settings.AMDAppDirectory = absoluteFilePath; if (string.IsNullOrEmpty(settings.AMDAppDirectory)) { ChutzpahTracer.TraceWarning("Unable to find AMDAppDirectory at {0}", settings.AMDAppDirectory); } } // Legacy AMDBasePath property if (!string.IsNullOrEmpty(settings.AMDBasePath)) { string absoluteFilePath = ResolveFolderPath(settings, ExpandVariable(chutzpahVariables, settings.AMDBasePath)); settings.AMDBasePath = absoluteFilePath; if (string.IsNullOrEmpty(settings.AMDBasePath)) { ChutzpahTracer.TraceWarning("Unable to find AMDBasePath at {0}", settings.AMDBasePath); } } } private void ProcessPathSettings(ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables) { var i = 0; foreach (var test in settings.Tests) { test.SettingsFileDirectory = settings.SettingsFileDirectory; test.Path = ExpandVariable(chutzpahVariables, test.Path); for (i = 0; i < test.Includes.Count; i++) { test.Includes[i] = ExpandVariable(chutzpahVariables, test.Includes[i]); } for (i = 0; i < test.Excludes.Count; i++) { test.Excludes[i] = ExpandVariable(chutzpahVariables, test.Excludes[i]); } } foreach (var reference in settings.References) { reference.SettingsFileDirectory = settings.SettingsFileDirectory; reference.Path = ExpandVariable(chutzpahVariables, reference.Path); for (i = 0; i < reference.Includes.Count; i++) { reference.Includes[i] = ExpandVariable(chutzpahVariables, reference.Includes[i]); } for (i = 0; i < reference.Excludes.Count; i++) { reference.Excludes[i] = ExpandVariable(chutzpahVariables, reference.Excludes[i]); } } foreach (var transform in settings.Transforms) { transform.SettingsFileDirectory = settings.SettingsFileDirectory; transform.Path = ExpandVariable(chutzpahVariables, transform.Path); } } private void ResolveBatchCompileConfiguration(ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables) { if (settings.Compile != null) { settings.Compile.SettingsFileDirectory = settings.SettingsFileDirectory; settings.Compile.Extensions = settings.Compile.Extensions ?? new List<string>(); // If the mode is executable then set its properties if (settings.Compile.Mode == BatchCompileMode.Executable || (settings.Compile.Mode == null && !string.IsNullOrEmpty(settings.Compile.Executable))) { if (string.IsNullOrEmpty(settings.Compile.Executable)) { throw new ArgumentException("Executable path must be passed for compile setting"); } settings.Compile.Mode = BatchCompileMode.Executable; settings.Compile.Executable = ResolveFilePath(settings, ExpandVariable(chutzpahVariables, settings.Compile.Executable)); settings.Compile.Arguments = ExpandVariable(chutzpahVariables, settings.Compile.Arguments); settings.Compile.WorkingDirectory = ResolveFolderPath(settings, settings.Compile.WorkingDirectory); // Default timeout to 5 minutes if missing settings.Compile.Timeout = settings.Compile.Timeout.HasValue ? settings.Compile.Timeout.Value : 1000 * 60 * 5; } else { settings.Compile.Mode = BatchCompileMode.External; } // If Paths are not given if (!settings.Compile.Paths.Any()) { // If not Paths are given handle backcompat and look at sourcedirectory and outdirectory. // This will also handle the empty case in general since it will set empty values which will get resolved to the Chutzpah Settings file directory settings.Compile.Paths.Add(new CompilePathMap { SourcePath = settings.Compile.SourceDirectory, OutputPath = settings.Compile.OutDirectory }); } foreach (var pathMap in settings.Compile.Paths) { ResolveCompilePathMap(settings, chutzpahVariables, pathMap); } } } private void ResolveCompilePathMap(ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables, CompilePathMap pathMap) { var sourcePath = pathMap.SourcePath; bool? sourcePathIsFile = false; // If SourcePath is null then we will assume later on this is the current settings directory pathMap.SourcePath = ResolvePath(settings, sourcePath, out sourcePathIsFile); if (pathMap.SourcePath == null) { throw new FileNotFoundException("Unable to find file/directory specified by SourcePath of {0}", (sourcePath ?? "")); } pathMap.SourcePathIsFile = sourcePathIsFile.HasValue ? sourcePathIsFile.Value : false; // If OutputPath is null then we will assume later on this is the current settings directory // We do not use the resolvePath method here since the path may not exist yet pathMap.OutputPath = UrlBuilder.NormalizeFilePath(Path.Combine(settings.SettingsFileDirectory, ExpandVariable(chutzpahVariables, pathMap.OutputPath))); if (pathMap.OutputPath == null) { throw new FileNotFoundException("Unable to find file/directory specified by OutputPath of {0}", (pathMap.OutputPath ?? "")); } // Since the output path might not exist yet we need a more complicated way to // determine if it is a file or folder // 1. If the user explicitly told us what it should be using OutputPathType use that // 2. Assume it is a file if it has a .js extension if (pathMap.OutputPathType.HasValue) { pathMap.OutputPathIsFile = pathMap.OutputPathType == CompilePathType.File; } else { pathMap.OutputPathIsFile = pathMap.OutputPath.EndsWith(".js", StringComparison.OrdinalIgnoreCase); } } private string ResolvePath(ChutzpahTestSettingsFile settings, string path, out bool? isFile) { isFile = null; var filePath = ResolveFilePath(settings, path); if (filePath == null) { filePath = ResolveFolderPath(settings, path); if (filePath != null) { isFile = false; } } else { isFile = true; } return filePath; } /// <summary> /// Resolved a path relative to the settings file if it is not absolute /// </summary> private string ResolveFolderPath(ChutzpahTestSettingsFile settings, string path) { string relativeLocationPath = Path.Combine(settings.SettingsFileDirectory, path ?? ""); string absoluteFilePath = fileProbe.FindFolderPath(relativeLocationPath); return absoluteFilePath ?? relativeLocationPath; } private string ResolveFilePath(ChutzpahTestSettingsFile settings, string path) { string relativeLocationPath = Path.Combine(settings.SettingsFileDirectory, path ?? ""); string absoluteFilePath = fileProbe.FindFilePath(relativeLocationPath); return absoluteFilePath; } private string ExpandVariable(IDictionary<string, string> chutzpahCompileVariables, string str) { return ExpandChutzpahVariables(chutzpahCompileVariables, Environment.ExpandEnvironmentVariables(str ?? "")); } private string ExpandChutzpahVariables(IDictionary<string, string> chutzpahCompileVariables, string str) { if (str == null) { return null; } return chutzpahCompileVariables.Aggregate(str, (current, pair) => current.Replace(pair.Key, pair.Value)); } private IDictionary<string, string> BuildChutzpahReplacementVariables(string settingsFilePath, ChutzpahSettingsFileEnvironment environment, ChutzpahTestSettingsFile settings) { IDictionary<string, string> chutzpahVariables = new Dictionary<string, string>(); var clrDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); var msbuildExe = Path.Combine(clrDir, "msbuild.exe"); var powershellExe = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"windowspowershell\v1.0\powershell.exe"); AddChutzpahVariable(chutzpahVariables, "chutzpahsettingsdir", settings.SettingsFileDirectory); AddChutzpahVariable(chutzpahVariables, "clrdir", clrDir); AddChutzpahVariable(chutzpahVariables, "msbuildexe", msbuildExe); AddChutzpahVariable(chutzpahVariables, "powershellexe", powershellExe); // This is not needed but it is a nice alias AddChutzpahVariable(chutzpahVariables, "cmdexe", Environment.ExpandEnvironmentVariables("%comspec%")); if (environment != null) { // See if we have a settingsfileenvironment set and if so add its properties as chutzpah settings file variables var props = environment.Properties; foreach (var prop in props) { AddChutzpahVariable(chutzpahVariables, prop.Name, prop.Value); } } return chutzpahVariables; } private void AddChutzpahVariable(IDictionary<string, string> chutzpahCompileVariables, string name, string value) { name = string.Format("%{0}%", name); chutzpahCompileVariables[name] = value; } } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - [email protected]) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.DistributedEmission { /// <summary> /// Enumeration values for EmissionBeamFunction (der.emission.beamfunction, Beam Function, /// section 8.1.4) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public enum EmissionBeamFunction : byte { /// <summary> /// Other. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Other.")] Other = 0, /// <summary> /// Search. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Search.")] Search = 1, /// <summary> /// Height finder. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Height finder.")] HeightFinder = 2, /// <summary> /// Acquisition. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Acquisition.")] Acquisition = 3, /// <summary> /// Tracking. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Tracking.")] Tracking = 4, /// <summary> /// Acquisition and tracking. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Acquisition and tracking.")] AcquisitionAndTracking = 5, /// <summary> /// Command guidance. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Command guidance.")] CommandGuidance = 6, /// <summary> /// Illumination. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Illumination.")] Illumination = 7, /// <summary> /// Range only radar. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Range only radar.")] RangeOnlyRadar = 8, /// <summary> /// Missile beacon. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Missile beacon.")] MissileBeacon = 9, /// <summary> /// Missile fuze. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Missile fuze.")] MissileFuze = 10, /// <summary> /// Active radar missile seeker. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Active radar missile seeker.")] ActiveRadarMissileSeeker = 11, /// <summary> /// Jammer. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Jammer.")] Jammer = 12, /// <summary> /// IFF. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("IFF.")] IFF = 13, /// <summary> /// Navigational / Weather. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Navigational / Weather.")] NavigationalWeather = 14, /// <summary> /// Meteorological. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Meteorological.")] Meteorological = 15, /// <summary> /// Data transmission. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Data transmission.")] DataTransmission = 16, /// <summary> /// Navigational directional beacon. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Navigational directional beacon.")] NavigationalDirectionalBeacon = 17 } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // Pkcs9Attribute.cs // namespace System.Security.Cryptography.Pkcs { using System.Collections; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public class Pkcs9AttributeObject : AsnEncodedData { // // Constructors. // internal Pkcs9AttributeObject (Oid oid) { base.Oid = oid; } public Pkcs9AttributeObject () : base () {} public Pkcs9AttributeObject (string oid, byte[] encodedData) : this(new AsnEncodedData(oid, encodedData)) {} public Pkcs9AttributeObject (Oid oid, byte[] encodedData) : this(new AsnEncodedData(oid, encodedData)) {} public Pkcs9AttributeObject (AsnEncodedData asnEncodedData) : base (asnEncodedData) { if (asnEncodedData.Oid == null) throw new ArgumentNullException("asnEncodedData.Oid"); string szOid = base.Oid.Value; if (szOid == null) throw new ArgumentNullException("oid.Value"); if (szOid.Length == 0) throw new ArgumentException(SecurityResources.GetResourceString("Arg_EmptyOrNullString"), "oid.Value"); } // // Public properties. // public new Oid Oid { get { return base.Oid; } } public override void CopyFrom (AsnEncodedData asnEncodedData) { if (asnEncodedData == null) throw new ArgumentNullException("asnEncodedData"); Pkcs9AttributeObject att = asnEncodedData as Pkcs9AttributeObject; if (att == null) throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_Pkcs9_AttributeMismatch")); base.CopyFrom(asnEncodedData); } } [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class Pkcs9SigningTime : Pkcs9AttributeObject { private DateTime m_signingTime; private bool m_decoded = false; // // Constructors. // public Pkcs9SigningTime() : this(DateTime.Now) {} public Pkcs9SigningTime(DateTime signingTime) : base(CAPI.szOID_RSA_signingTime, Encode(signingTime)) { m_signingTime = signingTime; m_decoded = true; } public Pkcs9SigningTime(byte[] encodedSigningTime) : base(CAPI.szOID_RSA_signingTime, encodedSigningTime) {} // // Public properties. // public DateTime SigningTime { get { if (!m_decoded && (null != RawData)) Decode(); return m_signingTime; } } public override void CopyFrom (AsnEncodedData asnEncodedData) { base.CopyFrom(asnEncodedData); m_decoded = false; } // // Private methods. // [System.Security.SecuritySafeCritical] private void Decode() { uint cbDecoded = 0; SafeLocalAllocHandle pbDecoded = null; if (!CAPI.DecodeObject(new IntPtr(CAPI.PKCS_UTC_TIME), RawData, out pbDecoded, out cbDecoded)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } long signingTime = Marshal.ReadInt64(pbDecoded.DangerousGetHandle()); pbDecoded.Dispose(); m_signingTime = DateTime.FromFileTimeUtc(signingTime); m_decoded = true; } [System.Security.SecuritySafeCritical] private static byte[] Encode (DateTime signingTime) { long ft = signingTime.ToFileTimeUtc(); SafeLocalAllocHandle pbSigningTime = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(Marshal.SizeOf(typeof(Int64)))); Marshal.WriteInt64(pbSigningTime.DangerousGetHandle(), ft); byte[] encodedSigningTime = new byte[0]; if (!CAPI.EncodeObject(CAPI.szOID_RSA_signingTime, pbSigningTime.DangerousGetHandle(), out encodedSigningTime)) throw new CryptographicException(Marshal.GetLastWin32Error()); pbSigningTime.Dispose(); return encodedSigningTime; } } [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class Pkcs9DocumentName : Pkcs9AttributeObject { private string m_documentName = null; private bool m_decoded = false; // // Constructors. // public Pkcs9DocumentName () : base(new Oid(CAPI.szOID_CAPICOM_documentName)) { // CAPI doesn't have an OID mapping for szOID_CAPICOM_documentName, so we cannot use the faster // FromOidValue factory } public Pkcs9DocumentName (string documentName) : base(CAPI.szOID_CAPICOM_documentName, Encode(documentName)) { m_documentName = documentName; m_decoded = true; } public Pkcs9DocumentName (byte[] encodedDocumentName) : base(CAPI.szOID_CAPICOM_documentName, encodedDocumentName) {} // // Public methods. // public string DocumentName { get { if (!m_decoded && (null != RawData)) Decode(); return m_documentName; } } public override void CopyFrom (AsnEncodedData asnEncodedData) { base.CopyFrom(asnEncodedData); m_decoded = false; } // // Private methods. // private void Decode() { m_documentName = PkcsUtils.DecodeOctetString(RawData); m_decoded = true; } private static byte[] Encode (string documentName) { if (String.IsNullOrEmpty(documentName)) throw new ArgumentNullException("documentName"); return PkcsUtils.EncodeOctetString(documentName); } } [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class Pkcs9DocumentDescription : Pkcs9AttributeObject { private string m_documentDescription = null; private bool m_decoded = false; // // Constructors. // public Pkcs9DocumentDescription () : base (new Oid(CAPI.szOID_CAPICOM_documentDescription)) { // CAPI doesn't have an OID mapping for szOID_CAPICOM_documentDescription, so we cannot use the faster // FromOidValue factory } public Pkcs9DocumentDescription(string documentDescription) : base(CAPI.szOID_CAPICOM_documentDescription, Encode(documentDescription)) { m_documentDescription = documentDescription; m_decoded = true; } public Pkcs9DocumentDescription(byte[] encodedDocumentDescription) : base(CAPI.szOID_CAPICOM_documentDescription, encodedDocumentDescription) {} // // Public methods. // public string DocumentDescription { get { if (!m_decoded && (null != RawData)) Decode(); return m_documentDescription; } } public override void CopyFrom (AsnEncodedData asnEncodedData) { base.CopyFrom(asnEncodedData); m_decoded = false; } // // Private methods. // private void Decode () { m_documentDescription = PkcsUtils.DecodeOctetString(RawData); m_decoded = true; } private static byte[] Encode (string documentDescription) { if (String.IsNullOrEmpty(documentDescription)) throw new ArgumentNullException("documentDescription"); return PkcsUtils.EncodeOctetString(documentDescription); } } [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class Pkcs9ContentType : Pkcs9AttributeObject { private Oid m_contentType = null; private bool m_decoded = false; // // Constructors. // internal Pkcs9ContentType (byte[] encodedContentType) : base(Oid.FromOidValue(CAPI.szOID_RSA_contentType, OidGroup.ExtensionOrAttribute), encodedContentType) { } public Pkcs9ContentType() : base(Oid.FromOidValue(CAPI.szOID_RSA_contentType, OidGroup.ExtensionOrAttribute)) { } // // Public properties. // public Oid ContentType { get { if (!m_decoded && (null != RawData)) Decode(); return m_contentType; } } public override void CopyFrom (AsnEncodedData asnEncodedData) { base.CopyFrom(asnEncodedData); m_decoded = false; } // // Private methods. // private void Decode () { if ((RawData.Length < 2) || ((uint) RawData[1] != (uint) (RawData.Length - 2))) throw new CryptographicException(CAPI.CRYPT_E_BAD_ENCODE); if (RawData[0] != CAPI.ASN_TAG_OBJID) throw new CryptographicException(CAPI.CRYPT_E_ASN1_BADTAG); m_contentType = new Oid(PkcsUtils.DecodeObjectIdentifier(RawData, 2)); m_decoded = true; } } [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class Pkcs9MessageDigest : Pkcs9AttributeObject { private byte[] m_messageDigest = null; private bool m_decoded = false; // // Constructors. // internal Pkcs9MessageDigest (byte[] encodedMessageDigest) : base(Oid.FromOidValue(CAPI.szOID_RSA_messageDigest, OidGroup.ExtensionOrAttribute), encodedMessageDigest) { } public Pkcs9MessageDigest () : base(Oid.FromOidValue(CAPI.szOID_RSA_messageDigest, OidGroup.ExtensionOrAttribute)) { } // // Public properties. // public byte[] MessageDigest { get { if (!m_decoded && (null != RawData)) Decode(); return m_messageDigest; } } public override void CopyFrom (AsnEncodedData asnEncodedData) { base.CopyFrom(asnEncodedData); m_decoded = false; } // // Private methods. // private void Decode () { m_messageDigest = PkcsUtils.DecodeOctetBytes(RawData); m_decoded = true; } } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot ([email protected]) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Threading; using ServiceStack.Text.Support; #if WINDOWS_PHONE using System.Linq.Expressions; #endif namespace ServiceStack.Text { public delegate EmptyCtorDelegate EmptyCtorFactoryDelegate(Type type); public delegate object EmptyCtorDelegate(); public static class ReflectionExtensions { private static Dictionary<Type, object> DefaultValueTypes = new Dictionary<Type, object>(); public static object GetDefaultValue(this Type type) { if (!type.IsValueType()) return null; object defaultValue; if (DefaultValueTypes.TryGetValue(type, out defaultValue)) return defaultValue; defaultValue = Activator.CreateInstance(type); Dictionary<Type, object> snapshot, newCache; do { snapshot = DefaultValueTypes; newCache = new Dictionary<Type, object>(DefaultValueTypes); newCache[type] = defaultValue; } while (!ReferenceEquals( Interlocked.CompareExchange(ref DefaultValueTypes, newCache, snapshot), snapshot)); return defaultValue; } public static bool IsInstanceOf(this Type type, Type thisOrBaseType) { while (type != null) { if (type == thisOrBaseType) return true; type = type.BaseType(); } return false; } public static bool HasGenericType(this Type type) { while (type != null) { if (type.IsGeneric()) return true; type = type.BaseType(); } return false; } public static Type GetGenericType(this Type type) { while (type != null) { if (type.IsGeneric()) return type; type = type.BaseType(); } return null; } public static bool IsOrHasGenericInterfaceTypeOf(this Type type, Type genericTypeDefinition) { return (type.GetTypeWithGenericTypeDefinitionOf(genericTypeDefinition) != null) || (type == genericTypeDefinition); } public static Type GetTypeWithGenericTypeDefinitionOf(this Type type, Type genericTypeDefinition) { foreach (var t in type.GetTypeInterfaces()) { if (t.IsGeneric() && t.GetGenericTypeDefinition() == genericTypeDefinition) { return t; } } var genericType = type.GetGenericType(); if (genericType != null && genericType.GetGenericTypeDefinition() == genericTypeDefinition) { return genericType; } return null; } public static Type GetTypeWithInterfaceOf(this Type type, Type interfaceType) { if (type == interfaceType) return interfaceType; foreach (var t in type.GetTypeInterfaces()) { if (t == interfaceType) return t; } return null; } public static bool HasInterface(this Type type, Type interfaceType) { foreach (var t in type.GetTypeInterfaces()) { if (t == interfaceType) return true; } return false; } public static bool AllHaveInterfacesOfType( this Type assignableFromType, params Type[] types) { foreach (var type in types) { if (assignableFromType.GetTypeWithInterfaceOf(type) == null) return false; } return true; } public static bool IsNumericType(this Type type) { if (type == null) return false; if (type.IsEnum) //TypeCode can be TypeCode.Int32 { return JsConfig.TreatEnumAsInteger || type.IsEnumFlags(); } switch (Type.GetTypeCode(type)) { case TypeCode.Byte: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; case TypeCode.Object: if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return IsNumericType(Nullable.GetUnderlyingType(type)); } if (type.IsEnum) { return JsConfig.TreatEnumAsInteger || type.IsEnumFlags(); } return false; } return false; } public static bool IsIntegerType(this Type type) { if (type == null) return false; switch (Type.GetTypeCode(type)) { case TypeCode.Byte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; case TypeCode.Object: if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return IsNumericType(Nullable.GetUnderlyingType(type)); } return false; } return false; } public static bool IsRealNumberType(this Type type) { if (type == null) return false; switch (Type.GetTypeCode(type)) { case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Single: return true; case TypeCode.Object: if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return IsNumericType(Nullable.GetUnderlyingType(type)); } return false; } return false; } public static Type GetTypeWithGenericInterfaceOf(this Type type, Type genericInterfaceType) { foreach (var t in type.GetTypeInterfaces()) { if (t.IsGeneric() && t.GetGenericTypeDefinition() == genericInterfaceType) return t; } if (!type.IsGeneric()) return null; var genericType = type.GetGenericType(); return genericType.GetGenericTypeDefinition() == genericInterfaceType ? genericType : null; } public static bool HasAnyTypeDefinitionsOf(this Type genericType, params Type[] theseGenericTypes) { if (!genericType.IsGeneric()) return false; var genericTypeDefinition = genericType.GenericTypeDefinition(); foreach (var thisGenericType in theseGenericTypes) { if (genericTypeDefinition == thisGenericType) return true; } return false; } public static Type[] GetGenericArgumentsIfBothHaveSameGenericDefinitionTypeAndArguments( this Type assignableFromType, Type typeA, Type typeB) { var typeAInterface = typeA.GetTypeWithGenericInterfaceOf(assignableFromType); if (typeAInterface == null) return null; var typeBInterface = typeB.GetTypeWithGenericInterfaceOf(assignableFromType); if (typeBInterface == null) return null; var typeAGenericArgs = typeAInterface.GetTypeGenericArguments(); var typeBGenericArgs = typeBInterface.GetTypeGenericArguments(); if (typeAGenericArgs.Length != typeBGenericArgs.Length) return null; for (var i = 0; i < typeBGenericArgs.Length; i++) { if (typeAGenericArgs[i] != typeBGenericArgs[i]) { return null; } } return typeAGenericArgs; } public static TypePair GetGenericArgumentsIfBothHaveConvertibleGenericDefinitionTypeAndArguments( this Type assignableFromType, Type typeA, Type typeB) { var typeAInterface = typeA.GetTypeWithGenericInterfaceOf(assignableFromType); if (typeAInterface == null) return null; var typeBInterface = typeB.GetTypeWithGenericInterfaceOf(assignableFromType); if (typeBInterface == null) return null; var typeAGenericArgs = typeAInterface.GetTypeGenericArguments(); var typeBGenericArgs = typeBInterface.GetTypeGenericArguments(); if (typeAGenericArgs.Length != typeBGenericArgs.Length) return null; for (var i = 0; i < typeBGenericArgs.Length; i++) { if (!AreAllStringOrValueTypes(typeAGenericArgs[i], typeBGenericArgs[i])) { return null; } } return new TypePair(typeAGenericArgs, typeBGenericArgs); } public static bool AreAllStringOrValueTypes(params Type[] types) { foreach (var type in types) { if (!(type == typeof(string) || type.IsValueType())) return false; } return true; } static Dictionary<Type, EmptyCtorDelegate> ConstructorMethods = new Dictionary<Type, EmptyCtorDelegate>(); public static EmptyCtorDelegate GetConstructorMethod(Type type) { EmptyCtorDelegate emptyCtorFn; if (ConstructorMethods.TryGetValue(type, out emptyCtorFn)) return emptyCtorFn; emptyCtorFn = GetConstructorMethodToCache(type); Dictionary<Type, EmptyCtorDelegate> snapshot, newCache; do { snapshot = ConstructorMethods; newCache = new Dictionary<Type, EmptyCtorDelegate>(ConstructorMethods); newCache[type] = emptyCtorFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref ConstructorMethods, newCache, snapshot), snapshot)); return emptyCtorFn; } static Dictionary<string, EmptyCtorDelegate> TypeNamesMap = new Dictionary<string, EmptyCtorDelegate>(); public static EmptyCtorDelegate GetConstructorMethod(string typeName) { EmptyCtorDelegate emptyCtorFn; if (TypeNamesMap.TryGetValue(typeName, out emptyCtorFn)) return emptyCtorFn; var type = JsConfig.TypeFinder.Invoke(typeName); if (type == null) return null; emptyCtorFn = GetConstructorMethodToCache(type); Dictionary<string, EmptyCtorDelegate> snapshot, newCache; do { snapshot = TypeNamesMap; newCache = new Dictionary<string, EmptyCtorDelegate>(TypeNamesMap); newCache[typeName] = emptyCtorFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref TypeNamesMap, newCache, snapshot), snapshot)); return emptyCtorFn; } public static EmptyCtorDelegate GetConstructorMethodToCache(Type type) { var emptyCtor = type.GetEmptyConstructor(); if (emptyCtor != null) { #if MONOTOUCH || c|| XBOX || NETFX_CORE return () => Activator.CreateInstance(type); #elif WINDOWS_PHONE return Expression.Lambda<EmptyCtorDelegate>(Expression.New(type)).Compile(); #else #if SILVERLIGHT var dm = new System.Reflection.Emit.DynamicMethod("MyCtor", type, Type.EmptyTypes); #else var dm = new System.Reflection.Emit.DynamicMethod("MyCtor", type, Type.EmptyTypes, typeof(ReflectionExtensions).Module, true); #endif var ilgen = dm.GetILGenerator(); ilgen.Emit(System.Reflection.Emit.OpCodes.Nop); ilgen.Emit(System.Reflection.Emit.OpCodes.Newobj, emptyCtor); ilgen.Emit(System.Reflection.Emit.OpCodes.Ret); return (EmptyCtorDelegate)dm.CreateDelegate(typeof(EmptyCtorDelegate)); #endif } #if (SILVERLIGHT && !WINDOWS_PHONE) || XBOX return () => Activator.CreateInstance(type); #elif WINDOWS_PHONE return Expression.Lambda<EmptyCtorDelegate>(Expression.New(type)).Compile(); #else if (type == typeof(string)) return () => String.Empty; //Anonymous types don't have empty constructors return () => FormatterServices.GetUninitializedObject(type); #endif } private static class TypeMeta<T> { public static readonly EmptyCtorDelegate EmptyCtorFn; static TypeMeta() { EmptyCtorFn = GetConstructorMethodToCache(typeof(T)); } } public static object CreateInstance<T>() { return TypeMeta<T>.EmptyCtorFn(); } public static object CreateInstance(this Type type) { var ctorFn = GetConstructorMethod(type); return ctorFn(); } public static object CreateInstance(string typeName) { var ctorFn = GetConstructorMethod(typeName); return ctorFn(); } public static PropertyInfo[] GetPublicProperties(this Type type) { if (type.IsInterface()) { var propertyInfos = new List<PropertyInfo>(); var considered = new List<Type>(); var queue = new Queue<Type>(); considered.Add(type); queue.Enqueue(type); while (queue.Count > 0) { var subType = queue.Dequeue(); foreach (var subInterface in subType.GetTypeInterfaces()) { if (considered.Contains(subInterface)) continue; considered.Add(subInterface); queue.Enqueue(subInterface); } var typeProperties = subType.GetTypesPublicProperties(); var newPropertyInfos = typeProperties .Where(x => !propertyInfos.Contains(x)); propertyInfos.InsertRange(0, newPropertyInfos); } return propertyInfos.ToArray(); } return type.GetTypesPublicProperties() .Where(t => t.GetIndexParameters().Length == 0) // ignore indexed properties .ToArray(); } const string DataContract = "DataContractAttribute"; const string DataMember = "DataMemberAttribute"; const string IgnoreDataMember = "IgnoreDataMemberAttribute"; public static PropertyInfo[] GetSerializableProperties(this Type type) { var publicProperties = GetPublicProperties(type); var publicReadableProperties = publicProperties.Where(x => x.PropertyGetMethod() != null); if (type.IsDto()) { return !Env.IsMono ? publicReadableProperties.Where(attr => attr.IsDefined(typeof(DataMemberAttribute), false)).ToArray() : publicReadableProperties.Where(attr => attr.CustomAttributes(false).Any(x => x.GetType().Name == DataMember)).ToArray(); } // else return those properties that are not decorated with IgnoreDataMember return publicReadableProperties.Where(prop => !prop.CustomAttributes(false).Any(attr => attr.GetType().Name == IgnoreDataMember)).ToArray(); } public static FieldInfo[] GetSerializableFields(this Type type) { if (type.IsDto()) { return new FieldInfo[0]; } var publicFields = type.GetPublicFields(); // else return those properties that are not decorated with IgnoreDataMember return publicFields.Where(prop => !prop.CustomAttributes(false).Any(attr => attr.GetType().Name == IgnoreDataMember)).ToArray(); } public static bool HasAttr<T>(this Type type) where T : Attribute { return type.HasAttribute<T>(); } #if !SILVERLIGHT && !MONOTOUCH static readonly Dictionary<Type, FastMember.TypeAccessor> typeAccessorMap = new Dictionary<Type, FastMember.TypeAccessor>(); #endif public static DataContractAttribute GetDataContract(this Type type) { var dataContract = type.FirstAttribute<DataContractAttribute>(); #if !SILVERLIGHT && !MONOTOUCH && !XBOX if (dataContract == null && Env.IsMono) return type.GetWeakDataContract(); #endif return dataContract; } public static DataMemberAttribute GetDataMember(this PropertyInfo pi) { var dataMember = pi.CustomAttributes(typeof(DataMemberAttribute), false) .FirstOrDefault() as DataMemberAttribute; #if !SILVERLIGHT && !MONOTOUCH && !XBOX if (dataMember == null && Env.IsMono) return pi.GetWeakDataMember(); #endif return dataMember; } #if !SILVERLIGHT && !MONOTOUCH && !XBOX public static DataContractAttribute GetWeakDataContract(this Type type) { var attr = type.CustomAttributes().FirstOrDefault(x => x.GetType().Name == DataContract); if (attr != null) { var attrType = attr.GetType(); FastMember.TypeAccessor accessor; lock (typeAccessorMap) { if (!typeAccessorMap.TryGetValue(attrType, out accessor)) typeAccessorMap[attrType] = accessor = FastMember.TypeAccessor.Create(attr.GetType()); } return new DataContractAttribute { Name = (string)accessor[attr, "Name"], Namespace = (string)accessor[attr, "Namespace"], }; } return null; } public static DataMemberAttribute GetWeakDataMember(this PropertyInfo pi) { var attr = pi.CustomAttributes().FirstOrDefault(x => x.GetType().Name == DataMember); if (attr != null) { var attrType = attr.GetType(); FastMember.TypeAccessor accessor; lock (typeAccessorMap) { if (!typeAccessorMap.TryGetValue(attrType, out accessor)) typeAccessorMap[attrType] = accessor = FastMember.TypeAccessor.Create(attr.GetType()); } var newAttr = new DataMemberAttribute { Name = (string) accessor[attr, "Name"], EmitDefaultValue = (bool)accessor[attr, "EmitDefaultValue"], IsRequired = (bool)accessor[attr, "IsRequired"], }; var order = (int)accessor[attr, "Order"]; if (order >= 0) newAttr.Order = order; //Throws Exception if set to -1 return newAttr; } return null; } #endif } public static class PlatformExtensions //Because WinRT is a POS { public static bool IsInterface(this Type type) { #if NETFX_CORE return type.GetTypeInfo().IsInterface; #else return type.IsInterface; #endif } public static bool IsArray(this Type type) { #if NETFX_CORE return type.GetTypeInfo().IsArray; #else return type.IsArray; #endif } public static bool IsValueType(this Type type) { #if NETFX_CORE return type.GetTypeInfo().IsValueType; #else return type.IsValueType; #endif } public static bool IsGeneric(this Type type) { #if NETFX_CORE return type.GetTypeInfo().IsGenericType; #else return type.IsGenericType; #endif } public static Type BaseType(this Type type) { #if NETFX_CORE return type.GetTypeInfo().BaseType; #else return type.BaseType; #endif } public static Type ReflectedType(this PropertyInfo pi) { #if NETFX_CORE return pi.PropertyType; #else return pi.ReflectedType; #endif } public static Type ReflectedType(this FieldInfo fi) { #if NETFX_CORE return fi.FieldType; #else return fi.ReflectedType; #endif } public static Type GenericTypeDefinition(this Type type) { #if NETFX_CORE return type.GetTypeInfo().GetGenericTypeDefinition(); #else return type.GetGenericTypeDefinition(); #endif } public static Type[] GetTypeInterfaces(this Type type) { #if NETFX_CORE return type.GetTypeInfo().ImplementedInterfaces.ToArray(); #else return type.GetInterfaces(); #endif } public static Type[] GetTypeGenericArguments(this Type type) { #if NETFX_CORE return type.GenericTypeArguments; #else return type.GetGenericArguments(); #endif } public static ConstructorInfo GetEmptyConstructor(this Type type) { #if NETFX_CORE return type.GetTypeInfo().DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Count() == 0); #else return type.GetConstructor(Type.EmptyTypes); #endif } internal static PropertyInfo[] GetTypesPublicProperties(this Type subType) { #if NETFX_CORE return subType.GetRuntimeProperties().ToArray(); #else return subType.GetProperties( BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); #endif } public static PropertyInfo[] Properties(this Type type) { #if NETFX_CORE return type.GetRuntimeProperties().ToArray(); #else return type.GetProperties(); #endif } public static FieldInfo[] GetPublicFields(this Type type) { if (type.IsInterface()) { return new FieldInfo[0]; } #if NETFX_CORE return type.GetRuntimeFields().Where(p => p.IsPublic && !p.IsStatic).ToArray(); #else return type.GetFields(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance) .ToArray(); #endif } public static MemberInfo[] GetPublicMembers(this Type type) { #if NETFX_CORE var members = new List<MemberInfo>(); members.AddRange(type.GetRuntimeFields().Where(p => p.IsPublic && !p.IsStatic)); members.AddRange(type.GetPublicProperties()); return members.ToArray(); #else return type.GetMembers(BindingFlags.Public | BindingFlags.Instance); #endif } public static MemberInfo[] GetAllPublicMembers(this Type type) { #if NETFX_CORE var members = new List<MemberInfo>(); members.AddRange(type.GetRuntimeFields().Where(p => p.IsPublic && !p.IsStatic)); members.AddRange(type.GetPublicProperties()); return members.ToArray(); #else return type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy); #endif } public static bool HasAttribute<T>(this Type type, bool inherit = true) where T : Attribute { return type.CustomAttributes(inherit).Any(x => x.GetType() == typeof(T)); } public static IEnumerable<T> AttributesOfType<T>(this Type type, bool inherit = true) where T : Attribute { #if NETFX_CORE return type.GetTypeInfo().GetCustomAttributes<T>(inherit); #else return type.GetCustomAttributes(inherit).OfType<T>(); #endif } const string DataContract = "DataContractAttribute"; public static bool IsDto(this Type type) { #if NETFX_CORE return type.GetTypeInfo().IsDefined(typeof(DataContractAttribute), false); #else return !Env.IsMono ? type.IsDefined(typeof(DataContractAttribute), false) : type.GetCustomAttributes(true).Any(x => x.GetType().Name == DataContract); #endif } public static MethodInfo PropertyGetMethod(this PropertyInfo pi, bool nonPublic = false) { #if NETFX_CORE return pi.GetMethod; #else return pi.GetGetMethod(false); #endif } public static Type[] Interfaces(this Type type) { #if NETFX_CORE return type.GetTypeInfo().ImplementedInterfaces.ToArray(); //return type.GetTypeInfo().ImplementedInterfaces // .FirstOrDefault(x => !x.GetTypeInfo().ImplementedInterfaces // .Any(y => y.GetTypeInfo().ImplementedInterfaces.Contains(y))); #else return type.GetInterfaces(); #endif } public static PropertyInfo[] AllProperties(this Type type) { #if NETFX_CORE return type.GetRuntimeProperties().ToArray(); #else return type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); #endif } public static object[] CustomAttributes(this PropertyInfo propertyInfo, bool inherit = true) { #if NETFX_CORE return propertyInfo.GetCustomAttributes(inherit).ToArray(); #else return propertyInfo.GetCustomAttributes(inherit); #endif } public static object[] CustomAttributes(this PropertyInfo propertyInfo, Type attrType, bool inherit = true) { #if NETFX_CORE return propertyInfo.GetCustomAttributes(inherit).Where(x => x.GetType() == attrType).ToArray(); #else return propertyInfo.GetCustomAttributes(attrType, inherit); #endif } public static object[] CustomAttributes(this FieldInfo fieldInfo, bool inherit = true) { #if NETFX_CORE return fieldInfo.GetCustomAttributes(inherit).ToArray(); #else return fieldInfo.GetCustomAttributes(inherit); #endif } public static object[] CustomAttributes(this FieldInfo fieldInfo, Type attrType, bool inherit = true) { #if NETFX_CORE return fieldInfo.GetCustomAttributes(inherit).Where(x => x.GetType() == attrType).ToArray(); #else return fieldInfo.GetCustomAttributes(attrType, inherit); #endif } public static object[] CustomAttributes(this Type type, bool inherit = true) { #if NETFX_CORE return type.GetTypeInfo().GetCustomAttributes(inherit).ToArray(); #else return type.GetCustomAttributes(inherit); #endif } public static object[] CustomAttributes(this Type type, Type attrType, bool inherit = true) { #if NETFX_CORE return type.GetTypeInfo().GetCustomAttributes(inherit).Where(x => x.GetType() == attrType).ToArray(); #else return type.GetCustomAttributes(attrType, inherit); #endif } public static TAttr FirstAttribute<TAttr>(this Type type, bool inherit = true) where TAttr : Attribute { #if NETFX_CORE return type.GetTypeInfo().GetCustomAttributes(typeof(TAttr), inherit) .FirstOrDefault() as TAttr; #else return type.GetCustomAttributes(typeof(TAttr), inherit) .FirstOrDefault() as TAttr; #endif } public static TAttribute FirstAttribute<TAttribute>(this PropertyInfo propertyInfo) where TAttribute : Attribute { return propertyInfo.FirstAttribute<TAttribute>(true); } public static TAttribute FirstAttribute<TAttribute>(this PropertyInfo propertyInfo, bool inherit) where TAttribute : Attribute { #if NETFX_CORE var attrs = propertyInfo.GetCustomAttributes<TAttribute>(inherit); return (TAttribute)(attrs.Count() > 0 ? attrs.ElementAt(0) : null); #else var attrs = propertyInfo.GetCustomAttributes(typeof(TAttribute), inherit); return (TAttribute)(attrs.Length > 0 ? attrs[0] : null); #endif } public static Type FirstGenericTypeDefinition(this Type type) { while (type != null) { if (type.HasGenericType()) return type.GenericTypeDefinition(); type = type.BaseType(); } return null; } public static bool IsDynamic(this Assembly assembly) { #if MONOTOUCH || WINDOWS_PHONE || NETFX_CORE return false; #else try { var isDyanmic = assembly is System.Reflection.Emit.AssemblyBuilder || string.IsNullOrEmpty(assembly.Location); return isDyanmic; } catch (NotSupportedException) { //Ignore assembly.Location not supported in a dynamic assembly. return true; } #endif } public static MethodInfo GetPublicStaticMethod(this Type type, string methodName, Type[] types = null) { #if NETFX_CORE return type.GetRuntimeMethod(methodName, types); #else return types == null ? type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static) : type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static, null, types, null); #endif } public static MethodInfo GetMethodInfo(this Type type, string methodName, Type[] types = null) { #if NETFX_CORE return type.GetRuntimeMethods().First(p => p.Name.Equals(methodName)); #else return types == null ? type.GetMethod(methodName) : type.GetMethod(methodName, types); #endif } public static object InvokeMethod(this Delegate fn, object instance, object[] parameters = null) { #if NETFX_CORE return fn.GetMethodInfo().Invoke(instance, parameters ?? new object[] { }); #else return fn.Method.Invoke(instance, parameters ?? new object[] { }); #endif } public static FieldInfo GetPublicStaticField(this Type type, string fieldName) { #if NETFX_CORE return type.GetRuntimeField(fieldName); #else return type.GetField(fieldName, BindingFlags.Public | BindingFlags.Static); #endif } public static Delegate MakeDelegate(this MethodInfo mi, Type delegateType, bool throwOnBindFailure=true) { #if NETFX_CORE return mi.CreateDelegate(delegateType); #else return Delegate.CreateDelegate(delegateType, mi, throwOnBindFailure); #endif } public static Type[] GenericTypeArguments(this Type type) { #if NETFX_CORE return type.GenericTypeArguments; #else return type.GetGenericArguments(); #endif } public static ConstructorInfo[] DeclaredConstructors(this Type type) { #if NETFX_CORE return type.GetTypeInfo().DeclaredConstructors.ToArray(); #else return type.GetConstructors(); #endif } public static bool AssignableFrom(this Type type, Type fromType) { #if NETFX_CORE return type.GetTypeInfo().IsAssignableFrom(fromType.GetTypeInfo()); #else return type.IsAssignableFrom(fromType); #endif } public static bool IsStandardClass(this Type type) { #if NETFX_CORE var typeInfo = type.GetTypeInfo(); return typeInfo.IsClass && !typeInfo.IsAbstract && !typeInfo.IsInterface; #else return type.IsClass && !type.IsAbstract && !type.IsInterface; #endif } public static bool IsAbstract(this Type type) { #if NETFX_CORE return type.GetTypeInfo().IsAbstract; #else return type.IsAbstract; #endif } public static PropertyInfo GetPropertyInfo(this Type type, string propertyName) { #if NETFX_CORE return type.GetRuntimeProperty(propertyName); #else return type.GetProperty(propertyName); #endif } public static FieldInfo GetFieldInfo(this Type type, string fieldName) { #if NETFX_CORE return type.GetRuntimeField(fieldName); #else return type.GetField(fieldName); #endif } public static FieldInfo[] GetWritableFields(this Type type) { #if NETFX_CORE return type.GetRuntimeFields().Where(p => !p.IsPublic && !p.IsStatic).ToArray(); #else return type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField); #endif } public static MethodInfo SetMethod(this PropertyInfo pi, bool nonPublic = true) { #if NETFX_CORE return pi.SetMethod; #else return pi.GetSetMethod(nonPublic); #endif } public static MethodInfo GetMethodInfo(this PropertyInfo pi, bool nonPublic = true) { #if NETFX_CORE return pi.GetMethod; #else return pi.GetGetMethod(nonPublic); #endif } public static bool InstanceOfType(this Type type, object instance) { #if NETFX_CORE return type.IsInstanceOf(instance.GetType()); #else return type.IsInstanceOfType(instance); #endif } public static bool IsClass(this Type type) { #if NETFX_CORE return type.GetTypeInfo().IsClass; #else return type.IsClass; #endif } public static bool IsEnum(this Type type) { #if NETFX_CORE return type.GetTypeInfo().IsEnum; #else return type.IsEnum; #endif } public static bool IsEnumFlags(this Type type) { #if NETFX_CORE return type.GetTypeInfo().IsEnum && type.FirstAttribute<FlagsAttribute>(false) != null; #else return type.IsEnum && type.FirstAttribute<FlagsAttribute>(false) != null; #endif } public static bool IsUnderlyingEnum(this Type type) { #if NETFX_CORE return type.GetTypeInfo().IsEnum; #else return type.IsEnum || type.UnderlyingSystemType.IsEnum; #endif } public static MethodInfo[] GetMethodInfos(this Type type) { #if NETFX_CORE return type.GetRuntimeMethods().ToArray(); #else return type.GetMethods(); #endif } public static PropertyInfo[] GetPropertyInfos(this Type type) { #if NETFX_CORE return type.GetRuntimeProperties().ToArray(); #else return type.GetProperties(); #endif } #if SILVERLIGHT || NETFX_CORE public static List<U> ConvertAll<T, U>(this List<T> list, Func<T, U> converter) { var result = new List<U>(); foreach (var element in list) { result.Add(converter(element)); } return result; } #endif } }
using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace RefExplorer.Gui { public partial class MyBrowser : WebBrowser { #region enums public enum OLECMDID { OLECMDID_OPEN = 1, OLECMDID_NEW = 2, OLECMDID_SAVE = 3, OLECMDID_SAVEAS = 4, OLECMDID_SAVECOPYAS = 5, OLECMDID_PRINT = 6, OLECMDID_PRINTPREVIEW = 7, OLECMDID_PAGESETUP = 8, OLECMDID_SPELL = 9, OLECMDID_PROPERTIES = 10, OLECMDID_CUT = 11, OLECMDID_COPY = 12, OLECMDID_PASTE = 13, OLECMDID_PASTESPECIAL = 14, OLECMDID_UNDO = 15, OLECMDID_REDO = 16, OLECMDID_SELECTALL = 17, OLECMDID_CLEARSELECTION = 18, OLECMDID_ZOOM = 19, OLECMDID_GETZOOMRANGE = 20, OLECMDID_UPDATECOMMANDS = 21, OLECMDID_REFRESH = 22, OLECMDID_STOP = 23, OLECMDID_HIDETOOLBARS = 24, OLECMDID_SETPROGRESSMAX = 25, OLECMDID_SETPROGRESSPOS = 26, OLECMDID_SETPROGRESSTEXT = 27, OLECMDID_SETTITLE = 28, OLECMDID_SETDOWNLOADSTATE = 29, OLECMDID_STOPDOWNLOAD = 30, OLECMDID_ONTOOLBARACTIVATED = 31, OLECMDID_FIND = 32, OLECMDID_DELETE = 33, OLECMDID_HTTPEQUIV = 34, OLECMDID_HTTPEQUIV_DONE = 35, OLECMDID_ENABLE_INTERACTION = 36, OLECMDID_ONUNLOAD = 37, OLECMDID_PROPERTYBAG2 = 38, OLECMDID_PREREFRESH = 39, OLECMDID_SHOWSCRIPTERROR = 40, OLECMDID_SHOWMESSAGE = 41, OLECMDID_SHOWFIND = 42, OLECMDID_SHOWPAGESETUP = 43, OLECMDID_SHOWPRINT = 44, OLECMDID_CLOSE = 45, OLECMDID_ALLOWUILESSSAVEAS = 46, OLECMDID_DONTDOWNLOADCSS = 47, OLECMDID_UPDATEPAGESTATUS = 48, OLECMDID_PRINT2 = 49, OLECMDID_PRINTPREVIEW2 = 50, OLECMDID_SETPRINTTEMPLATE = 51, OLECMDID_GETPRINTTEMPLATE = 52, OLECMDID_PAGEACTIONBLOCKED = 55, OLECMDID_PAGEACTIONUIQUERY = 56, OLECMDID_FOCUSVIEWCONTROLS = 57, OLECMDID_FOCUSVIEWCONTROLSQUERY = 58, OLECMDID_SHOWPAGEACTIONMENU = 59, OLECMDID_ADDTRAVELENTRY = 60, OLECMDID_UPDATETRAVELENTRY = 61, OLECMDID_UPDATEBACKFORWARDSTATE = 62, OLECMDID_OPTICAL_ZOOM = 63, OLECMDID_OPTICAL_GETZOOMRANGE = 64, OLECMDID_WINDOWSTATECHANGED = 65 } public enum OLECMDEXECOPT { OLECMDEXECOPT_DODEFAULT, OLECMDEXECOPT_PROMPTUSER, OLECMDEXECOPT_DONTPROMPTUSER, OLECMDEXECOPT_SHOWHELP } public enum OLECMDF { OLECMDF_DEFHIDEONCTXTMENU = 0x20, OLECMDF_ENABLED = 2, OLECMDF_INVISIBLE = 0x10, OLECMDF_LATCHED = 4, OLECMDF_NINCHED = 8, OLECMDF_SUPPORTED = 1 } #endregion #region IWebBrowser2 [ComImport, /*SuppressUnmanagedCodeSecurity,*/ TypeLibType(TypeLibTypeFlags.FOleAutomation | TypeLibTypeFlags.FDual | TypeLibTypeFlags.FHidden), Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E")] public interface IWebBrowser2 { [DispId(100)] void GoBack(); [DispId(0x65)] void GoForward(); [DispId(0x66)] void GoHome(); [DispId(0x67)] void GoSearch(); [DispId(0x68)] void Navigate([In] string Url, [In] ref object flags, [In] ref object targetFrameName, [In] ref object postData, [In] ref object headers); [DispId(-550)] void Refresh(); [DispId(0x69)] void Refresh2([In] ref object level); [DispId(0x6a)] void Stop(); [DispId(200)] object Application { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0xc9)] object Parent { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0xca)] object Container { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0xcb)] object Document { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0xcc)] bool TopLevelContainer { get; } [DispId(0xcd)] string Type { get; } [DispId(0xce)] int Left { get; set; } [DispId(0xcf)] int Top { get; set; } [DispId(0xd0)] int Width { get; set; } [DispId(0xd1)] int Height { get; set; } [DispId(210)] string LocationName { get; } [DispId(0xd3)] string LocationURL { get; } [DispId(0xd4)] bool Busy { get; } [DispId(300)] void Quit(); [DispId(0x12d)] void ClientToWindow(out int pcx, out int pcy); [DispId(0x12e)] void PutProperty([In] string property, [In] object vtValue); [DispId(0x12f)] object GetProperty([In] string property); [DispId(0)] string Name { get; } [DispId(-515)] int HWND { get; } [DispId(400)] string FullName { get; } [DispId(0x191)] string Path { get; } [DispId(0x192)] bool Visible { get; set; } [DispId(0x193)] bool StatusBar { get; set; } [DispId(0x194)] string StatusText { get; set; } [DispId(0x195)] int ToolBar { get; set; } [DispId(0x196)] bool MenuBar { get; set; } [DispId(0x197)] bool FullScreen { get; set; } [DispId(500)] void Navigate2([In] ref object URL, [In] ref object flags, [In] ref object targetFrameName, [In] ref object postData, [In] ref object headers); [DispId(0x1f5)] OLECMDF QueryStatusWB([In] OLECMDID cmdID); [DispId(0x1f6)] void ExecWB([In] OLECMDID cmdID, [In] OLECMDEXECOPT cmdexecopt, ref object pvaIn, IntPtr pvaOut); [DispId(0x1f7)] void ShowBrowserBar([In] ref object pvaClsid, [In] ref object pvarShow, [In] ref object pvarSize); [DispId(-525)] WebBrowserReadyState ReadyState { get; } [DispId(550)] bool Offline { get; set; } [DispId(0x227)] bool Silent { get; set; } [DispId(0x228)] bool RegisterAsBrowser { get; set; } [DispId(0x229)] bool RegisterAsDropTarget { get; set; } [DispId(0x22a)] bool TheaterMode { get; set; } [DispId(0x22b)] bool AddressBar { get; set; } [DispId(0x22c)] bool Resizable { get; set; } } #endregion private IWebBrowser2 axIWebBrowser2; public MyBrowser() { } protected override void AttachInterfaces(object nativeActiveXObject) { base.AttachInterfaces(nativeActiveXObject); this.axIWebBrowser2 = (IWebBrowser2)nativeActiveXObject; } protected override void DetachInterfaces() { base.DetachInterfaces(); this.axIWebBrowser2 = null; } public void Zoom(int factor) { object pvaIn = factor; try { this.axIWebBrowser2.ExecWB(OLECMDID.OLECMDID_OPTICAL_ZOOM, OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, ref pvaIn, IntPtr.Zero); } catch (Exception) { throw; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO.Enumeration; using System.Linq; namespace System.IO { public sealed partial class DirectoryInfo : FileSystemInfo { public DirectoryInfo(string path) { Init(originalPath: path, fullPath: Path.GetFullPath(path), isNormalized: true); } internal DirectoryInfo(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false) { Init(originalPath, fullPath, fileName, isNormalized); } private void Init(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false) { // Want to throw the original argument name OriginalPath = originalPath ?? throw new ArgumentNullException("path"); fullPath = fullPath ?? originalPath; Debug.Assert(!isNormalized || !PathInternal.IsPartiallyQualified(fullPath), $"'{fullPath}' should be fully qualified if normalized"); fullPath = isNormalized ? fullPath : Path.GetFullPath(fullPath); _name = fileName ?? (PathHelpers.IsRoot(fullPath) ? fullPath : Path.GetFileName(PathHelpers.TrimEndingDirectorySeparator(fullPath))); FullPath = fullPath; } public DirectoryInfo Parent { get { // FullPath might end in either "parent\child" or "parent\child\", and in either case we want // the parent of child, not the child. Trim off an ending directory separator if there is one, // but don't mangle the root. string parentName = Path.GetDirectoryName(PathHelpers.IsRoot(FullPath) ? FullPath : PathHelpers.TrimEndingDirectorySeparator(FullPath)); return parentName != null ? new DirectoryInfo(parentName, null) : null; } } public DirectoryInfo CreateSubdirectory(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); PathHelpers.ThrowIfEmptyOrRootedPath(path); string fullPath = Path.GetFullPath(Path.Combine(FullPath, path)); if (0 != string.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.StringComparison)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, FullPath), nameof(path)); } FileSystem.CreateDirectory(fullPath); return new DirectoryInfo(fullPath); } public void Create() => FileSystem.CreateDirectory(FullPath); // Returns an array of Files in the DirectoryInfo specified by path public FileInfo[] GetFiles() => GetFiles("*", enumerationOptions: EnumerationOptions.Compatible); // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). public FileInfo[] GetFiles(string searchPattern) => GetFiles(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public FileInfo[] GetFiles(string searchPattern, SearchOption searchOption) => GetFiles(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public FileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions) => ((IEnumerable<FileInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Files, enumerationOptions)).ToArray(); // Returns an array of strongly typed FileSystemInfo entries which will contain a listing // of all the files and directories. public FileSystemInfo[] GetFileSystemInfos() => GetFileSystemInfos("*", enumerationOptions: EnumerationOptions.Compatible); // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). public FileSystemInfo[] GetFileSystemInfos(string searchPattern) => GetFileSystemInfos(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public FileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) => GetFileSystemInfos(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public FileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) => InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Both, enumerationOptions).ToArray(); // Returns an array of Directories in the current directory. public DirectoryInfo[] GetDirectories() => GetDirectories("*", enumerationOptions: EnumerationOptions.Compatible); // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "System*" could match the System & System32 directories). public DirectoryInfo[] GetDirectories(string searchPattern) => GetDirectories(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) => GetDirectories(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public DirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions) => ((IEnumerable<DirectoryInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Directories, enumerationOptions)).ToArray(); public IEnumerable<DirectoryInfo> EnumerateDirectories() => EnumerateDirectories("*", enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern) => EnumerateDirectories(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, SearchOption searchOption) => EnumerateDirectories(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions) => (IEnumerable<DirectoryInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Directories, enumerationOptions); public IEnumerable<FileInfo> EnumerateFiles() => EnumerateFiles("*", enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<FileInfo> EnumerateFiles(string searchPattern) => EnumerateFiles(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, SearchOption searchOption) => EnumerateFiles(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions) => (IEnumerable<FileInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Files, enumerationOptions); public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() => EnumerateFileSystemInfos("*", enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern) => EnumerateFileSystemInfos(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) => EnumerateFileSystemInfos(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) => InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Both, enumerationOptions); internal static IEnumerable<FileSystemInfo> InternalEnumerateInfos( string path, string searchPattern, SearchTarget searchTarget, EnumerationOptions options) { Debug.Assert(path != null); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options); switch (searchTarget) { case SearchTarget.Directories: return FileSystemEnumerableFactory.DirectoryInfos(path, searchPattern, options); case SearchTarget.Files: return FileSystemEnumerableFactory.FileInfos(path, searchPattern, options); case SearchTarget.Both: return FileSystemEnumerableFactory.FileSystemInfos(path, searchPattern, options); default: throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(searchTarget)); } } public DirectoryInfo Root => new DirectoryInfo(Path.GetPathRoot(FullPath)); public void MoveTo(string destDirName) { if (destDirName == null) throw new ArgumentNullException(nameof(destDirName)); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName)); string destination = Path.GetFullPath(destDirName); string destinationWithSeparator = destination; if (!PathHelpers.EndsInDirectorySeparator(destinationWithSeparator)) destinationWithSeparator = destinationWithSeparator + PathHelpers.DirectorySeparatorCharAsString; string sourceWithSeparator = PathHelpers.EndsInDirectorySeparator(FullPath) ? FullPath : FullPath + PathHelpers.DirectorySeparatorCharAsString; if (string.Equals(sourceWithSeparator, destinationWithSeparator, PathInternal.StringComparison)) throw new IOException(SR.IO_SourceDestMustBeDifferent); string sourceRoot = Path.GetPathRoot(sourceWithSeparator); string destinationRoot = Path.GetPathRoot(destinationWithSeparator); if (!string.Equals(sourceRoot, destinationRoot, PathInternal.StringComparison)) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); // Windows will throw if the source file/directory doesn't exist, we preemptively check // to make sure our cross platform behavior matches NetFX behavior. if (!Exists && !FileSystem.FileExists(FullPath)) throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullPath)); if (FileSystem.DirectoryExists(destination)) throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, destinationWithSeparator)); FileSystem.MoveDirectory(FullPath, destination); Init(originalPath: destDirName, fullPath: destinationWithSeparator, fileName: _name, isNormalized: true); // Flush any cached information about the directory. Invalidate(); } public override void Delete() => FileSystem.RemoveDirectory(FullPath, recursive: false); public void Delete(bool recursive) => FileSystem.RemoveDirectory(FullPath, recursive); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Windows.Forms; using OpenLiveWriter.ApplicationFramework.Preferences; using OpenLiveWriter.BlogClient; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Layout; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.Localization; namespace OpenLiveWriter.PostEditor.Configuration.Wizard { /// <summary> /// Summary description for WelcomeToBlogControl. /// </summary> internal class WeblogConfigurationWizardPanelSharePointBasicInfo : WeblogConfigurationWizardPanel, IAccountBasicInfoProvider { private TextBox textBoxHomepageUrl; private Label labelHomepageUrl; /// <summary> /// Required designer variable. /// </summary> private Container components = null; public WeblogConfigurationWizardPanelSharePointBasicInfo() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); labelHeader.Text = Res.Get(StringId.CWBasicHeader); labelHomepageUrl.Text = Res.Get(StringId.CWSharePointHomepageUrl); } public override bool ShowProxySettingsLink { get { return true; } } public override ConfigPanelId? PanelId { get { return ConfigPanelId.SharePointBasicInfo; } } public override void NaturalizeLayout() { if (!DesignMode) { MaximizeWidth(labelHomepageUrl); LayoutHelper.NaturalizeHeightAndDistribute(3, labelHomepageUrl, textBoxHomepageUrl); } } public IBlogProviderAccountWizardDescription ProviderAccountWizard { set { } } public string AccountId { set { } } public string HomepageUrl { get { return UrlHelper.FixUpUrl(textBoxHomepageUrl.Text); } set { textBoxHomepageUrl.Text = value; } } public bool SavePassword { get { return false; } set { } } public bool ForceManualConfiguration { get { return false; } set { } } public IBlogCredentials Credentials { get { if(credentials == null) { credentials = new TemporaryBlogCredentials(); credentials.Username = "" ; credentials.Password = "" ; } return credentials ; } set { credentials = new TemporaryBlogCredentials(); credentials.Username = value.Username; credentials.Password = value.Password; } } private TemporaryBlogCredentials credentials; public bool IsDirty(TemporaryBlogSettings settings) { return !UrlHelper.UrlsAreEqual(HomepageUrl, settings.HomepageUrl) || !BlogCredentialsHelper.CredentialsAreEqual(Credentials, settings.Credentials) ; } public BlogInfo BlogAccount { get { return null; } } public override bool ValidatePanel() { if (HomepageUrl == String.Empty) { ShowValidationError( textBoxHomepageUrl, MessageId.HomepageUrlRequired ) ; return false; } return true ; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.labelHomepageUrl = new Label(); this.textBoxHomepageUrl = new TextBox(); this.panelMain.SuspendLayout(); this.SuspendLayout(); // // panelMain // this.panelMain.Controls.Add(this.labelHomepageUrl); this.panelMain.Controls.Add(this.textBoxHomepageUrl); this.panelMain.Location = new System.Drawing.Point(48, 8); this.panelMain.Size = new System.Drawing.Size(352, 224); // // textBoxHomepageUrl // this.textBoxHomepageUrl.Location = new System.Drawing.Point(20, 74); this.textBoxHomepageUrl.Name = "textBoxHomepageUrl"; this.textBoxHomepageUrl.Size = new System.Drawing.Size(275, 22); this.textBoxHomepageUrl.TabIndex = 2; this.textBoxHomepageUrl.Enter += new System.EventHandler(this.textBoxHomepageUrl_Enter); this.textBoxHomepageUrl.Leave += new System.EventHandler(this.textBoxHomepageUrl_Leave); // // labelHomepageUrl // this.labelHomepageUrl.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelHomepageUrl.Location = new System.Drawing.Point(20, 0); this.labelHomepageUrl.Name = "labelHomepageUrl"; this.labelHomepageUrl.Size = new System.Drawing.Size(167, 13); this.labelHomepageUrl.TabIndex = 1; this.labelHomepageUrl.Text = "Web &address of your blog:"; // // WeblogConfigurationWizardPanelSharePointBasicInfo // this.Name = "WeblogConfigurationWizardPanelSharePointBasicInfo"; this.Size = new System.Drawing.Size(432, 244); this.panelMain.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void textBoxHomepageUrl_Enter(object sender, EventArgs e) { textBoxHomepageUrl.SelectAll(); } private void textBoxHomepageUrl_Leave(object sender, EventArgs e) { // adds http:// if necessary HomepageUrl = HomepageUrl; } } }
//------------------------------------------------------------------------------ // <copyright file="AssetVocabularyService.cs"> // Copyright (c) 2014-present Andrea Di Giorgi // // 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> // <author>Andrea Di Giorgi</author> // <website>https://github.com/Ithildir/liferay-sdk-builder-windows</website> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Liferay.SDK.Service.V62.AssetVocabulary { public class AssetVocabularyService : ServiceBase { public AssetVocabularyService(ISession session) : base(session) { } public async Task<dynamic> AddVocabularyAsync(string title, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("title", title); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/assetvocabulary/add-vocabulary", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> AddVocabularyAsync(IDictionary<string, string> titleMap, IDictionary<string, string> descriptionMap, string settings, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("titleMap", titleMap); _parameters.Add("descriptionMap", descriptionMap); _parameters.Add("settings", settings); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/assetvocabulary/add-vocabulary", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> AddVocabularyAsync(string title, IDictionary<string, string> titleMap, IDictionary<string, string> descriptionMap, string settings, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("title", title); _parameters.Add("titleMap", titleMap); _parameters.Add("descriptionMap", descriptionMap); _parameters.Add("settings", settings); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/assetvocabulary/add-vocabulary", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task DeleteVocabulariesAsync(IEnumerable<long> vocabularyIds) { var _parameters = new JsonObject(); _parameters.Add("vocabularyIds", vocabularyIds); var _command = new JsonObject() { { "/assetvocabulary/delete-vocabularies", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task<IEnumerable<dynamic>> DeleteVocabulariesAsync(IEnumerable<long> vocabularyIds, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("vocabularyIds", vocabularyIds); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/assetvocabulary/delete-vocabularies", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task DeleteVocabularyAsync(long vocabularyId) { var _parameters = new JsonObject(); _parameters.Add("vocabularyId", vocabularyId); var _command = new JsonObject() { { "/assetvocabulary/delete-vocabulary", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task<IEnumerable<dynamic>> GetCompanyVocabulariesAsync(long companyId) { var _parameters = new JsonObject(); _parameters.Add("companyId", companyId); var _command = new JsonObject() { { "/assetvocabulary/get-company-vocabularies", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetGroupVocabulariesAsync(long groupId) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); var _command = new JsonObject() { { "/assetvocabulary/get-group-vocabularies", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetGroupVocabulariesAsync(long groupId, bool createDefaultVocabulary) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("createDefaultVocabulary", createDefaultVocabulary); var _command = new JsonObject() { { "/assetvocabulary/get-group-vocabularies", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetGroupVocabulariesAsync(long groupId, int start, int end, JsonObjectWrapper obc) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("start", start); _parameters.Add("end", end); this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc); var _command = new JsonObject() { { "/assetvocabulary/get-group-vocabularies", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetGroupVocabulariesAsync(long groupId, string name, int start, int end, JsonObjectWrapper obc) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("name", name); _parameters.Add("start", start); _parameters.Add("end", end); this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc); var _command = new JsonObject() { { "/assetvocabulary/get-group-vocabularies", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<long> GetGroupVocabulariesCountAsync(long groupId) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); var _command = new JsonObject() { { "/assetvocabulary/get-group-vocabularies-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<long> GetGroupVocabulariesCountAsync(long groupId, string name) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("name", name); var _command = new JsonObject() { { "/assetvocabulary/get-group-vocabularies-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<dynamic> GetGroupVocabulariesDisplayAsync(long groupId, string name, int start, int end, JsonObjectWrapper obc) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("name", name); _parameters.Add("start", start); _parameters.Add("end", end); this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc); var _command = new JsonObject() { { "/assetvocabulary/get-group-vocabularies-display", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> GetGroupVocabulariesDisplayAsync(long groupId, string name, int start, int end, bool addDefaultVocabulary, JsonObjectWrapper obc) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("name", name); _parameters.Add("start", start); _parameters.Add("end", end); _parameters.Add("addDefaultVocabulary", addDefaultVocabulary); this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc); var _command = new JsonObject() { { "/assetvocabulary/get-group-vocabularies-display", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<IEnumerable<dynamic>> GetGroupsVocabulariesAsync(IEnumerable<long> groupIds) { var _parameters = new JsonObject(); _parameters.Add("groupIds", groupIds); var _command = new JsonObject() { { "/assetvocabulary/get-groups-vocabularies", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetGroupsVocabulariesAsync(IEnumerable<long> groupIds, string className) { var _parameters = new JsonObject(); _parameters.Add("groupIds", groupIds); _parameters.Add("className", className); var _command = new JsonObject() { { "/assetvocabulary/get-groups-vocabularies", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<dynamic> GetJsonGroupVocabulariesAsync(long groupId, string name, int start, int end, JsonObjectWrapper obc) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("name", name); _parameters.Add("start", start); _parameters.Add("end", end); this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc); var _command = new JsonObject() { { "/assetvocabulary/get-json-group-vocabularies", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<IEnumerable<dynamic>> GetVocabulariesAsync(IEnumerable<long> vocabularyIds) { var _parameters = new JsonObject(); _parameters.Add("vocabularyIds", vocabularyIds); var _command = new JsonObject() { { "/assetvocabulary/get-vocabularies", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<dynamic> GetVocabularyAsync(long vocabularyId) { var _parameters = new JsonObject(); _parameters.Add("vocabularyId", vocabularyId); var _command = new JsonObject() { { "/assetvocabulary/get-vocabulary", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> UpdateVocabularyAsync(long vocabularyId, IDictionary<string, string> titleMap, IDictionary<string, string> descriptionMap, string settings, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("vocabularyId", vocabularyId); _parameters.Add("titleMap", titleMap); _parameters.Add("descriptionMap", descriptionMap); _parameters.Add("settings", settings); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/assetvocabulary/update-vocabulary", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> UpdateVocabularyAsync(long vocabularyId, string title, IDictionary<string, string> titleMap, IDictionary<string, string> descriptionMap, string settings, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("vocabularyId", vocabularyId); _parameters.Add("title", title); _parameters.Add("titleMap", titleMap); _parameters.Add("descriptionMap", descriptionMap); _parameters.Add("settings", settings); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/assetvocabulary/update-vocabulary", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } } }
using System; using System.Collections.Generic; using FluentAssertions; using System.Linq; using Xunit; using Xunit.Abstractions; using static Pocket.Logger; using static Pocket.LogEvents; namespace Pocket.Tests { public class LoggerTests : IDisposable { private readonly IDisposable disposables; public LoggerTests(ITestOutputHelper output) { disposables = Subscribe(e => output.WriteLine(e.ToLogString(), false)); } public void Dispose() { disposables.Dispose(); } [Fact] public void Subscribe_allows_all_log_events_to_be_monitored() { var log = new LogEntryList(); using (Subscribe(log.Add)) { Log.Info("hello"); } log.Should() .ContainSingle(e => e.Evaluate() .Message .Contains("hello")); } [Fact] public void Exceptions_thrown_by_subscribers_are_not_thrown_to_the_caller() { using (Subscribe(_ => throw new Exception("drat!"))) { Log.Info("hello"); } } [Fact] public void Further_log_entries_are_not_received_after_disposing_the_subscription() { var log = new LogEntryList(); using (Subscribe(log.Add)) { } Log.Info("hello"); log.Should() .BeEmpty(); } [Fact] public void When_args_are_logged_then_they_are_templated_into_the_message() { var log = new LogEntryList(); using (Subscribe(log.Add)) { Log.Info("It's {time} and all is {how}", DateTimeOffset.Parse("12/12/2012 12:00am"), "well"); } log.Single() .Evaluate() .Message .Should() .Match("*It's 12/12/*12 12:00:00 AM * and all is well*"); } [Fact] public void When_args_are_logged_they_are_accessble_on_the_LogEntry() { var log = new LogEntryList(); using (Subscribe(log.Add)) { Log.Info("It's 12 o'clock and all is {how}", "well"); } log.Single() .Evaluate() .Properties .Should() .ContainSingle(p => p.Name.Equals("how") && p.Value.Equals("well")); } [Fact] public void When_exceptions_are_logged_then_the_message_contains_the_exception_details() { var log = new LogEntryList(); var exception = new Exception("oops!"); using (Subscribe(log.Add)) { Log.Error("oh no!", exception); } log.Single() .ToString() .Should() .Contain(exception.ToString()); } [Fact] public void When_exceptions_are_logged_then_they_are_accessible_on_the_LogEntry() { var log = new LogEntryList(); var exception = new Exception("oops!"); using (Subscribe(log.Add)) { Log.Error("oh no!", exception); } log.Single() .Exception .Should() .Be(exception); } [Fact] public void Logs_can_be_written_at_Info_level() { var log = new LogEntryList(); using (Subscribe(log.Add)) { Log.Info("hello"); } log.Single().LogLevel.Should().Be((int) LogLevel.Information); } [Fact] public void Logs_can_be_written_at_Warning_level() { var log = new LogEntryList(); using (Subscribe(log.Add)) { Log.Warning("hello", new Exception("oops")); } log.Single().LogLevel.Should().Be((int) LogLevel.Warning); log.Single().Exception.Should().NotBeNull(); } [Fact] public void Exceptions_can_be_written_at_Warning_level() { var log = new LogEntryList(); using (Subscribe(log.Add)) { Log.Warning(new Exception("oops")); } log.Single().LogLevel.Should().Be((int) LogLevel.Warning); log.Single().Exception.Should().NotBeNull(); } [Fact] public void Logs_can_be_written_at_Error_level() { var log = new LogEntryList(); using (Subscribe(log.Add)) { Log.Error("oops!", new Exception("something went wrong...")); } log.Single().LogLevel.Should().Be((int) LogLevel.Error); log.Single().Exception.Should().NotBeNull(); } [Fact] public void Exceptions_can_be_written_at_Error_level() { var log = new LogEntryList(); using (Subscribe(log.Add)) { Log.Error(new Exception("oops")); } log.Single().LogLevel.Should().Be((int) LogLevel.Error); log.Single().Exception.Should().NotBeNull(); } [Fact] public void Logger_T_captures_a_category_based_on_type_T() { var logger = new Logger<LoggerTests>(); var log = new LogEntryList(); using (Subscribe(log.Add)) { logger.Info("hello"); } log.Should().Contain(e => e.Category == typeof(LoggerTests).FullName); } [Fact] public void Default_logger_has_no_category() { var log = new LogEntryList(); using (Subscribe(log.Add)) { new Logger().Info("hello"); Log.Info("hello"); } log.Should().OnlyContain(e => e.Category == ""); } [Fact] public void Log_entries_have_no_duration() { var log = new LogEntryList(); using (Subscribe(log.Add)) { Log.Info("hello"); } log.Should().OnlyContain(e => e.Operation.Duration == null); log[0].ToLogString().Should().NotContain("ms)"); } [Fact] public void Event_metrics_are_written_to_string_output() { var log = new List<string>(); using (Subscribe(e => log.Add(e.ToLogString()))) { Log.Event("some-event", metrics: ("some-metric", 12345)); } log[0].Should().Contain("some-metric"); log[0].Should().Contain("12345"); } [Fact] public void Event_properties_are_written_to_string_output() { var log = new List<string>(); using (Subscribe(e => log.Add(e.ToLogString()))) { // Log.Info("this", "some-property", "hi!"); Log.Event("some-event", properties: ("some-property", "hi!")); } log[0].Should().Contain("some-property"); log[0].Should().Contain("hi!"); } } }
using Kitware.VTK; using System; // input file is C:\VTK\Graphics\Testing\Tcl\TestSplineFilter.tcl // output file is AVTestSplineFilter.cs /// <summary> /// The testing class derived from AVTestSplineFilter /// </summary> public class AVTestSplineFilterClass { /// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVTestSplineFilter(String [] argv) { //Prefix Content is: "" // Create the RenderWindow, Renderer and both Actors[] //[] ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer((vtkRenderer)ren1); iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow((vtkRenderWindow)renWin); // create pipeline[] //[] pl3d = new vtkPLOT3DReader(); pl3d.SetXYZFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combxyz.bin"); pl3d.SetQFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combq.bin"); pl3d.SetScalarFunctionNumber((int)100); pl3d.SetVectorFunctionNumber((int)202); pl3d.Update(); ps = new vtkPlaneSource(); ps.SetXResolution((int)4); ps.SetYResolution((int)4); ps.SetOrigin((double)2,(double)-2,(double)26); ps.SetPoint1((double)2,(double)2,(double)26); ps.SetPoint2((double)2,(double)-2,(double)32); psMapper = vtkPolyDataMapper.New(); psMapper.SetInputConnection((vtkAlgorithmOutput)ps.GetOutputPort()); psActor = new vtkActor(); psActor.SetMapper((vtkMapper)psMapper); psActor.GetProperty().SetRepresentationToWireframe(); rk4 = new vtkRungeKutta4(); streamer = new vtkStreamLine(); streamer.SetInputConnection((vtkAlgorithmOutput)pl3d.GetOutputPort()); streamer.SetSource((vtkDataSet)ps.GetOutput()); streamer.SetMaximumPropagationTime((double)100); streamer.SetIntegrationStepLength((double).2); streamer.SetStepLength((double).001); streamer.SetNumberOfThreads((int)1); streamer.SetIntegrationDirectionToForward(); streamer.VorticityOn(); streamer.SetIntegrator((vtkInitialValueProblemSolver)rk4); sf = new vtkSplineFilter(); sf.SetInputConnection((vtkAlgorithmOutput)streamer.GetOutputPort()); sf.SetSubdivideToLength(); sf.SetLength((double)0.15); rf = new vtkRibbonFilter(); rf.SetInputConnection((vtkAlgorithmOutput)sf.GetOutputPort()); rf.SetWidth((double)0.1); rf.SetWidthFactor((double)5); streamMapper = vtkPolyDataMapper.New(); streamMapper.SetInputConnection((vtkAlgorithmOutput)rf.GetOutputPort()); streamMapper.SetScalarRange((double)((vtkDataSet)pl3d.GetOutput()).GetScalarRange()[0], (double)((vtkDataSet)pl3d.GetOutput()).GetScalarRange()[1]); streamline = new vtkActor(); streamline.SetMapper((vtkMapper)streamMapper); outline = new vtkStructuredGridOutlineFilter(); outline.SetInputConnection((vtkAlgorithmOutput)pl3d.GetOutputPort()); outlineMapper = vtkPolyDataMapper.New(); outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort()); outlineActor = new vtkActor(); outlineActor.SetMapper((vtkMapper)outlineMapper); // Add the actors to the renderer, set the background and size[] //[] ren1.AddActor((vtkProp)psActor); ren1.AddActor((vtkProp)outlineActor); ren1.AddActor((vtkProp)streamline); ren1.SetBackground((double)1,(double)1,(double)1); renWin.SetSize((int)300,(int)300); ren1.SetBackground((double)0.1,(double)0.2,(double)0.4); cam1 = ren1.GetActiveCamera(); cam1.SetClippingRange((double)3.95297,(double)50); cam1.SetFocalPoint((double)9.71821,(double)0.458166,(double)29.3999); cam1.SetPosition((double)2.7439,(double)-37.3196,(double)38.7167); cam1.SetViewUp((double)-0.16123,(double)0.264271,(double)0.950876); // render the image[] //[] renWin.Render(); // prevent the tk window from showing up then start the event loop[] // for testing[] threshold = 15; //deleteAllVTKObjects(); } static string VTK_DATA_ROOT; static int threshold; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; static vtkPLOT3DReader pl3d; static vtkPlaneSource ps; static vtkPolyDataMapper psMapper; static vtkActor psActor; static vtkRungeKutta4 rk4; static vtkStreamLine streamer; static vtkSplineFilter sf; static vtkRibbonFilter rf; static vtkPolyDataMapper streamMapper; static vtkActor streamline; static vtkStructuredGridOutlineFilter outline; static vtkPolyDataMapper outlineMapper; static vtkActor outlineActor; static vtkCamera cam1; ///<summary> A Get Method for Static Variables </summary> public static string GetVTK_DATA_ROOT() { return VTK_DATA_ROOT; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_DATA_ROOT(string toSet) { VTK_DATA_ROOT = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getthreshold() { return threshold; } ///<summary> A Set Method for Static Variables </summary> public static void Setthreshold(int toSet) { threshold = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderer Getren1() { return ren1; } ///<summary> A Set Method for Static Variables </summary> public static void Setren1(vtkRenderer toSet) { ren1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindow GetrenWin() { return renWin; } ///<summary> A Set Method for Static Variables </summary> public static void SetrenWin(vtkRenderWindow toSet) { renWin = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindowInteractor Getiren() { return iren; } ///<summary> A Set Method for Static Variables </summary> public static void Setiren(vtkRenderWindowInteractor toSet) { iren = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPLOT3DReader Getpl3d() { return pl3d; } ///<summary> A Set Method for Static Variables </summary> public static void Setpl3d(vtkPLOT3DReader toSet) { pl3d = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPlaneSource Getps() { return ps; } ///<summary> A Set Method for Static Variables </summary> public static void Setps(vtkPlaneSource toSet) { ps = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetpsMapper() { return psMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetpsMapper(vtkPolyDataMapper toSet) { psMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetpsActor() { return psActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetpsActor(vtkActor toSet) { psActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRungeKutta4 Getrk4() { return rk4; } ///<summary> A Set Method for Static Variables </summary> public static void Setrk4(vtkRungeKutta4 toSet) { rk4 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStreamLine Getstreamer() { return streamer; } ///<summary> A Set Method for Static Variables </summary> public static void Setstreamer(vtkStreamLine toSet) { streamer = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkSplineFilter Getsf() { return sf; } ///<summary> A Set Method for Static Variables </summary> public static void Setsf(vtkSplineFilter toSet) { sf = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRibbonFilter Getrf() { return rf; } ///<summary> A Set Method for Static Variables </summary> public static void Setrf(vtkRibbonFilter toSet) { rf = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetstreamMapper() { return streamMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetstreamMapper(vtkPolyDataMapper toSet) { streamMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getstreamline() { return streamline; } ///<summary> A Set Method for Static Variables </summary> public static void Setstreamline(vtkActor toSet) { streamline = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridOutlineFilter Getoutline() { return outline; } ///<summary> A Set Method for Static Variables </summary> public static void Setoutline(vtkStructuredGridOutlineFilter toSet) { outline = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetoutlineMapper() { return outlineMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineMapper(vtkPolyDataMapper toSet) { outlineMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetoutlineActor() { return outlineActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineActor(vtkActor toSet) { outlineActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkCamera Getcam1() { return cam1; } ///<summary> A Set Method for Static Variables </summary> public static void Setcam1(vtkCamera toSet) { cam1 = toSet; } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if(ren1!= null){ren1.Dispose();} if(renWin!= null){renWin.Dispose();} if(iren!= null){iren.Dispose();} if(pl3d!= null){pl3d.Dispose();} if(ps!= null){ps.Dispose();} if(psMapper!= null){psMapper.Dispose();} if(psActor!= null){psActor.Dispose();} if(rk4!= null){rk4.Dispose();} if(streamer!= null){streamer.Dispose();} if(sf!= null){sf.Dispose();} if(rf!= null){rf.Dispose();} if(streamMapper!= null){streamMapper.Dispose();} if(streamline!= null){streamline.Dispose();} if(outline!= null){outline.Dispose();} if(outlineMapper!= null){outlineMapper.Dispose();} if(outlineActor!= null){outlineActor.Dispose();} if(cam1!= null){cam1.Dispose();} } } //--- end of script --//
--- /dev/null 2016-03-10 10:22:00.000000000 -0500 +++ src/System.IO.UnmanagedMemoryStream/src/SR.cs 2016-03-10 10:27:47.592043000 -0500 @@ -0,0 +1,334 @@ +using System; +using System.Resources; + +namespace FxResources.System.IO.UnmanagedMemoryStream +{ + internal static class SR + { + + } +} + +namespace System +{ + internal static class SR + { + private static ResourceManager s_resourceManager; + + private const String s_resourcesName = "FxResources.System.IO.UnmanagedMemoryStream.SR"; + + internal static String Arg_BadDecimal + { + get + { + return SR.GetResourceString("Arg_BadDecimal", null); + } + } + + internal static String Arg_BufferTooSmall + { + get + { + return SR.GetResourceString("Arg_BufferTooSmall", null); + } + } + + internal static String Argument_InvalidOffLen + { + get + { + return SR.GetResourceString("Argument_InvalidOffLen", null); + } + } + + internal static String Argument_InvalidSafeBufferOffLen + { + get + { + return SR.GetResourceString("Argument_InvalidSafeBufferOffLen", null); + } + } + + internal static String Argument_InvalidSeekOrigin + { + get + { + return SR.GetResourceString("Argument_InvalidSeekOrigin", null); + } + } + + internal static String Argument_NotEnoughBytesToRead + { + get + { + return SR.GetResourceString("Argument_NotEnoughBytesToRead", null); + } + } + + internal static String Argument_NotEnoughBytesToWrite + { + get + { + return SR.GetResourceString("Argument_NotEnoughBytesToWrite", null); + } + } + + internal static String Argument_OffsetAndCapacityOutOfBounds + { + get + { + return SR.GetResourceString("Argument_OffsetAndCapacityOutOfBounds", null); + } + } + + internal static String Argument_UnmanagedMemAccessorWrapAround + { + get + { + return SR.GetResourceString("Argument_UnmanagedMemAccessorWrapAround", null); + } + } + + internal static String ArgumentNull_Buffer + { + get + { + return SR.GetResourceString("ArgumentNull_Buffer", null); + } + } + + internal static String ArgumentOutOfRange_Enum + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_Enum", null); + } + } + + internal static String ArgumentOutOfRange_LengthGreaterThanCapacity + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity", null); + } + } + + internal static String ArgumentOutOfRange_NeedNonNegNum + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null); + } + } + + internal static String ArgumentOutOfRange_NeedPosNum + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedPosNum", null); + } + } + + internal static String ArgumentOutOfRange_PositionLessThanCapacityRequired + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired", null); + } + } + + internal static String ArgumentOutOfRange_StreamLength + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_StreamLength", null); + } + } + + internal static String ArgumentOutOfRange_UnmanagedMemStreamWrapAround + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround", null); + } + } + + internal static String IndexOutOfRange_UMSPosition + { + get + { + return SR.GetResourceString("IndexOutOfRange_UMSPosition", null); + } + } + + internal static String InvalidOperation_CalledTwice + { + get + { + return SR.GetResourceString("InvalidOperation_CalledTwice", null); + } + } + + internal static String IO_FixedCapacity + { + get + { + return SR.GetResourceString("IO_FixedCapacity", null); + } + } + + internal static String IO_SeekBeforeBegin + { + get + { + return SR.GetResourceString("IO_SeekBeforeBegin", null); + } + } + + internal static String IO_StreamTooLong + { + get + { + return SR.GetResourceString("IO_StreamTooLong", null); + } + } + + internal static String NotSupported_Reading + { + get + { + return SR.GetResourceString("NotSupported_Reading", null); + } + } + + internal static String NotSupported_UmsSafeBuffer + { + get + { + return SR.GetResourceString("NotSupported_UmsSafeBuffer", null); + } + } + + internal static String NotSupported_UnreadableStream + { + get + { + return SR.GetResourceString("NotSupported_UnreadableStream", null); + } + } + + internal static String NotSupported_UnwritableStream + { + get + { + return SR.GetResourceString("NotSupported_UnwritableStream", null); + } + } + + internal static String NotSupported_Writing + { + get + { + return SR.GetResourceString("NotSupported_Writing", null); + } + } + + internal static String ObjectDisposed_StreamIsClosed + { + get + { + return SR.GetResourceString("ObjectDisposed_StreamIsClosed", null); + } + } + + internal static String ObjectDisposed_ViewAccessorClosed + { + get + { + return SR.GetResourceString("ObjectDisposed_ViewAccessorClosed", null); + } + } + + private static ResourceManager ResourceManager + { + get + { + if (SR.s_resourceManager == null) + { + SR.s_resourceManager = new ResourceManager(SR.ResourceType); + } + return SR.s_resourceManager; + } + } + + internal static Type ResourceType + { + get + { + return typeof(FxResources.System.IO.UnmanagedMemoryStream.SR); + } + } + + internal static String Format(String resourceFormat, params Object[] args) + { + if (args == null) + { + return resourceFormat; + } + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, args); + } + return String.Concat(resourceFormat, String.Join(", ", args)); + } + + internal static String Format(String resourceFormat, Object p1) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1); + } + return String.Join(", ", new Object[] { resourceFormat, p1 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2, Object p3) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2, p3); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 }); + } + + internal static String GetResourceString(String resourceKey, String defaultString) + { + String str = null; + try + { + str = SR.ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException missingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(str)) + { + return defaultString; + } + return str; + } + + private static Boolean UsingResourceKeys() + { + return false; + } + } +}
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Threading.Tasks; using Orleans.Concurrency; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans.Streams { [Serializable] [Immutable] internal class StreamImpl<T> : IStreamIdentity, IAsyncStream<T>, IStreamControl, ISerializable, IOnDeserialized { private readonly StreamId streamId; private readonly bool isRewindable; [NonSerialized] private IInternalStreamProvider provider; [NonSerialized] private volatile IInternalAsyncBatchObserver<T> producerInterface; [NonSerialized] private IInternalAsyncObservable<T> consumerInterface; [NonSerialized] private readonly object initLock; // need the lock since the same code runs in the provider on the client and in the silo. [NonSerialized] private IRuntimeClient runtimeClient; internal StreamId StreamId { get { return streamId; } } public bool IsRewindable { get { return isRewindable; } } public Guid Guid { get { return streamId.Guid; } } public string Namespace { get { return streamId.Namespace; } } public string ProviderName { get { return streamId.ProviderName; } } // IMPORTANT: This constructor needs to be public for Json deserialization to work. public StreamImpl() { initLock = new object(); } internal StreamImpl(StreamId streamId, IInternalStreamProvider provider, bool isRewindable, IRuntimeClient runtimeClient) { if (null == streamId) throw new ArgumentNullException(nameof(streamId)); if (null == provider) throw new ArgumentNullException(nameof(provider)); if (null == runtimeClient) throw new ArgumentNullException(nameof(runtimeClient)); this.streamId = streamId; this.provider = provider; producerInterface = null; consumerInterface = null; initLock = new object(); this.isRewindable = isRewindable; this.runtimeClient = runtimeClient; } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer) { return GetConsumerInterface().SubscribeAsync(observer, null); } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer, StreamSequenceToken token, StreamFilterPredicate filterFunc = null, object filterData = null) { return GetConsumerInterface().SubscribeAsync(observer, token, filterFunc, filterData); } public async Task Cleanup(bool cleanupProducers, bool cleanupConsumers) { // Cleanup producers if (cleanupProducers && producerInterface != null) { await producerInterface.Cleanup(); producerInterface = null; } // Cleanup consumers if (cleanupConsumers && consumerInterface != null) { await consumerInterface.Cleanup(); consumerInterface = null; } } public Task OnNextAsync(T item, StreamSequenceToken token = null) { return GetProducerInterface().OnNextAsync(item, token); } public Task OnNextBatchAsync(IEnumerable<T> batch, StreamSequenceToken token = null) { return GetProducerInterface().OnNextBatchAsync(batch, token); } public Task OnCompletedAsync() { return GetProducerInterface().OnCompletedAsync(); } public Task OnErrorAsync(Exception ex) { return GetProducerInterface().OnErrorAsync(ex); } internal Task<StreamSubscriptionHandle<T>> ResumeAsync( StreamSubscriptionHandle<T> handle, IAsyncObserver<T> observer, StreamSequenceToken token) { return GetConsumerInterface().ResumeAsync(handle, observer, token); } public Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptionHandles() { return GetConsumerInterface().GetAllSubscriptions(); } internal Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle) { return GetConsumerInterface().UnsubscribeAsync(handle); } internal IAsyncBatchObserver<T> GetProducerInterface() { if (producerInterface != null) return producerInterface; lock (initLock) { if (producerInterface != null) return producerInterface; if (provider == null) provider = GetStreamProvider(); producerInterface = provider.GetProducerInterface<T>(this); } return producerInterface; } internal IInternalAsyncObservable<T> GetConsumerInterface() { if (consumerInterface == null) { lock (initLock) { if (consumerInterface == null) { if (provider == null) provider = GetStreamProvider(); consumerInterface = provider.GetConsumerInterface<T>(this); } } } return consumerInterface; } private IInternalStreamProvider GetStreamProvider() { return this.runtimeClient.CurrentStreamProviderManager.GetProvider(streamId.ProviderName) as IInternalStreamProvider; } #region IComparable<IAsyncStream<T>> Members public int CompareTo(IAsyncStream<T> other) { var o = other as StreamImpl<T>; return o == null ? 1 : streamId.CompareTo(o.streamId); } #endregion #region IEquatable<IAsyncStream<T>> Members public virtual bool Equals(IAsyncStream<T> other) { var o = other as StreamImpl<T>; return o != null && streamId.Equals(o.streamId); } #endregion public override bool Equals(object obj) { var o = obj as StreamImpl<T>; return o != null && streamId.Equals(o.streamId); } public override int GetHashCode() { return streamId.GetHashCode(); } public override string ToString() { return streamId.ToString(); } #region ISerializable Members public void GetObjectData(SerializationInfo info, StreamingContext context) { // Use the AddValue method to specify serialized values. info.AddValue("StreamId", streamId, typeof(StreamId)); info.AddValue("IsRewindable", isRewindable, typeof(bool)); } // The special constructor is used to deserialize values. protected StreamImpl(SerializationInfo info, StreamingContext context) { // Reset the property value using the GetValue method. streamId = (StreamId)info.GetValue("StreamId", typeof(StreamId)); isRewindable = info.GetBoolean("IsRewindable"); initLock = new object(); #if !NETSTANDARD_TODO this.OnDeserialized(context); #endif } #if !NETSTANDARD_TODO /// <summary> /// Called by BinaryFormatter after deserialization has completed. /// </summary> /// <param name="context">The context.</param> [OnDeserialized] private void OnDeserialized(StreamingContext context) { var serializerContext = context.Context as ISerializerContext; ((IOnDeserialized)this).OnDeserialized(serializerContext); } #endif void IOnDeserialized.OnDeserialized(ISerializerContext context) { this.runtimeClient = context?.AdditionalContext as IRuntimeClient; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Serialization { using System.Reflection; using System.Collections; using System.IO; using System.Xml.Schema; using System; using System.Text; using System.Threading; using System.Globalization; using System.Security; using System.Security.Policy; using System.Xml.Serialization.Configuration; using System.Diagnostics; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Versioning; /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public struct XmlDeserializationEvents { private XmlNodeEventHandler _onUnknownNode; private XmlAttributeEventHandler _onUnknownAttribute; private XmlElementEventHandler _onUnknownElement; private UnreferencedObjectEventHandler _onUnreferencedObject; internal object sender; /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownNode"]/*' /> public XmlNodeEventHandler OnUnknownNode { get { return _onUnknownNode; } set { _onUnknownNode = value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownAttribute"]/*' /> public XmlAttributeEventHandler OnUnknownAttribute { get { return _onUnknownAttribute; } set { _onUnknownAttribute = value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownElement"]/*' /> public XmlElementEventHandler OnUnknownElement { get { return _onUnknownElement; } set { _onUnknownElement = value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnreferencedObject"]/*' /> public UnreferencedObjectEventHandler OnUnreferencedObject { get { return _onUnreferencedObject; } set { _onUnreferencedObject = value; } } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation"]/*' /> ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract class XmlSerializerImplementation { /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Reader"]/*' /> public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Writer"]/*' /> public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.ReadMethods"]/*' /> public virtual Hashtable ReadMethods { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.WriteMethods"]/*' /> public virtual Hashtable WriteMethods { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.TypedSerializers"]/*' /> public virtual Hashtable TypedSerializers { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.CanSerialize"]/*' /> public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.GetSerializer"]/*' /> public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlSerializer { private enum SerializationMode { CodeGenOnly, ReflectionOnly, ReflectionAsBackup } private SerializationMode Mode { get; set; } = SerializationMode.ReflectionAsBackup; private bool ReflectionMethodEnabled { get { return Mode == SerializationMode.ReflectionOnly || Mode == SerializationMode.ReflectionAsBackup; } } private TempAssembly _tempAssembly; #pragma warning disable 0414 private bool _typedSerializer; #pragma warning restore 0414 private Type _primitiveType; private XmlMapping _mapping; private XmlDeserializationEvents _events = new XmlDeserializationEvents(); #if NET_NATIVE private XmlSerializer innerSerializer; #endif public string DefaultNamespace = null; private Type rootType; private static TempAssemblyCache s_cache = new TempAssemblyCache(); private static volatile XmlSerializerNamespaces s_defaultNamespaces; private static XmlSerializerNamespaces DefaultNamespaces { get { if (s_defaultNamespaces == null) { XmlSerializerNamespaces nss = new XmlSerializerNamespaces(); nss.AddInternal("xsi", XmlSchema.InstanceNamespace); nss.AddInternal("xsd", XmlSchema.Namespace); if (s_defaultNamespaces == null) { s_defaultNamespaces = nss; } } return s_defaultNamespaces; } } private static readonly Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>> s_xmlSerializerTable = new Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>>(); /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer8"]/*' /> ///<internalonly/> protected XmlSerializer() { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) : this(type, overrides, extraTypes, root, defaultNamespace, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> #if !NET_NATIVE public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null) #else public XmlSerializer(Type type, Type[] extraTypes) : this(type) #endif { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(XmlTypeMapping xmlTypeMapping) { if (xmlTypeMapping == null) throw new ArgumentNullException(nameof(xmlTypeMapping)); #if !NET_NATIVE _tempAssembly = GenerateTempAssembly(xmlTypeMapping); #endif _mapping = xmlTypeMapping; } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer6"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type) : this(type, (string)null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, string defaultNamespace) { if (type == null) throw new ArgumentNullException(nameof(type)); DefaultNamespace = defaultNamespace; rootType = type; _mapping = GetKnownMapping(type, defaultNamespace); if (_mapping != null) { _primitiveType = type; return; } #if !NET_NATIVE _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { lock (s_cache) { _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { { // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); } } s_cache.Add(defaultNamespace, type, _tempAssembly); } } if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } #else XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly(); if (contract != null) { this.innerSerializer = contract.GetSerializer(type); } else if (ReflectionMethodEnabled) { var importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } } #endif } public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location) #pragma warning disable 618 // Passing through null evidence to keep the .ctor code centralized : this(type, overrides, extraTypes, root, defaultNamespace, location, null) { #pragma warning restore 618 } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> internal XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location, Evidence evidence) { if (type == null) throw new ArgumentNullException(nameof(type)); DefaultNamespace = defaultNamespace; rootType = type; XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) { for (int i = 0; i < extraTypes.Length; i++) importer.IncludeType(extraTypes[i]); } _mapping = importer.ImportTypeMapping(type, root, defaultNamespace); if (location != null || evidence != null) { DemandForUserLocationOrEvidence(); } #if !NET_NATIVE _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location, evidence); #endif } private void DemandForUserLocationOrEvidence() { // Ensure full trust before asserting full file access to the user-provided location or evidence } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping) { return GenerateTempAssembly(xmlMapping, null, null); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace) { if (xmlMapping == null) throw new ArgumentNullException(nameof(xmlMapping)); return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, null, null); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace, string location, Evidence evidence) { return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, location, evidence); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(TextWriter textWriter, object o) { Serialize(textWriter, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(textWriter); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 2; Serialize(xmlWriter, o, namespaces); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(Stream stream, object o) { Serialize(stream, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(stream, null); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 2; Serialize(xmlWriter, o, namespaces); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(XmlWriter xmlWriter, object o) { Serialize(xmlWriter, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) { Serialize(xmlWriter, o, namespaces, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' /> public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle) { Serialize(xmlWriter, o, namespaces, encodingStyle, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' /> public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { try { if (_primitiveType != null) { if (encodingStyle != null && encodingStyle.Length > 0) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } SerializePrimitive(xmlWriter, o, namespaces); } #if !NET_NATIVE else if (Mode == SerializationMode.ReflectionOnly) { XmlMapping mapping; if (_mapping != null && _mapping.GenerateSerializer) { mapping = _mapping; } else { XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace); mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace); } var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); writer.WriteObject(o); } else if (_tempAssembly == null || _typedSerializer) { // The contion for the block is never true, thus the block is never hit. XmlSerializationWriter writer = CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly); try { Serialize(o, writer); } finally { writer.Dispose(); } } else _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); #else else { if (this.innerSerializer != null) { if (!string.IsNullOrEmpty(this.DefaultNamespace)) { this.innerSerializer.DefaultNamespace = this.DefaultNamespace; } XmlSerializationWriter writer = this.innerSerializer.CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); try { this.innerSerializer.Serialize(o, writer); } finally { writer.Dispose(); } } else if (ReflectionMethodEnabled) { XmlMapping mapping; if (_mapping != null && _mapping.GenerateSerializer) { mapping = _mapping; } else { XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace); mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace); } var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); writer.WriteObject(o); } else { throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name)); } } #endif } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; throw new InvalidOperationException(SR.XmlGenError, e); } xmlWriter.Flush(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(Stream stream) { XmlTextReader xmlReader = new XmlTextReader(stream); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; xmlReader.Normalization = true; xmlReader.XmlResolver = null; return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(TextReader textReader) { XmlTextReader xmlReader = new XmlTextReader(textReader); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; xmlReader.Normalization = true; xmlReader.XmlResolver = null; return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(XmlReader xmlReader) { return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize3"]/*' /> public object Deserialize(XmlReader xmlReader, XmlDeserializationEvents events) { return Deserialize(xmlReader, null, events); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' /> public object Deserialize(XmlReader xmlReader, string encodingStyle) { return Deserialize(xmlReader, encodingStyle, _events); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize5"]/*' /> public object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) { events.sender = this; try { if (_primitiveType != null) { if (encodingStyle != null && encodingStyle.Length > 0) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } return DeserializePrimitive(xmlReader, events); } #if !NET_NATIVE else if (Mode == SerializationMode.ReflectionOnly) { XmlMapping mapping; if (_mapping != null && _mapping.GenerateSerializer) { mapping = _mapping; } else { XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace); mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace); } var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle); return reader.ReadObject(); } else if (_tempAssembly == null || _typedSerializer) { XmlSerializationReader reader = CreateReader(); reader.Init(xmlReader, events, encodingStyle, _tempAssembly); try { return Deserialize(reader); } finally { reader.Dispose(); } } else { return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle); } #else else { if (this.innerSerializer != null) { if (!string.IsNullOrEmpty(this.DefaultNamespace)) { this.innerSerializer.DefaultNamespace = this.DefaultNamespace; } XmlSerializationReader reader = this.innerSerializer.CreateReader(); reader.Init(xmlReader, encodingStyle); try { return this.innerSerializer.Deserialize(reader); } finally { reader.Dispose(); } } else if (ReflectionMethodEnabled) { XmlMapping mapping; if (_mapping != null && _mapping.GenerateSerializer) { mapping = _mapping; } else { XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace); mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace); } var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle); return reader.ReadObject(); } else { throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name)); } } #endif } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; if (xmlReader is IXmlLineInfo) { IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader; throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e); } else { throw new InvalidOperationException(SR.XmlSerializeError, e); } } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CanDeserialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual bool CanDeserialize(XmlReader xmlReader) { if (_primitiveType != null) { TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]; return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty); } #if !NET_NATIVE else if (_tempAssembly != null) { return _tempAssembly.CanRead(_mapping, xmlReader); } else { return false; } #else if (this.innerSerializer != null) { return this.innerSerializer.CanDeserialize(xmlReader); } else { return ReflectionMethodEnabled; } #endif } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromMappings(XmlMapping[] mappings) { return FromMappings(mappings, (Type)null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>(); #if NET_NATIVE var serializers = new XmlSerializer[mappings.Length]; for(int i=0;i<mappings.Length;i++) { serializers[i] = new XmlSerializer(); serializers[i].rootType = type; serializers[i]._mapping = mappings[i]; } return serializers; #else XmlSerializerImplementation contract = null; Assembly assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); TempAssembly tempAssembly = null; if (assembly == null) { if (XmlMapping.IsShallow(mappings)) { return Array.Empty<XmlSerializer>(); } else { if (type == null) { tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null, null); XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; contract = tempAssembly.Contract; for (int i = 0; i < serializers.Length; i++) { serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; serializers[i].SetTempAssembly(tempAssembly, mappings[i]); } return serializers; } else { // Use XmlSerializer cache when the type is not null. return GetSerializersFromCache(mappings, type); } } } else { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; return serializers; } #endif } private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type) { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; Dictionary<XmlSerializerMappingKey, XmlSerializer> typedMappingTable = null; lock (s_xmlSerializerTable) { if (!s_xmlSerializerTable.TryGetValue(type, out typedMappingTable)) { typedMappingTable = new Dictionary<XmlSerializerMappingKey, XmlSerializer>(); s_xmlSerializerTable[type] = typedMappingTable; } } lock (typedMappingTable) { var pendingKeys = new Dictionary<XmlSerializerMappingKey, int>(); for (int i = 0; i < mappings.Length; i++) { XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]); if (!typedMappingTable.TryGetValue(mappingKey, out serializers[i])) { pendingKeys.Add(mappingKey, i); } } if (pendingKeys.Count > 0) { XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count]; int index = 0; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { pendingMappings[index++] = mappingKey.Mapping; } TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null, null); XmlSerializerImplementation contract = tempAssembly.Contract; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { index = pendingKeys[mappingKey]; serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key]; serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping); typedMappingTable[mappingKey] = serializers[index]; } } } return serializers; } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GenerateSerializer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Assembly GenerateSerializer(Type[] types, XmlMapping[] mappings) { CompilerParameters parameters = new CompilerParameters(); parameters.TempFiles = new TempFileCollection(); parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = false; return GenerateSerializer(types, mappings, parameters); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GenerateSerializer1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. internal static Assembly GenerateSerializer(Type[] types, XmlMapping[] mappings, CompilerParameters parameters) { if (types == null || types.Length == 0) return null; if (mappings == null) throw new ArgumentNullException(nameof(mappings)); if (XmlMapping.IsShallow(mappings)) { throw new InvalidOperationException(SR.XmlMelformMapping); } Assembly assembly = null; for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, type.FullName)); } if (assembly == null) assembly = type.GetTypeInfo().Assembly; else if (type.GetTypeInfo().Assembly != assembly) { throw new ArgumentException(SR.Format(SR.XmlPregenOrphanType, type.FullName/*, assembly.Location*/), "types"); } } return TempAssembly.GenerateAssembly(mappings, types, null, null, XmlSerializerCompilerParameters.Create(parameters, /* needTempDirAccess = */ true), assembly, new Hashtable()); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromTypes(Type[] types) { if (types == null) return Array.Empty<XmlSerializer>(); #if NET_NATIVE var serializers = new XmlSerializer[types.Length]; for (int i = 0; i < types.Length; i++) { serializers[i] = new XmlSerializer(types[i]); } return serializers; #else XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length]; for (int i = 0; i < types.Length; i++) { mappings[i] = importer.ImportTypeMapping(types[i]); } return FromMappings(mappings); #endif } #if NET_NATIVE // this the global XML serializer contract introduced for multi-file private static XmlSerializerImplementation xmlSerializerContract; internal static XmlSerializerImplementation GetXmlSerializerContractFromGeneratedAssembly() { // hack to pull in SetXmlSerializerContract which is only referenced from the // code injected by MainMethodInjector transform // there's probably also a way to do this via [DependencyReductionRoot], // but I can't get the compiler to find that... if (xmlSerializerContract == null) SetXmlSerializerContract(null); // this method body used to be rewritten by an IL transform // with the restructuring for multi-file, it has become a regular method return xmlSerializerContract; } public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation) { xmlSerializerContract = xmlSerializerImplementation; } #endif /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GetXmlSerializerAssemblyName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string GetXmlSerializerAssemblyName(Type type) { return GetXmlSerializerAssemblyName(type, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GetXmlSerializerAssemblyName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace) { if (type == null) { throw new ArgumentNullException(nameof(type)); } return Compiler.GetTempAssemblyName(type.GetTypeInfo().Assembly.GetName(), defaultNamespace); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownNode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event XmlNodeEventHandler UnknownNode { add { _events.OnUnknownNode += value; } remove { _events.OnUnknownNode -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event XmlAttributeEventHandler UnknownAttribute { add { _events.OnUnknownAttribute += value; } remove { _events.OnUnknownAttribute -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownElement"]/*' /> public event XmlElementEventHandler UnknownElement { add { _events.OnUnknownElement += value; } remove { _events.OnUnknownElement -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnreferencedObject"]/*' /> public event UnreferencedObjectEventHandler UnreferencedObject { add { _events.OnUnreferencedObject += value; } remove { _events.OnUnreferencedObject -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateReader"]/*' /> ///<internalonly/> protected virtual XmlSerializationReader CreateReader() { throw new PlatformNotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' /> ///<internalonly/> protected virtual object Deserialize(XmlSerializationReader reader) { throw new PlatformNotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateWriter"]/*' /> ///<internalonly/> protected virtual XmlSerializationWriter CreateWriter() { throw new PlatformNotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize7"]/*' /> ///<internalonly/> protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new PlatformNotSupportedException(); } internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) { _tempAssembly = tempAssembly; _mapping = mapping; _typedSerializer = true; } private static XmlTypeMapping GetKnownMapping(Type type, string ns) { if (ns != null && ns != string.Empty) return null; TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[type]; if (typeDesc == null) return null; ElementAccessor element = new ElementAccessor(); element.Name = typeDesc.DataType.Name; XmlTypeMapping mapping = new XmlTypeMapping(null, element); mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null)); return mapping; } private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) { XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter(); writer.Init(xmlWriter, namespaces, null, null, null); switch (_primitiveType.GetTypeCode()) { case TypeCode.String: writer.Write_string(o); break; case TypeCode.Int32: writer.Write_int(o); break; case TypeCode.Boolean: writer.Write_boolean(o); break; case TypeCode.Int16: writer.Write_short(o); break; case TypeCode.Int64: writer.Write_long(o); break; case TypeCode.Single: writer.Write_float(o); break; case TypeCode.Double: writer.Write_double(o); break; case TypeCode.Decimal: writer.Write_decimal(o); break; case TypeCode.DateTime: writer.Write_dateTime(o); break; case TypeCode.Char: writer.Write_char(o); break; case TypeCode.Byte: writer.Write_unsignedByte(o); break; case TypeCode.SByte: writer.Write_byte(o); break; case TypeCode.UInt16: writer.Write_unsignedShort(o); break; case TypeCode.UInt32: writer.Write_unsignedInt(o); break; case TypeCode.UInt64: writer.Write_unsignedLong(o); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { writer.Write_QName(o); } else if (_primitiveType == typeof(byte[])) { writer.Write_base64Binary(o); } else if (_primitiveType == typeof(Guid)) { writer.Write_guid(o); } else if (_primitiveType == typeof(TimeSpan)) { writer.Write_TimeSpan(o); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); } break; } } private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) { XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader(); reader.Init(xmlReader, events, null, null); object o; switch (_primitiveType.GetTypeCode()) { case TypeCode.String: o = reader.Read_string(); break; case TypeCode.Int32: o = reader.Read_int(); break; case TypeCode.Boolean: o = reader.Read_boolean(); break; case TypeCode.Int16: o = reader.Read_short(); break; case TypeCode.Int64: o = reader.Read_long(); break; case TypeCode.Single: o = reader.Read_float(); break; case TypeCode.Double: o = reader.Read_double(); break; case TypeCode.Decimal: o = reader.Read_decimal(); break; case TypeCode.DateTime: o = reader.Read_dateTime(); break; case TypeCode.Char: o = reader.Read_char(); break; case TypeCode.Byte: o = reader.Read_unsignedByte(); break; case TypeCode.SByte: o = reader.Read_byte(); break; case TypeCode.UInt16: o = reader.Read_unsignedShort(); break; case TypeCode.UInt32: o = reader.Read_unsignedInt(); break; case TypeCode.UInt64: o = reader.Read_unsignedLong(); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { o = reader.Read_QName(); } else if (_primitiveType == typeof(byte[])) { o = reader.Read_base64Binary(); } else if (_primitiveType == typeof(Guid)) { o = reader.Read_guid(); } else if (_primitiveType == typeof(TimeSpan)) { o = reader.Read_TimeSpan(); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); } break; } return o; } private class XmlSerializerMappingKey { public XmlMapping Mapping; public XmlSerializerMappingKey(XmlMapping mapping) { this.Mapping = mapping; } public override bool Equals(object obj) { XmlSerializerMappingKey other = obj as XmlSerializerMappingKey; if (other == null) return false; if (this.Mapping.Key != other.Mapping.Key) return false; if (this.Mapping.ElementName != other.Mapping.ElementName) return false; if (this.Mapping.Namespace != other.Mapping.Namespace) return false; if (this.Mapping.IsSoap != other.Mapping.IsSoap) return false; return true; } public override int GetHashCode() { int hashCode = this.Mapping.IsSoap ? 0 : 1; if (this.Mapping.Key != null) hashCode ^= this.Mapping.Key.GetHashCode(); if (this.Mapping.ElementName != null) hashCode ^= this.Mapping.ElementName.GetHashCode(); if (this.Mapping.Namespace != null) hashCode ^= this.Mapping.Namespace.GetHashCode(); return hashCode; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System { internal static class UriHelper { internal static ReadOnlySpan<byte> HexUpperChars => new byte[16] { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F' }; internal static readonly Encoding s_noFallbackCharUTF8 = Encoding.GetEncoding( Encoding.UTF8.CodePage, new EncoderReplacementFallback(""), new DecoderReplacementFallback("")); // http://host/Path/Path/File?Query is the base of // - http://host/Path/Path/File/ ... (those "File" words may be different in semantic but anyway) // - http://host/Path/Path/#Fragment // - http://host/Path/Path/?Query // - http://host/Path/Path/MoreDir/ ... // - http://host/Path/Path/OtherFile?Query // - http://host/Path/Path/Fl // - http://host/Path/Path/ // // It is not a base for // - http://host/Path/Path (that last "Path" is not considered as a directory) // - http://host/Path/Path?Query // - http://host/Path/Path#Fragment // - http://host/Path/Path2/ // - http://host/Path/Path2/MoreDir // - http://host/Path/File // // ASSUMES that strings like http://host/Path/Path/MoreDir/../../ have been canonicalized before going to this method. // ASSUMES that back slashes already have been converted if applicable. // internal static unsafe bool TestForSubPath(char* selfPtr, ushort selfLength, char* otherPtr, ushort otherLength, bool ignoreCase) { ushort i = 0; char chSelf; char chOther; bool AllSameBeforeSlash = true; for (; i < selfLength && i < otherLength; ++i) { chSelf = *(selfPtr + i); chOther = *(otherPtr + i); if (chSelf == '?' || chSelf == '#') { // survived so far and selfPtr does not have any more path segments return true; } // If selfPtr terminates a path segment, so must otherPtr if (chSelf == '/') { if (chOther != '/') { // comparison has failed return false; } // plus the segments must be the same if (!AllSameBeforeSlash) { // comparison has failed return false; } //so far so good AllSameBeforeSlash = true; continue; } // if otherPtr terminates then selfPtr must not have any more path segments if (chOther == '?' || chOther == '#') { break; } if (!ignoreCase) { if (chSelf != chOther) { AllSameBeforeSlash = false; } } else { if (char.ToLowerInvariant(chSelf) != char.ToLowerInvariant(chOther)) { AllSameBeforeSlash = false; } } } // If self is longer then it must not have any more path segments for (; i < selfLength; ++i) { if ((chSelf = *(selfPtr + i)) == '?' || chSelf == '#') { return true; } if (chSelf == '/') { return false; } } //survived by getting to the end of selfPtr return true; } internal static string EscapeString( string stringToEscape, // same name as public API bool checkExistingEscaped, ReadOnlySpan<bool> unreserved, char forceEscape1 = '\0', char forceEscape2 = '\0') { if (stringToEscape is null) { throw new ArgumentNullException(nameof(stringToEscape)); } if (stringToEscape.Length == 0) { return string.Empty; } // Get the table of characters that do not need to be escaped. Debug.Assert(unreserved.Length == 0x80); ReadOnlySpan<bool> noEscape = stackalloc bool[0]; if ((forceEscape1 | forceEscape2) == 0) { noEscape = unreserved; } else { Span<bool> tmp = stackalloc bool[0x80]; unreserved.CopyTo(tmp); tmp[forceEscape1] = false; tmp[forceEscape2] = false; noEscape = tmp; } // If the whole string is made up of ASCII unreserved chars, just return it. Debug.Assert(!noEscape['%'], "Need to treat % specially; it should be part of any escaped set"); int i = 0; char c; for (; i < stringToEscape.Length && (c = stringToEscape[i]) <= 0x7F && noEscape[c]; i++) ; if (i == stringToEscape.Length) { return stringToEscape; } // Otherwise, create a ValueStringBuilder to store the escaped data into, // append to it all of the noEscape chars we already iterated through, // escape the rest, and return the result as a string. var vsb = new ValueStringBuilder(stackalloc char[256]); vsb.Append(stringToEscape.AsSpan(0, i)); EscapeStringToBuilder(stringToEscape.AsSpan(i), ref vsb, noEscape, checkExistingEscaped); return vsb.ToString(); } // forceX characters are always escaped if found // destPos - starting offset in dest for output, on return this will be an exclusive "end" in the output. // In case "dest" has lack of space it will be reallocated by preserving the _whole_ content up to current destPos // Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos [return: NotNullIfNotNull("dest")] internal static char[]? EscapeString( ReadOnlySpan<char> stringToEscape, char[]? dest, ref int destPos, bool checkExistingEscaped, char forceEscape1 = '\0', char forceEscape2 = '\0') { // Get the table of characters that do not need to be escaped. ReadOnlySpan<bool> noEscape = stackalloc bool[0]; if ((forceEscape1 | forceEscape2) == 0) { noEscape = UnreservedReservedTable; } else { Span<bool> tmp = stackalloc bool[0x80]; UnreservedReservedTable.CopyTo(tmp); tmp[forceEscape1] = false; tmp[forceEscape2] = false; noEscape = tmp; } // If the whole string is made up of ASCII unreserved chars, take a fast pasth. Per the contract, if // dest is null, just return it. If it's not null, copy everything to it and update destPos accordingly; // if that requires resizing it, do so. Debug.Assert(!noEscape['%'], "Need to treat % specially in case checkExistingEscaped is true"); int i = 0; char c; for (; i < stringToEscape.Length && (c = stringToEscape[i]) <= 0x7F && noEscape[c]; i++) ; if (i == stringToEscape.Length) { if (dest != null) { EnsureCapacity(dest, destPos, stringToEscape.Length); stringToEscape.CopyTo(dest.AsSpan(destPos)); destPos += stringToEscape.Length; } return dest; } // Otherwise, create a ValueStringBuilder to store the escaped data into, // append to it all of the noEscape chars we already iterated through, and // escape the rest into the ValueStringBuilder. var vsb = new ValueStringBuilder(stackalloc char[256]); vsb.Append(stringToEscape.Slice(0, i)); EscapeStringToBuilder(stringToEscape.Slice(i), ref vsb, noEscape, checkExistingEscaped); // Finally update dest with the result. EnsureCapacity(dest, destPos, vsb.Length); vsb.TryCopyTo(dest.AsSpan(destPos), out int charsWritten); destPos += charsWritten; return dest; static void EnsureCapacity(char[]? dest, int destSize, int requiredSize) { if (dest == null || dest.Length - destSize < requiredSize) { Array.Resize(ref dest, destSize + requiredSize + 120); // 120 == arbitrary minimum-empty space copied from previous implementation } } } private static void EscapeStringToBuilder( ReadOnlySpan<char> stringToEscape, ref ValueStringBuilder vsb, ReadOnlySpan<bool> noEscape, bool checkExistingEscaped) { // Allocate enough stack space to hold any Rune's UTF8 encoding. Span<byte> utf8Bytes = stackalloc byte[4]; // Then enumerate every rune in the input. SpanRuneEnumerator e = stringToEscape.EnumerateRunes(); while (e.MoveNext()) { Rune r = e.Current; if (!r.IsAscii) { // The rune is non-ASCII, so encode it as UTF8, and escape each UTF8 byte. r.TryEncodeToUtf8(utf8Bytes, out int bytesWritten); foreach (byte b in utf8Bytes.Slice(0, bytesWritten)) { vsb.Append('%'); vsb.Append((char)HexUpperChars[(b & 0xf0) >> 4]); vsb.Append((char)HexUpperChars[b & 0xf]); } continue; } // If the value doesn't need to be escaped, append it and continue. byte value = (byte)r.Value; if (noEscape[value]) { vsb.Append((char)value); continue; } // If we're checking for existing escape sequences, then if this is the beginning of // one, check the next two characters in the sequence. This is a little tricky to do // as we're using an enumerator, but luckily it's a ref struct-based enumerator: we can // make a copy and iterate through the copy without impacting the original, and then only // push the original ahead if we find what we're looking for in the copy. if (checkExistingEscaped && value == '%') { // If the next two characters are valid escaped ASCII, then just output them as-is. SpanRuneEnumerator tmpEnumerator = e; if (tmpEnumerator.MoveNext()) { Rune r1 = tmpEnumerator.Current; if (r1.IsAscii && IsHexDigit((char)r1.Value) && tmpEnumerator.MoveNext()) { Rune r2 = tmpEnumerator.Current; if (r2.IsAscii && IsHexDigit((char)r2.Value)) { vsb.Append('%'); vsb.Append((char)r1.Value); vsb.Append((char)r2.Value); e = tmpEnumerator; continue; } } } } // Otherwise, append the escaped character. vsb.Append('%'); vsb.Append((char)HexUpperChars[(value & 0xf0) >> 4]); vsb.Append((char)HexUpperChars[value & 0xf]); } } internal static unsafe char[] UnescapeString(string input, int start, int end, char[] dest, ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser? syntax, bool isQuery) { fixed (char* pStr = input) { return UnescapeString(pStr, start, end, dest, ref destPosition, rsvd1, rsvd2, rsvd3, unescapeMode, syntax, isQuery); } } internal static unsafe char[] UnescapeString(char* pStr, int start, int end, char[] dest, ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser? syntax, bool isQuery) { ValueStringBuilder vsb = new ValueStringBuilder(dest.Length); vsb.Append(dest.AsSpan(0, destPosition)); UnescapeString(pStr, start, end, ref vsb, rsvd1, rsvd2, rsvd3, unescapeMode, syntax, isQuery); if (vsb.Length > dest.Length) { dest = vsb.AsSpan().ToArray(); } else { vsb.AsSpan(destPosition).TryCopyTo(dest.AsSpan(destPosition)); } destPosition = vsb.Length; vsb.Dispose(); return dest; } // // This method will assume that any good Escaped Sequence will be unescaped in the output // - Assumes Dest.Length - detPosition >= end-start // - UnescapeLevel controls various modes of operation // - Any "bad" escape sequence will remain as is or '%' will be escaped. // - destPosition tells the starting index in dest for placing the result. // On return destPosition tells the last character + 1 position in the "dest" array. // - The control chars and chars passed in rsdvX parameters may be re-escaped depending on UnescapeLevel // - It is a RARE case when Unescape actually needs escaping some characters mentioned above. // For this reason it returns a char[] that is usually the same ref as the input "dest" value. // internal static unsafe void UnescapeString(string input, int start, int end, ref ValueStringBuilder dest, ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser? syntax, bool isQuery) { fixed (char* pStr = input) { UnescapeString(pStr, start, end, ref dest, rsvd1, rsvd2, rsvd3, unescapeMode, syntax, isQuery); destPosition = dest.Length; } } internal static unsafe void UnescapeString(char* pStr, int start, int end, ref ValueStringBuilder dest, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser? syntax, bool isQuery) { byte[]? bytes = null; bool escapeReserved = false; int next = start; bool iriParsing = Uri.IriParsingStatic(syntax) && ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.EscapeUnescape); char[]? unescapedChars = null; while (true) { if ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.CopyOnly) { while (start < end) dest.Append(pStr[start++]); return; } while (true) { char ch = (char)0; for (; next < end; ++next) { if ((ch = pStr[next]) == '%') { if ((unescapeMode & UnescapeMode.Unescape) == 0) { // re-escape, don't check anything else escapeReserved = true; } else if (next + 2 < end) { ch = EscapedAscii(pStr[next + 1], pStr[next + 2]); // Unescape a good sequence if full unescape is requested if (unescapeMode >= UnescapeMode.UnescapeAll) { if (ch == Uri.c_DummyChar) { if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow) { // Should be a rare case where the app tries to feed an invalid escaped sequence throw new UriFormatException(SR.net_uri_BadString); } continue; } } // re-escape % from an invalid sequence else if (ch == Uri.c_DummyChar) { if ((unescapeMode & UnescapeMode.Escape) != 0) escapeReserved = true; else continue; // we should throw instead but since v1.0 would just print '%' } // Do not unescape '%' itself unless full unescape is requested else if (ch == '%') { next += 2; continue; } // Do not unescape a reserved char unless full unescape is requested else if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3) { next += 2; continue; } // Do not unescape a dangerous char unless it's V1ToStringFlags mode else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0 && IsNotSafeForUnescape(ch)) { next += 2; continue; } else if (iriParsing && ((ch <= '\x9F' && IsNotSafeForUnescape(ch)) || (ch > '\x9F' && !IriHelper.CheckIriUnicodeRange(ch, isQuery)))) { // check if unenscaping gives a char outside iri range // if it does then keep it escaped next += 2; continue; } // unescape escaped char or escape % break; } else if (unescapeMode >= UnescapeMode.UnescapeAll) { if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow) { // Should be a rare case where the app tries to feed an invalid escaped sequence throw new UriFormatException(SR.net_uri_BadString); } // keep a '%' as part of a bogus sequence continue; } else { escapeReserved = true; } // escape (escapeReserved==true) or otherwise unescape the sequence break; } else if ((unescapeMode & (UnescapeMode.Unescape | UnescapeMode.UnescapeAll)) == (UnescapeMode.Unescape | UnescapeMode.UnescapeAll)) { continue; } else if ((unescapeMode & UnescapeMode.Escape) != 0) { // Could actually escape some of the characters if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3) { // found an unescaped reserved character -> escape it escapeReserved = true; break; } else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0 && (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F'))) { // found an unescaped reserved character -> escape it escapeReserved = true; break; } } } //copy off previous characters from input while (start < next) dest.Append(pStr[start++]); if (next != end) { if (escapeReserved) { //escape that char EscapeAsciiChar(pStr[next], ref dest); escapeReserved = false; start = ++next; continue; } // unescaping either one Ascii or possibly multiple Unicode if (ch <= '\x7F') { //ASCII dest.Append(ch); next += 3; start = next; continue; } // Unicode int byteCount = 1; // lazy initialization of max size, will reuse the array for next sequences if ((object?)bytes == null) bytes = new byte[end - next]; bytes[0] = (byte)ch; next += 3; while (next < end) { // Check on exit criterion if ((ch = pStr[next]) != '%' || next + 2 >= end) break; // already made sure we have 3 characters in str ch = EscapedAscii(pStr[next + 1], pStr[next + 2]); //invalid hex sequence ? if (ch == Uri.c_DummyChar) break; // character is not part of a UTF-8 sequence ? else if (ch < '\x80') break; else { //a UTF-8 sequence bytes[byteCount++] = (byte)ch; next += 3; } } if (unescapedChars == null || unescapedChars.Length < bytes.Length) { unescapedChars = new char[bytes.Length]; } int charCount = s_noFallbackCharUTF8.GetChars(bytes, 0, byteCount, unescapedChars, 0); start = next; // match exact bytes // Do not unescape chars not allowed by Iri // need to check for invalid utf sequences that may not have given any chars MatchUTF8Sequence(ref dest, unescapedChars.AsSpan(0, charCount), charCount, bytes, byteCount, isQuery, iriParsing); } if (next == end) goto done; } } done:; } // // Need to check for invalid utf sequences that may not have given any chars. // We got the unescaped chars, we then re-encode them and match off the bytes // to get the invalid sequence bytes that we just copy off // internal static unsafe void MatchUTF8Sequence(ref ValueStringBuilder dest, Span<char> unescapedChars, int charCount, byte[] bytes, int byteCount, bool isQuery, bool iriParsing) { Span<byte> maxUtf8EncodedSpan = stackalloc byte[4]; int count = 0; fixed (char* unescapedCharsPtr = unescapedChars) { for (int j = 0; j < charCount; ++j) { bool isHighSurr = char.IsHighSurrogate(unescapedCharsPtr[j]); Span<byte> encodedBytes = maxUtf8EncodedSpan; int bytesWritten = Encoding.UTF8.GetBytes(unescapedChars.Slice(j, isHighSurr ? 2 : 1), encodedBytes); encodedBytes = encodedBytes.Slice(0, bytesWritten); // we have to keep unicode chars outside Iri range escaped bool inIriRange = false; if (iriParsing) { if (!isHighSurr) inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], isQuery); else { bool surrPair = false; inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], unescapedChars[j + 1], ref surrPair, isQuery); } } while (true) { // Escape any invalid bytes that were before this character while (bytes[count] != encodedBytes[0]) { EscapeAsciiChar((char)bytes[count++], ref dest); } // check if all bytes match bool allBytesMatch = true; int k = 0; for (; k < encodedBytes.Length; ++k) { if (bytes[count + k] != encodedBytes[k]) { allBytesMatch = false; break; } } if (allBytesMatch) { count += encodedBytes.Length; if (iriParsing) { if (!inIriRange) { // need to keep chars not allowed as escaped for (int l = 0; l < encodedBytes.Length; ++l) { EscapeAsciiChar((char)encodedBytes[l], ref dest); } } else if (!UriHelper.IsBidiControlCharacter(unescapedCharsPtr[j]) || !UriParser.DontKeepUnicodeBidiFormattingCharacters) { //copy chars dest.Append(unescapedCharsPtr[j]); if (isHighSurr) { dest.Append(unescapedCharsPtr[j + 1]); } } } else { //copy chars dest.Append(unescapedCharsPtr[j]); if (isHighSurr) { dest.Append(unescapedCharsPtr[j + 1]); } } break; // break out of while (true) since we've matched this char bytes } else { // copy bytes till place where bytes don't match for (int l = 0; l < k; ++l) { EscapeAsciiChar((char)bytes[count++], ref dest); } } } if (isHighSurr) j++; } } // Include any trailing invalid sequences while (count < byteCount) { EscapeAsciiChar((char)bytes[count++], ref dest); } } internal static void EscapeAsciiChar(char ch, ref ValueStringBuilder to) { to.Append('%'); to.Append((char)HexUpperChars[(ch & 0xf0) >> 4]); to.Append((char)HexUpperChars[ch & 0xf]); } internal static char EscapedAscii(char digit, char next) { if (!(((digit >= '0') && (digit <= '9')) || ((digit >= 'A') && (digit <= 'F')) || ((digit >= 'a') && (digit <= 'f')))) { return Uri.c_DummyChar; } int res = (digit <= '9') ? ((int)digit - (int)'0') : (((digit <= 'F') ? ((int)digit - (int)'A') : ((int)digit - (int)'a')) + 10); if (!(((next >= '0') && (next <= '9')) || ((next >= 'A') && (next <= 'F')) || ((next >= 'a') && (next <= 'f')))) { return Uri.c_DummyChar; } return (char)((res << 4) + ((next <= '9') ? ((int)next - (int)'0') : (((next <= 'F') ? ((int)next - (int)'A') : ((int)next - (int)'a')) + 10))); } internal const string RFC3986ReservedMarks = @";/?:@&=+$,#[]!'()*"; private const string RFC2396ReservedMarks = @";/?:@&=+$,"; private const string AdditionalUnsafeToUnescape = @"%\#"; // While not specified as reserved, these are still unsafe to unescape. // When unescaping in safe mode, do not unescape the RFC 3986 reserved set: // gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" // / "*" / "+" / "," / ";" / "=" // // In addition, do not unescape the following unsafe characters: // excluded = "%" / "\" // // This implementation used to use the following variant of the RFC 2396 reserved set. // That behavior is now disabled by default, and is controlled by a UriSyntax property. // reserved = ";" | "/" | "?" | "@" | "&" | "=" | "+" | "$" | "," // excluded = control | "#" | "%" | "\" internal static bool IsNotSafeForUnescape(char ch) { if (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F')) { return true; } else if (UriParser.DontEnableStrictRFC3986ReservedCharacterSets) { if ((ch != ':' && (RFC2396ReservedMarks.IndexOf(ch) >= 0) || (AdditionalUnsafeToUnescape.IndexOf(ch) >= 0))) { return true; } } else if ((RFC3986ReservedMarks.IndexOf(ch) >= 0) || (AdditionalUnsafeToUnescape.IndexOf(ch) >= 0)) { return true; } return false; } // "Reserved" and "Unreserved" characters are based on RFC 3986. internal static ReadOnlySpan<bool> UnreservedReservedTable => new bool[0x80] { // true for all ASCII letters and digits, as well as the RFC3986 reserved characters, unreserved characters, and hash false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, true, false, }; internal static bool IsUnreserved(int c) => c < 0x80 && UnreservedTable[c]; internal static ReadOnlySpan<bool> UnreservedTable => new bool[0x80] { // true for all ASCII letters and digits, as well as the RFC3986 unreserved marks '-', '_', '.', and '~' false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, true, false, }; // // Is this a gen delim char from RFC 3986 // internal static bool IsGenDelim(char ch) { return (ch == ':' || ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']' || ch == '@'); } internal static readonly char[] s_WSchars = new char[] { ' ', '\n', '\r', '\t' }; internal static bool IsLWS(char ch) { return (ch <= ' ') && (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'); } internal static bool IsAsciiLetter(char character) => (((uint)character - 'A') & ~0x20) < 26; internal static bool IsAsciiLetterOrDigit(char character) => ((((uint)character - 'A') & ~0x20) < 26) || (((uint)character - '0') < 10); internal static bool IsHexDigit(char character) => ((((uint)character - 'A') & ~0x20) < 6) || (((uint)character - '0') < 10); // // Is this a Bidirectional control char.. These get stripped // internal static bool IsBidiControlCharacter(char ch) { return (ch == '\u200E' /*LRM*/ || ch == '\u200F' /*RLM*/ || ch == '\u202A' /*LRE*/ || ch == '\u202B' /*RLE*/ || ch == '\u202C' /*PDF*/ || ch == '\u202D' /*LRO*/ || ch == '\u202E' /*RLO*/); } // // Strip Bidirectional control characters from this string // internal static unsafe string StripBidiControlCharacter(char* strToClean, int start, int length) { if (length <= 0) return ""; char[] cleanStr = new char[length]; int count = 0; for (int i = 0; i < length; ++i) { char c = strToClean[start + i]; if (c < '\u200E' || c > '\u202E' || !IsBidiControlCharacter(c)) { cleanStr[count++] = c; } } return new string(cleanStr, 0, count); } } }
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt // http://dead-code.org/redir.php?target=wme using System; using System.Collections.Generic; using System.Text; using DeadCode.WME.Global.Actions; using System.Windows.Forms; using DeadCode.WME.Core; using System.IO; using DeadCode.WME.Global; using DeadCode.WME.Controls; using DeadCode.WME.DefinitionFileParser; using System.Drawing; using System.Media; using System.ComponentModel; namespace DeadCode.WME.WindowEdit { public partial class WindowDoc : Document, IActionProvider, IDisposable { const string ClipFormat = "Wme.WindowEdit.ItemsCollection"; ////////////////////////////////////////////////////////////////////////// public WindowDoc(FormBase ParentForm) { _ParentForm = ParentForm; } ////////////////////////////////////////////////////////////////////////// public void Dispose() { DisposeNatives(); GC.SuppressFinalize(this); } ////////////////////////////////////////////////////////////////////////// private void DisposeNatives() { if(_Canvas != null) { _Canvas.PaintContent -= new WmeCanvas.PaintContentDelegate(OnPaintContent); _Canvas.MouseMove -= new MouseEventHandler(OnMouseMove); _Canvas.MouseDown -= new MouseEventHandler(OnMouseDown); _Canvas.MouseUp -= new MouseEventHandler(OnMouseUp); _Canvas.KeyDown -= new KeyEventHandler(OnKeyDown); _Canvas.Release(); _Canvas.Invalidate(); _Canvas = null; } if(LayoutTree != null) { LayoutTree.SelectionsChanged -= new EventHandler(OnSelectionChanged); LayoutTree.ItemDrag -= new ItemDragEventHandler(TreeItemDrag); LayoutTree.DragEnter -= new DragEventHandler(TreeDragEnter); LayoutTree.DragOver -= new DragEventHandler(TreeDragOver); LayoutTree.DragLeave -= new EventHandler(TreeDragLeave); LayoutTree.DragDrop -= new DragEventHandler(TreeDragDrop); LayoutTree.KeyUp -= new KeyEventHandler(TreeKeyUp); LayoutTree.Nodes.Clear(); LayoutTree.SelectedNodes.Clear(); } Application.Idle -= new EventHandler(OnAppIdle); if (_PropGrid != null) { _PropGrid.SelectedGridItemChanged -= new SelectedGridItemChangedEventHandler(OnPropertySelected); _PropGrid.SelectedObject = null; } RectResizer = null; if (Window != null) { Window.Dispose(); Window = null; } if (InvBox != null) { InvBox.Dispose(); InvBox = null; } if (RespBox != null) { RespBox.Dispose(); RespBox = null; } if (Game != null) { Game.Dispose(); Game = null; } } private FormBase _ParentForm; ////////////////////////////////////////////////////////////////////////// public FormBase ParentForm { get { return _ParentForm; } } private WmeCanvas _Canvas; ////////////////////////////////////////////////////////////////////////// public WmeCanvas Canvas { get { return _Canvas; } } private PropertyGrid _PropGrid = null; ////////////////////////////////////////////////////////////////////////// public PropertyGrid PropGrid { get { return _PropGrid; } set { _PropGrid = value; if (_PropGrid != null) { _PropGrid.SelectedGridItemChanged += new SelectedGridItemChangedEventHandler(OnPropertySelected); } } } ////////////////////////////////////////////////////////////////////////// private void OnPropertySelected(object sender, SelectedGridItemChangedEventArgs e) { bool Handled = false; if (e.NewSelection != null && PropGrid.SelectedObjects.Length == 1 && PropGrid.SelectedObject is UiWindowProxy) { if (e.NewSelection.Value is Rectangle) { RectangleResizer.RectType NewType = RectangleResizer.RectType.Unknown; if(e.NewSelection.Label=="TitleRectangle") NewType = RectangleResizer.RectType.Title; else if (e.NewSelection.Label == "DragRectangle") NewType = RectangleResizer.RectType.Drag; if (NewType != RectangleResizer.RectType.Unknown) { UiWindowProxy Proxy = PropGrid.SelectedObject as UiWindowProxy; WUIWindow NewWindow = Proxy.NativeObject; if (RectResizer == null || RectResizer.Window != NewWindow || RectResizer.Type != NewType) RectResizer = new RectangleResizer(NewWindow, NewType); Handled = true; } } } if (!Handled) RectResizer = null; } private TreeViewMS _LayoutTree = null; ////////////////////////////////////////////////////////////////////////// public TreeViewMS LayoutTree { get { return _LayoutTree; } set { _LayoutTree = value; _LayoutTree.SelectionsChanged += new EventHandler(OnSelectionChanged); // drag and drop stuff _LayoutTree.ItemDrag += new ItemDragEventHandler(TreeItemDrag); _LayoutTree.DragEnter += new DragEventHandler(TreeDragEnter); _LayoutTree.DragOver += new DragEventHandler(TreeDragOver); _LayoutTree.DragLeave += new EventHandler(TreeDragLeave); _LayoutTree.DragDrop += new DragEventHandler(TreeDragDrop); _LayoutTree.KeyUp += new KeyEventHandler(TreeKeyUp); FillLayout(); } } ////////////////////////////////////////////////////////////////////////// private void OnSelectionChanged(object sender, EventArgs e) { if (UpdatingTree) return; DeselectAll(); List<object> SelObj = new List<object>(); foreach(TreeNode Node in LayoutTree.SelectedNodes) { NativePropProxy Proxy = Node.Tag as NativePropProxy; if (Proxy != null && Proxy.NativeObject != null) Proxy.NativeObject.EditorSelected = true; SelObj.Add(Node.Tag); } // update property grid if(PropGrid != null) PropGrid.SelectedObjects = SelObj.ToArray(); } ////////////////////////////////////////////////////////////////////////// private void FillLayout() { if (LayoutTree == null) return; List<WObject> ExpandedNodes = new List<WObject>(); List<WObject> SelectedNodes = new List<WObject>(); GetNodeStates(LayoutTree.Nodes, ExpandedNodes, SelectedNodes); UpdatingTree = true; LayoutTree.BeginUpdate(); LayoutTree.SelectedNodes.Clear(); LayoutTree.Nodes.Clear(); WUIWindow Win = this.MainWindow; if (Win == null) return; FillLayoutNodes(LayoutTree.Nodes, Win); if(InvBox != null) { TreeNode Node = new TreeNode(); Node.Text = "Inventory box"; Node.ImageKey = GetIconKey(InvBox); Node.Tag = new InvBoxProxy(InvBox); LayoutTree.Nodes.Add(Node); } if (RespBox != null) { TreeNode Node = new TreeNode(); Node.Text = "Response box"; Node.ImageKey = GetIconKey(RespBox); Node.Tag = new RespBoxProxy(RespBox); LayoutTree.Nodes.Add(Node); } SetNodeStates(LayoutTree.Nodes, ExpandedNodes, SelectedNodes, true); LayoutTree.EndUpdate(); UpdatingTree = false; // invoke selection changed OnSelectionChanged(LayoutTree, new EventArgs()); } ////////////////////////////////////////////////////////////////////////// private void GetNodeStates(TreeNodeCollection TreeNodes, List<WObject> ExpandedNodes, List<WObject> SelectedNodes) { foreach(TreeNode Node in TreeNodes) { if (Node.Tag != null && Node.Tag is NativePropProxy) { if(Node.IsExpanded) ExpandedNodes.Add(((NativePropProxy)Node.Tag).NativeObject); if (LayoutTree.SelectedNodes.Contains(Node)) SelectedNodes.Add(((NativePropProxy)Node.Tag).NativeObject); } if (Node.Nodes.Count > 0) GetNodeStates(Node.Nodes, ExpandedNodes, SelectedNodes); } } ////////////////////////////////////////////////////////////////////////// private void SetNodeStates(TreeNodeCollection TreeNodes, List<WObject> ExpandedNodes, List<WObject> SelectedNodes, bool HandleSelection) { foreach (TreeNode Node in TreeNodes) { if (Node.Tag != null && Node.Tag is NativePropProxy) { bool NeedsSelection = false; NativePropProxy Proxy = Node.Tag as NativePropProxy; if (ExpandedNodes != null && ExpandedNodes.Contains(Proxy.NativeObject)) Node.Expand(); if (SelectedNodes != null && SelectedNodes.Contains(Proxy.NativeObject)) { NeedsSelection = true; } if(Proxy is UiProxy) { WUIObject Obj = ((UiProxy)Proxy).NativeObject; Node.Text = Obj.Name; if (Obj.Text != null && Obj.Text != string.Empty) Node.Text += " [" + Obj.Text.Replace('\n', '|') + "]"; } if (Proxy.NativeObject.EditorSelected) NeedsSelection = true; if (HandleSelection) { if (NeedsSelection) { if (Node.Parent != null) Node.Parent.Expand(); LayoutTree.SelectedNodes.Add(Node); Node.EnsureVisible(); } else { if (LayoutTree.SelectedNodes.Contains(Node)) LayoutTree.SelectedNodes.Remove(Node); } } } if (Node.Nodes.Count > 0) SetNodeStates(Node.Nodes, ExpandedNodes, SelectedNodes, HandleSelection); } } ////////////////////////////////////////////////////////////////////////// private void FillLayoutNodes(TreeNodeCollection Nodes, WUIWindow Win) { TreeNode Node = new TreeNode(); Node.ImageKey = GetIconKey(Win); UiWindowProxy WinProxy = new UiWindowProxy(Win); WinProxy.RefreshNeeded += new EventHandler(OnTreeRefresh); WinProxy.PropertyChanging += new PropertyChangedEventHandler(OnPropertyChanging); WinProxy.PropertyChanged += new PropertyChangedEventHandler(OnLayoutChanged); Node.Tag = WinProxy; Nodes.Add(Node); foreach(WUIObject Obj in Win.Controls) { if (Obj is WUIWindow) { FillLayoutNodes(Node.Nodes, Obj as WUIWindow); } else { TreeNode Node2 = new TreeNode(); Node2.ImageKey = GetIconKey(Obj); UiProxy ControlProxy; if(Obj is WUIEntity) ControlProxy = new UiEntityProxy(Obj as WUIEntity); else if(Obj is WUIStatic) ControlProxy = new UiStaticProxy(Obj as WUIStatic); else if(Obj is WUIButton) ControlProxy = new UiButtonProxy(Obj as WUIButton); else if (Obj is WUIEdit) ControlProxy = new UiEditorProxy(Obj as WUIEdit); else ControlProxy = new UiControlProxy(Obj); ControlProxy.RefreshNeeded += new EventHandler(OnTreeRefresh); ControlProxy.PropertyChanging += new PropertyChangedEventHandler(OnPropertyChanging); ControlProxy.PropertyChanged += new PropertyChangedEventHandler(OnLayoutChanged); Node2.Tag = ControlProxy; Node.Nodes.Add(Node2); Node.Expand(); } } } ////////////////////////////////////////////////////////////////////////// private void OnTreeRefresh(object sender, EventArgs e) { RefreshTree(false); } ////////////////////////////////////////////////////////////////////////// private void OnLayoutChanged(object sender, PropertyChangedEventArgs e) { UpdateScrollSize(); } ////////////////////////////////////////////////////////////////////////// private void OnPropertyChanging(object sender, PropertyChangedEventArgs e) { string UndoName = "Property changed"; if(e.PropertyName != null && e.PropertyName != "") UndoName += " '" + e.PropertyName + "'"; SaveUndoState(UndoName); } bool UpdatingTree = false; ////////////////////////////////////////////////////////////////////////// private void RefreshTree(bool HandleSelection) { if (LayoutTree != null) { UpdatingTree = true; LayoutTree.BeginUpdate(); SetNodeStates(LayoutTree.Nodes, null, null, HandleSelection); LayoutTree.EndUpdate(); UpdatingTree = false; } } ////////////////////////////////////////////////////////////////////////// string GetIconKey(WObject Obj) { if (LayoutTree == null || LayoutTree.ImageList == null) return ""; ImageList Img = LayoutTree.ImageList; if (Obj is WUIWindow) return "window"; else if (Obj is WUIButton) return "button"; else if (Obj is WUIEdit) return "editor"; else if (Obj is WUIStatic) return "static"; else if (Obj is WUIEntity) return "entity"; else return "box"; } ////////////////////////////////////////////////////////////////////////// public bool CloseDocument() { bool CanClose = false; if (IsDirty) { DialogResult Res = MessageBox.Show("Do you want to save your changes?", Form.ActiveForm.Text, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); switch(Res) { case DialogResult.Yes: CanClose = SaveDocument(false); break; case DialogResult.No: CanClose = true; break; default: CanClose = false; break; } } else CanClose = true; if(CanClose) { FileName = ""; IsDirty = false; DisposeNatives(); return true; } return CanClose; } ////////////////////////////////////////////////////////////////////////// public bool NewDocument(WmeCanvas Canvas) { DocumentTypeForm dlg = new DocumentTypeForm(); dlg.AppMgr = ParentForm.AppMgr; if (dlg.ShowDialog() != DialogResult.OK) return false; if (InitEngine(null, Canvas)) { WUIWindow Win = new WUIWindow(Game); Win.Width = 200; Win.Height = 100; Game.Windows.Add(Win); Game.FocusedWindow = Win; switch(dlg.SelectedType) { case "InvBox": InvBox = new WAdInventoryBox(Game); InvBox.Window = Win; InvBox.Area = new Rectangle(0, 0, Win.Width, Win.Height); break; case "RespBox": RespBox = new WAdResponseBox(Game); RespBox.Window = Win; RespBox.Area = new Rectangle(0, 0, Win.Width, Win.Height); break; default: Window = Win; break; } UpdateScrollSize(); FileName = ""; IsDirty = true; return true; } else return false; } ////////////////////////////////////////////////////////////////////////// private bool InitEngine(string DefinitionFile, WmeCanvas Canvas) { try { DisposeNatives(); string ProjectFile = GetProjectFile(DefinitionFile, ParentForm); if (ProjectFile != null) { string LogFile = Path.Combine(Path.GetDirectoryName(ProjectFile), "WindowEdit.log"); Game = new WAdGame(); Game.ForceScripts = true; Game.DoNotExpandStrings = true; Game.EditorMode = true; if (!Canvas.Create(Game, ProjectFile, LogFile)) { DisposeNatives(); return false; } _Canvas = Canvas; _Canvas.PaintContent += new WmeCanvas.PaintContentDelegate(OnPaintContent); _Canvas.MouseMove += new MouseEventHandler(OnMouseMove); _Canvas.MouseDown += new MouseEventHandler(OnMouseDown); _Canvas.MouseUp += new MouseEventHandler(OnMouseUp); _Canvas.KeyDown += new KeyEventHandler(OnKeyDown); Application.Idle += new EventHandler(OnAppIdle); return true; } return false; } catch(Exception e) { MessageBox.Show("Error initializing game engine:\n\n" + e.Message, Form.ActiveForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } ////////////////////////////////////////////////////////////////////////// public DocumentOpenResult OpenDocument(WmeCanvas Canvas) { return OpenDocument(Canvas, null); } ////////////////////////////////////////////////////////////////////////// public DocumentOpenResult OpenDocument(WmeCanvas Canvas, string FileName) { if (FileName == null) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Windows and definition files (*.window; *.def)|*.window;*.def|Windows (*.window)|*.window|Defintion files (*.def)|*.def|All files (*.*)|*.*"; dlg.RestoreDirectory = true; dlg.CheckFileExists = true; if (dlg.ShowDialog() != DialogResult.OK) return DocumentOpenResult.Cancel; else FileName = dlg.FileName; } DefinitionFile DefFile = new DefinitionFile(); string FileType = ""; if(DefFile.ParseFile(FileName) && DefFile.Children.Count > 0) FileType = DefFile.Children[0].Name.ToUpper(); if(FileType != "WINDOW" && FileType != "INVENTORY_BOX" && FileType != "RESPONSE_BOX") { MessageBox.Show("Unsupported file type.", Form.ActiveForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return DocumentOpenResult.Cancel; } bool Ret = false; if (InitEngine(FileName, Canvas)) { Game.AbsolutePathWarning = false; switch(FileType) { case "WINDOW": Window = new WUIWindow(Game); Ret = Window.LoadFromFile(FileName); if(Ret) { Game.Windows.Add(Window); Game.FocusedWindow = Window; } break; case "INVENTORY_BOX": InvBox = new WAdInventoryBox(Game); Ret = InvBox.LoadFromFile(FileName); if(Ret && InvBox.Window != null) { Game.Windows.Add(InvBox.Window); Game.FocusedWindow = InvBox.Window; } break; case "RESPONSE_BOX": RespBox = new WAdResponseBox(Game); Ret = RespBox.LoadFromFile(FileName); if (Ret && RespBox.Window != null) { Game.Windows.Add(RespBox.Window); Game.FocusedWindow = RespBox.Window; } break; } Game.AbsolutePathWarning = true; UpdateScrollSize(); this.FileName = FileName; } else Ret = false; if (!Ret) DisposeNatives(); if (Ret) return DocumentOpenResult.Ok; else return DocumentOpenResult.Error; } ////////////////////////////////////////////////////////////////////////// public bool SaveDocument(bool SaveAs) { if (FileName == "") SaveAs = true; string NewFileName = FileName; if (SaveAs) { string Filter; if (InvBox != null || RespBox != null) Filter = "Definiton files (*.def)|*.def"; else Filter = "Windows (*.window)|*.window"; Filter += "|All files (*.*)|*.*"; SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = FileName; dlg.Filter = Filter; dlg.AddExtension = true; dlg.CheckPathExists = true; dlg.OverwritePrompt = true; dlg.RestoreDirectory = true; if (dlg.ShowDialog() != DialogResult.OK) return false; NewFileName = dlg.FileName; } DeleteEditorProps(); WDynBuffer Buf = new WDynBuffer(Game); if (InvBox != null) InvBox.SaveAsText(Buf); else if (RespBox != null) RespBox.SaveAsText(Buf); else Window.SaveAsText(Buf); string RelProjectPath = WmeUtils.GetRelativePath(NewFileName, Path.GetDirectoryName(Game.ProjectFile) + "\\"); string FileContent = ""; FileContent += "; generated by WindowEdit\n\n"; FileContent += "; $EDITOR_PROJECT_ROOT_DIR$ " + RelProjectPath + "\n\n"; FileContent += Buf.Text; Buf.Dispose(); try { using (StreamWriter sw = new StreamWriter(NewFileName, false, Encoding.Default)) { sw.WriteLine(FileContent); } FileName = NewFileName; IsDirty = false; return true; } catch(Exception e) { MessageBox.Show("Error saving file.\n\n" + e.Message, Form.ActiveForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } private bool RefreshProps = false; ////////////////////////////////////////////////////////////////////////// private void OnPaintContent(object sender, EventArgs e) { if (MainWindow != null) { MainWindow.X -= Canvas.HorizontalScroll.Value; MainWindow.Y -= Canvas.VerticalScroll.Value; Game.DisplayWindows(true); Game.DisplayWindows(false); Game.ActiveObject = Game.Renderer.GetObjectAt(Game.MousePos); PaintSelections(); MainWindow.X += Canvas.HorizontalScroll.Value; MainWindow.Y += Canvas.VerticalScroll.Value; } } ////////////////////////////////////////////////////////////////////////// private void OnAppIdle(object sender, EventArgs e) { if (RefreshProps && PropGrid != null) { PropGrid.Refresh(); RefreshProps = false; } if (!IsMoving && !IsResizing) { foreach (IEditorResizable It in AllItems) { SetOrigPos(It); } } } private List<HotSpot> HotSpots = new List<HotSpot>(); private Rectangle AddingRect = Rectangle.Empty; ////////////////////////////////////////////////////////////////////////// private void PaintSelections() { HotSpots.Clear(); if (IsAdding) { if (!AddingRect.IsEmpty) { Game.Renderer.DrawRect(AddingRect, SelectionColor); } } else { PaintSelections(MainWindow); if (InvBox != null) PaintInventoryBox(InvBox); if (RespBox != null) PaintResponseBox(RespBox); if (RectResizer != null) PaintResizer(RectResizer); } } ////////////////////////////////////////////////////////////////////////// private void PaintSelections(WUIWindow Win) { Rectangle Rect; int OffsetX = 0; int OffsetY = 0; bool MultiSel = SelectedControls.Length > 1; bool WinVisible = Win.Visible; WUIObject Parent = Win.Parent; while(Parent != null) { if (!Parent.Visible) WinVisible = false; OffsetX += Parent.X; OffsetY += Parent.Y; Parent = Parent.Parent; } Rect = new Rectangle(OffsetX + Win.X, OffsetY + Win.Y, Win.Width - 1, Win.Height - 1); if(WinVisible) HotSpots.Add(new HotSpot(Rect, Win, HotSpot.HotSpotType.Container)); if (Win.EditorSelected && RectResizer == null) { Game.Renderer.DrawRect(Rect, SelectionColor); if (!MultiSel && WinVisible) PaintResizeHandles(Rect, Win); } OffsetX += Win.X; OffsetY += Win.Y; foreach(WUIObject C in Win.Controls) { if (C is WUIWindow) PaintSelections(C as WUIWindow); else { bool IsVisible = C.Visible && WinVisible; Rect = new Rectangle(OffsetX + C.X, OffsetY + C.Y, C.Width - 1, C.Height - 1); if(IsVisible) HotSpots.Add(new HotSpot(Rect, C, HotSpot.HotSpotType.Control)); if (C.EditorSelected && RectResizer == null) { Game.Renderer.DrawRect(Rect, SelectionColor); if (!MultiSel && !(C is WUIEntity) && IsVisible) PaintResizeHandles(Rect, C); } } } } ////////////////////////////////////////////////////////////////////////// private void PaintResponseBox(WAdResponseBox RespBox) { int OffsetX = 0; int OffsetY = 0; if (MainWindow != null) { OffsetX += MainWindow.X; OffsetY += MainWindow.Y; } Color Col = RespBox.EditorSelected ? SelectionColor : BoxColor; Rectangle Rect = new Rectangle(OffsetX + RespBox.Area.X, OffsetY + RespBox.Area.Y, RespBox.Area.Width - 1, RespBox.Area.Height - 1); Game.Renderer.DrawRect(Rect, Col); if (RespBox.EditorSelected && RectResizer == null) { HotSpots.Add(new HotSpot(Rect, RespBox, HotSpot.HotSpotType.Control)); PaintResizeHandles(Rect, RespBox); } } ////////////////////////////////////////////////////////////////////////// private void PaintInventoryBox(WAdInventoryBox InvBox) { int OffsetX = 0; int OffsetY = 0; if (MainWindow != null) { OffsetX += MainWindow.X; OffsetY += MainWindow.Y; } Color Col = InvBox.EditorSelected ? SelectionColor : BoxColor; Rectangle Rect; // paint item rectangles int X = InvBox.Area.X; int Y = InvBox.Area.Y; while(Y + InvBox.ItemHeight <= InvBox.Area.Y + InvBox.Area.Height) { while(X + InvBox.ItemWidth <= InvBox.Area.X + InvBox.Area.Width) { Rect = new Rectangle(OffsetX + X, OffsetY + Y, InvBox.ItemWidth - 1, InvBox.ItemHeight - 1); Game.Renderer.DrawRect(Rect, Col); X += InvBox.ItemWidth + InvBox.Spacing; } X = InvBox.Area.X; Y += InvBox.ItemHeight + InvBox.Spacing; } Rect = new Rectangle(OffsetX + InvBox.Area.X, OffsetY + InvBox.Area.Y, InvBox.Area.Width - 1, InvBox.Area.Height - 1); Game.Renderer.DrawRect(Rect, Col); if (InvBox.EditorSelected && RectResizer == null) { HotSpots.Add(new HotSpot(Rect, InvBox, HotSpot.HotSpotType.Control)); PaintResizeHandles(Rect, InvBox); } } ////////////////////////////////////////////////////////////////////////// private void PaintResizer(RectangleResizer Resizer) { int OffsetX = 0; int OffsetY = 0; WUIObject Parent = Resizer.Window; while (Parent != null) { OffsetX += Parent.X; OffsetY += Parent.Y; Parent = Parent.Parent; } Rectangle Rect = new Rectangle(OffsetX + Resizer.X, OffsetY + Resizer.Y, Resizer.Width - 1, Resizer.Height - 1); Game.Renderer.DrawRect(Rect, SelectionColor); HotSpots.Add(new HotSpot(Rect, Resizer, HotSpot.HotSpotType.Control)); PaintResizeHandles(Rect, Resizer); } ////////////////////////////////////////////////////////////////////////// private WUIObject[] SelectedControls { get { List<WUIObject> SelObj = new List<WUIObject>(); GetSelectedObjects(MainWindow, SelObj); return SelObj.ToArray(); } } RectangleResizer RectResizer = null; ////////////////////////////////////////////////////////////////////////// private IEditorResizable[] SelectedItems { get { List<IEditorResizable> SelItems = new List<IEditorResizable>(); if (RespBox != null && RespBox.EditorSelected) { SelItems.Add(RespBox); } else if (InvBox != null && InvBox.EditorSelected) { SelItems.Add(InvBox); } else { List<WUIObject> SelObj = new List<WUIObject>(); GetSelectedObjects(MainWindow, SelObj); foreach(WUIObject C in SelObj) { SelItems.Add(C); } } if (RectResizer != null) SelItems.Add(RectResizer); return SelItems.ToArray(); } } ////////////////////////////////////////////////////////////////////////// private void GetSelectedObjects(WUIWindow Win, List<WUIObject> SelObj) { if (Win.EditorSelected) SelObj.Add(Win); foreach(WUIObject C in Win.Controls) { if (C is WUIWindow) GetSelectedObjects(C as WUIWindow, SelObj); else if (C.EditorSelected) SelObj.Add(C); } } ////////////////////////////////////////////////////////////////////////// private WUIObject[] AllControls { get { List<WUIObject> AllObj = new List<WUIObject>(); GetAllObjects(MainWindow,AllObj); return AllObj.ToArray(); } } ////////////////////////////////////////////////////////////////////////// private IEditorResizable[] AllItems { get { List<IEditorResizable> Items = new List<IEditorResizable>(); if (RespBox != null) { Items.Add(RespBox); } if (InvBox != null) { Items.Add(InvBox); } List<WUIObject> AllObj = new List<WUIObject>(); GetAllObjects(MainWindow, AllObj); foreach (WUIObject C in AllObj) { Items.Add(C); } if (RectResizer != null) Items.Add(RectResizer); return Items.ToArray(); } } ////////////////////////////////////////////////////////////////////////// private void GetAllObjects(WUIWindow Win, List<WUIObject> AllObj) { AllObj.Add(Win); foreach (WUIObject C in Win.Controls) { if (C is WUIWindow) GetAllObjects(C as WUIWindow, AllObj); else AllObj.Add(C); } } ////////////////////////////////////////////////////////////////////////// private void PaintResizeHandles(Rectangle OwnerRect, IEditorResizable Owner) { Rectangle Rect; Rect = new Rectangle(OwnerRect.X - 2, OwnerRect.Y - 2, 5, 5); Game.Renderer.DrawRect(Rect, SelectionColor); HotSpots.Add(new HotSpot(Rect, Owner, HotSpot.HotSpotType.ResizeNW)); Rect = new Rectangle(OwnerRect.X + OwnerRect.Width / 2 - 2, OwnerRect.Y - 2, 5, 5); Game.Renderer.DrawRect(Rect, SelectionColor); HotSpots.Add(new HotSpot(Rect, Owner, HotSpot.HotSpotType.ResizeN)); Rect = new Rectangle(OwnerRect.X + OwnerRect.Width - 3, OwnerRect.Y - 2, 5, 5); Game.Renderer.DrawRect(Rect, SelectionColor); HotSpots.Add(new HotSpot(Rect, Owner, HotSpot.HotSpotType.ResizeNE)); Rect = new Rectangle(OwnerRect.X - 2, OwnerRect.Y + OwnerRect.Height / 2 - 2, 5, 5); Game.Renderer.DrawRect(Rect, SelectionColor); HotSpots.Add(new HotSpot(Rect, Owner, HotSpot.HotSpotType.ResizeW)); Rect = new Rectangle(OwnerRect.X + OwnerRect.Width - 3, OwnerRect.Y + OwnerRect.Height / 2 - 2, 5, 5); Game.Renderer.DrawRect(Rect, SelectionColor); HotSpots.Add(new HotSpot(Rect, Owner, HotSpot.HotSpotType.ResizeE)); Rect = new Rectangle(OwnerRect.X - 2, OwnerRect.Y + OwnerRect.Height - 3, 5, 5); Game.Renderer.DrawRect(Rect, SelectionColor); HotSpots.Add(new HotSpot(Rect, Owner, HotSpot.HotSpotType.ResizeSW)); Rect = new Rectangle(OwnerRect.X + OwnerRect.Width / 2 - 2, OwnerRect.Y + OwnerRect.Height - 3, 5, 5); Game.Renderer.DrawRect(Rect, SelectionColor); HotSpots.Add(new HotSpot(Rect, Owner, HotSpot.HotSpotType.ResizeS)); Rect = new Rectangle(OwnerRect.X + OwnerRect.Width - 3, OwnerRect.Y + OwnerRect.Height - 3, 5, 5); Game.Renderer.DrawRect(Rect, SelectionColor); HotSpots.Add(new HotSpot(Rect, Owner, HotSpot.HotSpotType.ResizeSE)); } ////////////////////////////////////////////////////////////////////////// private void DeselectAll() { foreach(IEditorResizable It in AllItems) { It.EditorSelected = false; } } ////////////////////////////////////////////////////////////////////////// private void CreateControl(Type ControlToAdd, Rectangle AddingRect) { WUIObject NewControl = null; if (ControlToAdd != null) { try { NewControl = (WUIObject)Activator.CreateInstance(ControlToAdd, new object[] { Game }); } catch { NewControl = null; } } if (NewControl != null) { SaveUndoState("Create control"); if(AddingRect.IsEmpty) { AddingRect.X = StartPoint.X; AddingRect.Y = StartPoint.Y; } AddingRect.Offset(Canvas.HorizontalScroll.Value, Canvas.VerticalScroll.Value); WUIWindow Parent = GetNearestWindow(AddingRect.X, AddingRect.Y); if (AddingRect.Width < 0) { AddingRect.Width = -AddingRect.Width; AddingRect.X -= AddingRect.Width; } if (AddingRect.Height < 0) { AddingRect.Height = -AddingRect.Height; AddingRect.Y -= AddingRect.Height; } int OffsetX, OffsetY; Parent.GetTotalOffset(out OffsetX, out OffsetY); NewControl.X = AddingRect.X - OffsetX - Parent.X; NewControl.Y = AddingRect.Y - OffsetY - Parent.Y; NewControl.Width = AddingRect.Width; NewControl.Height = AddingRect.Height; if (NewControl.Width == 0) NewControl.Width = 100; if (NewControl.Height == 0) NewControl.Height = 50; if(NewControl is WUIEntity) { NewControl.Width = 50; NewControl.Height = 50; } if (NewControl is WUIButton) NewControl.Text = "Button"; if (NewControl is WUIStatic) NewControl.Text = "Static"; if (NewControl is WUIEdit) NewControl.Text = "Editor"; NewControl.ParentNotify = true; Parent.AddControl(NewControl); DeselectAll(); RefreshTree(true); NewControl.EditorSelected = true; FillLayout(); RefreshTree(true); OnSelectionChanged(LayoutTree, new EventArgs()); } } ////////////////////////////////////////////////////////////////////////// private WUIWindow GetNearestWindow(int X, int Y) { for (int i = AllControls.Length - 1; i >= 0; i--) { WUIWindow C = AllControls[i] as WUIWindow; if (C == null) continue; int WinX, WinY; C.GetTotalOffset(out WinX, out WinY); WinX += C.X; WinY += C.Y; if(X >= WinX && X <= WinX + C.Width && Y >= WinY && Y <= WinY + C.Height) return C; } return MainWindow; } ////////////////////////////////////////////////////////////////////////// private static void SetOrigPos(IEditorResizable Obj) { Obj.OrigRect = new Rectangle(Obj.X, Obj.Y, Obj.Width, Obj.Height); } ////////////////////////////////////////////////////////////////////////// private void UpdateScrollSize() { if(MainWindow != null) { Rectangle Rect = GetWindowSize(MainWindow); if(IsAdding) { Rectangle Rect2 = AddingRect; Rect2.Offset(Canvas.HorizontalScroll.Value, Canvas.VerticalScroll.Value); Rect = Rectangle.Union(Rect, Rect2); } Canvas.AutoScrollMinSize = new Size(Rect.Width + MainWindow.X, Rect.Height + MainWindow.Y); } } ////////////////////////////////////////////////////////////////////////// private Rectangle GetWindowSize(WUIWindow Win) { return GetWindowSize(Win, 0, 0); } ////////////////////////////////////////////////////////////////////////// private Rectangle GetWindowSize(WUIWindow Win, int OffsetX, int OffsetY) { Rectangle Rect = new Rectangle(OffsetX + Win.X, OffsetY + Win.Y, Win.Width, Win.Height); foreach(WUIObject Obj in Win.Controls) { Rectangle Rect2; if(Obj is WUIWindow) Rect2 = GetWindowSize((WUIWindow)Obj, OffsetX + Win.X, OffsetY + Win.Y); else Rect2 = new Rectangle(OffsetX + Win.X + Obj.X, OffsetY + Win.Y + Obj.Y, Obj.Width, Obj.Height); Rect = Rectangle.Union(Rect, Rect2); } return Rect; } ////////////////////////////////////////////////////////////////////////// private WUIWindow MainWindow { get { if (Window != null) return Window; else if (InvBox != null && InvBox.Window != null) return InvBox.Window; else if (RespBox != null && RespBox.Window != null) return RespBox.Window; else return null; } } private WUIWindow Window = null; private WAdGame Game = null; private WAdInventoryBox InvBox = null; private WAdResponseBox RespBox = null; ////////////////////////////////////////////////////////////////////////// private void AddControl(Type type) { IsAboutToAdd = true; ControlToAdd = type; } ////////////////////////////////////////////////////////////////////////// public override string GetCurrentStateForUndo() { WDynBuffer Buf = new WDynBuffer(Game); if (InvBox != null) InvBox.SaveAsText(Buf); else if (RespBox != null) RespBox.SaveAsText(Buf); else if (Window != null) Window.SaveAsText(Buf); else { Buf.Dispose(); return null; } string Ret = Buf.Text; Buf.Dispose(); return Ret; } ////////////////////////////////////////////////////////////////////////// public void LoadUndoState(string State) { if(InvBox != null) { WAdInventoryBox NewInvBox = new WAdInventoryBox(Game); if (NewInvBox.LoadFromBuffer(State)) { Game.Windows.Remove(MainWindow); InvBox.Dispose(); InvBox = NewInvBox; } else NewInvBox.Dispose(); } else if(RespBox != null) { WAdResponseBox NewRespBox = new WAdResponseBox(Game); if (NewRespBox.LoadFromBuffer(State)) { Game.Windows.Remove(MainWindow); RespBox.Dispose(); RespBox = NewRespBox; } else NewRespBox.Dispose(); } else if(Window != null) { WUIWindow NewWin = new WUIWindow(Game); if (NewWin.LoadFromBuffer(State)) { Game.Windows.Remove(MainWindow); Window.Dispose(); Window = NewWin; } else NewWin.Dispose(); } Game.Windows.Add(MainWindow); Game.FocusedWindow = MainWindow; FillLayout(); RefreshTree(true); } #region Clipboard handling ////////////////////////////////////////////////////////////////////////// private void DeleteSelectedItems() { if (!CanDeleteSelectedItems()) { SystemSounds.Asterisk.Play(); return; } SaveUndoState("Delete items"); foreach(WUIObject C in SelectedControls) { C.Parent.RemoveControl(C); } FillLayout(); } ////////////////////////////////////////////////////////////////////////// private bool CanDeleteSelectedItems() { bool Ret = false; if (SelectedControls.Length > 0) { Ret = true; foreach (WUIObject C in SelectedControls) { if (C == MainWindow) { Ret = false; break; } } } return Ret; } ////////////////////////////////////////////////////////////////////////// private void DeleteEditorProps() { foreach(WUIObject C in AllControls) { DeleteEditorProps(C); } if (InvBox != null) DeleteEditorProps(InvBox); if (RespBox != null) DeleteEditorProps(RespBox); } ////////////////////////////////////////////////////////////////////////// private void DeleteEditorProps(WObject Obj) { Obj.DeleteEditorProp("OrigX"); Obj.DeleteEditorProp("OrigY"); Obj.DeleteEditorProp("OrigWidth"); Obj.DeleteEditorProp("OrigHeight"); } ////////////////////////////////////////////////////////////////////////// private void CopySelectedItems() { List<string> Types = new List<string>(); List<string> Values = new List<string>(); WDynBuffer Buf = new WDynBuffer(Game); foreach(WUIObject C in SelectedControls) { bool IsParentSelected = false; WUIObject Parent = C.Parent; while (Parent != null) { if (Parent.EditorSelected) { IsParentSelected = true; break; } Parent = Parent.Parent; } if (IsParentSelected) continue; Types.Add(C.GetType().AssemblyQualifiedName); Buf.Clear(); C.SaveAsText(Buf); Values.Add(Buf.Text); } Buf.Dispose(); if (Types.Count == 0) { SystemSounds.Asterisk.Play(); return; } string[,] ClipData = new string[Types.Count, 2]; for(int i=0; i<Types.Count; i++) { ClipData[i, 0] = Types[i]; ClipData[i, 1] = Values[i]; } Clipboard.SetData(ClipFormat, ClipData); } ////////////////////////////////////////////////////////////////////////// private void PasteItems() { if (!Clipboard.ContainsData(ClipFormat)) return; SaveUndoState("Paste from clipboard"); bool WasError = false; DeselectAll(); RefreshTree(true); string[,] ClipData = (string[,])Clipboard.GetData(ClipFormat); for (int i = 0; i < ClipData.Length / 2; i++) { string TypeName = ClipData[i, 0]; string Value = ClipData[i, 1]; try { WUIObject NewControl = (WUIObject)Activator.CreateInstance(Type.GetType(TypeName), new object[] { Game }); if (NewControl.LoadFromBuffer(Value, true)) { MainWindow.AddControl(NewControl); NewControl.EditorSelected = true; } else { NewControl.Dispose(); WasError = true; } } catch { WasError = true; } } if (WasError) SystemSounds.Asterisk.Play(); FillLayout(); RefreshTree(true); } #endregion #region Drag and drop ////////////////////////////////////////////////////////////////////////// private void TreeItemDrag(object sender, ItemDragEventArgs e) { foreach(TreeNode Node in LayoutTree.SelectedNodes) { if (Node.Tag is UiWindowProxy && ((UiWindowProxy)Node.Tag).NativeObject == MainWindow) return; if (!(Node.Tag is UiProxy)) return; } LayoutTree.DoDragDrop(e.Item, DragDropEffects.Move); } ////////////////////////////////////////////////////////////////////////// private void TreeDragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } ////////////////////////////////////////////////////////////////////////// private void TreeDragLeave(object sender, EventArgs e) { DeselectPrevNode(); } TreeNode previousNode = null; ////////////////////////////////////////////////////////////////////////// private void TreeDragOver(object sender, DragEventArgs e) { // Scrolling down/up Point pt = LayoutTree.PointToClient(new Point(e.X, e.Y)); if (pt.Y + 10 > LayoutTree.ClientSize.Height) NativeMethods.SendMessage(LayoutTree.Handle, 277, 1, IntPtr.Zero); else if (pt.Y < LayoutTree.Top + 10) NativeMethods.SendMessage(LayoutTree.Handle, 277, 0, IntPtr.Zero); if (e.Data.GetDataPresent(typeof(NodesCollection))) { TreeNode DestinationNode = LayoutTree.GetNodeAt(pt); if (DestinationNode != null && !LayoutTree.SelectedNodes.Contains(DestinationNode) && DestinationNode.Tag is UiProxy) { e.Effect = DragDropEffects.Move; if (previousNode != DestinationNode) DeselectPrevNode(); previousNode = DestinationNode; previousNode.BackColor = LayoutTree.SelectionBackColor; previousNode.ForeColor = LayoutTree.BackColor; DestinationNode.EnsureVisible(); return; } } e.Effect = DragDropEffects.None; DeselectPrevNode(); } ////////////////////////////////////////////////////////////////////////// private void TreeKeyUp(object sender, KeyEventArgs e) { if(e.KeyCode == Keys.Escape) { DeselectPrevNode(); } } ////////////////////////////////////////////////////////////////////////// private void TreeDragDrop(object sender, DragEventArgs e) { DeselectPrevNode(); if(e.Data.GetDataPresent(typeof(NodesCollection))) { Point pt = LayoutTree.PointToClient(new Point(e.X, e.Y)); TreeNode DestinationNode = LayoutTree.GetNodeAt(pt); if (DestinationNode == null) return; if (DestinationNode.Tag as UiProxy == null) return; SaveUndoState("Controls reorder"); WUIObject Target = ((UiProxy)DestinationNode.Tag).NativeObject; WUIWindow NewParent; int NewIndex; if(Target is WUIWindow) { NewParent = Target as WUIWindow; NewIndex = 0; } else { NewParent = Target.Parent as WUIWindow; NewIndex = NewParent.Controls.IndexOf(Target); } foreach (TreeNode Node in LayoutTree.SelectedNodes) { UiProxy Proxy = Node.Tag as UiProxy; if(Proxy == null) continue; WUIObject Obj = Proxy.NativeObject; if (Obj.Parent != NewParent) { Obj.Parent.Controls.Remove(Obj); NewParent.AddControl(Obj); } NewParent.Controls.Remove(Obj); NewParent.Controls.Insert(NewIndex, Obj); // **************FIX**************** // This is pretty much bad, because you can't increment index as you go node by node // NewIndex++; // **************FIX ENDS**************** } FillLayout(); RefreshTree(true); } } ////////////////////////////////////////////////////////////////////////// private void DeselectPrevNode() { if (previousNode != null) { previousNode.BackColor = LayoutTree.BackColor; previousNode.ForeColor = LayoutTree.ForeColor; previousNode = null; } } #endregion } }
// Copyright 2008-2009 Louis DeJardin - http://whereslou.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Collections.Generic; using Spark.Parser; using Spark.Parser.Code; using Spark.Parser.Markup; namespace Spark.Compiler { public class Chunk { public Position Position { get; set; } } public class SendLiteralChunk : Chunk { public string Text { get; set; } } public class SendExpressionChunk : Chunk { public Snippets Code { get; set; } //public IList<Snippet> Snippets { get; set; } public bool SilentNulls { get; set; } public bool AutomaticallyEncode { get; set; } } public class CodeStatementChunk : Chunk { public Snippets Code { get; set; } //public IList<Snippet> Snippets { get; set; } } public class GlobalVariableChunk : Chunk { public GlobalVariableChunk() { Type = "object"; } public Snippets Name { get; set; } public Snippets Type { get; set; } public Snippets Value { get; set; } } public class LocalVariableChunk : Chunk { public LocalVariableChunk() { Type = "var"; } public Snippets Name { get; set; } public Snippets Type { get; set; } public Snippets Value { get; set; } } public class DefaultVariableChunk : Chunk { public DefaultVariableChunk() { Type = "var"; } public string Name { get; set; } public Snippets Type { get; set; } public Snippets Value { get; set; } } public class ViewDataChunk : Chunk { public ViewDataChunk() { Type = "object"; } public Snippets Name { get; set; } public Snippets Type { get; set; } public string Key { get; set; } public Snippets Default { get; set; } } public class ViewDataModelChunk : Chunk { public Snippets TModel { get; set; } public Snippets TModelAlias { get; set; } } public class AssignVariableChunk : Chunk { public string Name { get; set; } public Snippets Value { get; set; } } public class UseContentChunk : Chunk { public UseContentChunk() { Default = new List<Chunk>(); } public string Name { get; set; } public IList<Chunk> Default { get; set; } } public class RenderPartialChunk : Chunk { public RenderPartialChunk() { Body = new List<Chunk>(); Sections = new Dictionary<string, IList<Chunk>>(); } public string Name { get; set; } public FileContext FileContext { get; set; } public IList<Chunk> Body { get; set; } public IDictionary<string, IList<Chunk>> Sections { get; set; } } public class UseImportChunk : Chunk { public string Name { get; set; } } public class UseMasterChunk : Chunk { public string Name { get; set; } } public class RenderSectionChunk : Chunk { public RenderSectionChunk() { Default = new List<Chunk>(); } public string Name { get; set; } public IList<Chunk> Default { get; set; } } public class UseNamespaceChunk : Chunk { public Snippets Namespace { get; set; } } public class UseAssemblyChunk : Chunk { public string Assembly { get; set; } } public class ContentChunk : Chunk { public ContentChunk() { Body = new List<Chunk>(); } public string Name { get; set; } public IList<Chunk> Body { get; set; } } public enum ContentAddType { Replace, InsertBefore, AppendAfter } public class ContentSetChunk : Chunk { public ContentSetChunk() { Body = new List<Chunk>(); AddType = ContentAddType.Replace; } public Snippets Variable { get; set; } public IList<Chunk> Body { get; set; } public ContentAddType AddType { get; set; } } public class ForEachChunk : Chunk { public ForEachChunk() { Body = new List<Chunk>(); } public Snippets Code { get; set; } public IList<Chunk> Body { get; set; } } public class MacroChunk : Chunk { public MacroChunk() { Body = new List<Chunk>(); Parameters = new List<MacroParameter>(); } public string Name { get; set; } public IList<MacroParameter> Parameters { get; set; } public IList<Chunk> Body { get; set; } } public class MacroParameter { public string Name { get; set; } public Snippets Type { get; set; } } public class ScopeChunk : Chunk { public ScopeChunk() { Body = new List<Chunk>(); } public IList<Chunk> Body { get; set; } } public class ConditionalChunk : Chunk { public ConditionalChunk() { Body = new List<Chunk>(); } public ConditionalType Type { get; set; } public Snippets Condition { get; set; } public IList<Chunk> Body { get; set; } //public IList<Snippet> Snippets { get; set; } } public enum ConditionalType { If, Else, ElseIf, Once, Unless } public class ExtensionChunk : Chunk { public ExtensionChunk() { Body = new List<Chunk>(); } public ISparkExtension Extension { get; set; } public IList<Chunk> Body { get; set; } } public class PageBaseTypeChunk : Chunk { public Snippets BaseClass { get; set; } } public class CacheChunk : Chunk { public CacheChunk() { Body = new List<Chunk>(); } public Snippets Key { get; set; } public Snippets Expires { get; set; } public Snippets Signal { get; set; } public IList<Chunk> Body { get; set; } } public class MarkdownChunk : Chunk { public MarkdownChunk() { Body = new List<Chunk>(); } public IList<Chunk> Body { get; set; } } }
/* * OANDA v20 REST API * * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. * * OpenAPI spec version: 3.0.15 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace Oanda.RestV20.Model { /// <summary> /// A TransferFundsTransaction represents the transfer of funds in/out of an Account. /// </summary> [DataContract] public partial class TransferFundsTransaction : IEquatable<TransferFundsTransaction>, IValidatableObject { /// <summary> /// The Type of the Transaction. Always set to \"TRANSFER_FUNDS\" in a TransferFundsTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"TRANSFER_FUNDS\" in a TransferFundsTransaction.</value> [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { /// <summary> /// Enum CREATE for "CREATE" /// </summary> [EnumMember(Value = "CREATE")] CREATE, /// <summary> /// Enum CLOSE for "CLOSE" /// </summary> [EnumMember(Value = "CLOSE")] CLOSE, /// <summary> /// Enum REOPEN for "REOPEN" /// </summary> [EnumMember(Value = "REOPEN")] REOPEN, /// <summary> /// Enum CLIENTCONFIGURE for "CLIENT_CONFIGURE" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE")] CLIENTCONFIGURE, /// <summary> /// Enum CLIENTCONFIGUREREJECT for "CLIENT_CONFIGURE_REJECT" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE_REJECT")] CLIENTCONFIGUREREJECT, /// <summary> /// Enum TRANSFERFUNDS for "TRANSFER_FUNDS" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS")] TRANSFERFUNDS, /// <summary> /// Enum TRANSFERFUNDSREJECT for "TRANSFER_FUNDS_REJECT" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS_REJECT")] TRANSFERFUNDSREJECT, /// <summary> /// Enum MARKETORDER for "MARKET_ORDER" /// </summary> [EnumMember(Value = "MARKET_ORDER")] MARKETORDER, /// <summary> /// Enum MARKETORDERREJECT for "MARKET_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_ORDER_REJECT")] MARKETORDERREJECT, /// <summary> /// Enum LIMITORDER for "LIMIT_ORDER" /// </summary> [EnumMember(Value = "LIMIT_ORDER")] LIMITORDER, /// <summary> /// Enum LIMITORDERREJECT for "LIMIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "LIMIT_ORDER_REJECT")] LIMITORDERREJECT, /// <summary> /// Enum STOPORDER for "STOP_ORDER" /// </summary> [EnumMember(Value = "STOP_ORDER")] STOPORDER, /// <summary> /// Enum STOPORDERREJECT for "STOP_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_ORDER_REJECT")] STOPORDERREJECT, /// <summary> /// Enum MARKETIFTOUCHEDORDER for "MARKET_IF_TOUCHED_ORDER" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER")] MARKETIFTOUCHEDORDER, /// <summary> /// Enum MARKETIFTOUCHEDORDERREJECT for "MARKET_IF_TOUCHED_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER_REJECT")] MARKETIFTOUCHEDORDERREJECT, /// <summary> /// Enum TAKEPROFITORDER for "TAKE_PROFIT_ORDER" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER")] TAKEPROFITORDER, /// <summary> /// Enum TAKEPROFITORDERREJECT for "TAKE_PROFIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER_REJECT")] TAKEPROFITORDERREJECT, /// <summary> /// Enum STOPLOSSORDER for "STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER")] STOPLOSSORDER, /// <summary> /// Enum STOPLOSSORDERREJECT for "STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER_REJECT")] STOPLOSSORDERREJECT, /// <summary> /// Enum TRAILINGSTOPLOSSORDER for "TRAILING_STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER")] TRAILINGSTOPLOSSORDER, /// <summary> /// Enum TRAILINGSTOPLOSSORDERREJECT for "TRAILING_STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER_REJECT")] TRAILINGSTOPLOSSORDERREJECT, /// <summary> /// Enum ORDERFILL for "ORDER_FILL" /// </summary> [EnumMember(Value = "ORDER_FILL")] ORDERFILL, /// <summary> /// Enum ORDERCANCEL for "ORDER_CANCEL" /// </summary> [EnumMember(Value = "ORDER_CANCEL")] ORDERCANCEL, /// <summary> /// Enum ORDERCANCELREJECT for "ORDER_CANCEL_REJECT" /// </summary> [EnumMember(Value = "ORDER_CANCEL_REJECT")] ORDERCANCELREJECT, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFY for "ORDER_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY")] ORDERCLIENTEXTENSIONSMODIFY, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFYREJECT for "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT")] ORDERCLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFY for "TRADE_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY")] TRADECLIENTEXTENSIONSMODIFY, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFYREJECT for "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT")] TRADECLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum MARGINCALLENTER for "MARGIN_CALL_ENTER" /// </summary> [EnumMember(Value = "MARGIN_CALL_ENTER")] MARGINCALLENTER, /// <summary> /// Enum MARGINCALLEXTEND for "MARGIN_CALL_EXTEND" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXTEND")] MARGINCALLEXTEND, /// <summary> /// Enum MARGINCALLEXIT for "MARGIN_CALL_EXIT" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXIT")] MARGINCALLEXIT, /// <summary> /// Enum DELAYEDTRADECLOSURE for "DELAYED_TRADE_CLOSURE" /// </summary> [EnumMember(Value = "DELAYED_TRADE_CLOSURE")] DELAYEDTRADECLOSURE, /// <summary> /// Enum DAILYFINANCING for "DAILY_FINANCING" /// </summary> [EnumMember(Value = "DAILY_FINANCING")] DAILYFINANCING, /// <summary> /// Enum RESETRESETTABLEPL for "RESET_RESETTABLE_PL" /// </summary> [EnumMember(Value = "RESET_RESETTABLE_PL")] RESETRESETTABLEPL } /// <summary> /// The reason that an Account is being funded. /// </summary> /// <value>The reason that an Account is being funded.</value> [JsonConverter(typeof(StringEnumConverter))] public enum FundingReasonEnum { /// <summary> /// Enum CLIENTFUNDING for "CLIENT_FUNDING" /// </summary> [EnumMember(Value = "CLIENT_FUNDING")] CLIENTFUNDING, /// <summary> /// Enum ACCOUNTTRANSFER for "ACCOUNT_TRANSFER" /// </summary> [EnumMember(Value = "ACCOUNT_TRANSFER")] ACCOUNTTRANSFER, /// <summary> /// Enum DIVISIONMIGRATION for "DIVISION_MIGRATION" /// </summary> [EnumMember(Value = "DIVISION_MIGRATION")] DIVISIONMIGRATION, /// <summary> /// Enum SITEMIGRATION for "SITE_MIGRATION" /// </summary> [EnumMember(Value = "SITE_MIGRATION")] SITEMIGRATION, /// <summary> /// Enum ADJUSTMENT for "ADJUSTMENT" /// </summary> [EnumMember(Value = "ADJUSTMENT")] ADJUSTMENT } /// <summary> /// The Type of the Transaction. Always set to \"TRANSFER_FUNDS\" in a TransferFundsTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"TRANSFER_FUNDS\" in a TransferFundsTransaction.</value> [DataMember(Name="type", EmitDefaultValue=false)] public TypeEnum? Type { get; set; } /// <summary> /// The reason that an Account is being funded. /// </summary> /// <value>The reason that an Account is being funded.</value> [DataMember(Name="fundingReason", EmitDefaultValue=false)] public FundingReasonEnum? FundingReason { get; set; } /// <summary> /// Initializes a new instance of the <see cref="TransferFundsTransaction" /> class. /// </summary> /// <param name="Id">The Transaction&#39;s Identifier..</param> /// <param name="Time">The date/time when the Transaction was created..</param> /// <param name="UserID">The ID of the user that initiated the creation of the Transaction..</param> /// <param name="AccountID">The ID of the Account the Transaction was created for..</param> /// <param name="BatchID">The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously..</param> /// <param name="RequestID">The Request ID of the request which generated the transaction..</param> /// <param name="Type">The Type of the Transaction. Always set to \&quot;TRANSFER_FUNDS\&quot; in a TransferFundsTransaction..</param> /// <param name="Amount">The amount to deposit/withdraw from the Account in the Account&#39;s home currency. A positive value indicates a deposit, a negative value indicates a withdrawal..</param> /// <param name="FundingReason">The reason that an Account is being funded..</param> /// <param name="Comment">An optional comment that may be attached to a fund transfer for audit purposes.</param> /// <param name="AccountBalance">The Account&#39;s balance after funds are transferred..</param> public TransferFundsTransaction(string Id = default(string), string Time = default(string), int? UserID = default(int?), string AccountID = default(string), string BatchID = default(string), string RequestID = default(string), TypeEnum? Type = default(TypeEnum?), string Amount = default(string), FundingReasonEnum? FundingReason = default(FundingReasonEnum?), string Comment = default(string), string AccountBalance = default(string)) { this.Id = Id; this.Time = Time; this.UserID = UserID; this.AccountID = AccountID; this.BatchID = BatchID; this.RequestID = RequestID; this.Type = Type; this.Amount = Amount; this.FundingReason = FundingReason; this.Comment = Comment; this.AccountBalance = AccountBalance; } /// <summary> /// The Transaction&#39;s Identifier. /// </summary> /// <value>The Transaction&#39;s Identifier.</value> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// The date/time when the Transaction was created. /// </summary> /// <value>The date/time when the Transaction was created.</value> [DataMember(Name="time", EmitDefaultValue=false)] public string Time { get; set; } /// <summary> /// The ID of the user that initiated the creation of the Transaction. /// </summary> /// <value>The ID of the user that initiated the creation of the Transaction.</value> [DataMember(Name="userID", EmitDefaultValue=false)] public int? UserID { get; set; } /// <summary> /// The ID of the Account the Transaction was created for. /// </summary> /// <value>The ID of the Account the Transaction was created for.</value> [DataMember(Name="accountID", EmitDefaultValue=false)] public string AccountID { get; set; } /// <summary> /// The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously. /// </summary> /// <value>The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously.</value> [DataMember(Name="batchID", EmitDefaultValue=false)] public string BatchID { get; set; } /// <summary> /// The Request ID of the request which generated the transaction. /// </summary> /// <value>The Request ID of the request which generated the transaction.</value> [DataMember(Name="requestID", EmitDefaultValue=false)] public string RequestID { get; set; } /// <summary> /// The amount to deposit/withdraw from the Account in the Account&#39;s home currency. A positive value indicates a deposit, a negative value indicates a withdrawal. /// </summary> /// <value>The amount to deposit/withdraw from the Account in the Account&#39;s home currency. A positive value indicates a deposit, a negative value indicates a withdrawal.</value> [DataMember(Name="amount", EmitDefaultValue=false)] public string Amount { get; set; } /// <summary> /// An optional comment that may be attached to a fund transfer for audit purposes /// </summary> /// <value>An optional comment that may be attached to a fund transfer for audit purposes</value> [DataMember(Name="comment", EmitDefaultValue=false)] public string Comment { get; set; } /// <summary> /// The Account&#39;s balance after funds are transferred. /// </summary> /// <value>The Account&#39;s balance after funds are transferred.</value> [DataMember(Name="accountBalance", EmitDefaultValue=false)] public string AccountBalance { 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 TransferFundsTransaction {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Time: ").Append(Time).Append("\n"); sb.Append(" UserID: ").Append(UserID).Append("\n"); sb.Append(" AccountID: ").Append(AccountID).Append("\n"); sb.Append(" BatchID: ").Append(BatchID).Append("\n"); sb.Append(" RequestID: ").Append(RequestID).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" Amount: ").Append(Amount).Append("\n"); sb.Append(" FundingReason: ").Append(FundingReason).Append("\n"); sb.Append(" Comment: ").Append(Comment).Append("\n"); sb.Append(" AccountBalance: ").Append(AccountBalance).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 string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as TransferFundsTransaction); } /// <summary> /// Returns true if TransferFundsTransaction instances are equal /// </summary> /// <param name="other">Instance of TransferFundsTransaction to be compared</param> /// <returns>Boolean</returns> public bool Equals(TransferFundsTransaction other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Time == other.Time || this.Time != null && this.Time.Equals(other.Time) ) && ( this.UserID == other.UserID || this.UserID != null && this.UserID.Equals(other.UserID) ) && ( this.AccountID == other.AccountID || this.AccountID != null && this.AccountID.Equals(other.AccountID) ) && ( this.BatchID == other.BatchID || this.BatchID != null && this.BatchID.Equals(other.BatchID) ) && ( this.RequestID == other.RequestID || this.RequestID != null && this.RequestID.Equals(other.RequestID) ) && ( this.Type == other.Type || this.Type != null && this.Type.Equals(other.Type) ) && ( this.Amount == other.Amount || this.Amount != null && this.Amount.Equals(other.Amount) ) && ( this.FundingReason == other.FundingReason || this.FundingReason != null && this.FundingReason.Equals(other.FundingReason) ) && ( this.Comment == other.Comment || this.Comment != null && this.Comment.Equals(other.Comment) ) && ( this.AccountBalance == other.AccountBalance || this.AccountBalance != null && this.AccountBalance.Equals(other.AccountBalance) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Time != null) hash = hash * 59 + this.Time.GetHashCode(); if (this.UserID != null) hash = hash * 59 + this.UserID.GetHashCode(); if (this.AccountID != null) hash = hash * 59 + this.AccountID.GetHashCode(); if (this.BatchID != null) hash = hash * 59 + this.BatchID.GetHashCode(); if (this.RequestID != null) hash = hash * 59 + this.RequestID.GetHashCode(); if (this.Type != null) hash = hash * 59 + this.Type.GetHashCode(); if (this.Amount != null) hash = hash * 59 + this.Amount.GetHashCode(); if (this.FundingReason != null) hash = hash * 59 + this.FundingReason.GetHashCode(); if (this.Comment != null) hash = hash * 59 + this.Comment.GetHashCode(); if (this.AccountBalance != null) hash = hash * 59 + this.AccountBalance.GetHashCode(); return hash; } } /// <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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Linq; using Xunit; namespace System.Runtime.CompilerServices.Tests { public partial class ConditionalWeakTableTests { [Fact] public static void AddOrUpdateDataTest() { var cwt = new ConditionalWeakTable<string, string>(); string key = "key1"; cwt.AddOrUpdate(key, "value1"); string value; Assert.True(cwt.TryGetValue(key, out value)); Assert.Equal(value, "value1"); Assert.Equal(value, cwt.GetOrCreateValue(key)); Assert.Equal(value, cwt.GetValue(key, k => "value1")); Assert.Throws<ArgumentNullException>(() => cwt.AddOrUpdate(null, "value2")); cwt.AddOrUpdate(key, "value2"); Assert.True(cwt.TryGetValue(key, out value)); Assert.Equal(value, "value2"); Assert.Equal(value, cwt.GetOrCreateValue(key)); Assert.Equal(value, cwt.GetValue(key, k => "value1")); } [Fact] public static void Clear_EmptyTable() { var cwt = new ConditionalWeakTable<object, object>(); cwt.Clear(); // no exception cwt.Clear(); } [Fact] public static void Clear_AddThenEmptyRepeatedly_ItemsRemoved() { var cwt = new ConditionalWeakTable<object, object>(); object key = new object(), value = new object(); object result; for (int i = 0; i < 3; i++) { cwt.Add(key, value); Assert.True(cwt.TryGetValue(key, out result)); Assert.Same(value, result); cwt.Clear(); Assert.False(cwt.TryGetValue(key, out result)); Assert.Null(result); } } [Fact] public static void Clear_AddMany_Clear_AllItemsRemoved() { var cwt = new ConditionalWeakTable<object, object>(); object[] keys = Enumerable.Range(0, 33).Select(_ => new object()).ToArray(); object[] values = Enumerable.Range(0, keys.Length).Select(_ => new object()).ToArray(); for (int i = 0; i < keys.Length; i++) { cwt.Add(keys[i], values[i]); } Assert.Equal(keys.Length, ((IEnumerable<KeyValuePair<object, object>>)cwt).Count()); cwt.Clear(); Assert.Equal(0, ((IEnumerable<KeyValuePair<object, object>>)cwt).Count()); GC.KeepAlive(keys); GC.KeepAlive(values); } [Fact] public static void GetEnumerator_Empty_ReturnsEmptyEnumerator() { var cwt = new ConditionalWeakTable<object, object>(); var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt; Assert.Equal(0, enumerable.Count()); } [Fact] public static void GetEnumerator_AddedAndRemovedItems_AppropriatelyShowUpInEnumeration() { var cwt = new ConditionalWeakTable<object, object>(); var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt; object key1 = new object(), value1 = new object(); for (int i = 0; i < 20; i++) // adding and removing multiple times, across internal container boundary { cwt.Add(key1, value1); Assert.Equal(1, enumerable.Count()); Assert.Equal(new KeyValuePair<object, object>(key1, value1), enumerable.First()); Assert.True(cwt.Remove(key1)); Assert.Equal(0, enumerable.Count()); } GC.KeepAlive(key1); GC.KeepAlive(value1); } [Fact] public static void GetEnumerator_CollectedItemsNotEnumerated() { var cwt = new ConditionalWeakTable<object, object>(); var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt; // Delegate to add collectible items to the table, separated out // to avoid the JIT extending the lifetimes of the temporaries Action<ConditionalWeakTable<object, object>> addItem = t => t.Add(new object(), new object()); for (int i = 0; i < 10; i++) addItem(cwt); GC.Collect(); Assert.Equal(0, enumerable.Count()); } [Fact] public static void GetEnumerator_MultipleEnumeratorsReturnSameResults() { var cwt = new ConditionalWeakTable<object, object>(); var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt; object[] keys = Enumerable.Range(0, 33).Select(_ => new object()).ToArray(); object[] values = Enumerable.Range(0, keys.Length).Select(_ => new object()).ToArray(); for (int i = 0; i < keys.Length; i++) { cwt.Add(keys[i], values[i]); } using (IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator()) using (IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator()) { while (enumerator1.MoveNext()) { Assert.True(enumerator2.MoveNext()); Assert.Equal(enumerator1.Current, enumerator2.Current); } Assert.False(enumerator2.MoveNext()); } GC.KeepAlive(keys); GC.KeepAlive(values); } [Fact] public static void GetEnumerator_RemovedItems_RemovedFromResults() { var cwt = new ConditionalWeakTable<object, object>(); var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt; object[] keys = Enumerable.Range(0, 33).Select(_ => new object()).ToArray(); object[] values = Enumerable.Range(0, keys.Length).Select(_ => new object()).ToArray(); for (int i = 0; i < keys.Length; i++) { cwt.Add(keys[i], values[i]); } for (int i = 0; i < keys.Length; i++) { Assert.Equal(keys.Length - i, enumerable.Count()); Assert.Equal( Enumerable.Range(i, keys.Length - i).Select(j => new KeyValuePair<object, object>(keys[j], values[j])), enumerable); cwt.Remove(keys[i]); } Assert.Equal(0, enumerable.Count()); GC.KeepAlive(keys); GC.KeepAlive(values); } [Fact] public static void GetEnumerator_ItemsAddedAfterGetEnumeratorNotIncluded() { var cwt = new ConditionalWeakTable<object, object>(); var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt; object key1 = new object(), key2 = new object(), value1 = new object(), value2 = new object(); cwt.Add(key1, value1); IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator(); cwt.Add(key2, value2); IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator(); Assert.True(enumerator1.MoveNext()); Assert.Equal(new KeyValuePair<object, object>(key1, value1), enumerator1.Current); Assert.False(enumerator1.MoveNext()); Assert.True(enumerator2.MoveNext()); Assert.Equal(new KeyValuePair<object, object>(key1, value1), enumerator2.Current); Assert.True(enumerator2.MoveNext()); Assert.Equal(new KeyValuePair<object, object>(key2, value2), enumerator2.Current); Assert.False(enumerator2.MoveNext()); enumerator1.Dispose(); enumerator2.Dispose(); GC.KeepAlive(key1); GC.KeepAlive(key2); GC.KeepAlive(value1); GC.KeepAlive(value2); } [Fact] public static void GetEnumerator_ItemsRemovedAfterGetEnumeratorNotIncluded() { var cwt = new ConditionalWeakTable<object, object>(); var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt; object key1 = new object(), key2 = new object(), value1 = new object(), value2 = new object(); cwt.Add(key1, value1); cwt.Add(key2, value2); IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator(); cwt.Remove(key1); IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator(); Assert.True(enumerator1.MoveNext()); Assert.Equal(new KeyValuePair<object, object>(key2, value2), enumerator1.Current); Assert.False(enumerator1.MoveNext()); Assert.True(enumerator2.MoveNext()); Assert.Equal(new KeyValuePair<object, object>(key2, value2), enumerator2.Current); Assert.False(enumerator2.MoveNext()); enumerator1.Dispose(); enumerator2.Dispose(); GC.KeepAlive(key1); GC.KeepAlive(key2); GC.KeepAlive(value1); GC.KeepAlive(value2); } [Fact] public static void GetEnumerator_ItemsClearedAfterGetEnumeratorNotIncluded() { var cwt = new ConditionalWeakTable<object, object>(); var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt; object key1 = new object(), key2 = new object(), value1 = new object(), value2 = new object(); cwt.Add(key1, value1); cwt.Add(key2, value2); IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator(); cwt.Clear(); IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator(); Assert.False(enumerator1.MoveNext()); Assert.False(enumerator2.MoveNext()); enumerator1.Dispose(); enumerator2.Dispose(); GC.KeepAlive(key1); GC.KeepAlive(key2); GC.KeepAlive(value1); GC.KeepAlive(value2); } [Fact] public static void GetEnumerator_Current_ThrowsOnInvalidUse() { var cwt = new ConditionalWeakTable<object, object>(); var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt; object key1 = new object(), value1 = new object(); cwt.Add(key1, value1); using (IEnumerator<KeyValuePair<object, object>> enumerator = enumerable.GetEnumerator()) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); // before first MoveNext } GC.KeepAlive(key1); GC.KeepAlive(value1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Xml.Schema; using System.Diagnostics; using System.Collections.Generic; using System.Globalization; using System.Runtime.Versioning; namespace System.Xml { // Specifies the state of the XmlWriter. public enum WriteState { // Nothing has been written yet. Start, // Writing the prolog. Prolog, // Writing a the start tag for an element. Element, // Writing an attribute value. Attribute, // Writing element content. Content, // XmlWriter is closed; Close has been called. Closed, // Writer is in error state. Error, }; // Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents // that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification. public abstract partial class XmlWriter : IDisposable { // Helper buffer for WriteNode(XmlReader, bool) private char[] _writeNodeBuffer; // Constants private const int WriteNodeBufferSize = 1024; // Returns the settings describing the features of the the writer. Returns null for V1 XmlWriters (XmlTextWriter). public virtual XmlWriterSettings Settings { get { return null; } } // Write methods // Writes out the XML declaration with the version "1.0". public abstract void WriteStartDocument(); //Writes out the XML declaration with the version "1.0" and the speficied standalone attribute. public abstract void WriteStartDocument(bool standalone); //Closes any open elements or attributes and puts the writer back in the Start state. public abstract void WriteEndDocument(); // Writes out the DOCTYPE declaration with the specified name and optional attributes. public abstract void WriteDocType(string name, string pubid, string sysid, string subset); // Writes out the specified start tag and associates it with the given namespace. public void WriteStartElement(string localName, string ns) { WriteStartElement(null, localName, ns); } // Writes out the specified start tag and associates it with the given namespace and prefix. public abstract void WriteStartElement(string prefix, string localName, string ns); // Writes out a start tag with the specified local name with no namespace. public void WriteStartElement(string localName) { WriteStartElement(null, localName, (string)null); } // Closes one element and pops the corresponding namespace scope. public abstract void WriteEndElement(); // Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>. public abstract void WriteFullEndElement(); // Writes out the attribute with the specified LocalName, value, and NamespaceURI. public void WriteAttributeString(string localName, string ns, string value) { WriteStartAttribute(null, localName, ns); WriteString(value); WriteEndAttribute(); } // Writes out the attribute with the specified LocalName and value. public void WriteAttributeString(string localName, string value) { WriteStartAttribute(null, localName, (string)null); WriteString(value); WriteEndAttribute(); } // Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value. public void WriteAttributeString(string prefix, string localName, string ns, string value) { WriteStartAttribute(prefix, localName, ns); WriteString(value); WriteEndAttribute(); } // Writes the start of an attribute. public void WriteStartAttribute(string localName, string ns) { WriteStartAttribute(null, localName, ns); } // Writes the start of an attribute. public abstract void WriteStartAttribute(string prefix, string localName, string ns); // Writes the start of an attribute. public void WriteStartAttribute(string localName) { WriteStartAttribute(null, localName, (string)null); } // Closes the attribute opened by WriteStartAttribute call. public abstract void WriteEndAttribute(); // Writes out a <![CDATA[...]]>; block containing the specified text. public abstract void WriteCData(string text); // Writes out a comment <!--...-->; containing the specified text. public abstract void WriteComment(string text); // Writes out a processing instruction with a space between the name and text as follows: <?name text?> public abstract void WriteProcessingInstruction(string name, string text); // Writes out an entity reference as follows: "&"+name+";". public abstract void WriteEntityRef(string name); // Forces the generation of a character entity for the specified Unicode character value. public abstract void WriteCharEntity(char ch); // Writes out the given whitespace. public abstract void WriteWhitespace(string ws); // Writes out the specified text content. public abstract void WriteString(string text); // Write out the given surrogate pair as an entity reference. public abstract void WriteSurrogateCharEntity(char lowChar, char highChar); // Writes out the specified text content. public abstract void WriteChars(char[] buffer, int index, int count); // Writes raw markup from the given character buffer. public abstract void WriteRaw(char[] buffer, int index, int count); // Writes raw markup from the given string. public abstract void WriteRaw(string data); // Encodes the specified binary bytes as base64 and writes out the resulting text. public abstract void WriteBase64(byte[] buffer, int index, int count); // Encodes the specified binary bytes as binhex and writes out the resulting text. public virtual void WriteBinHex(byte[] buffer, int index, int count) { BinHexEncoder.Encode(buffer, index, count, this); } // Returns the state of the XmlWriter. public abstract WriteState WriteState { get; } // Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader. public abstract void Flush(); // Returns the closest prefix defined in the current namespace scope for the specified namespace URI. public abstract string LookupPrefix(string ns); // Gets an XmlSpace representing the current xml:space scope. public virtual XmlSpace XmlSpace { get { return XmlSpace.Default; } } // Gets the current xml:lang scope. public virtual string XmlLang { get { return string.Empty; } } // Scalar Value Methods // Writes out the specified name, ensuring it is a valid NmToken according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual void WriteNmToken(string name) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } WriteString(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException)); } // Writes out the specified name, ensuring it is a valid Name according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual void WriteName(string name) { WriteString(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException)); } // Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace. public virtual void WriteQualifiedName(string localName, string ns) { if (ns != null && ns.Length > 0) { string prefix = LookupPrefix(ns); if (prefix == null) { throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns)); } WriteString(prefix); WriteString(":"); } WriteString(localName); } // Writes out the specified value. public virtual void WriteValue(object value) { if (value == null) { throw new ArgumentNullException("value"); } WriteString(XmlUntypedStringConverter.Instance.ToString(value, null)); } // Writes out the specified value. public virtual void WriteValue(string value) { if (value == null) { return; } WriteString(value); } // Writes out the specified value. public virtual void WriteValue(bool value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. internal virtual void WriteValue(DateTime value) { WriteString(XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind)); } // Writes out the specified value. public virtual void WriteValue(DateTimeOffset value) { // Under Win8P, WriteValue(DateTime) will invoke this overload, but custom writers // might not have implemented it. This base implementation should call WriteValue(DateTime). // The following conversion results in the same string as calling ToString with DateTimeOffset. if (value.Offset != TimeSpan.Zero) { WriteValue(value.LocalDateTime); } else { WriteValue(value.UtcDateTime); } } // Writes out the specified value. public virtual void WriteValue(double value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(float value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(decimal value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(int value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(long value) { WriteString(XmlConvert.ToString(value)); } // XmlReader Helper Methods // Writes out all the attributes found at the current position in the specified XmlReader. public virtual void WriteAttributes(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException("reader"); } if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.XmlDeclaration) { if (reader.MoveToFirstAttribute()) { WriteAttributes(reader, defattr); reader.MoveToElement(); } } else if (reader.NodeType != XmlNodeType.Attribute) { throw new XmlException(SR.Xml_InvalidPosition, string.Empty); } else { do { // we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault. // If either of these is true and defattr=false, we should not write the attribute out if (defattr || !reader.IsDefaultInternal) { WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI); while (reader.ReadAttributeValue()) { if (reader.NodeType == XmlNodeType.EntityReference) { WriteEntityRef(reader.Name); } else { WriteString(reader.Value); } } WriteEndAttribute(); } } while (reader.MoveToNextAttribute()); } } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. public virtual void WriteNode(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException("reader"); } bool canReadChunk = reader.CanReadValueChunk; int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth; do { switch (reader.NodeType) { case XmlNodeType.Element: WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); WriteAttributes(reader, defattr); if (reader.IsEmptyElement) { WriteEndElement(); break; } break; case XmlNodeType.Text: if (canReadChunk) { if (_writeNodeBuffer == null) { _writeNodeBuffer = new char[WriteNodeBufferSize]; } int read; while ((read = reader.ReadValueChunk(_writeNodeBuffer, 0, WriteNodeBufferSize)) > 0) { this.WriteChars(_writeNodeBuffer, 0, read); } } else { WriteString(reader.Value); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: WriteWhitespace(reader.Value); break; case XmlNodeType.CDATA: WriteCData(reader.Value); break; case XmlNodeType.EntityReference: WriteEntityRef(reader.Name); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: WriteProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.DocumentType: WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value); break; case XmlNodeType.Comment: WriteComment(reader.Value); break; case XmlNodeType.EndElement: WriteFullEndElement(); break; } } while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement))); } // Element Helper Methods // Writes out an element with the specified name containing the specified string value. public void WriteElementString(string localName, String value) { WriteElementString(localName, null, value); } // Writes out an attribute with the specified name, namespace URI and string value. public void WriteElementString(string localName, String ns, String value) { WriteStartElement(localName, ns); if (null != value && 0 != value.Length) { WriteString(value); } WriteEndElement(); } // Writes out an attribute with the specified name, namespace URI, and string value. public void WriteElementString(string prefix, String localName, String ns, String value) { WriteStartElement(prefix, localName, ns); if (null != value && 0 != value.Length) { WriteString(value); } WriteEndElement(); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { } // // Static methods for creating writers // // Creates an XmlWriter for writing into the provided stream. public static XmlWriter Create(Stream output) { return Create(output, null); } // Creates an XmlWriter for writing into the provided stream with the specified settings. public static XmlWriter Create(Stream output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } return settings.CreateWriter(output); } // Creates an XmlWriter for writing into the provided TextWriter. public static XmlWriter Create(TextWriter output) { return Create(output, null); } // Creates an XmlWriter for writing into the provided TextWriter with the specified settings. public static XmlWriter Create(TextWriter output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } return settings.CreateWriter(output); } // Creates an XmlWriter for writing into the provided StringBuilder. public static XmlWriter Create(StringBuilder output) { return Create(output, null); } // Creates an XmlWriter for writing into the provided StringBuilder with the specified settings. public static XmlWriter Create(StringBuilder output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } if (output == null) { throw new ArgumentNullException("output"); } return settings.CreateWriter(new StringWriter(output, CultureInfo.InvariantCulture)); } // Creates an XmlWriter wrapped around the provided XmlWriter with the default settings. public static XmlWriter Create(XmlWriter output) { return Create(output, null); } // Creates an XmlWriter wrapped around the provided XmlWriter with the specified settings. public static XmlWriter Create(XmlWriter output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } return settings.CreateWriter(output); } } }
// 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: Helper functions that require elevation but are safe to use. * \***************************************************************************/ // The SecurityHelper class differs between assemblies and could not actually be // shared, so it is duplicated across namespaces to prevent name collision. // This duplication seems hardly necessary now. We should continue // trying to reduce it by pushing things from Framework to Core (whenever it makes sense). #if WINDOWS_BASE namespace MS.Internal.WindowsBase #elif PRESENTATION_CORE using MS.Internal.PresentationCore; namespace MS.Internal // Promote the one from PresentationCore as the default to use. #elif PRESENTATIONFRAMEWORK namespace MS.Internal.PresentationFramework #elif PBTCOMPILER namespace MS.Internal.PresentationBuildTasks #elif REACHFRAMEWORK namespace MS.Internal.ReachFramework #elif DRT namespace MS.Internal.Drt #else #error Class is being used from an unknown assembly. #endif { using System; using System.Globalization; // CultureInfo using System.Security; using System.ComponentModel; using System.Runtime.InteropServices; using Microsoft.Win32; using System.Diagnostics.CodeAnalysis; #if !PBTCOMPILER using MS.Win32; using System.IO.Packaging; #endif #if PRESENTATION_CORE using MS.Internal.AppModel; #endif #if PRESENTATIONFRAMEWORK_ONLY using System.Diagnostics; using System.Windows; using MS.Internal.Utility; // BindUriHelper using MS.Internal.AppModel; #endif #if REACHFRAMEWORK using MS.Internal.Utility; #endif #if WINDOWS_BASE // This existed originally to allow FontCache service to // see the WindowsBase variant of this class. We no longer have // a FontCache service, but over time other parts of WPF might // have started to depend on this, so we leave it as-is for // compat. [FriendAccessAllowed] #endif internal static class SecurityHelper { #if PRESENTATION_CORE internal static Uri GetBaseDirectory(AppDomain domain) { Uri appBase = null; appBase = new Uri(domain.BaseDirectory); return( appBase ); } internal static int MapUrlToZoneWrapper(Uri uri) { int targetZone = NativeMethods.URLZONE_LOCAL_MACHINE ; // fail securely this is the most priveleged zone int hr = NativeMethods.S_OK ; object curSecMgr = null; hr = UnsafeNativeMethods.CoInternetCreateSecurityManager( null, out curSecMgr , 0 ); if ( NativeMethods.Failed( hr )) throw new Win32Exception( hr ) ; UnsafeNativeMethods.IInternetSecurityManager pSec = (UnsafeNativeMethods.IInternetSecurityManager) curSecMgr; string uriString = BindUriHelper.UriToString( uri ) ; // // special case the condition if file is on local machine or UNC to ensure that content with mark of the web // does not yield with an internet zone result // if (uri.IsFile) { pSec.MapUrlToZone( uriString, out targetZone, MS.Win32.NativeMethods.MUTZ_NOSAVEDFILECHECK ); } else { pSec.MapUrlToZone( uriString, out targetZone, 0 ); } // // This is the condition for Invalid zone // if (targetZone < 0) { throw new SecurityException( SR.Get(SRID.Invalid_URI) ); } pSec = null; curSecMgr = null; return targetZone; } #endif #if WINDOWS_BASE internal static void RunClassConstructor(Type t) { System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(t.TypeHandle); } #endif // WINDOWS_BASE #if DRT /// <remarks> The LinkDemand on Marshal.SizeOf() was removed in v4. </remarks> internal static int SizeOf(Type t) { return Marshal.SizeOf(t); } #endif #if DRT internal static int SizeOf(Object o) { return Marshal.SizeOf(o); } #endif #if WINDOWS_BASE || PRESENTATION_CORE || PRESENTATIONFRAMEWORK internal static Exception GetExceptionForHR(int hr) { return Marshal.GetExceptionForHR(hr, new IntPtr(-1)); } #endif #if WINDOWS_BASE || PRESENTATION_CORE internal static void ThrowExceptionForHR(int hr) { Marshal.ThrowExceptionForHR(hr, new IntPtr(-1)); } internal static int GetHRForException(Exception exception) { if (exception == null) { throw new ArgumentNullException("exception"); } // GetHRForException fills a per thread IErrorInfo object with data from the exception // The exception may contain security sensitive data like full file paths that we do not // want to leak into an IErrorInfo int hr = Marshal.GetHRForException(exception); // Call GetHRForException a second time with a security safe exception object // to make sure the per thread IErrorInfo is cleared of security sensitive data Marshal.GetHRForException(new Exception()); return hr; } #endif #if PRESENTATIONFRAMEWORK /// <summary> /// A helper method to do the necessary work to display a standard MessageBox. This method performs /// and necessary elevations to make the dialog work as well. /// </summary> internal static void ShowMessageBoxHelper( System.Windows.Window parent, string text, string title, System.Windows.MessageBoxButton buttons, System.Windows.MessageBoxImage image ) { // if we have a known parent window set, let's use it when alerting the user. if (parent != null) { System.Windows.MessageBox.Show(parent, text, title, buttons, image); } else { System.Windows.MessageBox.Show(text, title, buttons, image); } } /// <summary> /// A helper method to do the necessary work to display a standard MessageBox. This method performs /// and necessary elevations to make the dialog work as well. /// </summary> internal static void ShowMessageBoxHelper( IntPtr parentHwnd, string text, string title, System.Windows.MessageBoxButton buttons, System.Windows.MessageBoxImage image ) { // NOTE: the last param must always be MessageBoxOptions.None for this to be considered TreatAsSafe System.Windows.MessageBox.ShowCore(parentHwnd, text, title, buttons, image, MessageBoxResult.None, MessageBoxOptions.None); } #endif #if PRESENTATION_CORE || PRESENTATIONFRAMEWORK || WINDOWS_BASE internal static bool AreStringTypesEqual(string m1, string m2) { return (String.Compare(m1, m2, StringComparison.OrdinalIgnoreCase) == 0); } #endif //PRESENTATION_CORE || PRESENTATIONFRAMEWORK || WINDOWS_BASE #if WINDOWS_BASE /// /// Read and return a registry value. static internal object ReadRegistryValue( RegistryKey baseRegistryKey, string keyName, string valueName ) { object value = null; RegistryKey key = baseRegistryKey.OpenSubKey(keyName); if (key != null) { using( key ) { value = key.GetValue(valueName); } } return value; } #endif // WINDOWS_BASE } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.Threading; using dnlib.DotNet.MD; namespace dnlib.DotNet { /// <summary> /// A high-level representation of a row in the MemberRef table /// </summary> public abstract class MemberRef : IHasCustomAttribute, IMethodDefOrRef, ICustomAttributeType, IField, IContainsGenericParameter { /// <summary> /// The row id in its table /// </summary> protected uint rid; /// <summary> /// The owner module /// </summary> protected ModuleDef module; /// <inheritdoc/> public MDToken MDToken { get { return new MDToken(Table.MemberRef, rid); } } /// <inheritdoc/> public uint Rid { get { return rid; } set { rid = value; } } /// <inheritdoc/> public int HasCustomAttributeTag { get { return 6; } } /// <inheritdoc/> public int MethodDefOrRefTag { get { return 1; } } /// <inheritdoc/> public int CustomAttributeTypeTag { get { return 3; } } /// <summary> /// From column MemberRef.Class /// </summary> public IMemberRefParent Class { get { return @class; } set { @class = value; } } /// <summary/> protected IMemberRefParent @class; /// <summary> /// From column MemberRef.Name /// </summary> public UTF8String Name { get { return name; } set { name = value; } } /// <summary>Name</summary> protected UTF8String name; /// <summary> /// From column MemberRef.Signature /// </summary> public CallingConventionSig Signature { get { return signature; } set { signature = value; } } /// <summary/> protected CallingConventionSig signature; /// <summary> /// Gets all custom attributes /// </summary> public CustomAttributeCollection CustomAttributes { get { if (customAttributes == null) InitializeCustomAttributes(); return customAttributes; } } /// <summary/> protected CustomAttributeCollection customAttributes; /// <summary>Initializes <see cref="customAttributes"/></summary> protected virtual void InitializeCustomAttributes() { Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null); } /// <inheritdoc/> public bool HasCustomAttributes { get { return CustomAttributes.Count > 0; } } /// <inheritdoc/> public ITypeDefOrRef DeclaringType { get { var owner = @class; var tdr = owner as ITypeDefOrRef; if (tdr != null) return tdr; var method = owner as MethodDef; if (method != null) return method.DeclaringType; var mr = owner as ModuleRef; if (mr != null) { var tr = GetGlobalTypeRef(mr); if (module != null) return module.UpdateRowId(tr); return tr; } return null; } } TypeRefUser GetGlobalTypeRef(ModuleRef mr) { if (module == null) return CreateDefaultGlobalTypeRef(mr); var globalType = module.GlobalType; if (globalType != null && new SigComparer().Equals(module, mr)) return new TypeRefUser(module, globalType.Namespace, globalType.Name, mr); var asm = module.Assembly; if (asm == null) return CreateDefaultGlobalTypeRef(mr); var mod = asm.FindModule(mr.Name); if (mod == null) return CreateDefaultGlobalTypeRef(mr); globalType = mod.GlobalType; if (globalType == null) return CreateDefaultGlobalTypeRef(mr); return new TypeRefUser(module, globalType.Namespace, globalType.Name, mr); } TypeRefUser CreateDefaultGlobalTypeRef(ModuleRef mr) { var tr = new TypeRefUser(module, string.Empty, "<Module>", mr); if (module != null) module.UpdateRowId(tr); return tr; } bool IIsTypeOrMethod.IsType { get { return false; } } bool IIsTypeOrMethod.IsMethod { get { return IsMethodRef; } } bool IMemberRef.IsField { get { return IsFieldRef; } } bool IMemberRef.IsTypeSpec { get { return false; } } bool IMemberRef.IsTypeRef { get { return false; } } bool IMemberRef.IsTypeDef { get { return false; } } bool IMemberRef.IsMethodSpec { get { return false; } } bool IMemberRef.IsMethodDef { get { return false; } } bool IMemberRef.IsMemberRef { get { return true; } } bool IMemberRef.IsFieldDef { get { return false; } } bool IMemberRef.IsPropertyDef { get { return false; } } bool IMemberRef.IsEventDef { get { return false; } } bool IMemberRef.IsGenericParam { get { return false; } } /// <summary> /// <c>true</c> if this is a method reference (<see cref="MethodSig"/> != <c>null</c>) /// </summary> public bool IsMethodRef { get { return MethodSig != null; } } /// <summary> /// <c>true</c> if this is a field reference (<see cref="FieldSig"/> != <c>null</c>) /// </summary> public bool IsFieldRef { get { return FieldSig != null; } } /// <summary> /// Gets/sets the method sig /// </summary> public MethodSig MethodSig { get { return signature as MethodSig; } set { signature = value; } } /// <summary> /// Gets/sets the field sig /// </summary> public FieldSig FieldSig { get { return signature as FieldSig; } set { signature = value; } } /// <inheritdoc/> public ModuleDef Module { get { return module; } } /// <summary> /// <c>true</c> if the method has a hidden 'this' parameter /// </summary> public bool HasThis { get { var ms = MethodSig; return ms == null ? false : ms.HasThis; } } /// <summary> /// <c>true</c> if the method has an explicit 'this' parameter /// </summary> public bool ExplicitThis { get { var ms = MethodSig; return ms == null ? false : ms.ExplicitThis; } } /// <summary> /// Gets the calling convention /// </summary> public CallingConvention CallingConvention { get { var ms = MethodSig; return ms == null ? 0 : ms.CallingConvention & CallingConvention.Mask; } } /// <summary> /// Gets/sets the method return type /// </summary> public TypeSig ReturnType { get { var ms = MethodSig; return ms == null ? null : ms.RetType; } set { var ms = MethodSig; if (ms != null) ms.RetType = value; } } /// <inheritdoc/> int IGenericParameterProvider.NumberOfGenericParameters { get { var sig = MethodSig; return sig == null ? 0 : (int)sig.GenParamCount; } } /// <summary> /// Gets the full name /// </summary> public string FullName { get { var parent = @class; IList<TypeSig> typeGenArgs = null; if (parent is TypeSpec) { var sig = ((TypeSpec)parent).TypeSig as GenericInstSig; if (sig != null) typeGenArgs = sig.GenericArguments; } var methodSig = MethodSig; if (methodSig != null) return FullNameCreator.MethodFullName(GetDeclaringTypeFullName(parent), name, methodSig, typeGenArgs, null); var fieldSig = FieldSig; if (fieldSig != null) return FullNameCreator.FieldFullName(GetDeclaringTypeFullName(parent), name, fieldSig, typeGenArgs); return string.Empty; } } /// <summary> /// Get the declaring type's full name /// </summary> /// <returns>Full name or <c>null</c> if there's no declaring type</returns> public string GetDeclaringTypeFullName() { return GetDeclaringTypeFullName(@class); } string GetDeclaringTypeFullName(IMemberRefParent parent) { if (parent == null) return null; if (parent is ITypeDefOrRef) return ((ITypeDefOrRef)parent).FullName; if (parent is ModuleRef) return string.Format("[module:{0}]<Module>", ((ModuleRef)parent).ToString()); if (parent is MethodDef) { var declaringType = ((MethodDef)parent).DeclaringType; return declaringType == null ? null : declaringType.FullName; } return null; // Should never be reached } /// <summary> /// Resolves the method/field /// </summary> /// <returns>A <see cref="MethodDef"/> or a <see cref="FieldDef"/> instance or <c>null</c> /// if it couldn't be resolved.</returns> public IMemberForwarded Resolve() { if (module == null) return null; return module.Context.Resolver.Resolve(this); } /// <summary> /// Resolves the method/field /// </summary> /// <returns>A <see cref="MethodDef"/> or a <see cref="FieldDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the method/field couldn't be resolved</exception> public IMemberForwarded ResolveThrow() { var memberDef = Resolve(); if (memberDef != null) return memberDef; throw new MemberRefResolveException(string.Format("Could not resolve method/field: {0} ({1})", this, this.GetDefinitionAssembly())); } /// <summary> /// Resolves the field /// </summary> /// <returns>A <see cref="FieldDef"/> instance or <c>null</c> if it couldn't be resolved.</returns> public FieldDef ResolveField() { return Resolve() as FieldDef; } /// <summary> /// Resolves the field /// </summary> /// <returns>A <see cref="FieldDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the field couldn't be resolved</exception> public FieldDef ResolveFieldThrow() { var field = ResolveField(); if (field != null) return field; throw new MemberRefResolveException(string.Format("Could not resolve field: {0} ({1})", this, this.GetDefinitionAssembly())); } /// <summary> /// Resolves the method /// </summary> /// <returns>A <see cref="MethodDef"/> instance or <c>null</c> if it couldn't be resolved.</returns> public MethodDef ResolveMethod() { return Resolve() as MethodDef; } /// <summary> /// Resolves the method /// </summary> /// <returns>A <see cref="MethodDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the method couldn't be resolved</exception> public MethodDef ResolveMethodThrow() { var method = ResolveMethod(); if (method != null) return method; throw new MemberRefResolveException(string.Format("Could not resolve method: {0} ({1})", this, this.GetDefinitionAssembly())); } bool IContainsGenericParameter.ContainsGenericParameter { get { return TypeHelper.ContainsGenericParameter(this); } } /// <summary> /// Gets a <see cref="GenericParamContext"/> that can be used as signature context /// </summary> /// <param name="gpContext">Context passed to the constructor</param> /// <param name="class">Field/method class owner</param> /// <returns></returns> protected static GenericParamContext GetSignatureGenericParamContext(GenericParamContext gpContext, IMemberRefParent @class) { TypeDef type = null; MethodDef method = gpContext.Method; var ts = @class as TypeSpec; if (ts != null) { var gis = ts.TypeSig as GenericInstSig; if (gis != null) type = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef(); } return new GenericParamContext(type, method); } /// <inheritdoc/> public override string ToString() { return FullName; } } /// <summary> /// A MemberRef row created by the user and not present in the original .NET file /// </summary> public class MemberRefUser : MemberRef { /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> public MemberRefUser(ModuleDef module) { this.module = module; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of ref</param> public MemberRefUser(ModuleDef module, UTF8String name) { this.module = module; this.name = name; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of field ref</param> /// <param name="sig">Field sig</param> public MemberRefUser(ModuleDef module, UTF8String name, FieldSig sig) : this(module, name, sig, null) { } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of field ref</param> /// <param name="sig">Field sig</param> /// <param name="class">Owner of field</param> public MemberRefUser(ModuleDef module, UTF8String name, FieldSig sig, IMemberRefParent @class) { this.module = module; this.name = name; this.@class = @class; this.signature = sig; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of method ref</param> /// <param name="sig">Method sig</param> public MemberRefUser(ModuleDef module, UTF8String name, MethodSig sig) : this(module, name, sig, null) { } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of method ref</param> /// <param name="sig">Method sig</param> /// <param name="class">Owner of method</param> public MemberRefUser(ModuleDef module, UTF8String name, MethodSig sig, IMemberRefParent @class) { this.module = module; this.name = name; this.@class = @class; this.signature = sig; } } /// <summary> /// Created from a row in the MemberRef table /// </summary> sealed class MemberRefMD : MemberRef, IMDTokenProviderMD { /// <summary>The module where this instance is located</summary> readonly ModuleDefMD readerModule; readonly uint origRid; /// <inheritdoc/> public uint OrigRid { get { return origRid; } } /// <inheritdoc/> protected override void InitializeCustomAttributes() { var list = readerModule.MetaData.GetCustomAttributeRidList(Table.MemberRef, origRid); var tmp = new CustomAttributeCollection((int)list.Length, list, (list2, index) => readerModule.ReadCustomAttribute(((RidList)list2)[index])); Interlocked.CompareExchange(ref customAttributes, tmp, null); } /// <summary> /// Constructor /// </summary> /// <param name="readerModule">The module which contains this <c>MemberRef</c> row</param> /// <param name="rid">Row ID</param> /// <param name="gpContext">Generic parameter context</param> /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception> /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception> public MemberRefMD(ModuleDefMD readerModule, uint rid, GenericParamContext gpContext) { #if DEBUG if (readerModule == null) throw new ArgumentNullException("readerModule"); if (readerModule.TablesStream.MemberRefTable.IsInvalidRID(rid)) throw new BadImageFormatException(string.Format("MemberRef rid {0} does not exist", rid)); #endif this.origRid = rid; this.rid = rid; this.readerModule = readerModule; this.module = readerModule; uint @class, name; uint signature = readerModule.TablesStream.ReadMemberRefRow(origRid, out @class, out name); this.name = readerModule.StringsStream.ReadNoNull(name); this.@class = readerModule.ResolveMemberRefParent(@class, gpContext); this.signature = readerModule.ReadSignature(signature, GetSignatureGenericParamContext(gpContext, this.@class)); } } }
#region License // /* // See license included in this library folder. // */ #endregion using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Text; using System.Xml; using Sqloogle.Libs.NLog.Internal; #if !SILVERLIGHT namespace Sqloogle.Libs.NLog { /// <summary> /// TraceListener which routes all messages through NLog. /// </summary> public class NLogTraceListener : TraceListener { private static readonly Assembly systemAssembly = typeof (Trace).Assembly; private LogFactory logFactory; private LogLevel defaultLogLevel = LogLevel.Debug; private bool attributesLoaded; #if !NET_CF private bool autoLoggerName; #endif private LogLevel forceLogLevel; /// <summary> /// Gets or sets the log factory to use when outputting messages (null - use LogManager). /// </summary> public LogFactory LogFactory { get { InitAttributes(); return logFactory; } set { attributesLoaded = true; logFactory = value; } } /// <summary> /// Gets or sets the default log level. /// </summary> public LogLevel DefaultLogLevel { get { InitAttributes(); return defaultLogLevel; } set { attributesLoaded = true; defaultLogLevel = value; } } /// <summary> /// Gets or sets the log which should be always used regardless of source level. /// </summary> public LogLevel ForceLogLevel { get { InitAttributes(); return forceLogLevel; } set { attributesLoaded = true; forceLogLevel = value; } } #if !NET_CF /// <summary> /// Gets a value indicating whether the trace listener is thread safe. /// </summary> /// <value></value> /// <returns>true if the trace listener is thread safe; otherwise, false. The default is false.</returns> public override bool IsThreadSafe { get { return true; } } /// <summary> /// Gets or sets a value indicating whether to use auto logger name detected from the stack trace. /// </summary> public bool AutoLoggerName { get { InitAttributes(); return autoLoggerName; } set { attributesLoaded = true; autoLoggerName = value; } } #endif /// <summary> /// When overridden in a derived class, writes the specified message to the listener you create in the derived class. /// </summary> /// <param name="message">A message to write.</param> public override void Write(string message) { ProcessLogEventInfo(DefaultLogLevel, null, message, null, null); } /// <summary> /// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator. /// </summary> /// <param name="message">A message to write.</param> public override void WriteLine(string message) { ProcessLogEventInfo(DefaultLogLevel, null, message, null, null); } /// <summary> /// When overridden in a derived class, closes the output stream so it no longer receives tracing or debugging output. /// </summary> public override void Close() { } /// <summary> /// Emits an error message. /// </summary> /// <param name="message">A message to emit.</param> public override void Fail(string message) { ProcessLogEventInfo(LogLevel.Error, null, message, null, null); } /// <summary> /// Emits an error message and a detailed error message. /// </summary> /// <param name="message">A message to emit.</param> /// <param name="detailMessage">A detailed message to emit.</param> public override void Fail(string message, string detailMessage) { ProcessLogEventInfo(LogLevel.Error, null, message + " " + detailMessage, null, null); } /// <summary> /// Flushes the output buffer. /// </summary> public override void Flush() { if (LogFactory != null) { LogFactory.Flush(); } else { LogManager.Flush(); } } #if !NET_CF /// <summary> /// Writes trace information, a data object and event information to the listener specific output. /// </summary> /// <param name="eventCache"> /// A <see cref="T:System.Diagnostics.TraceEventCache" /> object that contains the current process ID, thread ID, and stack trace information. /// </param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType"> /// One of the <see cref="T:System.Diagnostics.TraceEventType" /> values specifying the type of event that has caused the trace. /// </param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="data">The trace data to emit.</param> public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { TraceData(eventCache, source, eventType, id, new[] {data}); } /// <summary> /// Writes trace information, an array of data objects and event information to the listener specific output. /// </summary> /// <param name="eventCache"> /// A <see cref="T:System.Diagnostics.TraceEventCache" /> object that contains the current process ID, thread ID, and stack trace information. /// </param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType"> /// One of the <see cref="T:System.Diagnostics.TraceEventType" /> values specifying the type of event that has caused the trace. /// </param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="data">An array of objects to emit as data.</param> public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data) { var sb = new StringBuilder(); for (var i = 0; i < data.Length; ++i) { if (i > 0) { sb.Append(", "); } sb.Append("{"); sb.Append(i); sb.Append("}"); } ProcessLogEventInfo(TranslateLogLevel(eventType), source, sb.ToString(), data, id); } /// <summary> /// Writes trace and event information to the listener specific output. /// </summary> /// <param name="eventCache"> /// A <see cref="T:System.Diagnostics.TraceEventCache" /> object that contains the current process ID, thread ID, and stack trace information. /// </param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType"> /// One of the <see cref="T:System.Diagnostics.TraceEventType" /> values specifying the type of event that has caused the trace. /// </param> /// <param name="id">A numeric identifier for the event.</param> public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id) { ProcessLogEventInfo(TranslateLogLevel(eventType), source, string.Empty, null, id); } /// <summary> /// Writes trace information, a formatted array of objects and event information to the listener specific output. /// </summary> /// <param name="eventCache"> /// A <see cref="T:System.Diagnostics.TraceEventCache" /> object that contains the current process ID, thread ID, and stack trace information. /// </param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType"> /// One of the <see cref="T:System.Diagnostics.TraceEventType" /> values specifying the type of event that has caused the trace. /// </param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="format"> /// A format string that contains zero or more format items, which correspond to objects in the <paramref name="args" /> array. /// </param> /// <param name="args">An object array containing zero or more objects to format.</param> public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { ProcessLogEventInfo(TranslateLogLevel(eventType), source, format, args, id); } /// <summary> /// Writes trace information, a message, and event information to the listener specific output. /// </summary> /// <param name="eventCache"> /// A <see cref="T:System.Diagnostics.TraceEventCache" /> object that contains the current process ID, thread ID, and stack trace information. /// </param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType"> /// One of the <see cref="T:System.Diagnostics.TraceEventType" /> values specifying the type of event that has caused the trace. /// </param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="message">A message to write.</param> public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { ProcessLogEventInfo(TranslateLogLevel(eventType), source, message, null, id); } /// <summary> /// Writes trace information, a message, a related activity identity and event information to the listener specific output. /// </summary> /// <param name="eventCache"> /// A <see cref="T:System.Diagnostics.TraceEventCache" /> object that contains the current process ID, thread ID, and stack trace information. /// </param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="message">A message to write.</param> /// <param name="relatedActivityId"> /// A <see cref="T:System.Guid" /> object identifying a related activity. /// </param> public override void TraceTransfer(TraceEventCache eventCache, string source, int id, string message, Guid relatedActivityId) { ProcessLogEventInfo(LogLevel.Debug, source, message, null, id); } /// <summary> /// Gets the custom attributes supported by the trace listener. /// </summary> /// <returns> /// A string array naming the custom attributes supported by the trace listener, or null if there are no custom attributes. /// </returns> protected override string[] GetSupportedAttributes() { return new[] {"defaultLogLevel", "autoLoggerName", "forceLogLevel"}; } /// <summary> /// Translates the event type to level from <see cref="TraceEventType" />. /// </summary> /// <param name="eventType">Type of the event.</param> /// <returns>Translated log level.</returns> private static LogLevel TranslateLogLevel(TraceEventType eventType) { switch (eventType) { case TraceEventType.Verbose: return LogLevel.Trace; case TraceEventType.Information: return LogLevel.Info; case TraceEventType.Warning: return LogLevel.Warn; case TraceEventType.Error: return LogLevel.Error; case TraceEventType.Critical: return LogLevel.Fatal; default: return LogLevel.Debug; } } #endif private void ProcessLogEventInfo(LogLevel logLevel, string loggerName, [Localizable(false)] string message, object[] arguments, int? eventId) { var ev = new LogEventInfo(); ev.LoggerName = (loggerName ?? Name) ?? string.Empty; #if !NET_CF if (AutoLoggerName) { var stack = new StackTrace(); var userFrameIndex = -1; MethodBase userMethod = null; for (var i = 0; i < stack.FrameCount; ++i) { var frame = stack.GetFrame(i); var method = frame.GetMethod(); if (method.DeclaringType == GetType()) { // skip all methods of this type continue; } if (method.DeclaringType.Assembly == systemAssembly) { // skip all methods from System.dll continue; } userFrameIndex = i; userMethod = method; break; } if (userFrameIndex >= 0) { ev.SetStackTrace(stack, userFrameIndex); if (userMethod.DeclaringType != null) { ev.LoggerName = userMethod.DeclaringType.FullName; } } } #endif ev.TimeStamp = CurrentTimeGetter.Now; ev.Message = message; ev.Parameters = arguments; ev.Level = forceLogLevel ?? logLevel; if (eventId.HasValue) { ev.Properties.Add("EventID", eventId.Value); } var logger = LogManager.GetLogger(ev.LoggerName); logger.Log(ev); } private void InitAttributes() { if (!attributesLoaded) { attributesLoaded = true; #if !NET_CF foreach (DictionaryEntry de in Attributes) { var key = (string) de.Key; var value = (string) de.Value; switch (key.ToUpperInvariant()) { case "DEFAULTLOGLEVEL": defaultLogLevel = LogLevel.FromString(value); break; case "FORCELOGLEVEL": forceLogLevel = LogLevel.FromString(value); break; case "AUTOLOGGERNAME": AutoLoggerName = XmlConvert.ToBoolean(value); break; } } #endif } } } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for QueuesOperations. /// </summary> public static partial class QueuesOperationsExtensions { /// <summary> /// Lists the queues within the namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> public static IPage<QueueResource> ListAll(this IQueuesOperations operations, string resourceGroupName, string namespaceName) { return Task.Factory.StartNew(s => ((IQueuesOperations)s).ListAllAsync(resourceGroupName, namespaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the queues within the namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<QueueResource>> ListAllAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates/Updates a service Queue. This operation is idempotent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Queue Resource. /// </param> public static QueueResource CreateOrUpdate(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, QueueCreateOrUpdateParameters parameters) { return Task.Factory.StartNew(s => ((IQueuesOperations)s).CreateOrUpdateAsync(resourceGroupName, namespaceName, queueName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates/Updates a service Queue. This operation is idempotent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Queue Resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<QueueResource> CreateOrUpdateAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, QueueCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a queue from the specified namespace in resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> public static void Delete(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName) { Task.Factory.StartNew(s => ((IQueuesOperations)s).DeleteAsync(resourceGroupName, namespaceName, queueName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a queue from the specified namespace in resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns the description for the specified queue. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> public static QueueResource Get(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName) { return Task.Factory.StartNew(s => ((IQueuesOperations)s).GetAsync(resourceGroupName, namespaceName, queueName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns the description for the specified queue. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<QueueResource> GetAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns all Queue authorizationRules. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRules(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName) { return Task.Factory.StartNew(s => ((IQueuesOperations)s).ListAuthorizationRulesAsync(resourceGroupName, namespaceName, queueName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns all Queue authorizationRules. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates an authorization rule for a queue /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> public static SharedAccessAuthorizationRuleResource CreateOrUpdateAuthorizationRule(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) { return Task.Factory.StartNew(s => ((IQueuesOperations)s).CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates an authorization rule for a queue /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SharedAccessAuthorizationRuleResource> CreateOrUpdateAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a queue authorization rule /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> public static void DeleteAuthorizationRule(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName) { Task.Factory.StartNew(s => ((IQueuesOperations)s).DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a queue authorization rule /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Queue authorizationRule for a queue by name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> public static SharedAccessAuthorizationRuleResource GetAuthorizationRule(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName) { return Task.Factory.StartNew(s => ((IQueuesOperations)s).GetAuthorizationRuleAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Queue authorizationRule for a queue by name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SharedAccessAuthorizationRuleResource> GetAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Primary and Secondary ConnectionStrings to the queue. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> public static ResourceListKeys ListKeys(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName) { return Task.Factory.StartNew(s => ((IQueuesOperations)s).ListKeysAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Primary and Secondary ConnectionStrings to the queue. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceListKeys> ListKeysAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the Primary or Secondary ConnectionStrings to the Queue /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate Auth Rule. /// </param> public static ResourceListKeys RegenerateKeys(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, RegenerateKeysParameters parameters) { return Task.Factory.StartNew(s => ((IQueuesOperations)s).RegenerateKeysAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Regenerates the Primary or Secondary ConnectionStrings to the Queue /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate Auth Rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceListKeys> RegenerateKeysAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, RegenerateKeysParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the queues within the namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<QueueResource> ListAllNext(this IQueuesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IQueuesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the queues within the namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<QueueResource>> ListAllNextAsync(this IQueuesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns all Queue authorizationRules. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRulesNext(this IQueuesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IQueuesOperations)s).ListAuthorizationRulesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns all Queue authorizationRules. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesNextAsync(this IQueuesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// 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. // NOTE: This is a generated file - do not manually edit! #pragma warning disable 649 using System; using System.IO; using System.Collections.Generic; using System.Reflection; using Internal.NativeFormat; using Debug = System.Diagnostics.Debug; namespace Internal.Metadata.NativeFormat { internal static partial class MdBinaryReader { public static unsafe uint Read(this NativeReader reader, uint offset, out BooleanCollection values) { values = new BooleanCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Boolean)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out CharCollection values) { values = new CharCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Char)); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out StringCollection values) { values = new StringCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out ByteCollection values) { values = new ByteCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Byte)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out SByteCollection values) { values = new SByteCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(SByte)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out Int16Collection values) { values = new Int16Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Int16)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out UInt16Collection values) { values = new UInt16Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(UInt16)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out Int32Collection values) { values = new Int32Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Int32)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out UInt32Collection values) { values = new UInt32Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(UInt32)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out Int64Collection values) { values = new Int64Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Int64)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out UInt64Collection values) { values = new UInt64Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(UInt64)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out SingleCollection values) { values = new SingleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Single)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out DoubleCollection values) { values = new DoubleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Double)); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out AssemblyFlags value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (AssemblyFlags)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out AssemblyHashAlgorithm value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (AssemblyHashAlgorithm)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out CallingConventions value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (CallingConventions)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out EventAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (EventAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FieldAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (FieldAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FixedArgumentAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (FixedArgumentAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out GenericParameterAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (GenericParameterAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out GenericParameterKind value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (GenericParameterKind)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (MethodAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodImplAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (MethodImplAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (MethodSemanticsAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamedArgumentMemberKind value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (NamedArgumentMemberKind)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ParameterAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (ParameterAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PInvokeAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (PInvokeAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PropertyAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (PropertyAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (TypeAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out HandleCollection values) { values = new HandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ArraySignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ArraySignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ByReferenceSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ByReferenceSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantBooleanArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantBooleanArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantBooleanValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantBooleanValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantBoxedEnumValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantBoxedEnumValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantByteArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantByteArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantByteValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantByteValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantCharArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantCharArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantCharValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantCharValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantDoubleArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantDoubleArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantDoubleValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantDoubleValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantHandleArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantHandleArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt16ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt16ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt16ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt16ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt32ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt32ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt32ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt32ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt64ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt64ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt64ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt64ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantReferenceValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantReferenceValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantSByteArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantSByteArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantSByteValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantSByteValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantSingleArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantSingleArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantSingleValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantSingleValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantStringArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantStringArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantStringValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantStringValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt16ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt16ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt16ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt16ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt32ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt32ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt32ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt32ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt64ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt64ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt64ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt64ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out CustomAttributeHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new CustomAttributeHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out EventHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new EventHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FieldHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new FieldHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FieldSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new FieldSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FixedArgumentHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new FixedArgumentHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out GenericParameterHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new GenericParameterHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MemberReferenceHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MemberReferenceHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodImplHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodImplHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodInstantiationHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodInstantiationHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodSemanticsHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodTypeVariableSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodTypeVariableSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ModifiedTypeHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ModifiedTypeHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamedArgumentHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new NamedArgumentHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamespaceDefinitionHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new NamespaceDefinitionHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamespaceReferenceHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new NamespaceReferenceHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ParameterHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ParameterHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PointerSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new PointerSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PropertyHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new PropertyHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PropertySignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new PropertySignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out QualifiedFieldHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new QualifiedFieldHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out QualifiedMethodHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new QualifiedMethodHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out SZArraySignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new SZArraySignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ScopeDefinitionHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ScopeDefinitionHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ScopeReferenceHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ScopeReferenceHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeDefinitionHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeDefinitionHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeForwarderHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeForwarderHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeInstantiationSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeInstantiationSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeReferenceHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeReferenceHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeSpecificationHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeSpecificationHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeVariableSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeVariableSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FixedArgumentHandleCollection values) { values = new FixedArgumentHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamedArgumentHandleCollection values) { values = new NamedArgumentHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsHandleCollection values) { values = new MethodSemanticsHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out CustomAttributeHandleCollection values) { values = new CustomAttributeHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ParameterHandleCollection values) { values = new ParameterHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out GenericParameterHandleCollection values) { values = new GenericParameterHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeDefinitionHandleCollection values) { values = new TypeDefinitionHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeForwarderHandleCollection values) { values = new TypeForwarderHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamespaceDefinitionHandleCollection values) { values = new NamespaceDefinitionHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodHandleCollection values) { values = new MethodHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FieldHandleCollection values) { values = new FieldHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PropertyHandleCollection values) { values = new PropertyHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out EventHandleCollection values) { values = new EventHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodImplHandleCollection values) { values = new MethodImplHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ScopeDefinitionHandleCollection values) { values = new ScopeDefinitionHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read } // MdBinaryReader } // Internal.Metadata.NativeFormat
// Copyright (c) Lex Li. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace Microsoft.Web.Management.Client.Win32 { #if DESIGN public class WizardForm : BaseTaskForm #else public abstract class WizardForm : BaseTaskForm #endif { private WizardPage[] _pages; private Panel _panel1; private Label _txtTitle; private Panel _pnlContainer; private Button _btnCancel; private Button _btnFinish; private Button _btnNext; private Button _btnPrevious; private ProgressBar _pbMain; private int _index; private PictureBox _pictureBox1; private Image _taskGlyph; #if DESIGN public WizardForm() { InitializeComponent(); } #endif protected WizardForm(IServiceProvider serviceProvider) : base(serviceProvider) { InitializeComponent(); } protected virtual void CancelWizard() { Close(); } private void btnPrevious_Click(object sender, EventArgs e) { NavigateToPreviousPage(); Update(); } private void btnNext_Click(object sender, EventArgs e) { StartTaskProgress(); _btnPrevious.Enabled = false; _btnNext.Enabled = false; _btnFinish.Enabled = false; _btnCancel.Focus(); NavigateToNextPage(); StopTaskProgress(); Update(); } #if DESIGN protected virtual void CompleteWizard() { } protected virtual WizardPage[] GetWizardPages() { return new WizardPage[0]; } #else protected abstract void CompleteWizard(); protected abstract WizardPage[] GetWizardPages(); #endif protected void NavigateToNextPage() { if (!CurrentPage.OnNext()) { return; } OnPageChanging(EventArgs.Empty); var next = CurrentPage.NextPage; next.SetPreviousPage(CurrentPage); _index = this.Pages.IndexOf(next); OnPageChanged(EventArgs.Empty); } protected void NavigateToPreviousPage() { if (!CurrentPage.OnPrevious()) { return; } OnPageChanging(EventArgs.Empty); var previous = this.CurrentPage.PreviousPage; _index = this.Pages.IndexOf(previous); OnPageChanged(EventArgs.Empty); } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); } protected override void OnInitialActivated(EventArgs e) { base.OnInitialActivated(e); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); _index = StartPageIndex; OnPageChanged(e); Update(); } protected virtual void OnPageChanged(EventArgs e) { if (CurrentPage == null) { return; } _pnlContainer.Controls.Clear(); _pnlContainer.Controls.Add(CurrentPage); CurrentPage.Activate(); _txtTitle.Text = CurrentPage.Caption; } protected virtual void OnPageChanging(EventArgs e) { } protected override void OnPaint(PaintEventArgs e) { } protected virtual bool ShouldShowPage(WizardPage page) { return false; } protected override void ShowHelp() { throw new NotImplementedException(); } protected override void StartTaskProgress() { _pbMain.Visible = true; } protected override void StopTaskProgress() { _pbMain.Visible = false; } protected override sealed void Update() { if (CurrentPage == null) { return; } _btnNext.Enabled = CurrentPage.CanNavigateNext && _index + 1 != _pages.Length; _btnPrevious.Enabled = CurrentPage.CanNavigatePrevious; _btnFinish.Enabled = CanComplete; if (_btnFinish.Enabled) { AcceptButton = _btnFinish; } else if (_btnNext.Enabled) { AcceptButton = _btnNext; } else { AcceptButton = null; } } protected internal void UpdateWizard() { Update(); } protected override int BorderMargin { get { return 0; } } protected virtual bool CanCancel { get { return true; } } protected virtual bool CanComplete { get { return _pages.Length == _index + 1 && CurrentPage.CanNavigateNext; } } protected override bool CanShowHelp { get { return CurrentPage.CanShowHelp; } } protected WizardPage CurrentPage { get { return Pages.Count == 0 ? null : (WizardPage)Pages[_index]; } } protected virtual bool IsCancellable { get { return false; } } protected internal IList Pages { get { return _pages ?? (_pages = GetWizardPages()); } } protected virtual int StartPageIndex { get { return 0; } } public string TaskCaption { get; set; } public BorderStyle TaskCaptionBorderStyle { get; set; } public string TaskDescription { get; set; } public Image TaskGlyph { get { return _taskGlyph; } set { _taskGlyph = value; _pictureBox1.Image = value; } } public Color TaskProgressEndColor { get; set; } public int TaskProgressGradientSpeed { get; set; } public int TaskProgressScrollSpeed { get; set; } public Color TaskProgressStartColor { get; set; } protected internal virtual object WizardData { get; } private void InitializeComponent() { _panel1 = new Panel(); _pictureBox1 = new PictureBox(); _txtTitle = new Label(); _pnlContainer = new Panel(); _btnCancel = new Button(); _btnFinish = new Button(); _btnNext = new Button(); _btnPrevious = new Button(); _pbMain = new ProgressBar(); _panel1.SuspendLayout(); ((ISupportInitialize)(_pictureBox1)).BeginInit(); SuspendLayout(); // // panel1 // _panel1.Anchor = (AnchorStyles.Top | AnchorStyles.Left) | AnchorStyles.Right; _panel1.BackColor = Color.White; _panel1.Controls.Add(_pictureBox1); _panel1.Controls.Add(_txtTitle); _panel1.Location = new Point(-1, 6); _panel1.Name = "panel1"; _panel1.Size = new Size(670, 65); _panel1.TabIndex = 10; // // pictureBox1 // _pictureBox1.Location = new Point(10, 10); _pictureBox1.Name = "pictureBox1"; _pictureBox1.Size = new Size(48, 48); _pictureBox1.TabIndex = 1; _pictureBox1.TabStop = false; // // txtTitle // _txtTitle.AutoSize = true; _txtTitle.Font = new Font("Microsoft Sans Serif", 14.25F, FontStyle.Regular, GraphicsUnit.Point, 0); _txtTitle.Location = new Point(87, 22); _txtTitle.Name = "txtTitle"; _txtTitle.Size = new Size(0, 24); _txtTitle.TabIndex = 2; // // pnlContainer // _pnlContainer.Location = new Point(-1, 66); _pnlContainer.Name = "pnlContainer"; _pnlContainer.Size = new Size(670, 380); _pnlContainer.TabIndex = 15; // // btnCancel // _btnCancel.DialogResult = DialogResult.Cancel; _btnCancel.Location = new Point(571, 452); _btnCancel.Name = "btnCancel"; _btnCancel.Size = new Size(85, 23); _btnCancel.TabIndex = 14; _btnCancel.Text = "Cancel"; _btnCancel.UseVisualStyleBackColor = true; // // btnFinish // _btnFinish.DialogResult = DialogResult.OK; _btnFinish.Enabled = false; _btnFinish.Location = new Point(480, 452); _btnFinish.Name = "btnFinish"; _btnFinish.Size = new Size(85, 23); _btnFinish.TabIndex = 13; _btnFinish.Text = "Finish"; _btnFinish.UseVisualStyleBackColor = true; _btnFinish.Click += btnFinish_Click; // // btnNext // _btnNext.Enabled = false; _btnNext.Location = new Point(389, 452); _btnNext.Name = "btnNext"; _btnNext.Size = new Size(85, 23); _btnNext.TabIndex = 12; _btnNext.Text = "Next"; _btnNext.UseVisualStyleBackColor = true; _btnNext.Click += btnNext_Click; // // btnPrevious // _btnPrevious.Enabled = false; _btnPrevious.Location = new Point(298, 452); _btnPrevious.Name = "btnPrevious"; _btnPrevious.Size = new Size(85, 23); _btnPrevious.TabIndex = 11; _btnPrevious.Text = "Previous"; _btnPrevious.UseVisualStyleBackColor = true; _btnPrevious.Click += btnPrevious_Click; // // pbMain // _pbMain.Location = new Point(-1, 72); _pbMain.Name = "pbMain"; _pbMain.Size = new Size(670, 4); _pbMain.Style = ProgressBarStyle.Marquee; _pbMain.TabIndex = 16; _pbMain.Visible = false; // // WizardForm // ClientSize = new Size(669, 481); Controls.Add(_pbMain); Controls.Add(_panel1); Controls.Add(_pnlContainer); Controls.Add(_btnCancel); Controls.Add(_btnFinish); Controls.Add(_btnNext); Controls.Add(_btnPrevious); HelpButton = true; MaximizeBox = false; MinimizeBox = false; Name = "WizardForm"; ShowIcon = false; ShowInTaskbar = false; HelpRequested += WizardForm_HelpRequested; _panel1.ResumeLayout(false); _panel1.PerformLayout(); ((ISupportInitialize)(_pictureBox1)).EndInit(); ResumeLayout(false); } private void btnFinish_Click(object sender, EventArgs e) { CompleteWizard(); } private void WizardForm_HelpRequested(object sender, HelpEventArgs hlpevent) { ShowHelp(); } } }
#define AWSSDK_UNITY // // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (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/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Globalization; using System.IO; using Amazon.DynamoDBv2.Model; using Amazon.Runtime.Internal.Util; using Amazon.Util; using System.Collections; using System.Collections.Generic; #if AWSSDK_UNITY #pragma warning disable 3021 #endif namespace Amazon.DynamoDBv2.DocumentModel { /// <summary> /// Enumerator describing type of DynamoDB data in a Primitive or PrimitiveList /// </summary> public enum DynamoDBEntryType { String, Numeric, Binary } /// <summary> /// A DynamoDBEntry that represents a scalar DynamoDB type /// </summary> public class Primitive : DynamoDBEntry, IEquatable<Primitive> { #region Private members private static DynamoDBEntryConversion V1Conversion = DynamoDBEntryConversion.V1; #endregion #region Constructors /// <summary> /// Constructs an empty Primitive /// </summary> public Primitive() : this(null, DynamoDBEntryType.String) { } /// <summary> /// Constructs a Primitive with the specified value. /// Value is stored as a string, not numeric. /// </summary> /// <param name="value">Value of the Primitive</param> public Primitive(string value) : this(value, DynamoDBEntryType.String) { } /// <summary> /// Constructs a Primitive with the specified value /// and specifies whether it should be stored as a number or not. /// </summary> /// <param name="value">Value of the Primitive</param> /// <param name="saveAsNumeric"> /// Flag, set to true if value should be treated as a number instead of a string /// </param> public Primitive(string value, bool saveAsNumeric) : this(value, saveAsNumeric ? DynamoDBEntryType.Numeric : DynamoDBEntryType.String) { } /// <summary> /// Constructs a Binary Primitive with the specified MemoryStream value. /// Note: Primitive's Value is set to the stream's ToArray() response. /// </summary> /// <param name="value">Value of the Primitive</param> public Primitive(MemoryStream value) : this(value.ToArray()) { } /// <summary> /// Constructs a Binary Primitive with the specified byte[] value. /// </summary> /// <param name="value">Value of the Primitive</param> public Primitive(byte[] value) : this(value, DynamoDBEntryType.Binary) { } internal Primitive(object value, DynamoDBEntryType type) { Value = value; Type = type; } #endregion #region Properties /// <summary> /// Value of the Primitive. /// If Type is String or Numeric, this property is a string. /// If Type is Binary, this property is a byte array. /// </summary> public object Value { get; set; } /// <summary> /// Type of this primitive object /// </summary> public DynamoDBEntryType Type { get; set; } #endregion #region Internal conversion methods internal override AttributeValue ConvertToAttributeValue(AttributeConversionConfig conversionConfig) { if (this.Value == null) return null; if (this.Type != DynamoDBEntryType.Binary && string.IsNullOrEmpty(this.StringValue)) return null; AttributeValue attribute = new AttributeValue(); switch (this.Type) { case DynamoDBEntryType.Numeric: attribute.N = StringValue; break; case DynamoDBEntryType.String: attribute.S = StringValue; break; case DynamoDBEntryType.Binary: byte[] bytes = (byte[])Value; attribute.B = new MemoryStream(bytes); break; } return attribute; } internal string StringValue { get { if (this.Type == DynamoDBEntryType.Numeric || this.Type == DynamoDBEntryType.String) return this.Value as string; return null; } } #endregion #region Explicit and Implicit conversions /// <summary> /// Explicitly convert Primitive to Boolean /// </summary> /// <returns>Boolean value of this object</returns> public override Boolean AsBoolean() { return V1Conversion.ConvertFromEntry<Boolean>(this); } /// <summary> /// Implicitly convert Boolean to Primitive /// </summary> /// <param name="data">Boolean data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(Boolean data) { return V1Conversion.ConvertToEntry<Boolean>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to Boolean /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>Boolean value of Primitive</returns> public static explicit operator Boolean(Primitive p) { return p.AsBoolean(); } /// <summary> /// Explicitly convert Primitive to Byte /// </summary> /// <returns>Byte value of this object</returns> public override Byte AsByte() { return V1Conversion.ConvertFromEntry<Byte>(this); } /// <summary> /// Implicitly convert Byte to Primitive /// </summary> /// <param name="data">Byte data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(Byte data) { return V1Conversion.ConvertToEntry<Byte>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to Byte /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>Byte value of Primitive</returns> public static explicit operator Byte(Primitive p) { return p.AsByte(); } /// <summary> /// Explicitly convert Primitive to SByte /// </summary> /// <returns>SByte value of this object</returns> [CLSCompliant(false)] public override SByte AsSByte() { return V1Conversion.ConvertFromEntry<SByte>(this); } /// <summary> /// Implicitly convert SByte to Primitive /// </summary> /// <param name="data">SByte data to convert</param> /// <returns>Primitive representing the data</returns> [CLSCompliant(false)] public static implicit operator Primitive(SByte data) { return V1Conversion.ConvertToEntry<SByte>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to SByte /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>SByte value of Primitive</returns> [CLSCompliant(false)] public static explicit operator SByte(Primitive p) { return p.AsSByte(); } /// <summary> /// Explicitly convert Primitive to UInt16 /// </summary> /// <returns>UInt16 value of this object</returns> [CLSCompliant(false)] public override UInt16 AsUShort() { return V1Conversion.ConvertFromEntry<UInt16>(this); } /// <summary> /// Implicitly convert UInt16 to Primitive /// </summary> /// <param name="data">UInt16 data to convert</param> /// <returns>Primitive representing the data</returns> [CLSCompliant(false)] public static implicit operator Primitive(UInt16 data) { return V1Conversion.ConvertToEntry<UInt16>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to UInt16 /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>UInt16 value of Primitive</returns> [CLSCompliant(false)] public static explicit operator UInt16(Primitive p) { return p.AsUShort(); } /// <summary> /// Explicitly convert Primitive to Int16 /// </summary> /// <returns>Int16 value of this object</returns> public override Int16 AsShort() { return V1Conversion.ConvertFromEntry<Int16>(this); } /// <summary> /// Implicitly convert Int16 to Primitive /// </summary> /// <param name="data">Int16 data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(Int16 data) { return V1Conversion.ConvertToEntry<Int16>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to Int16 /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>Int16 value of Primitive</returns> public static explicit operator Int16(Primitive p) { return p.AsShort(); } /// <summary> /// Explicitly convert Primitive to UInt32 /// </summary> /// <returns>UInt32 value of this object</returns> [CLSCompliant(false)] public override UInt32 AsUInt() { return V1Conversion.ConvertFromEntry<UInt32>(this); } /// <summary> /// Implicitly convert UInt32 to Primitive /// </summary> /// <param name="data">UInt32 data to convert</param> /// <returns>Primitive representing the data</returns> [CLSCompliant(false)] public static implicit operator Primitive(UInt32 data) { return V1Conversion.ConvertToEntry<UInt32>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to UInt32 /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>UInt32 value of Primitive</returns> [CLSCompliant(false)] public static explicit operator UInt32(Primitive p) { return p.AsUInt(); } /// <summary> /// Explicitly convert Primitive to Int32 /// </summary> /// <returns>Int32 value of this object</returns> public override Int32 AsInt() { return V1Conversion.ConvertFromEntry<Int32>(this); } /// <summary> /// Implicitly convert Int32 to Primitive /// </summary> /// <param name="data">Int32 data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(Int32 data) { return V1Conversion.ConvertToEntry<Int32>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to Int32 /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>Int32 value of Primitive</returns> public static explicit operator Int32(Primitive p) { return p.AsInt(); } /// <summary> /// Explicitly convert Primitive to UInt64 /// </summary> /// <returns>UInt64 value of this object</returns> [CLSCompliant(false)] public override UInt64 AsULong() { return V1Conversion.ConvertFromEntry<UInt64>(this); } /// <summary> /// Implicitly convert UInt64 to Primitive /// </summary> /// <param name="data">UInt64 data to convert</param> /// <returns>Primitive representing the data</returns> [CLSCompliant(false)] public static implicit operator Primitive(UInt64 data) { return V1Conversion.ConvertToEntry<UInt64>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to UInt64 /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>UInt64 value of Primitive</returns> [CLSCompliant(false)] public static explicit operator UInt64(Primitive p) { return p.AsULong(); } /// <summary> /// Explicitly convert Primitive to Int64 /// </summary> /// <returns>Int64 value of this object</returns> public override Int64 AsLong() { return V1Conversion.ConvertFromEntry<Int64>(this); } /// <summary> /// Implicitly convert Int64 to Primitive /// </summary> /// <param name="data">Int64 data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(Int64 data) { return V1Conversion.ConvertToEntry<Int64>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to Int64 /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>Int64 value of Primitive</returns> public static explicit operator Int64(Primitive p) { return p.AsLong(); } /// <summary> /// Explicitly convert Primitive to Single /// </summary> /// <returns>Single value of this object</returns> public override Single AsSingle() { return V1Conversion.ConvertFromEntry<Single>(this); } /// <summary> /// Implicitly convert Single to Primitive /// </summary> /// <param name="data">Single data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(Single data) { return V1Conversion.ConvertToEntry<Single>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to Single /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>Single value of Primitive</returns> public static explicit operator Single(Primitive p) { return p.AsSingle(); } /// <summary> /// Explicitly convert Primitive to Double /// </summary> /// <returns>Double value of this object</returns> public override Double AsDouble() { return V1Conversion.ConvertFromEntry<Double>(this); } /// <summary> /// Implicitly convert Double to Primitive /// </summary> /// <param name="data">Double data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(Double data) { return V1Conversion.ConvertToEntry<Double>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to Double /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>Double value of Primitive</returns> public static explicit operator Double(Primitive p) { return p.AsDouble(); } /// <summary> /// Explicitly convert Primitive to Decimal /// </summary> /// <returns>Decimal value of this object</returns> public override Decimal AsDecimal() { return V1Conversion.ConvertFromEntry<Decimal>(this); } /// <summary> /// Implicitly convert Decimal to Primitive /// </summary> /// <param name="data">Decimal data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(Decimal data) { return V1Conversion.ConvertToEntry<Decimal>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to Decimal /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>Decimal value of Primitive</returns> public static explicit operator Decimal(Primitive p) { return p.AsDecimal(); } /// <summary> /// Explicitly convert Primitive to Char /// </summary> /// <returns>Char value of this object</returns> public override Char AsChar() { return V1Conversion.ConvertFromEntry<Char>(this); } /// <summary> /// Implicitly convert Char to Primitive /// </summary> /// <param name="data">Char data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(Char data) { return V1Conversion.ConvertToEntry<Char>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to Char /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>Char value of Primitive</returns> public static explicit operator Char(Primitive p) { return p.AsChar(); } /// <summary> /// Explicitly convert Primitive to String /// </summary> /// <returns>String value of this object</returns> public override String AsString() { return V1Conversion.ConvertFromEntry<String>(this); } /// <summary> /// Implicitly convert String to Primitive /// </summary> /// <param name="data">String data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(String data) { return V1Conversion.ConvertToEntry<String>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to String /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>String value of Primitive</returns> public static implicit operator String(Primitive p) { return p.AsString(); } /// <summary> /// Explicitly convert Primitive to DateTime /// </summary> /// <returns>DateTime value of this object</returns> public override DateTime AsDateTime() { return V1Conversion.ConvertFromEntry<DateTime>(this); } /// <summary> /// Implicitly convert DateTime to Primitive /// </summary> /// <param name="data">DateTime data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(DateTime data) { return V1Conversion.ConvertToEntry<DateTime>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to DateTime /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>DateTime value of Primitive</returns> public static explicit operator DateTime(Primitive p) { return p.AsDateTime(); } /// <summary> /// Explicitly convert Primitive to Guid /// </summary> /// <returns>Guid value of this object</returns> public override Guid AsGuid() { return V1Conversion.ConvertFromEntry<Guid>(this); } /// <summary> /// Implicitly convert Guid to Primitive /// </summary> /// <param name="data">Guid data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(Guid data) { return V1Conversion.ConvertToEntry<Guid>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to Guid /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>Guid value of Primitive</returns> public static explicit operator Guid(Primitive p) { return p.AsGuid(); } /// <summary> /// Explicitly convert Primitive to byte[] /// </summary> /// <returns>byte[] value of this object</returns> public override byte[] AsByteArray() { return V1Conversion.ConvertFromEntry<byte[]>(this); } /// <summary> /// Implicitly convert byte[] to Primitive /// </summary> /// <param name="data">byte[] data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(byte[] data) { return V1Conversion.ConvertToEntry<byte[]>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to byte[] /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>byte[] value of Primitive</returns> public static explicit operator byte[](Primitive p) { return p.AsByteArray(); } /// <summary> /// Explicitly convert Primitive to MemoryStream /// </summary> /// <returns>MemoryStream value of this object</returns> public override MemoryStream AsMemoryStream() { return V1Conversion.ConvertFromEntry<MemoryStream>(this); } /// <summary> /// Implicitly convert MemoryStream to Primitive /// </summary> /// <param name="data">MemoryStream data to convert</param> /// <returns>Primitive representing the data</returns> public static implicit operator Primitive(MemoryStream data) { return V1Conversion.ConvertToEntry<MemoryStream>(data).AsPrimitive(); } /// <summary> /// Explicitly convert Primitive to MemoryStream /// </summary> /// <param name="p">Primitive to convert</param> /// <returns>MemoryStream value of Primitive</returns> public static explicit operator MemoryStream(Primitive p) { return p.AsMemoryStream(); } #endregion #region Public overrides public override string ToString() { if (this.Value == null) return string.Empty; return this.Value.ToString(); } public override object Clone() { return new Primitive(this.Value, this.Type); } public override int GetHashCode() { var typeHashCode = this.Type.GetHashCode(); var valueHashCode = 0; if (this.Value != null) { if (this.Type == DynamoDBEntryType.Numeric || this.Type == DynamoDBEntryType.String) valueHashCode = this.Value.GetHashCode(); else if (this.Type == DynamoDBEntryType.Binary) { var bytes = this.Value as byte[]; if (bytes != null) { for (int i = 0; i < bytes.Length; i++) { byte b = bytes[i]; valueHashCode = Hashing.CombineHashes(valueHashCode, b.GetHashCode()); } } } } return Hashing.CombineHashes(typeHashCode, valueHashCode); } public override bool Equals(object obj) { Primitive entryOther = obj as Primitive; if (entryOther == null) return false; if (this.Type != entryOther.Type) return false; if (this.Type == DynamoDBEntryType.Numeric || this.Type == DynamoDBEntryType.String) { return (string.Equals(this.StringValue, entryOther.StringValue)); } else if (this.Type == DynamoDBEntryType.Binary) { byte[] thisByteArray = this.Value as byte[]; byte[] otherByteArray = entryOther.Value as byte[]; if (thisByteArray.Length != otherByteArray.Length) return false; for (int i = 0; i < thisByteArray.Length; i++) { if (thisByteArray[i] != otherByteArray[i]) return false; } return true; } else { return false; } } #endregion #region IEquatable<Primitive> Members public bool Equals(Primitive other) { return this.Equals((object)other); } #endregion } internal class PrimitiveEqualityComparer : IEqualityComparer<Primitive> { public static readonly PrimitiveEqualityComparer Default = new PrimitiveEqualityComparer(); public bool Equals(Primitive x, Primitive y) { if (x == null || y == null) return (x == y); return x.Equals(y); } public int GetHashCode(Primitive obj) { if (obj == null) return 0; return obj.GetHashCode(); } } internal class PrimitiveComparer : IComparer<Primitive> { public int Compare(Primitive x, Primitive y) { if (x.Type != y.Type) return x.Type.CompareTo(y.Type); if (x.Type == DynamoDBEntryType.Numeric || x.Type == DynamoDBEntryType.String) { return (string.Compare(x.StringValue, y.StringValue, StringComparison.Ordinal)); } else if (x.Type == DynamoDBEntryType.Binary) { byte[] xByteArray = x.Value as byte[]; byte[] yByteArray = y.Value as byte[]; if (xByteArray.Length != yByteArray.Length) return xByteArray.Length.CompareTo(yByteArray.Length); for (int i = 0; i < xByteArray.Length; i++) { byte xb = xByteArray[i]; byte yb = yByteArray[i]; int byteCompare = xb.CompareTo(yb); if (byteCompare != 0) return byteCompare; } return 0; } else { throw new InvalidOperationException("Unknown type of Primitive: " + x.Type); } } public static PrimitiveComparer Default = new PrimitiveComparer(); } } #if AWSSDK_UNITY #pragma warning restore 3021 #endif
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace O365_TaxidermistWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
namespace android.net { [global::MonoJavaBridge.JavaClass()] public partial class LocalSocket : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected LocalSocket(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.net.LocalSocket.staticClass, "toString", "()Ljava/lang/String;", ref global::android.net.LocalSocket._m0) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m1; public virtual void close() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.net.LocalSocket.staticClass, "close", "()V", ref global::android.net.LocalSocket._m1); } public new global::java.io.InputStream InputStream { get { return getInputStream(); } } private static global::MonoJavaBridge.MethodId _m2; public virtual global::java.io.InputStream getInputStream() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.net.LocalSocket.staticClass, "getInputStream", "()Ljava/io/InputStream;", ref global::android.net.LocalSocket._m2) as java.io.InputStream; } private static global::MonoJavaBridge.MethodId _m3; public virtual void connect(android.net.LocalSocketAddress arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.net.LocalSocket.staticClass, "connect", "(Landroid/net/LocalSocketAddress;I)V", ref global::android.net.LocalSocket._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m4; public virtual void connect(android.net.LocalSocketAddress arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.net.LocalSocket.staticClass, "connect", "(Landroid/net/LocalSocketAddress;)V", ref global::android.net.LocalSocket._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public virtual bool isClosed() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.net.LocalSocket.staticClass, "isClosed", "()Z", ref global::android.net.LocalSocket._m5); } public new global::java.io.OutputStream OutputStream { get { return getOutputStream(); } } private static global::MonoJavaBridge.MethodId _m6; public virtual global::java.io.OutputStream getOutputStream() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.net.LocalSocket.staticClass, "getOutputStream", "()Ljava/io/OutputStream;", ref global::android.net.LocalSocket._m6) as java.io.OutputStream; } public new global::java.io.FileDescriptor FileDescriptor { get { return getFileDescriptor(); } } private static global::MonoJavaBridge.MethodId _m7; public virtual global::java.io.FileDescriptor getFileDescriptor() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.io.FileDescriptor>(this, global::android.net.LocalSocket.staticClass, "getFileDescriptor", "()Ljava/io/FileDescriptor;", ref global::android.net.LocalSocket._m7) as java.io.FileDescriptor; } private static global::MonoJavaBridge.MethodId _m8; public virtual void bind(android.net.LocalSocketAddress arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.net.LocalSocket.staticClass, "bind", "(Landroid/net/LocalSocketAddress;)V", ref global::android.net.LocalSocket._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m9; public virtual bool isConnected() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.net.LocalSocket.staticClass, "isConnected", "()Z", ref global::android.net.LocalSocket._m9); } public new global::android.net.LocalSocketAddress LocalSocketAddress { get { return getLocalSocketAddress(); } } private static global::MonoJavaBridge.MethodId _m10; public virtual global::android.net.LocalSocketAddress getLocalSocketAddress() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.net.LocalSocket.staticClass, "getLocalSocketAddress", "()Landroid/net/LocalSocketAddress;", ref global::android.net.LocalSocket._m10) as android.net.LocalSocketAddress; } private static global::MonoJavaBridge.MethodId _m11; public virtual void shutdownInput() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.net.LocalSocket.staticClass, "shutdownInput", "()V", ref global::android.net.LocalSocket._m11); } private static global::MonoJavaBridge.MethodId _m12; public virtual void shutdownOutput() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.net.LocalSocket.staticClass, "shutdownOutput", "()V", ref global::android.net.LocalSocket._m12); } private static global::MonoJavaBridge.MethodId _m13; public virtual void setReceiveBufferSize(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.net.LocalSocket.staticClass, "setReceiveBufferSize", "(I)V", ref global::android.net.LocalSocket._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int ReceiveBufferSize { get { return getReceiveBufferSize(); } set { setReceiveBufferSize(value); } } private static global::MonoJavaBridge.MethodId _m14; public virtual int getReceiveBufferSize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.net.LocalSocket.staticClass, "getReceiveBufferSize", "()I", ref global::android.net.LocalSocket._m14); } private static global::MonoJavaBridge.MethodId _m15; public virtual void setSoTimeout(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.net.LocalSocket.staticClass, "setSoTimeout", "(I)V", ref global::android.net.LocalSocket._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int SoTimeout { get { return getSoTimeout(); } set { setSoTimeout(value); } } private static global::MonoJavaBridge.MethodId _m16; public virtual int getSoTimeout() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.net.LocalSocket.staticClass, "getSoTimeout", "()I", ref global::android.net.LocalSocket._m16); } private static global::MonoJavaBridge.MethodId _m17; public virtual void setSendBufferSize(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.net.LocalSocket.staticClass, "setSendBufferSize", "(I)V", ref global::android.net.LocalSocket._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int SendBufferSize { get { return getSendBufferSize(); } set { setSendBufferSize(value); } } private static global::MonoJavaBridge.MethodId _m18; public virtual int getSendBufferSize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.net.LocalSocket.staticClass, "getSendBufferSize", "()I", ref global::android.net.LocalSocket._m18); } public new global::android.net.LocalSocketAddress RemoteSocketAddress { get { return getRemoteSocketAddress(); } } private static global::MonoJavaBridge.MethodId _m19; public virtual global::android.net.LocalSocketAddress getRemoteSocketAddress() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.net.LocalSocket.staticClass, "getRemoteSocketAddress", "()Landroid/net/LocalSocketAddress;", ref global::android.net.LocalSocket._m19) as android.net.LocalSocketAddress; } private static global::MonoJavaBridge.MethodId _m20; public virtual bool isBound() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.net.LocalSocket.staticClass, "isBound", "()Z", ref global::android.net.LocalSocket._m20); } private static global::MonoJavaBridge.MethodId _m21; public virtual bool isOutputShutdown() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.net.LocalSocket.staticClass, "isOutputShutdown", "()Z", ref global::android.net.LocalSocket._m21); } private static global::MonoJavaBridge.MethodId _m22; public virtual bool isInputShutdown() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.net.LocalSocket.staticClass, "isInputShutdown", "()Z", ref global::android.net.LocalSocket._m22); } public new global::java.io.FileDescriptor[] FileDescriptorsForSend { set { setFileDescriptorsForSend(value); } } private static global::MonoJavaBridge.MethodId _m23; public virtual void setFileDescriptorsForSend(java.io.FileDescriptor[] arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.net.LocalSocket.staticClass, "setFileDescriptorsForSend", "([Ljava/io/FileDescriptor;)V", ref global::android.net.LocalSocket._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::java.io.FileDescriptor[] AncillaryFileDescriptors { get { return getAncillaryFileDescriptors(); } } private static global::MonoJavaBridge.MethodId _m24; public virtual global::java.io.FileDescriptor[] getAncillaryFileDescriptors() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.io.FileDescriptor>(this, global::android.net.LocalSocket.staticClass, "getAncillaryFileDescriptors", "()[Ljava/io/FileDescriptor;", ref global::android.net.LocalSocket._m24) as java.io.FileDescriptor[]; } public new global::android.net.Credentials PeerCredentials { get { return getPeerCredentials(); } } private static global::MonoJavaBridge.MethodId _m25; public virtual global::android.net.Credentials getPeerCredentials() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.net.LocalSocket.staticClass, "getPeerCredentials", "()Landroid/net/Credentials;", ref global::android.net.LocalSocket._m25) as android.net.Credentials; } private static global::MonoJavaBridge.MethodId _m26; public LocalSocket() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.net.LocalSocket._m26.native == global::System.IntPtr.Zero) global::android.net.LocalSocket._m26 = @__env.GetMethodIDNoThrow(global::android.net.LocalSocket.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.net.LocalSocket.staticClass, global::android.net.LocalSocket._m26); Init(@__env, handle); } static LocalSocket() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.net.LocalSocket.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/LocalSocket")); } } }
using UnityEngine; using System.Collections; /* Detonator - A parametric explosion system for Unity Created by Ben Throop in August 2009 for the Unity Summer of Code Simplest use case: 1) Use a prefab OR 1) Attach a Detonator to a GameObject, either through code or the Unity UI 2) Either set the Detonator's ExplodeOnStart = true or call Explode() yourself when the time is right 3) View explosion :) Medium Complexity Use Case: 1) Attach a Detonator as above 2) Change parameters, add your own materials, etc 3) Explode() 4) View Explosion Super Fun Use Case: 1) Attach a Detonator as above 2) Drag one or more DetonatorComponents to that same GameObject 3) Tweak those parameters 4) Explode() 5) View Explosion Better documentation is included as a PDF with this package, or is available online. Check the Unity site for a link or visit my site, listed below. Ben Throop @ben_throop */ [AddComponentMenu("Detonator/Detonator")] public class Detonator : MonoBehaviour { private static float _baseSize = 30f; private static Color _baseColor = new Color(1f, .423f, 0f, .5f); private static float _baseDuration = 3f; /* _baseSize reflects the size that DetonatorComponents at size 1 match. Yes, this is really big (30m) size below is the default Detonator size, which is more reasonable for typical useage. It wasn't my intention for them to be different, and I may change that, but for now, that's how it is. */ public float size = 10f; public Color color = Detonator._baseColor; public bool explodeOnStart = true; public float duration = Detonator._baseDuration; public float detail = 1f; public float upwardsBias = 0f; public float destroyTime = 7f; //sorry this is not auto calculated... yet. public bool useWorldSpace = true; public Vector3 direction = Vector3.zero; public Material fireballAMaterial; public Material fireballBMaterial; public Material smokeAMaterial; public Material smokeBMaterial; public Material shockwaveMaterial; public Material sparksMaterial; public Material glowMaterial; public Material heatwaveMaterial; private Component[] components; private DetonatorFireball _fireball; private DetonatorSparks _sparks; private DetonatorShockwave _shockwave; private DetonatorSmoke _smoke; private DetonatorGlow _glow; private DetonatorLight _light; private DetonatorForce _force; // private DetonatorHeatwave _heatwave; public bool autoCreateFireball = true; public bool autoCreateSparks = true; public bool autoCreateShockwave = true; public bool autoCreateSmoke = true; public bool autoCreateGlow = true; public bool autoCreateLight = true; public bool autoCreateForce = true; public bool autoCreateHeatwave = false; void Awake() { FillDefaultMaterials(); components = this.GetComponents(typeof(DetonatorComponent)); foreach (DetonatorComponent dc in components) { if (dc is DetonatorFireball) { _fireball = dc as DetonatorFireball; } if (dc is DetonatorSparks) { _sparks = dc as DetonatorSparks; } if (dc is DetonatorShockwave) { _shockwave = dc as DetonatorShockwave; } if (dc is DetonatorSmoke) { _smoke = dc as DetonatorSmoke; } if (dc is DetonatorGlow) { _glow = dc as DetonatorGlow; } if (dc is DetonatorLight) { _light = dc as DetonatorLight; } if (dc is DetonatorForce) { _force = dc as DetonatorForce; } if (dc is DetonatorHeatwave) { // _heatwave = dc as DetonatorHeatwave; } } if (!_fireball && autoCreateFireball) { _fireball = gameObject.AddComponent<DetonatorFireball>() as DetonatorFireball; _fireball.Reset(); } if (!_smoke && autoCreateSmoke) { _smoke = gameObject.AddComponent<DetonatorSmoke>() as DetonatorSmoke; _smoke.Reset(); } if (!_sparks && autoCreateSparks) { _sparks = gameObject.AddComponent<DetonatorSparks>() as DetonatorSparks; _sparks.Reset(); } if (!_shockwave && autoCreateShockwave) { _shockwave = gameObject.AddComponent<DetonatorShockwave>() as DetonatorShockwave; _shockwave.Reset(); } if (!_glow && autoCreateGlow) { _glow = gameObject.AddComponent<DetonatorGlow>() as DetonatorGlow; _glow.Reset(); } if (!_light && autoCreateLight) { _light = gameObject.AddComponent<DetonatorLight>() as DetonatorLight; _light.Reset(); } if (!_force && autoCreateForce) { _force = gameObject.AddComponent<DetonatorForce>() as DetonatorForce; _force.Reset(); } /* if (!_heatwave && autoCreateHeatwave && SystemInfo.supportsImageEffects) { _heatwave = gameObject.AddComponent<DetonatorHeatwave>() as DetonatorHeatwave; _heatwave.Reset(); } */ components = this.GetComponents(typeof(DetonatorComponent)); } void FillDefaultMaterials() { if (!fireballAMaterial) fireballAMaterial = DefaultFireballAMaterial(); if (!fireballBMaterial) fireballBMaterial = DefaultFireballBMaterial(); if (!smokeAMaterial) smokeAMaterial = DefaultSmokeAMaterial(); if (!smokeBMaterial) smokeBMaterial = DefaultSmokeBMaterial(); if (!shockwaveMaterial) shockwaveMaterial = DefaultShockwaveMaterial(); if (!sparksMaterial) sparksMaterial = DefaultSparksMaterial(); if (!glowMaterial) glowMaterial = DefaultGlowMaterial(); // if (!heatwaveMaterial) heatwaveMaterial = DefaultHeatwaveMaterial(); } void Start() { if (explodeOnStart) { UpdateComponents(); this.Explode(); } } private float _lastExplosionTime = 1000f; void Update () { if (destroyTime > 0f) { if (_lastExplosionTime + destroyTime <= Time.time) { Destroy(gameObject); } } } private bool _firstComponentUpdate = true; void UpdateComponents() { if (_firstComponentUpdate) { foreach (DetonatorComponent component in components) { component.Init(); component.SetStartValues(); } _firstComponentUpdate = false; } if (!_firstComponentUpdate) { float s = size / _baseSize; Vector3 sdir = new Vector3(direction.x * s, direction.y * s, direction.z * s); float d = duration / _baseDuration; foreach (DetonatorComponent component in components) { if (component.detonatorControlled) { component.size = component.startSize * s; component.timeScale = d; component.detail = component.startDetail * detail; component.force = new Vector3(component.startForce.x * s + sdir.x, component.startForce.y * s + sdir.y, component.startForce.z * s + sdir.z ); component.velocity = new Vector3(component.startVelocity.x * s + sdir.x, component.startVelocity.y * s + sdir.y, component.startVelocity.z * s + sdir.z ); //take the alpha of detonator color and consider it a weight - 1=use all detonator, 0=use all components component.color = Color.Lerp(component.startColor, color, color.a); } } } } private Component[] _subDetonators; public void Explode() { _lastExplosionTime = Time.time; foreach (DetonatorComponent component in components) { UpdateComponents(); component.Explode(); } } public void Reset() { size = 10f; //this is hardcoded because _baseSize up top is not really the default as much as what we match to color = _baseColor; duration = _baseDuration; FillDefaultMaterials(); } //Default Materials //The statics are so that even if there are multiple Detonators in the world, they //don't each create their own default materials. Theoretically this will reduce draw calls, but I haven't really //tested that. public static Material defaultFireballAMaterial; public static Material defaultFireballBMaterial; public static Material defaultSmokeAMaterial; public static Material defaultSmokeBMaterial; public static Material defaultShockwaveMaterial; public static Material defaultSparksMaterial; public static Material defaultGlowMaterial; public static Material defaultHeatwaveMaterial; public static Material DefaultFireballAMaterial() { if (defaultFireballAMaterial != null) return defaultFireballAMaterial; defaultFireballAMaterial = new Material(Shader.Find("Particles/Additive")); defaultFireballAMaterial.name = "FireballA-Default"; Texture2D tex = Resources.Load("Detonator/Textures/Fireball") as Texture2D; defaultFireballAMaterial.SetColor("_TintColor", Color.white); defaultFireballAMaterial.mainTexture = tex; defaultFireballAMaterial.mainTextureScale = new Vector2(0.5f, 1f); return defaultFireballAMaterial; } public static Material DefaultFireballBMaterial() { if (defaultFireballBMaterial != null) return defaultFireballBMaterial; defaultFireballBMaterial = new Material(Shader.Find("Particles/Additive")); defaultFireballBMaterial.name = "FireballB-Default"; Texture2D tex = Resources.Load("Detonator/Textures/Fireball") as Texture2D; defaultFireballBMaterial.SetColor("_TintColor", Color.white); defaultFireballBMaterial.mainTexture = tex; defaultFireballBMaterial.mainTextureScale = new Vector2(0.5f, 1f); defaultFireballBMaterial.mainTextureOffset = new Vector2(0.5f, 0f); return defaultFireballBMaterial; } public static Material DefaultSmokeAMaterial() { if (defaultSmokeAMaterial != null) return defaultSmokeAMaterial; defaultSmokeAMaterial = new Material(Shader.Find("Particles/Alpha Blended")); defaultSmokeAMaterial.name = "SmokeA-Default"; Texture2D tex = Resources.Load("Detonator/Textures/Smoke") as Texture2D; defaultSmokeAMaterial.SetColor("_TintColor", Color.white); defaultSmokeAMaterial.mainTexture = tex; defaultSmokeAMaterial.mainTextureScale = new Vector2(0.5f, 1f); return defaultSmokeAMaterial; } public static Material DefaultSmokeBMaterial() { if (defaultSmokeBMaterial != null) return defaultSmokeBMaterial; defaultSmokeBMaterial = new Material(Shader.Find("Particles/Alpha Blended")); defaultSmokeBMaterial.name = "SmokeB-Default"; Texture2D tex = Resources.Load("Detonator/Textures/Smoke") as Texture2D; defaultSmokeBMaterial.SetColor("_TintColor", Color.white); defaultSmokeBMaterial.mainTexture = tex; defaultSmokeBMaterial.mainTextureScale = new Vector2(0.5f, 1f); defaultSmokeBMaterial.mainTextureOffset = new Vector2(0.5f, 0f); return defaultSmokeBMaterial; } public static Material DefaultSparksMaterial() { if (defaultSparksMaterial != null) return defaultSparksMaterial; defaultSparksMaterial = new Material(Shader.Find("Particles/Additive")); defaultSparksMaterial.name = "Sparks-Default"; Texture2D tex = Resources.Load("Detonator/Textures/GlowDot") as Texture2D; defaultSparksMaterial.SetColor("_TintColor", Color.white); defaultSparksMaterial.mainTexture = tex; return defaultSparksMaterial; } public static Material DefaultShockwaveMaterial() { if (defaultShockwaveMaterial != null) return defaultShockwaveMaterial; defaultShockwaveMaterial = new Material(Shader.Find("Particles/Additive")); defaultShockwaveMaterial.name = "Shockwave-Default"; Texture2D tex = Resources.Load("Detonator/Textures/Shockwave") as Texture2D; defaultShockwaveMaterial.SetColor("_TintColor", new Color(0.1f,0.1f,0.1f,1f)); defaultShockwaveMaterial.mainTexture = tex; return defaultShockwaveMaterial; } public static Material DefaultGlowMaterial() { if (defaultGlowMaterial != null) return defaultGlowMaterial; defaultGlowMaterial = new Material(Shader.Find("Particles/Additive")); defaultGlowMaterial.name = "Glow-Default"; Texture2D tex = Resources.Load("Detonator/Textures/Glow") as Texture2D; defaultGlowMaterial.SetColor("_TintColor", Color.white); defaultGlowMaterial.mainTexture = tex; return defaultGlowMaterial; } public static Material DefaultHeatwaveMaterial() { //Unity Pro Only if (SystemInfo.supportsImageEffects) { if (defaultHeatwaveMaterial != null) return defaultHeatwaveMaterial; defaultHeatwaveMaterial = new Material(Shader.Find("HeatDistort")); defaultHeatwaveMaterial.name = "Heatwave-Default"; Texture2D tex = Resources.Load("Detonator/Textures/Heatwave") as Texture2D; defaultHeatwaveMaterial.SetTexture("_BumpMap", tex); return defaultHeatwaveMaterial; } else { return null; } } }
namespace Economy.scripts { using System; /// <summary> /// Some of these options will later be configurable in a setting file and/or in game commands but for now set as defaults /// </summary> public class EconomyConsts { /// <summary> /// This is used to indicate the base communication version. /// </summary> /// <remarks> /// If we change Message classes or add a new Message class in any way, we need to update this number. /// This is because of potentional conflict in communications when we release a new version of the mod. /// ie., An established server will be running with version 1. We release a new version with different /// communications classes. A Player will connect to the server, and will automatically download version 2. /// We would now have a Client running newer communication classes trying to talk to the Server with older classes. /// </remarks> public const int ModCommunicationVersion = 20161106; // This will be based on the date of update. //milestone level A=Alpha B=Beta, dev = development test version or Milestone eg 1.0A Milestone, 1.1A Dev etc public const string MajorVer = "Econ 3.396A +Bug Fixes"; //Name our money public const string CurrencyName = "Credits"; //Name our Trading Network public const string TradeNetworkName = "Blue Mining Inc Trade Network"; /// <summary> /// The is the Id which this mod registers iteself for sending and receiving messages through SE. /// </summary> /// <remarks> /// This Id needs to be unique with SE and other mods, otherwise it can send/receive /// messages to/from the other registered mod by mistake, and potentially cause SE to crash. /// This has been generated randomly. /// </remarks> public const ushort ConnectionId = 46912; /// <summary> /// The default % you need to own to sell a ship. /// </summary> public const decimal ShipOwned = 80; /// <summary> /// The starting balance for all new players. /// </summary> /// <remarks>This will still be the default value if a Admin does not configure a custom starting balance.</remarks> public const decimal DefaultStartingBalance = 100; /// <summary> /// The starting balance for NPC Bankers. /// </summary> /// <remarks>This will still be the default value if a Admin does not configure a custom starting balance.</remarks> public const decimal NPCStartingBalance = 200000; /// <summary>Should we have sliding price scales?</summary> /// <remarks>This sets if prices should react to available supply.</remarks> public const bool DefaultPriceScaling = true; //default will be true - this should be set/saved in server config /// <summary> /// Should players be near each other to trade or should it be unlimited distance. /// </summary> /// <remarks>This sets if players (or traders) should be nearby before being allowed to trade or not</remarks> public const bool DefaultLimitedRange = false; //default should be true; may be false for testing or gameplay reasons. /// <summary> /// Default range of trade zones. /// This is the radius of a sphere. /// </summary> public const double DefaultTradeRange = 2500; /// <summary> /// Should the NPC market be limited or unlimited supply. /// </summary> /// <remarks>This will be a bool that configures if buying and selling from 0.0.0 trade region /// should be unlimited supply of goods and funds or limited to what has been bought, sold and /// earn by the NPC</remarks> public const bool LimitedSupply = true; /// <summary> /// The internal id we used to identify the Merchant's server account. /// </summary> public const ulong NpcMerchantId = 1234; /// <summary> /// The name that will used to identify the Merchant's server account. /// </summary> public const string NpcMerchantName = "_Default_NPC_Merchant_"; public const string NpcMarketName = "Central Market"; /// <summary> /// The default value for timeouts. /// </summary> public readonly static TimeSpan TradeTimeout = new TimeSpan(0, 2, 0); /// <summary> /// The default age to allow accounts to be before expiry. /// </summary> public readonly static TimeSpan AccountExpiry = new TimeSpan(60, 0, 0, 0); /// <summary> /// The tags that are checked in Text Panels to determine if they are to be used by the Economy Mod. /// </summary> public readonly static string[] LCDTags = new string[] { "[Economy]", "(Economy)" }; /// <summary> /// Should the NPC market be randomly restocked with simulated trade traffic /// </summary> /// <remarks>This is a bool which enables or disables the behavior that when an NPC resource is /// exhausted, randomly simulate a random quantity of this resource being sold to the NPC every 5 minutes /// It will also randomly sell random quantities of overstocked resources if NPC funds are running low</remarks> // public const bool ReSupply = True; /// <summary> /// Resupply threshold /// </summary> /// <remarks>This is a quantity representing the over and understock thresholds for Resupply</remarks> // public const integer OverStocked = 60000; // public const integer UnderStocked = 5; /// <summary> /// Resupply multiplier /// </summary> /// <remarks>This is the max amount and multiplier to apply to random number generation for /// resupply of depleted materials. Eg 50 would represent any random number from 1 to 50 /// a multiplier of 5 would then multiply that amount. Eg 2 would make the random chosen number /// of 23 into 46, resulting in a sell of 46 items to the NPC character</remarks> // public const integer Restock = 50; // public const integer multiplier = 2; } public enum SellAction : byte { /// <summary> /// Creating the Sell order. /// </summary> Create, /// <summary> /// Accepting the sell order. /// </summary> Accept, /// <summary> /// Seller has cancelled the sell order. /// </summary> Cancel, /// <summary> /// Buyer has rejected the sell order. /// </summary> Deny, /// <summary> /// Items to be collected from the sell order (can be returned to the seller, or buyer). /// </summary> Collect } [Flags] public enum SetMarketItemType : byte { Quantity = 0x1, BuyPrice = 0x2, SellPrice = 0x4, Blacklisted = 0x8 } /// <summary> /// Names need to be explicitly set, as they will be written to the Data file. /// Otherwise if we change the names, they will break. /// </summary> public enum MarketZoneType { /// <summary> /// A fixed sphere shaped region in space that does not move or change size. /// </summary> FixedSphere, /// <summary> /// A fixed box shaped region in space that does not move or change size. /// </summary> FixedBox, /// <summary> /// A sphere shaped region in space that is centered about an Entity. It does not change size. /// </summary> EntitySphere, } /// <summary> /// Commands to be used when managing Npc Market zones. /// </summary> public enum NpcMarketManage : byte { Add, Delete, List, Rename, Move } /// <summary> /// Commands to be used when managing Player Market zones. /// </summary> public enum PlayerMarketManage : byte { List, Register, ConfirmRegister, Relink, ConfirmRelink, Unregister, Open, Close, Load, Save, FactionMode, BuyPrice, SellPrice, Stock, Unstock, Restrict, Limit, Blacklist, } /// <summary> /// Names need to be explicitly set, as they will be written to the Data file. /// Otherwise if we change the names, they will break. /// </summary> public enum TradeState { /// <summary> /// Indeterminate, not yet fixed. /// </summary> None, /// <summary> /// Trader is wanting to Buy something. /// </summary> Buy, /// <summary> /// market buy offer - goes to 0,0,0 stock exchange or a registered market /// (eg faction/merchant/station etc)- its an open ended offer available to anyone /// to fill within range of the desired market territory /// </summary> BuyWanted, /// <summary> /// Trader is selling something. /// </summary> Sell, /// <summary> /// We are selling/offering directly to a particular player. /// </summary> SellDirectPlayer, /// <summary> /// market sell offer - goes to 0,0,0 stock exchange or a registered market /// (eg faction/merchant/station etc)- its an open ended offer available to anyone /// to buy within range of the desired market territory /// </summary> SellOffer, /// <summary> /// The Sell was accepted, and the items held for collection. /// </summary> SellAccepted, /// <summary> /// The Sell was rejected, and the items held for return. /// </summary> SellRejected, /// <summary> /// The Sell has timeout but the player has not yet retrieved their goods. /// </summary> SellTimedout, /// <summary> /// transaction/funds have been frozen - either the admin has suspended trading or the /// server is shutting down and/or both the sender and receiver is offline - basically timer frozen /// </summary> Frozen, /// <summary> /// funds/items being held due to buyer/seller or payer or payee being offline; but the /// timer has expired. /// </summary> Holding, } public enum AttachedGrids { /// <summary> /// All attached grids will be found. /// </summary> All, /// <summary> /// Only grids statically attached to that grid, such as by piston or rotor will be found. /// </summary> Static } public enum ClientUpdateAction : byte { Account, CurrencyName, TradeNetworkName, TradeZones } public enum MissionType : int { None, Mine, Weld, JoinFaction, TravelToArea, DisplayAccountBalance, SellOre, BuySomething, PayPlayer, TradeWithPlayer, ShipWorth, BuySellShip, DeliverItemToTradeZone, KillPlayer, DeactivateBlock, ActivateBlock, DestroyBlock, CaptureBlock, } public enum PricingBias : byte { Buy, Sell } /// <summary> /// Commands to be used when managing missions. /// </summary> public enum PlayerMissionManage : byte { Test, AddSample, AddMission, SyncMission, DeleteMission, MissionComplete } public enum MissionAssignmentType : byte { /// <summary> /// Anyone can pick up the mission and do it, including players not yet on server. /// </summary> Open, /// <summary> /// Only the assigned players can do the mission. /// </summary> AssignedPlayers, /// <summary> /// Only players in the assigned factions can do the mission. /// </summary> AssignedFactions } public enum MissionWinRule : byte { /// <summary> /// All players can finish the mission and recieve the reward. /// </summary> AllPlayers, /// <summary> /// Only the first player will recieve the reward. /// </summary> FirstPlayer } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace EmployeeDirectoryWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace ID3.ID3v1Frame { /// <summary> /// Provide a class to read and write ID3v1 /// </summary> public class ID3v1 { private string _FilePath; private string _Title; private string _Artist; private string _Album; private string _Year; private string _Comment; private byte _TrackNumber; private byte _Genre; private bool _HaveTag; #region -> Public Properties <- /// <summary> /// Get file path of current ID3v1 /// </summary> public string FilePath { get { return _FilePath; } internal set { _FilePath = value; } } /// <summary> /// Get file name of current ID3v1 /// </summary> public string FileName { get { return Path.GetFileName(_FilePath); } } /// <summary> /// Get or set Title of current ID3v1 /// </summary> public string Title { get { return _Title; } set { if (value.Length > 30) throw (new ArgumentException("Title Length must be less than 30 characters")); _Title = value; } } /// <summary> /// Get or set Artist of current ID3v1 /// </summary> public string Artist { get { return _Artist; } set { if (value.Length > 30) throw (new ArgumentException("Artist Length must be less than 30 characters")); _Artist = value; } } /// <summary> /// Get or set Album of current ID3v1 /// </summary> public string Album { get { return _Album; } set { if (value.Length > 30) throw (new ArgumentException("Album Length must be less than 30 characters")); _Album = value; } } /// <summary> /// Get or set Year of current ID3v1 /// </summary> public string Year { get { return _Year; } set { if (value.Length > 4) throw (new ArgumentException("Year Length must be less than 4 characters")); _Year = value; } } /// <summary> /// Get or set Comment of current ID3v1 /// </summary> public string Comment { get { return _Comment; } set { if (value.Length > 28) throw (new ArgumentException("Comment Length must be less than 4 characters")); _Comment = value; } } /// <summary> /// Get or set TrackNumber of current ID3v1 /// </summary> public byte TrackNumber { get { return _TrackNumber; } set { _TrackNumber = value; } } /// <summary> /// Get or set Genre of current ID3v1 /// </summary> public byte Genre { get { return _Genre; } set { _Genre = value; } } /// <summary> /// Indicate if current File contain ID3v1 Information /// </summary> public bool HaveTag { get { return _HaveTag; } set { _HaveTag = value; } } #endregion /// <summary> /// Create new ID3v1 class /// </summary> /// <param name="FilePath">Path of file</param> /// <param name="LoadData">Indicate load data in constructor or not</param> public ID3v1(string FilePath, bool LoadData) { _FilePath = FilePath; if (LoadData) Load(); else { _FilePath = ""; _Title = ""; _Artist = ""; _Album = ""; _Year = ""; _Comment = ""; _TrackNumber = 0; _Genre = 0; _HaveTag = false; } } /// <summary> /// Load ID3v1 information from file /// </summary> public void Load() { FileStreamEx FS = new FileStreamEx(_FilePath, FileMode.Open); if (!FS.HaveID3v1()) { FS.Close(); _HaveTag = false; return; } _Title = FS.ReadText(30, TextEncodings.Ascii); FS.Seek(-95, SeekOrigin.End); _Artist = FS.ReadText(30, TextEncodings.Ascii); FS.Seek(-65, SeekOrigin.End); _Album = FS.ReadText(30, TextEncodings.Ascii); FS.Seek(-35, SeekOrigin.End); _Year = FS.ReadText(4, TextEncodings.Ascii); FS.Seek(-31, SeekOrigin.End); _Comment = FS.ReadText(28, TextEncodings.Ascii); FS.Seek(-2, SeekOrigin.End); _TrackNumber = FS.ReadByte(); _Genre = FS.ReadByte(); FS.Close(); _HaveTag = true; } /// <summary> /// Save ID3v1 information to file /// </summary> public void Save() { FileStreamEx fs = new FileStreamEx(_FilePath, FileMode.Open); bool HTag = fs.HaveID3v1(); if (HTag && !_HaveTag) // just delete ID3 fs.SetLength(fs.Length - 128); else if (!HTag && _HaveTag) { fs.Seek(0, SeekOrigin.End); fs.Write(GetTagBytes, 0, 128); } else if (HTag && _HaveTag) { fs.Seek(-128, SeekOrigin.End); fs.Write(GetTagBytes, 0, 128); } fs.Close(); } /// <summary> /// Convert data tot Byte Array to write to file /// </summary> private byte[] GetTagBytes { get { byte[] Buf = new byte[128]; Array.Clear(Buf, 0, 128); Encoding.Default.GetBytes("TAG").CopyTo(Buf, 0); Encoding.Default.GetBytes(_Title).CopyTo(Buf, 3); Encoding.Default.GetBytes(_Artist).CopyTo(Buf, 33); Encoding.Default.GetBytes(_Album).CopyTo(Buf, 63); Encoding.Default.GetBytes(_Year).CopyTo(Buf, 93); Encoding.Default.GetBytes(_Comment).CopyTo(Buf, 97); Buf[126] = _TrackNumber; Buf[127] = _Genre; return Buf; } } } }
namespace HyperSlackers.DbContext.Demo.Migrations { using AspNet.Identity.EntityFramework; using Models; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using System.Web; using Microsoft.AspNet.Identity.Owin; internal sealed class Configuration : DbMigrationsConfiguration<HyperSlackers.DbContext.Demo.Models.ApplicationDbContext> { public Configuration() { // DRM Changed //x AutomaticMigrationsEnabled = false; AutomaticMigrationsEnabled = true; // DRM Added // This SqlGenerator sets [KEY] columns to be NONCLUSTERED so we can define our own clustered index on the models SetSqlGenerator("System.Data.SqlClient", new HyperSqlServerMigrationSqlGenerator()); } protected override void Seed(HyperSlackers.DbContext.Demo.Models.ApplicationDbContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // // DRM Added // grab the managers var hostManager = new ApplicationHostManager(new HyperHostStoreGuid<ApplicationUser>(context)); var roleManager = new ApplicationRoleManager(new HyperRoleStoreGuid<ApplicationUser>(context)); var userManager = new ApplicationUserManager(new HyperUserStoreGuid<ApplicationUser>(context)); // don't audit this one! var auditingEnabled = context.AuditingEnabled; context.AuditingEnabled = false; // add the default host (will respond to "127.0.0.1" in URL) var systemHost = hostManager.GetSystemHost(); if (systemHost == null) { systemHost = new HyperHostGuid() { Name = "<system>", IsSystemHost = true }; systemHost.Domains.Add(new HyperHostDomainGuid() { DomainName = "127.0.0.1" }); hostManager.Create(systemHost); } // we can re-enable auditing here if we want, or at the end if we don't want to audit this stuff //context.AuditingEnabled = auditingEnabled; // add the "other" host (will respond to "localhost" in URL) var localHost = hostManager.FindByDomain("localhost"); if (localHost == null) { localHost = new HyperHostGuid() { Name = "localhost" }; hostManager.AddDomain(localHost, "localhost"); hostManager.AddDomain(localHost, "abc.com"); hostManager.AddDomain(localHost, "xyz.com"); hostManager.Create(localHost); context.SaveChanges(); } // add some global roles AddRole(context, systemHost.Id, "Super", true, true); AddRole(context, systemHost.Id, "User", true); // roles for 127.0.0.1 AddRole(context, systemHost.Id, "Admin"); AddRole(context, systemHost.Id, "Author"); AddRole(context, systemHost.Id, "Editor"); AddRole(context, systemHost.Id, "Player"); // roles for localhost AddRole(context, localHost.Id, "Admin"); AddRole(context, localHost.Id, "Author"); AddRole(context, localHost.Id, "Editor"); AddRole(context, localHost.Id, "Customer"); AddRole(context, localHost.Id, "Supervisor"); AddRole(context, localHost.Id, "Salesperson"); // add some groups AddGroup(context, localHost.Id, "Manager", false, new string[] { "Author", "Editor", "Supervisor", "Salesperson", "User" }); AddGroup(context, localHost.Id, "AssistantManager", false, new string[] { "Author", "Editor", "Salesperson", "User" }); context.SaveChanges(); // create some users ApplicationUser user = new ApplicationUser() { HostId = systemHost.Id, UserName = "anonymous", Email = "[email protected]", IsGlobal = true }; var result = userManager.Create(user, Guid.NewGuid().ToString()); if (result.Succeeded) { context.SaveChanges(); userManager.AddToRole(user.Id, "User", true); // global user role userManager.AddToRoleGroup(localHost.Id, user.Id, "Manager"); // localhost's manager group context.SaveChanges(); } // super user = new ApplicationUser() { HostId = systemHost.Id, UserName = "[email protected]", Email = "[email protected]", IsGlobal = true }; result = userManager.Create(user, "super_system"); if (result.Succeeded) { context.SaveChanges(); userManager.AddToRole(user.Id, "Super"); context.SaveChanges(); } // admin - system user = new ApplicationUser() { HostId = systemHost.Id, UserName = "[email protected]", Email = "[email protected]" }; result = userManager.Create(user, "admin_system"); if (result.Succeeded) { context.SaveChanges(); userManager.AddToRole(systemHost.Id, user.Id, "Admin"); // systemhost's admin role context.SaveChanges(); } // admin - localhost user = new ApplicationUser() { HostId = localHost.Id, UserName = "[email protected]", Email = "[email protected]" }; result = userManager.Create(user, "admin_local"); if (result.Succeeded) { context.SaveChanges(); userManager.AddToRole(localHost.Id, user.Id, "Admin"); // localhost's admin role context.SaveChanges(); } // bob - system (NOT GLOBAL) user = new ApplicationUser() { HostId = systemHost.Id, UserName = "[email protected]", Email = "[email protected]" }; result = userManager.Create(user, "bob_system"); if (result.Succeeded) { context.SaveChanges(); userManager.AddToRole(user.Id, "User", true); // global user role userManager.AddToRole(systemHost.Id, user.Id, "Player", true); // system player role (it's not a global role, so global param will get ignored) context.SaveChanges(); } // bob - localhost (NOT GLOBAL) user = new ApplicationUser() { HostId = localHost.Id, UserName = "[email protected]", Email = "[email protected]" }; result = userManager.Create(user, "bob_local"); if (result.Succeeded) { context.SaveChanges(); userManager.AddToRole(user.Id, "User", true); // global user role userManager.AddToRoleGroup(localHost.Id, user.Id, "Manager"); // localhost's manager group context.SaveChanges(); } // turn auditing back on context.AuditingEnabled = auditingEnabled; } // DRM Added private void AddRole(ApplicationDbContext context, Guid hostId, string roleName, bool isGlobal = false, bool isGlobalOnly = false) { var role = context.Roles.SingleOrDefault(r => r.HostId == hostId && r.Name == roleName); if (role == null) { context.Roles.Add(new HyperRoleGuid() { HostId = hostId, Name = roleName, IsGlobal = isGlobal, IsGlobalOnly = isGlobalOnly }); context.SaveChanges(); } } // DRM Added private void AddGroup(ApplicationDbContext context, Guid hostId, string groupName, bool isGlobal, string[] roles) { var group = context.RoleGroups.SingleOrDefault(g => g.HostId == hostId && g.Name == groupName); if (group == null) { context.RoleGroups.Add(new HyperRoleGroupGuid() { HostId = hostId, Name = groupName, IsGlobal = isGlobal }); context.SaveChanges(); group = context.RoleGroups.SingleOrDefault(g => g.HostId == hostId && g.Name == groupName); } foreach (var item in roles) { var role = context.Roles.SingleOrDefault(r => r.HostId == hostId && r.Name == item); // look for host role if (role == null) { role = context.Roles.SingleOrDefault(r => r.IsGlobal == true && r.Name == item); // look for global role } var gr = context.RoleGroupRoles.SingleOrDefault(rgr => rgr.RoleGroupId == group.Id && rgr.RoleId == role.Id); if (gr == null) { context.RoleGroupRoles.Add(new HyperRoleGroupRoleGuid() { RoleGroupId = group.Id, RoleId = role.Id }); } } context.SaveChanges(); } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Persistence.Repositories; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement; using Umbraco.Cms.Tests.Common.Builders; using Umbraco.Cms.Tests.Common.Testing; using Umbraco.Cms.Tests.Integration.Testing; namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositories { [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class RedirectUrlRepositoryTests : UmbracoIntegrationTest { [SetUp] public void SetUp() => CreateTestData(); [Test] public void CanSaveAndGet() { IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, Url = "blah" }; repo.Save(rurl); scope.Complete(); Assert.AreNotEqual(0, rurl.Id); } using (IScope scope = provider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(provider); IRedirectUrl rurl = repo.GetMostRecentUrl("blah"); scope.Complete(); Assert.IsNotNull(rurl); Assert.AreEqual(_textpage.Id, rurl.ContentId); } } [Test] public void CanSaveAndGetWithCulture() { string culture = "en"; using (IScope scope = ScopeProvider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(ScopeProvider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, Url = "blah", Culture = culture }; repo.Save(rurl); scope.Complete(); Assert.AreNotEqual(0, rurl.Id); } using (IScope scope = ScopeProvider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(ScopeProvider); IRedirectUrl rurl = repo.GetMostRecentUrl("blah"); scope.Complete(); Assert.IsNotNull(rurl); Assert.AreEqual(_textpage.Id, rurl.ContentId); Assert.AreEqual(culture, rurl.Culture); } } [Test] public void CanSaveAndGetMostRecent() { IScopeProvider provider = ScopeProvider; Assert.AreNotEqual(_textpage.Id, _otherpage.Id); using (IScope scope = provider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, Url = "blah" }; repo.Save(rurl); scope.Complete(); Assert.AreNotEqual(0, rurl.Id); // FIXME: too fast = same date = key violation? // and... can that happen in real life? // we don't really *care* about the IX, only supposed to make things faster... // BUT in realife we AddOrUpdate in a trx so it should be safe, always rurl = new RedirectUrl { ContentKey = _otherpage.Key, Url = "blah", CreateDateUtc = rurl.CreateDateUtc.AddSeconds(1) // ensure time difference }; repo.Save(rurl); scope.Complete(); Assert.AreNotEqual(0, rurl.Id); } using (IScope scope = provider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(provider); IRedirectUrl rurl = repo.GetMostRecentUrl("blah"); scope.Complete(); Assert.IsNotNull(rurl); Assert.AreEqual(_otherpage.Id, rurl.ContentId); } } [Test] public void CanSaveAndGetMostRecentForCulture() { string cultureA = "en"; string cultureB = "de"; Assert.AreNotEqual(_textpage.Id, _otherpage.Id); using (IScope scope = ScopeProvider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(ScopeProvider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, Url = "blah", Culture = cultureA }; repo.Save(rurl); scope.Complete(); Assert.AreNotEqual(0, rurl.Id); // FIXME: too fast = same date = key violation? // and... can that happen in real life? // we don't really *care* about the IX, only supposed to make things faster... // BUT in realife we AddOrUpdate in a trx so it should be safe, always rurl = new RedirectUrl { ContentKey = _otherpage.Key, Url = "blah", CreateDateUtc = rurl.CreateDateUtc.AddSeconds(1), // ensure time difference Culture = cultureB }; repo.Save(rurl); scope.Complete(); Assert.AreNotEqual(0, rurl.Id); } using (IScope scope = ScopeProvider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(ScopeProvider); IRedirectUrl rurl = repo.GetMostRecentUrl("blah", cultureA); scope.Complete(); Assert.IsNotNull(rurl); Assert.AreEqual(_textpage.Id, rurl.ContentId); Assert.AreEqual(cultureA, rurl.Culture); } } [Test] public void CanSaveAndGetByContent() { IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, Url = "blah" }; repo.Save(rurl); scope.Complete(); Assert.AreNotEqual(0, rurl.Id); // FIXME: goes too fast and bam, errors, first is blah rurl = new RedirectUrl { ContentKey = _textpage.Key, Url = "durg", CreateDateUtc = rurl.CreateDateUtc.AddSeconds(1) // ensure time difference }; repo.Save(rurl); scope.Complete(); Assert.AreNotEqual(0, rurl.Id); } using (IScope scope = provider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(provider); IRedirectUrl[] rurls = repo.GetContentUrls(_textpage.Key).ToArray(); scope.Complete(); Assert.AreEqual(2, rurls.Length); Assert.AreEqual("durg", rurls[0].Url); Assert.AreEqual("blah", rurls[1].Url); } } [Test] public void CanSaveAndDelete() { IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, Url = "blah" }; repo.Save(rurl); scope.Complete(); Assert.AreNotEqual(0, rurl.Id); rurl = new RedirectUrl { ContentKey = _otherpage.Key, Url = "durg" }; repo.Save(rurl); scope.Complete(); Assert.AreNotEqual(0, rurl.Id); } using (IScope scope = provider.CreateScope()) { IRedirectUrlRepository repo = CreateRepository(provider); repo.DeleteContentUrls(_textpage.Key); scope.Complete(); IEnumerable<IRedirectUrl> rurls = repo.GetContentUrls(_textpage.Key); Assert.AreEqual(0, rurls.Count()); } } private IRedirectUrlRepository CreateRepository(IScopeProvider provider) => new RedirectUrlRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger<RedirectUrlRepository>()); private IContent _textpage; private IContent _subpage; private IContent _otherpage; private IContent _trashed; public void CreateTestData() { IFileService fileService = GetRequiredService<IFileService>(); Template template = TemplateBuilder.CreateTextPageTemplate(); fileService.SaveTemplate(template); // else, FK violation on contentType! IContentService contentService = GetRequiredService<IContentService>(); IContentTypeService contentTypeService = GetRequiredService<IContentTypeService>(); // Create and Save ContentType "umbTextpage" -> (NodeDto.NodeIdSeed) ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); contentType.Key = Guid.NewGuid(); contentTypeService.Save(contentType); // Create and Save Content "Homepage" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 1) _textpage = ContentBuilder.CreateSimpleContent(contentType); _textpage.Key = Guid.NewGuid(); contentService.Save(_textpage); // Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 2) _subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 1", _textpage.Id); _subpage.Key = Guid.NewGuid(); contentService.Save(_subpage); // Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 3) _otherpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 2", _textpage.Id); _otherpage.Key = Guid.NewGuid(); contentService.Save(_otherpage); // Create and Save Content "Text Page Deleted" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 4) _trashed = ContentBuilder.CreateSimpleContent(contentType, "Text Page Deleted", -20); _trashed.Key = Guid.NewGuid(); ((Content)_trashed).Trashed = true; contentService.Save(_trashed); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace MVP { 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 MVPProduction. /// </summary> public static partial class MVPProductionExtensions { /// <summary> /// Gets a list of Contribution areas grouped by Award Names /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static void GetContributionAreas(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { Task.Factory.StartNew(s => ((IMVPProduction)s).GetContributionAreasAsync(subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of Contribution areas grouped by Award Names /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task GetContributionAreasAsync(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.GetContributionAreasWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Supports pagination /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='offset'> /// Format - int32. Page skip integer /// </param> /// <param name='limit'> /// Format - int32. Page take integer /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static ContributionViewModel GetContributions(this IMVPProduction operations, int offset, int limit, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).GetContributionsAsync(offset, limit, subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Supports pagination /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='offset'> /// Format - int32. Page skip integer /// </param> /// <param name='limit'> /// Format - int32. Page take integer /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ContributionViewModel> GetContributionsAsync(this IMVPProduction operations, int offset, int limit, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetContributionsWithHttpMessagesAsync(offset, limit, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a Contribution item by id /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// Format - int32. ContributionId /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static ContributionsModel GetContributionById(this IMVPProduction operations, int id, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).GetContributionByIdAsync(id, subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a Contribution item by id /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// Format - int32. ContributionId /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ContributionsModel> GetContributionByIdAsync(this IMVPProduction operations, int id, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetContributionByIdWithHttpMessagesAsync(id, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a Contribution item /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='contributionsModel'> /// ContributionsModel object /// </param> public static void PutContribution(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), ContributionsModel contributionsModel = default(ContributionsModel)) { Task.Factory.StartNew(s => ((IMVPProduction)s).PutContributionAsync(subscriptionKey, ocpApimSubscriptionKey, contributionsModel), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates a Contribution item /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='contributionsModel'> /// ContributionsModel object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutContributionAsync(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), ContributionsModel contributionsModel = default(ContributionsModel), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutContributionWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, contributionsModel, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates a new Contribution item /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='contributionsModel'> /// ContributionsModel object /// </param> public static object PostContribution(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), ContributionsModel contributionsModel = default(ContributionsModel)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).PostContributionAsync(subscriptionKey, ocpApimSubscriptionKey, contributionsModel), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new Contribution item /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='contributionsModel'> /// ContributionsModel object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> PostContributionAsync(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), ContributionsModel contributionsModel = default(ContributionsModel), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostContributionWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, contributionsModel, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a Contribution item /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// Format - int32. Contribution ID (model PrivateSiteId value) /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static object DeleteContribution(this IMVPProduction operations, int id, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).DeleteContributionAsync(id, subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a Contribution item /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// Format - int32. Contribution ID (model PrivateSiteId value) /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> DeleteContributionAsync(this IMVPProduction operations, int id, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteContributionWithHttpMessagesAsync(id, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retricted to the current user /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static IList<OnlineIdentityViewModel> GetOnlineIdentities(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).GetOnlineIdentitiesAsync(subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retricted to the current user /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<OnlineIdentityViewModel>> GetOnlineIdentitiesAsync(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOnlineIdentitiesWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Set PrivateSiteId in model to identity id /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='onlineIdentityViewModel'> /// OnlineIdentityViewModel model /// </param> public static void PutOnlineIdentity(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), OnlineIdentityViewModel onlineIdentityViewModel = default(OnlineIdentityViewModel)) { Task.Factory.StartNew(s => ((IMVPProduction)s).PutOnlineIdentityAsync(subscriptionKey, ocpApimSubscriptionKey, onlineIdentityViewModel), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Set PrivateSiteId in model to identity id /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='onlineIdentityViewModel'> /// OnlineIdentityViewModel model /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOnlineIdentityAsync(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), OnlineIdentityViewModel onlineIdentityViewModel = default(OnlineIdentityViewModel), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOnlineIdentityWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, onlineIdentityViewModel, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Keep PrivateSiteId == 0 and Retricted to the current user /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='onlineIdentityViewModel'> /// OnlineIdentityViewModel object /// </param> public static object PostOnlineIdentity(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), OnlineIdentityViewModel onlineIdentityViewModel = default(OnlineIdentityViewModel)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).PostOnlineIdentityAsync(subscriptionKey, ocpApimSubscriptionKey, onlineIdentityViewModel), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Keep PrivateSiteId == 0 and Retricted to the current user /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='onlineIdentityViewModel'> /// OnlineIdentityViewModel object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> PostOnlineIdentityAsync(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), OnlineIdentityViewModel onlineIdentityViewModel = default(OnlineIdentityViewModel), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostOnlineIdentityWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, onlineIdentityViewModel, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete Online Identity /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// Format - int32. The items identity id (PrivateSiteId) /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static object DeleteOnlineIdentity(this IMVPProduction operations, int id, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).DeleteOnlineIdentityAsync(id, subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete Online Identity /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// Format - int32. The items identity id (PrivateSiteId) /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> DeleteOnlineIdentityAsync(this IMVPProduction operations, int id, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteOnlineIdentityWithHttpMessagesAsync(id, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retricted to the current user /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nominationsId'> /// Format - uuid. Guid nominationsId /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static IList<OnlineIdentityViewModel> GetOnlineIdentitiesByNominationsId(this IMVPProduction operations, string nominationsId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).GetOnlineIdentitiesByNominationsIdAsync(nominationsId, subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retricted to the current user /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nominationsId'> /// Format - uuid. Guid nominationsId /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<OnlineIdentityViewModel>> GetOnlineIdentitiesByNominationsIdAsync(this IMVPProduction operations, string nominationsId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOnlineIdentitiesByNominationsIdWithHttpMessagesAsync(nominationsId, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retricted to the current user /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// Format - int32. id of item to be retrieved /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static OnlineIdentity GetOnlineIdentityById(this IMVPProduction operations, int id, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).GetOnlineIdentityByIdAsync(id, subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retricted to the current user /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// Format - int32. id of item to be retrieved /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OnlineIdentity> GetOnlineIdentityByIdAsync(this IMVPProduction operations, int id, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOnlineIdentityByIdWithHttpMessagesAsync(id, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the current logged on user profile summary /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static ProfileViewModel GetMVPProfile(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).GetMVPProfileAsync(subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the current logged on user profile summary /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProfileViewModel> GetMVPProfileAsync(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMVPProfileWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a users public profile /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='mvpid'> /// Users mvpid /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static ProfileViewModel GetMVPProfileById(this IMVPProduction operations, string mvpid, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).GetMVPProfileByIdAsync(mvpid, subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a users public profile /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='mvpid'> /// Users mvpid /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProfileViewModel> GetMVPProfileByIdAsync(this IMVPProduction operations, string mvpid, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMVPProfileByIdWithHttpMessagesAsync(mvpid, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the MVP Profile Image /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static void GetMVPProfileImage(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { Task.Factory.StartNew(s => ((IMVPProduction)s).GetMVPProfileImageAsync(subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the MVP Profile Image /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task GetMVPProfileImageAsync(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.GetMVPProfileImageWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets a list of Contribution Types /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static IList<ContributionTypeModel> GetContributionTypes(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { return Task.Factory.StartNew(s => ((IMVPProduction)s).GetContributionTypesAsync(subscriptionKey, ocpApimSubscriptionKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of Contribution Types /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<ContributionTypeModel>> GetContributionTypesAsync(this IMVPProduction operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetContributionTypesWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }