context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System.Diagnostics; using OpenLiveWriter.HtmlParser.Parser; namespace OpenLiveWriter.CoreServices { public abstract class LightWeightHTMLDocumentIterator { public LightWeightHTMLDocumentIterator(string html) { _html = html; } protected virtual string Html { get { return _html; } } private string _html; public void Parse() { SimpleHtmlParser parser = new SimpleHtmlParser(_html); OnDocumentBegin(); while (true) { Element currentElement = parser.Next(); BeginTag beginTag = currentElement as BeginTag; if (beginTag != null) { OnBeginTag(beginTag); continue; } EndTag endTag = currentElement as EndTag; if (endTag != null) { OnEndTag(endTag); continue; } ScriptLiteral literal = currentElement as ScriptLiteral; if (literal != null) { OnScriptLiteral(literal); continue; } Comment comment = currentElement as Comment; if (comment != null) { OnComment(comment); continue; } MarkupDirective markupDirective = currentElement as MarkupDirective; if (markupDirective != null) { OnMarkupDirective(markupDirective); continue; } ScriptText scriptText = currentElement as ScriptText; if (scriptText != null) { OnScriptText(scriptText); continue; } ScriptComment scriptComment = currentElement as ScriptComment; if (scriptComment != null) { OnScriptComment(scriptComment); continue; } StyleText styleText = currentElement as StyleText; if (styleText != null) { OnStyleText(styleText); continue; } StyleUrl styleUrl = currentElement as StyleUrl; if (styleUrl != null) { OnStyleUrl(styleUrl); continue; } StyleImport styleImport = currentElement as StyleImport; if (styleImport != null) { OnStyleImport(styleImport); continue; } StyleComment styleComment = currentElement as StyleComment; if (styleComment != null) { OnStyleComment(styleComment); continue; } StyleLiteral styleLiteral = currentElement as StyleLiteral; if (styleLiteral != null) { OnStyleLiteral(styleLiteral); continue; } Text text = currentElement as Text; if (text != null) { OnText(text); continue; } if (currentElement == null) { OnDocumentEnd(); return; } Debug.Fail("Unrecognized element in LightWeightHTMLDocumentIterator"); } } protected virtual void OnDocumentBegin() { } protected virtual void OnDocumentEnd() { } protected virtual void DefaultAction(Element el) { } protected virtual void OnStyleImport(StyleImport styleImport) { DefaultAction(styleImport); } protected virtual void OnStyleText(StyleText text) { DefaultAction(text); } protected virtual void OnStyleLiteral(StyleLiteral literal) { DefaultAction(literal); } protected virtual void OnBeginTag(BeginTag tag) { DefaultAction(tag); } protected virtual void OnEndTag(EndTag tag) { DefaultAction(tag); } protected virtual void OnScriptLiteral(ScriptLiteral literal) { DefaultAction(literal); } protected virtual void OnComment(Comment comment) { DefaultAction(comment); } protected virtual void OnMarkupDirective(MarkupDirective markupDirective) { DefaultAction(markupDirective); } protected virtual void OnScriptText(ScriptText scriptText) { DefaultAction(scriptText); } protected virtual void OnScriptComment(ScriptComment scriptComment) { DefaultAction(scriptComment); } protected virtual void OnText(Text text) { DefaultAction(text); } protected virtual void OnStyleUrl(StyleUrl styleUrl) { DefaultAction(styleUrl); } protected virtual void OnStyleComment(StyleComment styleComment) { DefaultAction(styleComment); } } }
// // System.Security.Permissions.ResourcePermissionBase.cs // // Authors: // Jonathan Pryor (jonpryor@vt.edu) // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2002 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.Globalization; namespace System.Security.Permissions { [Serializable] public abstract class ResourcePermissionBase : CodeAccessPermission, IUnrestrictedPermission { private const int version = 1; private ArrayList _list; private bool _unrestricted; private Type _type; private string[] _tags; protected ResourcePermissionBase () { _list = new ArrayList (); } protected ResourcePermissionBase (PermissionState state) : this () { PermissionHelper.CheckPermissionState (state, true); _unrestricted = (state == PermissionState.Unrestricted); } public const string Any = "*"; public const string Local = "."; protected Type PermissionAccessType { get { return _type; } set { if (value == null) throw new ArgumentNullException ("PermissionAccessType"); if (!value.IsEnum) throw new ArgumentException ("!Enum", "PermissionAccessType"); _type = value; } } protected string[] TagNames { get { return _tags; } set { if (value == null) throw new ArgumentNullException ("TagNames"); if (value.Length == 0) throw new ArgumentException ("Length==0", "TagNames"); _tags = value; } } protected void AddPermissionAccess (ResourcePermissionBaseEntry entry) { CheckEntry (entry); if (Exists (entry)) { string msg = "Entry already exists."; throw new InvalidOperationException (msg); } _list.Add (entry); } protected void Clear () { _list.Clear (); } public override IPermission Copy () { ResourcePermissionBase copy = CreateFromType (this.GetType (), _unrestricted); if (_tags != null) copy._tags = (string[]) _tags.Clone (); copy._type = _type; // FIXME: shallow or deep copy ? copy._list.AddRange (_list); return copy; } [MonoTODO ("incomplete - need more test")] public override void FromXml (SecurityElement securityElement) { if (securityElement == null) throw new ArgumentNullException ("securityElement"); #if !BOOTSTRAP_BASIC // CheckSecurityElement (securityElement, "securityElement", version, version); // Note: we do not (yet) care about the return value // as we only accept version 1 (min/max values) #endif _list.Clear (); _unrestricted = PermissionHelper.IsUnrestricted (securityElement); if ((securityElement.Children == null) || (securityElement.Children.Count < 1)) return; string[] names = new string [1]; foreach (SecurityElement child in securityElement.Children) { // TODO: handle multiple names names [0] = child.Attribute ("name"); int access = (int) Enum.Parse (PermissionAccessType, child.Attribute ("access")); ResourcePermissionBaseEntry entry = new ResourcePermissionBaseEntry (access, names); AddPermissionAccess (entry); } } protected ResourcePermissionBaseEntry[] GetPermissionEntries () { ResourcePermissionBaseEntry[] entries = new ResourcePermissionBaseEntry [_list.Count]; _list.CopyTo (entries, 0); return entries; } public override IPermission Intersect (IPermission target) { ResourcePermissionBase rpb = Cast (target); if (rpb == null) return null; bool su = this.IsUnrestricted (); bool tu = rpb.IsUnrestricted (); // if one is empty we return null (unless the other one is unrestricted) if (IsEmpty () && !tu) return null; if (rpb.IsEmpty () && !su) return null; ResourcePermissionBase result = CreateFromType (this.GetType (), (su && tu)); foreach (ResourcePermissionBaseEntry entry in _list) { if (tu || rpb.Exists (entry)) result.AddPermissionAccess (entry); } foreach (ResourcePermissionBaseEntry entry in rpb._list) { // don't add twice if ((su || this.Exists (entry)) && !result.Exists (entry)) result.AddPermissionAccess (entry); } return result; } public override bool IsSubsetOf (IPermission target) { if (target == null) { // do not use Cast - different permissions (and earlier Fx) return false :-/ return true; } ResourcePermissionBase rpb = (target as ResourcePermissionBase); if (rpb == null) return false; if (rpb.IsUnrestricted ()) return true; if (IsUnrestricted ()) return rpb.IsUnrestricted (); foreach (ResourcePermissionBaseEntry entry in _list) { if (!rpb.Exists (entry)) return false; } return true; } public bool IsUnrestricted () { return _unrestricted; } protected void RemovePermissionAccess (ResourcePermissionBaseEntry entry) { CheckEntry (entry); for (int i = 0; i < _list.Count; i++) { ResourcePermissionBaseEntry rpbe = (ResourcePermissionBaseEntry) _list [i]; if (Equals (entry, rpbe)) { _list.RemoveAt (i); return; } } string msg = "Entry doesn't exists."; throw new InvalidOperationException (msg); } public override SecurityElement ToXml () { SecurityElement se = PermissionHelper.Element (this.GetType (), version); if (IsUnrestricted ()) { se.AddAttribute ("Unrestricted", "true"); } else { foreach (ResourcePermissionBaseEntry entry in _list) { SecurityElement container = se; string access = null; if (PermissionAccessType != null) access = Enum.Format (PermissionAccessType, entry.PermissionAccess, "g"); for (int i=0; i < _tags.Length; i++) { SecurityElement child = new SecurityElement (_tags [i]); child.AddAttribute ("name", entry.PermissionAccessPath [i]); if (access != null) child.AddAttribute ("access", access); container.AddChild (child); child = container; } } } return se; } public override IPermission Union (IPermission target) { ResourcePermissionBase rpb = Cast (target); if (rpb == null) return Copy (); if (IsEmpty () && rpb.IsEmpty ()) return null; if (rpb.IsEmpty ()) return Copy (); if (IsEmpty ()) return rpb.Copy (); bool unrestricted = (IsUnrestricted () || rpb.IsUnrestricted ()); ResourcePermissionBase result = CreateFromType (this.GetType (), unrestricted); // strangely unrestricted union doesn't process the elements (while intersect does) if (!unrestricted) { foreach (ResourcePermissionBaseEntry entry in _list) { result.AddPermissionAccess (entry); } foreach (ResourcePermissionBaseEntry entry in rpb._list) { // don't add twice if (!result.Exists (entry)) result.AddPermissionAccess (entry); } } return result; } // helpers private bool IsEmpty () { return (!_unrestricted && (_list.Count == 0)); } private ResourcePermissionBase Cast (IPermission target) { if (target == null) return null; ResourcePermissionBase rp = (target as ResourcePermissionBase); if (rp == null) { PermissionHelper.ThrowInvalidPermission (target, typeof (ResourcePermissionBase)); } return rp; } internal void CheckEntry (ResourcePermissionBaseEntry entry) { if (entry == null) throw new ArgumentNullException ("entry"); if ((entry.PermissionAccessPath == null) || (entry.PermissionAccessPath.Length != _tags.Length)) { string msg = "Entry doesn't match TagNames"; throw new InvalidOperationException (msg); } } internal bool Equals (ResourcePermissionBaseEntry entry1, ResourcePermissionBaseEntry entry2) { if (entry1.PermissionAccess != entry2.PermissionAccess) return false; if (entry1.PermissionAccessPath.Length != entry2.PermissionAccessPath.Length) return false; for (int i=0; i < entry1.PermissionAccessPath.Length; i++) { if (entry1.PermissionAccessPath [i] != entry2.PermissionAccessPath [i]) return false; } return true; } internal bool Exists (ResourcePermissionBaseEntry entry) { if (_list.Count == 0) return false; foreach (ResourcePermissionBaseEntry rpbe in _list) { if (Equals (rpbe, entry)) return true; } return false; } // static helpers private static char[] invalidChars = new char[] { '\t', '\n', '\v', '\f', '\r', ' ', '\\', '\x160' }; internal static void ValidateMachineName (string name) { // FIXME: maybe other checks are required (but not documented) if ((name == null) || (name.Length == 0) || (name.IndexOfAny (invalidChars) != -1)) { string msg = "Invalid machine name '{0}'."; if (name == null) name = "(null)"; msg = String.Format (msg, name); throw new ArgumentException (msg, "MachineName"); } } internal static ResourcePermissionBase CreateFromType (Type type, bool unrestricted) { object[] parameters = new object [1]; parameters [0] = (object) ((unrestricted) ? PermissionState.Unrestricted : PermissionState.None); // we must return the derived type - this is why an empty constructor is required ;-) return (ResourcePermissionBase) Activator.CreateInstance (type, parameters); } } }
//----------------------------------------------------------------------- // <copyright file="ActorRefBackpressureSinkSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using Akka.Actor; using Akka.Configuration; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Dsl { public class ActorRefBackpressureSinkSpec : AkkaSpec { #region internal classes private sealed class TriggerAckMessage { public static readonly TriggerAckMessage Instance = new TriggerAckMessage(); private TriggerAckMessage() { } } private sealed class Fw : ReceiveActor { public Fw(IActorRef aref) { Receive<string>(s => s == InitMessage, s => { Sender.Tell(AckMessage); aref.Forward(InitMessage); }); Receive<string>(s => s == CompleteMessage, s => aref.Forward(CompleteMessage)); Receive<int>(i => { Sender.Tell(AckMessage); aref.Forward(i); }); } } private sealed class Fw2 : ReceiveActor { public Fw2(IActorRef aref) { var actorRef = ActorRefs.NoSender; Receive<TriggerAckMessage>(_ => actorRef.Tell(AckMessage)); ReceiveAny(msg => { actorRef = Sender; aref.Forward(msg); }); } } #endregion private const string InitMessage = "start"; private const string CompleteMessage = "complete"; private const string AckMessage = "ack"; private ActorMaterializer Materializer { get; } public ActorRefBackpressureSinkSpec(ITestOutputHelper output) : base(output, ConfigurationFactory.FromResource<ScriptedTest>("Akka.Streams.TestKit.Tests.reference.conf")) { Materializer = ActorMaterializer.Create(Sys); } private IActorRef CreateActor<T>() => Sys.ActorOf(Props.Create(typeof(T), TestActor).WithDispatcher("akka.test.stream-dispatcher")); [Fact] public void ActorBackpressureSink_should_send_the_elements_to_the_ActorRef() { this.AssertAllStagesStopped(() => { var fw = CreateActor<Fw>(); Source.From(Enumerable.Range(1, 3)) .RunWith(Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage), Materializer); ExpectMsg("start"); ExpectMsg(1); ExpectMsg(2); ExpectMsg(3); ExpectMsg(CompleteMessage); }, Materializer); } [Fact] public void ActorBackpressureSink_should_send_the_elements_to_the_ActorRef2() { this.AssertAllStagesStopped(() => { var fw = CreateActor<Fw>(); var probe = this.SourceProbe<int>() .To(Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage)) .Run(Materializer); probe.SendNext(1); ExpectMsg("start"); ExpectMsg(1); probe.SendNext(2); ExpectMsg(2); probe.SendNext(3); ExpectMsg(3); probe.SendComplete(); ExpectMsg(CompleteMessage); }, Materializer); } [Fact] public void ActorBackpressureSink_should_cancel_stream_when_actor_terminates() { this.AssertAllStagesStopped(() => { var fw = CreateActor<Fw>(); var publisher = this.SourceProbe<int>() .To(Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage)) .Run(Materializer); publisher.SendNext(1); ExpectMsg(InitMessage); ExpectMsg(1); Sys.Stop(fw); publisher.ExpectCancellation(); }, Materializer); } [Fact] public void ActorBackpressureSink_should_send_message_only_when_backpressure_received() { this.AssertAllStagesStopped(() => { var fw = CreateActor<Fw2>(); var publisher = this.SourceProbe<int>() .To(Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage)) .Run(Materializer); ExpectMsg(InitMessage); publisher.SendNext(1); ExpectNoMsg(); fw.Tell(TriggerAckMessage.Instance); ExpectMsg(1); publisher.SendNext(2); publisher.SendNext(3); publisher.SendComplete(); fw.Tell(TriggerAckMessage.Instance); ExpectMsg(2); fw.Tell(TriggerAckMessage.Instance); ExpectMsg(3); ExpectMsg(CompleteMessage); }, Materializer); } [Fact] public void ActorBackpressureSink_should_keep_on_sending_even_after_the_buffer_has_been_full() { this.AssertAllStagesStopped(() => { var bufferSize = 16; var streamElementCount = bufferSize + 4; var fw = CreateActor<Fw2>(); var sink = Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage) .WithAttributes(Attributes.CreateInputBuffer(bufferSize, bufferSize)); var probe = Source.From(Enumerable.Range(1, streamElementCount)) .AlsoToMaterialized( Flow.Create<int>().Take(bufferSize).WatchTermination(Keep.Right).To(Sink.Ignore<int>()), Keep.Right) .To(sink) .Run(Materializer); probe.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); probe.IsCompleted.Should().BeTrue(); ExpectMsg(InitMessage); fw.Tell(TriggerAckMessage.Instance); for (var i = 1; i <= streamElementCount; i++) { ExpectMsg(i); fw.Tell(TriggerAckMessage.Instance); } ExpectMsg(CompleteMessage); }, Materializer); } [Fact] public void ActorBackpressureSink_should_work_with_one_element_buffer() { this.AssertAllStagesStopped(() => { var fw = CreateActor<Fw2>(); var publisher = this.SourceProbe<int>() .To(Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage)) .WithAttributes(Attributes.CreateInputBuffer(1, 1)).Run(Materializer); ExpectMsg(InitMessage); fw.Tell(TriggerAckMessage.Instance); publisher.SendNext(1); ExpectMsg(1); fw.Tell(TriggerAckMessage.Instance); ExpectNoMsg(); // Ack received but buffer empty publisher.SendNext(2); // Buffer this value fw.Tell(TriggerAckMessage.Instance); ExpectMsg(2); publisher.SendComplete(); ExpectMsg(CompleteMessage); }, Materializer); } [Fact] public void ActorBackpressurSink_should_fail_to_materialize_with_zero_sized_input_buffer() { var fw = CreateActor<Fw>(); var badSink = Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage) .WithAttributes(Attributes.CreateInputBuffer(0, 0)); Source.Single(1).Invoking(s => s.RunWith(badSink, Materializer)).ShouldThrow<ArgumentException>(); } [Fact] public void ActorBackpressurSink_should_signal_failure_on_abrupt_termination() { var materializer = ActorMaterializer.Create(Sys); var probe = CreateTestProbe(); var sink = Sink.ActorRefWithAck<string>(probe.Ref, InitMessage, AckMessage, CompleteMessage) .WithAttributes(Attributes.CreateInputBuffer(1, 1)); Source.Maybe<string>().To(sink).Run(materializer); probe.ExpectMsg(InitMessage); materializer.Shutdown(); probe.ExpectMsg<Status.Failure>(); } } }
/* * Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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.Generic; using OpenMetaverse; using EventFlags = OpenMetaverse.DirectoryManager.EventFlags; using Aurora.Framework; namespace Aurora.Framework { public interface IDirectoryServiceConnector : IAuroraDataPlugin { #region Regions /// <summary> /// Adds a region into search /// </summary> /// <param name = "args"></param> void AddRegion(List<LandData> args); /// <summary> /// Removes a region from search /// </summary> /// <param name = "regionID"></param> /// <param name = "args"></param> void ClearRegion(UUID regionID); #endregion #region Parcels /// <summary> /// Gets a parcel from the search database by Info UUID (the true cross instance parcel ID) /// </summary> /// <param name = "ParcelID"></param> /// <returns></returns> LandData GetParcelInfo(UUID ParcelID); /// <summary> /// Gets the first parcel from the search database in the specified region with the specified name /// </summary> /// <param name="RegionID"></param> /// <param name="ParcelName"></param> /// <returns></returns> LandData GetParcelInfo(UUID RegionID, string ParcelName); /// <summary> /// Gets all parcels owned by the given user /// </summary> /// <param name = "OwnerID"></param> /// <returns></returns> List<ExtendedLandData> GetParcelByOwner(UUID OwnerID); /// <summary> /// Gets all parcels in a region, optionally filtering by owner, parcel flags and category. /// </summary> /// <param name="start"></param> /// <param name="count"></param> /// <param name="RegionID"></param> /// <param name="scopeID"></param> /// <param name="owner"></param> /// <param name="flags"></param> /// <param name="category"></param> /// <returns></returns> List<LandData> GetParcelsByRegion(uint start, uint count, UUID RegionID, UUID owner, ParcelFlags flags, ParcelCategory category); /// <summary> /// Get the number of parcels in the specified region that match the specified filters. /// </summary> /// <param name="RegionID"></param> /// <param name="scopeID"></param> /// <param name="owner"></param> /// <param name="flags"></param> /// <param name="category"></param> /// <returns></returns> uint GetNumberOfParcelsByRegion(UUID RegionID, UUID owner, ParcelFlags flags, ParcelCategory category); /// <summary> /// Get a list of parcels in a region with the specified name. /// </summary> /// <param name="start"></param> /// <param name="count"></param> /// <param name="RegionID"></param> /// <param name="ScopeID"></param> /// <param name="name"></param> /// <param name="flags"></param> /// <param name="category"></param> /// <returns></returns> List<LandData> GetParcelsWithNameByRegion(uint start, uint count, UUID RegionID, string name); /// <summary> /// Get the number of parcels in the specified region with the specified name /// </summary> /// <param name="RegionID"></param> /// <param name="ScopeID"></param> /// <param name="name"></param> /// <returns></returns> uint GetNumberOfParcelsWithNameByRegion(UUID RegionID, string name); /// <summary> /// Searches for parcels around the grid /// </summary> /// <param name = "queryText"></param> /// <param name = "category"></param> /// <param name = "StartQuery"></param> /// <returns></returns> List<DirPlacesReplyData> FindLand(string queryText, string category, int StartQuery, uint Flags, UUID scopeID); /// <summary> /// Searches for parcels for sale around the grid /// </summary> /// <param name = "searchType"></param> /// <param name = "price"></param> /// <param name = "area"></param> /// <param name = "StartQuery"></param> /// <returns></returns> List<DirLandReplyData> FindLandForSale(string searchType, uint price, uint area, int StartQuery, uint Flags, UUID scopeID); /// <summary> /// Searches for parcels for sale around the grid /// </summary> /// <param name = "searchType"></param> /// <param name = "price"></param> /// <param name = "area"></param> /// <param name = "StartQuery"></param> /// <returns></returns> List<DirLandReplyData> FindLandForSaleInRegion(string searchType, uint price, uint area, int StartQuery, uint Flags, UUID regionID); /// <summary> /// Searches for the most popular places around the grid /// </summary> /// <param name = "searchType"></param> /// <param name = "price"></param> /// <param name = "area"></param> /// <param name = "StartQuery"></param> /// <returns></returns> List<DirPopularReplyData> FindPopularPlaces(uint queryFlags, UUID scopeID); #endregion #region Classifieds /// <summary> /// Searches for classifieds /// </summary> /// <param name = "queryText"></param> /// <param name = "category"></param> /// <param name = "queryFlags"></param> /// <param name = "StartQuery"></param> /// <returns></returns> List<DirClassifiedReplyData> FindClassifieds(string queryText, string category, uint queryFlags, int StartQuery, UUID scopeID); /// <summary> /// Gets all classifieds in the given region /// </summary> /// <param name = "regionName"></param> /// <returns></returns> List<Classified> GetClassifiedsInRegion(string regionName); Classified GetClassifiedByID(UUID id); #endregion #region Events /// <summary> /// Searches for events with the given parameters /// </summary> /// <param name = "queryText"></param> /// <param name = "flags"></param> /// <param name = "StartQuery"></param> /// <returns></returns> List<DirEventsReplyData> FindEvents(string queryText, uint flags, int StartQuery, UUID scopeID); /// <summary> /// Retrives all events in the given region by their maturity level /// </summary> /// <param name = "regionName"></param> /// <param name = "maturity">Uses DirectoryManager.EventFlags to determine the maturity requested</param> /// <returns></returns> List<DirEventsReplyData> FindAllEventsInRegion(string regionName, int maturity); /// <summary> /// Gets more info about the event by the events unique event ID /// </summary> /// <param name = "EventID"></param> /// <returns></returns> EventData GetEventInfo(uint EventID); /// <summary> /// creates an event /// </summary> /// <param name="creator"></param> /// <param name="region"></param> /// <param name="parcel"></param> /// <param name="date"></param> /// <param name="cover"></param> /// <param name="maturity"></param> /// <param name="flags"></param> /// <param name="duration"></param> /// <param name="localPos"></param> /// <param name="name"></param> /// <param name="description"></param> /// <param name="category"></param> /// <returns></returns> EventData CreateEvent(UUID creator, UUID region, UUID parcel, DateTime date, uint cover, EventFlags maturity, uint flags, uint duration, Vector3 localPos, string name, string description, string category); /// <summary> /// Gets a list of events with optional filters /// </summary> /// <param name="start"></param> /// <param name="count"></param> /// <param name="sort"></param> /// <param name="filter"></param> /// <returns></returns> List<EventData> GetEvents(uint start, uint count, Dictionary<string, bool> sort, Dictionary<string, object> filter); /// <summary> /// Get the number of events matching the specified filters /// </summary> /// <param name="filter"></param> /// <returns></returns> uint GetNumberOfEvents(Dictionary<string, object> filter); /// <summary> /// Gets the highest event ID /// </summary> /// <returns></returns> uint GetMaxEventID(); #endregion } }
// 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.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using mshtml; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.ImageEditing; using OpenLiveWriter.PostEditor.PostHtmlEditing.ImageEditing.Decorators; namespace OpenLiveWriter.PostEditor.PostHtmlEditing { internal interface IImagePropertyEditingContext { IHTMLImgElement SelectedImage { get; } event ImagePropertyEventHandler ImagePropertyChanged; ImagePropertiesInfo ImagePropertiesInfo { get; set; } } /// <summary> /// Summary description for ImagePropertiesHandler. /// </summary> internal class ImageEditingPropertyHandler { ImageInsertHandler _imageInsertHandler; IImagePropertyEditingContext _propertyEditingContext; IBlogPostImageEditingContext _editorContext; internal ImageEditingPropertyHandler(IImagePropertyEditingContext propertyEditingContext, CreateFileCallback createFileCallback, IBlogPostImageEditingContext imageEditingContext) { _propertyEditingContext = propertyEditingContext; _imageInsertHandler = new ImageInsertHandler(); _editorContext = imageEditingContext; } public void RefreshView() { _propertyEditingContext.ImagePropertyChanged -= new ImagePropertyEventHandler(imageProperties_ImagePropertyChanged); IHTMLImgElement imgElement = ImgElement as IHTMLImgElement; if (imgElement != null) _propertyEditingContext.ImagePropertiesInfo = GetImagePropertiesInfo(imgElement, _editorContext); else _propertyEditingContext.ImagePropertiesInfo = null; _propertyEditingContext.ImagePropertyChanged += new ImagePropertyEventHandler(imageProperties_ImagePropertyChanged); } public static ImagePropertiesInfo GetImagePropertiesInfo(IHTMLImgElement imgElement, IBlogPostImageEditingContext editorContext) { IHTMLElement imgHtmlElement = (IHTMLElement)imgElement; string imgSrc = imgHtmlElement.getAttribute("src", 2) as string; BlogPostImageData imageData = null; try { imageData = BlogPostImageDataList.LookupImageDataByInlineUri(editorContext.ImageList, new Uri(imgSrc)); } catch (UriFormatException) { //this URI is probably relative web URL, so extract the image src letting the //DOM fill in the full URL for us based on the base URL. imgSrc = imgHtmlElement.getAttribute("src", 0) as string; } ImagePropertiesInfo info; if (imageData != null && imageData.GetImageSourceFile() != null) { //clone the image data to the sidebar doesn't change it (required for preserving image undo/redo state) imageData = (BlogPostImageData)imageData.Clone(); //this is an attached local image info = new BlogPostImagePropertiesInfo(imageData, new ImageDecoratorsList(editorContext.DecoratorsManager, imageData.ImageDecoratorSettings)); info.ImgElement = imgHtmlElement; } else { //this is not an attached local image, so treat as a web image ImageDecoratorsList remoteImageDecoratorsList = new ImageDecoratorsList(editorContext.DecoratorsManager, new BlogPostSettingsBag()); remoteImageDecoratorsList.AddDecorator(editorContext.DecoratorsManager.GetDefaultRemoteImageDecorators()); //The source image size is unknown, so calculate the actual image size by removing //the size attributes, checking the size, and then placing the size attributes back string oldHeight = imgHtmlElement.getAttribute("height", 2) as string; string oldWidth = imgHtmlElement.getAttribute("width", 2) as string; imgHtmlElement.removeAttribute("width", 0); imgHtmlElement.removeAttribute("height", 0); int width = imgElement.width; int height = imgElement.height; if (!String.IsNullOrEmpty(oldHeight)) imgHtmlElement.setAttribute("height", oldHeight, 0); if (!String.IsNullOrEmpty(oldWidth)) imgHtmlElement.setAttribute("width", oldWidth, 0); info = new ImagePropertiesInfo(new Uri(imgSrc), new Size(width, height), remoteImageDecoratorsList); info.ImgElement = imgHtmlElement; // Sets the correct inline image size and image size name for the remote image. if (!String.IsNullOrEmpty(oldWidth) && !String.IsNullOrEmpty(oldHeight)) { int inlineWidth, inlineHeight; if (Int32.TryParse(oldWidth, NumberStyles.Integer, CultureInfo.InvariantCulture, out inlineWidth) && Int32.TryParse(oldHeight, NumberStyles.Integer, CultureInfo.InvariantCulture, out inlineHeight)) { info.InlineImageSize = new Size(inlineWidth, inlineHeight); } } // Sets the correct border style for the remote image. if (new HtmlBorderDecoratorSettings(imgHtmlElement).InheritBorder) { if (!info.ImageDecorators.ContainsDecorator(HtmlBorderDecorator.Id)) info.ImageDecorators.AddDecorator(HtmlBorderDecorator.Id); } else if (new NoBorderDecoratorSettings(imgHtmlElement).NoBorder) { if (!info.ImageDecorators.ContainsDecorator(NoBorderDecorator.Id)) info.ImageDecorators.AddDecorator(NoBorderDecorator.Id); } } //transfer image data properties if (imageData != null) { info.UploadSettings = imageData.UploadInfo.Settings; info.UploadServiceId = imageData.UploadInfo.ImageServiceId; if (info.UploadServiceId == null) { info.UploadServiceId = editorContext.ImageServiceId; } } return info; } private IHTMLElement ImgElement { get { return _propertyEditingContext.SelectedImage as IHTMLElement; } } private void imageProperties_ImagePropertyChanged(object source, ImagePropertyEvent evt) { if (ImgElement != null) { switch (evt.PropertyType) { case ImagePropertyType.Source: case ImagePropertyType.InlineSize: case ImagePropertyType.Decorators: UpdateImageSource(evt.ImageProperties, evt.InvocationSource); break; default: Debug.Fail("Unsupported image property type update: " + evt.PropertyType); break; } } } private void UpdateImageSource(ImagePropertiesInfo imgProperties, ImageDecoratorInvocationSource invocationSource) { UpdateImageSource(imgProperties, ImgElement, _editorContext, _imageInsertHandler, invocationSource); } internal static void UpdateImageSource(ImagePropertiesInfo imgProperties, IHTMLElement imgElement, IBlogPostImageEditingContext editorContext, ImageInsertHandler imageInsertHandler, ImageDecoratorInvocationSource invocationSource) { ISupportingFile oldImageFile = null; try { oldImageFile = editorContext.SupportingFileService.GetFileByUri(new Uri((string)imgElement.getAttribute("src", 2))); } catch (UriFormatException) { } if (oldImageFile != null) //then this is a known supporting image file { using (new WaitCursor()) { BlogPostImageData imageData = BlogPostImageDataList.LookupImageDataByInlineUri(editorContext.ImageList, oldImageFile.FileUri); if (imageData != null) { //Create a new ImageData object based on the image data attached to the current image src file. BlogPostImageData newImageData = (BlogPostImageData)imageData.Clone(); //initialize some handlers for creating files based on the image's existing ISupportingFile objects //This is necessary so that the new image files are recognized as being updates to an existing image //which allows the updates to be re-uploaded back to the same location. CreateImageFileHandler inlineFileCreator = new CreateImageFileHandler(editorContext.SupportingFileService, newImageData.InlineImageFile != null ? newImageData.InlineImageFile.SupportingFile : null); CreateImageFileHandler linkedFileCreator = new CreateImageFileHandler(editorContext.SupportingFileService, newImageData.LinkedImageFile != null ? newImageData.LinkedImageFile.SupportingFile : null); //re-write the image files on disk using the latest settings imageInsertHandler.WriteImages(imgProperties, true, invocationSource, new CreateFileCallback(inlineFileCreator.CreateFileCallback), new CreateFileCallback(linkedFileCreator.CreateFileCallback), editorContext.EditorOptions); //update the ImageData file references Size imageSizeWithBorder = imgProperties.InlineImageSizeWithBorder; //force a refresh of the image size values in the DOM by setting the new size attributes imgElement.setAttribute("width", imageSizeWithBorder.Width, 0); imgElement.setAttribute("height", imageSizeWithBorder.Height, 0); newImageData.InlineImageFile.SupportingFile = inlineFileCreator.ImageSupportingFile; newImageData.InlineImageFile.Height = imageSizeWithBorder.Height; newImageData.InlineImageFile.Width = imageSizeWithBorder.Width; if (imgProperties.LinkTarget == LinkTargetType.IMAGE) { newImageData.LinkedImageFile = new ImageFileData(linkedFileCreator.ImageSupportingFile, imgProperties.LinkTargetImageSize.Width, imgProperties.LinkTargetImageSize.Height, ImageFileRelationship.Linked); } else newImageData.LinkedImageFile = null; //assign the image decorators applied during WriteImages //Note: this is a clone so the sidebar doesn't affect the decorator values for the newImageData image src file newImageData.ImageDecoratorSettings = (BlogPostSettingsBag)imgProperties.ImageDecorators.SettingsBag.Clone(); //update the upload settings newImageData.UploadInfo.ImageServiceId = imgProperties.UploadServiceId; //save the new image data in the image list editorContext.ImageList.AddImage(newImageData); } else Debug.Fail("imageData could not be located"); } } if (imgProperties.LinkTarget == LinkTargetType.NONE) { imgProperties.RemoveLinkTarget(); } } //Utility for an updating image file based on a particular ISupportingFile. private class CreateImageFileHandler { public ISupportingFile ImageSupportingFile; ISupportingFileService _fileService; public CreateImageFileHandler(ISupportingFileService fileService, ISupportingFile supportingFile) { _fileService = fileService; ImageSupportingFile = supportingFile; } public string CreateFileCallback(string requestedFileName) { if (ImageSupportingFile == null) ImageSupportingFile = _fileService.CreateSupportingFile(requestedFileName, new MemoryStream(new byte[0])); else ImageSupportingFile = ImageSupportingFile.UpdateFile(new MemoryStream(new byte[0]), requestedFileName); return ImageSupportingFile.FileUri.LocalPath; } } } public delegate void ImagePropertyEventHandler(object source, ImagePropertyEvent evt); public enum ImagePropertyType { Source, InlineSize, Decorators }; public class ImagePropertyEvent : EventArgs { public ImagePropertiesInfo ImageProperties { get { return _imageProperties; } } private readonly ImagePropertiesInfo _imageProperties; public readonly ImagePropertyType PropertyType; public readonly ImageDecoratorInvocationSource InvocationSource; public ImagePropertyEvent(ImagePropertyType propertyType, ImagePropertiesInfo imgProperties, ImageDecoratorInvocationSource invocationSource) { PropertyType = propertyType; _imageProperties = imgProperties; InvocationSource = invocationSource; } } }
#if !DISABLE_PLAYFABENTITY_API using System; using System.Collections.Generic; using PlayFab.MultiplayerModels; using PlayFab.Internal; using PlayFab.Json; using PlayFab.Public; namespace PlayFab { /// <summary> /// API methods for managing multiplayer servers. /// </summary> public static class PlayFabMultiplayerAPI { static PlayFabMultiplayerAPI() {} /// <summary> /// Clear the Client SessionToken which allows this Client to call API calls requiring login. /// A new/fresh login will be required after calling this. /// </summary> public static void ForgetAllCredentials() { PlayFabHttp.ForgetAllCredentials(); } /// <summary> /// Creates a multiplayer server build with a custom container. /// </summary> public static void CreateBuildWithCustomContainer(CreateBuildWithCustomContainerRequest request, Action<CreateBuildWithCustomContainerResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/CreateBuildWithCustomContainer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Creates a multiplayer server build with a managed container. /// </summary> public static void CreateBuildWithManagedContainer(CreateBuildWithManagedContainerRequest request, Action<CreateBuildWithManagedContainerResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/CreateBuildWithManagedContainer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Creates a remote user to log on to a VM for a multiplayer server build. /// </summary> public static void CreateRemoteUser(CreateRemoteUserRequest request, Action<CreateRemoteUserResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/CreateRemoteUser", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Deletes a multiplayer server game asset for a title. /// </summary> public static void DeleteAsset(DeleteAssetRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteAsset", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Deletes a multiplayer server build. /// </summary> public static void DeleteBuild(DeleteBuildRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteBuild", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Deletes a multiplayer server game certificate. /// </summary> public static void DeleteCertificate(DeleteCertificateRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteCertificate", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Deletes a remote user to log on to a VM for a multiplayer server build. /// </summary> public static void DeleteRemoteUser(DeleteRemoteUserRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteRemoteUser", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Enables the multiplayer server feature for a title. /// </summary> public static void EnableMultiplayerServersForTitle(EnableMultiplayerServersForTitleRequest request, Action<EnableMultiplayerServersForTitleResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/EnableMultiplayerServersForTitle", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Gets the URL to upload assets to. /// </summary> public static void GetAssetUploadUrl(GetAssetUploadUrlRequest request, Action<GetAssetUploadUrlResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/GetAssetUploadUrl", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Gets a multiplayer server build. /// </summary> public static void GetBuild(GetBuildRequest request, Action<GetBuildResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/GetBuild", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Gets the credentials to the container registry. /// </summary> public static void GetContainerRegistryCredentials(GetContainerRegistryCredentialsRequest request, Action<GetContainerRegistryCredentialsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/GetContainerRegistryCredentials", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Gets multiplayer server session details for a build. /// </summary> public static void GetMultiplayerServerDetails(GetMultiplayerServerDetailsRequest request, Action<GetMultiplayerServerDetailsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/GetMultiplayerServerDetails", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Gets a remote login endpoint to a VM that is hosting a multiplayer server build. /// </summary> public static void GetRemoteLoginEndpoint(GetRemoteLoginEndpointRequest request, Action<GetRemoteLoginEndpointResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/GetRemoteLoginEndpoint", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Gets the status of whether a title is enabled for the multiplayer server feature. /// </summary> public static void GetTitleEnabledForMultiplayerServersStatus(GetTitleEnabledForMultiplayerServersStatusRequest request, Action<GetTitleEnabledForMultiplayerServersStatusResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/GetTitleEnabledForMultiplayerServersStatus", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Lists archived multiplayer server sessions for a build. /// </summary> public static void ListArchivedMultiplayerServers(ListMultiplayerServersRequest request, Action<ListMultiplayerServersResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/ListArchivedMultiplayerServers", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Lists multiplayer server game assets for a title. /// </summary> public static void ListAssetSummaries(ListAssetSummariesRequest request, Action<ListAssetSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/ListAssetSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Lists summarized details of all multiplayer server builds for a title. /// </summary> public static void ListBuildSummaries(ListBuildSummariesRequest request, Action<ListBuildSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/ListBuildSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Lists multiplayer server game certificates for a title. /// </summary> public static void ListCertificateSummaries(ListCertificateSummariesRequest request, Action<ListCertificateSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/ListCertificateSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Lists custom container images for a title. /// </summary> public static void ListContainerImages(ListContainerImagesRequest request, Action<ListContainerImagesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/ListContainerImages", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Lists the tags for a custom container image. /// </summary> public static void ListContainerImageTags(ListContainerImageTagsRequest request, Action<ListContainerImageTagsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/ListContainerImageTags", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Lists multiplayer server sessions for a build. /// </summary> public static void ListMultiplayerServers(ListMultiplayerServersRequest request, Action<ListMultiplayerServersResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/ListMultiplayerServers", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Lists quality of service servers. /// </summary> public static void ListQosServers(ListQosServersRequest request, Action<ListQosServersResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/ListQosServers", request, AuthType.None, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Lists virtual machines for a title. /// </summary> public static void ListVirtualMachineSummaries(ListVirtualMachineSummariesRequest request, Action<ListVirtualMachineSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/ListVirtualMachineSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Request a multiplayer server session. Accepts tokens for title and if game client accesss is enabled, allows game client /// to request a server with player entity token. /// </summary> public static void RequestMultiplayerServer(RequestMultiplayerServerRequest request, Action<RequestMultiplayerServerResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/RequestMultiplayerServer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Rolls over the credentials to the container registry. /// </summary> public static void RolloverContainerRegistryCredentials(RolloverContainerRegistryCredentialsRequest request, Action<RolloverContainerRegistryCredentialsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/RolloverContainerRegistryCredentials", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Shuts down a multiplayer server session. /// </summary> public static void ShutdownMultiplayerServer(ShutdownMultiplayerServerRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/ShutdownMultiplayerServer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Updates a multiplayer server build's regions. /// </summary> public static void UpdateBuildRegions(UpdateBuildRegionsRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/UpdateBuildRegions", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } /// <summary> /// Uploads a multiplayer server game certificate. /// </summary> public static void UploadCertificate(UploadCertificateRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { PlayFabHttp.MakeApiCall("/MultiplayerServer/UploadCertificate", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders); } } } #endif
// 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.Concurrent; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindSymbols.SymbolTree; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; using static Roslyn.Utilities.PortableShim; namespace Microsoft.CodeAnalysis.IncrementalCaches { /// <summary> /// Features like add-using want to be able to quickly search symbol indices for projects and /// metadata. However, creating those indices can be expensive. As such, we don't want to /// construct them during the add-using process itself. Instead, we expose this type as an /// Incremental-Analyzer to walk our projects/metadata in the background to keep the indices /// up to date. /// /// We also then export this type as a service that can give back the index for a project or /// metadata dll on request. If the index has been produced then it will be returned and /// can be used by add-using. Otherwise, nothing is returned and no results will be found. /// /// This means that as the project is being indexed, partial results may be returned. However /// once it is fully indexed, then total results will be returned. /// </summary> [Shared] [ExportIncrementalAnalyzerProvider(nameof(SymbolTreeInfoIncrementalAnalyzerProvider), new[] { WorkspaceKind.Host })] [ExportWorkspaceServiceFactory(typeof(ISymbolTreeInfoCacheService))] internal class SymbolTreeInfoIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider, IWorkspaceServiceFactory { private struct ProjectInfo { public readonly VersionStamp VersionStamp; public readonly SymbolTreeInfo SymbolTreeInfo; public ProjectInfo(VersionStamp versionStamp, SymbolTreeInfo info) { VersionStamp = versionStamp; SymbolTreeInfo = info; } } private struct MetadataInfo { public readonly DateTime TimeStamp; public readonly SymbolTreeInfo SymbolTreeInfo; /// <summary> /// Note: the Incremental-Analyzer infrastructure guarantees that it will call all the methods /// on <see cref="IncrementalAnalyzer"/> in a serial fashion. As that is the only type that /// reads/writes these <see cref="MetadataInfo"/> objects, we don't need to lock this. /// </summary> public readonly HashSet<ProjectId> ReferencingProjects; public MetadataInfo(DateTime timeStamp, SymbolTreeInfo info, HashSet<ProjectId> referencingProjects) { TimeStamp = timeStamp; SymbolTreeInfo = info; ReferencingProjects = referencingProjects; } } // Concurrent dictionaries so they can be read from the SymbolTreeInfoCacheService while // they are being populated/updated by the IncrementalAnalyzer. private readonly ConcurrentDictionary<ProjectId, ProjectInfo> _projectToInfo = new ConcurrentDictionary<ProjectId, ProjectInfo>(); private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo = new ConcurrentDictionary<string, MetadataInfo>(); public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { var cacheService = workspace.Services.GetService<IWorkspaceCacheService>(); if (cacheService != null) { cacheService.CacheFlushRequested += OnCacheFlushRequested; } return new IncrementalAnalyzer(_projectToInfo, _metadataPathToInfo); } private void OnCacheFlushRequested(object sender, EventArgs e) { // If we hear about low memory conditions, flush our caches. This will degrade the // experience a bit (as we will no longer offer to Add-Using for p2p refs/metadata), // but will be better than OOM'ing. These caches will be regenerated in the future // when the incremental analyzer reanalyzers the projects in teh workspace. _projectToInfo.Clear(); _metadataPathToInfo.Clear(); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { return new SymbolTreeInfoCacheService(_projectToInfo, _metadataPathToInfo); } private static string GetReferenceKey(PortableExecutableReference reference) { return reference.FilePath ?? reference.Display; } private static bool TryGetLastWriteTime(string path, out DateTime time) { var succeeded = false; time = IOUtilities.PerformIO( () => { var result = File.GetLastWriteTimeUtc(path); succeeded = true; return result; }, default(DateTime)); return succeeded; } private class SymbolTreeInfoCacheService : ISymbolTreeInfoCacheService { private readonly ConcurrentDictionary<ProjectId, ProjectInfo> _projectToInfo; private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo; public SymbolTreeInfoCacheService( ConcurrentDictionary<ProjectId, ProjectInfo> projectToInfo, ConcurrentDictionary<string, MetadataInfo> metadataPathToInfo) { _projectToInfo = projectToInfo; _metadataPathToInfo = metadataPathToInfo; } public async Task<SymbolTreeInfo> TryGetMetadataSymbolTreeInfoAsync( Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { var key = GetReferenceKey(reference); if (key != null) { MetadataInfo metadataInfo; if (_metadataPathToInfo.TryGetValue(key, out metadataInfo)) { DateTime writeTime; if (TryGetLastWriteTime(key, out writeTime) && writeTime == metadataInfo.TimeStamp) { return metadataInfo.SymbolTreeInfo; } } } // If we didn't have it in our cache, see if we can load it from disk. // Note: pass 'loadOnly' so we only attempt to load from disk, not to actually // try to create the metadata. var info = await SymbolTreeInfo.GetInfoForMetadataReferenceAsync( solution, reference, loadOnly: true, cancellationToken: cancellationToken).ConfigureAwait(false); return info; } public async Task<SymbolTreeInfo> TryGetSourceSymbolTreeInfoAsync( Project project, CancellationToken cancellationToken) { ProjectInfo projectInfo; if (_projectToInfo.TryGetValue(project.Id, out projectInfo)) { var version = await project.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); if (version == projectInfo.VersionStamp) { return projectInfo.SymbolTreeInfo; } } return null; } } private class IncrementalAnalyzer : IncrementalAnalyzerBase { private readonly ConcurrentDictionary<ProjectId, ProjectInfo> _projectToInfo; private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo; public IncrementalAnalyzer( ConcurrentDictionary<ProjectId, ProjectInfo> projectToInfo, ConcurrentDictionary<string, MetadataInfo> metadataPathToInfo) { _projectToInfo = projectToInfo; _metadataPathToInfo = metadataPathToInfo; } public override Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { if (!document.SupportsSyntaxTree) { // Not a language we can produce indices for (i.e. TypeScript). Bail immediately. return SpecializedTasks.EmptyTask; } if (bodyOpt != null) { // This was a method level edit. This can't change the symbol tree info // for this project. Bail immediately. return SpecializedTasks.EmptyTask; } return UpdateSymbolTreeInfoAsync(document.Project, cancellationToken); } public override Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { return UpdateSymbolTreeInfoAsync(project, cancellationToken); } private async Task UpdateSymbolTreeInfoAsync(Project project, CancellationToken cancellationToken) { if (!project.SupportsCompilation) { return; } // Check the semantic version of this project. The semantic version will change // if any of the source files changed, or if the project version itself changed. // (The latter happens when something happens to the project like metadata // changing on disk). var version = await project.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); ProjectInfo projectInfo; if (!_projectToInfo.TryGetValue(project.Id, out projectInfo) || projectInfo.VersionStamp != version) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); // Update the symbol tree infos for metadata and source in parallel. var referencesTask = UpdateReferencesAync(project, compilation, cancellationToken); var projectTask = SymbolTreeInfo.GetInfoForSourceAssemblyAsync(project, cancellationToken); await Task.WhenAll(referencesTask, projectTask).ConfigureAwait(false); // Mark that we're up to date with this project. Future calls with the same // semantic version can bail out immediately. projectInfo = new ProjectInfo(version, await projectTask.ConfigureAwait(false)); _projectToInfo.AddOrUpdate(project.Id, projectInfo, (_1, _2) => projectInfo); } } private Task UpdateReferencesAync(Project project, Compilation compilation, CancellationToken cancellationToken) { // Process all metadata references in parallel. var tasks = project.MetadataReferences.OfType<PortableExecutableReference>() .Select(r => UpdateReferenceAsync(project, compilation, r, cancellationToken)) .ToArray(); return Task.WhenAll(tasks); } private async Task UpdateReferenceAsync( Project project, Compilation compilation, PortableExecutableReference reference, CancellationToken cancellationToken) { var key = GetReferenceKey(reference); if (key == null) { return; } DateTime lastWriteTime; if (!TryGetLastWriteTime(key, out lastWriteTime)) { // Couldn't get the write time. Just ignore this reference. return; } MetadataInfo metadataInfo; if (!_metadataPathToInfo.TryGetValue(key, out metadataInfo) || metadataInfo.TimeStamp == lastWriteTime) { var info = await SymbolTreeInfo.GetInfoForMetadataReferenceAsync( project.Solution, reference, loadOnly: false, cancellationToken: cancellationToken).ConfigureAwait(false); metadataInfo = new MetadataInfo(lastWriteTime, info, metadataInfo.ReferencingProjects ?? new HashSet<ProjectId>()); _metadataPathToInfo.AddOrUpdate(key, metadataInfo, (_1, _2) => metadataInfo); } // Keep track that this dll is referenced by this project. metadataInfo.ReferencingProjects.Add(project.Id); } public override void RemoveProject(ProjectId projectId) { ProjectInfo info; _projectToInfo.TryRemove(projectId, out info); RemoveMetadataReferences(projectId); } private void RemoveMetadataReferences(ProjectId projectId) { foreach (var kvp in _metadataPathToInfo.ToArray()) { if (kvp.Value.ReferencingProjects.Remove(projectId)) { if (kvp.Value.ReferencingProjects.Count == 0) { // This metadata dll isn't referenced by any project. We can just dump it. MetadataInfo unneeded; _metadataPathToInfo.TryRemove(kvp.Key, out unneeded); } } } } } } }
// 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. /* We are testing the following scenario: interface I<T> {} [in Class_ImplicitOverrideVirtualNewslot.cs] class C<T> : I<T> { virtual newslot methods} class D<T> : C<T> {virtual methods} --> When invoking I::method<T>() we should get the most derived child's implementation. */ using System; public class CC1 : C1 { public override int method1() { return 10; } public override int method2<T>() { return 20; } } public class CC2<T> : C2<T> { public override int method1() { return 30; } public override int method2<U>() { return 40; } } public class CC3Int : C3Int { public override int method1() { return 50; } public override int method2<U>() { return 60; } } public class CC3String : C3String { public override int method1() { return 50; } public override int method2<U>() { return 60; } } public class CC3Object: C3Object { public override int method1() { return 50; } public override int method2<U>() { return 60; } } public class CC4<T> : C4<T> { public override int method1() { return 70; } public override int method2<U>() { return 80; } } public class Test { public static int counter = 0; public static bool pass = true; public static void Eval(bool exp) { counter++; if (!exp) { pass = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static void TestNonGenInterface_NonGenType() { I ic1 = new CC1(); // since CC1's method doesn't have newslot, in both cases we should get CC1's method // TEST1: test generic virtual method Eval( (ic1.method2<int>().ToString()).Equals("20") ); Eval( (ic1.method2<string>() .ToString()).Equals("20") ); Eval( (ic1.method2<object>().ToString()).Equals("20") ); Eval( (ic1.method2<A<int>>().ToString()).Equals("20") ); Eval( (ic1.method2<S<object>>().ToString()).Equals("20") ); } public static void TestNonGenInterface_GenType() { I ic2Int = new CC2<int>(); I ic2Object = new CC2<object>(); I ic2String = new CC2<string>(); // TEST2: test non generic virtual method Eval( (ic2Int.method1().ToString()).Equals("30") ); Eval( (ic2String.method1().ToString()).Equals("30") ); Eval( (ic2Object.method1().ToString()).Equals("30") ); // TEST3: test generic virtual method Eval( (ic2Int.method2<int>().ToString()).Equals("40") ); Eval( (ic2Int.method2<object>().ToString()).Equals("40") ); Eval( (ic2Int.method2<string>().ToString()).Equals("40") ); Eval( (ic2Int.method2<A<int>>().ToString()).Equals("40") ); Eval( (ic2Int.method2<S<string>>().ToString()).Equals("40") ); Eval( (ic2String.method2<int>().ToString()).Equals("40") ); Eval( (ic2String.method2<object>().ToString()).Equals("40") ); Eval( (ic2String.method2<string>().ToString()).Equals("40") ); Eval( (ic2String.method2<A<int>>().ToString()).Equals("40") ); Eval( (ic2String.method2<S<string>>().ToString()).Equals("40") ); Eval( (ic2Object.method2<int>().ToString()).Equals("40") ); Eval( (ic2Object.method2<object>().ToString()).Equals("40") ); Eval( (ic2Object.method2<string>().ToString()).Equals("40") ); Eval( (ic2Object.method2<A<int>>().ToString()).Equals("40") ); Eval( (ic2Object.method2<S<string>>().ToString()).Equals("40") ); } public static void TestGenInterface_NonGenType() { IGen<int> iIntc3 = new CC3Int(); IGen<object> iObjectc3 = new CC3Object(); IGen<string> iStringc3 = new CC3String(); // TEST4: test non generic virtual method Eval( (iIntc3.method1().ToString()).Equals("50") ); Eval( (iObjectc3.method1().ToString()).Equals("50") ); Eval( (iStringc3.method1().ToString()).Equals("50") ); // TEST5: test generic virtual method Eval( (iIntc3.method2<int>().ToString()).Equals("60") ); Eval( (iIntc3.method2<object>().ToString()).Equals("60") ); Eval( (iIntc3.method2<string>().ToString()).Equals("60") ); Eval( (iIntc3.method2<A<int>>().ToString()).Equals("60") ); Eval( (iIntc3.method2<S<string>>().ToString()).Equals("60") ); Eval( (iStringc3.method2<int>().ToString()).Equals("60") ); Eval( (iStringc3.method2<object>().ToString()).Equals("60") ); Eval( (iStringc3.method2<string>().ToString()).Equals("60") ); Eval( (iStringc3.method2<A<int>>().ToString()).Equals("60") ); Eval( (iStringc3.method2<S<string>>().ToString()).Equals("60") ); Eval( (iObjectc3.method2<int>().ToString()).Equals("60") ); Eval( (iObjectc3.method2<object>().ToString()).Equals("60") ); Eval( (iObjectc3.method2<string>().ToString()).Equals("60") ); Eval( (iObjectc3.method2<A<int>>().ToString()).Equals("60") ); Eval( (iObjectc3.method2<S<string>>().ToString()).Equals("60") ); } public static void TestGenInterface_GenType() { IGen<int> iGenC4Int = new CC4<int>(); IGen<object> iGenC4Object = new CC4<object>(); IGen<string> iGenC4String = new CC4<string>(); // TEST6: test non generic virtual method Eval( (iGenC4Int.method1().ToString()).Equals("70") ); Eval( (iGenC4Object.method1().ToString()).Equals("70") ); Eval( (iGenC4String.method1().ToString()).Equals("70") ); // TEST7: test generic virtual method Eval( (iGenC4Int.method2<int>().ToString()).Equals("80") ); Eval( (iGenC4Int.method2<object>().ToString()).Equals("80") ); Eval( (iGenC4Int.method2<string>().ToString()).Equals("80") ); Eval( (iGenC4Int.method2<A<int>>().ToString()).Equals("80") ); Eval( (iGenC4Int.method2<S<string>>().ToString()).Equals("80") ); Eval( (iGenC4String.method2<int>().ToString()).Equals("80") ); Eval( (iGenC4String.method2<object>().ToString()).Equals("80") ); Eval( (iGenC4String.method2<string>().ToString()).Equals("80") ); Eval( (iGenC4String.method2<A<int>>().ToString()).Equals("80") ); Eval( (iGenC4String.method2<S<string>>().ToString()).Equals("80") ); Eval( (iGenC4Object.method2<int>().ToString()).Equals("80") ); Eval( (iGenC4Object.method2<object>().ToString()).Equals("80") ); Eval( (iGenC4Object.method2<string>().ToString()).Equals("80") ); Eval( (iGenC4Object.method2<A<int>>().ToString()).Equals("80") ); Eval( (iGenC4Object.method2<S<string>>().ToString()).Equals("80") ); } public static int Main() { TestNonGenInterface_NonGenType(); TestNonGenInterface_GenType(); TestGenInterface_NonGenType(); TestGenInterface_GenType(); if (pass) { Console.WriteLine("PASS"); return 100; } else { Console.WriteLine("FAIL"); return 101; } } }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Reflection; using Google.ProtocolBuffers.Collections; using Google.ProtocolBuffers.DescriptorProtos; namespace Google.ProtocolBuffers.Descriptors { /// <summary> /// Descriptor for a field or extension within a message in a .proto file. /// </summary> public sealed class FieldDescriptor : IndexedDescriptorBase<FieldDescriptorProto, FieldOptions>, IComparable<FieldDescriptor> { private readonly MessageDescriptor extensionScope; private EnumDescriptor enumType; private MessageDescriptor messageType; private MessageDescriptor containingType; private object defaultValue; private FieldType fieldType; private MappedType mappedType; private CSharpFieldOptions csharpFieldOptions; private readonly object optionsLock = new object(); internal FieldDescriptor(FieldDescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int index, bool isExtension) : base(proto, file, ComputeFullName(file, parent, proto.Name), index) { if (proto.HasType) { fieldType = GetFieldTypeFromProtoType(proto.Type); mappedType = FieldTypeToMappedTypeMap[fieldType]; } if (FieldNumber <= 0) { throw new DescriptorValidationException(this, "Field numbers must be positive integers."); } if (isExtension) { if (!proto.HasExtendee) { throw new DescriptorValidationException(this, "FieldDescriptorProto.Extendee not set for extension field."); } containingType = null; // Will be filled in when cross-linking if (parent != null) { extensionScope = parent; } else { extensionScope = null; } } else { if (proto.HasExtendee) { throw new DescriptorValidationException(this, "FieldDescriptorProto.Extendee set for non-extension field."); } containingType = parent; extensionScope = null; } file.DescriptorPool.AddSymbol(this); } private CSharpFieldOptions BuildOrFakeCSharpOptions() { // TODO(jonskeet): Check if we could use FileDescriptorProto.Descriptor.Name - interesting bootstrap issues if (File.Proto.Name == "google/protobuf/csharp_options.proto") { if (Name=="csharp_field_options") { return new CSharpFieldOptions.Builder { PropertyName = "CSharpFieldOptions" }.Build(); } if (Name=="csharp_file_options") { return new CSharpFieldOptions.Builder { PropertyName = "CSharpFileOptions" }.Build(); } } CSharpFieldOptions.Builder builder = CSharpFieldOptions.CreateBuilder(); if (Proto.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFieldOptions)) { builder.MergeFrom(Proto.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFieldOptions)); } if (!builder.HasPropertyName) { string fieldName = FieldType == FieldType.Group ? MessageType.Name : Name; string propertyName = NameHelpers.UnderscoresToPascalCase(fieldName); if (propertyName == ContainingType.Name) { propertyName += "_"; } builder.PropertyName = propertyName; } return builder.Build(); } /// <summary> /// Maps a field type as included in the .proto file to a FieldType. /// </summary> private static FieldType GetFieldTypeFromProtoType(FieldDescriptorProto.Types.Type type) { switch (type) { case FieldDescriptorProto.Types.Type.TYPE_DOUBLE: return FieldType.Double; case FieldDescriptorProto.Types.Type.TYPE_FLOAT: return FieldType.Float; case FieldDescriptorProto.Types.Type.TYPE_INT64: return FieldType.Int64; case FieldDescriptorProto.Types.Type.TYPE_UINT64: return FieldType.UInt64; case FieldDescriptorProto.Types.Type.TYPE_INT32: return FieldType.Int32; case FieldDescriptorProto.Types.Type.TYPE_FIXED64: return FieldType.Fixed64; case FieldDescriptorProto.Types.Type.TYPE_FIXED32: return FieldType.Fixed32; case FieldDescriptorProto.Types.Type.TYPE_BOOL: return FieldType.Bool; case FieldDescriptorProto.Types.Type.TYPE_STRING: return FieldType.String; case FieldDescriptorProto.Types.Type.TYPE_GROUP: return FieldType.Group; case FieldDescriptorProto.Types.Type.TYPE_MESSAGE: return FieldType.Message; case FieldDescriptorProto.Types.Type.TYPE_BYTES: return FieldType.Bytes; case FieldDescriptorProto.Types.Type.TYPE_UINT32: return FieldType.UInt32; case FieldDescriptorProto.Types.Type.TYPE_ENUM: return FieldType.Enum; case FieldDescriptorProto.Types.Type.TYPE_SFIXED32: return FieldType.SFixed32; case FieldDescriptorProto.Types.Type.TYPE_SFIXED64: return FieldType.SFixed64; case FieldDescriptorProto.Types.Type.TYPE_SINT32: return FieldType.SInt32; case FieldDescriptorProto.Types.Type.TYPE_SINT64: return FieldType.SInt64; default: throw new ArgumentException("Invalid type specified"); } } /// <summary> /// Returns the default value for a mapped type. /// </summary> private static object GetDefaultValueForMappedType(MappedType type) { switch (type) { case MappedType.Int32: return 0; case MappedType.Int64: return (long) 0; case MappedType.UInt32: return (uint) 0; case MappedType.UInt64: return (ulong) 0; case MappedType.Single: return (float) 0; case MappedType.Double: return (double) 0; case MappedType.Boolean: return false; case MappedType.String: return ""; case MappedType.ByteString: return ByteString.Empty; case MappedType.Message: return null; case MappedType.Enum: return null; default: throw new ArgumentException("Invalid type specified"); } } public bool IsRequired { get { return Proto.Label == FieldDescriptorProto.Types.Label.LABEL_REQUIRED; } } public bool IsOptional { get { return Proto.Label == FieldDescriptorProto.Types.Label.LABEL_OPTIONAL; } } public bool IsRepeated { get { return Proto.Label == FieldDescriptorProto.Types.Label.LABEL_REPEATED; } } public bool IsPacked { get { return Proto.Options.Packed; } } /// <valule> /// Indicates whether or not the field had an explicitly-defined default value. /// </value> public bool HasDefaultValue { get { return Proto.HasDefaultValue; } } /// <value> /// The field's default value. Valid for all types except messages /// and groups. For all other types, the object returned is of the /// same class that would be returned by IMessage[this]. /// For repeated fields this will always be an empty immutable list compatible with IList[object]. /// For message fields it will always be null. For singular values, it will depend on the descriptor. /// </value> public object DefaultValue { get { if (MappedType == MappedType.Message) { throw new InvalidOperationException("FieldDescriptor.DefaultValue called on an embedded message field."); } return defaultValue; } } /// <value> /// Indicates whether or not this field is an extension. /// </value> public bool IsExtension { get { return Proto.HasExtendee; } } /* * Get the field's containing type. For extensions, this is the type being * extended, not the location where the extension was defined. See * {@link #getExtensionScope()}. */ /// <summary> /// Get the field's containing type. For extensions, this is the type being /// extended, not the location where the extension was defined. See /// <see cref="ExtensionScope" />. /// </summary> public MessageDescriptor ContainingType { get { return containingType; } } /// <summary> /// Returns the C#-specific options for this field descriptor. This will always be /// completely filled in. /// </summary> public CSharpFieldOptions CSharpOptions { get { lock (optionsLock) { if (csharpFieldOptions == null) { csharpFieldOptions = BuildOrFakeCSharpOptions(); } } return csharpFieldOptions; } } /// <summary> /// For extensions defined nested within message types, gets /// the outer type. Not valid for non-extension fields. /// </summary> /// <example> /// <code> /// message Foo { /// extensions 1000 to max; /// } /// extend Foo { /// optional int32 baz = 1234; /// } /// message Bar { /// extend Foo { /// optional int32 qux = 4321; /// } /// } /// </code> /// The containing type for both <c>baz</c> and <c>qux</c> is <c>Foo</c>. /// However, the extension scope for <c>baz</c> is <c>null</c> while /// the extension scope for <c>qux</c> is <c>Bar</c>. /// </example> public MessageDescriptor ExtensionScope { get { if (!IsExtension) { throw new InvalidOperationException("This field is not an extension."); } return extensionScope; } } public MappedType MappedType { get { return mappedType; } } public FieldType FieldType { get { return fieldType; } } public bool IsCLSCompliant { get { return mappedType != MappedType.UInt32 && mappedType != MappedType.UInt64; } } public int FieldNumber { get { return Proto.Number; } } /// <summary> /// Compares this descriptor with another one, ordering in "canonical" order /// which simply means ascending order by field number. <paramref name="other"/> /// must be a field of the same type, i.e. the <see cref="ContainingType"/> of /// both fields must be the same. /// </summary> public int CompareTo(FieldDescriptor other) { if (other.containingType != containingType) { throw new ArgumentException("FieldDescriptors can only be compared to other FieldDescriptors " + "for fields of the same message type."); } return FieldNumber - other.FieldNumber; } /// <summary> /// For enum fields, returns the field's type. /// </summary> public EnumDescriptor EnumType { get { if (MappedType != MappedType.Enum) { throw new InvalidOperationException("EnumType is only valid for enum fields."); } return enumType; } } /// <summary> /// For embedded message and group fields, returns the field's type. /// </summary> public MessageDescriptor MessageType { get { if (MappedType != MappedType.Message) { throw new InvalidOperationException("MessageType is only valid for enum fields."); } return messageType; } } /// <summary> /// Immutable mapping from field type to mapped type. Built using the attributes on /// FieldType values. /// </summary> public static readonly IDictionary<FieldType, MappedType> FieldTypeToMappedTypeMap = MapFieldTypes(); private static IDictionary<FieldType, MappedType> MapFieldTypes() { var map = new Dictionary<FieldType, MappedType>(); foreach (FieldInfo field in typeof(FieldType).GetFields(BindingFlags.Static | BindingFlags.Public)) { FieldType fieldType = (FieldType)field.GetValue(null); FieldMappingAttribute mapping = (FieldMappingAttribute)field.GetCustomAttributes(typeof(FieldMappingAttribute), false)[0]; map[fieldType] = mapping.MappedType; } return Dictionaries.AsReadOnly(map); } /// <summary> /// Look up and cross-link all field types etc. /// </summary> internal void CrossLink() { if (Proto.HasExtendee) { IDescriptor extendee = File.DescriptorPool.LookupSymbol(Proto.Extendee, this); if (!(extendee is MessageDescriptor)) { throw new DescriptorValidationException(this, "\"" + Proto.Extendee + "\" is not a message type."); } containingType = (MessageDescriptor) extendee; if (!containingType.IsExtensionNumber(FieldNumber)) { throw new DescriptorValidationException(this, "\"" + containingType.FullName + "\" does not declare " + FieldNumber + " as an extension number."); } } if (Proto.HasTypeName) { IDescriptor typeDescriptor = File.DescriptorPool.LookupSymbol(Proto.TypeName, this); if (!Proto.HasType) { // Choose field type based on symbol. if (typeDescriptor is MessageDescriptor) { fieldType = FieldType.Message; mappedType = MappedType.Message; } else if (typeDescriptor is EnumDescriptor) { fieldType = FieldType.Enum; mappedType = MappedType.Enum; } else { throw new DescriptorValidationException(this, "\"" + Proto.TypeName + "\" is not a type."); } } if (MappedType == MappedType.Message) { if (!(typeDescriptor is MessageDescriptor)) { throw new DescriptorValidationException(this, "\"" + Proto.TypeName + "\" is not a message type."); } messageType = (MessageDescriptor) typeDescriptor; if (Proto.HasDefaultValue) { throw new DescriptorValidationException(this, "Messages can't have default values."); } } else if (MappedType == Descriptors.MappedType.Enum) { if (!(typeDescriptor is EnumDescriptor)) { throw new DescriptorValidationException(this, "\"" + Proto.TypeName + "\" is not an enum type."); } enumType = (EnumDescriptor)typeDescriptor; } else { throw new DescriptorValidationException(this, "Field with primitive type has type_name."); } } else { if (MappedType == MappedType.Message || MappedType == MappedType.Enum) { throw new DescriptorValidationException(this, "Field with message or enum type missing type_name."); } } // We don't attempt to parse the default value until here because for // enums we need the enum type's descriptor. if (Proto.HasDefaultValue) { if (IsRepeated) { throw new DescriptorValidationException(this, "Repeated fields cannot have default values."); } try { switch (FieldType) { case FieldType.Int32: case FieldType.SInt32: case FieldType.SFixed32: defaultValue = TextFormat.ParseInt32(Proto.DefaultValue); break; case FieldType.UInt32: case FieldType.Fixed32: defaultValue = TextFormat.ParseUInt32(Proto.DefaultValue); break; case FieldType.Int64: case FieldType.SInt64: case FieldType.SFixed64: defaultValue = TextFormat.ParseInt64(Proto.DefaultValue); break; case FieldType.UInt64: case FieldType.Fixed64: defaultValue = TextFormat.ParseUInt64(Proto.DefaultValue); break; case FieldType.Float: defaultValue = TextFormat.ParseFloat(Proto.DefaultValue); break; case FieldType.Double: defaultValue = TextFormat.ParseDouble(Proto.DefaultValue); break; case FieldType.Bool: if (Proto.DefaultValue == "true") { defaultValue = true; } else if (Proto.DefaultValue == "false") { defaultValue = false; } else { throw new FormatException("Boolean values must be \"true\" or \"false\""); } break; case FieldType.String: defaultValue = Proto.DefaultValue; break; case FieldType.Bytes: try { defaultValue = TextFormat.UnescapeBytes(Proto.DefaultValue); } catch (FormatException e) { throw new DescriptorValidationException(this, "Couldn't parse default value: " + e.Message); } break; case FieldType.Enum: defaultValue = enumType.FindValueByName(Proto.DefaultValue); if (defaultValue == null) { throw new DescriptorValidationException(this, "Unknown enum default value: \"" + Proto.DefaultValue + "\""); } break; case FieldType.Message: case FieldType.Group: throw new DescriptorValidationException(this, "Message type had default value."); } } catch (FormatException e) { DescriptorValidationException validationException = new DescriptorValidationException(this, "Could not parse default value: \"" + Proto.DefaultValue + "\"", e); throw validationException; } } else { // Determine the default default for this field. if (IsRepeated) { defaultValue = Lists<object>.Empty; } else { switch (MappedType) { case MappedType.Enum: // We guarantee elsewhere that an enum type always has at least // one possible value. defaultValue = enumType.Values[0]; break; case MappedType.Message: defaultValue = null; break; default: defaultValue = GetDefaultValueForMappedType(MappedType); break; } } } if (!IsExtension) { File.DescriptorPool.AddFieldByNumber(this); } if (containingType != null && containingType.Options.MessageSetWireFormat) { if (IsExtension) { if (!IsOptional || FieldType != FieldType.Message) { throw new DescriptorValidationException(this, "Extensions of MessageSets must be optional messages."); } } else { throw new DescriptorValidationException(this, "MessageSets cannot have fields, only extensions."); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.CoreFunctionLibrary { /// <summary> /// Core Function Library - Parameter Type Coercion /// </summary> public static partial class ParameterTypeCoercionTests { /// <summary> /// count() can only take node sets as arguments. /// count(string('book')]) /// </summary> [Fact] public static void ParameterTypeCoercionTest281() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"count(string('book'))"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// count() can only take node sets as arguments. /// count(true()) /// </summary> [Fact] public static void ParameterTypeCoercionTest282() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"count(true())"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// count() can only take node sets as arguments. /// count(10) /// </summary> [Fact] public static void ParameterTypeCoercionTest283() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"count(10)"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// count() can only take node sets as arguments. /// count() /// </summary> [Fact] public static void ParameterTypeCoercionTest284() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"count()"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// expression returns empty node set /// count(//foo) /// </summary> [Fact] public static void ParameterTypeCoercionTest285() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"count(//foo)"; var expected = 0d; Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// local-name() can only take node sets as arguments. /// local-name(string('book')) /// </summary> [Fact] public static void ParameterTypeCoercionTest286() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"local-name(string('book'))"; Utils.XPathStringTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// local-name() can only take node sets as arguments. /// local-name(true()) /// </summary> [Fact] public static void ParameterTypeCoercionTest287() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"local-name(true())"; Utils.XPathStringTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// local-name() can only take node sets as arguments. /// local-name(10) /// </summary> [Fact] public static void ParameterTypeCoercionTest288() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"local-name(10)"; Utils.XPathStringTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// local-name() can only take node sets as arguments. /// local-name() /// </summary> [Fact] public static void ParameterTypeCoercionTest289() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"local-name()"; var expected = @"bookstore"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// expression returns empty node set /// local-name(//foo) /// </summary> [Fact] public static void ParameterTypeCoercionTest2810() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"local-name(//foo)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// name() can only take node sets as arguments. /// name(string('book')) /// </summary> [Fact] public static void ParameterTypeCoercionTest2811() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"name(string('book'))"; Utils.XPathStringTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// name() can only take node sets as arguments. /// name(true()) /// </summary> [Fact] public static void ParameterTypeCoercionTest2812() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"name(true())"; Utils.XPathStringTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// name() can only take node sets as arguments. /// name(10) /// </summary> [Fact] public static void ParameterTypeCoercionTest2813() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"name(10)"; Utils.XPathStringTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// expression returns empty node set /// name(//foo) /// </summary> [Fact] public static void ParameterTypeCoercionTest2814() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"name(//foo)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// namespace-uri() can only take node sets as arguments. /// namespace-uri(string('book')) /// </summary> [Fact] public static void ParameterTypeCoercionTest2815() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"namespace-uri(string('book'))"; Utils.XPathStringTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// namespace-uri() can only take node sets as arguments. /// namespace-uri(true()) /// </summary> [Fact] public static void ParameterTypeCoercionTest2816() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"namespace-uri(true())"; Utils.XPathStringTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// namespace-uri() can only take node sets as arguments. /// namespace-uri(10) /// </summary> [Fact] public static void ParameterTypeCoercionTest2817() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"namespace-uri(10)"; Utils.XPathStringTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// expression returns empty node set /// namespace-uri(//foo) /// </summary> [Fact] public static void ParameterTypeCoercionTest2818() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"namespace-uri(//foo)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// position() takes no args /// position(string('book')]) /// </summary> [Fact] public static void ParameterTypeCoercionTest2819() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"position(string('book'))"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// position() takes no args /// position(true()) /// </summary> [Fact] public static void ParameterTypeCoercionTest2820() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"position(true())"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// position() takes no args /// position(10) /// </summary> [Fact] public static void ParameterTypeCoercionTest2821() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"position(10)"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// position() takes no args /// position(//foo) /// </summary> [Fact] public static void ParameterTypeCoercionTest2822() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"position(//foo)"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// last() takes no args /// last(string('book')]) /// </summary> [Fact] public static void ParameterTypeCoercionTest2823() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"last(string('book'))"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// last() takes no args /// last(true()) /// </summary> [Fact] public static void ParameterTypeCoercionTest2824() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"last(true())"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// last() takes no args /// last(10) /// </summary> [Fact] public static void ParameterTypeCoercionTest2825() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"last(10)"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// last() takes no args /// last(//foo) /// </summary> [Fact] public static void ParameterTypeCoercionTest2826() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"last(//foo)"; Utils.XPathNumberTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; namespace Microsoft.Msagl.Routing.Visibility { /// <summary> /// the visibility graph /// </summary> public class VisibilityGraph { Dictionary<VisibilityVertex, VisibilityEdge> _prevEdgesDictionary=new Dictionary<VisibilityVertex,VisibilityEdge>(); internal void ClearPrevEdgesTable() { _prevEdgesDictionary.Clear(); } internal void ShrinkLengthOfPrevEdge(VisibilityVertex v, double lengthMultiplier) { _prevEdgesDictionary[v].LengthMultiplier = lengthMultiplier; } /// <summary> /// needed for shortest path calculations /// </summary> internal VisibilityVertex PreviosVertex(VisibilityVertex v) { VisibilityEdge prev; if (!_prevEdgesDictionary.TryGetValue(v, out prev)) return null; if (prev.Source == v) return prev.Target; return prev.Source; } internal void SetPreviousEdge(VisibilityVertex v, VisibilityEdge e) { Debug.Assert(v == e.Source || v == e.Target); _prevEdgesDictionary[v] = e; } /// <summary> /// the default is just to return VisibilityVertex /// </summary> Func<Point,VisibilityVertex> vertexFactory = (point => new VisibilityVertex(point)); internal Func<Point, VisibilityVertex> VertexFactory { get { return vertexFactory; } set { vertexFactory = value; } } readonly Dictionary<Point, VisibilityVertex> pointToVertexMap = new Dictionary<Point, VisibilityVertex>(); /// <summary> /// /// </summary> /// <param name="pathStart"></param> /// <param name="pathEnd"></param> /// <param name="obstacles"></param> /// <param name="sourceVertex">graph vertex corresponding to the source</param> /// <param name="targetVertex">graph vertex corresponding to the target</param> /// <returns></returns> internal static VisibilityGraph GetVisibilityGraphForShortestPath(Point pathStart, Point pathEnd, IEnumerable<Polyline> obstacles, out VisibilityVertex sourceVertex, out VisibilityVertex targetVertex) { var holes = new List<Polyline>(OrientHolesClockwise(obstacles)); var visibilityGraph = CalculateGraphOfBoundaries(holes); var polygons = holes.Select(hole => new Polygon(hole)).ToList(); TangentVisibilityGraphCalculator.AddTangentVisibilityEdgesToGraph(polygons, visibilityGraph); PointVisibilityCalculator.CalculatePointVisibilityGraph(holes, visibilityGraph, pathStart, VisibilityKind.Tangent, out sourceVertex); PointVisibilityCalculator.CalculatePointVisibilityGraph(holes, visibilityGraph, pathEnd, VisibilityKind.Tangent, out targetVertex); return visibilityGraph; } /// <summary> /// Calculates the tangent visibility graph /// </summary> /// <param name="obstacles">a list of polylines representing obstacles</param> /// <returns></returns> public static VisibilityGraph FillVisibilityGraphForShortestPath(IEnumerable<Polyline> obstacles) { var holes = new List<Polyline>(OrientHolesClockwise(obstacles)); var visibilityGraph = CalculateGraphOfBoundaries(holes); var polygons = holes.Select(hole => new Polygon(hole)).ToList(); TangentVisibilityGraphCalculator.AddTangentVisibilityEdgesToGraph(polygons, visibilityGraph); return visibilityGraph; } static internal VisibilityGraph CalculateGraphOfBoundaries(List<Polyline> holes) { var graphOfHoleBoundaries = new VisibilityGraph(); foreach (Polyline polyline in holes) graphOfHoleBoundaries.AddHole(polyline); return graphOfHoleBoundaries; } internal void AddHole(Polyline polyline) { var p = polyline.StartPoint; while (p != polyline.EndPoint) { AddEdge(p, p.Next); p = p.Next; } AddEdge(polyline.EndPoint, polyline.StartPoint); } internal static IEnumerable<Polyline> OrientHolesClockwise(IEnumerable<Polyline> holes) { #if TEST_MSAGL || VERIFY CheckThatPolylinesAreConvex(holes); #endif // TEST || VERIFY foreach (Polyline poly in holes) { for (PolylinePoint p = poly.StartPoint;; p = p.Next) { // Find the first non-collinear segments and see which direction the triangle is. // If it's consistent with Clockwise, then return the polyline, else return its Reverse. var orientation = Point.GetTriangleOrientation(p.Point, p.Next.Point,p.Next.Next.Point); if (orientation != TriangleOrientation.Collinear) { yield return orientation == TriangleOrientation.Clockwise ? poly : (Polyline)poly.Reverse(); break; } } } } #if TEST_MSAGL || VERIFY internal static void CheckThatPolylinesAreConvex(IEnumerable<Polyline> holes) { foreach (var polyline in holes) CheckThatPolylineIsConvex(polyline); } [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] internal static void CheckThatPolylineIsConvex(Polyline polyline) { Debug.Assert(polyline.Closed, "Polyline is not closed"); PolylinePoint a = polyline.StartPoint; PolylinePoint b = a.Next; PolylinePoint c = b.Next; TriangleOrientation orient = Point.GetTriangleOrientation(a.Point, b.Point, c.Point); while (c != polyline.EndPoint) { a = a.Next; b = b.Next; c = c.Next; var currentOrient = Point.GetTriangleOrientation(a.Point, b.Point, c.Point); if (currentOrient == TriangleOrientation.Collinear) continue; if (orient == TriangleOrientation.Collinear) orient = currentOrient; else if (orient != currentOrient) throw new InvalidOperationException(); } var o = Point.GetTriangleOrientation(polyline.EndPoint.Point, polyline.StartPoint.Point, polyline.StartPoint.Next.Point); if (o != TriangleOrientation.Collinear && o != orient) throw new InvalidOperationException(); } #endif // TEST || VERIFY /// <summary> /// Enumerate all VisibilityEdges in the VisibilityGraph. /// </summary> public IEnumerable<VisibilityEdge> Edges { get { return PointToVertexMap.Values.SelectMany(vertex => vertex.OutEdges); } } internal Dictionary<Point, VisibilityVertex> PointToVertexMap { get { return pointToVertexMap; } } internal int VertexCount { get { return PointToVertexMap.Count; } } internal VisibilityVertex AddVertex(PolylinePoint polylinePoint) { return AddVertex(polylinePoint.Point); } internal VisibilityVertex AddVertex(Point point) { #if SHARPKIT //https://code.google.com/p/sharpkit/issues/detail?id=370 //SharpKit/Colin - http://code.google.com/p/sharpkit/issues/detail?id=277 VisibilityVertex currentVertex; if (PointToVertexMap.TryGetValue(point, out currentVertex)) return currentVertex; var newVertex = VertexFactory(point); PointToVertexMap[point] = newVertex; return newVertex; #else VisibilityVertex vertex; return !PointToVertexMap.TryGetValue(point, out vertex) ? (PointToVertexMap[point] = VertexFactory(point)) : vertex; #endif } internal void AddVertex(VisibilityVertex vertex) { Debug.Assert(!PointToVertexMap.ContainsKey(vertex.Point), "A vertex already exists at this location"); PointToVertexMap[vertex.Point] = vertex; } internal bool ContainsVertex(Point point) { return PointToVertexMap.ContainsKey(point); } static internal VisibilityEdge AddEdge(VisibilityVertex source, VisibilityVertex target) { VisibilityEdge visEdge; if(source.TryGetEdge(target, out visEdge)) return visEdge; if (source == target) { Debug.Assert(false, "Self-edges are not allowed"); throw new InvalidOperationException("Self-edges are not allowed"); } var edge = new VisibilityEdge(source, target); source.OutEdges.Insert(edge); target.InEdges.Add(edge); return edge; } void AddEdge(PolylinePoint source, PolylinePoint target) { AddEdge(source.Point, target.Point); } static internal void AddEdge(VisibilityEdge edge) { Debug.Assert(edge.Source!=edge.Target); edge.Source.OutEdges.Insert(edge); edge.Target.InEdges.Add(edge); } internal VisibilityEdge AddEdge(Point source, Point target) { VisibilityEdge edge; var sourceV = FindVertex(source); VisibilityVertex targetV = null; if (sourceV != null){ targetV=FindVertex(target); if ( targetV != null && sourceV.TryGetEdge(targetV, out edge)) return edge; } if (sourceV == null) { //then targetV is also null sourceV = AddVertex(source); targetV = AddVertex(target); }else if (targetV == null) targetV = AddVertex(target); edge = new VisibilityEdge(sourceV, targetV); sourceV.OutEdges.Insert(edge); targetV.InEdges.Add(edge); return edge; } /* internal static bool DebugClose(Point target, Point source) { var a = new Point(307, 7); var b = new Point(540.6, 15); return (target - a).Length < 2 && (source - b).Length < 5 || (source - a).Length < 2 && (target - b).Length<5; } */ internal VisibilityEdge AddEdge(Point source, Point target, Func<VisibilityVertex, VisibilityVertex,VisibilityEdge> edgeCreator) { VisibilityEdge edge; var sourceV = FindVertex(source); VisibilityVertex targetV = null; if (sourceV != null) { targetV = FindVertex(target); if ( targetV != null && sourceV.TryGetEdge(targetV, out edge)) return edge; } if (sourceV == null) { //then targetV is also null sourceV = AddVertex(source); targetV = AddVertex(target); } else if (targetV == null) targetV = AddVertex(target); edge = edgeCreator(sourceV, targetV); sourceV.OutEdges.Insert(edge); targetV.InEdges.Add(edge); return edge; } internal VisibilityVertex FindVertex(Point point) { VisibilityVertex v; return PointToVertexMap.TryGetValue(point,out v) ? v : null; } internal VisibilityVertex GetVertex(PolylinePoint polylinePoint) { return FindVertex(polylinePoint.Point); } internal IEnumerable<VisibilityVertex> Vertices() { return PointToVertexMap.Values; } internal void RemoveVertex(VisibilityVertex vertex) { // Debug.Assert(PointToVertexMap.ContainsKey(vertex.Point), "Cannot find vertex in PointToVertexMap"); foreach (var edge in vertex.OutEdges) edge.Target.RemoveInEdge(edge); foreach (var edge in vertex.InEdges) edge.Source.RemoveOutEdge(edge); PointToVertexMap.Remove(vertex.Point); } internal void RemoveEdge(VisibilityVertex v1, VisibilityVertex v2) { VisibilityEdge edge; if (!v1.TryGetEdge(v2, out edge)) return; edge.Source.RemoveOutEdge(edge); edge.Target.RemoveInEdge(edge); } internal void RemoveEdge(Point p1, Point p2) { // the order of p1 and p2 is not important. VisibilityEdge edge = FindEdge(p1, p2); if (edge == null) return; edge.Source.RemoveOutEdge(edge); edge.Target.RemoveInEdge(edge); } static internal VisibilityEdge FindEdge(VisibilityEdge edge) { if(edge.Source.TryGetEdge(edge.Target, out edge)) return edge; return null; } internal VisibilityEdge FindEdge(Point source, Point target) { var sourceV = FindVertex(source); if (sourceV == null) return null; var targetV = FindVertex(target); if (targetV == null) return null; VisibilityEdge edge; if (sourceV.TryGetEdge(targetV, out edge)) return edge; return null; } static internal void RemoveEdge(VisibilityEdge edge) { edge.Source.OutEdges.Remove(edge);//not efficient! edge.Target.InEdges.Remove(edge);//not efficient } public void ClearEdges() { foreach (var visibilityVertex in Vertices()) { visibilityVertex.ClearEdges(); } } } }
// 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.Immutable; using System.Diagnostics; using System.IO; using System.Reflection.Internal; using System.Reflection.Metadata; using System.Threading; namespace System.Reflection.PortableExecutable { /// <summary> /// Portable Executable format reader. /// </summary> /// <remarks> /// The implementation is thread-safe, that is multiple threads can read data from the reader in parallel. /// Disposal of the reader is not thread-safe (see <see cref="Dispose"/>). /// </remarks> public sealed class PEReader : IDisposable { // May be null in the event that the entire image is not // deemed necessary and we have been instructed to read // the image contents without being lazy. private MemoryBlockProvider _peImage; // If we read the data from the image lazily (peImage != null) we defer reading the PE headers. private PEHeaders _lazyPEHeaders; private AbstractMemoryBlock _lazyMetadataBlock; private AbstractMemoryBlock _lazyImageBlock; private AbstractMemoryBlock[] _lazyPESectionBlocks; /// <summary> /// Creates a Portable Executable reader over a PE image stored in memory. /// </summary> /// <param name="peImage">Pointer to the start of the PE image.</param> /// <param name="size">The size of the PE image.</param> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is <see cref="IntPtr.Zero"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is negative.</exception> /// <remarks> /// The memory is owned by the caller and not released on disposal of the <see cref="PEReader"/>. /// The caller is responsible for keeping the memory alive and unmodified throughout the lifetime of the <see cref="PEReader"/>. /// The content of the image is not read during the construction of the <see cref="PEReader"/> /// </remarks> public unsafe PEReader(byte* peImage, int size) { if (peImage == null) { throw new ArgumentNullException(nameof(peImage)); } if (size < 0) { throw new ArgumentOutOfRangeException(nameof(size)); } _peImage = new ExternalMemoryBlockProvider(peImage, size); } /// <summary> /// Creates a Portable Executable reader over a PE image stored in a stream. /// </summary> /// <param name="peStream">PE image stream.</param> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="BadImageFormatException"> /// <see cref="PEStreamOptions.PrefetchMetadata"/> is specified and the PE headers of the image are invalid. /// </exception> /// <remarks> /// Ownership of the stream is transferred to the <see cref="PEReader"/> upon successful validation of constructor arguments. It will be /// disposed by the <see cref="PEReader"/> and the caller must not manipulate it. /// </remarks> public PEReader(Stream peStream) : this(peStream, PEStreamOptions.Default) { } /// <summary> /// Creates a Portable Executable reader over a PE image stored in a stream beginning at its current position and ending at the end of the stream. /// </summary> /// <param name="peStream">PE image stream.</param> /// <param name="options"> /// Options specifying how sections of the PE image are read from the stream. /// /// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/> /// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it. /// /// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data /// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated /// by caller while the <see cref="PEReader"/> is alive and undisposed. /// /// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/> /// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also /// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/> /// after construction. /// </param> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="options"/> has an invalid value.</exception> /// <exception cref="BadImageFormatException"> /// <see cref="PEStreamOptions.PrefetchMetadata"/> is specified and the PE headers of the image are invalid. /// </exception> public PEReader(Stream peStream, PEStreamOptions options) : this(peStream, options, (int?)null) { } /// <summary> /// Creates a Portable Executable reader over a PE image of the given size beginning at the stream's current position. /// </summary> /// <param name="peStream">PE image stream.</param> /// <param name="size">PE image size.</param> /// <param name="options"> /// Options specifying how sections of the PE image are read from the stream. /// /// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/> /// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it. /// /// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data /// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated /// by caller while the <see cref="PEReader"/> is alive and undisposed. /// /// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/> /// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also /// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/> /// after construction. /// </param> /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception> public PEReader(Stream peStream, PEStreamOptions options, int size) : this(peStream, options, (int?)size) { } private unsafe PEReader(Stream peStream, PEStreamOptions options, int? sizeOpt) { if (peStream == null) { throw new ArgumentNullException(nameof(peStream)); } if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream)); } if (!options.IsValid()) { throw new ArgumentOutOfRangeException(nameof(options)); } long start = peStream.Position; int size = PEBinaryReader.GetAndValidateSize(peStream, sizeOpt); bool closeStream = true; try { bool isFileStream = FileStreamReadLightUp.IsFileStream(peStream); if ((options & (PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage)) == 0) { _peImage = new StreamMemoryBlockProvider(peStream, start, size, isFileStream, (options & PEStreamOptions.LeaveOpen) != 0); closeStream = false; } else { // Read in the entire image or metadata blob: if ((options & PEStreamOptions.PrefetchEntireImage) != 0) { var imageBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, 0, (int)Math.Min(peStream.Length, int.MaxValue)); _lazyImageBlock = imageBlock; _peImage = new ExternalMemoryBlockProvider(imageBlock.Pointer, imageBlock.Size); // if the caller asked for metadata initialize the PE headers (calculates metadata offset): if ((options & PEStreamOptions.PrefetchMetadata) != 0) { InitializePEHeaders(); } } else { // The peImage is left null, but the lazyMetadataBlock is initialized up front. _lazyPEHeaders = new PEHeaders(peStream); _lazyMetadataBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, _lazyPEHeaders.MetadataStartOffset, _lazyPEHeaders.MetadataSize); } // We read all we need, the stream is going to be closed. } } finally { if (closeStream && (options & PEStreamOptions.LeaveOpen) == 0) { peStream.Dispose(); } } } /// <summary> /// Creates a Portable Executable reader over a PE image stored in a byte array. /// </summary> /// <param name="peImage">PE image.</param> /// <remarks> /// The content of the image is not read during the construction of the <see cref="PEReader"/> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public PEReader(ImmutableArray<byte> peImage) { if (peImage.IsDefault) { throw new ArgumentNullException(nameof(peImage)); } _peImage = new ByteArrayMemoryProvider(peImage); } /// <summary> /// Disposes all memory allocated by the reader. /// </summary> /// <remarks> /// <see cref="Dispose"/> can be called multiple times (but not in parallel). /// It is not safe to call <see cref="Dispose"/> in parallel with any other operation on the <see cref="PEReader"/> /// or reading from <see cref="PEMemoryBlock"/>s retrieved from the reader. /// </remarks> public void Dispose() { var image = _peImage; if (image != null) { image.Dispose(); _peImage = null; } var imageBlock = _lazyImageBlock; if (imageBlock != null) { imageBlock.Dispose(); _lazyImageBlock = null; } var metadataBlock = _lazyMetadataBlock; if (metadataBlock != null) { metadataBlock.Dispose(); _lazyMetadataBlock = null; } var peSectionBlocks = _lazyPESectionBlocks; if (peSectionBlocks != null) { foreach (var block in peSectionBlocks) { if (block != null) { block.Dispose(); } } _lazyPESectionBlocks = null; } } /// <summary> /// Gets the PE headers. /// </summary> /// <exception cref="BadImageFormatException">The headers contain invalid data.</exception> public PEHeaders PEHeaders { get { if (_lazyPEHeaders == null) { InitializePEHeaders(); } return _lazyPEHeaders; } } private void InitializePEHeaders() { Debug.Assert(_peImage != null); StreamConstraints constraints; Stream stream = _peImage.GetStream(out constraints); PEHeaders headers; if (constraints.GuardOpt != null) { lock (constraints.GuardOpt) { headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize); } } else { headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize); } Interlocked.CompareExchange(ref _lazyPEHeaders, headers, null); } private static PEHeaders ReadPEHeadersNoLock(Stream stream, long imageStartPosition, int imageSize) { Debug.Assert(imageStartPosition >= 0 && imageStartPosition <= stream.Length); stream.Seek(imageStartPosition, SeekOrigin.Begin); return new PEHeaders(stream, imageSize); } /// <summary> /// Returns a view of the entire image as a pointer and length. /// </summary> /// <exception cref="InvalidOperationException">PE image not available.</exception> private AbstractMemoryBlock GetEntireImageBlock() { if (_lazyImageBlock == null) { if (_peImage == null) { throw new InvalidOperationException(SR.PEImageNotAvailable); } var newBlock = _peImage.GetMemoryBlock(); if (Interlocked.CompareExchange(ref _lazyImageBlock, newBlock, null) != null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); } } return _lazyImageBlock; } private AbstractMemoryBlock GetMetadataBlock() { if (!HasMetadata) { throw new InvalidOperationException(SR.PEImageDoesNotHaveMetadata); } if (_lazyMetadataBlock == null) { Debug.Assert(_peImage != null, "We always have metadata if peImage is not available."); var newBlock = _peImage.GetMemoryBlock(PEHeaders.MetadataStartOffset, PEHeaders.MetadataSize); if (Interlocked.CompareExchange(ref _lazyMetadataBlock, newBlock, null) != null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); } } return _lazyMetadataBlock; } private AbstractMemoryBlock GetPESectionBlock(int index) { Debug.Assert(index >= 0 && index < PEHeaders.SectionHeaders.Length); Debug.Assert(_peImage != null); if (_lazyPESectionBlocks == null) { Interlocked.CompareExchange(ref _lazyPESectionBlocks, new AbstractMemoryBlock[PEHeaders.SectionHeaders.Length], null); } var newBlock = _peImage.GetMemoryBlock( PEHeaders.SectionHeaders[index].PointerToRawData, PEHeaders.SectionHeaders[index].SizeOfRawData); if (Interlocked.CompareExchange(ref _lazyPESectionBlocks[index], newBlock, null) != null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); } return _lazyPESectionBlocks[index]; } /// <summary> /// Return true if the reader can access the entire PE image. /// </summary> /// <remarks> /// Returns false if the <see cref="PEReader"/> is constructed from a stream and only part of it is prefetched into memory. /// </remarks> public bool IsEntireImageAvailable { get { return _lazyImageBlock != null || _peImage != null; } } /// <summary> /// Gets a pointer to and size of the PE image if available (<see cref="IsEntireImageAvailable"/>). /// </summary> /// <exception cref="InvalidOperationException">The entire PE image is not available.</exception> public PEMemoryBlock GetEntireImage() { return new PEMemoryBlock(GetEntireImageBlock()); } /// <summary> /// Returns true if the PE image contains CLI metadata. /// </summary> /// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception> public bool HasMetadata { get { return PEHeaders.MetadataSize > 0; } } /// <summary> /// Loads PE section that contains CLI metadata. /// </summary> /// <exception cref="InvalidOperationException">The PE image doesn't contain metadata (<see cref="HasMetadata"/> returns false).</exception> /// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception> public PEMemoryBlock GetMetadata() { return new PEMemoryBlock(GetMetadataBlock()); } /// <summary> /// Loads PE section that contains the specified <paramref name="relativeVirtualAddress"/> into memory /// and returns a memory block that starts at <paramref name="relativeVirtualAddress"/> and ends at the end of the containing section. /// </summary> /// <param name="relativeVirtualAddress">Relative Virtual Address of the data to read.</param> /// <returns> /// An empty block if <paramref name="relativeVirtualAddress"/> doesn't represent a location in any of the PE sections of this PE image. /// </returns> /// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception> public PEMemoryBlock GetSectionData(int relativeVirtualAddress) { var sectionIndex = PEHeaders.GetContainingSectionIndex(relativeVirtualAddress); if (sectionIndex < 0) { return default(PEMemoryBlock); } int relativeOffset = relativeVirtualAddress - PEHeaders.SectionHeaders[sectionIndex].VirtualAddress; int size = PEHeaders.SectionHeaders[sectionIndex].VirtualSize - relativeOffset; AbstractMemoryBlock block; if (_peImage != null) { block = GetPESectionBlock(sectionIndex); } else { block = GetEntireImageBlock(); relativeOffset += PEHeaders.SectionHeaders[sectionIndex].PointerToRawData; } return new PEMemoryBlock(block, relativeOffset); } /// <summary> /// Reads all Debug Directory table entries. /// </summary> /// <exception cref="BadImageFormatException">Bad format of the entry.</exception> public unsafe ImmutableArray<DebugDirectoryEntry> ReadDebugDirectory() { var debugDirectory = PEHeaders.PEHeader.DebugTableDirectory; if (debugDirectory.Size == 0) { return ImmutableArray<DebugDirectoryEntry>.Empty; } int position; if (!PEHeaders.TryGetDirectoryOffset(debugDirectory, out position)) { throw new BadImageFormatException(SR.InvalidDirectoryRVA); } const int entrySize = 0x1c; if (debugDirectory.Size % entrySize != 0) { throw new BadImageFormatException(SR.InvalidDirectorySize); } using (AbstractMemoryBlock block = _peImage.GetMemoryBlock(position, debugDirectory.Size)) { var reader = new BlobReader(block.Pointer, block.Size); int entryCount = debugDirectory.Size / entrySize; var builder = ImmutableArray.CreateBuilder<DebugDirectoryEntry>(entryCount); for (int i = 0; i < entryCount; i++) { // Reserved, must be zero. int characteristics = reader.ReadInt32(); if (characteristics != 0) { throw new BadImageFormatException(SR.InvalidDebugDirectoryEntryCharacteristics); } uint stamp = reader.ReadUInt32(); ushort majorVersion = reader.ReadUInt16(); ushort minorVersion = reader.ReadUInt16(); var type = (DebugDirectoryEntryType)reader.ReadInt32(); int dataSize = reader.ReadInt32(); int dataRva = reader.ReadInt32(); int dataPointer = reader.ReadInt32(); builder.Add(new DebugDirectoryEntry(stamp, majorVersion, minorVersion, type, dataSize, dataRva, dataPointer)); } return builder.MoveToImmutable(); } } /// <summary> /// Reads the data pointed to by the specifed Debug Directory entry and interprets them as CodeView. /// </summary> /// <exception cref="ArgumentException"><paramref name="entry"/> is not a CodeView entry.</exception> /// <exception cref="BadImageFormatException">Bad format of the data.</exception> public unsafe CodeViewDebugDirectoryData ReadCodeViewDebugDirectoryData(DebugDirectoryEntry entry) { if (entry.Type != DebugDirectoryEntryType.CodeView) { throw new ArgumentException(SR.NotCodeViewEntry, nameof(entry)); } using (AbstractMemoryBlock block = _peImage.GetMemoryBlock(entry.DataPointer, entry.DataSize)) { var reader = new BlobReader(block.Pointer, block.Size); if (reader.ReadByte() != (byte)'R' || reader.ReadByte() != (byte)'S' || reader.ReadByte() != (byte)'D' || reader.ReadByte() != (byte)'S') { throw new BadImageFormatException(SR.UnexpectedCodeViewDataSignature); } Guid guid = reader.ReadGuid(); int age = reader.ReadInt32(); string path = reader.ReadUtf8NullTerminated(); // path may be padded with NULs while (reader.RemainingBytes > 0) { if (reader.ReadByte() != 0) { throw new BadImageFormatException(SR.InvalidPathPadding); } } return new CodeViewDebugDirectoryData(guid, age, path); } } } }
// // This file is part of the game Voxalia, created by FreneticXYZ. // This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license. // See README.md or LICENSE.txt for contents of the MIT license. // If these are not available, see https://opensource.org/licenses/MIT // using System; using System.Collections.Generic; using System.Linq; using System.Text; using LiteDB; using Voxalia.Shared; using Voxalia.Shared.Collision; using Voxalia.Shared.Files; namespace Voxalia.ServerGame.WorldSystem { public class ChunkDataManager { public Region TheRegion; LiteDatabase Database; LiteCollection<BsonDocument> DBChunks; LiteDatabase LODsDatabase; LiteCollection<BsonDocument> DBLODs; LiteDatabase EntsDatabase; LiteCollection<BsonDocument> DBEnts; LiteDatabase ImageDatabase; LiteCollection<BsonDocument> DBImages; LiteCollection<BsonDocument> DBMaxes; LiteCollection<BsonDocument> DBImages2; public void Init(Region tregion) { TheRegion = tregion; string dir = "/saves/" + TheRegion.TheWorld.Name + "/"; TheRegion.TheServer.Files.CreateDirectory(dir); dir = TheRegion.TheServer.Files.BaseDirectory + dir; Database = new LiteDatabase("filename=" + dir + "chunks.ldb"); DBChunks = Database.GetCollection<BsonDocument>("chunks"); LODsDatabase = new LiteDatabase("filename=" + dir + "lod_chunks.ldb"); DBLODs = LODsDatabase.GetCollection<BsonDocument>("lodchunks"); EntsDatabase = new LiteDatabase("filename=" + dir + "ents.ldb"); DBEnts = EntsDatabase.GetCollection<BsonDocument>("ents"); ImageDatabase = new LiteDatabase("filename=" + dir + "images.ldb"); DBImages = ImageDatabase.GetCollection<BsonDocument>("images"); DBMaxes = ImageDatabase.GetCollection<BsonDocument>("maxes"); DBImages2 = ImageDatabase.GetCollection<BsonDocument>("images_angle"); } public KeyValuePair<int, int> GetMaxes(int x, int y) { BsonDocument doc; doc = DBMaxes.FindById(GetIDFor(x, y, 0)); if (doc == null) { return new KeyValuePair<int, int>(0, 0); } return new KeyValuePair<int, int>(doc["min"].AsInt32, doc["max"].AsInt32); } public void SetMaxes(int x, int y, int min, int max) { BsonValue id = GetIDFor(x, y, 0); BsonDocument newdoc = new BsonDocument(); Dictionary<string, BsonValue> tbs = newdoc.RawValue; tbs["_id"] = id; tbs["min"] = new BsonValue(min); tbs["max"] = new BsonValue(max); if (!DBMaxes.Update(newdoc)) { DBMaxes.Insert(newdoc); } } public byte[] GetImageAngle(int x, int y, int z) { BsonDocument doc; doc = DBImages2.FindById(GetIDFor(x, y, z)); if (doc == null) { return null; } return doc["image"].AsBinary; } public byte[] GetImage(int x, int y, int z) { BsonDocument doc; doc = DBImages.FindById(GetIDFor(x, y, z)); if (doc == null) { return null; } return doc["image"].AsBinary; } public void WriteImageAngle(int x, int y, int z, byte[] data) { BsonValue id = GetIDFor(x, y, z); BsonDocument newdoc = new BsonDocument(); Dictionary<string, BsonValue> tbs = newdoc.RawValue; tbs["_id"] = id; tbs["image"] = new BsonValue(data); if (!DBImages2.Update(newdoc)) { DBImages2.Insert(newdoc); } } public void WriteImage(int x, int y, int z, byte[] data) { BsonValue id = GetIDFor(x, y, z); BsonDocument newdoc = new BsonDocument(); Dictionary<string, BsonValue> tbs = newdoc.RawValue; tbs["_id"] = id; tbs["image"] = new BsonValue(data); if (!DBImages.Update(newdoc)) { DBImages.Insert(newdoc); } } public void Shutdown() { Database.Dispose(); LODsDatabase.Dispose(); EntsDatabase.Dispose(); ImageDatabase.Dispose(); } public BsonValue GetIDFor(int x, int y, int z) { byte[] array = new byte[12]; Utilities.IntToBytes(x).CopyTo(array, 0); Utilities.IntToBytes(y).CopyTo(array, 4); Utilities.IntToBytes(z).CopyTo(array, 8); return new BsonValue(array); } public byte[] GetLODChunkDetails(int x, int y, int z) { BsonDocument doc; doc = DBLODs.FindById(GetIDFor(x, y, z)); if (doc == null) { return null; } return FileHandler.Uncompress(doc["blocks"].AsBinary); } public void WriteLODChunkDetails(int x, int y, int z, byte[] LOD) { BsonValue id = GetIDFor(x, y, z); BsonDocument newdoc = new BsonDocument(); Dictionary<string, BsonValue> tbs = newdoc.RawValue; tbs["_id"] = id; tbs["blocks"] = new BsonValue(FileHandler.Compress(LOD)); DBLODs.Delete(id); DBLODs.Insert(newdoc); if (!DBLODs.Update(newdoc)) { DBLODs.Insert(newdoc); } } public ChunkDetails GetChunkEntities(int x, int y, int z) { BsonDocument doc; doc = DBEnts.FindById(GetIDFor(x, y, z)); if (doc == null) { return null; } ChunkDetails det = new ChunkDetails(); det.X = x; det.Y = y; det.Z = z; det.Version = doc["version"].AsInt32; det.Blocks = /*FileHandler.UnGZip(*/doc["entities"].AsBinary/*)*/; return det; } public void WriteChunkEntities(ChunkDetails details) { BsonValue id = GetIDFor(details.X, details.Y, details.Z); BsonDocument newdoc = new BsonDocument(); Dictionary<string, BsonValue> tbs = newdoc.RawValue; tbs["_id"] = id; tbs["version"] = new BsonValue(details.Version); tbs["entities"] = new BsonValue(/*FileHandler.GZip(*/details.Blocks/*)*/); if (!DBEnts.Update(newdoc)) { DBEnts.Insert(newdoc); } } public ChunkDetails GetChunkDetails(int x, int y, int z) { BsonDocument doc; doc = DBChunks.FindById(GetIDFor(x, y, z)); if (doc == null) { return null; } ChunkDetails det = new ChunkDetails(); det.X = x; det.Y = y; det.Z = z; det.Version = doc["version"].AsInt32; det.Flags = (ChunkFlags)doc["flags"].AsInt32; det.Blocks = FileHandler.Uncompress(doc["blocks"].AsBinary); det.Reachables = doc["reach"].AsBinary; return det; } public void WriteChunkDetails(ChunkDetails details) { BsonValue id = GetIDFor(details.X, details.Y, details.Z); BsonDocument newdoc = new BsonDocument(); Dictionary<string, BsonValue> tbs = newdoc.RawValue; tbs["_id"] = id; tbs["version"] = new BsonValue(details.Version); tbs["flags"] = new BsonValue((int)details.Flags); tbs["blocks"] = new BsonValue(FileHandler.Compress(details.Blocks)); tbs["reach"] = new BsonValue(details.Reachables); if (!DBChunks.Update(newdoc)) { DBChunks.Insert(newdoc); } } public void ClearChunkDetails(Vector3i details) { BsonValue id = GetIDFor(details.X, details.Y, details.Z); DBChunks.Delete(id); } } }
using System; using System.Globalization; using System.Web; using System.Web.Util; using System.Threading; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Debug = System.Web.Util.Debug; // // Welcome to the CacheManager class, CM for short. CM monitors private bytes for the // worker process. If the Private Bytes limit is about to be exceeded, CM will trim // the cache (as necessary), and induce a GC to prevent the process from recycling. // // A timer thread is used to monitor Private Bytes. The interval is adjusted depending // on the current memory pressure. The maximum interval is every 2 minutes, and the // minimum interval is every 5 seconds. // namespace System.Web.Hosting { internal class CacheManager: IDisposable { const int HIGH_FREQ_INTERVAL_S = 5; const int HIGH_FREQ_INTERVAL_MS = 5 * Msec.ONE_SECOND; const int MEDIUM_FREQ_INTERVAL_S = 30; const int MEDIUM_FREQ_INTERVAL_MS = 30 * Msec.ONE_SECOND; const int LOW_FREQ_INTERVAL_S = 120; const int LOW_FREQ_INTERVAL_MS = 120 * Msec.ONE_SECOND; const int MEGABYTE_SHIFT = 20; const long MEGABYTE = 1L << MEGABYTE_SHIFT; // 1048576 const int SAMPLE_COUNT = 2; const int DELTA_SAMPLE_COUNT = 10; private ApplicationManager _appManager; private long _totalCacheSize; private long _trimDurationTicks; private int _lastTrimPercent = 10; // starts at 10, but changes to fit workload private long _inducedGCMinInterval = TimeSpan.TicksPerSecond * 5; // starts at 5 seconds, but changes to fit workload private DateTime _inducedGCFinishTime = DateTime.MinValue; private long _inducedGCDurationTicks; private int _inducedGCCount; private long _inducedGCPostPrivateBytes; private long _inducedGCPrivateBytesChange; private int _currentPollInterval = MEDIUM_FREQ_INTERVAL_MS; private DateTime _timerSuspendTime = DateTime.MinValue; private int _inPBytesMonitorThread; private Timer _timer; private Object _timerLock = new object(); private long _limit; // the "effective" worker process Private Bytes limit private long _highPressureMark; private long _mediumPressureMark; private long _lowPressureMark; private long[] _deltaSamples; // a history of the increase in private bytes per second private int _idxDeltaSamples; private long _maxDelta; // the maximum expected increase in private bytes per second private long _minMaxDelta; // _maxDelta must always be at least this large private long[] _samples; // a history of the sample values (private bytes for the process) private DateTime[] _sampleTimes; // time at which samples were taken private int _idx; private bool _useGetProcessMemoryInfo; private uint _pid; private bool _disposed; private CacheManager() {} internal CacheManager(ApplicationManager appManager, long privateBytesLimit) { #if PERF SafeNativeMethods.OutputDebugString(String.Format("Creating CacheManager with PrivateBytesLimit = {0:N}\n", privateBytesLimit)); #endif // don't create timer if there's no memory limit if (privateBytesLimit <= 0) { return; } _appManager = appManager; _limit = privateBytesLimit; _pid = (uint) SafeNativeMethods.GetCurrentProcessId(); // the initial expected maximum increase in private bytes is 2MB per second per CPU _minMaxDelta = 2 * MEGABYTE * SystemInfo.GetNumProcessCPUs(); AdjustMaxDeltaAndPressureMarks(_minMaxDelta); _samples = new long[SAMPLE_COUNT]; _sampleTimes = new DateTime[SAMPLE_COUNT]; _useGetProcessMemoryInfo = (VersionInfo.ExeName == "w3wp"); _deltaSamples = new long[DELTA_SAMPLE_COUNT]; // start timer with initial poll interval _timer = new Timer(new TimerCallback(this.PBytesMonitorThread), null, _currentPollInterval, _currentPollInterval); } void Adjust() { // not thread-safe, only invoke from timer callback Debug.Assert(_inPBytesMonitorThread == 1); Debug.Assert(SAMPLE_COUNT == 2); // current sample long s2 = _samples[_idx]; // previous sample long s1 = _samples[_idx ^ 1]; // adjust _maxDelta and pressure marks if (s2 > s1 && s1 > 0) { // current time DateTime d2 = _sampleTimes[_idx]; // previous time DateTime d1 = _sampleTimes[_idx ^ 1]; long numBytes = s2 - s1; long numSeconds = (long)Math.Round(d2.Subtract(d1).TotalSeconds); if (numSeconds > 0) { long delta = numBytes / numSeconds; _deltaSamples[_idxDeltaSamples] = delta; _idxDeltaSamples = (_idxDeltaSamples + 1) % DELTA_SAMPLE_COUNT; // update rate of change in private bytes and pressure marks AdjustMaxDeltaAndPressureMarks(delta); } } lock (_timerLock) { if (_timer == null) { return; } // adjust timer frequency if (s2 > _mediumPressureMark) { if (_currentPollInterval > HIGH_FREQ_INTERVAL_MS) { _currentPollInterval = HIGH_FREQ_INTERVAL_MS; _timer.Change(_currentPollInterval, _currentPollInterval); } } else if (s2 > _lowPressureMark) { if (_currentPollInterval > MEDIUM_FREQ_INTERVAL_MS) { _currentPollInterval = MEDIUM_FREQ_INTERVAL_MS; _timer.Change(_currentPollInterval, _currentPollInterval); } } else { if (_currentPollInterval != LOW_FREQ_INTERVAL_MS) { _currentPollInterval = LOW_FREQ_INTERVAL_MS; _timer.Change(_currentPollInterval, _currentPollInterval); } } } } void AdjustMaxDeltaAndPressureMarks(long delta) { // not thread-safe...only invoke from ctor or timer callback Debug.Assert(_inPBytesMonitorThread == 1 || _timer == null); // The value of _maxDelta is the largest rate of change we've seen, // but it is reduced if the rate is now consistently less than what // it once was. long newMaxDelta = _maxDelta; if (delta > newMaxDelta) { // set maxDelta to the current rate of change newMaxDelta = delta; } else { // if _maxDelta is at least four times larger than every sample rate in the history, // then reduce _maxDelta bool reduce = true; long maxDelta = _maxDelta / 4; foreach (long rate in _deltaSamples) { if (rate > maxDelta) { reduce = false; break; } } if (reduce) { newMaxDelta = maxDelta * 2; } } // ensure that maxDelta is sufficiently large so that the _highPressureMark is sufficiently // far away from the memory limit newMaxDelta = Math.Max(newMaxDelta, _minMaxDelta); // Do we have a new maxDelta? If so, adjust it and pressure marks. if (_maxDelta != newMaxDelta) { // adjust _maxDelta _maxDelta = newMaxDelta; // instead of using _maxDelta, use twice _maxDelta since recycling is // expensive and the real delta fluctuates _highPressureMark = Math.Max(_limit * 9 / 10, _limit - (_maxDelta * 2 * HIGH_FREQ_INTERVAL_S)); _lowPressureMark = Math.Max(_limit * 6 / 10, _limit - (_maxDelta * 2 * LOW_FREQ_INTERVAL_S)); _mediumPressureMark = Math.Max((_highPressureMark + _lowPressureMark) / 2 , _limit - (_maxDelta * 2 * MEDIUM_FREQ_INTERVAL_S)); _mediumPressureMark = Math.Min(_highPressureMark , _mediumPressureMark); #if PERF SafeNativeMethods.OutputDebugString(String.Format("CacheManager.AdjustMaxDeltaAndPressureMarks: _highPressureMark={0:N}, _mediumPressureMark={1:N}, _lowPressureMark={2:N}, _maxDelta={3:N}\n", _highPressureMark, _mediumPressureMark, _lowPressureMark, _maxDelta)); #endif #if DBG Debug.Trace("CacheMemory", "AdjustMaxDeltaAndPressureMarks " + "delta=" + delta + ", _maxDelta=" + _maxDelta + ", _highPressureMark=" + _highPressureMark + ", _mediumPressureMark=" + _mediumPressureMark + ", _lowPressureMark=" + _lowPressureMark); #endif } } [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", Justification="Need to call GC.Collect.")] private void CollectInfrequently(long privateBytes) { // not thread-safe, only invoke from timer callback Debug.Assert(_inPBytesMonitorThread == 1); // The Server GC on x86 can traverse ~200mb per CPU per second, and the maximum heap size // is about 3400mb, so the worst case scenario on x86 would take about 8 seconds to collect // on a dual CPU box. // // The Server GC on x64 can traverse ~300mb per CPU per second, so a 6000 MB heap will take // about 10 seconds to collect on a dual CPU box. The worst case scenario on x64 would make // you want to return your hardware for a refund. long timeSinceInducedGC = DateTime.UtcNow.Subtract(_inducedGCFinishTime).Ticks; bool infrequent = (timeSinceInducedGC > _inducedGCMinInterval); // if we haven't collected recently, or if the trim percent is low (less than 50%), // we need to collect again if (infrequent || _lastTrimPercent < 50) { // if we're inducing GC too frequently, increase the trim percentage, but don't go above 50% if (!infrequent) { _lastTrimPercent = Math.Min(50, _lastTrimPercent + 10); } // if we're inducing GC infrequently, we may want to decrease the trim percentage else if (_lastTrimPercent > 10 && timeSinceInducedGC > 2 * _inducedGCMinInterval) { _lastTrimPercent = Math.Max(10, _lastTrimPercent - 10); } int percent = (_totalCacheSize > 0) ? _lastTrimPercent : 0; long trimmedOrExpired = 0; if (percent > 0) { Stopwatch sw1 = Stopwatch.StartNew(); trimmedOrExpired = _appManager.TrimCaches(percent); sw1.Stop(); _trimDurationTicks = sw1.Elapsed.Ticks; } // if (trimmedOrExpired == 0 || _appManager.ShutdownInProgress) { return; } // collect and record statistics Stopwatch sw2 = Stopwatch.StartNew(); GC.Collect(); sw2.Stop(); _inducedGCCount++; // only used for debugging _inducedGCFinishTime = DateTime.UtcNow; _inducedGCDurationTicks = sw2.Elapsed.Ticks; _inducedGCPostPrivateBytes = NextSample(); _inducedGCPrivateBytesChange = privateBytes - _inducedGCPostPrivateBytes; // target 3.3% Time in GC, but don't induce a GC more than once every 5 seconds // Notes on calculation below: If G is duration of garbage collection and T is duration // between starting the next collection, then G/T is % Time in GC. If we target 3.3%, // then G/T = 3.3% = 33/1000, so T = G * 1000/33. _inducedGCMinInterval = Math.Max(_inducedGCDurationTicks * 1000 / 33, 5 * TimeSpan.TicksPerSecond); // no more frequently than every 60 seconds if change is less than 1% if (_inducedGCPrivateBytesChange * 100 <= privateBytes) { _inducedGCMinInterval = Math.Max(_inducedGCMinInterval, 60 * TimeSpan.TicksPerSecond); } #if DBG Debug.Trace("CacheMemory", "GC.COLLECT STATS " + "TrimCaches(" + percent + ")" + ", trimDurationSeconds=" + (_trimDurationTicks/TimeSpan.TicksPerSecond) + ", trimmedOrExpired=" + trimmedOrExpired + ", #secondsSinceInducedGC=" + (timeSinceInducedGC/TimeSpan.TicksPerSecond) + ", InducedGCCount=" + _inducedGCCount + ", gcDurationSeconds=" + (_inducedGCDurationTicks/TimeSpan.TicksPerSecond) + ", PrePrivateBytes=" + privateBytes + ", PostPrivateBytes=" + _inducedGCPostPrivateBytes + ", PrivateBytesChange=" + _inducedGCPrivateBytesChange + ", gcMinIntervalSeconds=" + (_inducedGCMinInterval/TimeSpan.TicksPerSecond)); #endif #if PERF SafeNativeMethods.OutputDebugString(" ** COLLECT **: " + percent + "%, " + (_trimDurationTicks/TimeSpan.TicksPerSecond) + " seconds" + ", infrequent=" + infrequent + ", removed=" + trimmedOrExpired + ", sinceIGC=" + (timeSinceInducedGC/TimeSpan.TicksPerSecond) + ", IGCCount=" + _inducedGCCount + ", IGCDuration=" + (_inducedGCDurationTicks/TimeSpan.TicksPerSecond) + ", preBytes=" + privateBytes + ", postBytes=" + _inducedGCPostPrivateBytes + ", byteChange=" + _inducedGCPrivateBytesChange + ", IGCMinInterval=" + (_inducedGCMinInterval/TimeSpan.TicksPerSecond) + "\n"); #endif } } internal long GetUpdatedTotalCacheSize(long sizeUpdate) { if (sizeUpdate != 0) { long totalSize = Interlocked.Add(ref _totalCacheSize, sizeUpdate); #if PERF SafeNativeMethods.OutputDebugString("CacheManager.GetUpdatedTotalCacheSize:" + " _totalCacheSize= " + totalSize + ", sizeUpdate=" + sizeUpdate + "\n"); #endif return totalSize; } else { return _totalCacheSize; } } public void Dispose() { _disposed = true; Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // managed and unmanaged resources can be touched/released DisposeTimer(); } else { // the finalizer is calling, so don't touch managed state } } private void DisposeTimer() { lock (_timerLock) { if (_timer != null) { _timer.Dispose(); _timer = null; } } } private void PBytesMonitorThread(object state) { // callbacks are queued and can unleash all at once, so concurrent invocations must be prevented if (Interlocked.Exchange(ref _inPBytesMonitorThread, 1) != 0) return; try { if (_disposed) { return; } #if DBG Debug.Trace("CacheMemory", "\r\n\r\n***BEG** PBytesMonitorThread " + DateTime.Now.ToString("T", CultureInfo.InvariantCulture)); #endif // get another sample long privateBytes = NextSample(); // adjust frequency of timer and pressure marks after the sample is captured Adjust(); if (privateBytes > _highPressureMark) { // induce a GC if necessary CollectInfrequently(privateBytes); } #if DBG Debug.Trace("CacheMemory", "**END** PBytesMonitorThread " + "privateBytes=" + privateBytes + ", _highPressureMark=" + _highPressureMark); #endif } finally { Interlocked.Exchange(ref _inPBytesMonitorThread, 0); } } private long NextSample() { // not thread-safe, only invoke from timer callback Debug.Assert(_inPBytesMonitorThread == 1); // NtQuerySystemInformation is a very expensive call. A new function // exists on XP Pro and later versions of the OS and it performs much // better. The name of that function is GetProcessMemoryInfo. For hosting // scenarios where a larger number of w3wp.exe instances are running, we // want to use the new API (VSWhidbey 417366). long privateBytes; if (_useGetProcessMemoryInfo) { long privatePageCount; UnsafeNativeMethods.GetPrivateBytesIIS6(out privatePageCount, true /*nocache*/); privateBytes = privatePageCount; } else { uint dummy; uint privatePageCount = 0; // this is a very expensive call UnsafeNativeMethods.GetProcessMemoryInformation(_pid, out privatePageCount, out dummy, true /*nocache*/); privateBytes = (long)privatePageCount << MEGABYTE_SHIFT; } // increment the index (it's either 1 or 0) Debug.Assert(SAMPLE_COUNT == 2); _idx = _idx ^ 1; // remember the sample time _sampleTimes[_idx] = DateTime.UtcNow; // remember the sample value _samples[_idx] = privateBytes; #if PERF SafeNativeMethods.OutputDebugString(String.Format("CacheManager.NextSample: privateBytes={0:N}, _highPresureMark={1:N}\n", privateBytes, _highPressureMark)); #endif return privateBytes; } } }
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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.IO; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// <summary>Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> [SecurityCritical] public static IEnumerable<string> EnumerateDirectories(string path) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath); } /// <summary>Returns an enumerable collection of directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> [SecurityCritical] public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, searchPattern, null, null, null, PathFormat.RelativePath); } /// <summary>Returns an enumerable collection of directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="searchOption"> /// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/> /// should include only the current directory or should include all subdirectories. /// </param> [SecurityCritical] public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, searchPattern, searchOption, null, null, PathFormat.RelativePath); } #endregion // .NET /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateDirectories(string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, Path.WildcardStarMatchAll, null, null, null, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, searchPattern, null, null, null, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="searchOption"> /// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/> /// should include only the current directory or should include all subdirectories. /// </param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, searchPattern, searchOption, null, null, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> [SecurityCritical] public static IEnumerable<string> EnumerateDirectories(string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateDirectories(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, Path.WildcardStarMatchAll, null, options, null, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, searchPattern, null, options, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, searchPattern, null, options, null, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="filters">The specification of custom filters to be used in the process.</param> [SecurityCritical] public static IEnumerable<string> EnumerateDirectories(string path, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="filters">The specification of custom filters to be used in the process.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateDirectories(string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="filters">The specification of custom filters to be used in the process.</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, searchPattern, null, null, filters, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="filters">The specification of custom filters to be used in the process.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, searchPattern, null, null, filters, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="filters">The specification of custom filters to be used in the process.</param> [SecurityCritical] public static IEnumerable<string> EnumerateDirectories(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="filters">The specification of custom filters to be used in the process.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateDirectories(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="filters">The specification of custom filters to be used in the process.</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, searchPattern, null, options, filters, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="filters">The specification of custom filters to be used in the process.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(true, null, path, searchPattern, null, options, filters, pathFormat); } } }
// 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.Data.SqlTypes; using System.Globalization; using System.Text; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class SqlTypeTest { private static readonly string[] s_sampleString = new string[] { "In", "its", "first", "month", "on", "the", "market,", "Microsoft\u2019s", "new", "search", "engine", "Bing", "Yahoo\u2019s", "Wednesday", "from", "tracker", "comScore", "8.4% of queries", "Earlier, Microsoft said that unique visitors to Bing", "rose 8% in June compared to the previous month. ", "The company also touted the search engine\u2019s success with advertisers, saying electronics", "retailer TigerDirect increased its marketing spend on", "Bing \u201Cby twofold.\u201D", "\u3072\u3089\u304C\u306A", "\u304B\u305F\u304B\u306A", "\u30AB\u30BF\u30AB\u30CA", "\uFF2C\uFF4F\uFF52\uFF45\uFF4D\u3000\uFF49\uFF50\uFF53\uFF55\uFF4D\u3000\uFF44\uFF4F\uFF4C\uFF4F\uFF52\u3000\uFF53\uFF49\uFF54\u3000\uFF41\uFF4D\uFF45\uFF54", "\uFF8C\uFF67\uFF7D\uFF9E\uFF65\uFF77\uFF9E\uFF80\uFF70", "\u30D5\u30A1\u30BA\u30FB\u30AE\u30BF\u30FC", "eNGine", new string(new char[] {'I', 'n', '\uD800', '\uDC00', 'z'}), // surrogate pair new string(new char[] {'\uD800', '\uDC00', '\uD800', '\uDCCC', '\uDBFF', '\uDFCC', '\uDBFF', '\uDFFF'}) // surrogate pairs }; private static readonly string[,] s_specialMatchingString = new string[4, 2] {{"Lorem ipsum dolor sit amet", "\uFF2C\uFF4F\uFF52\uFF45\uFF4D\u3000\uFF49\uFF50\uFF53\uFF55\uFF4D\u3000\uFF44\uFF4F\uFF4C\uFF4F\uFF52\u3000\uFF53\uFF49\uFF54\u3000\uFF41\uFF4D\uFF45\uFF54"}, {"\u304B\u305F\u304B\u306A", "\u30AB\u30BF\u30AB\u30CA"}, {"\uFF8C\uFF67\uFF7D\uFF9E\uFF65\uFF77\uFF9E\uFF80\uFF70", "\u30D5\u30A1\u30BA\u30FB\u30AE\u30BF\u30FC"}, {"engine", "eNGine"}}; private static readonly SqlCompareOptions s_defaultCompareOption = SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth; private static readonly SqlCompareOptions[] s_compareOptions = new SqlCompareOptions[] { SqlCompareOptions.None, SqlCompareOptions.BinarySort, SqlCompareOptions.BinarySort2, s_defaultCompareOption}; private static readonly int s_sampleStringCount = s_sampleString.Length - 1; private static readonly UnicodeEncoding s_unicodeEncoding = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true); private static CultureInfo[] s_cultureInfo = { new CultureInfo("ar-SA"), // Arabic - Saudi Arabia new CultureInfo("ja-JP"), // Japanese - Japan new CultureInfo("de-DE"), // German - Germany new CultureInfo("hi-IN"), // Hindi - India new CultureInfo("tr-TR"), // Turkish - Turkey new CultureInfo("th-TH"), // Thai - Thailand new CultureInfo("el-GR"), // Greek - Greece new CultureInfo("ru-RU"), // Russian - Russia new CultureInfo("he-IL"), // Hebrew - Israel new CultureInfo("cs-CZ"), // Czech - Czech Republic new CultureInfo("fr-CH"), // French - Switzerland new CultureInfo("en-US") // English - United States }; private static int[] s_cultureLocaleIDs = { 0x0401, // Arabic - Saudi Arabia 0x0411, // Japanese - Japan 0x0407, // German - Germany 0x0439, // Hindi - India 0x041f, // Turkish - Turkey 0x041e, // Thai - Thailand 0x0408, // Greek - Greece 0x0419, // Russian - Russia 0x040d, // Hebrew - Israel 0x0405, // Czech - Czech Republic 0x100c, // French - Switzerland 0x0409 // English - United States }; [CheckConnStrSetupFact] public static void SqlStringValidComparisonTest() { for (int j = 0; j < s_cultureInfo.Length; ++j) { SqlStringDefaultCompareOptionTest(s_cultureLocaleIDs[j]); for (int i = 0; i < s_compareOptions.Length; ++i) { SqlStringCompareTest(200, s_compareOptions[i], s_cultureInfo[j], s_cultureLocaleIDs[j]); } } } [CheckConnStrSetupFact] public static void SqlStringNullComparisonTest() { SqlString nullSqlString = new SqlString(null); SqlString nonNullSqlString = new SqlString("abc "); Assert.True( (bool)(nullSqlString < nonNullSqlString || nonNullSqlString >= nullSqlString || nullSqlString.CompareTo(nonNullSqlString) < 0 || nonNullSqlString.CompareTo(nullSqlString) >= 0), "FAILED: (SqlString Null Comparison): Null SqlString not equal to null"); Assert.True((nullSqlString == null && nullSqlString.CompareTo(null) == 0).IsNull, "FAILED: (SqlString Null Comparison): Null SqlString not equal to null"); } // Special characters matching test for default option (SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth) private static void SqlStringDefaultCompareOptionTest(int localeID) { SqlString str1; SqlString str2; for (int i = 0; i < s_specialMatchingString.GetLength(0); ++i) { // SqlString(string) creates instance with the default comparison options str1 = new SqlString(s_specialMatchingString[i, 0], localeID); str2 = new SqlString(s_specialMatchingString[i, 1], localeID); // Per default option, each set contains two string which should be matched as equal per default option Assert.True((bool)(str1 == str2), string.Format("Error (Default Comparison Option with Operator): {0} and {1} should be equal", s_specialMatchingString[i, 0], s_specialMatchingString[i, 1])); Assert.True(str1.CompareTo(str2) == 0, string.Format("FAILED: (Default Comparison Option with CompareTo): {0} and {1} should be equal", s_specialMatchingString[i, 0], s_specialMatchingString[i, 1])); } } private static void SqlStringCompareTest(int numberOfItems, SqlCompareOptions compareOption, CultureInfo cInfo, int localeID) { SortedList<SqlString, SqlString> items = CreateSortedSqlStringList(numberOfItems, compareOption, cInfo, localeID); VerifySortedSqlStringList(items, compareOption, cInfo); } private static SortedList<SqlString, SqlString> CreateSortedSqlStringList(int numberOfItems, SqlCompareOptions compareOption, CultureInfo cInfo, int localeID) { SortedList<SqlString, SqlString> items = new SortedList<SqlString, SqlString>(numberOfItems); // // Generate list of SqlString // Random rand = new Random(500); int numberOfWords; StringBuilder builder = new StringBuilder(); SqlString word; for (int i = 0; i < numberOfItems; ++i) { do { builder.Clear(); numberOfWords = rand.Next(10) + 1; for (int j = 0; j < numberOfWords; ++j) { builder.Append(s_sampleString[rand.Next(s_sampleStringCount)]); builder.Append(" "); } if (numberOfWords % 2 == 1) { for (int k = 0; k < rand.Next(100); ++k) { builder.Append(' '); } } word = new SqlString(builder.ToString(), localeID, compareOption); } while (items.ContainsKey(word)); items.Add(word, word); } return items; } private static void VerifySortedSqlStringList(SortedList<SqlString, SqlString> items, SqlCompareOptions compareOption, CultureInfo cInfo) { // // Verify the list is in order // IList<SqlString> keyList = items.Keys; for (int i = 0; i < items.Count - 1; ++i) { SqlString currentString = keyList[i]; SqlString nextString = keyList[i + 1]; Assert.True((bool)((currentString < nextString) && (nextString >= currentString)), "FAILED: (SqlString Operator Comparison): SqlStrings are out of order"); Assert.True((currentString.CompareTo(nextString) < 0) && (nextString.CompareTo(currentString) > 0), "FAILED: (SqlString.CompareTo): SqlStrings are out of order"); switch (compareOption) { case SqlCompareOptions.BinarySort: Assert.True(CompareBinary(currentString.Value, nextString.Value) < 0, "FAILED: (SqlString BinarySort Comparison): SqlStrings are out of order"); break; case SqlCompareOptions.BinarySort2: Assert.True(string.CompareOrdinal(currentString.Value.TrimEnd(), nextString.Value.TrimEnd()) < 0, "FAILED: (SqlString BinarySort2 Comparison): SqlStrings are out of order"); break; default: CompareInfo cmpInfo = cInfo.CompareInfo; CompareOptions cmpOptions = SqlString.CompareOptionsFromSqlCompareOptions(nextString.SqlCompareOptions); Assert.True(cmpInfo.Compare(currentString.Value.TrimEnd(), nextString.Value.TrimEnd(), cmpOptions) < 0, "FAILED: (SqlString Comparison): SqlStrings are out of order"); break; } } } // Wide-character string comparison for Binary Unicode Collation (for SqlCompareOptions.BinarySort) // Return values: // -1 : wstr1 < wstr2 // 0 : wstr1 = wstr2 // 1 : wstr1 > wstr2 // // Does a memory comparison. // NOTE: This comparison algorithm is different from BinraySory2. The algorithm is copied fro SqlString implementation private static int CompareBinary(string x, string y) { byte[] rgDataX = s_unicodeEncoding.GetBytes(x); byte[] rgDataY = s_unicodeEncoding.GetBytes(y); int cbX = rgDataX.Length; int cbY = rgDataY.Length; int cbMin = cbX < cbY ? cbX : cbY; int i; for (i = 0; i < cbMin; i++) { if (rgDataX[i] < rgDataY[i]) return -1; else if (rgDataX[i] > rgDataY[i]) return 1; } i = cbMin; int iCh; int iSpace = (int)' '; if (cbX < cbY) { for (; i < cbY; i += 2) { iCh = ((int)rgDataY[i + 1]) << 8 + rgDataY[i]; if (iCh != iSpace) return (iSpace > iCh) ? 1 : -1; } } else { for (; i < cbX; i += 2) { iCh = ((int)rgDataX[i + 1]) << 8 + rgDataX[i]; if (iCh != iSpace) return (iCh > iSpace) ? 1 : -1; } } return 0; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { [TestFixture] public class ProxyTest { [Test] public void NotInitializedProxy() { Proxy proxy = new Proxy(); Assert.That(proxy.Kind, Is.EqualTo(ProxyKind.Unspecified)); Assert.That(proxy.FtpProxy, Is.Null); Assert.That(proxy.HttpProxy, Is.Null); Assert.That(proxy.SslProxy, Is.Null); Assert.That(proxy.SocksProxy, Is.Null); Assert.That(proxy.SocksVersion, Is.Null); Assert.That(proxy.SocksUserName, Is.Null); Assert.That(proxy.SocksPassword, Is.Null); Assert.That(proxy.ProxyAutoConfigUrl, Is.Null); Assert.That(proxy.BypassProxyAddresses, Is.Null); Assert.That(proxy.IsAutoDetect, Is.False); } [Test] public void CanNotChangeAlreadyInitializedProxyType() { Proxy proxy = new Proxy(); proxy.Kind = ProxyKind.Direct; Assert.That(() => proxy.IsAutoDetect = true, Throws.InvalidOperationException); Assert.That(() => proxy.SocksPassword = "", Throws.InvalidOperationException); Assert.That(() => proxy.SocksUserName = "", Throws.InvalidOperationException); Assert.That(() => proxy.SocksProxy = "", Throws.InvalidOperationException); Assert.That(() => proxy.SocksVersion = 5, Throws.InvalidOperationException); Assert.That(() => proxy.FtpProxy = "", Throws.InvalidOperationException); Assert.That(() => proxy.HttpProxy = "", Throws.InvalidOperationException); Assert.That(() => proxy.SslProxy = "", Throws.InvalidOperationException); Assert.That(() => proxy.ProxyAutoConfigUrl = "", Throws.InvalidOperationException); Assert.That(() => proxy.AddBypassAddress("localhost"), Throws.InvalidOperationException); Assert.That(() => proxy.AddBypassAddresses("", ""), Throws.InvalidOperationException); Assert.That(() => proxy.Kind = ProxyKind.System, Throws.InvalidOperationException); Proxy proxy2 = new Proxy(); proxy2.Kind = ProxyKind.AutoDetect; Assert.That(() => proxy2.Kind = ProxyKind.System, Throws.InvalidOperationException); } [Test] public void ManualProxy() { Proxy proxy = new Proxy(); proxy.HttpProxy = "http.proxy:1234"; proxy.FtpProxy = "ftp.proxy"; proxy.SslProxy = "ssl.proxy"; proxy.AddBypassAddresses("localhost", "127.0.0.*"); proxy.SocksProxy = "socks.proxy:65555"; proxy.SocksVersion = 5; proxy.SocksUserName = "test1"; proxy.SocksPassword = "test2"; Assert.That(proxy.Kind, Is.EqualTo(ProxyKind.Manual)); Assert.That(proxy.FtpProxy, Is.EqualTo("ftp.proxy")); Assert.That(proxy.HttpProxy, Is.EqualTo("http.proxy:1234")); Assert.That(proxy.SslProxy, Is.EqualTo("ssl.proxy")); Assert.That(proxy.SocksProxy, Is.EqualTo("socks.proxy:65555")); Assert.That(proxy.SocksVersion, Is.EqualTo(5)); Assert.That(proxy.SocksUserName, Is.EqualTo("test1")); Assert.That(proxy.SocksPassword, Is.EqualTo("test2")); Assert.That(proxy.BypassProxyAddresses, Is.EquivalentTo(new List<string>() { "localhost", "127.0.0.*" })); Assert.That(proxy.ProxyAutoConfigUrl, Is.Null); Assert.That(proxy.IsAutoDetect, Is.False); } [Test] public void PACProxy() { Proxy proxy = new Proxy(); proxy.ProxyAutoConfigUrl = "http://aaa/bbb.pac"; Assert.That(proxy.Kind, Is.EqualTo(ProxyKind.ProxyAutoConfigure)); Assert.That(proxy.ProxyAutoConfigUrl, Is.EqualTo("http://aaa/bbb.pac")); Assert.That(proxy.FtpProxy, Is.Null); Assert.That(proxy.HttpProxy, Is.Null); Assert.That(proxy.SslProxy, Is.Null); Assert.That(proxy.SocksProxy, Is.Null); Assert.That(proxy.SocksVersion, Is.Null); Assert.That(proxy.SocksUserName, Is.Null); Assert.That(proxy.SocksPassword, Is.Null); Assert.That(proxy.BypassProxyAddresses, Is.Null); Assert.That(proxy.IsAutoDetect, Is.False); } [Test] public void AutoDetectProxy() { Proxy proxy = new Proxy(); proxy.IsAutoDetect = true; Assert.That(proxy.Kind, Is.EqualTo(ProxyKind.AutoDetect)); Assert.That(proxy.IsAutoDetect, Is.True); Assert.That(proxy.FtpProxy, Is.Null); Assert.That(proxy.HttpProxy, Is.Null); Assert.That(proxy.SslProxy, Is.Null); Assert.That(proxy.SocksProxy, Is.Null); Assert.That(proxy.SocksVersion, Is.Null); Assert.That(proxy.SocksUserName, Is.Null); Assert.That(proxy.SocksPassword, Is.Null); Assert.That(proxy.BypassProxyAddresses, Is.Null); Assert.That(proxy.ProxyAutoConfigUrl, Is.Null); } [Test] public void ManualProxyFromDictionary() { Dictionary<string, object> proxyData = new Dictionary<string, object>(); proxyData.Add("proxyType", "manual"); proxyData.Add("httpProxy", "http.proxy:1234"); proxyData.Add("ftpProxy", "ftp.proxy"); proxyData.Add("sslProxy", "ssl.proxy"); proxyData.Add("noProxy", "localhost;127.0.0.*"); proxyData.Add("socksProxy", "socks.proxy:65555"); proxyData.Add("socksVersion", 5); proxyData.Add("socksUsername", "test1"); proxyData.Add("socksPassword", "test2"); Proxy proxy = new Proxy(proxyData); Assert.That(proxy.Kind, Is.EqualTo(ProxyKind.Manual)); Assert.That(proxy.FtpProxy, Is.EqualTo("ftp.proxy")); Assert.That(proxy.HttpProxy, Is.EqualTo("http.proxy:1234")); Assert.That(proxy.SslProxy, Is.EqualTo("ssl.proxy")); Assert.That(proxy.SocksProxy, Is.EqualTo("socks.proxy:65555")); Assert.That(proxy.SocksVersion, Is.EqualTo(5)); Assert.That(proxy.SocksUserName, Is.EqualTo("test1")); Assert.That(proxy.SocksPassword, Is.EqualTo("test2")); Assert.That(proxy.BypassProxyAddresses, Is.EquivalentTo(new List<string>() { "localhost", "127.0.0.*" })); Assert.That(proxy.ProxyAutoConfigUrl, Is.Null); Assert.That(proxy.IsAutoDetect, Is.False); } [Test] public void LongSocksVersionFromDictionary() { Dictionary<string, object> proxyData = new Dictionary<string, object>(); long longValue = 5; proxyData.Add("proxyType", "manual"); proxyData.Add("httpProxy", "http.proxy:1234"); proxyData.Add("ftpProxy", "ftp.proxy"); proxyData.Add("sslProxy", "ssl.proxy"); proxyData.Add("noProxy", "localhost,127.0.0.*"); proxyData.Add("socksProxy", "socks.proxy:65555"); proxyData.Add("socksVersion", longValue); proxyData.Add("socksUsername", "test1"); proxyData.Add("socksPassword", "test2"); Proxy proxy = new Proxy(proxyData); int intValue = 5; Assert.That(proxy.SocksVersion, Is.EqualTo(intValue)); } [Test] public void ManualProxyToJson() { Proxy proxy = new Proxy(); proxy.Kind = ProxyKind.Manual; proxy.HttpProxy = "http.proxy:1234"; proxy.FtpProxy = "ftp.proxy"; proxy.SslProxy = "ssl.proxy"; proxy.AddBypassAddresses("localhost", "127.0.0.*"); proxy.SocksProxy = "socks.proxy:65555"; proxy.SocksVersion = 5; proxy.SocksUserName = "test1"; proxy.SocksPassword = "test2"; string jsonValue = JsonConvert.SerializeObject(proxy); JObject json = JObject.Parse(jsonValue); Assert.That(json.ContainsKey("proxyType"), Is.True); Assert.That(json["proxyType"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["proxyType"].Value<string>(), Is.EqualTo("manual")); Assert.That(json.ContainsKey("ftpProxy"), Is.True); Assert.That(json["ftpProxy"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["ftpProxy"].Value<string>(), Is.EqualTo("ftp.proxy")); Assert.That(json.ContainsKey("httpProxy"), Is.True); Assert.That(json["httpProxy"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["httpProxy"].Value<string>(), Is.EqualTo("http.proxy:1234")); Assert.That(json.ContainsKey("sslProxy"), Is.True); Assert.That(json["sslProxy"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["sslProxy"].Value<string>(), Is.EqualTo("ssl.proxy")); Assert.That(json.ContainsKey("socksProxy"), Is.True); Assert.That(json["socksProxy"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["socksProxy"].Value<string>(), Is.EqualTo("socks.proxy:65555")); Assert.That(json.ContainsKey("socksVersion"), Is.True); Assert.That(json["socksVersion"].Type, Is.EqualTo(JTokenType.Integer)); Assert.That(json["socksVersion"].Value<int>(), Is.EqualTo(5)); Assert.That(json.ContainsKey("socksUsername"), Is.True); Assert.That(json["socksUsername"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["socksUsername"].Value<string>(), Is.EqualTo("test1")); Assert.That(json.ContainsKey("socksPassword"), Is.True); Assert.That(json["socksPassword"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["socksPassword"].Value<string>(), Is.EqualTo("test2")); Assert.That(json.ContainsKey("noProxy"), Is.True); Assert.That(json["noProxy"].Type, Is.EqualTo(JTokenType.Array)); Assert.That(json["noProxy"].ToObject<string[]>(), Is.EqualTo(new string[] { "localhost", "127.0.0.*" })); Assert.That(json.Count, Is.EqualTo(9)); } [Test] public void PacProxyFromDictionary() { Dictionary<string, object> proxyData = new Dictionary<string, object>(); proxyData.Add("proxyType", "pac"); proxyData.Add("proxyAutoconfigUrl", "http://aaa/bbb.pac"); Proxy proxy = new Proxy(proxyData); Assert.That(proxy.Kind, Is.EqualTo(ProxyKind.ProxyAutoConfigure)); Assert.That(proxy.ProxyAutoConfigUrl, Is.EqualTo("http://aaa/bbb.pac")); Assert.That(proxy.FtpProxy, Is.Null); Assert.That(proxy.HttpProxy, Is.Null); Assert.That(proxy.SslProxy, Is.Null); Assert.That(proxy.SocksProxy, Is.Null); Assert.That(proxy.SocksVersion, Is.Null); Assert.That(proxy.SocksUserName, Is.Null); Assert.That(proxy.SocksPassword, Is.Null); Assert.That(proxy.BypassProxyAddresses, Is.Null); Assert.That(proxy.IsAutoDetect, Is.False); } [Test] public void PacProxyToJson() { Proxy proxy = new Proxy(); proxy.Kind = ProxyKind.ProxyAutoConfigure; proxy.ProxyAutoConfigUrl = "http://aaa/bbb.pac"; string jsonValue = JsonConvert.SerializeObject(proxy); JObject json = JObject.Parse(jsonValue); Assert.That(json.ContainsKey("proxyType"), Is.True); Assert.That(json["proxyType"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["proxyType"].Value<string>(), Is.EqualTo("pac")); Assert.That(json.ContainsKey("proxyAutoconfigUrl"), Is.True); Assert.That(json["proxyAutoconfigUrl"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["proxyAutoconfigUrl"].Value<string>(), Is.EqualTo("http://aaa/bbb.pac")); Assert.That(json.Count, Is.EqualTo(2)); } [Test] public void AutoDetectProxyFromDictionary() { Dictionary<string, object> proxyData = new Dictionary<string, object>(); proxyData.Add("proxyType", "autodetect"); proxyData.Add("autodetect", true); Proxy proxy = new Proxy(proxyData); Assert.That(proxy.Kind, Is.EqualTo(ProxyKind.AutoDetect)); Assert.That(proxy.IsAutoDetect, Is.True); Assert.That(proxy.FtpProxy, Is.Null); Assert.That(proxy.HttpProxy, Is.Null); Assert.That(proxy.SslProxy, Is.Null); Assert.That(proxy.SocksProxy, Is.Null); Assert.That(proxy.SocksVersion, Is.Null); Assert.That(proxy.SocksUserName, Is.Null); Assert.That(proxy.SocksPassword, Is.Null); Assert.That(proxy.BypassProxyAddresses, Is.Null); Assert.That(proxy.ProxyAutoConfigUrl, Is.Null); } [Test] public void AutoDetectProxyToJson() { Proxy proxy = new Proxy(); proxy.Kind = ProxyKind.AutoDetect; proxy.IsAutoDetect = true; string jsonValue = JsonConvert.SerializeObject(proxy); JObject json = JObject.Parse(jsonValue); Assert.That(json.ContainsKey("proxyType"), Is.True); Assert.That(json["proxyType"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["proxyType"].Value<string>(), Is.EqualTo("autodetect")); Assert.That(json.Count, Is.EqualTo(1)); } [Test] public void SystemProxyFromDictionary() { Dictionary<string, object> proxyData = new Dictionary<string, object>(); proxyData.Add("proxyType", "SYSTEM"); Proxy proxy = new Proxy(proxyData); Assert.That(proxy.Kind, Is.EqualTo(ProxyKind.System)); Assert.That(proxy.FtpProxy, Is.Null); Assert.That(proxy.HttpProxy, Is.Null); Assert.That(proxy.SslProxy, Is.Null); Assert.That(proxy.SocksProxy, Is.Null); Assert.That(proxy.SocksVersion, Is.Null); Assert.That(proxy.SocksUserName, Is.Null); Assert.That(proxy.SocksPassword, Is.Null); Assert.That(proxy.BypassProxyAddresses, Is.Null); Assert.That(proxy.IsAutoDetect, Is.False); Assert.That(proxy.ProxyAutoConfigUrl, Is.Null); } [Test] public void SystemProxyToJson() { Proxy proxy = new Proxy(); proxy.Kind = ProxyKind.System; string jsonValue = JsonConvert.SerializeObject(proxy); JObject json = JObject.Parse(jsonValue); Assert.That(json.ContainsKey("proxyType"), Is.True); Assert.That(json["proxyType"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["proxyType"].Value<string>(), Is.EqualTo("system")); Assert.That(json.Count, Is.EqualTo(1)); } [Test] public void DirectProxyFromDictionary() { Dictionary<string, object> proxyData = new Dictionary<string, object>(); proxyData.Add("proxyType", "direct"); Proxy proxy = new Proxy(proxyData); Assert.That(proxy.Kind, Is.EqualTo(ProxyKind.Direct)); Assert.That(proxy.FtpProxy, Is.Null); Assert.That(proxy.HttpProxy, Is.Null); Assert.That(proxy.SslProxy, Is.Null); Assert.That(proxy.SocksProxy, Is.Null); Assert.That(proxy.SocksVersion, Is.Null); Assert.That(proxy.SocksUserName, Is.Null); Assert.That(proxy.SocksPassword, Is.Null); Assert.That(proxy.BypassProxyAddresses, Is.Null); Assert.That(proxy.IsAutoDetect, Is.False); Assert.That(proxy.ProxyAutoConfigUrl, Is.Null); } [Test] public void DirectProxyToJson() { Proxy proxy = new Proxy(); proxy.Kind = ProxyKind.Direct; string jsonValue = JsonConvert.SerializeObject(proxy); JObject json = JObject.Parse(jsonValue); Assert.That(json.ContainsKey("proxyType"), Is.True); Assert.That(json["proxyType"].Type, Is.EqualTo(JTokenType.String)); Assert.That(json["proxyType"].Value<string>(), Is.EqualTo("direct")); Assert.That(json.Count, Is.EqualTo(1)); } [Test] public void ConstructingWithNullKeysWorksAsExpected() { Dictionary<string, object> rawProxy = new Dictionary<string, object>(); rawProxy.Add("ftpProxy", null); rawProxy.Add("httpProxy", "http://www.example.com"); rawProxy.Add("autodetect", null); Proxy proxy = new Proxy(rawProxy); Assert.That(proxy.FtpProxy, Is.Null); Assert.That(proxy.IsAutoDetect, Is.False); Assert.That(proxy.HttpProxy, Is.EqualTo("http://www.example.com")); } } }
/************************************************** * Class responsible for the establishing of a * network multiplayer game and the loading of * the game scene **************************************************/ #region Using Statements using UnityEngine; using System.Collections.Generic; using System.Threading; using System.Net; using System.Net.Sockets; using System.Text; using System; #endregion /************************************************* * Result of two tutorials * * I am mentioning it here mainly because it is interspersed through out the whole * class and is not used anywhere fully (in a block). But will comment where it is * used explicitly. * *http://cgcookie.com/unity/2011/12/20/introduction-to-networking-in-unity/ *The connecting to the master server and the button layout of hostdata was heavily influenced from the above tutorial. * *http://www.jarloo.com/c-udp-multicasting-tutorial/ *This tutorial was used to get familiar with UDP multicasting * * The threaded approach to UDP listener is my own, taking what Ive learned from the above two tutorials and * merging them so that I can start/discover LAN games and not have to rely on the master server * and internet connectivity. *************************************************/ public class NetworkManagerSplashScreen : MonoBehaviour { #region Class State public GameObject PlayerPrefab, SpawnPointsPrefab; public static List<PlayerInfo> PlayerInfoList; public static List<GameObject> SpawnPoints; public static List<MissileInTheAir> HotMissileList; private float _btnX, _btnY, _btnW, _btnH, _textfieldH, _textfieldW, _textfieldX, _textfieldY, _playerNameLabelX, _playerNameLabelY, _playerNameLabelH, _playerNameLabelW; private const string GameName = "RedSky"; private const string Password = "Openup"; private string _playerName = string.Empty; private List<HostData> _hostdata; private bool _waitForServerResponse, _startServerCalled, _listen, _iamserver, _iamclient; private List<string> _lanHosts; private const int MaxNumOfPlayers = 4; private const int Port = 25001; private Thread _thread; private UdpClient _udpClientBroadcast, _udpClientListen; private IPEndPoint _localIpEp, _remoteIpEp; private IPAddress _multiCastAddress; private const int MultiCastPort = 2225; private const string MulticastAddressAsString = "239.255.40.40"; private string _myIpPrivateAddress; #endregion #region Start method void Start() { _myIpPrivateAddress = Network.player.ipAddress; _lanHosts = new List<string>(); PlayerInfoList = new List<PlayerInfo>(); SpawnPoints = new List<GameObject>(); HotMissileList = new List<MissileInTheAir>(); foreach (Transform child in SpawnPointsPrefab.transform) { SpawnPoints.Add(child.gameObject); } // This game object (the object which this script is attached to) needs to stay alive after a scene change to maintain the network view records DontDestroyOnLoad(this); _playerNameLabelX = Screen.width * 0.05f; _playerNameLabelY = Screen.width * 0.05f; _playerNameLabelH = Screen.width * 0.02f; _playerNameLabelW = Screen.width * 0.1f; _textfieldX = Screen.width * 0.05f; _textfieldY = Screen.width * 0.07f; _textfieldH = Screen.width * 0.03f; _textfieldW = Screen.width * 0.2f; _btnX = Screen.width * 0.05f; _btnY = Screen.width * 0.12f; _btnW = Screen.width * 0.2f; _btnH = Screen.width * 0.05f; // Intialise the multicast properties that will be common to both a (LAN) server and client. _multiCastAddress = IPAddress.Parse(MulticastAddressAsString); _localIpEp = new IPEndPoint(IPAddress.Any, MultiCastPort); _remoteIpEp = new IPEndPoint(_multiCastAddress, MultiCastPort); } #endregion #region On GUI method // Used for displaying GUI items such as buttons, labels, textfields.... void OnGUI() { if (!Network.isClient && !Network.isServer) // Nobody is connected so display the options to the user { // ************************************************************************************************ // The GUI layout here is heaily based on the same in the unity networking tutorial mentioned above // mainly because it works and I felt it wouldnt benefit from changing it // ************************************************************************************************ GUI.Label(new Rect(_playerNameLabelX, _playerNameLabelY, _playerNameLabelW, _playerNameLabelH), "Username *required"); _playerName = GUI.TextField(new Rect(_textfieldX, _textfieldY, _textfieldW, _textfieldH), _playerName); if (GUI.Button(new Rect(_btnX, _btnY, _btnW, _btnH), "Start Server") && _playerName != string.Empty) { Debug.Log("Server started"); StartServer(); } if (GUI.Button(new Rect(_btnX, _btnY * 1.2f + _btnH, _btnW, _btnH), "Refresh Hosts")) { Debug.Log("Refreshing"); if (!Network.isServer) RefreshHostList(); } if (!Application.isWebPlayer) // This is standalone only as webplayer security wont allow multicast { if (GUI.Button(new Rect(_btnX, _btnY * 1.8f + _btnH, _btnW, _btnH), "Start LAN") && _playerName != string.Empty) { StartLANServer(); _iamserver = true; } if (GUI.Button(new Rect(_btnX, _btnY * 2.4f + _btnH, _btnW, _btnH), "Search For LAN game")) { SearchForLANServers(); _iamclient = true; } } // This will display a list of web hosts available if the (WEB) refresh is hit if (_hostdata != null) { var i = 0; foreach (var item in _hostdata) { if (GUI.Button(new Rect((_btnX * 1.5f + _btnW), (_btnY * 1.2f + (_btnH * i)), _btnW * 3f, _btnH), item.gameName) && _playerName != string.Empty) Network.Connect(item, Password); i++; } } // This will display a list of LAN hosts available if the (LAN) refresh is hit if (_lanHosts.Count > 0) { var x = 0; foreach (var item in _lanHosts) { Debug.Log(item); if (GUI.Button(new Rect((_btnX * 1.5f + _btnW), (_btnY * 2f + (_btnH * x)), _btnW * 2f, _btnH), item) && _playerName != string.Empty) { string ipaddress = item.Split('_').GetValue(6).ToString(); Network.Connect(ipaddress, Port, Password); } } } } } #endregion #region Refresh Host List method private void RefreshHostList() { MasterServer.RequestHostList(GameName); _waitForServerResponse = true; } #endregion #region Start Server method private void StartServer() { if (!_startServerCalled) { _startServerCalled = true; bool shouldUseNAT = !Network.HavePublicAddress(); NetworkConnectionError ne = Network.InitializeServer(MaxNumOfPlayers, Port, shouldUseNAT); if (ne == NetworkConnectionError.NoError) { Network.incomingPassword = Password; MasterServer.RegisterHost(GameName, "RedSky Multiplayer Game", "This is a third year project demonstration"); } else { Debug.Log("Failed to initialize Server - Check network connection"); } } } #endregion #region Start LAN Server method private void StartLANServer() { Network.InitializeServer(4, 25001, false); Network.incomingPassword = Password; _listen = true; _thread = new Thread(UDPListen); _thread.Start(); } #endregion #region UDP Listen method void UDPListen() { // *********************************************************************** // UPD multicast is based on the tutorial mentioned at the top of the page // *********************************************************************** _udpClientListen = new UdpClient(); _udpClientListen.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _udpClientListen.ExclusiveAddressUse = false; _udpClientListen.Client.Bind(_localIpEp); _udpClientListen.JoinMulticastGroup(_multiCastAddress); Debug.Log("Listener Started"); while (_listen) { byte[] data = _udpClientListen.Receive(ref _localIpEp); string strData = Encoding.Unicode.GetString(data); if (strData.Equals("game_request") && _iamserver) { Debug.Log(strData); BroadcastMessage(string.Format("RedSky_ServerIP_hosted_by_{0}_at_{1}", _playerName, _myIpPrivateAddress), 10); } if (strData.Contains("RedSky_ServerIP")) { if (!_lanHosts.Contains(strData)) { Debug.Log("Recieved Reply"); _lanHosts.Add(strData); } } Thread.Sleep(10); } } #endregion #region On Application Quit method void OnApplicationQuit() { // It is vital to release the UPDclient or game crashes will ensue if trying to restart the game try { if (_thread != null) { if (_thread.IsAlive) { _listen = false; if (_udpClientListen != null) _udpClientListen.Close(); if (_udpClientBroadcast != null) _udpClientBroadcast.Close(); _thread.Abort(); } } } catch (Exception ex) { Debug.Log(ex.ToString()); } } #endregion #region Search For LAN Servers method private void SearchForLANServers() { _listen = true; if (_thread == null) { _thread = new Thread(UDPListen); _thread.Start(); } if (_iamclient) BroadcastMessage("game_request", 10); } #endregion #region Broadcast Message method private void BroadcastMessage(string msg, int timestosend) { // *********************************************************************** // UPD multicast is based on the tutorial mentioned at the top of the page // *********************************************************************** try { // from referenced UDP multicasting tutorial _udpClientBroadcast = new UdpClient(); _udpClientBroadcast.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _udpClientBroadcast.JoinMulticastGroup(_multiCastAddress); for (int i = 0; i < timestosend; i++) { byte[] buffer = Encoding.Unicode.GetBytes(msg); _udpClientBroadcast.Send(buffer, buffer.Length, _remoteIpEp); } _udpClientBroadcast.Close(); } catch (Exception e) { Debug.Log(e.ToString()); _udpClientBroadcast.Close(); } } #endregion #region On Server Initialized method private void OnServerInitialized() { Debug.Log("Server initialized!"); if (Network.isServer) { LoadScene(); SpawnPlayer(); } } #endregion #region Load Scene method private void LoadScene() { Application.LoadLevel(1); } #endregion #region On Master Server Event method // Checks if the game has been registered with the master server private void OnMasterServerEvent(MasterServerEvent e) { if (e == MasterServerEvent.RegistrationSucceeded) { Debug.Log("Server registered"); Debug.Log("Master Server Info:" + MasterServer.ipAddress + ":" + MasterServer.port); } } #endregion #region Update method // Update is called once per frame void Update() { // from referenced tutorial if (!Network.isServer && _waitForServerResponse) { if (MasterServer.PollHostList().Length > 0) { _waitForServerResponse = false; _hostdata = new List<HostData>(MasterServer.PollHostList()); } } } #endregion #region On Connected To Server method void OnConnectedToServer() { LoadScene(); SpawnPlayer(); } #endregion #region On Failed To Connect void OnFailedToConnect(NetworkConnectionError nce) { Debug.Log("Failed to connect - Check that you have network connectivity and Firewall settings are correct"); } #endregion #region On Failed To Connect To Master Server void OnFailedToConnectToMasterServer(NetworkConnectionError nce) { Debug.Log("Failed to connect to the master server " + nce.ToString()); } #endregion #region On Disconnected From Server method void OnDisconnectedFromServer(NetworkDisconnection info) { // From unity docs if (Network.isServer) Debug.Log("Local server connection disconnected"); else if (info == NetworkDisconnection.LostConnection) Debug.Log("Lost connection to the server"); else Debug.Log("Successfully diconnected from the server"); } #endregion #region On Player Disconnected void OnPlayerDisconnected(NetworkPlayer player) { Debug.Log("Clean up after player " + player); Network.RemoveRPCs(player); Network.DestroyPlayerObjects(player); } #endregion #region Spawn Player method void SpawnPlayer() { // Pick a random spawn point var r = new System.Random(); var ranNum = r.Next(0, SpawnPoints.Count); var go = (GameObject)Network.Instantiate(PlayerPrefab, SpawnPoints[ranNum].transform.position, SpawnPoints[ranNum].transform.rotation, 0); networkView.RPC("AddToPlayerList", RPCMode.AllBuffered, _playerName, go.networkView.viewID); } #endregion #region [RPC] Add To Player List method [RPC] private void AddToPlayerList(string playerName, NetworkViewID viewID) { // Need all games to maintain a list of players NetworkManagerSplashScreen.PlayerInfoList.Add(new PlayerInfo(playerName, viewID)); } #endregion }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using Kodestruct.Common.Mathematics; namespace Kodestruct.Steel.AISC.SteelEntities.Welds { /// <summary> /// Weld element is a small subdivision of weld segment. Weld element can be represented as a point. /// </summary> public class FilletWeldElement: WeldBase, IWeldElement { public Point2D NodeI { get; set; } public Point2D NodeJ { get; set; } public bool IsLoadedOutOfPlane { get; set; } public FilletWeldElement(Point2D StartNode, Point2D EndNode, double Leg, double ElectrodeStrength, bool IsLoadedOutOfPlane =false) :base(Leg,ElectrodeStrength) { this.NodeI = StartNode; this.NodeJ = EndNode; this.IsLoadedOutOfPlane = IsLoadedOutOfPlane; } private double length; public double Length { get { double dx = NodeJ.X - NodeI.X; double dy = NodeJ.Y-NodeI.Y; length = Math.Sqrt(Math.Pow(dx, 2) + Math.Pow(dy, 2)); return length; } } public double GetCentroidDistanceToNode(Point2D IC) { Point2D WeldCentroid = this.Location; return WeldCentroid.GetDistanceToPoint(IC); } public double CalculateNominalShearStrength(double pi, double thetaInput) { double theta = GetAdjustedTheta(thetaInput); double F_EXX = this.WeldElectrodeStrength; double sin_theta = Math.Sin(thetaInput.ToRadians()); double L = this.Length; double E = Math.Sqrt(2.0) / 2.0 * this.LegLength; //AISC formula 8-3 Page 8-10 of the steel manual double Fnwi = 0.60 * F_EXX *E* (1.0 + 0.5 * Math.Pow(sin_theta, 1.5)) * Math.Pow(pi * (1.9 - 0.9 * pi), 0.3)*L; return Fnwi; } private double GetAdjustedTheta(double OriginalTheta) { double theta = OriginalTheta; if (theta > 180) theta = theta % 180; if (theta > 90) theta = 180 - theta; if (theta < 0) theta = -theta; return theta; } /// Point2D location; /// <summary> /// Weld element centroid location. /// </summary> public Point2D Location { get { double x; double y; if (IsLoadedOutOfPlane ==true) { x = 0; } else { x = (NodeJ.X + NodeI.X) / 2.0; } y = (NodeJ.Y + NodeI.Y) / 2.0; if (location == null) { location = new Point2D(x, y); } else { location.X = x; location.Y = y; } return location; } set { location = value; } } public double GetAngleBetweenElementAndProjectionFromPoint(Point2D IC) { //Move system to centroid Point2D c = this.Location; double dx = Location.X; double dy = Location.Y; Vector3 VI = new Vector3(NodeI.X - dx, NodeI.Y - dy,0); Vector3 VIC = new Vector3(IC.X - dx, IC.Y - dy,0); //double Angle= Vector.AngleBetween(VI, VIC); double Angle = Vector3.Angle(VI, VIC); return Angle; } public double GetAngleOfForceResultant(Point2D IC) { double AngleBetweenTheVectorFromICAndElement = this.GetAngleBetweenElementAndProjectionFromPoint(IC); return 90.0 - AngleBetweenTheVectorFromICAndElement; } public double GetLineMomentOfInertiaYAroundPoint(Point2D center) { double m = (this.NodeJ.X - this.NodeI.X); double m2 =Math.Pow(m,2); double l = this.Length; double dx = (this.NodeJ.X + this.NodeI.X) / 2.0 - center.X; double dx2 = Math.Pow(dx, 2); double Iy = l * m2 / 12.0 + l * dx2; //property as line return Iy*this.LegLength; } public double GetLineMomentOfInertiaXAroundPoint(Point2D center) { double n = (this.NodeJ.Y - this.NodeI.Y); double n2 = Math.Pow(n, 2); double l = this.Length; double dy = (this.NodeJ.Y + this.NodeI.Y) / 2.0 - center.Y; double dy2 = Math.Pow(dy, 2); double Iy = l * n2 / 12.0 + l * dy2;//property as line return Iy * this.LegLength; } public double GetLinePolarMomentOfInetriaAroundPoint(Point2D center) { double Ix = this.GetLineMomentOfInertiaXAroundPoint(center); double Iy = this.GetLineMomentOfInertiaYAroundPoint(center); return Ix + Iy; } /// <summary> /// For fillet weld limit deformation is the deformation at fracture /// </summary> public double LimitDeformation { get; set; } /// <summary> /// Ultimate load deformation /// </summary> public double UltimateLoadDeformation { get; set; } public double GetAngleTheta(Point2D Center) { double Dx = Center.X - this.Location.X; double Dy = Center.Y - this.Location.Y; //Define vector from the IC to weld element centroid Vector2d PositionVector = new Vector2d(Dx, Dy); Vector2d ForceVector = new Vector2d(Dy, -Dx); Vector2d ElementLineVector = new Vector2d(this.NodeJ.X - this.NodeI.X, this.NodeJ.Y - this.NodeI.Y); double theta = ForceVector.GetAngle0to90(ElementLineVector); return theta; } public double GetDistanceToPoint(Point2D point) { return Math.Sqrt(Math.Pow(point.X - this.Location.X, 2) + Math.Pow(point.Y - this.Location.Y, 2)); } public double DistanceFromCentroid { get; set; } } }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. namespace UnitTests { using System; using System.IO; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.TestTools.UnitTesting; using NativeClientVSAddIn; /// <summary> /// This is a test class for PropertyManagerTest and is intended /// to contain all PropertyManager Unit Tests /// </summary> [TestClass] public class PropertyManagerTest { /// <summary> /// This holds the path to the NaCl solution used in these tests. /// The NaCl solution is a valid NaCl/pepper plug-in VS solution. /// It is copied into the testing deployment directory and opened in some tests. /// Because unit-tests run in any order, the solution should not be written to /// in any tests. /// </summary> private static string naclSolution; /// <summary> /// The main visual studio object. /// </summary> private DTE2 dte_; /// <summary> /// Gets or sets the test context which provides information about, /// and functionality for the current test run. /// </summary> public TestContext TestContext { get; set; } /// <summary> /// This is run one time before any test methods are called. Here we set-up a test-copy of a /// new NaCl solution for use in the tests. /// </summary> /// <param name="testContext">Holds information about the current test run</param> [ClassInitialize] public static void ClassSetup(TestContext testContext) { DTE2 dte = TestUtilities.StartVisualStudioInstance(); try { naclSolution = TestUtilities.CreateBlankValidNaClSolution( dte, "PropertyManagerTest", NativeClientVSAddIn.Strings.PepperPlatformName, NativeClientVSAddIn.Strings.NaCl64PlatformName, testContext); } finally { TestUtilities.CleanUpVisualStudioInstance(dte); } } /// <summary> /// This is run before each test to create test resources. /// </summary> [TestInitialize] public void TestSetup() { dte_ = TestUtilities.StartVisualStudioInstance(); try { TestUtilities.AssertAddinLoaded(dte_, NativeClientVSAddIn.Strings.AddInName); } catch { TestUtilities.CleanUpVisualStudioInstance(dte_); throw; } } /// <summary> /// This is run after each test to clean up things created in TestSetup(). /// </summary> [TestCleanup] public void TestCleanup() { TestUtilities.CleanUpVisualStudioInstance(dte_); } /// <summary> /// Tests SetTarget() and SetTargetToActive(). /// </summary> [TestMethod] public void SetTargetTest() { string expectedSDKRootDir = Environment.GetEnvironmentVariable(Strings.SDKPathEnvironmentVariable); Assert.IsNotNull(expectedSDKRootDir, "SDK Path environment variable not set!"); expectedSDKRootDir = expectedSDKRootDir.TrimEnd(new char[] { '/', '\\' }); PropertyManager target = new PropertyManager(); dte_.Solution.Open(naclSolution); Project naclProject = dte_.Solution.Projects.Item(TestUtilities.NaClProjectUniqueName); Project notNacl = dte_.Solution.Projects.Item(TestUtilities.NotNaClProjectUniqueName); // Invalid project. target.SetTarget(notNacl, Strings.PepperPlatformName, "Debug"); Assert.AreEqual( PropertyManager.ProjectPlatformType.Other, target.PlatformType, "SetTarget should not succeed with non-nacl/pepper project."); // Try valid project with different platforms. target.SetTarget(naclProject, Strings.NaCl64PlatformName, "Debug"); Assert.AreEqual( PropertyManager.ProjectPlatformType.NaCl, target.PlatformType, "SetTarget did not succeed with NaCl64 platform on valid project."); Assert.AreEqual(expectedSDKRootDir, target.SDKRootDirectory, "SDK Root incorrect."); target.SetTarget(naclProject, Strings.NaClARMPlatformName, "Debug"); Assert.AreEqual( PropertyManager.ProjectPlatformType.NaCl, target.PlatformType, "SetTarget did not succeed with NaClARM platform on valid project."); Assert.AreEqual(expectedSDKRootDir, target.SDKRootDirectory, "SDK Root incorrect."); target.SetTarget(naclProject, Strings.PNaClPlatformName, "Debug"); Assert.AreEqual( PropertyManager.ProjectPlatformType.NaCl, target.PlatformType, "SetTarget did not succeed with nacl platform on valid project."); Assert.AreEqual(expectedSDKRootDir, target.SDKRootDirectory, "SDK Root incorrect."); target.SetTarget(naclProject, Strings.PepperPlatformName, "Debug"); Assert.AreEqual( PropertyManager.ProjectPlatformType.Pepper, target.PlatformType, "SetTarget did not succeed with pepper platform on valid project."); Assert.AreEqual(expectedSDKRootDir, target.SDKRootDirectory, "SDK Root incorrect."); target.SetTarget(naclProject, "Win32", "Debug"); Assert.AreEqual( PropertyManager.ProjectPlatformType.Other, target.PlatformType, "SetTarget did not set 'other' platform on when Win32 platform of valid project."); // Setting the start-up project to a non-cpp project should make loading fail. object[] badStartupProj = { TestUtilities.NotNaClProjectUniqueName }; dte_.Solution.SolutionBuild.StartupProjects = badStartupProj; target.SetTargetToActive(dte_); Assert.AreEqual( PropertyManager.ProjectPlatformType.Other, target.PlatformType, "SetTargetToActive should not succeed with non-nacl/pepper project."); // Setting the start-up project to correct C++ project, but also setting the platform // to non-nacl/pepper should make loading fail. object[] startupProj = { TestUtilities.NaClProjectUniqueName }; dte_.Solution.SolutionBuild.StartupProjects = startupProj; TestUtilities.SetSolutionConfiguration(dte_, TestUtilities.NaClProjectUniqueName, "Debug", "Win32"); target.SetTargetToActive(dte_); Assert.AreEqual( PropertyManager.ProjectPlatformType.Other, target.PlatformType, "SetTargetToActive should not succeed with Win32 platform."); // Now setting the platform to NaCl64 should make this succeed. TestUtilities.SetSolutionConfiguration(dte_, TestUtilities.NaClProjectUniqueName, "Debug", Strings.NaCl64PlatformName); target.SetTargetToActive(dte_); Assert.AreEqual( PropertyManager.ProjectPlatformType.NaCl, target.PlatformType, "SetTargetToActive should succeed with NaCl platform and valid project."); Assert.AreEqual(expectedSDKRootDir, target.SDKRootDirectory, "SDK Root incorrect."); } /// <summary> /// A test for GetProperty. Checks some non-trivial C# properties and the GetProperty method. /// </summary> [TestMethod] public void GetPropertyTest() { string expectedSDKRootDir = Environment.GetEnvironmentVariable(Strings.SDKPathEnvironmentVariable); Assert.IsNotNull(expectedSDKRootDir, "SDK Path environment variable not set!"); expectedSDKRootDir = expectedSDKRootDir.TrimEnd(new char[] { '/', '\\' }); // Set up the property manager to read the NaCl platform settings from BlankValidSolution. PropertyManager target = new PropertyManager(); dte_.Solution.Open(naclSolution); Project naclProject = dte_.Solution.Projects.Item(TestUtilities.NaClProjectUniqueName); string slnDir = Path.GetDirectoryName(naclSolution); string projectDir = Path.Combine( slnDir, Path.GetDirectoryName(TestUtilities.NaClProjectUniqueName)) + @"\"; foreach (string platform in NaClPlatformNames()) { target.SetTarget(naclProject, platform, "Debug"); Assert.AreEqual( PropertyManager.ProjectPlatformType.NaCl, target.PlatformType, "SetTarget did not succeed with nacl platform on valid project."); string outputDir = Path.Combine(projectDir, platform, "newlib", "Debug") + @"\"; string assembly = Path.Combine(outputDir, TestUtilities.BlankNaClProjectName); if (platform == "NaCl64") assembly += "_64.nexe"; else if (platform == "NaCl32") assembly += "_32.nexe"; else if (platform == "NaClARM") assembly += "_arm.nexe"; else if (platform == "PNaCl") assembly += ".pexe"; else Assert.Fail(); Assert.AreEqual(projectDir, target.ProjectDirectory, "ProjectDirectory."); Assert.AreEqual(outputDir, target.OutputDirectory, "OutputDirectory."); Assert.AreEqual(assembly, target.PluginAssembly, "PluginAssembly."); Assert.AreEqual(expectedSDKRootDir, target.SDKRootDirectory, "SDK Root."); Assert.AreEqual( @"newlib", target.GetProperty("ConfigurationGeneral", "ToolchainName"), "GetProperty() with ToolchainName incorrect."); } } /// <summary> /// Return a list of all nacl platform names. /// </summary> public static string[] NaClPlatformNames() { return new string[] { Strings.NaCl32PlatformName, Strings.NaCl64PlatformName, Strings.NaClARMPlatformName, Strings.PNaClPlatformName }; } /// <summary> /// A test for SetProperty. /// </summary> [TestMethod] public void SetPropertyTest() { string setTargetSolution = TestUtilities.CreateBlankValidNaClSolution( dte_, "PropertyManagerTestSetTarget", NativeClientVSAddIn.Strings.NaCl64PlatformName, NativeClientVSAddIn.Strings.NaCl64PlatformName, TestContext); // Set up the property manager to read the NaCl platform settings from BlankValidSolution. PropertyManager target = new PropertyManager(); dte_.Solution.Open(setTargetSolution); Project naclProject = dte_.Solution.Projects.Item(TestUtilities.NaClProjectUniqueName); foreach (string platform in NaClPlatformNames()) { target.SetTarget(naclProject, platform, "Debug"); Assert.AreEqual( PropertyManager.ProjectPlatformType.NaCl, target.PlatformType, "SetTarget did not succeed with nacl platform on valid project."); string newValue = "ThisIsNew"; target.SetProperty("ConfigurationGeneral", "VSNaClSDKRoot", newValue); Assert.AreEqual( newValue, target.GetProperty("ConfigurationGeneral", "VSNaClSDKRoot"), "SetProperty() did not set property VSNaClSDKRoot."); } } } }
#region File Description //----------------------------------------------------------------------------- // AudioManager.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Media; #endregion namespace HoneycombRush { /// <summary> /// Component that manages audio playback for all sounds. /// </summary> public class AudioManager : GameComponent { #region Fields /// <summary> /// The singleton for this type. /// </summary> static AudioManager audioManager = null; public static AudioManager Instance { get { return audioManager; } } static readonly string soundAssetLocation = "Sounds/"; // Audio Data Dictionary<string, SoundEffectInstance> soundBank; Dictionary<string, Song> musicBank; #endregion #region Initialization private AudioManager(Game game) : base(game) { } /// <summary> /// Initialize the static AudioManager functionality. /// </summary> /// <param name="game">The game that this component will be attached to.</param> public static void Initialize(Game game) { audioManager = new AudioManager(game); audioManager.soundBank = new Dictionary<string, SoundEffectInstance>(); audioManager.musicBank = new Dictionary<string, Song>(); game.Components.Add(audioManager); } #endregion #region Loading Methodes /// <summary> /// Loads a single sound into the sound manager, giving it a specified alias. /// </summary> /// <param name="contentName">The content name of the sound file. Assumes all sounds are located under /// the "Sounds" folder in the content project.</param> /// <param name="alias">Alias to give the sound. This will be used to identify the sound uniquely.</param> /// <remarks>Loading a sound with an alias that is already used will have no effect.</remarks> public static void LoadSound(string contentName, string alias) { SoundEffect soundEffect = audioManager.Game.Content.Load<SoundEffect>(soundAssetLocation + contentName); SoundEffectInstance soundEffectInstance = soundEffect.CreateInstance(); if (!audioManager.soundBank.ContainsKey(alias)) { audioManager.soundBank.Add(alias, soundEffectInstance); } } /// <summary> /// Loads a single song into the sound manager, giving it a specified alias. /// </summary> /// <param name="contentName">The content name of the sound file containing the song. Assumes all sounds are /// located under the "Sounds" folder in the content project.</param> /// <param name="alias">Alias to give the song. This will be used to identify the song uniquely.</param> /// /// <remarks>Loading a song with an alias that is already used will have no effect.</remarks> public static void LoadSong(string contentName, string alias) { Song song = audioManager.Game.Content.Load<Song>(soundAssetLocation + contentName); if (!audioManager.musicBank.ContainsKey(alias)) { audioManager.musicBank.Add(alias, song); } } /// <summary> /// Loads and organizes the sounds used by the game. /// </summary> public static void LoadSounds() { LoadSound("10SecondCountDown", "10SecondCountDown"); LoadSound("30SecondWarning", "30SecondWarning"); LoadSound("BeeBuzzing_Loop", "BeeBuzzing_Loop"); LoadSound("Defeat", "Defeat"); LoadSound("DepositingIntoVat_Loop", "DepositingIntoVat_Loop"); LoadSound("FillingHoneyPot_Loop", "FillingHoneyPot_Loop"); LoadSound("HighScore", "HighScore"); LoadSound("HoneyPotBreak", "HoneyPotBreak"); LoadSound("SmokeGun_Loop", "SmokeGun_Loop"); LoadSound("Stung", "Stung"); LoadSound("Stunned", "Stunned"); LoadSound("Victory", "Victory"); } /// <summary> /// Loads and organizes the music used by the game. /// </summary> public static void LoadMusic() { LoadSong("InGameSong_Loop", "InGameSong_Loop"); LoadSong("MenuMusic_Loop", "MenuMusic_Loop"); } #endregion #region Sound Methods /// <summary> /// Indexer. Return a sound instance by name. /// </summary> public SoundEffectInstance this[string soundName] { get { if (audioManager.soundBank.ContainsKey(soundName)) { return audioManager.soundBank[soundName]; } else { return null; } } } /// <summary> /// Plays a sound by name. /// </summary> /// <param name="soundName">The name of the sound to play.</param> public static void PlaySound(string soundName) { // If the sound exists, start it if (audioManager.soundBank.ContainsKey(soundName)) { audioManager.soundBank[soundName].Play(); } } /// <summary> /// Plays a sound by name. /// </summary> /// <param name="soundName">The name of the sound to play.</param> /// <param name="isLooped">Indicates if the sound should loop.</param> public static void PlaySound(string soundName, bool isLooped) { // If the sound exists, start it if (audioManager.soundBank.ContainsKey(soundName)) { if (audioManager.soundBank[soundName].IsLooped != isLooped) { audioManager.soundBank[soundName].IsLooped = isLooped; } audioManager.soundBank[soundName].Play(); } } /// <summary> /// Plays a sound by name. /// </summary> /// <param name="soundName">The name of the sound to play.</param> /// <param name="isLooped">Indicates if the sound should loop.</param> /// <param name="volume">Indicates if the volume</param> public static void PlaySound(string soundName, bool isLooped, float volume) { // If the sound exists, start it if (audioManager.soundBank.ContainsKey(soundName)) { if (audioManager.soundBank[soundName].IsLooped != isLooped) { audioManager.soundBank[soundName].IsLooped = isLooped; } audioManager.soundBank[soundName].Volume = volume; audioManager.soundBank[soundName].Play(); } } /// <summary> /// Stops a sound mid-play. If the sound is not playing, this /// method does nothing. /// </summary> /// <param name="soundName">The name of the sound to stop.</param> public static void StopSound(string soundName) { // If the sound exists, stop it if (audioManager.soundBank.ContainsKey(soundName)) { audioManager.soundBank[soundName].Stop(); } } /// <summary> /// Stops all currently playing sounds. /// </summary> public static void StopSounds() { foreach (SoundEffectInstance sound in audioManager.soundBank.Values) { if (sound.State != SoundState.Stopped) { sound.Stop(); } } } /// <summary> /// Pause or resume all sounds. /// </summary> /// <param name="resumeSounds">True to resume all paused sounds or false /// to pause all playing sounds.</param> public static void PauseResumeSounds(bool resumeSounds) { SoundState state = resumeSounds ? SoundState.Paused : SoundState.Playing; foreach (SoundEffectInstance sound in audioManager.soundBank.Values) { if (sound.State == state) { if (resumeSounds) { sound.Resume(); } else { sound.Pause(); } } } } /// <summary> /// Play music by name. This stops the currently playing music first. Music will loop until stopped. /// </summary> /// <param name="musicSoundName">The name of the music sound.</param> /// <remarks>If the desired music is not in the music bank, nothing will happen.</remarks> public static void PlayMusic(string musicSoundName) { // If the music sound exists if (audioManager.musicBank.ContainsKey(musicSoundName)) { // Stop the old music sound if (MediaPlayer.State != MediaState.Stopped) { MediaPlayer.Stop(); } MediaPlayer.IsRepeating = true; MediaPlayer.Play(audioManager.musicBank[musicSoundName]); } } /// <summary> /// Stops the currently playing music. /// </summary> public static void StopMusic() { if (MediaPlayer.State != MediaState.Stopped) { MediaPlayer.Stop(); } } #endregion #region Instance Disposal Methods /// <summary> /// Clean up the component when it is disposing. /// </summary> protected override void Dispose(bool disposing) { try { if (disposing) { foreach (var item in soundBank) { item.Value.Dispose(); } soundBank.Clear(); soundBank = null; } } finally { base.Dispose(disposing); } } #endregion } }
// // DatabaseImportManager.cs // // Authors: // Aaron Bockover <abockover@novell.com> // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using Mono.Unix; using Hyena; using Hyena.Data.Sqlite; using Banshee.Base; using Banshee.Sources; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration.Schema; using Banshee.ServiceStack; using Banshee.Streaming; namespace Banshee.Collection.Database { public class DatabaseImportManager : ImportManager { // This is a list of known media files that we may encounter. The extensions // in this list do not mean they are actually supported - this list is just // used to see if we should allow the file to be processed by TagLib. The // point is to rule out, at the path level, files that we won't support. public static readonly Banshee.IO.ExtensionSet WhiteListFileExtensions = new Banshee.IO.ExtensionSet ( "3g2", "3gp", "3gp2", "3gpp", "aac", "ac3", "aif", "aifc", "aiff", "al", "alaw", "ape", "asf", "asx", "au", "avi", "cda", "cdr", "divx", "dv", "flac", "flv", "gvi", "gvp", "m1v", "m21", "m2p", "m2v", "m4a", "m4b", "m4e", "m4p", "m4u", "m4v", "mp+", "mid", "midi", "mjp", "mkv", "moov", "mov", "movie","mp1", "mp2", "mp21", "mp3", "mp4", "mpa", "mpc", "mpe", "mpeg", "mpg", "mpga", "mpp", "mpu", "mpv", "mpv2", "oga", "ogg", "ogv", "ogm", "omf", "qt", "ra", "ram", "raw", "rm", "rmvb", "rts", "smil", "swf", "tivo", "u", "vfw", "vob", "wav", "wave", "wax", "wm", "wma", "wmd", "wmv", "wmx", "wv", "wvc", "wvx", "yuv", "f4v", "f4a", "f4b", "669", "it", "med", "mod", "mol", "mtm", "nst", "s3m", "stm", "ult", "wow", "xm", "xnm", "spx", "ts", "webm", "spc", "mka", "opus" ); public static bool IsWhiteListedFile (string path) { return WhiteListFileExtensions.IsMatchingFile (path); } public delegate PrimarySource TrackPrimarySourceChooser (DatabaseTrackInfo track); private TrackPrimarySourceChooser trackPrimarySourceChooser; private Dictionary<int, int> counts; private ErrorSource error_source; private int [] primary_source_ids; private string base_directory; private bool force_copy; public event DatabaseImportResultHandler ImportResult; public DatabaseImportManager (PrimarySource psource) : this (psource.ErrorSource, delegate { return psource; }, new int [] {psource.DbId}, psource.BaseDirectory) { } public DatabaseImportManager (ErrorSource error_source, TrackPrimarySourceChooser chooser, int [] primarySourceIds, string baseDirectory) : this (chooser) { this.error_source = error_source; primary_source_ids = primarySourceIds; base_directory = baseDirectory; } public DatabaseImportManager (TrackPrimarySourceChooser chooser) { trackPrimarySourceChooser = chooser; counts = new Dictionary<int, int> (); } protected virtual ErrorSource ErrorSource { get { return error_source; } } protected virtual int [] PrimarySourceIds { get { return primary_source_ids; } set { primary_source_ids = value; } } protected virtual string BaseDirectory { get { return base_directory; } set { base_directory = value; } } protected virtual bool ForceCopy { get { return force_copy; } set { force_copy = value; } } protected override void OnImportRequested (string path) { try { DatabaseTrackInfo track = ImportTrack (path); if (track != null && track.TrackId > 0) { UpdateProgress (String.Format ("{0} - {1}", track.DisplayArtistName, track.DisplayTrackTitle)); } else { UpdateProgress (null); } OnImportResult (track, path, null); } catch (Exception e) { LogError (SafeUri.UriToFilename (path), e); UpdateProgress (null); OnImportResult (null, path, e); } } protected virtual void OnImportResult (DatabaseTrackInfo track, string path, Exception error) { DatabaseImportResultHandler handler = ImportResult; if (handler != null) { handler (this, new DatabaseImportResultArgs (track, path, error)); } } public DatabaseTrackInfo ImportTrack (string path) { return ImportTrack (new SafeUri (path)); } public DatabaseTrackInfo ImportTrack (SafeUri uri) { if (!IsWhiteListedFile (uri.AbsoluteUri)) { return null; } if (DatabaseTrackInfo.ContainsUri (uri, PrimarySourceIds)) { // TODO add DatabaseTrackInfo.SyncedStamp property, and if the file has been // updated since the last sync, fetch its metadata into the db. return null; } if (Banshee.IO.File.GetSize (uri) == 0) { throw new InvalidFileException (String.Format ( Catalog.GetString ("File is empty so it could not be imported: {0}"), Path.GetFileName (uri.LocalPath))); } DatabaseTrackInfo track = new DatabaseTrackInfo () { Uri = uri }; using (var file = StreamTagger.ProcessUri (uri)) { StreamTagger.TrackInfoMerge (track, file, false, true, true); } track.Uri = uri; if (FindOutdatedDupe (track)) { return null; } track.PrimarySource = trackPrimarySourceChooser (track); // TODO note, there is deadlock potential here b/c of locking of shared commands and blocking // because of transactions. Needs to be fixed in HyenaDatabaseConnection. ServiceManager.DbConnection.BeginTransaction (); try { bool save_track = true; if (track.PrimarySource is Banshee.Library.LibrarySource) { save_track = track.CopyToLibraryIfAppropriate (force_copy); } if (save_track) { track.Save (false); } ServiceManager.DbConnection.CommitTransaction (); } catch (Exception) { ServiceManager.DbConnection.RollbackTransaction (); throw; } counts[track.PrimarySourceId] = counts.ContainsKey (track.PrimarySourceId) ? counts[track.PrimarySourceId] + 1 : 1; // Reload every 20% or every 250 tracks, whatever is more (eg at most reload 5 times during an import) if (counts[track.PrimarySourceId] >= Math.Max (TotalCount/5, 250)) { counts[track.PrimarySourceId] = 0; track.PrimarySource.NotifyTracksAdded (); } return track; } private bool FindOutdatedDupe (DatabaseTrackInfo track) { if (DatabaseTrackInfo.MetadataHashCount (track.MetadataHash, PrimarySourceIds) != 1) { return false; } var track_to_update = DatabaseTrackInfo.GetTrackForMetadataHash (track.MetadataHash, PrimarySourceIds); if (track_to_update == null || Banshee.IO.File.Exists (track_to_update.Uri)) { return false; } track_to_update.Uri = track.Uri; track_to_update.Save (); return true; } private void LogError (string path, Exception e) { LogError (path, e.Message); if (!(e is TagLib.CorruptFileException) && !(e is TagLib.UnsupportedFormatException)) { Log.DebugFormat ("Full import exception: {0}", e.ToString ()); } } private void LogError (string path, string msg) { ErrorSource.AddMessage (path, msg); Log.Error (path, msg, false); } public void NotifyAllSources () { foreach (int primary_source_id in counts.Keys) { PrimarySource.GetById (primary_source_id).NotifyTracksAdded (); } counts.Clear (); } protected override void OnFinished () { NotifyAllSources (); base.OnFinished (); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace KaoriStudio.Core.Helpers { /// <summary> /// Explode enumerable /// </summary> /// <typeparam name="K">The key type</typeparam> /// <typeparam name="T">The element type</typeparam> public class ExplodeEnumerable<K, T> : IEnumerable<T>, IGrouping<K, T> { /// <summary> /// The key for this enumerable /// </summary> public K Key { get { return key; } } /// <summary> /// Whether the enumerator is exhausted /// </summary> public bool EnumeratorDone { get { if (!enumdone && cache == null) { new Enumerator(this).MoveNext(); } return enumdone; } } /// <summary> /// Whether the enumerator is done for this enumerable /// </summary> public bool Done { get { return done; } } /// <summary> /// Discards until done is true /// </summary> public void ForceDone() { if (!done) { var discarder = new Enumerator(this, cache != null ? cache.Count : 0); while (!done && discarder.MoveNext()) ; } } /// <summary> /// The delimiters /// </summary> public T[] Delimiters { get { return delimiters; } set { delimiters = value; } } List<T> cache; bool done; bool enumdone; IEnumerator<T> enumerator; T[] delimiters; IEqualityComparer<T> comparer; K key; /// <summary> /// Creates a new ExplodeEnumerable /// </summary> /// <param name="enumerator">The enumerator</param> /// <param name="key">The key</param> /// <param name="comparer">The value comparer</param> /// <param name="delimiters">The delimiters</param> public ExplodeEnumerable(IEnumerator<T> enumerator, K key, IEqualityComparer<T> comparer, T[] delimiters) { this.cache = null; this.done = false; this.enumdone = false; this.enumerator = enumerator; this.delimiters = delimiters; this.comparer = comparer; this.key = key; } /// <summary> /// Creates a new ExplodeEnumerable /// </summary> /// <param name="previous">The previous enumerator</param> /// <param name="key">The key</param> public ExplodeEnumerable(ExplodeEnumerable<K, T> previous, K key) { this.cache = null; this.done = previous.enumdone; this.enumdone = previous.enumdone; this.enumerator = previous.enumerator; this.delimiters = previous.delimiters; this.comparer = previous.comparer; this.key = key; } /// <summary> /// Gets the enumerator /// </summary> /// <returns>The enumerator</returns> public IEnumerator<T> GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } class Enumerator : IEnumerator<T> { int index; T current; ExplodeEnumerable<K, T> enumerable; public Enumerator(ExplodeEnumerable<K, T> enumerable) : this(enumerable, 0) { } public Enumerator(ExplodeEnumerable<K, T> enumerable, int index) { this.enumerable = enumerable; this.index = index; this.current = default(T); } public T Current { get { return current; } } object IEnumerator.Current { get { return current; } } public void Dispose() { } public void Reset() { throw new NotImplementedException(); } public bool MoveNext() { if (enumerable.cache == null) enumerable.cache = new List<T>(); if (index < enumerable.cache.Count) { current = enumerable.cache[index]; index++; return true; } else { if (!enumerable.done) { if (enumerable.enumerator.MoveNext()) { current = enumerable.enumerator.Current; if (enumerable.delimiters != null && enumerable.delimiters.Any(x => enumerable.comparer.Equals(x, current))) { enumerable.done = true; return false; } enumerable.cache.Add(current = enumerable.enumerator.Current); index++; return true; } else { enumerable.enumdone = true; enumerable.done = true; return false; } } else { return false; } } } } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.IO; using Gallio.Common.IO; using Gallio.Common.Policies; using Gallio.Icarus.Commands; using Gallio.Icarus.Controllers.Interfaces; using Gallio.Icarus.Events; using Gallio.UI.Controls; using Gallio.Icarus.Helpers; using Gallio.Runner.Projects; using Gallio.Runtime.ProgressMonitoring; using Gallio.UI.Common.Policies; using Gallio.UI.DataBinding; using Gallio.UI.Events; using Gallio.UI.ProgressMonitoring; namespace Gallio.Icarus.Controllers { public class ApplicationController : NotifyController, IApplicationController, Handles<RunStarted>, Handles<RunFinished>, Handles<ExploreFinished>, Handles<TestsFailed> { private string projectFileName = Paths.DefaultProject; private readonly IFileSystem fileSystem; private readonly IOptionsController optionsController; private readonly ITaskManager taskManager; private readonly IUnhandledExceptionPolicy unhandledExceptionPolicy; private readonly IEventAggregator eventAggregator; private readonly ICommandFactory commandFactory; public string Title { get { return string.Format("{0} - {1}", Path.GetFileNameWithoutExtension(projectFileName), Properties.Resources.ApplicationName); } set { projectFileName = value; OnPropertyChanged(new PropertyChangedEventArgs("ProjectFileName")); } } public Boolean DefaultProject { get { return (projectFileName.ToUpper() == Paths.DefaultProject.ToUpper()); } } public ToolStripMenuItem[] RecentProjects { get { var menuListHelper = new MenuListHelper(optionsController, fileSystem); return menuListHelper.GetRecentProjectsMenuList(OpenProject); } } public IcarusArguments Arguments { get; set; } public Observable<bool> CanRunTests { get; private set; } public event EventHandler ExploreFinished; public event EventHandler RunStarted = (s, e) => { }; public event EventHandler RunFinished = (s, e) => { }; public event EventHandler TestsFailed = (s, e) => { }; // FIXME: too many dependencies! public ApplicationController(IOptionsController optionsController, IFileSystem fileSystem, ITaskManager taskManager, ITestController testController, IProjectController projectController, IUnhandledExceptionPolicy unhandledExceptionPolicy, IEventAggregator eventAggregator, ICommandFactory commandFactory) { this.optionsController = optionsController; this.fileSystem = fileSystem; this.taskManager = taskManager; this.unhandledExceptionPolicy = unhandledExceptionPolicy; this.eventAggregator = eventAggregator; this.commandFactory = commandFactory; optionsController.PropertyChanged += (sender, e) => { if (e.PropertyName == "RecentProjects") OnPropertyChanged(new PropertyChangedEventArgs("RecentProjects")); }; CanRunTests = new Observable<bool>(); } public void Load() { HandleArguments(); } private void HandleArguments() { if (Arguments.Files.Length > 0) { AddFiles(); return; } if (optionsController.RestorePreviousSettings && optionsController.RecentProjects.Count > 0) { var projectName = optionsController.RecentProjects.Items[0]; if (fileSystem.FileExists(projectName)) { OpenProject(projectName); return; } } NewProject(); } private void AddFiles() { var files = new List<string>(); foreach (var file in Arguments.Files) { if (!fileSystem.FileExists(file)) continue; if (Path.GetExtension(file) == TestProject.Extension) { OpenProject(file); return; } files.Add(file); } var command = commandFactory.CreateAddFilesCommand(files); taskManager.QueueTask(command); } public void OpenProject(string projectName) { Title = projectName; var command = commandFactory.CreateOpenProjectCommand(projectName); taskManager.QueueTask(command); } public void SaveProject(bool queueTask) { var command = commandFactory.CreateSaveProjectCommand(projectFileName); if (queueTask) { taskManager.QueueTask(command); } else { // we're shutting down, so eat any errors try { command.Execute(NullProgressMonitor.CreateInstance()); } catch (Exception ex) { unhandledExceptionPolicy.Report("Error saving project", ex); } } } public void NewProject() { // TODO: DRY, this shouldn't be necessary here Title = Paths.DefaultProject; var command = commandFactory.CreateNewProjectCommand(); taskManager.QueueTask(command); } public void Shutdown() { eventAggregator.Send(this, new ApplicationShutdown()); optionsController.Save(); if (optionsController.AutoSaveProject) { SaveProject(false); } } public void Handle(RunStarted @event) { EventHandlerPolicy.SafeInvoke(RunStarted, this, System.EventArgs.Empty); } public void Handle(RunFinished @event) { EventHandlerPolicy.SafeInvoke(RunFinished, this, System.EventArgs.Empty); } public void Handle(ExploreFinished @event) { EventHandlerPolicy.SafeInvoke(ExploreFinished, this, System.EventArgs.Empty); } public void Handle(TestsFailed @event) { TestsFailed(this, System.EventArgs.Empty); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 ASC.Mail.Net.IO { #region usings using System; using System.Collections.Generic; using System.IO; #endregion /// <summary> /// This class combines multiple stream into one stream for reading. /// The most common usage for that stream is when you need to insert some data to the beginning of some stream. /// </summary> public class MultiStream : Stream { #region Members private bool m_IsDisposed; private Queue<Stream> m_pStreams; #endregion #region Properties /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanRead { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return true; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanSeek { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return false; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanWrite { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return false; } } /// <summary> /// Gets the length in bytes of the stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when one of the source streams won't support <b>Length</b> property.</exception> public override long Length { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } long length = 0; foreach (Stream stream in m_pStreams.ToArray()) { length += stream.Length; } return length; } } /// <summary> /// Gets or sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception> public override long Position { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } throw new NotSupportedException(); } set { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } throw new NotSupportedException(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public MultiStream() { m_pStreams = new Queue<Stream>(); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public new void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; m_pStreams = null; base.Dispose(); } /// <summary> /// Appends this stream to read queue. /// </summary> /// <param name="stream">Stream to add.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception> public void AppendStream(Stream stream) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (stream == null) { throw new ArgumentNullException("stream"); } m_pStreams.Enqueue(stream); } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public override void Flush() { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } } /// <summary> /// Sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="offset">A byte offset relative to the <b>origin</b> parameter.</param> /// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception> public override long Seek(long offset, SeekOrigin origin) { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } throw new NotSupportedException(); } /// <summary> /// Sets the length of the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="Seek">Is raised when this method is accessed.</exception> public override void SetLength(long value) { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } throw new NotSupportedException(); } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public override int Read(byte[] buffer, int offset, int count) { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } while (true) { // We have readed all streams data, no data left. if (m_pStreams.Count == 0) { return 0; } else { int readedCount = m_pStreams.Peek().Read(buffer, offset, count); // We have readed all current stream data. if (readedCount == 0) { // Move to next stream . m_pStreams.Dequeue(); // Next while loop will process "read". } else { return readedCount; } } } } /// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception> public override void Write(byte[] buffer, int offset, int count) { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } throw new NotSupportedException(); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Timers; using log4net; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim { /// <summary> /// Interactive OpenSim region server /// </summary> public class OpenSim : OpenSimBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_startupCommandsFile; protected string m_shutdownCommandsFile; protected bool m_gui = false; protected string m_consoleType = "local"; protected uint m_consolePort = 0; /// <summary> /// Prompt to use for simulator command line. /// </summary> private string m_consolePrompt; /// <summary> /// Regex for parsing out special characters in the prompt. /// </summary> private Regex m_consolePromptRegex = new Regex(@"([^\\])\\(\w)", RegexOptions.Compiled); private string m_timedScript = "disabled"; private int m_timeInterval = 1200; private Timer m_scriptTimer; public OpenSim(IConfigSource configSource) : base(configSource) { } protected override void ReadExtraConfigSettings() { base.ReadExtraConfigSettings(); IConfig startupConfig = Config.Configs["Startup"]; IConfig networkConfig = Config.Configs["Network"]; int stpMinThreads = 2; int stpMaxThreads = 15; if (startupConfig != null) { m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt"); m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt"); if (startupConfig.GetString("console", String.Empty) == String.Empty) m_gui = startupConfig.GetBoolean("gui", false); else m_consoleType= startupConfig.GetString("console", String.Empty); if (networkConfig != null) m_consolePort = (uint)networkConfig.GetInt("console_port", 0); m_timedScript = startupConfig.GetString("timer_Script", "disabled"); if (m_timedScript != "disabled") { m_timeInterval = startupConfig.GetInt("timer_Interval", 1200); } string asyncCallMethodStr = startupConfig.GetString("async_call_method", String.Empty); FireAndForgetMethod asyncCallMethod; if (!String.IsNullOrEmpty(asyncCallMethodStr) && Utils.EnumTryParse<FireAndForgetMethod>(asyncCallMethodStr, out asyncCallMethod)) Util.FireAndForgetMethod = asyncCallMethod; stpMinThreads = startupConfig.GetInt("MinPoolThreads", 2 ); stpMaxThreads = startupConfig.GetInt("MaxPoolThreads", 25); m_consolePrompt = startupConfig.GetString("ConsolePrompt", @"Region (\R) "); } if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool) Util.InitThreadPool(stpMinThreads, stpMaxThreads); m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod); } /// <summary> /// Performs initialisation of the scene, such as loading configuration from disk. /// </summary> protected override void StartupSpecific() { m_log.Info("===================================================================="); m_log.Info("========================= STARTING OPENSIM ========================="); m_log.Info("===================================================================="); //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString()); // http://msdn.microsoft.com/en-us/library/bb384202.aspx //GCSettings.LatencyMode = GCLatencyMode.Batch; //m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString()); if (m_gui) // Driven by external GUI { m_console = new CommandConsole("Region"); } else { switch (m_consoleType) { case "basic": m_console = new CommandConsole("Region"); break; case "rest": m_console = new RemoteConsole("Region"); ((RemoteConsole)m_console).ReadConfig(Config); break; default: m_console = new LocalConsole("Region", Config.Configs["Startup"]); break; } } MainConsole.Instance = m_console; LogEnvironmentInformation(); RegisterCommonAppenders(Config.Configs["Startup"]); RegisterConsoleCommands(); base.StartupSpecific(); MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler()); MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this)); if (userStatsURI != String.Empty) MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this)); if (managedStatsURI != String.Empty) { string urlBase = String.Format("/{0}/", managedStatsURI); MainServer.Instance.AddHTTPHandler(urlBase, StatsManager.HandleStatsRequest); m_log.InfoFormat("[OPENSIM] Enabling remote managed stats fetch. URL = {0}", urlBase); } if (m_console is RemoteConsole) { if (m_consolePort == 0) { ((RemoteConsole)m_console).SetServer(m_httpServer); } else { ((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort)); } } // Hook up to the watchdog timer Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler; PrintFileToConsole("startuplogo.txt"); // For now, start at the 'root' level by default if (SceneManager.Scenes.Count == 1) // If there is only one region, select it ChangeSelectedRegion("region", new string[] {"change", "region", SceneManager.Scenes[0].RegionInfo.RegionName}); else ChangeSelectedRegion("region", new string[] {"change", "region", "root"}); //Run Startup Commands if (String.IsNullOrEmpty(m_startupCommandsFile)) { m_log.Info("[STARTUP]: No startup command script specified. Moving on..."); } else { RunCommandScript(m_startupCommandsFile); } // Start timer script (run a script every xx seconds) if (m_timedScript != "disabled") { m_scriptTimer = new Timer(); m_scriptTimer.Enabled = true; m_scriptTimer.Interval = m_timeInterval*1000; m_scriptTimer.Elapsed += RunAutoTimerScript; } } /// <summary> /// Register standard set of region console commands /// </summary> private void RegisterConsoleCommands() { MainServer.RegisterHttpConsoleCommands(m_console); m_console.Commands.AddCommand("Objects", false, "force update", "force update", "Force the update of all objects on clients", HandleForceUpdate); m_console.Commands.AddCommand("General", false, "change region", "change region <region name>", "Change current console region", ChangeSelectedRegion); m_console.Commands.AddCommand("Archiving", false, "save xml", "save xml", "Save a region's data in XML format", SaveXml); m_console.Commands.AddCommand("Archiving", false, "save xml2", "save xml2", "Save a region's data in XML2 format", SaveXml2); m_console.Commands.AddCommand("Archiving", false, "load xml", "load xml [-newIDs [<x> <y> <z>]]", "Load a region's data from XML format", LoadXml); m_console.Commands.AddCommand("Archiving", false, "load xml2", "load xml2", "Load a region's data from XML2 format", LoadXml2); m_console.Commands.AddCommand("Archiving", false, "save prims xml2", "save prims xml2 [<prim name> <file name>]", "Save named prim to XML2", SavePrimsXml2); m_console.Commands.AddCommand("Archiving", false, "load oar", "load oar [-m|--merge] [-s|--skip-assets]" + " [--default-user \"User Name\"]" + " [--force-terrain] [--force-parcels]" + " [--no-objects]" + " [--rotation degrees]" + " [--bounding-origin \"<x,y,z>\"]" + " [--bounding-size \"<x,y,z>\"]" + " [--displacement \"<x,y,z>\"]" + " [-d|--debug]" + " [<OAR path>]", "Load a region's data from an OAR archive.", "--merge will merge the OAR with the existing scene (suppresses terrain and parcel info loading).\n" + "--skip-assets will load the OAR but ignore the assets it contains.\n" + "--default-user will use this user for any objects with an owner whose UUID is not found in the grid.\n" + "--force-terrain forces the loading of terrain from the oar (undoes suppression done by --merge).\n" + "--force-parcels forces the loading of parcels from the oar (undoes suppression done by --merge).\n" + "--no-objects suppresses the addition of any objects (good for loading only the terrain).\n" + "--rotation specified rotation to be applied to the oar. Specified in degrees.\n" + "--bounding-origin will only place objects that after displacement and rotation fall within the bounding cube who's position starts at <x,y,z>. Defaults to <0,0,0>.\n" + "--bounding-size specifies the size of the bounding cube. The default is the size of the destination region and cannot be larger than this.\n" + "--displacement will add this value to the position of every object loaded.\n" + "--debug forces the archiver to display messages about where each object is being placed.\n\n" + "The path can be either a filesystem location or a URI.\n" + " If this is not given then the command looks for an OAR named region.oar in the current directory." + " [--rotation-center \"<x,y,z>\"] used to be an option, now it does nothing and will be removed soon." + "When an OAR is being loaded, operations are applied in this order:\n" + "1: Rotation (around the incoming OARs region center)\n" + "2: Cropping (a bounding cube with origin and size)\n" + "3: Displacement (setting offset coordinates within the destination region)", LoadOar); ; m_console.Commands.AddCommand("Archiving", false, "save oar", //"save oar [-v|--version=<N>] [-p|--profile=<url>] [<OAR path>]", "save oar [-h|--home=<url>] [--noassets] [--publish] [--perm=<permissions>] [--all] [<OAR path>]", "Save a region's data to an OAR archive.", // "-v|--version=<N> generates scene objects as per older versions of the serialization (e.g. -v=0)" + Environment.NewLine "-h|--home=<url> adds the url of the profile service to the saved user information.\n" + "--noassets stops assets being saved to the OAR.\n" + "--publish saves an OAR stripped of owner and last owner information.\n" + " on reload, the estate owner will be the owner of all objects\n" + " this is useful if you're making oars generally available that might be reloaded to the same grid from which you published\n" + "--perm=<permissions> stops objects with insufficient permissions from being saved to the OAR.\n" + " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer\n" + "--all saves all the regions in the simulator, instead of just the current region.\n" + "The OAR path must be a filesystem path." + " If this is not given then the oar is saved to region.oar in the current directory.", SaveOar); m_console.Commands.AddCommand("Objects", false, "edit scale", "edit scale <name> <x> <y> <z>", "Change the scale of a named prim", HandleEditScale); m_console.Commands.AddCommand("Objects", false, "rotate scene", "rotate scene <degrees> [centerX, centerY]", "Rotates all scene objects around centerX, centerY (default 128, 128) (please back up your region before using)", HandleRotateScene); m_console.Commands.AddCommand("Objects", false, "scale scene", "scale scene <factor>", "Scales the scene objects (please back up your region before using)", HandleScaleScene); m_console.Commands.AddCommand("Objects", false, "translate scene", "translate scene xOffset yOffset zOffset", "translates the scene objects (please back up your region before using)", HandleTranslateScene); m_console.Commands.AddCommand("Users", false, "kick user", "kick user <first> <last> [--force] [message]", "Kick a user off the simulator", "The --force option will kick the user without any checks to see whether it's already in the process of closing\n" + "Only use this option if you are sure the avatar is inactive and a normal kick user operation does not removed them", KickUserCommand); m_console.Commands.AddCommand("Users", false, "show users", "show users [full]", "Show user data for users currently on the region", "Without the 'full' option, only users actually on the region are shown." + " With the 'full' option child agents of users in neighbouring regions are also shown.", HandleShow); m_console.Commands.AddCommand("Comms", false, "show connections", "show connections", "Show connection data", HandleShow); m_console.Commands.AddCommand("Comms", false, "show circuits", "show circuits", "Show agent circuit data", HandleShow); m_console.Commands.AddCommand("Comms", false, "show pending-objects", "show pending-objects", "Show # of objects on the pending queues of all scene viewers", HandleShow); m_console.Commands.AddCommand("General", false, "show modules", "show modules", "Show module data", HandleShow); m_console.Commands.AddCommand("Regions", false, "show regions", "show regions", "Show region data", HandleShow); m_console.Commands.AddCommand("Regions", false, "show ratings", "show ratings", "Show rating data", HandleShow); m_console.Commands.AddCommand("Objects", false, "backup", "backup", "Persist currently unsaved object changes immediately instead of waiting for the normal persistence call.", RunCommand); m_console.Commands.AddCommand("Regions", false, "create region", "create region [\"region name\"] <region_file.ini>", "Create a new region.", "The settings for \"region name\" are read from <region_file.ini>. Paths specified with <region_file.ini> are relative to your Regions directory, unless an absolute path is given." + " If \"region name\" does not exist in <region_file.ini>, it will be added." + Environment.NewLine + "Without \"region name\", the first region found in <region_file.ini> will be created." + Environment.NewLine + "If <region_file.ini> does not exist, it will be created.", HandleCreateRegion); m_console.Commands.AddCommand("Regions", false, "restart", "restart", "Restart the currently selected region(s) in this instance", RunCommand); m_console.Commands.AddCommand("General", false, "command-script", "command-script <script>", "Run a command script from file", RunCommand); m_console.Commands.AddCommand("Regions", false, "remove-region", "remove-region <name>", "Remove a region from this simulator", RunCommand); m_console.Commands.AddCommand("Regions", false, "delete-region", "delete-region <name>", "Delete a region from disk", RunCommand); m_console.Commands.AddCommand("Estates", false, "estate create", "estate create <owner UUID> <estate name>", "Creates a new estate with the specified name, owned by the specified user." + " Estate name must be unique.", CreateEstateCommand); m_console.Commands.AddCommand("Estates", false, "estate set owner", "estate set owner <estate-id>[ <UUID> | <Firstname> <Lastname> ]", "Sets the owner of the specified estate to the specified UUID or user. ", SetEstateOwnerCommand); m_console.Commands.AddCommand("Estates", false, "estate set name", "estate set name <estate-id> <new name>", "Sets the name of the specified estate to the specified value. New name must be unique.", SetEstateNameCommand); m_console.Commands.AddCommand("Estates", false, "estate link region", "estate link region <estate ID> <region ID>", "Attaches the specified region to the specified estate.", EstateLinkRegionCommand); } protected override void ShutdownSpecific() { if (m_shutdownCommandsFile != String.Empty) { RunCommandScript(m_shutdownCommandsFile); } base.ShutdownSpecific(); } /// <summary> /// Timer to run a specific text file as console commands. Configured in in the main ini file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RunAutoTimerScript(object sender, EventArgs e) { if (m_timedScript != "disabled") { RunCommandScript(m_timedScript); } } private void WatchdogTimeoutHandler(Watchdog.ThreadWatchdogInfo twi) { int now = Environment.TickCount & Int32.MaxValue; m_log.ErrorFormat( "[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago. {3}", twi.Thread.Name, twi.Thread.ThreadState, now - twi.LastTick, twi.AlarmMethod != null ? string.Format("Data: {0}", twi.AlarmMethod()) : ""); } #region Console Commands /// <summary> /// Kicks users off the region /// </summary> /// <param name="module"></param> /// <param name="cmdparams">name of avatar to kick</param> private void KickUserCommand(string module, string[] cmdparams) { bool force = false; OptionSet options = new OptionSet().Add("f|force", delegate (string v) { force = v != null; }); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 4) return; string alert = null; if (mainParams.Count > 4) alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4)); IList agents = SceneManager.GetCurrentSceneAvatars(); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; if (presence.Firstname.ToLower().Equals(mainParams[2].ToLower()) && presence.Lastname.ToLower().Equals(mainParams[3].ToLower())) { MainConsole.Instance.Output( String.Format( "Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}", presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName)); // kick client... if (alert != null) presence.ControllingClient.Kick(alert); else presence.ControllingClient.Kick("\nYou have been logged out by an administrator.\n"); presence.Scene.CloseAgent(presence.UUID, force); break; } } MainConsole.Instance.Output(""); } /// <summary> /// Opens a file and uses it as input to the console command parser. /// </summary> /// <param name="fileName">name of file to use as input to the console</param> private static void PrintFileToConsole(string fileName) { if (File.Exists(fileName)) { StreamReader readFile = File.OpenText(fileName); string currentLine; while ((currentLine = readFile.ReadLine()) != null) { m_log.Info("[!]" + currentLine); } } } /// <summary> /// Force resending of all updates to all clients in active region(s) /// </summary> /// <param name="module"></param> /// <param name="args"></param> private void HandleForceUpdate(string module, string[] args) { MainConsole.Instance.Output("Updating all clients"); SceneManager.ForceCurrentSceneClientUpdate(); } /// <summary> /// Edits the scale of a primative with the name specified /// </summary> /// <param name="module"></param> /// <param name="args">0,1, name, x, y, z</param> private void HandleEditScale(string module, string[] args) { if (args.Length == 6) { SceneManager.HandleEditCommandOnCurrentScene(args); } else { MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>"); } } private void HandleRotateScene(string module, string[] args) { string usage = "Usage: rotate scene <angle in degrees> [centerX centerY] (centerX and centerY are optional and default to Constants.RegionSize / 2"; float centerX = Constants.RegionSize * 0.5f; float centerY = Constants.RegionSize * 0.5f; if (args.Length < 3 || args.Length == 4) { MainConsole.Instance.Output(usage); return; } float angle = (float)(Convert.ToSingle(args[2]) / 180.0 * Math.PI); OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, angle); if (args.Length > 4) { centerX = Convert.ToSingle(args[3]); centerY = Convert.ToSingle(args[4]); } Vector3 center = new Vector3(centerX, centerY, 0.0f); SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) { sog.RootPart.UpdateRotation(rot * sog.GroupRotation); Vector3 offset = sog.AbsolutePosition - center; offset *= rot; sog.UpdateGroupPosition(center + offset); } }); }); } private void HandleScaleScene(string module, string[] args) { string usage = "Usage: scale scene <factor>"; if (args.Length < 3) { MainConsole.Instance.Output(usage); return; } float factor = (float)(Convert.ToSingle(args[2])); float minZ = float.MaxValue; SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) { if (sog.RootPart.AbsolutePosition.Z < minZ) minZ = sog.RootPart.AbsolutePosition.Z; } }); }); SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) { Vector3 tmpRootPos = sog.RootPart.AbsolutePosition; tmpRootPos.Z -= minZ; tmpRootPos *= factor; tmpRootPos.Z += minZ; foreach (SceneObjectPart sop in sog.Parts) { if (sop.ParentID != 0) sop.OffsetPosition *= factor; sop.Scale *= factor; } sog.UpdateGroupPosition(tmpRootPos); } }); }); } private void HandleTranslateScene(string module, string[] args) { string usage = "Usage: translate scene <xOffset, yOffset, zOffset>"; if (args.Length < 5) { MainConsole.Instance.Output(usage); return; } float xOFfset = (float)Convert.ToSingle(args[2]); float yOffset = (float)Convert.ToSingle(args[3]); float zOffset = (float)Convert.ToSingle(args[4]); Vector3 offset = new Vector3(xOFfset, yOffset, zOffset); SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) sog.UpdateGroupPosition(sog.AbsolutePosition + offset); }); }); } /// <summary> /// Creates a new region based on the parameters specified. This will ask the user questions on the console /// </summary> /// <param name="module"></param> /// <param name="cmd">0,1,region name, region ini or XML file</param> private void HandleCreateRegion(string module, string[] cmd) { string regionName = string.Empty; string regionFile = string.Empty; if (cmd.Length == 3) { regionFile = cmd[2]; } else if (cmd.Length > 3) { regionName = cmd[2]; regionFile = cmd[3]; } string extension = Path.GetExtension(regionFile).ToLower(); bool isXml = extension.Equals(".xml"); bool isIni = extension.Equals(".ini"); if (!isXml && !isIni) { MainConsole.Instance.Output("Usage: create region [\"region name\"] <region_file.ini>"); return; } if (!Path.IsPathRooted(regionFile)) { string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim(); regionFile = Path.Combine(regionsDir, regionFile); } RegionInfo regInfo; if (isXml) { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source); } else { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source, regionName); } Scene existingScene; if (SceneManager.TryGetScene(regInfo.RegionID, out existingScene)) { MainConsole.Instance.OutputFormat( "ERROR: Cannot create region {0} with ID {1}, this ID is already assigned to region {2}", regInfo.RegionName, regInfo.RegionID, existingScene.RegionInfo.RegionName); return; } bool changed = PopulateRegionEstateInfo(regInfo); IScene scene; CreateRegion(regInfo, true, out scene); if (changed) m_estateDataService.StoreEstateSettings(regInfo.EstateSettings); scene.Start(); } /// <summary> /// Runs commands issued by the server console from the operator /// </summary> /// <param name="command">The first argument of the parameter (the command)</param> /// <param name="cmdparams">Additional arguments passed to the command</param> public void RunCommand(string module, string[] cmdparams) { List<string> args = new List<string>(cmdparams); if (args.Count < 1) return; string command = args[0]; args.RemoveAt(0); cmdparams = args.ToArray(); switch (command) { case "backup": MainConsole.Instance.Output("Triggering save of pending object updates to persistent store"); SceneManager.BackupCurrentScene(); break; case "remove-region": string regRemoveName = CombineParams(cmdparams, 0); Scene removeScene; if (SceneManager.TryGetScene(regRemoveName, out removeScene)) RemoveRegion(removeScene, false); else MainConsole.Instance.Output("No region with that name"); break; case "delete-region": string regDeleteName = CombineParams(cmdparams, 0); Scene killScene; if (SceneManager.TryGetScene(regDeleteName, out killScene)) RemoveRegion(killScene, true); else MainConsole.Instance.Output("no region with that name"); break; case "restart": SceneManager.RestartCurrentScene(); break; } } /// <summary> /// Change the currently selected region. The selected region is that operated upon by single region commands. /// </summary> /// <param name="cmdParams"></param> protected void ChangeSelectedRegion(string module, string[] cmdparams) { if (cmdparams.Length > 2) { string newRegionName = CombineParams(cmdparams, 2); if (!SceneManager.TrySetCurrentScene(newRegionName)) MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName)); else RefreshPrompt(); } else { MainConsole.Instance.Output("Usage: change region <region name>"); } } /// <summary> /// Refreshs prompt with the current selection details. /// </summary> private void RefreshPrompt() { string regionName = (SceneManager.CurrentScene == null ? "root" : SceneManager.CurrentScene.RegionInfo.RegionName); MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName)); // m_log.DebugFormat("Original prompt is {0}", m_consolePrompt); string prompt = m_consolePrompt; // Replace "\R" with the region name // Replace "\\" with "\" prompt = m_consolePromptRegex.Replace(prompt, m => { // m_log.DebugFormat("Matched {0}", m.Groups[2].Value); if (m.Groups[2].Value == "R") return m.Groups[1].Value + regionName; else return m.Groups[0].Value; }); m_console.DefaultPrompt = prompt; m_console.ConsoleScene = SceneManager.CurrentScene; } protected override void HandleRestartRegion(RegionInfo whichRegion) { base.HandleRestartRegion(whichRegion); // Where we are restarting multiple scenes at once, a previous call to RefreshPrompt may have set the // m_console.ConsoleScene to null (indicating all scenes). if (m_console.ConsoleScene != null && whichRegion.RegionName == ((Scene)m_console.ConsoleScene).Name) SceneManager.TrySetCurrentScene(whichRegion.RegionName); RefreshPrompt(); } // see BaseOpenSimServer /// <summary> /// Many commands list objects for debugging. Some of the types are listed here /// </summary> /// <param name="mod"></param> /// <param name="cmd"></param> public override void HandleShow(string mod, string[] cmd) { base.HandleShow(mod, cmd); List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "users": IList agents; if (showParams.Length > 1 && showParams[1] == "full") { agents = SceneManager.GetCurrentScenePresences(); } else { agents = SceneManager.GetCurrentSceneAvatars(); } MainConsole.Instance.Output(String.Format("\nAgents connected: {0}\n", agents.Count)); MainConsole.Instance.Output( String.Format("{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", "Firstname", "Lastname", "Agent ID", "Root/Child", "Region", "Position") ); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; string regionName; if (regionInfo == null) { regionName = "Unresolvable"; } else { regionName = regionInfo.RegionName; } MainConsole.Instance.Output( String.Format( "{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", presence.Firstname, presence.Lastname, presence.UUID, presence.IsChildAgent ? "Child" : "Root", regionName, presence.AbsolutePosition.ToString()) ); } MainConsole.Instance.Output(String.Empty); break; case "connections": HandleShowConnections(); break; case "circuits": HandleShowCircuits(); break; case "modules": SceneManager.ForEachSelectedScene( scene => { MainConsole.Instance.OutputFormat("Loaded region modules in {0} are:", scene.Name); List<IRegionModuleBase> sharedModules = new List<IRegionModuleBase>(); List<IRegionModuleBase> nonSharedModules = new List<IRegionModuleBase>(); foreach (IRegionModuleBase module in scene.RegionModules.Values) { if (module.GetType().GetInterface("ISharedRegionModule") == null) nonSharedModules.Add(module); else sharedModules.Add(module); } foreach (IRegionModuleBase module in sharedModules.OrderBy(m => m.Name)) MainConsole.Instance.OutputFormat("New Region Module (Shared): {0}", module.Name); foreach (IRegionModuleBase module in nonSharedModules.OrderBy(m => m.Name)) MainConsole.Instance.OutputFormat("New Region Module (Non-Shared): {0}", module.Name); } ); MainConsole.Instance.Output(""); break; case "regions": ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Name", ConsoleDisplayUtil.RegionNameSize); cdt.AddColumn("ID", ConsoleDisplayUtil.UuidSize); cdt.AddColumn("Position", ConsoleDisplayUtil.CoordTupleSize); cdt.AddColumn("Size", 11); cdt.AddColumn("Port", ConsoleDisplayUtil.PortSize); cdt.AddColumn("Ready?", 6); cdt.AddColumn("Estate", ConsoleDisplayUtil.EstateNameSize); SceneManager.ForEachScene( scene => { RegionInfo ri = scene.RegionInfo; cdt.AddRow( ri.RegionName, ri.RegionID, string.Format("{0},{1}", ri.RegionLocX, ri.RegionLocY), string.Format("{0}x{1}", ri.RegionSizeX, ri.RegionSizeY), ri.InternalEndPoint.Port, scene.Ready ? "Yes" : "No", ri.EstateSettings.EstateName); } ); MainConsole.Instance.Output(cdt.ToString()); break; case "ratings": SceneManager.ForEachScene( delegate(Scene scene) { string rating = ""; if (scene.RegionInfo.RegionSettings.Maturity == 1) { rating = "MATURE"; } else if (scene.RegionInfo.RegionSettings.Maturity == 2) { rating = "ADULT"; } else { rating = "PG"; } MainConsole.Instance.Output(String.Format( "Region Name: {0}, Region Rating {1}", scene.RegionInfo.RegionName, rating)); }); break; } } private void HandleShowCircuits() { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Region", 20); cdt.AddColumn("Avatar name", 24); cdt.AddColumn("Type", 5); cdt.AddColumn("Code", 10); cdt.AddColumn("IP", 16); cdt.AddColumn("Viewer Name", 24); SceneManager.ForEachScene( s => { foreach (AgentCircuitData aCircuit in s.AuthenticateHandler.GetAgentCircuits().Values) cdt.AddRow( s.Name, aCircuit.Name, aCircuit.child ? "child" : "root", aCircuit.circuitcode.ToString(), aCircuit.IPAddress != null ? aCircuit.IPAddress.ToString() : "not set", Util.GetViewerName(aCircuit)); }); MainConsole.Instance.Output(cdt.ToString()); } private void HandleShowConnections() { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Region", 20); cdt.AddColumn("Avatar name", 24); cdt.AddColumn("Circuit code", 12); cdt.AddColumn("Endpoint", 23); cdt.AddColumn("Active?", 7); cdt.AddColumn("ChildAgent?", 7); cdt.AddColumn("ping(ms)", 8); SceneManager.ForEachScene( s => s.ForEachClient( c => { bool child = false; if(c.SceneAgent != null && c.SceneAgent.IsChildAgent) child = true; cdt.AddRow( s.Name, c.Name, c.CircuitCode.ToString(), c.RemoteEndPoint.ToString(), c.IsActive.ToString(), child.ToString(), c.PingTimeMS); })); MainConsole.Instance.Output(cdt.ToString()); } /// <summary> /// Use XML2 format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SavePrimsXml2(string module, string[] cmdparams) { if (cmdparams.Length > 5) { SceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]); } else { SceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Use XML format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, save-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use save-xml2, please file a mantis detailing the reason."); if (cmdparams.Length > 0) { SceneManager.SaveCurrentSceneToXml(cmdparams[2]); } else { SceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Loads data and region objects from XML format. /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, load-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use load-xml2, please file a mantis detailing the reason."); Vector3 loadOffset = new Vector3(0, 0, 0); if (cmdparams.Length > 2) { bool generateNewIDS = false; if (cmdparams.Length > 3) { if (cmdparams[3] == "-newUID") { generateNewIDS = true; } if (cmdparams.Length > 4) { loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo); if (cmdparams.Length > 5) { loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo); } if (cmdparams.Length > 6) { loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo); } MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z)); } } SceneManager.LoadCurrentSceneFromXml(cmdparams[2], generateNewIDS, loadOffset); } else { try { SceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>"); } } } /// <summary> /// Serialize region data to XML2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { SceneManager.SaveCurrentSceneToXml2(cmdparams[2]); } else { SceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Load region data from Xml2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { try { SceneManager.LoadCurrentSceneFromXml2(cmdparams[2]); } catch (FileNotFoundException) { MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>"); } } else { try { SceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>"); } } } /// <summary> /// Load a whole region from an opensimulator archive. /// </summary> /// <param name="cmdparams"></param> protected void LoadOar(string module, string[] cmdparams) { try { SceneManager.LoadArchiveToCurrentScene(cmdparams); } catch (Exception e) { MainConsole.Instance.Output(e.Message); } } /// <summary> /// Save a region to a file, including all the assets needed to restore it. /// </summary> /// <param name="cmdparams"></param> protected void SaveOar(string module, string[] cmdparams) { SceneManager.SaveCurrentSceneToArchive(cmdparams); } protected void CreateEstateCommand(string module, string[] args) { string response = null; UUID userID; if (args.Length == 2) { response = "No user specified."; } else if (!UUID.TryParse(args[2], out userID)) { response = String.Format("{0} is not a valid UUID", args[2]); } else if (args.Length == 3) { response = "No estate name specified."; } else { Scene scene = SceneManager.CurrentOrFirstScene; // TODO: Is there a better choice here? UUID scopeID = UUID.Zero; UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, userID); if (account == null) { response = String.Format("Could not find user {0}", userID); } else { // concatenate it all to "name" StringBuilder sb = new StringBuilder(args[3]); for (int i = 4; i < args.Length; i++) sb.Append (" " + args[i]); string estateName = sb.ToString().Trim(); // send it off for processing. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); response = estateModule.CreateEstate(estateName, userID); if (response == String.Empty) { List<int> estates = scene.EstateDataService.GetEstates(estateName); response = String.Format("Estate {0} created as \"{1}\"", estates.ElementAt(0), estateName); } } } // give the user some feedback if (response != null) MainConsole.Instance.Output(response); } protected void SetEstateOwnerCommand(string module, string[] args) { string response = null; Scene scene = SceneManager.CurrentOrFirstScene; IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); if (args.Length == 3) { response = "No estate specified."; } else { int estateId; if (!int.TryParse(args[3], out estateId)) { response = String.Format("\"{0}\" is not a valid ID for an Estate", args[3]); } else { if (args.Length == 4) { response = "No user specified."; } else { UserAccount account = null; // TODO: Is there a better choice here? UUID scopeID = UUID.Zero; string s1 = args[4]; if (args.Length == 5) { // attempt to get account by UUID UUID u; if (UUID.TryParse(s1, out u)) { account = scene.UserAccountService.GetUserAccount(scopeID, u); if (account == null) response = String.Format("Could not find user {0}", s1); } else { response = String.Format("Invalid UUID {0}", s1); } } else { // attempt to get account by Firstname, Lastname string s2 = args[5]; account = scene.UserAccountService.GetUserAccount(scopeID, s1, s2); if (account == null) response = String.Format("Could not find user {0} {1}", s1, s2); } // If it's valid, send it off for processing. if (account != null) response = estateModule.SetEstateOwner(estateId, account); if (response == String.Empty) { response = String.Format("Estate owner changed to {0} ({1} {2})", account.PrincipalID, account.FirstName, account.LastName); } } } } // give the user some feedback if (response != null) MainConsole.Instance.Output(response); } protected void SetEstateNameCommand(string module, string[] args) { string response = null; Scene scene = SceneManager.CurrentOrFirstScene; IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); if (args.Length == 3) { response = "No estate specified."; } else { int estateId; if (!int.TryParse(args[3], out estateId)) { response = String.Format("\"{0}\" is not a valid ID for an Estate", args[3]); } else { if (args.Length == 4) { response = "No name specified."; } else { // everything after the estate ID is "name" StringBuilder sb = new StringBuilder(args[4]); for (int i = 5; i < args.Length; i++) sb.Append (" " + args[i]); string estateName = sb.ToString(); // send it off for processing. response = estateModule.SetEstateName(estateId, estateName); if (response == String.Empty) { response = String.Format("Estate {0} renamed to \"{1}\"", estateId, estateName); } } } } // give the user some feedback if (response != null) MainConsole.Instance.Output(response); } private void EstateLinkRegionCommand(string module, string[] args) { int estateId =-1; UUID regionId = UUID.Zero; Scene scene = null; string response = null; if (args.Length == 3) { response = "No estate specified."; } else if (!int.TryParse(args [3], out estateId)) { response = String.Format("\"{0}\" is not a valid ID for an Estate", args [3]); } else if (args.Length == 4) { response = "No region specified."; } else if (!UUID.TryParse(args[4], out regionId)) { response = String.Format("\"{0}\" is not a valid UUID for a Region", args [4]); } else if (!SceneManager.TryGetScene(regionId, out scene)) { // region may exist, but on a different sim. response = String.Format("No access to Region \"{0}\"", args [4]); } if (response != null) { MainConsole.Instance.Output(response); return; } // send it off for processing. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); response = estateModule.SetRegionEstate(scene.RegionInfo, estateId); if (response == String.Empty) { estateModule.TriggerRegionInfoChange(); estateModule.sendRegionHandshakeToAll(); response = String.Format ("Region {0} is now attached to estate {1}", regionId, estateId); } // give the user some feedback if (response != null) MainConsole.Instance.Output (response); } #endregion private static string CombineParams(string[] commandParams, int pos) { string result = String.Empty; for (int i = pos; i < commandParams.Length; i++) { result += commandParams[i] + " "; } result = result.TrimEnd(' '); return result; } } }
// 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. //----------------------------------------------------------------------------- // // Description: // This is a base abstract class for PackagePart. This is a part of the // Packaging Layer // //----------------------------------------------------------------------------- using System; using System.IO; using System.Collections; using System.Collections.Generic; // For List <> using System.Diagnostics; // For Debug.Assert namespace System.IO.Packaging { /// <summary> /// This class represents the a PackagePart within a container. /// This is a part of the Packaging Layer APIs /// </summary> public abstract class PackagePart { //------------------------------------------------------ // // Public Constructors // //------------------------------------------------------ #region Protected Constructor /// <summary> /// Protected constructor for the abstract Base class. /// This is the current contract between the subclass and the base class /// If we decide some registration mechanism then this might change /// /// You should use this constructor in the rare case when you do not have /// the content type information related to this part and would prefer to /// obtain it later as required. /// /// These parts have the CompressionOption as NotCompressed by default. /// /// NOTE : If you are using this constructor from your subclass or passing a null /// for the content type parameter, be sure to implement the GetContentTypeCore /// method, as that will be called to get the content type value. This is provided /// to enable lazy initialization of the ContentType property. /// /// </summary> /// <param name="package">Package in which this part is being created</param> /// <param name="partUri">uri of the part</param> /// <exception cref="ArgumentNullException">If parameter "package" is null</exception> /// <exception cref="ArgumentNullException">If parameter "partUri" is null</exception> protected PackagePart(Package package, Uri partUri) : this(package, partUri, null, CompressionOption.NotCompressed) { } /// <summary> /// Protected constructor for the abstract Base class. /// This is the current contract between the subclass and the base class /// If we decide some registration mechanism then this might change /// /// These parts have the CompressionOption as NotCompressed by default. /// /// NOTE : If you are using this constructor from your subclass or passing a null /// for the content type parameter, be sure to implement the GetContentTypeCore /// method, as that will be called to get the content type value. This is provided /// to enable lazy initialization of the ContentType property. /// /// </summary> /// <param name="package">Package in which this part is being created</param> /// <param name="partUri">uri of the part</param> /// <param name="contentType">Content Type of the part, can be null if the value /// is unknown at the time of construction. However the value has to be made /// available anytime the ContentType property is called. A null value only indicates /// that the value will be provided later. Every PackagePart must have a valid /// Content Type</param> /// <exception cref="ArgumentNullException">If parameter "package" is null</exception> /// <exception cref="ArgumentNullException">If parameter "partUri" is null</exception> /// <exception cref="ArgumentException">If parameter "partUri" does not conform to the valid partUri syntax</exception> protected PackagePart(Package package, Uri partUri, string contentType) : this(package, partUri, contentType, CompressionOption.NotCompressed) { } /// <summary> /// Protected constructor for the abstract Base class. /// This is the current contract between the subclass and the base class /// If we decide some registration mechanism then this might change /// /// NOTE : If you are using this constructor from your subclass or passing a null /// for the content type parameter, be sure to implement the GetContentTypeCore /// method, as that will be called to get the content type value. This is provided /// to enable lazy initialization of the ContentType property. /// /// </summary> /// <param name="package">Package in which this part is being created</param> /// <param name="partUri">uri of the part</param> /// <param name="contentType">Content Type of the part, can be null if the value /// is unknown at the time of construction. However the value has to be made /// available anytime the ContentType property is called. A null value only indicates /// that the value will be provided later. Every PackagePart must have a valid /// Content Type</param> /// <param name="compressionOption">compression option for this part</param> /// <exception cref="ArgumentNullException">If parameter "package" is null</exception> /// <exception cref="ArgumentNullException">If parameter "partUri" is null</exception> /// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception> /// <exception cref="ArgumentException">If parameter "partUri" does not conform to the valid partUri syntax</exception> protected PackagePart(Package package, Uri partUri, string contentType, CompressionOption compressionOption) { if (package == null) throw new ArgumentNullException(nameof(package)); if (partUri == null) throw new ArgumentNullException(nameof(partUri)); Package.ThrowIfCompressionOptionInvalid(compressionOption); _uri = PackUriHelper.ValidatePartUri(partUri); _container = package; if (contentType == null) _contentType = null; else _contentType = new ContentType(contentType); _requestedStreams = null; _compressionOption = compressionOption; _isRelationshipPart = PackUriHelper.IsRelationshipPartUri(partUri); } #endregion Protected Constructor //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// The Uri for this PackagePart. It is always relative to the Package Root /// The PackagePart properties can not be accessed if the parent container is closed. /// </summary> /// <value></value> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> public Uri Uri { get { CheckInvalidState(); return _uri; } } /// <summary> /// The Content type of the stream that is represented by this part. /// The PackagePart properties can not be accessed if the parent container is closed. /// The content type value can be provided by the underlying physical format /// implementation at the time of creation of the Part object ( constructor ) or /// We can initialize it in a lazy manner when the ContentType property is called /// called for the first time by calling the GetContentTypeCore method. /// Note: This method GetContentTypeCore() is only for lazy initialization of the Content /// type value and will only be called once. There is no way to change the content type of /// the part once it has been assigned. /// </summary> /// <value>Content Type of the Part [can never return null] </value> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="InvalidOperationException">If the subclass fails to provide a non-null content type value.</exception> public string ContentType { get { CheckInvalidState(); if (_contentType == null) { //Lazy initialization for the content type string contentType = GetContentTypeCore(); if (contentType == null) { // We have seen this bug in the past and have said that this should be // treated as exception. If we get a null content type, it's an error. // We want to throw this exception so that anyone sub-classing this class // should not be setting the content type to null. Its like any other // parameter validation. This is the only place we can validate it. We // throw an ArgumentNullException, when the content type is set to null // in the constructor. // // We cannot get rid of this exception. At most, we can change it to // Debug.Assert. But then client code will see an Assert if they make // a mistake and that is also not desirable. // // PackagePart is a public API. throw new InvalidOperationException(SR.NullContentTypeProvided); } _contentType = new ContentType(contentType); } return _contentType.ToString(); } } /// <summary> /// The parent container for this PackagePart /// The PackagePart properties can not be accessed if the parent container is closed. /// </summary> /// <value></value> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> public Package Package { get { CheckInvalidState(); return _container; } } /// <summary> /// CompressionOption class that was provided as a parameter during the original CreatePart call. /// The PackagePart properties can not be accessed if the parent container is closed. /// </summary> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> public CompressionOption CompressionOption { get { CheckInvalidState(); return _compressionOption; } } #endregion Public Properties //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods #region Content Type Method /// <summary> /// Custom Implementation for the GetContentType Method /// This method should only be implemented by those physical format implementors where /// the value for the content type cannot be provided at the time of construction of /// Part object and if calculating the content type value is a non-trivial or costly /// operation. The return value has to be a valid ContentType. This method will be used in /// real corner cases. The most common usage should be to provide the content type in the /// constructor. /// This method is only for lazy initialization of the Content type value and will only /// be called once. There is no way to change the content type of the part once it is /// assigned. /// </summary> /// <returns>Content type for the Part</returns> /// <exception cref="NotSupportedException">By default, this method throws a NotSupportedException. If a subclass wants to /// initialize the content type for a PackagePart in a lazy manner they must override this method.</exception> protected virtual string GetContentTypeCore() { throw new NotSupportedException(SR.GetContentTypeCoreNotImplemented); } #endregion Content Type Method #region Stream Methods /// <summary> /// Returns the underlying stream that is represented by this part /// with the default FileMode and FileAccess /// Note: If you are requesting a stream for a relationship part and /// at the same time using relationship APIs to manipulate relationships, /// the final persisted data will depend on which data gets flushed last. /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the subclass fails to provide a non-null stream object</exception> public Stream GetStream() { CheckInvalidState(); return GetStream(FileMode.OpenOrCreate, _container.FileOpenAccess); } /// <summary> /// Returns the underlying stream in the specified mode and the /// default FileAccess /// Note: If you are requesting a stream for a relationship part for editing /// and at the same time using relationship APIs to manipulate relationships, /// the final persisted data will depend on which data gets flushed last. /// </summary> /// <param name="mode"></param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [mode] does not have one of the valid values</exception> /// <exception cref="IOException">If FileAccess.Read is provided and FileMode values are any of the following - /// FileMode.Create, FileMode.CreateNew, FileMode.Truncate, FileMode.Append</exception> /// <exception cref="IOException">If the mode and access for the Package and the Stream are not compatible</exception> /// <exception cref="IOException">If the subclass fails to provide a non-null stream object</exception> public Stream GetStream(FileMode mode) { CheckInvalidState(); return GetStream(mode, _container.FileOpenAccess); } /// <summary> /// Returns the underlying stream that is represented by this part /// in the specified mode with the access. /// Note: If you are requesting a stream for a relationship part and /// at the same time using relationship APIs to manipulate relationships, /// the final persisted data will depend on which data gets flushed last. /// </summary> /// <param name="mode"></param> /// <param name="access"></param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [mode] does not have one of the valid values</exception> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration [access] does not have one of the valid values</exception> /// <exception cref="IOException">If FileAccess.Read is provided and FileMode values are any of the following - /// FileMode.Create, FileMode.CreateNew, FileMode.Truncate, FileMode.Append</exception> /// <exception cref="IOException">If the mode and access for the Package and the Stream are not compatible</exception> /// <exception cref="IOException">If the subclass fails to provide a non-null stream object</exception> public Stream GetStream(FileMode mode, FileAccess access) { CheckInvalidState(); ThrowIfOpenAccessModesAreIncompatible(mode, access); if (mode == FileMode.CreateNew) throw new ArgumentException(SR.CreateNewNotSupported); if (mode == FileMode.Truncate) throw new ArgumentException(SR.TruncateNotSupported); Stream s = GetStreamCore(mode, access); if (s == null) throw new IOException(SR.NullStreamReturned); //Detect if any stream implementations are returning all three //properties - CanSeek, CanWrite and CanRead as false. Such a //stream should be pretty much useless. And as per current programming //practice, these properties are all false, when the stream has been //disposed. Debug.Assert(!IsStreamClosed(s)); //Lazy init if (_requestedStreams == null) _requestedStreams = new List<Stream>(); //Default capacity is 4 //Delete all the closed streams from the _requestedStreams list. //Each time a new stream is handed out, we go through the list //to clean up streams that were handed out and have been closed. //Thus those stream can be garbage collected and we will avoid //keeping around stream objects that have been disposed CleanUpRequestedStreamsList(); _requestedStreams.Add(s); return s; } /// <summary> /// Custom Implementation for the GetSream Method /// </summary> /// <param name="mode"></param> /// <param name="access"></param> /// <returns></returns> protected abstract Stream GetStreamCore(FileMode mode, FileAccess access); #endregion Stream Methods #region PackageRelationship Methods /// <summary> /// Adds a relationship to this PackagePart with the Target PackagePart specified as the Uri /// Initial and trailing spaces in the name of the PackageRelationship are trimmed. /// </summary> /// <param name="targetUri"></param> /// <param name="targetMode">Enumeration indicating the base uri for the target uri</param> /// <param name="relationshipType">PackageRelationship type, having uri like syntax that is used to /// uniquely identify the role of the relationship</param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "targetUri" is null</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentOutOfRangeException">If parameter "targetMode" enumeration does not have a valid value</exception> /// <exception cref="ArgumentException">If TargetMode is TargetMode.Internal and the targetUri is an absolute Uri </exception> /// <exception cref="ArgumentException">If relationship is being targeted to a relationship part</exception> public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType) { return CreateRelationship(targetUri, targetMode, relationshipType, null); } /// <summary> /// Adds a relationship to this PackagePart with the Target PackagePart specified as the Uri /// Initial and trailing spaces in the name of the PackageRelationship are trimmed. /// </summary> /// <param name="targetUri"></param> /// <param name="targetMode">Enumeration indicating the base uri for the target uri</param> /// <param name="relationshipType">PackageRelationship type, having uri like syntax that is used to /// uniquely identify the role of the relationship</param> /// <param name="id">String that conforms to the xsd:ID datatype. Unique across the source's /// relationships. Null is OK (ID will be generated). An empty string is an invalid XML ID.</param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "targetUri" is null</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentOutOfRangeException">If parameter "targetMode" enumeration does not have a valid value</exception> /// <exception cref="ArgumentException">If TargetMode is TargetMode.Internal and the targetUri is an absolute Uri </exception> /// <exception cref="ArgumentException">If relationship is being targeted to a relationship part</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> /// <exception cref="System.Xml.XmlException">If an id is provided in the method, and its not unique</exception> public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType, String id) { CheckInvalidState(); _container.ThrowIfReadOnly(); EnsureRelationships(); //All parameter validation is done in the following method return _relationships.Add(targetUri, targetMode, relationshipType, id); } /// <summary> /// Deletes a relationship from the PackagePart. This is done based on the /// relationship's ID. The target PackagePart is not affected by this operation. /// </summary> /// <param name="id">The ID of the relationship to delete. An invalid ID will not /// throw an exception, but nothing will be deleted.</param> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> public void DeleteRelationship(string id) { CheckInvalidState(); _container.ThrowIfReadOnly(); if (id == null) throw new ArgumentNullException(nameof(id)); InternalRelationshipCollection.ThrowIfInvalidXsdId(id); EnsureRelationships(); _relationships.Delete(id); } /// <summary> /// Returns a collection of all the Relationships that are /// owned by this PackagePart /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> public PackageRelationshipCollection GetRelationships() { //All the validations for dispose and file access are done in the //GetRelationshipsHelper method. return GetRelationshipsHelper(null); } /// <summary> /// Returns a collection of filtered Relationships that are /// owned by this PackagePart /// The relationshipType string is compared with the type of the relationships /// in a case sensitive and culture ignorant manner. /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentException">If parameter "relationshipType" is an empty string</exception> public PackageRelationshipCollection GetRelationshipsByType(string relationshipType) { //These checks are made in the GetRelationshipsHelper as well, but we make them //here as we need to perform parameter validation CheckInvalidState(); _container.ThrowIfWriteOnly(); if (relationshipType == null) throw new ArgumentNullException(nameof(relationshipType)); InternalRelationshipCollection.ThrowIfInvalidRelationshipType(relationshipType); return GetRelationshipsHelper(relationshipType); } /// <summary> /// Retrieve a relationship per ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>The relationship with ID 'id' or throw an exception if not found.</returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> /// <exception cref="InvalidOperationException">If the requested relationship does not exist in the Package</exception> public PackageRelationship GetRelationship(string id) { //All the validations for dispose and file access are done in the //GetRelationshipHelper method. PackageRelationship returnedRelationship = GetRelationshipHelper(id); if (returnedRelationship == null) throw new InvalidOperationException(SR.PackagePartRelationshipDoesNotExist); else return returnedRelationship; } /// <summary> /// Returns whether there is a relationship with the specified ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>true iff a relationship with ID 'id' is defined on this source.</returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> public bool RelationshipExists(string id) { //All the validations for dispose and file access are done in the //GetRelationshipHelper method. return (GetRelationshipHelper(id) != null); } #endregion PackageRelationship Methods #endregion Public Methods //------------------------------------------------------ // // Public Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties internal bool IsRelationshipPart { get { return _isRelationshipPart; } } //This property can be set to indicate if the part has been deleted internal bool IsDeleted { get { return _deleted; } set { _deleted = value; } } //This property can be set to indicate if the part has been deleted internal bool IsClosed { get { return _disposed; } } /// <summary> /// This property returns the content type of the part /// as a validated strongly typed ContentType object /// </summary> internal ContentType ValidatedContentType { get { return _contentType; } } #endregion Internal Properties //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods //Delete all the relationships for this part internal void ClearRelationships() { if (_relationships != null) _relationships.Clear(); } //Flush all the streams that are currently opened for this part and the relationships for this part //Note: This method is never be called on a deleted part internal void Flush() { Debug.Assert(_deleted != true, "PackagePart.Flush should never be called on a deleted part"); if (_requestedStreams != null) { foreach (Stream s in _requestedStreams) { // Streams in this list are never set to null, so we do not need to check for // stream being null; However it could be closed by some external code. In that case // this property (CanWrite) will still be accessible and we can check to see // whether we can call flush or no. if (s.CanWrite) s.Flush(); } } // Relationships for this part should have been flushed earlier in the Package.Flush method. } //Close all the streams that are open for this part. internal void Close() { if (!_disposed) { try { if (_requestedStreams != null) { //Adding this extra check here to optimize delete operation //Everytime we delete a part we close it before deleting to //ensure that its deleted in a valid state. However, we do not //need to persist any changes if the part is being deleted. if (!_deleted) { foreach (Stream s in _requestedStreams) { s.Dispose(); } } _requestedStreams.Clear(); } // Relationships for this part should have been flushed/closed earlier in the Package.Close method. } finally { _requestedStreams = null; //InternalRelationshipCollection is not required any more _relationships = null; //Once the container is closed there is no way to get to the stream or any other part //in the container. _container = null; //We do not need to explicitly call GC.SuppressFinalize(this) _disposed = true; } } } /// <summary> /// write the relationships part /// </summary> /// <remarks> /// </remarks> internal void FlushRelationships() { Debug.Assert(_deleted != true, "PackagePart.FlushRelationsips should never be called on a deleted part"); // flush relationships if (_relationships != null && _container.FileOpenAccess != FileAccess.Read) { _relationships.Flush(); } } internal void CloseRelationships() { if (!_deleted) { //Flush the relationships for this part. FlushRelationships(); } } #endregion Internal Methods //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // lazy init private void EnsureRelationships() { if (_relationships == null) { // check here ThrowIfRelationship(); // obtain the relationships from the PackageRelationship part (if available) _relationships = new InternalRelationshipCollection(this); } } //Make sure that the access modes for the container and the part are compatible private void ThrowIfOpenAccessModesAreIncompatible(FileMode mode, FileAccess access) { Package.ThrowIfFileModeInvalid(mode); Package.ThrowIfFileAccessInvalid(access); //Creating a part using a readonly stream. if (access == FileAccess.Read && (mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate || mode == FileMode.Append)) throw new IOException(SR.UnsupportedCombinationOfModeAccess); //Incompatible access modes between container and part stream. if ((_container.FileOpenAccess == FileAccess.Read && access != FileAccess.Read) || (_container.FileOpenAccess == FileAccess.Write && access != FileAccess.Write)) throw new IOException(SR.ContainerAndPartModeIncompatible); } //Check if the part is in an invalid state private void CheckInvalidState() { ThrowIfPackagePartDeleted(); ThrowIfParentContainerClosed(); } //If the parent container is closed then the operations on this part like getting stream make no sense private void ThrowIfParentContainerClosed() { if (_container == null) throw new InvalidOperationException(SR.ParentContainerClosed); } //If the part has been deleted then we throw private void ThrowIfPackagePartDeleted() { if (_deleted == true) throw new InvalidOperationException(SR.PackagePartDeleted); } // some operations are invalid if we are a relationship part private void ThrowIfRelationship() { if (IsRelationshipPart) throw new InvalidOperationException(SR.RelationshipPartsCannotHaveRelationships); } /// <summary> /// Retrieve a relationship per ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>The relationship with ID 'id' or null if not found.</returns> private PackageRelationship GetRelationshipHelper(string id) { CheckInvalidState(); _container.ThrowIfWriteOnly(); if (id == null) throw new ArgumentNullException(nameof(id)); InternalRelationshipCollection.ThrowIfInvalidXsdId(id); EnsureRelationships(); return _relationships.GetRelationship(id); } /// <summary> /// Returns a collection of all the Relationships that are /// owned by this PackagePart, based on the filter string /// </summary> /// <returns></returns> private PackageRelationshipCollection GetRelationshipsHelper(string filterString) { CheckInvalidState(); _container.ThrowIfWriteOnly(); EnsureRelationships(); //Internally null is used to indicate that no filter string was specified and //and all the relationships should be returned. return new PackageRelationshipCollection(_relationships, filterString); } //Deletes all the streams that have been closed from the _requestedStreams list. private void CleanUpRequestedStreamsList() { if (_requestedStreams != null) { for (int i = _requestedStreams.Count - 1; i >= 0; i--) { if (IsStreamClosed(_requestedStreams[i])) _requestedStreams.RemoveAt(i); } } } //Detect if the stream has been closed. //When a stream is closed the three flags - CanSeek, CanRead and CanWrite //return false. These properties do not throw ObjectDisposedException. //So we rely on the values of these properties to determine if a stream //has been closed. private bool IsStreamClosed(Stream s) { return !s.CanRead && !s.CanSeek && !s.CanWrite; } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Members private PackUriHelper.ValidatedPartUri _uri; private Package _container; private ContentType _contentType; private List<Stream> _requestedStreams; private InternalRelationshipCollection _relationships; private CompressionOption _compressionOption = CompressionOption.NotCompressed; private bool _disposed; private bool _deleted; private bool _isRelationshipPart; #endregion Private Members } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net; using System.Reflection; using System.Runtime.Remoting.Messaging; using System.Threading; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenMetaverse.StructuredData; using Mono.Addins; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.CoreModules.World.Land; using Caps=OpenSim.Framework.Capabilities.Caps; using OSDArray=OpenMetaverse.StructuredData.OSDArray; using OSDMap=OpenMetaverse.StructuredData.OSDMap; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.World.WorldMap { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WorldMapModule")] public class WorldMapModule : INonSharedRegionModule, IWorldMapModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #pragma warning disable 414 private static string LogHeader = "[WORLD MAP]"; #pragma warning restore 414 private static readonly string DEFAULT_WORLD_MAP_EXPORT_PATH = "exportmap.jpg"; private static readonly UUID STOP_UUID = UUID.Random(); private static readonly string m_mapLayerPath = "0001/"; private IMapImageGenerator m_mapImageGenerator; private IMapImageUploadModule m_mapImageServiceModule; private OpenSim.Framework.BlockingQueue<MapRequestState> requests = new OpenSim.Framework.BlockingQueue<MapRequestState>(); protected Scene m_scene; private List<MapBlockData> cachedMapBlocks = new List<MapBlockData>(); private int cachedTime = 0; private int blacklistTimeout = 10*60*1000; // 10 minutes private byte[] myMapImageJPEG; protected volatile bool m_Enabled = false; private Dictionary<UUID, MapRequestState> m_openRequests = new Dictionary<UUID, MapRequestState>(); private Dictionary<string, int> m_blacklistedurls = new Dictionary<string, int>(); private Dictionary<ulong, int> m_blacklistedregions = new Dictionary<ulong, int>(); private Dictionary<ulong, string> m_cachedRegionMapItemsAddress = new Dictionary<ulong, string>(); private List<UUID> m_rootAgents = new List<UUID>(); private volatile bool threadrunning = false; private IServiceThrottleModule m_ServiceThrottle; //private int CacheRegionsDistance = 256; #region INonSharedRegionModule Members public virtual void Initialise (IConfigSource config) { string[] configSections = new string[] { "Map", "Startup" }; if (Util.GetConfigVarFromSections<string>( config, "WorldMapModule", configSections, "WorldMap") == "WorldMap") m_Enabled = true; blacklistTimeout = Util.GetConfigVarFromSections<int>(config, "BlacklistTimeout", configSections, 10 * 60) * 1000; } public virtual void AddRegion(Scene scene) { if (!m_Enabled) return; lock (scene) { m_scene = scene; m_scene.RegisterModuleInterface<IWorldMapModule>(this); m_scene.AddCommand( "Regions", this, "export-map", "export-map [<path>]", "Save an image of the world map", HandleExportWorldMapConsoleCommand); m_scene.AddCommand( "Regions", this, "generate map", "generate map", "Generates and stores a new maptile.", HandleGenerateMapConsoleCommand); AddHandlers(); } } public virtual void RemoveRegion (Scene scene) { if (!m_Enabled) return; lock (m_scene) { m_Enabled = false; RemoveHandlers(); m_scene = null; } } public virtual void RegionLoaded (Scene scene) { if (!m_Enabled) return; m_ServiceThrottle = scene.RequestModuleInterface<IServiceThrottleModule>(); m_mapImageGenerator = m_scene.RequestModuleInterface<IMapImageGenerator>(); m_mapImageServiceModule = m_scene.RequestModuleInterface<IMapImageUploadModule>(); } public virtual void Close() { } public Type ReplaceableInterface { get { return null; } } public virtual string Name { get { return "WorldMapModule"; } } #endregion // this has to be called with a lock on m_scene protected virtual void AddHandlers() { myMapImageJPEG = new byte[0]; string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString(); regionimage = regionimage.Replace("-", ""); m_log.Info("[WORLD MAP]: JPEG Map location: " + m_scene.RegionInfo.ServerURI + "index.php?method=" + regionimage); MainServer.Instance.AddHTTPHandler(regionimage, new GenericHTTPDOSProtector(OnHTTPGetMapImage, OnHTTPThrottled, new BasicDosProtectorOptions() { AllowXForwardedFor = false, ForgetTimeSpan = TimeSpan.FromMinutes(2), MaxRequestsInTimeframe = 4, ReportingName = "MAPDOSPROTECTOR", RequestTimeSpan = TimeSpan.FromSeconds(10), ThrottledAction = BasicDOSProtector.ThrottleAction.DoThrottledMethod }).Process); MainServer.Instance.AddLLSDHandler( "/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(), HandleRemoteMapItemRequest); m_scene.EventManager.OnRegisterCaps += OnRegisterCaps; m_scene.EventManager.OnNewClient += OnNewClient; m_scene.EventManager.OnClientClosed += ClientLoggedOut; m_scene.EventManager.OnMakeChildAgent += MakeChildAgent; m_scene.EventManager.OnMakeRootAgent += MakeRootAgent; m_scene.EventManager.OnRegionUp += OnRegionUp; // StartThread(new object()); } // this has to be called with a lock on m_scene protected virtual void RemoveHandlers() { // StopThread(); m_scene.EventManager.OnRegionUp -= OnRegionUp; m_scene.EventManager.OnMakeRootAgent -= MakeRootAgent; m_scene.EventManager.OnMakeChildAgent -= MakeChildAgent; m_scene.EventManager.OnClientClosed -= ClientLoggedOut; m_scene.EventManager.OnNewClient -= OnNewClient; m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps; string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString(); regionimage = regionimage.Replace("-", ""); MainServer.Instance.RemoveLLSDHandler("/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(), HandleRemoteMapItemRequest); MainServer.Instance.RemoveHTTPHandler("", regionimage); } public void OnRegisterCaps(UUID agentID, Caps caps) { //m_log.DebugFormat("[WORLD MAP]: OnRegisterCaps: agentID {0} caps {1}", agentID, caps); string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler( "MapLayer", new RestStreamHandler( "POST", capsBase + m_mapLayerPath, (request, path, param, httpRequest, httpResponse) => MapLayerRequest(request, path, param, agentID, caps), "MapLayer", agentID.ToString())); } /// <summary> /// Callback for a map layer request /// </summary> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="agentID"></param> /// <param name="caps"></param> /// <returns></returns> public string MapLayerRequest(string request, string path, string param, UUID agentID, Caps caps) { //try // //m_log.DebugFormat("[MAPLAYER]: path: {0}, param: {1}, agent:{2}", // path, param, agentID.ToString()); // There is a major hack going on in this method. The viewer doesn't request // map blocks (RequestMapBlocks) above 2048. That means that if we don't hack, // grids above that cell don't have a map at all. So, here's the hack: we wait // for this CAP request to come, and we inject the map blocks at this point. // In a normal scenario, this request simply sends back the MapLayer (the blue color). // In the hacked scenario, it also sends the map blocks via UDP. // // 6/8/2011 -- I'm adding an explicit 2048 check, so that we never forget that there is // a hack here, and so that regions below 4096 don't get spammed with unnecessary map blocks. if (m_scene.RegionInfo.RegionLocX >= 2048 || m_scene.RegionInfo.RegionLocY >= 2048) { ScenePresence avatarPresence = null; m_scene.TryGetScenePresence(agentID, out avatarPresence); if (avatarPresence != null) { bool lookup = false; lock (cachedMapBlocks) { if (cachedMapBlocks.Count > 0 && ((cachedTime + 1800) > Util.UnixTimeSinceEpoch())) { List<MapBlockData> mapBlocks; mapBlocks = cachedMapBlocks; avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0); } else { lookup = true; } } if (lookup) { List<MapBlockData> mapBlocks = new List<MapBlockData>(); ; // Get regions that are within 8 regions of here List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID, (int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocX - 8), (int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocX + 8), (int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocY - 8), (int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocY + 8) ); foreach (GridRegion r in regions) { MapBlockData block = MapBlockFromGridRegion(r, 0); mapBlocks.Add(block); } avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0); lock (cachedMapBlocks) cachedMapBlocks = mapBlocks; cachedTime = Util.UnixTimeSinceEpoch(); } } } LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse(); mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse()); return mapResponse.ToString(); } /// <summary> /// /// </summary> /// <param name="mapReq"></param> /// <returns></returns> public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq) { // m_log.DebugFormat("[WORLD MAP]: MapLayer Request in region: {0}", m_scene.RegionInfo.RegionName); LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse(); mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse()); return mapResponse; } /// <summary> /// /// </summary> /// <returns></returns> protected static OSDMapLayer GetOSDMapLayerResponse() { OSDMapLayer mapLayer = new OSDMapLayer(); mapLayer.Right = 5000; mapLayer.Top = 5000; mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006"); return mapLayer; } #region EventHandlers /// <summary> /// Registered for event /// </summary> /// <param name="client"></param> private void OnNewClient(IClientAPI client) { client.OnRequestMapBlocks += RequestMapBlocks; client.OnMapItemRequest += HandleMapItemRequest; } /// <summary> /// Client logged out, check to see if there are any more root agents in the simulator /// If not, stop the mapItemRequest Thread /// Event handler /// </summary> /// <param name="AgentId">AgentID that logged out</param> private void ClientLoggedOut(UUID AgentId, Scene scene) { lock (m_rootAgents) { m_rootAgents.Remove(AgentId); } } #endregion /// <summary> /// Starts the MapItemRequest Thread /// Note that this only gets started when there are actually agents in the region /// Additionally, it gets stopped when there are none. /// </summary> /// <param name="o"></param> private void StartThread(object o) { if (threadrunning) return; threadrunning = true; // m_log.Debug("[WORLD MAP]: Starting remote MapItem request thread"); WorkManager.StartThread( process, string.Format("MapItemRequestThread ({0})", m_scene.RegionInfo.RegionName), ThreadPriority.BelowNormal, true, true); } /// <summary> /// Enqueues a 'stop thread' MapRequestState. Causes the MapItemRequest thread to end /// </summary> private void StopThread() { MapRequestState st = new MapRequestState(); st.agentID = STOP_UUID; st.EstateID=0; st.flags=0; st.godlike=false; st.itemtype=0; st.regionhandle=0; requests.Enqueue(st); } public virtual void HandleMapItemRequest(IClientAPI remoteClient, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { // m_log.DebugFormat("[WORLD MAP]: Handle MapItem request {0} {1}", regionhandle, itemtype); lock (m_rootAgents) { if (!m_rootAgents.Contains(remoteClient.AgentId)) return; } uint xstart = 0; uint ystart = 0; Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle, out xstart, out ystart); if (itemtype == (int)GridItemType.AgentLocations) { if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle) { // Just requesting map info about the current, local region int tc = Environment.TickCount; List<mapItemReply> mapitems = new List<mapItemReply>(); mapItemReply mapitem = new mapItemReply(); if (m_scene.GetRootAgentCount() <= 1) { mapitem = new mapItemReply( xstart + 1, ystart + 1, UUID.Zero, Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()), 0, 0); mapitems.Add(mapitem); } else { m_scene.ForEachRootScenePresence(delegate(ScenePresence sp) { // Don't send a green dot for yourself if (sp.UUID != remoteClient.AgentId) { mapitem = new mapItemReply( xstart + (uint)sp.AbsolutePosition.X, ystart + (uint)sp.AbsolutePosition.Y, UUID.Zero, Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()), 1, 0); mapitems.Add(mapitem); } }); } remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); } else { // Remote Map Item Request // ensures that the blockingqueue doesn't get borked if the GetAgents() timing changes. RequestMapItems("",remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle); } } else if (itemtype == (int)GridItemType.LandForSale) // Service 7 (MAP_ITEM_LAND_FOR_SALE) { if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle) { // Parcels ILandChannel landChannel = m_scene.LandChannel; List<ILandObject> parcels = landChannel.AllParcels(); // Local Map Item Request List<mapItemReply> mapitems = new List<mapItemReply>(); mapItemReply mapitem = new mapItemReply(); if ((parcels != null) && (parcels.Count >= 1)) { foreach (ILandObject parcel_interface in parcels) { // Play it safe if (!(parcel_interface is LandObject)) continue; LandObject land = (LandObject)parcel_interface; LandData parcel = land.LandData; // Show land for sale if ((parcel.Flags & (uint)ParcelFlags.ForSale) == (uint)ParcelFlags.ForSale) { Vector3 min = parcel.AABBMin; Vector3 max = parcel.AABBMax; float x = (min.X+max.X)/2; float y = (min.Y+max.Y)/2; mapitem = new mapItemReply( xstart + (uint)x, ystart + (uint)y, parcel.GlobalID, parcel.Name, parcel.Area, parcel.SalePrice ); mapitems.Add(mapitem); } } } remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); } else { // Remote Map Item Request // ensures that the blockingqueue doesn't get borked if the GetAgents() timing changes. RequestMapItems("",remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle); } } else if (itemtype == (int)GridItemType.Telehub) // Service 1 (MAP_ITEM_TELEHUB) { if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle) { List<mapItemReply> mapitems = new List<mapItemReply>(); mapItemReply mapitem = new mapItemReply(); SceneObjectGroup sog = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject); if (sog != null) { mapitem = new mapItemReply( xstart + (uint)sog.AbsolutePosition.X, ystart + (uint)sog.AbsolutePosition.Y, UUID.Zero, sog.Name, 0, // color (not used) 0 // 0 = telehub / 1 = infohub ); mapitems.Add(mapitem); remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); } } else { // Remote Map Item Request RequestMapItems("",remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle); } } } private int nAsyncRequests = 0; /// <summary> /// Processing thread main() loop for doing remote mapitem requests /// </summary> public void process() { //const int MAX_ASYNC_REQUESTS = 20; try { while (true) { MapRequestState st = requests.Dequeue(1000); // end gracefully if (st.agentID == STOP_UUID) break; if (st.agentID != UUID.Zero) { bool dorequest = true; lock (m_rootAgents) { if (!m_rootAgents.Contains(st.agentID)) dorequest = false; } if (dorequest && !m_blacklistedregions.ContainsKey(st.regionhandle)) { while (nAsyncRequests >= MAX_ASYNC_REQUESTS) // hit the break Thread.Sleep(80); RequestMapItemsDelegate d = RequestMapItemsAsync; d.BeginInvoke(st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle, RequestMapItemsCompleted, null); //OSDMap response = RequestMapItemsAsync(st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle); //RequestMapItemsCompleted(response); Interlocked.Increment(ref nAsyncRequests); } } Watchdog.UpdateThread(); } } catch (Exception e) { m_log.ErrorFormat("[WORLD MAP]: Map item request thread terminated abnormally with exception {0}", e); } threadrunning = false; Watchdog.RemoveThread(); } const int MAX_ASYNC_REQUESTS = 20; /// <summary> /// Enqueues the map item request into the services throttle processing thread /// </summary> /// <param name="state"></param> public void EnqueueMapItemRequest(MapRequestState st) { m_ServiceThrottle.Enqueue("map-item", st.regionhandle.ToString() + st.agentID.ToString(), delegate { if (st.agentID != UUID.Zero) { bool dorequest = true; lock (m_rootAgents) { if (!m_rootAgents.Contains(st.agentID)) dorequest = false; } if (dorequest && !m_blacklistedregions.ContainsKey(st.regionhandle)) { if (nAsyncRequests >= MAX_ASYNC_REQUESTS) // hit the break { // AH!!! Recursive ! // Put this request back in the queue and return EnqueueMapItemRequest(st); return; } RequestMapItemsDelegate d = RequestMapItemsAsync; d.BeginInvoke(st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle, RequestMapItemsCompleted, null); //OSDMap response = RequestMapItemsAsync(st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle); //RequestMapItemsCompleted(response); Interlocked.Increment(ref nAsyncRequests); } } }); } /// <summary> /// Sends the mapitem response to the IClientAPI /// </summary> /// <param name="response">The OSDMap Response for the mapitem</param> private void RequestMapItemsCompleted(IAsyncResult iar) { AsyncResult result = (AsyncResult)iar; RequestMapItemsDelegate icon = (RequestMapItemsDelegate)result.AsyncDelegate; OSDMap response = (OSDMap)icon.EndInvoke(iar); Interlocked.Decrement(ref nAsyncRequests); if (!response.ContainsKey("requestID")) return; UUID requestID = response["requestID"].AsUUID(); if (requestID != UUID.Zero) { MapRequestState mrs = new MapRequestState(); mrs.agentID = UUID.Zero; lock (m_openRequests) { if (m_openRequests.ContainsKey(requestID)) { mrs = m_openRequests[requestID]; m_openRequests.Remove(requestID); } } if (mrs.agentID != UUID.Zero) { ScenePresence av = null; m_scene.TryGetScenePresence(mrs.agentID, out av); if (av != null) { if (response.ContainsKey(mrs.itemtype.ToString())) { List<mapItemReply> returnitems = new List<mapItemReply>(); OSDArray itemarray = (OSDArray)response[mrs.itemtype.ToString()]; for (int i = 0; i < itemarray.Count; i++) { OSDMap mapitem = (OSDMap)itemarray[i]; mapItemReply mi = new mapItemReply(); mi.FromOSD(mapitem); returnitems.Add(mi); } av.ControllingClient.SendMapItemReply(returnitems.ToArray(), mrs.itemtype, mrs.flags); } // Service 7 (MAP_ITEM_LAND_FOR_SALE) uint itemtype = (uint)GridItemType.LandForSale; if (response.ContainsKey(itemtype.ToString())) { List<mapItemReply> returnitems = new List<mapItemReply>(); OSDArray itemarray = (OSDArray)response[itemtype.ToString()]; for (int i = 0; i < itemarray.Count; i++) { OSDMap mapitem = (OSDMap)itemarray[i]; mapItemReply mi = new mapItemReply(); mi.FromOSD(mapitem); returnitems.Add(mi); } av.ControllingClient.SendMapItemReply(returnitems.ToArray(), itemtype, mrs.flags); } // Service 1 (MAP_ITEM_TELEHUB) itemtype = (uint)GridItemType.Telehub; if (response.ContainsKey(itemtype.ToString())) { List<mapItemReply> returnitems = new List<mapItemReply>(); OSDArray itemarray = (OSDArray)response[itemtype.ToString()]; for (int i = 0; i < itemarray.Count; i++) { OSDMap mapitem = (OSDMap)itemarray[i]; mapItemReply mi = new mapItemReply(); mi.FromOSD(mapitem); returnitems.Add(mi); } av.ControllingClient.SendMapItemReply(returnitems.ToArray(), itemtype, mrs.flags); } } } } } /// <summary> /// Enqueue the MapItem request for remote processing /// </summary> /// <param name="httpserver">blank string, we discover this in the process</param> /// <param name="id">Agent ID that we are making this request on behalf</param> /// <param name="flags">passed in from packet</param> /// <param name="EstateID">passed in from packet</param> /// <param name="godlike">passed in from packet</param> /// <param name="itemtype">passed in from packet</param> /// <param name="regionhandle">Region we're looking up</param> public void RequestMapItems(string httpserver, UUID id, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { MapRequestState st = new MapRequestState(); st.agentID = id; st.flags = flags; st.EstateID = EstateID; st.godlike = godlike; st.itemtype = itemtype; st.regionhandle = regionhandle; EnqueueMapItemRequest(st); } private delegate OSDMap RequestMapItemsDelegate(UUID id, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle); /// <summary> /// Does the actual remote mapitem request /// This should be called from an asynchronous thread /// Request failures get blacklisted until region restart so we don't /// continue to spend resources trying to contact regions that are down. /// </summary> /// <param name="httpserver">blank string, we discover this in the process</param> /// <param name="id">Agent ID that we are making this request on behalf</param> /// <param name="flags">passed in from packet</param> /// <param name="EstateID">passed in from packet</param> /// <param name="godlike">passed in from packet</param> /// <param name="itemtype">passed in from packet</param> /// <param name="regionhandle">Region we're looking up</param> /// <returns></returns> private OSDMap RequestMapItemsAsync(UUID id, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { // m_log.DebugFormat("[WORLDMAP]: RequestMapItemsAsync; region handle: {0} {1}", regionhandle, itemtype); string httpserver = ""; bool blacklisted = false; lock (m_blacklistedregions) { if (m_blacklistedregions.ContainsKey(regionhandle)) { if (Environment.TickCount > (m_blacklistedregions[regionhandle] + blacklistTimeout)) { m_log.DebugFormat("[WORLD MAP]: Unblock blacklisted region {0}", regionhandle); m_blacklistedregions.Remove(regionhandle); } else blacklisted = true; } } if (blacklisted) return new OSDMap(); UUID requestID = UUID.Random(); lock (m_cachedRegionMapItemsAddress) { if (m_cachedRegionMapItemsAddress.ContainsKey(regionhandle)) httpserver = m_cachedRegionMapItemsAddress[regionhandle]; } if (httpserver.Length == 0) { uint x = 0, y = 0; Util.RegionHandleToWorldLoc(regionhandle, out x, out y); GridRegion mreg = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y); if (mreg != null) { httpserver = mreg.ServerURI + "MAP/MapItems/" + regionhandle.ToString(); lock (m_cachedRegionMapItemsAddress) { if (!m_cachedRegionMapItemsAddress.ContainsKey(regionhandle)) m_cachedRegionMapItemsAddress.Add(regionhandle, httpserver); } } else { lock (m_blacklistedregions) { if (!m_blacklistedregions.ContainsKey(regionhandle)) m_blacklistedregions.Add(regionhandle, Environment.TickCount); } //m_log.InfoFormat("[WORLD MAP]: Blacklisted region {0}", regionhandle.ToString()); } } blacklisted = false; lock (m_blacklistedurls) { if (m_blacklistedurls.ContainsKey(httpserver)) { if (Environment.TickCount > (m_blacklistedurls[httpserver] + blacklistTimeout)) { m_log.DebugFormat("[WORLD MAP]: Unblock blacklisted URL {0}", httpserver); m_blacklistedurls.Remove(httpserver); } else blacklisted = true; } } // Can't find the http server if (httpserver.Length == 0 || blacklisted) return new OSDMap(); MapRequestState mrs = new MapRequestState(); mrs.agentID = id; mrs.EstateID = EstateID; mrs.flags = flags; mrs.godlike = godlike; mrs.itemtype=itemtype; mrs.regionhandle = regionhandle; lock (m_openRequests) m_openRequests.Add(requestID, mrs); WebRequest mapitemsrequest = null; try { mapitemsrequest = WebRequest.Create(httpserver); } catch (Exception e) { m_log.DebugFormat("[WORLD MAP]: Access to {0} failed with {1}", httpserver, e); return new OSDMap(); } mapitemsrequest.Method = "POST"; mapitemsrequest.ContentType = "application/xml+llsd"; OSDMap RAMap = new OSDMap(); // string RAMapString = RAMap.ToString(); OSD LLSDofRAMap = RAMap; // RENAME if this works byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap); OSDMap responseMap = new OSDMap(); responseMap["requestID"] = OSD.FromUUID(requestID); Stream os = null; try { // send the Post mapitemsrequest.ContentLength = buffer.Length; //Count bytes to send os = mapitemsrequest.GetRequestStream(); os.Write(buffer, 0, buffer.Length); //Send it //m_log.DebugFormat("[WORLD MAP]: Getting MapItems from {0}", httpserver); } catch (WebException ex) { m_log.WarnFormat("[WORLD MAP]: Bad send on GetMapItems {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); lock (m_blacklistedurls) { if (!m_blacklistedurls.ContainsKey(httpserver)) m_blacklistedurls.Add(httpserver, Environment.TickCount); } m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver); return responseMap; } catch { m_log.DebugFormat("[WORLD MAP]: RequestMapItems failed for {0}", httpserver); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } finally { if (os != null) os.Dispose(); } string response_mapItems_reply = null; { try { using (WebResponse webResponse = mapitemsrequest.GetResponse()) { if (webResponse != null) { using (Stream s = webResponse.GetResponseStream()) using (StreamReader sr = new StreamReader(s)) response_mapItems_reply = sr.ReadToEnd().Trim(); } else { return new OSDMap(); } } } catch (WebException) { responseMap["connect"] = OSD.FromBoolean(false); lock (m_blacklistedurls) { if (!m_blacklistedurls.ContainsKey(httpserver)) m_blacklistedurls.Add(httpserver, Environment.TickCount); } m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver); return responseMap; } catch { m_log.DebugFormat("[WORLD MAP]: RequestMapItems failed for {0}", httpserver); responseMap["connect"] = OSD.FromBoolean(false); lock (m_blacklistedregions) { if (!m_blacklistedregions.ContainsKey(regionhandle)) m_blacklistedregions.Add(regionhandle, Environment.TickCount); } return responseMap; } OSD rezResponse = null; try { rezResponse = OSDParser.DeserializeLLSDXml(response_mapItems_reply); responseMap = (OSDMap)rezResponse; responseMap["requestID"] = OSD.FromUUID(requestID); } catch (Exception ex) { m_log.InfoFormat("[WORLD MAP]: exception on parse of RequestMapItems reply from {0}: {1}", httpserver, ex.Message); responseMap["connect"] = OSD.FromBoolean(false); lock (m_blacklistedregions) { if (!m_blacklistedregions.ContainsKey(regionhandle)) m_blacklistedregions.Add(regionhandle, Environment.TickCount); } return responseMap; } } if (!responseMap.ContainsKey(itemtype.ToString())) // remote sim doesnt have the stated region handle { m_log.DebugFormat("[WORLD MAP]: Remote sim does not have the stated region. Blacklisting."); lock (m_blacklistedregions) { if (!m_blacklistedregions.ContainsKey(regionhandle)) m_blacklistedregions.Add(regionhandle, Environment.TickCount); } } return responseMap; } /// <summary> /// Requests map blocks in area of minX, maxX, minY, MaxY in world cordinates /// </summary> /// <param name="minX"></param> /// <param name="minY"></param> /// <param name="maxX"></param> /// <param name="maxY"></param> public virtual void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag) { if ((flag & 0x10000) != 0) // user clicked on qthe map a tile that isn't visible { List<MapBlockData> response = new List<MapBlockData>(); // this should return one mapblock at most. It is triggered by a click // on an unloaded square. // But make sure: Look whether the one we requested is in there List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID, (int)Util.RegionToWorldLoc((uint)minX), (int)Util.RegionToWorldLoc((uint)maxX), (int)Util.RegionToWorldLoc((uint)minY), (int)Util.RegionToWorldLoc((uint)maxY) ); m_log.DebugFormat("[WORLD MAP MODULE] RequestMapBlocks min=<{0},{1}>, max=<{2},{3}>, flag={4}, cntFound={5}", minX, minY, maxX, maxY, flag.ToString("X"), regions.Count); if (regions != null) { foreach (GridRegion r in regions) { if (r.RegionLocX == Util.RegionToWorldLoc((uint)minX) && r.RegionLocY == Util.RegionToWorldLoc((uint)minY) ) { // found it => add it to response // Version 2 viewers can handle the larger regions if ((flag & 2) == 2) response.AddRange(Map2BlockFromGridRegion(r, flag)); else response.Add(MapBlockFromGridRegion(r, flag)); break; } } } if (response.Count == 0) { // response still empty => couldn't find the map-tile the user clicked on => tell the client MapBlockData block = new MapBlockData(); block.X = (ushort)minX; block.Y = (ushort)minY; block.Access = (byte)SimAccess.Down; // means 'simulator is offline' // block.Access = (byte)SimAccess.NonExistent; response.Add(block); } // The lower 16 bits are an unsigned int16 remoteClient.SendMapBlock(response, flag & 0xffff); } else { // normal mapblock request. Use the provided values GetAndSendBlocks(remoteClient, minX, minY, maxX, maxY, flag); } } protected virtual List<MapBlockData> GetAndSendBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag) { List<MapBlockData> mapBlocks = new List<MapBlockData>(); List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID, (int)Util.RegionToWorldLoc((uint)(minX - 4)), (int)Util.RegionToWorldLoc((uint)(maxX + 4)), (int)Util.RegionToWorldLoc((uint)(minY - 4)), (int)Util.RegionToWorldLoc((uint)(maxY + 4)) ); //m_log.DebugFormat("{0} GetAndSendBlocks. min=<{1},{2}>, max=<{3},{4}>, cntFound={5}", // LogHeader, minX, minY, maxX, maxY, regions.Count); foreach (GridRegion r in regions) { // Version 2 viewers can handle the larger regions if ((flag & 2) == 2) mapBlocks.AddRange(Map2BlockFromGridRegion(r, flag)); else mapBlocks.Add(MapBlockFromGridRegion(r, flag)); } remoteClient.SendMapBlock(mapBlocks, flag & 0xffff); return mapBlocks; } // Fill a passed MapBlockData from a GridRegion public MapBlockData MapBlockFromGridRegion(GridRegion r, uint flag) { MapBlockData block = new MapBlockData(); block.Access = r.Access; switch (flag & 0xffff) { case 0: block.MapImageId = r.TerrainImage; break; case 2: block.MapImageId = r.ParcelImage; break; default: block.MapImageId = UUID.Zero; break; } block.Name = r.RegionName; block.X = (ushort)Util.WorldToRegionLoc((uint)r.RegionLocX); block.Y = (ushort)Util.WorldToRegionLoc((uint)r.RegionLocY); block.SizeX = (ushort) r.RegionSizeX; block.SizeY = (ushort) r.RegionSizeY; return block; } public List<MapBlockData> Map2BlockFromGridRegion(GridRegion r, uint flag) { List<MapBlockData> blocks = new List<MapBlockData>(); MapBlockData block = new MapBlockData(); if (r == null) { block.Access = (byte)SimAccess.Down; block.MapImageId = UUID.Zero; blocks.Add(block); } else { block.Access = r.Access; switch (flag & 0xffff) { case 0: block.MapImageId = r.TerrainImage; break; case 2: block.MapImageId = r.ParcelImage; break; default: block.MapImageId = UUID.Zero; break; } block.Name = r.RegionName; block.X = (ushort)(r.RegionLocX / Constants.RegionSize); block.Y = (ushort)(r.RegionLocY / Constants.RegionSize); block.SizeX = (ushort)r.RegionSizeX; block.SizeY = (ushort)r.RegionSizeY; blocks.Add(block); } return blocks; } public Hashtable OnHTTPThrottled(Hashtable keysvals) { Hashtable reply = new Hashtable(); int statuscode = 500; reply["str_response_string"] = ""; reply["int_response_code"] = statuscode; reply["content_type"] = "text/plain"; return reply; } public Hashtable OnHTTPGetMapImage(Hashtable keysvals) { m_log.Debug("[WORLD MAP]: Sending map image jpeg"); Hashtable reply = new Hashtable(); int statuscode = 200; byte[] jpeg = new byte[0]; if (myMapImageJPEG.Length == 0) { MemoryStream imgstream = null; Bitmap mapTexture = new Bitmap(1,1); ManagedImage managedImage; Image image = (Image)mapTexture; try { // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data imgstream = new MemoryStream(); // non-async because we know we have the asset immediately. AssetBase mapasset = m_scene.AssetService.Get(m_scene.RegionInfo.RegionSettings.TerrainImageID.ToString()); // Decode image to System.Drawing.Image if (OpenJPEG.DecodeToImage(mapasset.Data, out managedImage, out image)) { // Save to bitmap mapTexture = new Bitmap(image); EncoderParameters myEncoderParameters = new EncoderParameters(); myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L); // Save bitmap to stream mapTexture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters); // Write the stream to a byte array for output jpeg = imgstream.ToArray(); myMapImageJPEG = jpeg; } } catch (Exception) { // Dummy! m_log.Warn("[WORLD MAP]: Unable to generate Map image"); } finally { // Reclaim memory, these are unmanaged resources // If we encountered an exception, one or more of these will be null if (mapTexture != null) mapTexture.Dispose(); if (image != null) image.Dispose(); if (imgstream != null) imgstream.Dispose(); } } else { // Use cached version so we don't have to loose our mind jpeg = myMapImageJPEG; } reply["str_response_string"] = Convert.ToBase64String(jpeg); reply["int_response_code"] = statuscode; reply["content_type"] = "image/jpeg"; return reply; } // From msdn private static ImageCodecInfo GetEncoderInfo(String mimeType) { ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } /// <summary> /// Export the world map /// </summary> /// <param name="fileName"></param> public void HandleExportWorldMapConsoleCommand(string module, string[] cmdparams) { if (m_scene.ConsoleScene() == null) { // FIXME: If console region is root then this will be printed by every module. Currently, there is no // way to prevent this, short of making the entire module shared (which is complete overkill). // One possibility is to return a bool to signal whether the module has completely handled the command m_log.InfoFormat("[WORLD MAP]: Please change to a specific region in order to export its world map"); return; } if (m_scene.ConsoleScene() != m_scene) return; string exportPath; if (cmdparams.Length > 1) exportPath = cmdparams[1]; else exportPath = DEFAULT_WORLD_MAP_EXPORT_PATH; m_log.InfoFormat( "[WORLD MAP]: Exporting world map for {0} to {1}", m_scene.RegionInfo.RegionName, exportPath); List<MapBlockData> mapBlocks = new List<MapBlockData>(); List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID, (int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocX - 9), (int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocX + 9), (int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocY - 9), (int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocY + 9)); List<AssetBase> textures = new List<AssetBase>(); List<Image> bitImages = new List<Image>(); foreach (GridRegion r in regions) { MapBlockData mapBlock = MapBlockFromGridRegion(r, 0); AssetBase texAsset = m_scene.AssetService.Get(mapBlock.MapImageId.ToString()); if (texAsset != null) { textures.Add(texAsset); } //else //{ // // WHAT?!? This doesn't seem right. Commenting (diva) // texAsset = m_scene.AssetService.Get(mapBlock.MapImageId.ToString()); // if (texAsset != null) // { // textures.Add(texAsset); // } //} } foreach (AssetBase asset in textures) { ManagedImage managedImage; Image image; if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image)) bitImages.Add(image); } Bitmap mapTexture = new Bitmap(2560, 2560); Graphics g = Graphics.FromImage(mapTexture); SolidBrush sea = new SolidBrush(Color.DarkBlue); g.FillRectangle(sea, 0, 0, 2560, 2560); for (int i = 0; i < mapBlocks.Count; i++) { ushort x = (ushort)((mapBlocks[i].X - m_scene.RegionInfo.RegionLocX) + 10); ushort y = (ushort)((mapBlocks[i].Y - m_scene.RegionInfo.RegionLocY) + 10); g.DrawImage(bitImages[i], (x * 128), 2560 - (y * 128), 128, 128); // y origin is top } mapTexture.Save(exportPath, ImageFormat.Jpeg); m_log.InfoFormat( "[WORLD MAP]: Successfully exported world map for {0} to {1}", m_scene.RegionInfo.RegionName, exportPath); } public void HandleGenerateMapConsoleCommand(string module, string[] cmdparams) { Scene consoleScene = m_scene.ConsoleScene(); if (consoleScene != null && consoleScene != m_scene) return; if (m_mapImageGenerator == null) { Console.WriteLine("No map image generator available for {0}", m_scene.Name); return; } using (Bitmap mapbmp = m_mapImageGenerator.CreateMapTile()) { GenerateMaptile(mapbmp); m_mapImageServiceModule.UploadMapTile(m_scene, mapbmp); } } public OSD HandleRemoteMapItemRequest(string path, OSD request, string endpoint) { uint xstart = 0; uint ystart = 0; Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle,out xstart,out ystart); // m_log.DebugFormat("{0} HandleRemoteMapItemRequest. loc=<{1},{2}>", // LogHeader, Util.WorldToRegionLoc(xstart), Util.WorldToRegionLoc(ystart)); // Service 6 (MAP_ITEM_AGENTS_LOCATION; green dots) OSDMap responsemap = new OSDMap(); int tc = Environment.TickCount; if (m_scene.GetRootAgentCount() == 0) { OSDMap responsemapdata = new OSDMap(); responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1)); responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1)); responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString())); responsemapdata["Extra"] = OSD.FromInteger(0); responsemapdata["Extra2"] = OSD.FromInteger(0); OSDArray responsearr = new OSDArray(); responsearr.Add(responsemapdata); responsemap["6"] = responsearr; } else { OSDArray responsearr = new OSDArray(m_scene.GetRootAgentCount()); m_scene.ForEachRootScenePresence(delegate(ScenePresence sp) { OSDMap responsemapdata = new OSDMap(); responsemapdata["X"] = OSD.FromInteger((int)(xstart + sp.AbsolutePosition.X)); responsemapdata["Y"] = OSD.FromInteger((int)(ystart + sp.AbsolutePosition.Y)); responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString())); responsemapdata["Extra"] = OSD.FromInteger(1); responsemapdata["Extra2"] = OSD.FromInteger(0); responsearr.Add(responsemapdata); }); responsemap["6"] = responsearr; } // Service 7 (MAP_ITEM_LAND_FOR_SALE) ILandChannel landChannel = m_scene.LandChannel; List<ILandObject> parcels = landChannel.AllParcels(); if ((parcels == null) || (parcels.Count == 0)) { OSDMap responsemapdata = new OSDMap(); responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1)); responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1)); responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); responsemapdata["Name"] = OSD.FromString(""); responsemapdata["Extra"] = OSD.FromInteger(0); responsemapdata["Extra2"] = OSD.FromInteger(0); OSDArray responsearr = new OSDArray(); responsearr.Add(responsemapdata); responsemap["7"] = responsearr; } else { OSDArray responsearr = new OSDArray(m_scene.GetRootAgentCount()); foreach (ILandObject parcel_interface in parcels) { // Play it safe if (!(parcel_interface is LandObject)) continue; LandObject land = (LandObject)parcel_interface; LandData parcel = land.LandData; // Show land for sale if ((parcel.Flags & (uint)ParcelFlags.ForSale) == (uint)ParcelFlags.ForSale) { Vector3 min = parcel.AABBMin; Vector3 max = parcel.AABBMax; float x = (min.X+max.X)/2; float y = (min.Y+max.Y)/2; OSDMap responsemapdata = new OSDMap(); responsemapdata["X"] = OSD.FromInteger((int)(xstart + x)); responsemapdata["Y"] = OSD.FromInteger((int)(ystart + y)); // responsemapdata["Z"] = OSD.FromInteger((int)m_scene.GetGroundHeight(x,y)); responsemapdata["ID"] = OSD.FromUUID(parcel.GlobalID); responsemapdata["Name"] = OSD.FromString(parcel.Name); responsemapdata["Extra"] = OSD.FromInteger(parcel.Area); responsemapdata["Extra2"] = OSD.FromInteger(parcel.SalePrice); responsearr.Add(responsemapdata); } } responsemap["7"] = responsearr; } if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero) { SceneObjectGroup sog = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject); if (sog != null) { OSDArray responsearr = new OSDArray(); OSDMap responsemapdata = new OSDMap(); responsemapdata["X"] = OSD.FromInteger((int)(xstart + sog.AbsolutePosition.X)); responsemapdata["Y"] = OSD.FromInteger((int)(ystart + sog.AbsolutePosition.Y)); // responsemapdata["Z"] = OSD.FromInteger((int)m_scene.GetGroundHeight(x,y)); responsemapdata["ID"] = OSD.FromUUID(sog.UUID); responsemapdata["Name"] = OSD.FromString(sog.Name); responsemapdata["Extra"] = OSD.FromInteger(0); // color (unused) responsemapdata["Extra2"] = OSD.FromInteger(0); // 0 = telehub / 1 = infohub responsearr.Add(responsemapdata); responsemap["1"] = responsearr; } } return responsemap; } public void GenerateMaptile() { // Cannot create a map for a nonexistent heightmap if (m_scene.Heightmap == null) return; m_log.DebugFormat("[WORLD MAP]: Generating map image for {0}", m_scene.Name); using (Bitmap mapbmp = m_mapImageGenerator.CreateMapTile()) { // V1 (This Module) GenerateMaptile(mapbmp); // v2/3 (MapImageServiceModule) m_mapImageServiceModule.UploadMapTile(m_scene, mapbmp); } } private void GenerateMaptile(Bitmap mapbmp) { byte[] data; try { data = OpenJPEG.EncodeFromImage(mapbmp, true); } catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke { m_log.Error("[WORLD MAP]: Failed generating terrain map: " + e); return; } byte[] overlay = GenerateOverlay(); UUID terrainImageID = UUID.Random(); UUID parcelImageID = UUID.Zero; AssetBase asset = new AssetBase( terrainImageID, "terrainImage_" + m_scene.RegionInfo.RegionID.ToString(), (sbyte)AssetType.Texture, m_scene.RegionInfo.RegionID.ToString()); asset.Data = data; asset.Description = m_scene.RegionInfo.RegionName; asset.Temporary = false; asset.Flags = AssetFlags.Maptile; // Store the new one m_log.DebugFormat("[WORLD MAP]: Storing map tile {0} for {1}", asset.ID, m_scene.RegionInfo.RegionName); m_scene.AssetService.Store(asset); if (overlay != null) { parcelImageID = UUID.Random(); AssetBase parcels = new AssetBase( parcelImageID, "parcelImage_" + m_scene.RegionInfo.RegionID.ToString(), (sbyte)AssetType.Texture, m_scene.RegionInfo.RegionID.ToString()); parcels.Data = overlay; parcels.Description = m_scene.RegionInfo.RegionName; parcels.Temporary = false; parcels.Flags = AssetFlags.Maptile; m_scene.AssetService.Store(parcels); } // Switch to the new one UUID lastTerrainImageID = m_scene.RegionInfo.RegionSettings.TerrainImageID; UUID lastParcelImageID = m_scene.RegionInfo.RegionSettings.ParcelImageID; m_scene.RegionInfo.RegionSettings.TerrainImageID = terrainImageID; m_scene.RegionInfo.RegionSettings.ParcelImageID = parcelImageID; m_scene.RegionInfo.RegionSettings.Save(); // Delete the old one // m_log.DebugFormat("[WORLDMAP]: Deleting old map tile {0}", lastTerrainImageID); m_scene.AssetService.Delete(lastTerrainImageID.ToString()); if (lastParcelImageID != UUID.Zero) m_scene.AssetService.Delete(lastParcelImageID.ToString()); } private void MakeRootAgent(ScenePresence avatar) { lock (m_rootAgents) { if (!m_rootAgents.Contains(avatar.UUID)) { m_rootAgents.Add(avatar.UUID); } } } private void MakeChildAgent(ScenePresence avatar) { lock (m_rootAgents) { m_rootAgents.Remove(avatar.UUID); } } public void OnRegionUp(GridRegion otherRegion) { ulong regionhandle = otherRegion.RegionHandle; string httpserver = otherRegion.ServerURI + "MAP/MapItems/" + regionhandle.ToString(); lock (m_blacklistedregions) { if (!m_blacklistedregions.ContainsKey(regionhandle)) m_blacklistedregions.Remove(regionhandle); } lock (m_blacklistedurls) { if (m_blacklistedurls.ContainsKey(httpserver)) m_blacklistedurls.Remove(httpserver); } lock (m_cachedRegionMapItemsAddress) { if (!m_cachedRegionMapItemsAddress.ContainsKey(regionhandle)) m_cachedRegionMapItemsAddress.Remove(regionhandle); } } private Byte[] GenerateOverlay() { // These need to be ints for bitmap generation int regionSizeX = (int)m_scene.RegionInfo.RegionSizeX; int regionSizeY = (int)m_scene.RegionInfo.RegionSizeY; int landTileSize = LandManagementModule.LandUnit; int regionLandTilesX = regionSizeX / landTileSize; int regionLandTilesY = regionSizeY / landTileSize; using (Bitmap overlay = new Bitmap(regionSizeX, regionSizeY)) { bool[,] saleBitmap = new bool[regionLandTilesX, regionLandTilesY]; for (int x = 0; x < regionLandTilesX; x++) { for (int y = 0; y < regionLandTilesY; y++) saleBitmap[x, y] = false; } bool landForSale = false; List<ILandObject> parcels = m_scene.LandChannel.AllParcels(); Color background = Color.FromArgb(0, 0, 0, 0); using (Graphics g = Graphics.FromImage(overlay)) { using (SolidBrush transparent = new SolidBrush(background)) g.FillRectangle(transparent, 0, 0, regionSizeX, regionSizeY); foreach (ILandObject land in parcels) { // m_log.DebugFormat("[WORLD MAP]: Parcel {0} flags {1}", land.LandData.Name, land.LandData.Flags); if ((land.LandData.Flags & (uint)ParcelFlags.ForSale) != 0) { landForSale = true; saleBitmap = land.MergeLandBitmaps(saleBitmap, land.GetLandBitmap()); } } if (!landForSale) { m_log.DebugFormat("[WORLD MAP]: Region {0} has no parcels for sale, not generating overlay", m_scene.RegionInfo.RegionName); return null; } m_log.DebugFormat("[WORLD MAP]: Region {0} has parcels for sale, generating overlay", m_scene.RegionInfo.RegionName); using (SolidBrush yellow = new SolidBrush(Color.FromArgb(255, 249, 223, 9))) { for (int x = 0 ; x < regionLandTilesX ; x++) { for (int y = 0 ; y < regionLandTilesY ; y++) { if (saleBitmap[x, y]) g.FillRectangle( yellow, x * landTileSize, regionSizeX - landTileSize - (y * landTileSize), landTileSize, landTileSize); } } } } try { return OpenJPEG.EncodeFromImage(overlay, true); } catch (Exception e) { m_log.DebugFormat("[WORLD MAP]: Error creating parcel overlay: " + e.ToString()); } } return null; } } public struct MapRequestState { public UUID agentID; public uint flags; public uint EstateID; public bool godlike; public uint itemtype; public ulong regionhandle; } }
// 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.IO; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Net.Http.WinHttpHandlerUnitTests; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; internal static partial class Interop { internal static partial class Crypt32 { public static bool CertFreeCertificateContext(IntPtr certContext) { return true; } public static bool CertVerifyCertificateChainPolicy( IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, ref CERT_CHAIN_POLICY_PARA pPolicyPara, ref CERT_CHAIN_POLICY_STATUS pPolicyStatus) { return true; } } internal static partial class mincore { public static string GetMessage(IntPtr moduleName, int error) { string messageFormat = "Fake error message, error code: {0}"; return string.Format(messageFormat, error); } public static IntPtr GetModuleHandle(string moduleName) { return IntPtr.Zero; } } internal static partial class WinHttp { public static SafeWinHttpHandle WinHttpOpen( IntPtr userAgent, uint accessType, string proxyName, string proxyBypass, uint flags) { if (TestControl.WinHttpOpen.ErrorWithApiCall) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INVALID_HANDLE; return new FakeSafeWinHttpHandle(false); } if (accessType == Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY && !TestControl.WinHttpAutomaticProxySupport) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INVALID_PARAMETER; return new FakeSafeWinHttpHandle(false); } APICallHistory.ProxyInfo proxyInfo; proxyInfo.AccessType = accessType; proxyInfo.Proxy = proxyName; proxyInfo.ProxyBypass = proxyBypass; APICallHistory.SessionProxySettings = proxyInfo; return new FakeSafeWinHttpHandle(true); } public static bool WinHttpCloseHandle(IntPtr sessionHandle) { Marshal.FreeHGlobal(sessionHandle); return true; } public static SafeWinHttpHandle WinHttpConnect( SafeWinHttpHandle sessionHandle, string serverName, ushort serverPort, uint reserved) { return new FakeSafeWinHttpHandle(true); } public static bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, StringBuilder headers, uint headersLength, uint modifiers) { return true; } public static bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, string headers, uint headersLength, uint modifiers) { return true; } public static SafeWinHttpHandle WinHttpOpenRequest( SafeWinHttpHandle connectHandle, string verb, string objectName, string version, string referrer, string acceptTypes, uint flags) { return new FakeSafeWinHttpHandle(true); } public static bool WinHttpSendRequest( SafeWinHttpHandle requestHandle, StringBuilder headers, uint headersLength, IntPtr optional, uint optionalLength, uint totalLength, IntPtr context) { Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; fakeHandle.Context = context; fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, IntPtr.Zero, 0); }); return true; } public static bool WinHttpReceiveResponse(SafeWinHttpHandle requestHandle, IntPtr reserved) { Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReceiveResponse.Delay); if (aborted || TestControl.WinHttpReadData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_RECEIVE_RESPONSE); asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpReceiveResponse.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, IntPtr.Zero, 0); } }); return true; } public static bool WinHttpQueryDataAvailable( SafeWinHttpHandle requestHandle, IntPtr bytesAvailableShouldBeNullForAsync) { if (bytesAvailableShouldBeNullForAsync != IntPtr.Zero) { return false; } if (TestControl.WinHttpQueryDataAvailable.ErrorWithApiCall) { return false; } Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReadData.Delay); if (aborted || TestControl.WinHttpQueryDataAvailable.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_QUERY_DATA_AVAILABLE); asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpQueryDataAvailable.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { int bufferSize = Marshal.SizeOf<int>(); IntPtr buffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(buffer, TestServer.DataAvailable); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, buffer, (uint)bufferSize); Marshal.FreeHGlobal(buffer); } }); return true; } public static bool WinHttpReadData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr bytesReadShouldBeNullForAsync) { if (bytesReadShouldBeNullForAsync != IntPtr.Zero) { return false; } if (TestControl.WinHttpReadData.ErrorWithApiCall) { return false; } uint bytesRead; TestServer.ReadFromResponseBody(buffer, bufferSize, out bytesRead); Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReadData.Delay); if (aborted || TestControl.WinHttpReadData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_READ_DATA); asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytesRead); } }); return true; } public static bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, IntPtr buffer, ref uint bufferLength, ref uint index) { string httpVersion = "HTTP/1.1"; string statusText = "OK"; if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_SET_COOKIE) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND; return false; } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_VERSION) { return CopyToBufferOrFailIfInsufficientBufferLength(httpVersion, buffer, ref bufferLength); } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT) { return CopyToBufferOrFailIfInsufficientBufferLength(statusText, buffer, ref bufferLength); } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING) { string compression = TestServer.ResponseHeaders.Contains("Content-Encoding: deflate") ? "deflate" : TestServer.ResponseHeaders.Contains("Content-Encoding: gzip") ? "gzip" : null; if (compression == null) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND; return false; } return CopyToBufferOrFailIfInsufficientBufferLength(compression, buffer, ref bufferLength); } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF) { return CopyToBufferOrFailIfInsufficientBufferLength(TestServer.ResponseHeaders, buffer, ref bufferLength); } return false; } private static bool CopyToBufferOrFailIfInsufficientBufferLength(string value, IntPtr buffer, ref uint bufferLength) { // The length of the string (plus terminating null char) in bytes. uint bufferLengthNeeded = ((uint)value.Length + 1) * sizeof(char); if (buffer == IntPtr.Zero || bufferLength < bufferLengthNeeded) { bufferLength = bufferLengthNeeded; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } // Copy the string to the buffer. char[] temp = new char[value.Length + 1]; // null terminated. value.CopyTo(0, temp, 0, value.Length); Marshal.Copy(temp, 0, buffer, temp.Length); // The length in bytes, minus the length of the null char at the end. bufferLength = (uint)value.Length * sizeof(char); return true; } public static bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, ref uint number, ref uint bufferLength, IntPtr index) { infoLevel &= ~Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER; if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE) { number = (uint)HttpStatusCode.OK; return true; } return false; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, StringBuilder buffer, ref uint bufferSize) { string uri = "http://www.contoso.com/"; if (option == Interop.WinHttp.WINHTTP_OPTION_URL) { if (buffer == null) { bufferSize = ((uint)uri.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(uri); return true; } return false; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, ref IntPtr buffer, ref uint bufferSize) { return true; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, IntPtr buffer, ref uint bufferSize) { return true; } public static bool WinHttpWriteData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr bytesWrittenShouldBeNullForAsync) { if (bytesWrittenShouldBeNullForAsync != IntPtr.Zero) { return false; } if (TestControl.WinHttpWriteData.ErrorWithApiCall) { return false; } uint bytesWritten; TestServer.WriteToRequestBody(buffer, bufferSize); bytesWritten = bufferSize; Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpWriteData.Delay); if (aborted || TestControl.WinHttpWriteData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_WRITE_DATA); asyncResult.dwError = Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpWriteData.Wait(); fakeHandle.InvokeCallback(aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpWriteData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, IntPtr.Zero, 0); } }); return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, ref uint optionData, uint optionLength = sizeof(uint)) { if (option == Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION & !TestControl.WinHttpDecompressionSupport) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION; return false; } if (option == Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE && optionData == Interop.WinHttp.WINHTTP_DISABLE_COOKIES) { APICallHistory.WinHttpOptionDisableCookies = true; } else if (option == Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE && optionData == Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION) { APICallHistory.WinHttpOptionEnableSslRevocation = true; } else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS) { APICallHistory.WinHttpOptionSecureProtocols = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS) { APICallHistory.WinHttpOptionSecurityFlags = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS) { APICallHistory.WinHttpOptionMaxHttpAutomaticRedirects = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY) { APICallHistory.WinHttpOptionRedirectPolicy = optionData; } return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, string optionData, uint optionLength) { if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_USERNAME) { APICallHistory.ProxyUsernameWithDomain = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_PASSWORD) { APICallHistory.ProxyPassword = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_USERNAME) { APICallHistory.ServerUsernameWithDomain = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_PASSWORD) { APICallHistory.ServerPassword = optionData; } return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, IntPtr optionData, uint optionLength) { if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY) { var proxyInfo = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_PROXY_INFO>(optionData); var proxyInfoHistory = new APICallHistory.ProxyInfo(); proxyInfoHistory.AccessType = proxyInfo.AccessType; proxyInfoHistory.Proxy = Marshal.PtrToStringUni(proxyInfo.Proxy); proxyInfoHistory.ProxyBypass = Marshal.PtrToStringUni(proxyInfo.ProxyBypass); APICallHistory.RequestProxySettings = proxyInfoHistory; } else if (option == Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT) { APICallHistory.WinHttpOptionClientCertContext.Add(optionData); } return true; } public static bool WinHttpSetCredentials( SafeWinHttpHandle requestHandle, uint authTargets, uint authScheme, string userName, string password, IntPtr reserved) { return true; } public static bool WinHttpQueryAuthSchemes( SafeWinHttpHandle requestHandle, out uint supportedSchemes, out uint firstScheme, out uint authTarget) { supportedSchemes = 0; firstScheme = 0; authTarget = 0; return true; } public static bool WinHttpSetTimeouts( SafeWinHttpHandle handle, int resolveTimeout, int connectTimeout, int sendTimeout, int receiveTimeout) { return true; } public static bool WinHttpGetIEProxyConfigForCurrentUser( out Interop.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig) { if (FakeRegistry.WinInetProxySettings.RegistryKeyMissing) { proxyConfig.AutoDetect = false; proxyConfig.AutoConfigUrl = IntPtr.Zero; proxyConfig.Proxy = IntPtr.Zero; proxyConfig.ProxyBypass = IntPtr.Zero; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_FILE_NOT_FOUND; return false; } proxyConfig.AutoDetect = FakeRegistry.WinInetProxySettings.AutoDetect; proxyConfig.AutoConfigUrl = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.AutoConfigUrl); proxyConfig.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy); proxyConfig.ProxyBypass = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.ProxyBypass); return true; } public static bool WinHttpGetProxyForUrl( SafeWinHttpHandle sessionHandle, string url, ref Interop.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions, out Interop.WinHttp.WINHTTP_PROXY_INFO proxyInfo) { if (TestControl.PACFileNotDetectedOnNetwork) { proxyInfo.AccessType = WINHTTP_ACCESS_TYPE_NO_PROXY; proxyInfo.Proxy = IntPtr.Zero; proxyInfo.ProxyBypass = IntPtr.Zero; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED; return false; } proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY; proxyInfo.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy); proxyInfo.ProxyBypass = IntPtr.Zero; return true; } public static IntPtr WinHttpSetStatusCallback( SafeWinHttpHandle handle, Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback, uint notificationFlags, IntPtr reserved) { if (handle == null) { throw new ArgumentNullException(nameof(handle)); } var fakeHandle = (FakeSafeWinHttpHandle)handle; fakeHandle.Callback = callback; return IntPtr.Zero; } } }
//----------------------------------------------------------------------------- // Filename: UACInviteTransaction.cs // // Description: SIP Transaction that implements UAC (Sser Agent Client) functionality for // an INVITE transaction. // // History: // 21 Nov 2006 Aaron Clauson Created. // // License: // This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php // // Copyright (c) 2006-2012 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery Pty Ltd, Hobart, Australia (www.sipsorcery.com) // 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 SIP Sorcery Pty Ltd. // nor the names of its contributors may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using SIPSorcery.Sys; using log4net; namespace SIPSorcery.SIP { /// <summary> /// SIP transaction that initiates a call to a SIP User Agent Server. This transaction processes outgoing calls SENT by the application. /// </summary> public class UACInviteTransaction : SIPTransaction { public event SIPTransactionResponseReceivedDelegate UACInviteTransactionInformationResponseReceived; public event SIPTransactionResponseReceivedDelegate UACInviteTransactionFinalResponseReceived; public event SIPTransactionTimedOutDelegate UACInviteTransactionTimedOut; private bool _sendOkAckManually = false; /// <param name="sendOkAckManually">If set an ACK request for the 2xx response will NOT be sent and it will be up to the application to explicitly call the SendACK request.</param> internal UACInviteTransaction(SIPTransport sipTransport, SIPRequest sipRequest, SIPEndPoint dstEndPoint, SIPEndPoint localSIPEndPoint, SIPEndPoint outboundProxy, bool sendOkAckManually = false) : base(sipTransport, sipRequest, dstEndPoint, localSIPEndPoint, outboundProxy) { TransactionType = SIPTransactionTypesEnum.Invite; m_localTag = sipRequest.Header.From.FromTag; SIPEndPoint localEP = SIPEndPoint.TryParse(sipRequest.Header.ProxySendFrom) ?? localSIPEndPoint; CDR = new SIPCDR(SIPCallDirection.Out, sipRequest.URI, sipRequest.Header.From, sipRequest.Header.CallId, localEP, dstEndPoint); _sendOkAckManually = sendOkAckManually; TransactionFinalResponseReceived += UACInviteTransaction_TransactionFinalResponseReceived; TransactionInformationResponseReceived += UACInviteTransaction_TransactionInformationResponseReceived; TransactionTimedOut += UACInviteTransaction_TransactionTimedOut; TransactionRequestReceived += UACInviteTransaction_TransactionRequestReceived; TransactionRemoved += UACInviteTransaction_TransactionRemoved; } private void UACInviteTransaction_TransactionRemoved(SIPTransaction transaction) { // Remove event handlers. UACInviteTransactionInformationResponseReceived = null; UACInviteTransactionFinalResponseReceived = null; UACInviteTransactionTimedOut = null; CDR = null; } public void SendInviteRequest(SIPEndPoint dstEndPoint, SIPRequest inviteRequest) { this.RemoteEndPoint = dstEndPoint; base.SendReliableRequest(); } private void UACInviteTransaction_TransactionRequestReceived(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPRequest sipRequest) { logger.Warn("UACInviteTransaction received unexpected request, " + sipRequest.Method + " from " + remoteEndPoint.ToString() + ", ignoring."); } private void UACInviteTransaction_TransactionTimedOut(SIPTransaction sipTransaction) { try { if (UACInviteTransactionTimedOut != null) { UACInviteTransactionTimedOut(sipTransaction); } if (CDR != null) { CDR.TimedOut(); } } catch (Exception excp) { logger.Error("Exception UACInviteTransaction_TransactionTimedOut. " + excp.Message); throw; } } private void UACInviteTransaction_TransactionInformationResponseReceived(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPResponse sipResponse) { try { if (UACInviteTransactionInformationResponseReceived != null) { UACInviteTransactionInformationResponseReceived(localSIPEndPoint, remoteEndPoint, sipTransaction, sipResponse); } if (CDR != null) { SIPEndPoint localEP = SIPEndPoint.TryParse(sipResponse.Header.ProxyReceivedOn) ?? localSIPEndPoint; SIPEndPoint remoteEP = SIPEndPoint.TryParse(sipResponse.Header.ProxyReceivedFrom) ?? remoteEndPoint; CDR.Progress(sipResponse.Status, sipResponse.ReasonPhrase, localEP, remoteEP); } } catch (Exception excp) { logger.Error("Exception UACInviteTransaction_TransactionInformationResponseReceived. " + excp.Message); } } private void UACInviteTransaction_TransactionFinalResponseReceived(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPResponse sipResponse) { try { // BranchId for 2xx responses needs to be a new one, non-2xx final responses use same one as original request. if (sipResponse.StatusCode >= 200 && sipResponse.StatusCode < 299) { if (_sendOkAckManually == false) { Send2xxAckRequest(null, null); } } else { // ACK for non 2xx response is part of the INVITE transaction and gets routed to the same endpoint as the INVITE. var ackRequest = GetInTransactionACKRequest(sipResponse, m_transactionRequest.URI, LocalSIPEndPoint); base.SendRequest(RemoteEndPoint, ackRequest); } if (UACInviteTransactionFinalResponseReceived != null) { UACInviteTransactionFinalResponseReceived(localSIPEndPoint, remoteEndPoint, sipTransaction, sipResponse); } if (CDR != null) { SIPEndPoint localEP = SIPEndPoint.TryParse(sipResponse.Header.ProxyReceivedOn) ?? localSIPEndPoint; SIPEndPoint remoteEP = SIPEndPoint.TryParse(sipResponse.Header.ProxyReceivedFrom) ?? remoteEndPoint; CDR.Answered(sipResponse.StatusCode, sipResponse.Status, sipResponse.ReasonPhrase, localEP, remoteEP); } } catch (Exception excp) { logger.Error("Exception UACInviteTransaction_TransactionFinalResponseReceived. " + excp.Message); } } public void Send2xxAckRequest(string content, string contentType) { var sipResponse = m_transactionFinalResponse; if (sipResponse.Header.To != null) { m_remoteTag = sipResponse.Header.To.ToTag; } SIPURI ackURI = m_transactionRequest.URI; if (sipResponse.Header.Contact != null && sipResponse.Header.Contact.Count > 0) { ackURI = sipResponse.Header.Contact[0].ContactURI; // Don't mangle private contacts if there is a Record-Route header. If a proxy is putting private IP's in a Record-Route header that's its problem. if ((sipResponse.Header.RecordRoutes == null || sipResponse.Header.RecordRoutes.Length == 0) && IPSocket.IsPrivateAddress(ackURI.Host) && !sipResponse.Header.ProxyReceivedFrom.IsNullOrBlank()) { // Setting the Proxy-ReceivedOn header is how an upstream proxy will let an agent know it should mangle the contact. SIPEndPoint remoteUASSIPEndPoint = SIPEndPoint.ParseSIPEndPoint(sipResponse.Header.ProxyReceivedFrom); ackURI.Host = remoteUASSIPEndPoint.GetIPEndPoint().ToString(); } } // ACK for 2xx response needs to be a new transaction and gets routed based on SIP request fields. var ackRequest = GetNewTransactionACKRequest(sipResponse, ackURI, LocalSIPEndPoint); if(content.NotNullOrBlank()) { ackRequest.Body = content; ackRequest.Header.ContentLength = ackRequest.Body.Length; ackRequest.Header.ContentType = contentType; } base.SendRequest(ackRequest); } /// <summary> /// New transaction ACK requests are for 2xx responses, i.e. INVITE accepted and dialogue being created. /// </summary> /// <remarks> /// From RFC 3261 Chapter 17.1.1.3 - ACK for non-2xx final responses /// /// IMPORTANT: /// an ACK for a non-2xx response will also have the same branch ID as the INVITE whose response it acknowledges. /// /// The ACK request constructed by the client transaction MUST contain /// values for the Call-ID, From, and Request-URI that are equal to the /// values of those header fields in the request passed to the transport /// by the client transaction (call this the "original request"). The To /// header field in the ACK MUST equal the To header field in the /// response being acknowledged, and therefore will usually differ from /// the To header field in the original request by the addition of the /// tag parameter. The ACK MUST contain a single Via header field, and /// this MUST be equal to the top Via header field of the original /// request. The CSeq header field in the ACK MUST contain the same /// value for the sequence number as was present in the original request, /// but the method parameter MUST be equal to "ACK". /// /// If the INVITE request whose response is being acknowledged had Route /// header fields, those header fields MUST appear in the ACK. This is /// to ensure that the ACK can be routed properly through any downstream /// stateless proxies. /// /// From RFC 3261 Chapter 13.2.2.4 - ACK for 2xx final responses /// /// IMPORTANT: /// an ACK for a 2xx final response is a new transaction and has a new branch ID. /// /// The UAC core MUST generate an ACK request for each 2xx received from /// the transaction layer. The header fields of the ACK are constructed /// in the same way as for any request sent within a dialog (see Section /// 12) with the exception of the CSeq and the header fields related to /// authentication. The sequence number of the CSeq header field MUST be /// the same as the INVITE being acknowledged, but the CSeq method MUST /// be ACK. The ACK MUST contain the same credentials as the INVITE. If /// the 2xx contains an offer (based on the rules above), the ACK MUST /// carry an answer in its body. If the offer in the 2xx response is not /// acceptable, the UAC core MUST generate a valid answer in the ACK and /// then send a BYE immediately. /// </remarks> private SIPRequest GetNewTransactionACKRequest(SIPResponse sipResponse, SIPURI ackURI, SIPEndPoint localSIPEndPoint) { SIPRequest ackRequest = new SIPRequest(SIPMethodsEnum.ACK, ackURI.ToString()); ackRequest.LocalSIPEndPoint = localSIPEndPoint; SIPHeader header = new SIPHeader(TransactionRequest.Header.From, sipResponse.Header.To, sipResponse.Header.CSeq, sipResponse.Header.CallId); header.CSeqMethod = SIPMethodsEnum.ACK; header.AuthenticationHeader = TransactionRequest.Header.AuthenticationHeader; header.ProxySendFrom = base.TransactionRequest.Header.ProxySendFrom; // If the UAS supplies a desired Record-Route list use that first. Otherwise fall back to any Route list used in the original transaction. if (sipResponse.Header.RecordRoutes != null) { header.Routes = sipResponse.Header.RecordRoutes.Reversed(); } else if(base.TransactionRequest.Header.Routes != null) { header.Routes = base.TransactionRequest.Header.Routes; } ackRequest.Header = header; SIPViaHeader viaHeader = new SIPViaHeader(localSIPEndPoint, CallProperties.CreateBranchId()); ackRequest.Header.Vias.PushViaHeader(viaHeader); return ackRequest; } /// <summary> /// In transaction ACK requests are for non-2xx responses, i.e. INVITE rejected and no dialogue being created. /// </summary> private SIPRequest GetInTransactionACKRequest(SIPResponse sipResponse, SIPURI ackURI, SIPEndPoint localSIPEndPoint) { SIPRequest ackRequest = new SIPRequest(SIPMethodsEnum.ACK, ackURI.ToString()); ackRequest.LocalSIPEndPoint = localSIPEndPoint; SIPHeader header = new SIPHeader(TransactionRequest.Header.From, sipResponse.Header.To, sipResponse.Header.CSeq, sipResponse.Header.CallId); header.CSeqMethod = SIPMethodsEnum.ACK; header.AuthenticationHeader = TransactionRequest.Header.AuthenticationHeader; header.Routes = base.TransactionRequest.Header.Routes; header.ProxySendFrom = base.TransactionRequest.Header.ProxySendFrom; ackRequest.Header = header; SIPViaHeader viaHeader = new SIPViaHeader(localSIPEndPoint, sipResponse.Header.Vias.TopViaHeader.Branch); ackRequest.Header.Vias.PushViaHeader(viaHeader); return ackRequest; } public void CancelCall(string cancelReason = null) { try { base.Cancel(); if (CDR != null) { CDR.Cancelled(cancelReason); } } catch (Exception excp) { logger.Error("Exception UACInviteTransaction CancelCall. " + excp.Message); throw; } } } }
//===--- SliceExtensions.cs -----------------------------------------------===// // // Copyright (c) 2015 Joe Duffy. All rights reserved. // // This file is distributed under the MIT License. See LICENSE.md for details. // //===----------------------------------------------------------------------===// namespace System { /// <summary> /// A collection of convenient Slice helpers, exposed as extension methods. /// </summary> public static class SliceExtensions { // Slice creation helpers: /// <summary> /// Creates a new slice over the portion of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'array' parameter is null. /// </exception> public static Slice<T> Slice<T>(this T[] array) { return new Slice<T>(array); } /// <summary> /// Creates a new slice over the portion of the target array beginning /// at 'start' index. /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the slice.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'array' parameter is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start index is not in range (&lt;0 or &gt;&eq;length). /// </exception> public static Slice<T> Slice<T>(this T[] array, int start) { return new Slice<T>(array, start); } /// <summary> /// Creates a new slice over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the slice.</param> /// <param name="end">The index at which to end the slice (exclusive).</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'array' parameter is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start or end index is not in range (&lt;0 or &gt;&eq;length). /// </exception> public static Slice<T> Slice<T>(this T[] array, int start, int end) { return new Slice<T>(array, start, end - start); } /// <summary> /// Creates a new slice over the portion of the target string. /// </summary> /// <param name="str">The target string.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'str' parameter is null. /// </exception> public static Slice<char> Slice(this string str) { Contract.Requires(str != null); return new Slice<char>( str, new UIntPtr((uint)SliceHelpers.OffsetToStringData), str.Length ); } /// <summary> /// Creates a new slice over the portion of the target string beginning /// at 'start' index. /// </summary> /// <param name="str">The target string.</param> /// <param name="start">The index at which to begin the slice.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'str' parameter is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start index is not in range (&lt;0 or &gt;&eq;length). /// </exception> public static Slice<char> Slice(this string str, int start) { Contract.Requires(str != null); Contract.RequiresInInclusiveRange(start, str.Length); return new Slice<char>( str, new UIntPtr((uint)(SliceHelpers.OffsetToStringData + (start * sizeof(char)))), str.Length - start ); } /// <summary> /// Creates a new slice over the portion of the target string beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="str">The target string.</param> /// <param name="start">The index at which to begin the slice.</param> /// <param name="end">The index at which to end the slice (exclusive).</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'start' parameter is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start or end index is not in range (&lt;0 or &gt;&eq;length). /// </exception> public static Slice<char> Slice(this string str, int start, int end) { Contract.Requires(str != null); Contract.RequiresInInclusiveRange(start, end, str.Length); return new Slice<char>( str, new UIntPtr((uint)(SliceHelpers.OffsetToStringData + (start * sizeof(char)))), end - start ); } // Some handy byte manipulation helpers: /// <summary> /// Casts a Slice of one primitive type (T) to another primitive type (U). /// These types may not contain managed objects, in order to preserve type /// safety. This is checked statically by a Roslyn analyzer. /// </summary> /// <param name="slice">The source slice, of type T.</param> public static Slice<U> Cast<[Primitive]T, [Primitive]U>(this Slice<T> slice) where T : struct where U : struct { int countOfU = slice.Length * PtrUtils.SizeOf<T>() / PtrUtils.SizeOf<U>(); if (countOfU == 0) { return default(Slice<U>); } return new Slice<U>(slice.Object, slice.Offset, countOfU); } /// <summary> /// Reads a structure of type T out of a slice of bytes. /// </summary> public static T Read<[Primitive]T>(this Slice<byte> slice) where T : struct { Contract.Requires(slice.Length >= PtrUtils.SizeOf<T>()); return slice.Cast<byte, T>()[0]; } /// <summary> /// Writes a structure of type T into a slice of bytes. /// </summary> public static void Write<[Primitive]T>(this Slice<byte> slice, T value) where T : struct { Contract.Requires(slice.Length >= PtrUtils.SizeOf<T>()); var cast = slice.Cast<byte, T>(); cast[0] = value; } // Helper methods similar to System.ArrayExtension: // String helper methods, offering methods like String on Slice<char>: // TODO(joe): culture-sensitive comparisons. public static bool Contains(this Slice<char> str, Slice<char> value) { if (value.Length > str.Length) { return false; } return str.IndexOf(value) >= 0; } public static bool EndsWith(this Slice<char> str, Slice<char> value) { if (value.Length > str.Length) { return false; } int j = str.Length - value.Length - 1; foreach (var c in value) { if (str[j] != c) { return false; } j++; } return true; } public static int IndexOf(this Slice<char> str, char value) { throw new NotImplementedException(); } public static int IndexOf(this Slice<char> str, string value) { return IndexOf(str, value.Slice()); } public static int IndexOf(this Slice<char> str, Slice<char> value) { throw new NotImplementedException(); } public static int IndexOfAny(this Slice<char> str, params char[] values) { throw new NotImplementedException(); } public static int IndexOfAny(this Slice<char> str, params string[] values) { throw new NotImplementedException(); } public static int IndexOfAny(this Slice<char> str, params Slice<char>[] values) { throw new NotImplementedException(); } public static int LastIndexOf(this Slice<char> str, char value) { throw new NotImplementedException(); } public static int LastIndexOf(this Slice<char> str, string value) { return LastIndexOf(str, value.Slice()); } public static int LastIndexOf(this Slice<char> str, Slice<char> value) { throw new NotImplementedException(); } public static int LastIndexOfAny(this Slice<char> str, params char[] values) { throw new NotImplementedException(); } public static int LastIndexOfAny(this Slice<char> str, params string[] values) { throw new NotImplementedException(); } public static int LastIndexOfAny(this Slice<char> str, params Slice<char>[] values) { throw new NotImplementedException(); } public static SplitEnumerator Split(this Slice<char> str, params char[] separator) { throw new NotImplementedException(); } public struct SplitEnumerator { } public static bool StartsWith(this Slice<char> str, Slice<char> value) { if (value.Length > str.Length) { return false; } for (int i = 0; i < value.Length; i++) { if (str[i] != value[i]) { return false; } } return true; } } }
//----------------------------------------------------------------------- // <copyright file="GenericMethodParameterAcceptanceTest.cs" company="NMock2"> // // http://www.sourceforge.net/projects/NMock2 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // This is the easiest way to ignore StyleCop rules on this file, even if we shouldn't use this tag: // <auto-generated /> // This is the easiest way to ignore StyleCop rules on this file, even if we shouldn't use this tag: // <auto-generated /> //----------------------------------------------------------------------- using System.Collections; using NMock2; using NUnit.Framework; namespace NMocha.AcceptanceTests { /// <summary> /// Tests for generic method parameters and return values. /// <see cref="GenericMethodTypeParamAcceptanceTest"/> for acceptance tests about /// generic type parameters. /// </summary> /// <remarks> /// Created on user request for Generic return types. /// Request was fed by Adrian Krummenacher on 18-JAN-2008. /// </remarks> [TestFixture] public class GenericMethodParameterAcceptanceTest : AcceptanceTestBase { public interface IServiceOne { string ServiceOneGetsName(); } public interface IServiceTwo { bool ServiceTwoSaves(); } public interface ILocator { Hashtable Instances { get; } void Register<T>(T instance); T Get<T>(); } public abstract class Locator : ILocator { #region ILocator Members public abstract Hashtable Instances { get; } public abstract void Register<T>(T instance); public abstract T Get<T>(); #endregion } private class PersistentClass { private int integerValue; private string stringValue; public PersistentClass(int integerValue, string stringValue) { this.integerValue = integerValue; this.stringValue = stringValue; } } private PersistentClass CreatePersistentObject() { return new PersistentClass(23, "Persistent string"); } private void AssertCanMockGenericMethod(ILocator locatorMock) { var serviceOneMock = Mockery.NewInstanceOfRole<IServiceOne>(); var serviceTwoMock = Mockery.NewInstanceOfRole<IServiceTwo>(); // That works only with Expect and if the order of calls to Get match the order of the expectations: Expect.Once.On(locatorMock).Message("Get").Will(Return.Value(serviceOneMock)); Expect.Once.On(locatorMock).Message("Get").Will(Return.Value(serviceTwoMock)); Expect.Once.On(serviceOneMock).Message("ServiceOneGetsName").Will(Return.Value("ServiceOne")); Expect.Once.On(serviceTwoMock).Message("ServiceTwoSaves").Will(Return.Value(true)); // real call now; only works in same order as the expectations var serviceOne = locatorMock.Get<IServiceOne>(); string name = serviceOne.ServiceOneGetsName(); Assert.AreEqual("ServiceOne", name, "Service one returned wrong name."); var serviceTwo = locatorMock.Get<IServiceTwo>(); bool res = serviceTwo.ServiceTwoSaves(); Assert.AreEqual(true, res, "Service two returned wrong boolean value."); } public void AssertCanMockGenericMethodWithGenericParameter(IGenericSpeaker genericMock) { const bool expectedSaveResult = true; PersistentClass persistentObject = CreatePersistentObject(); Expect.Once.On(genericMock).Message("Save").With(persistentObject).Will(Return.Value(expectedSaveResult)); bool saveResult = genericMock.Save(persistentObject); Assert.AreEqual(expectedSaveResult, saveResult, "Generic method 'Save' with PersistentClass did not return correct value."); } private void AssertCanMockGenericMethodWithGenericParameterUsingValueType(IGenericSpeaker genericMock) { const bool expectedSaveResult = true; const decimal decimalValue = 13.5m; Expect.Once.On(genericMock).Message("Save").With(decimalValue).Will(Return.Value(expectedSaveResult)); bool saveResult = genericMock.Save(decimalValue); Assert.AreEqual(expectedSaveResult, saveResult, "Generic method 'Save' with decimal value did not return correct value."); } private void AssertCanMockGenericMethodWithGenericReturnValueUsingMixedTypes(IGenericSpeaker genericMock) { const int integerValue = 12; const string stringValue = "Hello World"; Expect.Once.On(genericMock).Message("Find").Will(Return.Value(integerValue)); Expect.Once.On(genericMock).Message("Find").Will(Return.Value(stringValue)); var integerFindResult = genericMock.Find<int>(); Assert.AreEqual(integerValue, integerFindResult, "Generic method did not return correct Value Type value."); var stringFindResult = genericMock.Find<string>(); Assert.AreEqual(stringValue, stringFindResult, "Generic method did not return correct Reference Type value."); } public void AssertCanMockGenericMethodWithGenericReturnValueUsingReferenceType(IGenericSpeaker genericMock) { const string stringValue = "Hello World"; Expect.Once.On(genericMock).Message("Find").Will(Return.Value(stringValue)); var findResult = genericMock.Find<string>(); Assert.AreEqual(stringValue, findResult, "Generic method did not return correct Reference Type value."); } private void AssertCanMockGenericMethodWithGenericReturnValueUsingValueType(IGenericSpeaker genericMock) { const int integerValue = 12; Expect.Once.On(genericMock).Message("Find").Will(Return.Value(integerValue)); var findResult = genericMock.Find<int>(); Assert.AreEqual(integerValue, findResult, "Generic method did not return correct Value Type value."); } private void AssertCanMockGenericMethodWithMixedParameters(IGenericSpeaker genericMock) { string variableA = "Contents of variable a"; string variableB = "Contents of variable b"; Expect.Once.On(genericMock).Message("SetVariable").With("A", "Contents of variable a"); Expect.Once.On(genericMock).Message("SetVariable").With("B", "Contents of variable b"); Expect.Once.On(genericMock).Message("ReadVariable").With("A").Will(Return.Value(variableA)); Expect.Once.On(genericMock).Message("ReadVariable").With("B").Will(Return.Value(variableB)); genericMock.SetVariable("A", "Contents of variable a"); var resultA = genericMock.ReadVariable<string>("A"); Assert.AreEqual("Contents of variable a", resultA, "Variable 'A' was not read correctly."); genericMock.SetVariable("B", "Contents of variable b"); var resultB = genericMock.ReadVariable<string>("B"); Assert.AreEqual("Contents of variable b", resultB, "Variable 'B' was not read correctly."); } [Test, Class] public void CanMockGenericMethodOnClass() { AssertCanMockGenericMethod(Mockery.NewInstanceOfRole<Locator>()); } [Test] public void CanMockGenericMethodOnInterface() { AssertCanMockGenericMethod(Mockery.NewInstanceOfRole<ILocator>()); } [Test, Class] public void CanMockGenericMethodWithGenericParameterOnClass() { AssertCanMockGenericMethodWithGenericParameter(Mockery.NewInstanceOfRole<GenericSpeaker>()); } [Test] public void CanMockGenericMethodWithGenericParameterOnInterface() { AssertCanMockGenericMethodWithGenericParameter(Mockery.NewInstanceOfRole<IGenericSpeaker>()); } [Test, Class] public void CanMockGenericMethodWithGenericParameterUsingValueTypeOnClass() { AssertCanMockGenericMethodWithGenericParameterUsingValueType(Mockery.NewInstanceOfRole<GenericSpeaker>()); } [Test] public void CanMockGenericMethodWithGenericParameterUsingValueTypeOnInterface() { AssertCanMockGenericMethodWithGenericParameterUsingValueType(Mockery.NewInstanceOfRole<IGenericSpeaker>()); } [Test, Class] public void CanMockGenericMethodWithGenericReturnValueUsingMixedTypesOnClass() { AssertCanMockGenericMethodWithGenericReturnValueUsingMixedTypes(Mockery.NewInstanceOfRole<GenericSpeaker>()); } [Test] public void CanMockGenericMethodWithGenericReturnValueUsingMixedTypesOnInterface() { AssertCanMockGenericMethodWithGenericReturnValueUsingMixedTypes(Mockery.NewInstanceOfRole<IGenericSpeaker>()); } [Test, Class] public void CanMockGenericMethodWithGenericReturnValueUsingReferenceTypeOnClass() { AssertCanMockGenericMethodWithGenericReturnValueUsingReferenceType( Mockery.NewInstanceOfRole<GenericSpeaker>()); } [Test] public void CanMockGenericMethodWithGenericReturnValueUsingReferenceTypeOnInterface() { AssertCanMockGenericMethodWithGenericReturnValueUsingReferenceType( Mockery.NewInstanceOfRole<IGenericSpeaker>()); } [Test, Class] public void CanMockGenericMethodWithGenericReturnValueUsingValueTypeOnClass() { AssertCanMockGenericMethodWithGenericReturnValueUsingValueType(Mockery.NewInstanceOfRole<GenericSpeaker>()); } [Test] public void CanMockGenericMethodWithGenericReturnValueUsingValueTypeOnInterface() { AssertCanMockGenericMethodWithGenericReturnValueUsingValueType(Mockery.NewInstanceOfRole<IGenericSpeaker>()); } [Test, Class] public void CanMockGenericMethodWithMixedParametersOnClass() { AssertCanMockGenericMethodWithMixedParameters(Mockery.NewInstanceOfRole<GenericSpeaker>()); } [Test] public void CanMockGenericMethodWithMixedParametersOnInterface() { AssertCanMockGenericMethodWithMixedParameters(Mockery.NewInstanceOfRole<IGenericSpeaker>()); } } }
// 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.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Globalization; namespace System.DirectoryServices.AccountManagement { internal class PrincipalCollectionEnumerator : IEnumerator<Principal>, IEnumerator { // // Public properties // public Principal Current { get { CheckDisposed(); // Since MoveNext() saved off the current value for us, this is largely trivial. if (_endReached == true || _currentMode == CurrentEnumeratorMode.None) { // Either we're at the end or before the beginning // (CurrentEnumeratorMode.None implies we're _before_ the first value) GlobalDebug.WriteLineIf( GlobalDebug.Warn, "PrincipalCollectionEnumerator", "Current: bad position, endReached={0}, currentMode={1}", _endReached, _currentMode); throw new InvalidOperationException(SR.PrincipalCollectionEnumInvalidPos); } Debug.Assert(_current != null); return _current; } } object IEnumerator.Current { get { return Current; } } // // Public methods // public bool MoveNext() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "Entering MoveNext"); CheckDisposed(); CheckChanged(); // We previously reached the end, nothing more to do if (_endReached) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: endReached"); return false; } lock (_resultSet) { if (_currentMode == CurrentEnumeratorMode.None) { // At the very beginning // In case this ResultSet was previously used with another PrincipalCollectionEnumerator instance // (e.g., two foreach loops in a row) _resultSet.Reset(); if (!_memberCollection.Cleared && !_memberCollection.ClearCompleted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: None mode, starting with existing values"); // Start by enumerating the existing values in the store _currentMode = CurrentEnumeratorMode.ResultSet; _enumerator = null; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: None mode, skipping existing values"); // The member collection was cleared. Skip the ResultSet phase _currentMode = CurrentEnumeratorMode.InsertedValuesCompleted; _enumerator = (IEnumerator<Principal>)_insertedValuesCompleted.GetEnumerator(); } } Debug.Assert(_resultSet != null); if (_currentMode == CurrentEnumeratorMode.ResultSet) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: ResultSet mode"); bool needToRepeat = false; do { bool f = _resultSet.MoveNext(); if (f) { Principal principal = (Principal)_resultSet.CurrentAsPrincipal; if (_removedValuesCompleted.Contains(principal) || _removedValuesPending.Contains(principal)) { // It's a value that's been removed (either a pending remove that hasn't completed, or a remove // that completed _after_ we loaded the ResultSet from the store). GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: ResultSet mode, found remove, skipping"); needToRepeat = true; continue; } else if (_insertedValuesCompleted.Contains(principal) || _insertedValuesPending.Contains(principal)) { // insertedValuesCompleted: We must have gotten the ResultSet after the inserted committed. // We don't want to return // the principal twice, so we'll skip it here and later return it in // the CurrentEnumeratorMode.InsertedValuesCompleted mode. // // insertedValuesPending: The principal must have been originally in the ResultSet, but then // removed, saved, and re-added, with the re-add still pending. GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: ResultSet mode, found insert, skipping"); needToRepeat = true; continue; } else { needToRepeat = false; _current = principal; return true; } } else { // No more values left to retrieve. Now try the insertedValuesCompleted list. GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: ResultSet mode, moving to InsValuesComp mode"); _currentMode = CurrentEnumeratorMode.InsertedValuesCompleted; _enumerator = (IEnumerator<Principal>)_insertedValuesCompleted.GetEnumerator(); needToRepeat = false; } } while (needToRepeat); } // These are values whose insertion has completed, but after we already loaded the ResultSet from the store. if (_currentMode == CurrentEnumeratorMode.InsertedValuesCompleted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: InsValuesComp mode"); bool f = _enumerator.MoveNext(); if (f) { _current = _enumerator.Current; return true; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: InsValuesComp mode, moving to InsValuesPend mode"); _currentMode = CurrentEnumeratorMode.InsertedValuesPending; _enumerator = (IEnumerator<Principal>)_insertedValuesPending.GetEnumerator(); } } // These are values whose insertion has not yet been committed to the store. if (_currentMode == CurrentEnumeratorMode.InsertedValuesPending) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: InsValuesPend mode"); bool f = _enumerator.MoveNext(); if (f) { _current = _enumerator.Current; return true; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: InsValuesPend mode, nothing left"); _endReached = true; return false; } } } Debug.Fail($"PrincipalCollectionEnumerator.MoveNext: fell off end of function, mode = {_currentMode}"); return false; } bool IEnumerator.MoveNext() { return MoveNext(); } public void Reset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "Reset"); CheckDisposed(); CheckChanged(); // Set us up to start enumerating from the very beginning again _endReached = false; _enumerator = null; _currentMode = CurrentEnumeratorMode.None; } void IEnumerator.Reset() { Reset(); } public void Dispose() // IEnumerator<Principal> inherits from IDisposable { _disposed = true; } // // Internal constructors // internal PrincipalCollectionEnumerator( ResultSet resultSet, PrincipalCollection memberCollection, List<Principal> removedValuesCompleted, List<Principal> removedValuesPending, List<Principal> insertedValuesCompleted, List<Principal> insertedValuesPending ) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "Ctor"); Debug.Assert(resultSet != null); _resultSet = resultSet; _memberCollection = memberCollection; _removedValuesCompleted = removedValuesCompleted; _removedValuesPending = removedValuesPending; _insertedValuesCompleted = insertedValuesCompleted; _insertedValuesPending = insertedValuesPending; } // // Private implementation // private Principal _current; // Remember: these are references to objects held by the PrincipalCollection class from which we came. // We don't own these, and shouldn't Dispose the ResultSet. // // SYNCHRONIZATION // Access to: // resultSet // must be synchronized, since multiple enumerators could be iterating over us at once. // Synchronize by locking on resultSet. private ResultSet _resultSet; private List<Principal> _insertedValuesPending; private List<Principal> _insertedValuesCompleted; private List<Principal> _removedValuesPending; private List<Principal> _removedValuesCompleted; private bool _endReached = false; // true if there are no results left to iterate over private IEnumerator<Principal> _enumerator = null; // The insertedValues{Completed,Pending} enumerator, used by MoveNext private enum CurrentEnumeratorMode // The set of values that MoveNext is currently iterating over { None, ResultSet, InsertedValuesCompleted, InsertedValuesPending } private CurrentEnumeratorMode _currentMode = CurrentEnumeratorMode.None; // To support IDisposable private bool _disposed = false; private void CheckDisposed() { if (_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalCollectionEnumerator", "CheckDisposed: accessing disposed object"); throw new ObjectDisposedException("PrincipalCollectionEnumerator"); } } // When this enumerator was constructed, to detect changes made to the PrincipalCollection after it was constructed private DateTime _creationTime = DateTime.UtcNow; private PrincipalCollection _memberCollection = null; private void CheckChanged() { // Make sure the app hasn't changed our underlying list if (_memberCollection.LastChange > _creationTime) { GlobalDebug.WriteLineIf( GlobalDebug.Warn, "PrincipalCollectionEnumerator", "CheckChanged: has changed (last change={0}, creation={1})", _memberCollection.LastChange, _creationTime); throw new InvalidOperationException(SR.PrincipalCollectionEnumHasChanged); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using System.IO; using System.Xml; using System.Diagnostics; using Moritz.Globals; namespace Krystals4ObjectLibrary { /// <summary> /// The static class K contains application-wide constants and enum definitions, /// together with generally useful functions. /// </summary> public static class K { static K() // cribbed from CapXML.Utilities { CultureInfo ci = new CultureInfo("en-US", false); _numberFormat = ci.NumberFormat; _dateTimeFormat = ci.DateTimeFormat; KrystalsFolder = M.LocalMoritzKrystalsFolder; ExpansionOperatorsFolder = M.LocalMoritzExpansionFieldsFolder; ModulationOperatorsFolder = M.LocalMoritzModulationOperatorsFolder; // The Schemas location is a programmer's preference. The user need not bother with it. MoritzXmlSchemasFolder = M.OnlineXMLSchemasFolder; } public static Krystal LoadKrystal(string pathname) { Krystal krystal = null; string filename = Path.GetFileName(pathname); if(IsConstantKrystalFilename(filename)) krystal = new ConstantKrystal(pathname); else if(IsLineKrystalFilename(filename)) krystal = new LineKrystal(pathname); else if(IsExpansionKrystalFilename(filename)) krystal = new ExpansionKrystal(pathname); else if(IsShapedExpansionKrystalFilename(filename)) krystal = new ShapedExpansionKrystal(pathname); else if(IsModulationKrystalFilename(filename)) krystal = new ModulationKrystal(pathname); else if(IsPermutationKrystalFilename(filename)) krystal = new PermutationKrystal(pathname); else { string msg = pathname + "\r\n\r\n is not a known type of krystal."; MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } return krystal; } public static Krystal GetKrystal(string krystalFileName) { Krystal krystal = null; try { string krystalPath = KrystalsFolder + @"\" + krystalFileName; krystal = K.LoadKrystal(krystalPath); } catch(Exception ex) { MessageBox.Show("Error loading krystal.\n\n" + ex.Message); krystal = null; } return krystal; } /// <summary> /// returns an array containing density values (greater than or equal to 1, and less than or equal /// to density), describing a contour. /// </summary> /// <param name="density">A value greater than 0, and less than or equal to 7</param> /// <param name="contourNumberMod12">A value greater than or equal to 1, and less than or equal to 12</param> /// <param name="axisNumberMod12">A value greater than or equal to 1, and less than or equal to 12</param> /// <returns></returns> public static int[] Contour(int density, int contourNumberMod12, int axisNumberMod12) { Debug.Assert( density > 0 && density <= 7 && contourNumberMod12 > 0 && contourNumberMod12 <= 12 && axisNumberMod12 > 0 && axisNumberMod12 <= 12); #region contours // These arrays are the contours those used for 'beyond the symbolic' - notebook July 1986 int[, ,] dom2Contours = new int[,,] { {{1,2},{2,1}}, {{2,1},{1,2}} }; int[, ,] dom3Contours = new int[,,] { {{1,2,3},{2,1,3},{3,2,1},{3,1,2}}, {{2,1,3},{1,2,3},{3,1,2},{3,2,1}}, {{3,2,1},{2,3,1},{1,2,3},{1,3,2}}, {{2,3,1},{3,2,1},{1,3,2},{1,2,3}} }; int[, ,] dom4Contours = new int[,,] { {{1,2,3,4},{2,1,3,4},{4,2,1,3},{4,3,2,1},{4,3,1,2},{3,1,2,4}}, {{2,1,3,4},{1,2,3,4},{4,1,2,3},{4,3,1,2},{4,3,2,1},{3,2,1,4}}, {{3,2,4,1},{2,3,4,1},{1,2,3,4},{1,4,2,3},{1,4,3,2},{4,3,2,1}}, {{4,3,2,1},{3,4,2,1},{1,3,4,2},{1,2,3,4},{1,2,4,3},{2,4,3,1}}, {{3,4,2,1},{4,3,2,1},{1,4,3,2},{1,2,4,3},{1,2,3,4},{2,3,4,1}}, {{2,3,1,4},{3,2,1,4},{4,3,2,1},{4,1,3,2},{4,1,2,3},{1,2,3,4}}, }; int[, ,] dom5Contours = new int[,,] { {{1,2,3,4,5},{2,1,3,4,5},{4,2,1,3,5},{5,4,2,1,3},{5,4,3,2,1},{5,4,3,1,2},{5,3,1,2,4},{3,1,2,4,5}}, {{2,1,3,4,5},{1,2,3,4,5},{4,1,2,3,5},{5,4,1,2,3},{5,4,3,1,2},{5,4,3,2,1},{5,3,2,1,4},{3,2,1,4,5}}, {{3,2,4,1,5},{2,3,4,1,5},{1,2,3,4,5},{5,1,2,3,4},{5,1,4,2,3},{5,1,4,3,2},{5,4,3,2,1},{4,3,2,1,5}}, {{4,3,5,2,1},{3,4,5,2,1},{2,3,4,5,1},{1,2,3,4,5},{1,2,5,3,4},{1,2,5,4,3},{1,5,4,3,2},{5,4,3,2,1}}, {{5,4,3,2,1},{4,5,3,2,1},{2,4,5,3,1},{1,2,4,5,3},{1,2,3,4,5},{1,2,3,5,4},{1,3,5,4,2},{3,5,4,2,1}}, {{4,5,3,2,1},{5,4,3,2,1},{2,5,4,3,1},{1,2,3,4,5},{1,2,3,5,4},{1,2,3,4,5},{1,3,4,5,2},{3,4,5,2,1}}, {{3,4,2,5,1},{4,3,2,5,1},{5,4,3,2,1},{1,5,4,3,2},{1,5,2,4,3},{1,5,2,3,4},{1,2,3,4,5},{2,3,4,5,1}}, {{2,3,1,4,5},{3,2,1,4,5},{4,3,2,1,5},{5,4,3,2,1},{5,4,1,3,2},{5,4,1,2,3},{5,1,2,3,4},{1,2,3,4,5}} }; int[, ,] dom6Contours = new int[,,] { {{1,2,3,4,5,6},{2,1,3,4,5,6},{4,2,1,3,5,6},{6,4,2,1,3,5},{6,5,4,2,1,3}, {6,5,4,3,2,1},{6,5,4,3,1,2},{6,5,3,1,2,4},{5,3,1,2,4,6},{3,1,2,4,5,6}}, {{2,1,3,4,5,6},{1,2,3,4,5,6},{4,1,2,3,5,6},{6,4,1,2,3,5},{6,5,4,1,2,3}, {6,5,4,3,1,2},{6,5,4,3,2,1},{6,5,3,2,1,4},{5,3,2,1,4,6},{3,2,1,4,5,6}}, {{3,2,4,1,5,6},{2,3,4,1,5,6},{1,2,3,4,5,6},{6,1,2,3,4,5},{6,5,1,2,3,4}, {6,5,1,4,2,3},{6,5,1,4,3,2},{6,5,4,3,2,1},{5,4,3,2,1,6},{4,3,2,1,5,6}}, {{4,3,5,2,6,1},{3,4,5,2,6,1},{2,3,4,5,6,1},{1,2,3,4,5,6},{1,6,2,3,4,5}, {1,6,2,5,3,4},{1,6,2,5,4,3},{1,6,5,4,3,2},{6,5,4,3,2,1},{5,4,3,2,6,1}}, {{5,4,6,3,2,1},{4,5,6,3,2,1},{3,4,5,6,2,1},{1,3,4,5,6,2},{1,2,3,4,5,6}, {1,2,3,6,4,5},{1,2,3,6,5,4},{1,2,6,5,4,3},{2,6,5,4,3,1},{6,5,4,3,2,1}}, {{6,5,4,3,2,1},{5,6,4,3,2,1},{3,5,6,4,2,1},{1,3,5,6,4,2},{1,2,3,5,6,4}, {1,2,3,4,5,6},{1,2,3,4,6,5},{1,2,4,6,5,3},{2,4,6,5,3,1},{4,6,5,3,2,1}}, {{5,6,4,3,2,1},{6,5,4,3,2,1},{3,6,5,4,2,1},{1,3,6,5,4,2},{1,2,3,6,5,4}, {1,2,3,4,6,5},{1,2,3,4,5,6},{1,2,4,5,6,3},{2,4,5,6,3,1},{4,5,6,3,2,1}}, {{4,5,3,6,2,1},{5,4,3,6,2,1},{6,5,4,3,2,1},{1,6,5,4,3,2},{1,2,6,5,4,3}, {1,2,6,3,5,4},{1,2,6,3,4,5},{1,2,3,4,5,6},{2,3,4,5,6,1},{3,4,5,6,2,1}}, {{3,4,2,5,1,6},{4,3,2,5,1,6},{5,4,3,2,1,6},{6,5,4,3,2,1},{6,1,5,4,3,2}, {6,1,5,2,4,3},{6,1,5,2,3,4},{6,1,2,3,4,5},{1,2,3,4,5,6},{2,3,4,5,1,6}}, {{2,3,1,4,5,6},{3,2,1,4,5,6},{4,3,2,1,5,6},{6,4,3,2,1,5},{6,5,4,3,2,1}, {6,5,4,1,3,2},{6,5,4,1,2,3},{6,5,1,2,3,4},{5,1,2,3,4,6},{1,2,3,4,5,6}} }; int[, ,] dom7Contours = new int[,,] { {{1,2,3,4,5,6,7},{2,1,3,4,5,6,7},{4,2,1,3,5,6,7},{6,4,2,1,3,5,7},{7,6,4,2,1,3,5},{7,6,5,4,2,1,3}, {7,6,5,4,3,2,1},{7,6,5,4,3,1,2},{7,6,5,3,1,2,4},{7,5,3,1,2,4,6},{5,3,1,2,4,6,7},{3,1,2,4,5,6,7}}, {{2,1,3,4,5,6,7},{1,2,3,4,5,6,7},{4,1,2,3,5,6,7},{6,4,1,2,3,5,7},{7,6,4,1,2,3,5},{7,6,5,4,1,2,3}, {7,6,5,4,3,1,2},{7,6,5,4,3,2,1},{7,6,5,3,2,1,4},{7,5,3,2,1,4,6},{5,3,2,1,4,6,7},{3,2,1,4,5,6,7}}, {{3,2,4,1,5,6,7},{2,3,4,1,5,6,7},{1,2,3,4,5,6,7},{6,1,2,3,4,5,7},{7,6,1,2,3,4,5},{7,6,5,1,2,3,4}, {7,6,5,1,4,2,3},{7,6,5,1,4,3,2},{7,6,5,4,3,2,1},{7,5,4,3,2,1,6},{5,4,3,2,1,6,7},{4,3,2,1,5,6,7}}, {{4,3,5,2,6,1,7},{3,4,5,2,6,1,7},{2,3,4,5,6,1,7},{1,2,3,4,5,6,7},{7,1,2,3,4,5,6},{7,1,6,2,3,4,5}, {7,1,6,2,5,3,4},{7,1,6,2,5,4,3},{7,1,6,5,4,3,2},{7,6,5,4,3,2,1},{6,5,4,3,2,1,7},{5,4,3,2,6,1,7}}, {{5,4,6,3,7,2,1},{4,5,6,3,7,2,1},{3,4,5,6,7,2,1},{2,3,4,5,6,7,1},{1,2,3,4,5,6,7},{1,2,7,3,4,5,6}, {1,2,7,3,6,4,5},{1,2,7,3,6,5,4},{1,2,7,6,5,4,3},{1,7,6,5,4,3,2},{7,6,5,4,3,2,1},{6,5,4,3,7,2,1}}, {{6,5,7,4,3,2,1},{5,6,7,4,3,2,1},{4,5,6,7,3,2,1},{2,4,5,6,7,3,1},{1,2,4,5,6,7,3},{1,2,3,4,5,6,7}, {1,2,3,4,7,5,6},{1,2,3,4,7,6,5},{1,2,3,7,6,5,4},{1,3,7,6,5,4,2},{3,7,6,5,4,2,1},{7,6,5,4,3,2,1}}, {{7,6,5,4,3,2,1},{6,7,5,4,3,2,1},{4,6,7,5,3,2,1},{2,4,6,7,5,3,1},{1,2,4,6,7,5,3},{1,2,3,4,6,7,5}, {1,2,3,4,5,6,7},{1,2,3,4,5,7,6},{1,2,3,5,7,6,4},{1,3,5,7,6,4,2},{3,5,7,6,4,2,1},{5,7,6,4,3,2,1}}, {{6,7,5,4,3,2,1},{7,6,5,4,3,2,1},{4,7,6,5,3,2,1},{2,4,7,6,5,3,1},{1,2,4,7,6,5,3},{1,2,3,4,7,6,5}, {1,2,3,4,5,7,6},{1,2,3,4,5,6,7},{1,2,3,5,6,7,4},{1,3,5,6,7,4,2},{3,5,6,7,4,2,1},{5,6,7,4,3,2,1}}, {{5,6,4,7,3,2,1},{6,5,4,7,3,2,1},{7,6,5,4,3,2,1},{2,7,6,5,4,3,1},{1,2,7,6,5,4,3},{1,2,3,7,6,5,4}, {1,2,3,7,4,6,5},{1,2,3,7,4,5,6},{1,2,3,4,5,6,7},{1,3,4,5,6,7,2},{3,4,5,6,7,2,1},{4,5,6,7,3,2,1}}, {{4,5,3,6,2,7,1},{5,4,3,6,2,7,1},{6,5,4,3,2,7,1},{7,6,5,4,3,2,1},{1,7,6,5,4,3,2},{1,7,2,6,5,4,3}, {1,7,2,6,3,5,4},{1,7,2,6,3,4,5},{1,7,2,3,4,5,6},{1,2,3,4,5,6,7},{2,3,4,5,6,7,1},{3,4,5,6,2,7,1}}, {{3,4,2,5,1,6,7},{4,3,2,5,1,6,7},{5,4,3,2,1,6,7},{6,5,4,3,2,1,7},{7,6,5,4,3,2,1},{7,6,1,5,4,3,2}, {7,6,1,5,2,4,3},{7,6,1,5,2,3,4},{7,6,1,2,3,4,5},{7,1,2,3,4,5,6},{1,2,3,4,5,6,7},{2,3,4,5,1,6,7}}, {{2,3,1,4,5,6,7},{3,2,1,4,5,6,7},{4,3,2,1,5,6,7},{6,4,3,2,1,5,7},{7,6,4,3,2,1,5},{7,6,5,4,3,2,1}, {7,6,5,4,1,3,2},{7,6,5,4,1,2,3},{7,6,5,1,2,3,4},{7,5,1,2,3,4,6},{5,1,2,3,4,6,7},{1,2,3,4,5,6,7}} }; int[][, ,] contours = new int[6][, ,]; contours[0] = dom2Contours; contours[1] = dom3Contours; contours[2] = dom4Contours; contours[3] = dom5Contours; contours[4] = dom6Contours; contours[5] = dom7Contours; int[,] rectifiedCoordinates = { {1,1,1,1,1,1,2,2,2,2,2,2}, {1,1,1,2,2,2,3,3,3,4,4,4}, {1,1,2,2,3,3,4,4,5,5,6,6}, {1,1,2,3,3,4,5,5,6,7,7,8}, {1,1,2,3,4,5,6,6,7,8,9,10}, {1,2,3,4,5,6,7,8,9,10,11,12} }; #endregion int[] contour = { 0, 0, 0, 0, 0, 0, 0 }; if(density == 1) { contour[0] = 1; } else { int axisNumber = rectifiedCoordinates[density - 2, axisNumberMod12 - 1]; int contourNumber = rectifiedCoordinates[density - 2, contourNumberMod12 - 1]; for(int j = 0; j < density; j++) { contour[j] = contours[density - 2][contourNumber - 1, axisNumber - 1, j]; } } return contour; } #region Regex Filename verification public static bool IsConstantKrystalFilename(string name) { return Regex.IsMatch(name, @"^[c][k][0][\(]([0-9])+[\)][.][k][r][y][s]$"); } public static bool IsLineKrystalFilename(string name) { return Regex.IsMatch(name, @"^[l][k][1][\(]([0-9])+[\)][\-]([0-9])+[.][k][r][y][s]$"); } public static bool IsModulationKrystalFilename(string name) { return Regex.IsMatch(name, @"^[m][k]([0-9])+[\(]([0-9])+[\)][\-]([0-9])+[.][k][r][y][s]$"); } public static bool IsPermutationKrystalFilename(string name) { return Regex.IsMatch(name, @"^[p][k]([0-9])+[\(]([0-9])+[\)][\-]([0-9])+[.][k][r][y][s]$"); } public static bool IsExpansionKrystalFilename(string name) { return Regex.IsMatch(name, @"^[x][k]([0-9])+[\(]([0-9])+[.]([0-9])+[.]([0-9])+[\)][\-]([0-9])+[.][k][r][y][s]$"); } public static bool IsShapedExpansionKrystalFilename(string name) { return Regex.IsMatch(name, @"^[s][k]([0-9])+[\(]([0-9])+[.]([0-9])+[.]([0-9])+[\)][\-]([0-9])+[.][k][r][y][s]$"); } public static bool IsKrystalFilename(string name) { return (IsConstantKrystalFilename(name) || IsLineKrystalFilename(name) || IsExpansionKrystalFilename(name) || IsShapedExpansionKrystalFilename(name) || IsModulationKrystalFilename(name) || IsPermutationKrystalFilename(name)); } public static bool IsModulationOperatorFilename(string name) { return Regex.IsMatch(name, @"^[m]([0-9])*[x]([0-9])*[(]([0-9])*[)][-]([0-9])*[.][k][m][o][d]$"); } public static bool IsExpansionOperatorFilename(string name) { return Regex.IsMatch(name, @"^[e][(]([0-9])+[.]([0-9])+[.]([0-9])+[)][.][k][e][x][p]$"); } public static bool IsKrystalOperatorFilename(string name) { return (IsExpansionOperatorFilename(name) || IsModulationOperatorFilename(name)); } #endregion public static uint KrystalMaxValue(string krystalName) { string maxValueString = "0"; int firstBracketIndex = krystalName.IndexOf('('); int secondBracketIndex = krystalName.IndexOf(')'); string bracketContentString = krystalName.Substring(firstBracketIndex + 1, secondBracketIndex - firstBracketIndex - 1); if(IsConstantKrystalFilename(krystalName) || IsLineKrystalFilename(krystalName) || IsModulationKrystalFilename(krystalName) || IsPermutationKrystalFilename(krystalName)) { maxValueString = bracketContentString; } else if(IsExpansionKrystalFilename(krystalName) || IsShapedExpansionKrystalFilename(krystalName)) { string[] substrings = bracketContentString.Split(new char[] { '.' }); maxValueString = substrings[1]; } return uint.Parse(maxValueString); } public static uint KrystalLevel(string krystalName) { uint level = 0; string head = krystalName.Substring(0, 2); switch(head) { case "ck": level = 0; break; case "lk": level = 1; break; case "mk": case "pk": case "sk": case "xk": string levelString = krystalName.Substring(2); int index = 0; while(Char.IsDigit(levelString[index])) index++; levelString = levelString.Substring(0, index); level = uint.Parse(levelString); break; default: break; } return level; } /// <summary> /// If krystalNameList is a list of krystal names, it can be sorted into ascending order by calling /// krystalNameList.Sort(K.CompareKrystalNames); /// /// Throws an exception if one or both of its arguments is not a krystalName. /// </summary /// <returns>0 if the names are equal, /// -1 if krystalName1 is less than krystalName2, /// 1 if krystalName1 is greater than krystalname2. /// </returns> public static int CompareKrystalNames(string krystalName1, string krystalName2) { if(!IsKrystalFilename(krystalName1) || !IsKrystalFilename(krystalName1)) { throw new ApplicationException("Argument to K:CompareKrystalNames() was not a krystal file name"); } string k1ID = krystalName1.Substring(0, 2); string k2ID = krystalName2.Substring(0, 2); int rval = String.Compare(k1ID, k2ID); if(rval == 0) // both krystals are of the same type { int k1InBracketIndex = krystalName1.IndexOf('(') + 1; int k2InBracketIndex = krystalName2.IndexOf('(') + 1; string k1LevelString = krystalName1.Substring(2, k1InBracketIndex - 3); string k2LevelString = krystalName2.Substring(2, k2InBracketIndex - 3); int k1Level, k2Level; try { k1Level = int.Parse(k1LevelString); k2Level = int.Parse(k2LevelString); rval = K.CompareInts(k1Level, k2Level); if(rval == 0) // the two names have the same level, so may differ by the content of the bracket { int k1CloseIndex = krystalName1.IndexOf(')'); int k2CloseIndex = krystalName2.IndexOf(')'); switch(k1ID) { case "ck": case "lk": case "mk": case "pk": rval = CompareDomains( krystalName1.Substring(k1InBracketIndex, k1CloseIndex - k1InBracketIndex), krystalName2.Substring(k2InBracketIndex, k2CloseIndex - k2InBracketIndex)); break; case "sk": case "xk": rval = CompareFields( krystalName1.Substring(k1InBracketIndex, k1CloseIndex - k1InBracketIndex), krystalName2.Substring(k2InBracketIndex, k2CloseIndex - k2InBracketIndex)); break; } if(rval == 0 && k1ID != "ck") // compare numbers { int k1NumberIndex = krystalName1.IndexOf('-') + 1; int k2NumberIndex = krystalName2.IndexOf('-') + 1; int k1SuffixIndex = krystalName1.IndexOf(".krys"); int k2SuffixIndex = krystalName2.IndexOf(".krys"); string k1Number = krystalName1.Substring(k1NumberIndex, k1SuffixIndex - k1NumberIndex); string k2Number = krystalName2.Substring(k2NumberIndex, k2SuffixIndex - k2NumberIndex); int k1Int = int.Parse(k1Number); int k2Int = int.Parse(k2Number); rval = K.CompareInts(k1Int, k2Int); } } } catch { throw new ApplicationException("Error comparing krystal names."); } } return rval; } private static int CompareDomains(string domStr1, string domStr2) { int rval = 0; try { int dom1 = int.Parse(domStr1); int dom2 = int.Parse(domStr2); rval = K.CompareInts(dom1, dom2); } catch { throw new ApplicationException("Error comparing domains in krystal names."); } return rval; } /// <summary> /// A field string consists of three integers separated by stops. e.g. "7.12.1" /// The three numbers are compared individually. /// </summary> /// <param name="fieldStr1"></param> /// <param name="fieldStr2"></param> /// <returns></returns> private static int CompareFields(string fieldStr1, string fieldStr2) { int rval = 0; int f1Dot1Index = fieldStr1.IndexOf('.'); int f1Dot2Index = fieldStr1.IndexOf('.', f1Dot1Index + 1); int f2Dot1Index = fieldStr2.IndexOf('.'); int f2Dot2Index = fieldStr2.IndexOf('.', f2Dot1Index + 1); string f1Num1Str = fieldStr1.Substring(0, f1Dot1Index); string f2Num1Str = fieldStr2.Substring(0, f2Dot1Index); try { int f1Num1 = int.Parse(f1Num1Str); int f2Num1 = int.Parse(f2Num1Str); rval = K.CompareInts(f1Num1, f2Num1); if(rval == 0) // Num1s are the same, now try Num2s { string f1Num2Str = fieldStr1.Substring(f1Dot1Index + 1, f1Dot2Index - f1Dot1Index - 1); string f2Num2Str = fieldStr2.Substring(f2Dot1Index + 1, f2Dot2Index - f2Dot1Index - 1); int f1Num2 = int.Parse(f1Num2Str); int f2Num2 = int.Parse(f2Num2Str); rval = K.CompareInts(f1Num2, f2Num2); if(rval == 0) // Num2s are the same, now try Num3s { string f1Num3Str = fieldStr1.Substring(f1Dot2Index + 1); string f2Num3Str = fieldStr2.Substring(f2Dot2Index + 1); int f1Num3 = int.Parse(f1Num3Str); int f2Num3 = int.Parse(f2Num3Str); rval = K.CompareInts(f1Num3, f2Num3); } } } catch { throw new ApplicationException("Error comparing fields in krystal names."); } return rval; } private static int CompareInts(int int1, int int2) { int rval = 0; if(int1 < int2) rval = -1; else if(int1 > int2) rval = 1; else if(int1 == int2) rval = 0; return rval; } /// <summary> /// If moritzName is a known Moritz filename type, the file index is returned, otherwise zero. /// </summary> public static uint FileIndex(string moritzName) { uint result = 0; string resultStr = ""; if(K.IsConstantKrystalFilename(moritzName)) result = 0; else if(K.IsLineKrystalFilename(moritzName) || K.IsModulationKrystalFilename(moritzName) || K.IsExpansionKrystalFilename(moritzName) || K.IsShapedExpansionKrystalFilename(moritzName) || K.IsModulationOperatorFilename(moritzName)) { int startindex = moritzName.IndexOf('-') + 1; int endindex = moritzName.Length - 5; resultStr = moritzName.Substring(startindex, endindex - startindex); result = uint.Parse(resultStr); } else if(K.IsExpansionOperatorFilename(moritzName)) { int endindex = moritzName.IndexOf(')'); int startindex = endindex - 1; while(Char.IsDigit(moritzName[startindex])) startindex--; startindex++; resultStr = moritzName.Substring(startindex, endindex - startindex); result = uint.Parse(resultStr); } return result; } /// <summary> /// If expanderName is a well formed expander name, its input domain is returned, otherwise zero. /// </summary> public static uint ExpansionOperatorInputDomain(string expanderName) { uint result = 0; if(K.IsExpansionOperatorFilename(expanderName)) { int startindex = 2; int endindex = 3; while(Char.IsDigit(expanderName[endindex])) endindex++; string resultStr = expanderName.Substring(startindex, endindex - startindex); result = uint.Parse(resultStr); } return result; } /// <summary> /// If expanderName is a well formed expander name, its output domain is returned, otherwise zero. /// </summary> public static uint ExpansionOperatorOutputDomain(string expanderName) { uint result = 0; if(K.IsExpansionOperatorFilename(expanderName)) { int startindex = expanderName.IndexOf('.') + 1; int endindex = startindex + 1; while(Char.IsDigit(expanderName[endindex])) endindex++; string resultStr = expanderName.Substring(startindex, endindex - startindex); result = uint.Parse(resultStr); } return result; } #region Loading and saving gametes and strands from files /// <summary> /// Reads to the next start or end tag having a name which is in the parameter list. /// When this function returns, XmlReader.Name is the name of the start or end tag found. /// If none of the names in the parameter list is found, an exception is thrown with a diagnostic message. /// </summary> /// <param name="r">XmlReader</param> /// <param name="possibleElements">Any number of strings, separated by commas</param> public static void ReadToXmlElementTag(XmlReader r, params string[] possibleElements) { List<string> elementNames = new List<string>(possibleElements); do { r.Read(); } while (!elementNames.Contains(r.Name) && !r.EOF); if (r.EOF) { StringBuilder msg = new StringBuilder("Error reading Xml file:\n" + "None of the following elements could be found:\n"); foreach(string s in elementNames) msg.Append( s.ToString() + "\n"); throw new ApplicationException(msg.ToString()); } } /// <summary> /// Gets a file path from a standard OpenFileDialog, filtering for various types of file. /// </summary> /// <returns>A path to a krystal, expander or modulator - or an empty string if the user cancels the dialog.</returns> public static string GetFilepathFromOpenFileDialog(DialogFilterIndex defaultFilterIndex) { string pathname = ""; OpenFileDialog openFileDialog = new OpenFileDialog(); switch(defaultFilterIndex) { case DialogFilterIndex.allKrystals: case DialogFilterIndex.constant: case DialogFilterIndex.line: case DialogFilterIndex.expansion: case DialogFilterIndex.shapedExpansion: case DialogFilterIndex.modulation: openFileDialog.InitialDirectory = K.KrystalsFolder;// @"D:\krystals\krystals"; break; case DialogFilterIndex.expander: openFileDialog.InitialDirectory = K.ExpansionOperatorsFolder;// @"D:\krystals\operators\expansion fields"; break; case DialogFilterIndex.modulator: openFileDialog.InitialDirectory = K.ModulationOperatorsFolder;// @"D:\krystals\operators\modulation operators"; break; } openFileDialog.Filter = DialogFilter; openFileDialog.FilterIndex = (int)defaultFilterIndex + 1; openFileDialog.Title = "Open file"; openFileDialog.RestoreDirectory = true; if(openFileDialog.ShowDialog() == DialogResult.OK) pathname = openFileDialog.FileName; return pathname; } #endregion Loading and saving gametes and strands from files /// <summary> /// Returns the portion of a string enclosed in single brackets (...), including the brackets. /// Used by expansion krystals and expanders, and by modulation krystals and modulators. /// </summary> /// <param name="filename"></param> /// <returns></returns> public static string FieldSignature(string filename) { return filename.Substring(filename.IndexOf('('), filename.IndexOf(')') - filename.IndexOf('(') + 1); } /// <summary> /// returns the filename of the expansion operator associated with the given expansion krystal /// </summary> public static string ExpansionOperatorFilename(string expansionKrystalFilename) { string expanderSignature = FieldSignature(expansionKrystalFilename); return String.Format("e{0}{1}", expanderSignature, K.ExpanderFilenameSuffix); } /// <summary> /// Converts a List of uints to a string containing the uints separated by spaces /// </summary> /// <param name="uintList"></param> /// <returns>the string</returns> public static string GetStringOfUnsignedInts(List<uint> uintList) { StringBuilder sb = new StringBuilder(); foreach (uint ui in uintList) { sb.Append(ui); sb.Append(" "); } if (uintList.Count > 0) sb.Remove(sb.Length - 1, 1); // remove the final space return sb.ToString(); } /// <summary> /// Converts a List of ints to a string containing the ints separated by spaces. /// Throws an exception if the intList contains a negative number. /// </summary> /// <param name="uintList"></param> /// <returns>the string</returns> public static string GetStringOfUnsignedInts(List<int> intList) { StringBuilder sb = new StringBuilder(); foreach (int i in intList) { if (i < 0) throw new ApplicationException("Attempt to store a negative number in a string of unsigned integers."); sb.Append(i); sb.Append(" "); } if (intList.Count > 0) sb.Remove(sb.Length - 1, 1); // remove the final space return sb.ToString(); } /// <summary> /// Converts a List of uints to a string containing the uints separated by spaces /// </summary> /// <param name="uintList"></param> /// <returns>the string</returns> public static string GetStringOfUnsignedInts(uint[] uintArray) { if (uintArray.Length > 0) { List<uint> uintList = new List<uint>(); for (int i = 0; i < uintArray.Length; i++) uintList.Add(uintArray[i]); return GetStringOfUnsignedInts(uintList); } else return ""; } /// <summary> /// Converts a string of numeric digits and separators (whitespace, newlines, tabs etc.) /// to a List of uint. Throws an ApplicationException if an illegal character is found. /// </summary> /// <param name="str">The string to be converted</param> /// <returns>a List of unsigned integers</returns> public static List<uint> GetUIntList(string str) { List<uint> values = new List<uint>(); str = str.Trim(); // removes white space from begin and end of the string if( str.Length > 0 ) { StringBuilder s = new StringBuilder(); bool inSeparator = false; // convert internal separators (spaces, newlines, tabs etc) to single spaces foreach( Char c in str ) { if( Char.IsDigit(c) ) { s.Append(c); inSeparator = false; } else if( Char.IsWhiteSpace(c) || Char.IsControl(c) ) { if( !inSeparator ) { s.Append(' '); inSeparator = true; } } else throw new ApplicationException("Illegal character in list of unsigned integer values."); } str = s.ToString(); string[] valueStrings = str.Split(' '); foreach( string valStr in valueStrings ) values.Add(uint.Parse(valStr)); } return values; } /// <summary> /// Convert a float to a string using the static en-US number format. /// This function is used when writing XML files. /// </summary> /// <param name="number"></param> /// <returns></returns> public static string FloatToAttributeString(float floatValue) { return floatValue.ToString("0.###", _numberFormat); } /// <summary> /// Convert a string to a float using the static en-US number format. /// This function is used when reading XML files. /// </summary> /// <param name="value"></param> /// <returns></returns> public static float StringToFloat(string value) { if (string.IsNullOrEmpty(value)) return 0.0f; else return (float)Convert.ToDouble(value, _numberFormat); } public static string Now { get { return DateTime.Today.ToString("dddd dd.MM.yyyy", _dateTimeFormat) + ", " + DateTime.Now.ToLongTimeString();} } #region public variables //the following three set from Moritz.Preferences in the above constructor public static readonly string KrystalsFolder = ""; public static readonly string ExpansionOperatorsFolder = ""; public static readonly string ModulationOperatorsFolder = ""; public static readonly string MoritzXmlSchemasFolder = ""; public static readonly string UntitledKrystalName = "Untitled.krys"; public static readonly string UntitledExpanderName = "Untitled.kexp"; //public static readonly string UntitledModulatorName = "Untitled.kmod"; public static readonly string DialogFilter = "all krystals (*.krys)|*.krys|" + "constants (ck*.krys)|ck*.krys|" + "lines (lk*.krys)|lk*.krys|" + "expansions (xk*.krys)|xk*.krys|" + "shaped expansions (sk*.krys)|sk*.krys|" + "modulations (mk*.krys)|mk*.krys|" + "expanders (e*.kexp) |e*.kexp|" + "modulators (m*.kmod) |m*.kmod"; public static readonly string KrystalFilenameSuffix = ".krys"; public static readonly string ExpanderFilenameSuffix = ".kexp"; public static readonly string ModulatorFilenameSuffix = ".kmod"; // used to index the Krystal dialog filter (see above) public enum DialogFilterIndex { allKrystals, constant, line, expansion, shapedExpansion, modulation, expander, modulator }; public enum PointGroupShape { circle, spiral, straightLine }; public enum DisplayColor { black, red, green, blue, orange, purple, magenta }; #endregion public variables #region private variables private static readonly NumberFormatInfo _numberFormat; private static readonly DateTimeFormatInfo _dateTimeFormat; #endregion private variables } }
#region Header // Vorspire _,-'/-'/ PortalClient.cs // . __,-; ,'( '/ // \. `-.__`-._`:_,-._ _ , . `` // `:-._,------' ` _,`--` -: `_ , ` ,' : // `---..__,,--' (C) 2018 ` -'. -' // # Vita-Nex [http://core.vita-nex.com] # // {o)xxx|===============- # -===============|xxx(o} // # The MIT License (MIT) # #endregion #region References using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; #endregion namespace Multiverse { public class PortalClient : PortalTransport { private static readonly byte[] _OneByte = new byte[1]; private long _Buffered; private ConcurrentQueue<PortalBuffer> _ReceiveQueue; private readonly IPEndPoint _EndPoint; private ushort? _ServerID; private long _NextPing, _PingExpire, _AuthExpire; private readonly bool _IsLocalClient, _IsRemoteClient; private volatile bool _IsSeeded, _IsAuthed; private volatile bool _DisplaySendOutput, _DisplayRecvOutput; private Socket _Client; public sealed override Socket Socket { get { return _Client; } } public Dictionary<ushort, PortalPacketHandler> Handlers { get; private set; } public ushort ServerID { get { return _ServerID ?? UInt16.MaxValue; } } public bool IsIdentified { get { return _ServerID.HasValue; } } public bool IsLocalClient { get { return _IsLocalClient; } } public bool IsRemoteClient { get { return _IsRemoteClient; } } public bool IsSeeded { get { return _IsSeeded; } set { _IsSeeded = value; } } public bool IsAuthed { get { return _IsAuthed; } set { _IsAuthed = value; } } public bool DisplaySendOutput { get { return _DisplaySendOutput; } set { _DisplaySendOutput = value; } } public bool DisplayRecvOutput { get { return _DisplayRecvOutput; } set { _DisplayRecvOutput = value; } } public int Pending { get { return _Client != null ? _Client.Available : -1; } } public long Buffered { get { return _Buffered; } } public bool IsConnected { get { if (_Client == null || IsDisposed) { return false; } /* if (_IsLocalClient) { if (GetState() == TcpState.Established) { return true; } } */ //if (_IsRemoteClient) { var b = _Client.Blocking; try { _Client.Blocking = false; try { _Client.Send(_OneByte, 0, 0, 0); } catch (SocketException) { } catch { return false; } } finally { _Client.Blocking = b; } if (_Client.Connected) { return true; } } return false; } } public PortalClient() : this(new Socket(Portal.Server.AddressFamily, SocketType.Stream, ProtocolType.Tcp), Portal.ClientID, false) { } public PortalClient(Socket client) : this(client, null, true) { } private PortalClient(Socket client, ushort? serverID, bool remote) { _ReceiveQueue = new ConcurrentQueue<PortalBuffer>(); _Client = client; //_Client.ReceiveBufferSize = PortalPacket.MaxSize; //_Client.SendBufferSize = PortalPacket.MaxSize; _Client.ReceiveTimeout = 10000; _Client.SendTimeout = 10000; _Client.Blocking = true; _Client.NoDelay = true; _NextPing = Portal.Ticks + 60000; _AuthExpire = _PingExpire = Int64.MaxValue; _ServerID = serverID; _IsRemoteClient = remote; _IsLocalClient = !remote; #if DEBUG _DisplaySendOutput = true; _DisplayRecvOutput = true; #endif var ep = _IsRemoteClient ? _Client.RemoteEndPoint ?? _Client.LocalEndPoint : _Client.LocalEndPoint ?? _Client.RemoteEndPoint; _EndPoint = (IPEndPoint)ep; Handlers = new Dictionary<ushort, PortalPacketHandler>(); PortalPacketHandlers.RegisterHandlers(this); } public PortalPacketHandler Register(ushort id, PortalContext context, PortalReceive onReceive) { if (Handlers.ContainsKey(id)) { ToConsole("Warning: Replacing Packet Handler for {0}", id); } return Handlers[id] = new PortalPacketHandler(id, context, onReceive); } public PortalPacketHandler Unregister(ushort id) { PortalPacketHandler h; if (Handlers.TryGetValue(id, out h)) { Handlers.Remove(id); } return h; } public PortalPacketHandler GetHandler(ushort id) { PortalPacketHandler h; Handlers.TryGetValue(id, out h); return h; } public TcpState GetState() { if (_Client == null) { return TcpState.Unknown; } try { TcpConnectionInformation[] a; TcpConnectionInformation b; if (_IsRemoteClient) { a = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections(); b = a.SingleOrDefault(o => o.RemoteEndPoint.Equals(_Client.RemoteEndPoint)); } else if (_IsLocalClient) { a = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections(); b = a.SingleOrDefault(o => o.LocalEndPoint.Equals(_Client.LocalEndPoint)); } else { return TcpState.Unknown; } return b != null ? b.State : TcpState.Unknown; } catch { return TcpState.Unknown; } } private bool Connect() { if (_Client == null) { return false; } if (_Client.Connected) { return true; } ToConsole("Connecting: {0}...", Portal.Server); try { _Client.Connect(Portal.Server); return true; } catch { } return false; } protected override void OnStart() { if (IsDisposed || IsDisposing || _Client == null) { return; } if (_IsLocalClient) { try { var attempts = 3; while (--attempts >= 0) { if (Connect()) { break; } Thread.Sleep(10); } if (attempts < 0) { ToConsole("Connect: Failed"); Dispose(); return; } ToConsole("Connect: Success"); _AuthExpire = Portal.Ticks + 30000; } #if DEBUG catch (Exception e) { ToConsole("Connect: Failed", e); Dispose(); return; } #else catch { ToConsole("Connect: Failed"); Dispose(); return; } #endif } if (!_IsAuthed) { _AuthExpire = Portal.Ticks + 30000; } } protected override void OnStarted() { if (_IsLocalClient) { if (!Send(PortalPackets.HandshakeRequest.Create)) { Dispose(); return; } if (_IsAuthed) { ToConsole("Connect: Authorized Access"); } else { ToConsole("Connect: Unauthorized Access"); Dispose(); return; } } Portal.InvokeConnected(this); try { if (!IsAlive || ThreadPool.QueueUserWorkItem(Receive)) { Thread.Sleep(0); return; } } catch (Exception e) { ToConsole("Exception Thrown", e); } Dispose(); } private volatile bool _NoReceive; private void Receive(object state) { try { if (!_NoReceive && Receive(false) && !_NoReceive) { ProcessReceiveQueue(); } if (!IsAlive || ThreadPool.QueueUserWorkItem(Receive)) { Thread.Sleep(0); return; } } catch (Exception e) { ToConsole("Exception Thrown", e); } Dispose(); } private bool Receive(bool wait) { try { if ((!wait && _NoReceive) || !IsAlive) { return false; } if (wait) { var timer = new Stopwatch(); var timeout = _Client.ReceiveTimeout; timer.Start(); while (Pending < Peek.Size) { if (!IsAlive || (Portal.Ticks % 1000 == 0 && !IsConnected)) { timer.Stop(); return false; } if (Pending < 0 || Pending >= Peek.Size) { timer.Reset(); break; } if (timeout > 0 && timer.ElapsedMilliseconds >= timeout) { timer.Stop(); break; } Thread.Sleep(1); } } if ((!wait && _NoReceive) || !IsAlive || Pending < Peek.Size) { return false; } var peek = Peek.Acquire(); var head = 0; while (head < peek.Length && _Client != null) { head += _Client.Receive(peek, head, peek.Length - head, SocketFlags.None); if (_Client == null || !_Client.Connected || head >= peek.Length) { break; } } if (head < peek.Length) { if (_DisplayRecvOutput) { ToConsole("Recv: Peek Failed at {0} / {1} bytes", head, peek.Length); } Peek.Free(ref peek); Dispose(); return false; } var pid = BitConverter.ToUInt16(peek, 0); if (GetHandler(pid) == null) { if (_DisplayRecvOutput) { ToConsole("Recv: Unknown Packet ({0})", pid); } Peek.Free(ref peek); Dispose(); return false; } var sid = BitConverter.ToUInt16(peek, 2); if (IsRemoteClient) { if (!_IsSeeded || !_ServerID.HasValue) { _ServerID = sid; _IsSeeded = true; } else if (_ServerID != sid) { if (_DisplayRecvOutput) { ToConsole("Recv: Server ID Spoofed ({0})", sid); } Peek.Free(ref peek); Dispose(); return false; } } else if (IsLocalClient) { if (!_IsSeeded) { _IsSeeded = true; } if (!_ServerID.HasValue) { _ServerID = sid; } } var size = BitConverter.ToInt32(peek, 4); if (size < PortalPacket.MinSize || size > PortalPacket.MaxSize) { if (_DisplayRecvOutput) { ToConsole( "Recv: Size Out Of Range for {0} at {1} / {2} - {3} bytes", pid, size, PortalPacket.MinSize, PortalPacket.MaxSize); } Peek.Free(ref peek); Dispose(); return false; } var buffer = new PortalBuffer(size); for (var i = 0; i < peek.Length; i++) { buffer[i] = peek[i]; } Peek.Free(ref peek); if (size > head) { var length = head + buffer.Receive(_Client, head, size - head); if (length < size) { if (_DisplayRecvOutput) { ToConsole("Recv: Failed for {0} at {1} / {2} bytes", pid, length, size); } buffer.Dispose(); Dispose(); return false; } } if (!QueueReceive(buffer)) { buffer.Dispose(); return false; } return true; } catch (Exception e) { ToConsole("Recv: Exception Thrown", e); Dispose(); return false; } } private bool QueueReceive(PortalBuffer buffer) { if (buffer == null) { return false; } if (_ReceiveQueue == null || buffer.Size < PortalPacket.MinSize) { return false; } if (_Buffered + buffer.Size > PortalPacket.MaxSize * 8L) { if (_DisplayRecvOutput) { ToConsole("Recv: Too much data pending: {0} + {1} bytes", _Buffered, buffer.Size); } Dispose(); return false; } _ReceiveQueue.Enqueue(buffer); _Buffered += buffer.Size; return true; } private void ProcessReceiveQueue() { PortalBuffer buffer; while (_ReceiveQueue != null && !_ReceiveQueue.IsEmpty) { if (_ReceiveQueue.TryDequeue(out buffer) && buffer != null) { _Buffered -= buffer.Size; using (buffer) { ProcessReceiveBuffer(buffer); } } Thread.Sleep(0); } if (_Buffered < 0 || _ReceiveQueue == null) { _Buffered = 0; } } private void ProcessReceiveBuffer(PortalBuffer buffer) { if (buffer == null || buffer.Size < PortalPacket.MinSize) { return; } var pid = BitConverter.ToUInt16(buffer.Join(0, 2), 0); PortalPacketHandler handler; if (!Handlers.TryGetValue(pid, out handler) || handler == null) { if (_DisplayRecvOutput) { ToConsole("Recv: Missing Handler for {0}", pid); } return; } if (handler.Context == PortalContext.Disabled) { if (_DisplayRecvOutput) { ToConsole("Recv: Ignoring Packet {0}", pid); } return; } if (handler.Context != PortalContext.Any && ((handler.Context == PortalContext.Server && !IsRemoteClient) || (handler.Context == PortalContext.Client && !IsLocalClient))) { if (_DisplayRecvOutput) { ToConsole("Recv: Out Of Context Packet {0} requires {1}", pid, handler.Context); } return; } if (_DisplayRecvOutput) { ToConsole("Recv: Packet {0} at {1} bytes", pid, buffer.Size); } using (var p = new PortalPacketReader(buffer)) { handler.OnReceive(this, p); } } public override bool Send(PortalPacket p) { return InternalSend(p); } public override bool SendTarget(PortalPacket p, ushort targetID) { return _ServerID == targetID && InternalSend(p); } public override bool SendExcept(PortalPacket p, ushort exceptID) { return _ServerID != exceptID && InternalSend(p); } private bool InternalSend(PortalPacket p) { if (p == null) { return false; } if (IsDisposing && p.ID != 255) { return false; } if (!IsAlive) { return false; } /* while (!_ReceiveSync.WaitOne(10)) { if (!IsAlive || (Portal.Ticks % 1000 == 0 && !IsConnected)) { return false; } Thread.Sleep(1); } */ if (IsDisposing && p.ID != 255) { return false; } if (!IsAlive) { return false; } try { _NoReceive = true; var buffer = p.Compile(); if (buffer == null) { if (_DisplaySendOutput) { ToConsole("Send: Buffer Null for {0}", p.ID); } Dispose(); return false; } var size = buffer.Size; if (size < PortalPacket.MinSize || size > PortalPacket.MaxSize) { if (_DisplaySendOutput) { ToConsole( "Send: Size Out Of Range for {0} at {1} / {2} - {3} bytes", p.ID, size, PortalPacket.MinSize, PortalPacket.MaxSize); } Dispose(); return false; } var length = buffer.Send(_Client, 0, size); if (length < size) { if (_DisplaySendOutput) { ToConsole("Send: Failed for {0} at {1} / {2} bytes", p.ID, length, size); } Dispose(); return false; } if (_DisplaySendOutput) { ToConsole("Send: Packet {0} at {1} bytes", p.ID, size); } if (p.GetResponse) { if (!Receive(true)) { if (_DisplaySendOutput) { ToConsole("Send: {0} requires a response which could not be handled.", p.ID); } Dispose(); return false; } ProcessReceiveQueue(); } _NoReceive = false; return true; } catch (Exception e) { ToConsole("Send: Exception Thrown", e); Dispose(); return false; } finally { _NoReceive = false; } } public bool Ping(bool respond) { if (respond) { return InternalSend(PortalPackets.PingResponse.Instance); } _PingExpire = Portal.Ticks + 10000; _NextPing = Portal.Ticks + 60000; return InternalSend(PortalPackets.PingRequest.Instance); } public void Pong() { _PingExpire = Int64.MaxValue; _NextPing = Portal.Ticks + 60000; } protected override void OnBeforeDispose() { Portal.InvokeDisposed(this); base.OnBeforeDispose(); } protected override void OnDispose() { base.OnDispose(); if (Handlers != null) { Handlers.Clear(); Handlers = null; } _ReceiveQueue = null; _Client = null; } public override string ToString() { if (_EndPoint != null) { return String.Format("C{0}/{1}", _ServerID, _EndPoint.Address); } return String.Format("C{0}", _ServerID); } private static class Peek { public static int Size { get { return PortalPacket.MinSize; } } private static readonly Queue _Pool = Queue.Synchronized(new Queue()); public static byte[] Acquire() { if (_Pool.Count > 0) { return (byte[])_Pool.Dequeue(); } return new byte[Size]; } public static void Free(ref byte[] peek) { if (peek == null) { return; } for (var i = 0; i < peek.Length; i++) { peek[i] = 0; } if (peek.Length == Size) { _Pool.Enqueue(peek); } peek = null; } public static void Exchange(ref byte[] peek, byte[] buffer) { if (buffer != null) { Buffer.BlockCopy(peek, 0, buffer, 0, peek.Length); } buffer = Interlocked.Exchange(ref peek, buffer); Free(ref buffer); } } } }
using J2N.Threading.Atomic; using YAF.Lucene.Net.Documents; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Text; namespace YAF.Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BinaryDocValuesField = BinaryDocValuesField; using IBits = YAF.Lucene.Net.Util.IBits; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using Codec = YAF.Lucene.Net.Codecs.Codec; using Directory = YAF.Lucene.Net.Store.Directory; using DocValuesConsumer = YAF.Lucene.Net.Codecs.DocValuesConsumer; using DocValuesFormat = YAF.Lucene.Net.Codecs.DocValuesFormat; using IOContext = YAF.Lucene.Net.Store.IOContext; using IOUtils = YAF.Lucene.Net.Util.IOUtils; using LiveDocsFormat = YAF.Lucene.Net.Codecs.LiveDocsFormat; using IMutableBits = YAF.Lucene.Net.Util.IMutableBits; using NumericDocValuesField = NumericDocValuesField; using TrackingDirectoryWrapper = YAF.Lucene.Net.Store.TrackingDirectoryWrapper; /// <summary> /// Used by <see cref="IndexWriter"/> to hold open <see cref="SegmentReader"/>s (for /// searching or merging), plus pending deletes and updates, /// for a given segment /// </summary> internal class ReadersAndUpdates { // Not final because we replace (clone) when we need to // change it and it's been shared: public SegmentCommitInfo Info { get; private set; } // Tracks how many consumers are using this instance: private readonly AtomicInt32 refCount = new AtomicInt32(1); private readonly IndexWriter writer; // Set once (null, and then maybe set, and never set again): private SegmentReader reader; // TODO: it's sometimes wasteful that we hold open two // separate SRs (one for merging one for // reading)... maybe just use a single SR? The gains of // not loading the terms index (for merging in the // non-NRT case) are far less now... and if the app has // any deletes it'll open real readers anyway. // Set once (null, and then maybe set, and never set again): private SegmentReader mergeReader; // Holds the current shared (readable and writable) // liveDocs. this is null when there are no deleted // docs, and it's copy-on-write (cloned whenever we need // to change it but it's been shared to an external NRT // reader). private IBits liveDocs; // How many further deletions we've done against // liveDocs vs when we loaded it or last wrote it: private int pendingDeleteCount; // True if the current liveDocs is referenced by an // external NRT reader: private bool liveDocsShared; // Indicates whether this segment is currently being merged. While a segment // is merging, all field updates are also registered in the // mergingNumericUpdates map. Also, calls to writeFieldUpdates merge the // updates with mergingNumericUpdates. // That way, when the segment is done merging, IndexWriter can apply the // updates on the merged segment too. private bool isMerging = false; private readonly IDictionary<string, DocValuesFieldUpdates> mergingDVUpdates = new Dictionary<string, DocValuesFieldUpdates>(); public ReadersAndUpdates(IndexWriter writer, SegmentCommitInfo info) { this.Info = info; this.writer = writer; liveDocsShared = true; } public virtual void IncRef() { int rc = refCount.IncrementAndGet(); Debug.Assert(rc > 1); } public virtual void DecRef() { int rc = refCount.DecrementAndGet(); Debug.Assert(rc >= 0); } public virtual int RefCount() { int rc = refCount; Debug.Assert(rc >= 0); return rc; } public virtual int PendingDeleteCount { get { lock (this) { return pendingDeleteCount; } } } // Call only from assert! public virtual bool VerifyDocCounts() { lock (this) { int count; if (liveDocs != null) { count = 0; for (int docID = 0; docID < Info.Info.DocCount; docID++) { if (liveDocs.Get(docID)) { count++; } } } else { count = Info.Info.DocCount; } Debug.Assert(Info.Info.DocCount - Info.DelCount - pendingDeleteCount == count, "info.docCount=" + Info.Info.DocCount + " info.DelCount=" + Info.DelCount + " pendingDeleteCount=" + pendingDeleteCount + " count=" + count); return true; } } /// <summary> /// Returns a <see cref="SegmentReader"/>. </summary> public virtual SegmentReader GetReader(IOContext context) { if (reader == null) { // We steal returned ref: reader = new SegmentReader(Info, writer.Config.ReaderTermsIndexDivisor, context); if (liveDocs == null) { liveDocs = reader.LiveDocs; } } // Ref for caller reader.IncRef(); return reader; } // Get reader for merging (does not load the terms // index): public virtual SegmentReader GetMergeReader(IOContext context) { lock (this) { //System.out.println(" livedocs=" + rld.liveDocs); if (mergeReader == null) { if (reader != null) { // Just use the already opened non-merge reader // for merging. In the NRT case this saves us // pointless double-open: //System.out.println("PROMOTE non-merge reader seg=" + rld.info); // Ref for us: reader.IncRef(); mergeReader = reader; //System.out.println(Thread.currentThread().getName() + ": getMergeReader share seg=" + info.name); } else { //System.out.println(Thread.currentThread().getName() + ": getMergeReader seg=" + info.name); // We steal returned ref: mergeReader = new SegmentReader(Info, -1, context); if (liveDocs == null) { liveDocs = mergeReader.LiveDocs; } } } // Ref for caller mergeReader.IncRef(); return mergeReader; } } public virtual void Release(SegmentReader sr) { lock (this) { Debug.Assert(Info == sr.SegmentInfo); sr.DecRef(); } } public virtual bool Delete(int docID) { lock (this) { Debug.Assert(liveDocs != null); //Debug.Assert(Thread.holdsLock(Writer)); Debug.Assert(docID >= 0 && docID < liveDocs.Length, "out of bounds: docid=" + docID + " liveDocsLength=" + liveDocs.Length + " seg=" + Info.Info.Name + " docCount=" + Info.Info.DocCount); Debug.Assert(!liveDocsShared); bool didDelete = liveDocs.Get(docID); if (didDelete) { ((IMutableBits)liveDocs).Clear(docID); pendingDeleteCount++; //System.out.println(" new del seg=" + info + " docID=" + docID + " pendingDelCount=" + pendingDeleteCount + " totDelCount=" + (info.docCount-liveDocs.count())); } return didDelete; } } // NOTE: removes callers ref public virtual void DropReaders() { lock (this) { // TODO: can we somehow use IOUtils here...? problem is // we are calling .decRef not .close)... try { if (reader != null) { //System.out.println(" pool.drop info=" + info + " rc=" + reader.getRefCount()); try { reader.DecRef(); } finally { reader = null; } } } finally { if (mergeReader != null) { //System.out.println(" pool.drop info=" + info + " merge rc=" + mergeReader.getRefCount()); try { mergeReader.DecRef(); } finally { mergeReader = null; } } } DecRef(); } } /// <summary> /// Returns a ref to a clone. NOTE: you should <see cref="DecRef()"/> the reader when you're /// done (ie do not call <see cref="IndexReader.Dispose()"/>). /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public virtual SegmentReader GetReadOnlyClone(IOContext context) { lock (this) { if (reader == null) { GetReader(context).DecRef(); Debug.Assert(reader != null); } liveDocsShared = true; if (liveDocs != null) { return new SegmentReader(reader.SegmentInfo, reader, liveDocs, Info.Info.DocCount - Info.DelCount - pendingDeleteCount); } else { Debug.Assert(reader.LiveDocs == liveDocs); reader.IncRef(); return reader; } } } public virtual void InitWritableLiveDocs() { lock (this) { //Debug.Assert(Thread.holdsLock(Writer)); Debug.Assert(Info.Info.DocCount > 0); //System.out.println("initWritableLivedocs seg=" + info + " liveDocs=" + liveDocs + " shared=" + shared); if (liveDocsShared) { // Copy on write: this means we've cloned a // SegmentReader sharing the current liveDocs // instance; must now make a private clone so we can // change it: LiveDocsFormat liveDocsFormat = Info.Info.Codec.LiveDocsFormat; if (liveDocs == null) { //System.out.println("create BV seg=" + info); liveDocs = liveDocsFormat.NewLiveDocs(Info.Info.DocCount); } else { liveDocs = liveDocsFormat.NewLiveDocs(liveDocs); } liveDocsShared = false; } } } public virtual IBits LiveDocs { get { lock (this) { //Debug.Assert(Thread.holdsLock(Writer)); return liveDocs; } } } public virtual IBits GetReadOnlyLiveDocs() { lock (this) { //System.out.println("getROLiveDocs seg=" + info); //Debug.Assert(Thread.holdsLock(Writer)); liveDocsShared = true; //if (liveDocs != null) { //System.out.println(" liveCount=" + liveDocs.count()); //} return liveDocs; } } public virtual void DropChanges() { lock (this) { // Discard (don't save) changes when we are dropping // the reader; this is used only on the sub-readers // after a successful merge. If deletes had // accumulated on those sub-readers while the merge // is running, by now we have carried forward those // deletes onto the newly merged segment, so we can // discard them on the sub-readers: pendingDeleteCount = 0; DropMergingUpdates(); } } // Commit live docs (writes new _X_N.del files) and field updates (writes new // _X_N updates files) to the directory; returns true if it wrote any file // and false if there were no new deletes or updates to write: // TODO (DVU_RENAME) to writeDeletesAndUpdates [MethodImpl(MethodImplOptions.NoInlining)] public virtual bool WriteLiveDocs(Directory dir) { lock (this) { //Debug.Assert(Thread.holdsLock(Writer)); //System.out.println("rld.writeLiveDocs seg=" + info + " pendingDelCount=" + pendingDeleteCount + " numericUpdates=" + numericUpdates); if (pendingDeleteCount == 0) { return false; } // We have new deletes Debug.Assert(liveDocs.Length == Info.Info.DocCount); // Do this so we can delete any created files on // exception; this saves all codecs from having to do // it: TrackingDirectoryWrapper trackingDir = new TrackingDirectoryWrapper(dir); // We can write directly to the actual name (vs to a // .tmp & renaming it) because the file is not live // until segments file is written: bool success = false; try { Codec codec = Info.Info.Codec; codec.LiveDocsFormat.WriteLiveDocs((IMutableBits)liveDocs, trackingDir, Info, pendingDeleteCount, IOContext.DEFAULT); success = true; } finally { if (!success) { // Advance only the nextWriteDelGen so that a 2nd // attempt to write will write to a new file Info.AdvanceNextWriteDelGen(); // Delete any partially created file(s): foreach (string fileName in trackingDir.CreatedFiles) { try { dir.DeleteFile(fileName); } catch (Exception) { // Ignore so we throw only the first exc } } } } // If we hit an exc in the line above (eg disk full) // then info's delGen remains pointing to the previous // (successfully written) del docs: Info.AdvanceDelGen(); Info.DelCount = Info.DelCount + pendingDeleteCount; pendingDeleteCount = 0; return true; } } // Writes field updates (new _X_N updates files) to the directory [MethodImpl(MethodImplOptions.NoInlining)] public virtual void WriteFieldUpdates(Directory dir, DocValuesFieldUpdates.Container dvUpdates) { lock (this) { //Debug.Assert(Thread.holdsLock(Writer)); //System.out.println("rld.writeFieldUpdates: seg=" + info + " numericFieldUpdates=" + numericFieldUpdates); Debug.Assert(dvUpdates.Any()); // Do this so we can delete any created files on // exception; this saves all codecs from having to do // it: TrackingDirectoryWrapper trackingDir = new TrackingDirectoryWrapper(dir); FieldInfos fieldInfos = null; bool success = false; try { Codec codec = Info.Info.Codec; // reader could be null e.g. for a just merged segment (from // IndexWriter.commitMergedDeletes). SegmentReader reader = this.reader == null ? new SegmentReader(Info, writer.Config.ReaderTermsIndexDivisor, IOContext.READ_ONCE) : this.reader; try { // clone FieldInfos so that we can update their dvGen separately from // the reader's infos and write them to a new fieldInfos_gen file FieldInfos.Builder builder = new FieldInfos.Builder(writer.globalFieldNumberMap); // cannot use builder.add(reader.getFieldInfos()) because it does not // clone FI.attributes as well FI.dvGen foreach (FieldInfo fi in reader.FieldInfos) { FieldInfo clone = builder.Add(fi); // copy the stuff FieldInfos.Builder doesn't copy if (fi.Attributes != null) { foreach (KeyValuePair<string, string> e in fi.Attributes) { clone.PutAttribute(e.Key, e.Value); } } clone.DocValuesGen = fi.DocValuesGen; } // create new fields or update existing ones to have NumericDV type foreach (string f in dvUpdates.numericDVUpdates.Keys) { builder.AddOrUpdate(f, NumericDocValuesField.TYPE); } // create new fields or update existing ones to have BinaryDV type foreach (string f in dvUpdates.binaryDVUpdates.Keys) { builder.AddOrUpdate(f, BinaryDocValuesField.fType); } fieldInfos = builder.Finish(); long nextFieldInfosGen = Info.NextFieldInfosGen; string segmentSuffix = nextFieldInfosGen.ToString(CultureInfo.InvariantCulture);//Convert.ToString(nextFieldInfosGen, Character.MAX_RADIX)); SegmentWriteState state = new SegmentWriteState(null, trackingDir, Info.Info, fieldInfos, writer.Config.TermIndexInterval, null, IOContext.DEFAULT, segmentSuffix); DocValuesFormat docValuesFormat = codec.DocValuesFormat; DocValuesConsumer fieldsConsumer = docValuesFormat.FieldsConsumer(state); bool fieldsConsumerSuccess = false; try { // System.out.println("[" + Thread.currentThread().getName() + "] RLD.writeFieldUpdates: applying numeric updates; seg=" + info + " updates=" + numericFieldUpdates); foreach (KeyValuePair<string, NumericDocValuesFieldUpdates> e in dvUpdates.numericDVUpdates) { string field = e.Key; NumericDocValuesFieldUpdates fieldUpdates = e.Value; FieldInfo fieldInfo = fieldInfos.FieldInfo(field); Debug.Assert(fieldInfo != null); fieldInfo.DocValuesGen = nextFieldInfosGen; // write the numeric updates to a new gen'd docvalues file fieldsConsumer.AddNumericField(fieldInfo, GetInt64Enumerable(reader, field, fieldUpdates)); } // System.out.println("[" + Thread.currentThread().getName() + "] RAU.writeFieldUpdates: applying binary updates; seg=" + info + " updates=" + dvUpdates.binaryDVUpdates); foreach (KeyValuePair<string, BinaryDocValuesFieldUpdates> e in dvUpdates.binaryDVUpdates) { string field = e.Key; BinaryDocValuesFieldUpdates dvFieldUpdates = e.Value; FieldInfo fieldInfo = fieldInfos.FieldInfo(field); Debug.Assert(fieldInfo != null); // System.out.println("[" + Thread.currentThread().getName() + "] RAU.writeFieldUpdates: applying binary updates; seg=" + info + " f=" + dvFieldUpdates + ", updates=" + dvFieldUpdates); fieldInfo.DocValuesGen = nextFieldInfosGen; // write the numeric updates to a new gen'd docvalues file fieldsConsumer.AddBinaryField(fieldInfo, GetBytesRefEnumerable(reader, field, dvFieldUpdates)); } codec.FieldInfosFormat.FieldInfosWriter.Write(trackingDir, Info.Info.Name, segmentSuffix, fieldInfos, IOContext.DEFAULT); fieldsConsumerSuccess = true; } finally { if (fieldsConsumerSuccess) { fieldsConsumer.Dispose(); } else { IOUtils.DisposeWhileHandlingException(fieldsConsumer); } } } finally { if (reader != this.reader) { // System.out.println("[" + Thread.currentThread().getName() + "] RLD.writeLiveDocs: closeReader " + reader); reader.Dispose(); } } success = true; } finally { if (!success) { // Advance only the nextWriteDocValuesGen so that a 2nd // attempt to write will write to a new file Info.AdvanceNextWriteFieldInfosGen(); // Delete any partially created file(s): foreach (string fileName in trackingDir.CreatedFiles) { try { dir.DeleteFile(fileName); } catch (Exception) { // Ignore so we throw only the first exc } } } } Info.AdvanceFieldInfosGen(); // copy all the updates to mergingUpdates, so they can later be applied to the merged segment if (isMerging) { foreach (KeyValuePair<string, NumericDocValuesFieldUpdates> e in dvUpdates.numericDVUpdates) { DocValuesFieldUpdates updates; if (!mergingDVUpdates.TryGetValue(e.Key, out updates)) { mergingDVUpdates[e.Key] = e.Value; } else { updates.Merge(e.Value); } } foreach (KeyValuePair<string, BinaryDocValuesFieldUpdates> e in dvUpdates.binaryDVUpdates) { DocValuesFieldUpdates updates; if (!mergingDVUpdates.TryGetValue(e.Key, out updates)) { mergingDVUpdates[e.Key] = e.Value; } else { updates.Merge(e.Value); } } } // create a new map, keeping only the gens that are in use IDictionary<long, ISet<string>> genUpdatesFiles = Info.UpdatesFiles; IDictionary<long, ISet<string>> newGenUpdatesFiles = new Dictionary<long, ISet<string>>(); long fieldInfosGen = Info.FieldInfosGen; foreach (FieldInfo fi in fieldInfos) { long dvGen = fi.DocValuesGen; if (dvGen != -1 && !newGenUpdatesFiles.ContainsKey(dvGen)) { if (dvGen == fieldInfosGen) { newGenUpdatesFiles[fieldInfosGen] = trackingDir.CreatedFiles; } else { newGenUpdatesFiles[dvGen] = genUpdatesFiles[dvGen]; } } } Info.SetGenUpdatesFiles(newGenUpdatesFiles); // wrote new files, should checkpoint() writer.Checkpoint(); // if there is a reader open, reopen it to reflect the updates if (reader != null) { SegmentReader newReader = new SegmentReader(Info, reader, liveDocs, Info.Info.DocCount - Info.DelCount - pendingDeleteCount); bool reopened = false; try { reader.DecRef(); reader = newReader; reopened = true; } finally { if (!reopened) { newReader.DecRef(); } } } } } /// <summary> /// NOTE: This was getLongEnumerable() in Lucene /// </summary> private IEnumerable<long?> GetInt64Enumerable(SegmentReader reader, string field, NumericDocValuesFieldUpdates fieldUpdates) { int maxDoc = reader.MaxDoc; IBits DocsWithField = reader.GetDocsWithField(field); NumericDocValues currentValues = reader.GetNumericDocValues(field); NumericDocValuesFieldUpdates.Iterator iter = (NumericDocValuesFieldUpdates.Iterator)fieldUpdates.GetIterator(); int updateDoc = iter.NextDoc(); for (int curDoc = 0; curDoc < maxDoc; ++curDoc) { if (curDoc == updateDoc) //document has an updated value { long? value = (long?)iter.Value; // either null or updated updateDoc = iter.NextDoc(); //prepare for next round yield return value; } else { // no update for this document if (currentValues != null && DocsWithField.Get(curDoc)) { // only read the current value if the document had a value before yield return currentValues.Get(curDoc); } else { yield return null; } } } } private IEnumerable<BytesRef> GetBytesRefEnumerable(SegmentReader reader, string field, BinaryDocValuesFieldUpdates fieldUpdates) { BinaryDocValues currentValues = reader.GetBinaryDocValues(field); IBits DocsWithField = reader.GetDocsWithField(field); int maxDoc = reader.MaxDoc; var iter = (BinaryDocValuesFieldUpdates.Iterator)fieldUpdates.GetIterator(); int updateDoc = iter.NextDoc(); for (int curDoc = 0; curDoc < maxDoc; ++curDoc) { if (curDoc == updateDoc) //document has an updated value { BytesRef value = (BytesRef)iter.Value; // either null or updated updateDoc = iter.NextDoc(); //prepare for next round yield return value; } else { // no update for this document if (currentValues != null && DocsWithField.Get(curDoc)) { var scratch = new BytesRef(); // only read the current value if the document had a value before currentValues.Get(curDoc, scratch); yield return scratch; } else { yield return null; } } } } /// <summary> /// Returns a reader for merge. this method applies field updates if there are /// any and marks that this segment is currently merging. /// </summary> internal virtual SegmentReader GetReaderForMerge(IOContext context) { lock (this) { //Debug.Assert(Thread.holdsLock(Writer)); // must execute these two statements as atomic operation, otherwise we // could lose updates if e.g. another thread calls writeFieldUpdates in // between, or the updates are applied to the obtained reader, but then // re-applied in IW.commitMergedDeletes (unnecessary work and potential // bugs). isMerging = true; return GetReader(context); } } /// <summary> /// Drops all merging updates. Called from IndexWriter after this segment /// finished merging (whether successfully or not). /// </summary> public virtual void DropMergingUpdates() { lock (this) { mergingDVUpdates.Clear(); isMerging = false; } } /// <summary> /// Returns updates that came in while this segment was merging. </summary> public virtual IDictionary<string, DocValuesFieldUpdates> MergingFieldUpdates { get { lock (this) { return mergingDVUpdates; } } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("ReadersAndLiveDocs(seg=").Append(Info); sb.Append(" pendingDeleteCount=").Append(pendingDeleteCount); sb.Append(" liveDocsShared=").Append(liveDocsShared); return sb.ToString(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Security; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.OptionalModules.Scripting.Minimodule.Object; using OpenSim.Region.Physics.Manager; using PrimType=OpenSim.Region.OptionalModules.Scripting.Minimodule.Object.PrimType; using SculptType=OpenSim.Region.OptionalModules.Scripting.Minimodule.Object.SculptType; namespace OpenSim.Region.OptionalModules.Scripting.Minimodule { class SOPObject : MarshalByRefObject, IObject, IObjectPhysics, IObjectShape, IObjectSound { private readonly Scene m_rootScene; private readonly uint m_localID; private readonly ISecurityCredential m_security; [Obsolete("Replace with 'credential' constructor [security]")] public SOPObject(Scene rootScene, uint localID) { m_rootScene = rootScene; m_localID = localID; } public SOPObject(Scene rootScene, uint localID, ISecurityCredential credential) { m_rootScene = rootScene; m_localID = localID; m_security = credential; } /// <summary> /// This needs to run very, very quickly. /// It is utilized in nearly every property and method. /// </summary> /// <returns></returns> private SceneObjectPart GetSOP() { return m_rootScene.GetSceneObjectPart(m_localID); } private bool CanEdit() { if (!m_security.CanEditObject(this)) { throw new SecurityException("Insufficient Permission to edit object with UUID [" + GetSOP().UUID + "]"); } return true; } #region OnTouch private event OnTouchDelegate _OnTouch; private bool _OnTouchActive = false; public event OnTouchDelegate OnTouch { add { if (CanEdit()) { if (!_OnTouchActive) { GetSOP().Flags |= PrimFlags.Touch; _OnTouchActive = true; m_rootScene.EventManager.OnObjectGrab += EventManager_OnObjectGrab; } _OnTouch += value; } } remove { _OnTouch -= value; if (_OnTouch == null) { GetSOP().Flags &= ~PrimFlags.Touch; _OnTouchActive = false; m_rootScene.EventManager.OnObjectGrab -= EventManager_OnObjectGrab; } } } void EventManager_OnObjectGrab(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { if (_OnTouchActive && m_localID == localID) { TouchEventArgs e = new TouchEventArgs(); e.Avatar = new SPAvatar(m_rootScene, remoteClient.AgentId, m_security); e.TouchBiNormal = surfaceArgs.Binormal; e.TouchMaterialIndex = surfaceArgs.FaceIndex; e.TouchNormal = surfaceArgs.Normal; e.TouchPosition = surfaceArgs.Position; e.TouchST = new Vector2(surfaceArgs.STCoord.X, surfaceArgs.STCoord.Y); e.TouchUV = new Vector2(surfaceArgs.UVCoord.X, surfaceArgs.UVCoord.Y); IObject sender = this; if (_OnTouch != null) _OnTouch(sender, e); } } #endregion public bool Exists { get { return GetSOP() != null; } } public uint LocalID { get { return m_localID; } } public UUID GlobalID { get { return GetSOP().UUID; } } public string Name { get { return GetSOP().Name; } set { if (CanEdit()) GetSOP().Name = value; } } public string Description { get { return GetSOP().Description; } set { if (CanEdit()) GetSOP().Description = value; } } public IObject[] Children { get { SceneObjectPart my = GetSOP(); int total = my.ParentGroup.Children.Count; IObject[] rets = new IObject[total]; int i = 0; foreach (KeyValuePair<UUID, SceneObjectPart> pair in my.ParentGroup.Children) { rets[i++] = new SOPObject(m_rootScene, pair.Value.LocalId, m_security); } return rets; } } public IObject Root { get { return new SOPObject(m_rootScene, GetSOP().ParentGroup.RootPart.LocalId, m_security); } } public IObjectMaterial[] Materials { get { SceneObjectPart sop = GetSOP(); IObjectMaterial[] rets = new IObjectMaterial[getNumberOfSides(sop)]; for (int i = 0; i < rets.Length; i++) { rets[i] = new SOPObjectMaterial(i, sop); } return rets; } } public Vector3 Scale { get { return GetSOP().Scale; } set { if (CanEdit()) GetSOP().Scale = value; } } public Quaternion WorldRotation { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public Quaternion OffsetRotation { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public Vector3 WorldPosition { get { return GetSOP().AbsolutePosition; } set { if (CanEdit()) { SceneObjectPart pos = GetSOP(); pos.UpdateOffSet(value - pos.AbsolutePosition); } } } public Vector3 OffsetPosition { get { return GetSOP().OffsetPosition; } set { if (CanEdit()) { GetSOP().OffsetPosition = value; } } } public Vector3 SitTarget { get { return GetSOP().SitTargetPosition; } set { if (CanEdit()) { GetSOP().SitTargetPosition = value; } } } public string SitTargetText { get { return GetSOP().SitName; } set { if (CanEdit()) { GetSOP().SitName = value; } } } public string TouchText { get { return GetSOP().TouchName; } set { if (CanEdit()) { GetSOP().TouchName = value; } } } public string Text { get { return GetSOP().Text; } set { if (CanEdit()) { GetSOP().SetText(value,new Vector3(1.0f,1.0f,1.0f),1.0f); } } } public bool IsRotationLockedX { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsRotationLockedY { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsRotationLockedZ { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsSandboxed { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsImmotile { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsAlwaysReturned { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsTemporary { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsFlexible { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public PhysicsMaterial PhysicsMaterial { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public IObjectPhysics Physics { get { return this; } } public IObjectShape Shape { get { return this; } } public IObjectInventory Inventory { get { return new SOPObjectInventory(m_rootScene, GetSOP().TaskInventory); } } #region Public Functions public void Say(string msg) { if (!CanEdit()) return; SceneObjectPart sop = GetSOP(); m_rootScene.SimChat(msg, ChatTypeEnum.Say, sop.AbsolutePosition, sop.Name, sop.UUID, false); } public void Say(string msg,int channel) { if (!CanEdit()) return; SceneObjectPart sop = GetSOP(); m_rootScene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,channel, sop.AbsolutePosition, sop.Name, sop.UUID, false); } #endregion #region Supporting Functions // Helper functions to understand if object has cut, hollow, dimple, and other affecting number of faces private static void hasCutHollowDimpleProfileCut(int primType, PrimitiveBaseShape shape, out bool hasCut, out bool hasHollow, out bool hasDimple, out bool hasProfileCut) { if (primType == (int)PrimType.Box || primType == (int)PrimType.Cylinder || primType == (int)PrimType.Prism) hasCut = (shape.ProfileBegin > 0) || (shape.ProfileEnd > 0); else hasCut = (shape.PathBegin > 0) || (shape.PathEnd > 0); hasHollow = shape.ProfileHollow > 0; hasDimple = (shape.ProfileBegin > 0) || (shape.ProfileEnd > 0); // taken from llSetPrimitiveParms hasProfileCut = hasDimple; // is it the same thing? } private static int getScriptPrimType(PrimitiveBaseShape primShape) { if (primShape.SculptEntry) return (int) PrimType.Sculpt; if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.Square) { if (primShape.PathCurve == (byte) Extrusion.Straight) return (int) PrimType.Box; if (primShape.PathCurve == (byte) Extrusion.Curve1) return (int) PrimType.Tube; } else if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.Circle) { if (primShape.PathCurve == (byte) Extrusion.Straight) return (int) PrimType.Cylinder; if (primShape.PathCurve == (byte) Extrusion.Curve1) return (int) PrimType.Torus; } else if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.HalfCircle) { if (primShape.PathCurve == (byte) Extrusion.Curve1 || primShape.PathCurve == (byte) Extrusion.Curve2) return (int) PrimType.Sphere; } else if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.EquilateralTriangle) { if (primShape.PathCurve == (byte) Extrusion.Straight) return (int) PrimType.Prism; if (primShape.PathCurve == (byte) Extrusion.Curve1) return (int) PrimType.Ring; } return (int) PrimType.NotPrimitive; } private static int getNumberOfSides(SceneObjectPart part) { int ret; bool hasCut; bool hasHollow; bool hasDimple; bool hasProfileCut; int primType = getScriptPrimType(part.Shape); hasCutHollowDimpleProfileCut(primType, part.Shape, out hasCut, out hasHollow, out hasDimple, out hasProfileCut); switch (primType) { default: case (int) PrimType.Box: ret = 6; if (hasCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Cylinder: ret = 3; if (hasCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Prism: ret = 5; if (hasCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Sphere: ret = 1; if (hasCut) ret += 2; if (hasDimple) ret += 2; if (hasHollow) ret += 1; // GOTCHA: LSL shows 2 additional sides here. // This has been fixed, but may cause porting issues. break; case (int) PrimType.Torus: ret = 1; if (hasCut) ret += 2; if (hasProfileCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Tube: ret = 4; if (hasCut) ret += 2; if (hasProfileCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Ring: ret = 3; if (hasCut) ret += 2; if (hasProfileCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Sculpt: ret = 1; break; } return ret; } #endregion #region IObjectPhysics public bool Enabled { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool Phantom { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool PhantomCollisions { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public double Density { get { return (GetSOP().PhysActor.Mass/Scale.X*Scale.Y/Scale.Z); } set { throw new NotImplementedException(); } } public double Mass { get { return GetSOP().PhysActor.Mass; } set { throw new NotImplementedException(); } } public double Buoyancy { get { return GetSOP().PhysActor.Buoyancy; } set { GetSOP().PhysActor.Buoyancy = (float)value; } } public Vector3 GeometricCenter { get { Vector3 tmp = GetSOP().PhysActor.GeometricCenter; return tmp; } } public Vector3 CenterOfMass { get { Vector3 tmp = GetSOP().PhysActor.CenterOfMass; return tmp; } } public Vector3 RotationalVelocity { get { Vector3 tmp = GetSOP().PhysActor.RotationalVelocity; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.RotationalVelocity = value; } } public Vector3 Velocity { get { Vector3 tmp = GetSOP().PhysActor.Velocity; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.Velocity = value; } } public Vector3 Torque { get { Vector3 tmp = GetSOP().PhysActor.Torque; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.Torque = value; } } public Vector3 Acceleration { get { Vector3 tmp = GetSOP().PhysActor.Acceleration; return tmp; } } public Vector3 Force { get { Vector3 tmp = GetSOP().PhysActor.Force; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.Force = value; } } public bool FloatOnWater { set { if (!CanEdit()) return; GetSOP().PhysActor.FloatOnWater = value; } } public void AddForce(Vector3 force, bool pushforce) { if (!CanEdit()) return; GetSOP().PhysActor.AddForce(force, pushforce); } public void AddAngularForce(Vector3 force, bool pushforce) { if (!CanEdit()) return; GetSOP().PhysActor.AddAngularForce(force, pushforce); } public void SetMomentum(Vector3 momentum) { if (!CanEdit()) return; GetSOP().PhysActor.SetMomentum(momentum); } #endregion #region Implementation of IObjectShape private UUID m_sculptMap = UUID.Zero; public UUID SculptMap { get { return m_sculptMap; } set { if (!CanEdit()) return; m_sculptMap = value; SetPrimitiveSculpted(SculptMap, (byte) SculptType); } } private SculptType m_sculptType = Object.SculptType.Default; public SculptType SculptType { get { return m_sculptType; } set { if (!CanEdit()) return; m_sculptType = value; SetPrimitiveSculpted(SculptMap, (byte) SculptType); } } public HoleShape HoleType { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public double HoleSize { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public PrimType PrimType { get { return (PrimType)getScriptPrimType(GetSOP().Shape); } set { throw new System.NotImplementedException(); } } private void SetPrimitiveSculpted(UUID map, byte type) { ObjectShapePacket.ObjectDataBlock shapeBlock = new ObjectShapePacket.ObjectDataBlock(); SceneObjectPart part = GetSOP(); UUID sculptId = map; shapeBlock.ObjectLocalID = part.LocalId; shapeBlock.PathScaleX = 100; shapeBlock.PathScaleY = 150; // retain pathcurve shapeBlock.PathCurve = part.Shape.PathCurve; part.Shape.SetSculptData((byte)type, sculptId); part.Shape.SculptEntry = true; part.UpdateShape(shapeBlock); } #endregion #region Implementation of IObjectSound public IObjectSound Sound { get { return this; } } public void Play(UUID asset, double volume) { if (!CanEdit()) return; GetSOP().SendSound(asset.ToString(), volume, true, 0, 0, false, false); } #endregion } }
//----------------------------------------------------------------------- // <copyright file="Sprite.cs" company=""> // Copyright (c) . All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace OpenTK.SpriteManager { using System; using System.Diagnostics.Contracts; using System.Drawing; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using OpenTK.Graphics.OpenGL; /// <summary> /// Layout for origin. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum Layout { TopLeft, TopCenter, TopRight, CenterLeft, Center, CenterRight, BottomLeft, BottomCenter, BottomRight } /// <summary> /// Represents a stored <see cref="Bitmap"/> image. /// </summary> public struct Sprite : IDisposable { /// <summary> /// Initializes a new instance of the <see cref="Sprite" /> struct from a file. /// </summary> /// <param name="name">The name.</param> /// <param name="transparent">if set to <c>true</c> uses transparency.</param> /// <param name="origin">The origin.</param> /// <param name="imageNumber">The image number.</param> [JsonConstructor] public Sprite(string name, bool transparent, Layout origin, Vector2 imageNumber = new Vector2()) { Name = name; Transparent = transparent; Origin = origin; ImageNumber = Vector2.Max(Vector2.One, imageNumber); Id = 0; ImageIndex = Vector2.Zero; Size = Vector2.Zero; // load the sprite Load(); } /// <summary> /// Initializes a new instance of the <see cref="Sprite" /> struct from a byte array. /// </summary> /// <param name="size">The size.</param> /// <param name="bytes">The bytes.</param> /// <param name="transparent">if set to <c>true</c> uses transparency.</param> /// <param name="origin">The origin.</param> /// <param name="imageNumber">The image number.</param> public Sprite(Vector2 size, byte[] bytes, bool transparent, Layout origin, Vector2 imageNumber = new Vector2()) { Contract.Requires(Size.X > 0 && Size.Y > 0); Contract.Requires(bytes.Length == (int)size.X * (transparent ? (int)size.Y * 4 : (int)size.Y * 3)); Transparent = transparent; Origin = origin; ImageNumber = Vector2.Max(Vector2.One, imageNumber); ImageIndex = Vector2.Zero; // generate the texture id Id = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, Id); // set the size Size = size; // create the texture GL.TexImage2D( TextureTarget.Texture2D, 0, transparent ? PixelInternalFormat.Rgba : PixelInternalFormat.Rgb, (int)(Size.X * ImageNumber.X), (int)(Size.Y * ImageNumber.Y), 0, transparent ? PixelFormat.Bgra : PixelFormat.Bgr, PixelType.UnsignedByte, bytes); Name = "Generated"; // register the sprite SpriteManager.Register(this); // set the texture parameters SetParameters(); } /// <summary> /// Gets the identifier. /// </summary> /// <value>The identifier.</value> [JsonIgnore] public int Id { get; private set; } /// <summary> /// Gets or sets the index of the image. /// </summary> /// <value> /// The index of the image. /// </value> [JsonIgnore] public Vector2 ImageIndex { get; set; } /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public string Name { get; } /// <summary> /// Gets or sets the origin. /// </summary> /// <value>The origin.</value> public Layout Origin { get; } /// <summary> /// Gets or sets the number of images contained in this sprite. /// </summary> /// <value> /// The number of images. /// </value> [JsonConverter(typeof(Vector2Converter))] public Vector2 ImageNumber { get; set; } /// <summary> /// Gets the size. /// </summary> /// <value>The size.</value> [JsonIgnore] public Vector2 Size { get; private set; } /// <summary> /// Gets or set a value indicating whether this <see cref="Sprite"/> has transparency. /// </summary> /// <value><c>true</c> if transparent; otherwise, <c>false</c>.</value> public bool Transparent { get; set; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="source">The source.</param> /// <param name="other">The other.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(Sprite source, Sprite other) { return !source.Equals(other); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="source">The source.</param> /// <param name="other">The other.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(Sprite source, Sprite other) { return source.Equals(other); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting /// unmanaged resources. /// </summary> public void Dispose() { GL.DeleteTexture(Id); GC.SuppressFinalize(this); } /// <summary> /// Draws this instance at the specified position. /// </summary> /// <param name="position">The position.</param> public void Draw(Vector2 position) { Draw(position, Size, Color.White); } /// <summary> /// Draws this instance with the specified parameters. /// </summary> /// <param name="position">The position.</param> /// <param name="scale">The scale.</param> /// <param name="color">The color.</param> public void Draw(Vector2 position, float scale, Color color) { Contract.Requires(scale > 0); Draw(position, Size * scale, color); } /// <summary> /// Draws this instance with the specified parameters. /// </summary> /// <param name="position">The position.</param> /// <param name="size">The size.</param> /// <param name="color">The color.</param> public void Draw(Vector2 position, Vector2 size, Color color) { Contract.Requires(size.X > 0 && Size.Y > 0); var drawPosition = position - (Origin.ToVector2() * size); if (color.A < 255 || Transparent) GL.Enable(EnableCap.Blend); GL.Enable(EnableCap.Texture2D); GL.BindTexture(TextureTarget.Texture2D, Id); GL.Begin(PrimitiveType.Quads); GL.Color4(color); GL.TexCoord2(0, 0); GL.Vertex2(drawPosition.X, drawPosition.Y); GL.TexCoord2(1, 0); GL.Vertex2(drawPosition.X + size.X, drawPosition.Y); GL.TexCoord2(1, 1); GL.Vertex2(drawPosition.X + size.X, drawPosition.Y + size.Y); GL.TexCoord2(0, 1); GL.Vertex2(drawPosition.X, drawPosition.Y + size.Y); GL.Color4(Color.White); GL.End(); GL.Disable(EnableCap.Texture2D); GL.Disable(EnableCap.Blend); GL.LoadIdentity(); } /// <summary> /// Draws this instance repeated at the specified positions. /// </summary> /// <param name="start">The start.</param> /// <param name="end">The end.</param> public void DrawRepeated(Vector2 start, Vector2 end) { DrawRepeated(start, end, Size, Color.White); } /// <summary> /// Draws this instance repeated with the specified parameters. /// </summary> /// <param name="start">The start.</param> /// <param name="end">The end.</param> /// <param name="scale">The scale.</param> /// <param name="color">The color.</param> public void DrawRepeated(Vector2 start, Vector2 end, float scale, Color color) { Contract.Requires(scale > 0); DrawRepeated(start, end, Size * scale, color); } /// <summary> /// Draws this instance repeated with the specified parameters. /// </summary> /// <param name="start">The start.</param> /// <param name="end">The end.</param> /// <param name="size">The size.</param> /// <param name="color">The color.</param> public void DrawRepeated(Vector2 start, Vector2 end, Vector2 size, Color color) { Contract.Requires(size.X > 0 && Size.Y > 0); // calculate position differences var diff = new Vector2(end.X - start.X, end.Y - start.Y); // calculate number of repeats by find the distance between a zero Vector2 and the // position difference var repeats = (int)Math.Round(Vector2.Zero.Distance(diff / size.X)); //// int drawAngle = angle + (int)Math.Round(start.Angle(end)); var step = repeats != 0 ? diff / repeats : Vector2.Zero; for (int i = 0; i <= repeats; i++) Draw(start + step * i, size, color); } /// <summary> /// Determines whether the specified <see cref="object"/>, is equal to this instance. /// </summary> /// <param name="obj">The <see cref="object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return obj is Sprite && Equals((Sprite)obj); } /// <summary> /// Determines whether the specified <see cref="Sprite"/>, is equal to this instance. /// </summary> /// <param name="sprite">The <see cref="Sprite"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="Sprite"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(Sprite sprite) { return Id.Equals(sprite.Id); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data /// structures like a hash table. /// </returns> public override int GetHashCode() { return Id.GetHashCode(); } /// <summary> /// Returns a <see cref="string"/> that represents this instance. /// </summary> /// <returns>A <see cref="string"/> that represents this instance.</returns> public override string ToString() { return Id.ToString() + ':' + Name; } /// <summary> /// Loads the sprite. /// </summary> public void Load() { // ensure file exists if (!File.Exists(SpriteManager.Directory + Name)) return; // check if this sprite was already loaded var id = SpriteManager.FindSprite(Name).Id; if (id != 0) { // set the id to the previously loaded one's Id = id; return; } // generate the texture id Id = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, Id); using (var bitmap = new Bitmap(SpriteManager.Directory + Name)) { // set the size Size = new Vector2(bitmap.Width / ImageNumber.X, bitmap.Height / ImageNumber.Y); // load the bitmap data var bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); try { // create the texture GL.TexImage2D( TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmap.Width, bitmap.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bitmapData.Scan0); } finally { bitmap.UnlockBits(bitmapData); } } // register the sprite SpriteManager.Register(this); // set the texture parameters SetParameters(); } /// <summary> /// Sets the texture parameters. /// </summary> private static void SetParameters() { GL.TexParameter( TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter( TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); } } }
using System; using System.IO; using System.Text; namespace SineSignal.Ottoman.Serialization { // This is loosely based off of LitJson's Lexer. I modified the naming convention and also updated // it a little also to take advantage of newer language features. It will do for now, until I have // more time to revisit and finish the task below. // TODO: Refactor using the State pattern(http://www.dofactory.com/Patterns/PatternState.aspx). It will make this a lot more maintainable and testable. internal sealed class JsonParser { private static int[] stateReturnTable; private static Func<StateContext, bool>[] stateHandlerTable; private StateContext Context { get; set; } private int InputBuffer { get; set; } private int InputCharacter { get; set; } private TextReader Reader { get; set; } private int State { get; set; } private StringBuilder StringBuffer { get; set; } private int UnicodeCharacter { get; set; } public bool AllowComments { get; set; } public bool AllowSingleQuotedStrings { get; set; } public bool EndOfInput { get; private set; } public int Token { get; private set; } public string StringValue { get; private set; } static JsonParser() { PopulateStateTables(); } public JsonParser(TextReader reader) { InputBuffer = 0; StringBuffer = new StringBuilder(128); State = 1; AllowComments = false; AllowSingleQuotedStrings = false; EndOfInput = false; this.Reader = reader; Context = new StateContext(); Context.Parser = this; } public bool NextToken() { Func<StateContext, bool> stateHandler; Context.Return = false; while (true) { stateHandler = stateHandlerTable[State - 1]; if (!stateHandler(Context)) throw new JsonException(InputCharacter); if (EndOfInput) return false; if (Context.Return) { StringValue = StringBuffer.ToString(); StringBuffer.Remove(0, StringBuffer.Length); Token = stateReturnTable[State - 1]; if (Token == (int)JsonParserToken.Char) Token = InputCharacter; State = Context.NextState; return true; } State = Context.NextState; } } private bool GetCharacter() { if ((InputCharacter = NextCharacter()) != -1) return true; EndOfInput = true; return false; } private int NextCharacter() { if (InputBuffer != 0) { int tmp = InputBuffer; InputBuffer = 0; return tmp; } return Reader.Read(); } private void PreviousCharacter() { InputBuffer = InputCharacter; } private static void PopulateStateTables() { stateHandlerTable = new Func<StateContext, bool>[28] { State1, State2, State3, State4, State5, State6, State7, State8, State9, State10, State11, State12, State13, State14, State15, State16, State17, State18, State19, State20, State21, State22, State23, State24, State25, State26, State27, State28 }; stateReturnTable = new int[28] { (int)JsonParserToken.Char, 0, (int)JsonParserToken.Number, (int)JsonParserToken.Number, 0, (int)JsonParserToken.Number, 0, (int)JsonParserToken.Number, 0, 0, (int)JsonParserToken.True, 0, 0, 0, (int)JsonParserToken.False, 0, 0, (int)JsonParserToken.Null, (int)JsonParserToken.CharSeq, (int)JsonParserToken.Char, 0, 0, (int)JsonParserToken.CharSeq, (int)JsonParserToken.Char, 0, 0, 0, 0 }; } private static bool State1(StateContext context) { while (context.Parser.GetCharacter()) { if (context.Parser.InputCharacter == ' ' || context.Parser.InputCharacter >= '\t' && context.Parser.InputCharacter <= '\r') continue; if (context.Parser.InputCharacter >= '1' && context.Parser.InputCharacter <= '9') { context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 3; return true; } switch (context.Parser.InputCharacter) { case '"': context.NextState = 19; context.Return = true; return true; case ',': case ':': case '[': case ']': case '{': case '}': context.NextState = 1; context.Return = true; return true; case '-': context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 2; return true; case '0': context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 4; return true; case 'f': context.NextState = 12; return true; case 'n': context.NextState = 16; return true; case 't': context.NextState = 9; return true; case '\'': if (!context.Parser.AllowSingleQuotedStrings) return false; context.Parser.InputCharacter = '"'; context.NextState = 23; context.Return = true; return true; case '/': if (!context.Parser.AllowComments) return false; context.NextState = 25; return true; default: return false; } } return true; } private static bool State2(StateContext context) { context.Parser.GetCharacter(); if (context.Parser.InputCharacter >= '1' && context.Parser.InputCharacter<= '9') { context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 3; return true; } switch (context.Parser.InputCharacter) { case '0': context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 4; return true; default: return false; } } private static bool State3(StateContext context) { while (context.Parser.GetCharacter()) { if (context.Parser.InputCharacter >= '0' && context.Parser.InputCharacter <= '9') { context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); continue; } if (context.Parser.InputCharacter == ' ' || context.Parser.InputCharacter >= '\t' && context.Parser.InputCharacter <= '\r') { context.Return = true; context.NextState = 1; return true; } switch (context.Parser.InputCharacter) { case ',': case ']': case '}': context.Parser.PreviousCharacter(); context.Return = true; context.NextState = 1; return true; case '.': context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 5; return true; case 'e': case 'E': context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 7; return true; default: return false; } } return true; } private static bool State4(StateContext context) { context.Parser.GetCharacter(); if (context.Parser.InputCharacter == ' ' || context.Parser.InputCharacter >= '\t' && context.Parser.InputCharacter <= '\r') { context.Return = true; context.NextState = 1; return true; } switch (context.Parser.InputCharacter) { case ',': case ']': case '}': context.Parser.PreviousCharacter(); context.Return = true; context.NextState = 1; return true; case '.': context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 5; return true; case 'e': case 'E': context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 7; return true; default: return false; } } private static bool State5(StateContext context) { context.Parser.GetCharacter(); if (context.Parser.InputCharacter >= '0' && context.Parser.InputCharacter <= '9') { context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 6; return true; } return false; } private static bool State6(StateContext context) { while (context.Parser.GetCharacter()) { if (context.Parser.InputCharacter >= '0' && context.Parser.InputCharacter <= '9') { context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); continue; } if (context.Parser.InputCharacter == ' ' || context.Parser.InputCharacter >= '\t' && context.Parser.InputCharacter <= '\r') { context.Return = true; context.NextState = 1; return true; } switch (context.Parser.InputCharacter) { case ',': case ']': case '}': context.Parser.PreviousCharacter(); context.Return = true; context.NextState = 1; return true; case 'e': case 'E': context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 7; return true; default: return false; } } return true; } private static bool State7(StateContext context) { context.Parser.GetCharacter(); if (context.Parser.InputCharacter >= '0' && context.Parser.InputCharacter<= '9') { context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 8; return true; } switch (context.Parser.InputCharacter) { case '+': case '-': context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); context.NextState = 8; return true; default: return false; } } private static bool State8(StateContext context) { while (context.Parser.GetCharacter()) { if (context.Parser.InputCharacter >= '0' && context.Parser.InputCharacter<= '9') { context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); continue; } if (context.Parser.InputCharacter == ' ' || context.Parser.InputCharacter >= '\t' && context.Parser.InputCharacter<= '\r') { context.Return = true; context.NextState = 1; return true; } switch (context.Parser.InputCharacter) { case ',': case ']': case '}': context.Parser.PreviousCharacter(); context.Return = true; context.NextState = 1; return true; default: return false; } } return true; } private static bool State9(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case 'r': context.NextState = 10; return true; default: return false; } } private static bool State10(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case 'u': context.NextState = 11; return true; default: return false; } } private static bool State11(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case 'e': context.Return = true; context.NextState = 1; return true; default: return false; } } private static bool State12(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case 'a': context.NextState = 13; return true; default: return false; } } private static bool State13(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case 'l': context.NextState = 14; return true; default: return false; } } private static bool State14(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case 's': context.NextState = 15; return true; default: return false; } } private static bool State15(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case 'e': context.Return = true; context.NextState = 1; return true; default: return false; } } private static bool State16(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case 'u': context.NextState = 17; return true; default: return false; } } private static bool State17(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case 'l': context.NextState = 18; return true; default: return false; } } private static bool State18(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case 'l': context.Return = true; context.NextState = 1; return true; default: return false; } } private static bool State19(StateContext context) { while (context.Parser.GetCharacter()) { switch (context.Parser.InputCharacter) { case '"': context.Parser.PreviousCharacter(); context.Return = true; context.NextState = 20; return true; case '\\': context.StateStack = 19; context.NextState = 21; return true; default: context.Parser.StringBuffer.Append((char)context.Parser.InputCharacter); continue; } } return true; } private static bool State20(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case '"': context.Return = true; context.NextState = 1; return true; default: return false; } } private static bool State21(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case 'u': context.NextState = 22; return true; case '"': case '\'': case '/': case '\\': case 'b': case 'f': case 'n': case 'r': case 't': context.Parser.StringBuffer.Append(ProcessEscChar(context.Parser.InputCharacter)); context.NextState = context.StateStack; return true; default: return false; } } private static bool State22(StateContext context) { int counter = 0; int mult = 4096; context.Parser.UnicodeCharacter = 0; while (context.Parser.GetCharacter()) { if (context.Parser.InputCharacter >= '0' && context.Parser.InputCharacter <= '9' || context.Parser.InputCharacter >= 'A' && context.Parser.InputCharacter <= 'F' || context.Parser.InputCharacter >= 'a' && context.Parser.InputCharacter <= 'f') { context.Parser.UnicodeCharacter += HexValue(context.Parser.InputCharacter) * mult; counter++; mult /= 16; if (counter == 4) { context.Parser.StringBuffer.Append(Convert.ToChar(context.Parser.UnicodeCharacter)); context.NextState = context.StateStack; return true; } continue; } return false; } return true; } private static bool State23(StateContext context) { while (context.Parser.GetCharacter()) { switch (context.Parser.InputCharacter) { case '\'': context.Parser.PreviousCharacter(); context.Return = true; context.NextState = 24; return true; case '\\': context.StateStack = 23; context.NextState = 21; return true; default: context.Parser.StringBuffer.Append((char) context.Parser.InputCharacter); continue; } } return true; } private static bool State24(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case '\'': context.Parser.InputCharacter = '"'; context.Return = true; context.NextState = 1; return true; default: return false; } } private static bool State25(StateContext context) { context.Parser.GetCharacter(); switch (context.Parser.InputCharacter) { case '*': context.NextState = 27; return true; case '/': context.NextState = 26; return true; default: return false; } } private static bool State26(StateContext context) { while (context.Parser.GetCharacter()) { if (context.Parser.InputCharacter == '\n') { context.NextState = 1; return true; } } return true; } private static bool State27(StateContext context) { while (context.Parser.GetCharacter()) { if (context.Parser.InputCharacter == '*') { context.NextState = 28; return true; } } return true; } private static bool State28(StateContext context) { while (context.Parser.GetCharacter()) { if (context.Parser.InputCharacter == '*') continue; if (context.Parser.InputCharacter == '/') { context.NextState = 1; return true; } context.NextState = 27; return true; } return true; } private static char ProcessEscChar(int esc_char) { switch (esc_char) { case '"': case '\'': case '\\': case '/': return Convert.ToChar(esc_char); case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'b': return '\b'; case 'f': return '\f'; default: // Unreachable return '?'; } } private static int HexValue(int digit) { switch (digit) { case 'a': case 'A': return 10; case 'b': case 'B': return 11; case 'c': case 'C': return 12; case 'd': case 'D': return 13; case 'e': case 'E': return 14; case 'f': case 'F': return 15; default: return digit - '0'; } } } internal class StateContext { public bool Return; public int NextState; public JsonParser Parser; public int StateStack; } }
// GZipStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2010-January-09 12:04:28> // // ------------------------------------------------------------------ // // This module defines the GZipStream class, which can be used as a replacement for // the System.IO.Compression.GZipStream class in the .NET BCL. NB: The design is not // completely OO clean: there is some intelligence in the ZlibBaseStream that reads the // GZip header. // // ------------------------------------------------------------------ using System; using System.IO; namespace Ionic.Zlib { /// <summary> /// A class for compressing and decompressing GZIP streams. /// </summary> /// <remarks> /// /// <para> /// The <c>GZipStream</c> is a <see /// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a /// <see cref="Stream"/>. It adds GZIP compression or decompression to any /// stream. /// </para> /// /// <para> /// Like the <c>System.IO.Compression.GZipStream</c> in the .NET Base Class Library, the /// <c>Ionic.Zlib.GZipStream</c> can compress while writing, or decompress while /// reading, but not vice versa. The compression method used is GZIP, which is /// documented in <see href="http://www.ietf.org/rfc/rfc1952.txt">IETF RFC /// 1952</see>, "GZIP file format specification version 4.3".</para> /// /// <para> /// A <c>GZipStream</c> can be used to decompress data (through <c>Read()</c>) or /// to compress data (through <c>Write()</c>), but not both. /// </para> /// /// <para> /// If you wish to use the <c>GZipStream</c> to compress data, you must wrap it /// around a write-able stream. As you call <c>Write()</c> on the <c>GZipStream</c>, the /// data will be compressed into the GZIP format. If you want to decompress data, /// you must wrap the <c>GZipStream</c> around a readable stream that contains an /// IETF RFC 1952-compliant stream. The data will be decompressed as you call /// <c>Read()</c> on the <c>GZipStream</c>. /// </para> /// /// <para> /// Though the GZIP format allows data from multiple files to be concatenated /// together, this stream handles only a single segment of GZIP format, typically /// representing a single file. /// </para> /// /// <para> /// This class is similar to <see cref="ZlibStream"/> and <see cref="DeflateStream"/>. /// <c>ZlibStream</c> handles RFC1950-compliant streams. <see cref="DeflateStream"/> /// handles RFC1951-compliant streams. This class handles RFC1952-compliant streams. /// </para> /// /// </remarks> /// /// <seealso cref="DeflateStream" /> /// <seealso cref="ZlibStream" /> public class GZipStream : System.IO.Stream { // GZip format // source: http://tools.ietf.org/html/rfc1952 // // header id: 2 bytes 1F 8B // compress method 1 byte 8= DEFLATE (none other supported) // flag 1 byte bitfield (See below) // mtime 4 bytes time_t (seconds since jan 1, 1970 UTC of the file. // xflg 1 byte 2 = max compress used , 4 = max speed (can be ignored) // OS 1 byte OS for originating archive. set to 0xFF in compression. // extra field length 2 bytes optional - only if FEXTRA is set. // extra field varies // filename varies optional - if FNAME is set. zero terminated. ISO-8859-1. // file comment varies optional - if FCOMMENT is set. zero terminated. ISO-8859-1. // crc16 1 byte optional - present only if FHCRC bit is set // compressed data varies // CRC32 4 bytes // isize 4 bytes data size modulo 2^32 // // FLG (FLaGs) // bit 0 FTEXT - indicates file is ASCII text (can be safely ignored) // bit 1 FHCRC - there is a CRC16 for the header immediately following the header // bit 2 FEXTRA - extra fields are present // bit 3 FNAME - the zero-terminated filename is present. encoding; ISO-8859-1. // bit 4 FCOMMENT - a zero-terminated file comment is present. encoding: ISO-8859-1 // bit 5 reserved // bit 6 reserved // bit 7 reserved // // On consumption: // Extra field is a bunch of nonsense and can be safely ignored. // Header CRC and OS, likewise. // // on generation: // all optional fields get 0, except for the OS, which gets 255. // /// <summary> /// The comment on the GZIP stream. /// </summary> /// /// <remarks> /// <para> /// The GZIP format allows for each file to optionally have an associated /// comment stored with the file. The comment is encoded with the ISO-8859-1 /// code page. To include a comment in a GZIP stream you create, set this /// property before calling <c>Write()</c> for the first time on the /// <c>GZipStream</c>. /// </para> /// /// <para> /// When using <c>GZipStream</c> to decompress, you can retrieve this property /// after the first call to <c>Read()</c>. If no comment has been set in the /// GZIP bytestream, the Comment property will return <c>null</c> /// (<c>Nothing</c> in VB). /// </para> /// </remarks> public String Comment { get { return _Comment; } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); _Comment = value; } } /// <summary> /// The FileName for the GZIP stream. /// </summary> /// /// <remarks> /// /// <para> /// The GZIP format optionally allows each file to have an associated /// filename. When compressing data (through <c>Write()</c>), set this /// FileName before calling <c>Write()</c> the first time on the <c>GZipStream</c>. /// The actual filename is encoded into the GZIP bytestream with the /// ISO-8859-1 code page, according to RFC 1952. It is the application's /// responsibility to insure that the FileName can be encoded and decoded /// correctly with this code page. /// </para> /// /// <para> /// When decompressing (through <c>Read()</c>), you can retrieve this value /// any time after the first <c>Read()</c>. In the case where there was no filename /// encoded into the GZIP bytestream, the property will return <c>null</c> (<c>Nothing</c> /// in VB). /// </para> /// </remarks> public String FileName { get { return _FileName; } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); _FileName = value; if (_FileName == null) return; if (_FileName.IndexOf("/") != -1) { _FileName = _FileName.Replace("/", "\\"); } if (_FileName.EndsWith("\\")) throw new Exception("Illegal filename"); if (_FileName.IndexOf("\\") != -1) { // trim any leading path _FileName = Path.GetFileName(_FileName); } } } /// <summary> /// The last modified time for the GZIP stream. /// </summary> /// /// <remarks> /// GZIP allows the storage of a last modified time with each GZIP entry. /// When compressing data, you can set this before the first call to /// <c>Write()</c>. When decompressing, you can retrieve this value any time /// after the first call to <c>Read()</c>. /// </remarks> public DateTime? LastModified; /// <summary> /// The CRC on the GZIP stream. /// </summary> /// <remarks> /// This is used for internal error checking. You probably don't need to look at this property. /// </remarks> public int Crc32 { get { return _Crc32; } } private int _headerByteCount; internal ZlibBaseStream _baseStream; bool _disposed; bool _firstReadDone; string _FileName; string _Comment; int _Crc32; /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>. /// </summary> /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>GZipStream</c> will use the /// default compression level. /// </para> /// /// <para> /// As noted in the class documentation, the <c>CompressionMode</c> (Compress /// or Decompress) also establishes the "direction" of the stream. A /// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through /// <c>Write()</c>. A <c>GZipStream</c> with /// <c>CompressionMode.Decompress</c> works only through <c>Read()</c>. /// </para> /// /// </remarks> /// /// <example> /// This example shows how to use a GZipStream to compress data. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(outputFile)) /// { /// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// <code lang="VB"> /// Dim outputFile As String = (fileToCompress &amp; ".compressed") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(outputFile) /// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// /// <example> /// This example shows how to use a GZipStream to uncompress a file. /// <code> /// private void GunZipFile(string filename) /// { /// if (!filename.EndsWith(".gz)) /// throw new ArgumentException("filename"); /// var DecompressedFile = filename.Substring(0,filename.Length-3); /// byte[] working = new byte[WORKING_BUFFER_SIZE]; /// int n= 1; /// using (System.IO.Stream input = System.IO.File.OpenRead(filename)) /// { /// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true)) /// { /// using (var output = System.IO.File.Create(DecompressedFile)) /// { /// while (n !=0) /// { /// n= decompressor.Read(working, 0, working.Length); /// if (n > 0) /// { /// output.Write(working, 0, n); /// } /// } /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Private Sub GunZipFile(ByVal filename as String) /// If Not (filename.EndsWith(".gz)) Then /// Throw New ArgumentException("filename") /// End If /// Dim DecompressedFile as String = filename.Substring(0,filename.Length-3) /// Dim working(WORKING_BUFFER_SIZE) as Byte /// Dim n As Integer = 1 /// Using input As Stream = File.OpenRead(filename) /// Using decompressor As Stream = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, True) /// Using output As Stream = File.Create(UncompressedFile) /// Do /// n= decompressor.Read(working, 0, working.Length) /// If n > 0 Then /// output.Write(working, 0, n) /// End IF /// Loop While (n > 0) /// End Using /// End Using /// End Using /// End Sub /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param> public GZipStream(Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, false) { } /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and /// the specified <c>CompressionLevel</c>. /// </summary> /// <remarks> /// /// <para> /// The <c>CompressionMode</c> (Compress or Decompress) also establishes the /// "direction" of the stream. A <c>GZipStream</c> with /// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A /// <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only /// through <c>Read()</c>. /// </para> /// /// </remarks> /// /// <example> /// /// This example shows how to use a <c>GZipStream</c> to compress a file into a .gz file. /// /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".gz")) /// { /// using (Stream compressor = new GZipStream(raw, /// CompressionMode.Compress, /// CompressionLevel.BestCompression)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".gz") /// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// <param name="stream">The stream to be read or written while deflating or inflating.</param> /// <param name="mode">Indicates whether the <c>GZipStream</c> will compress or decompress.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, false) { } /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>, and /// explicitly specify whether the stream should be left open after Deflation /// or Inflation. /// </summary> /// /// <remarks> /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// memory stream that will be re-read after compressed data has been written /// to it. Specify true for the <paramref name="leaveOpen"/> parameter to leave /// the stream open. /// </para> /// /// <para> /// The <see cref="CompressionMode"/> (Compress or Decompress) also /// establishes the "direction" of the stream. A <c>GZipStream</c> with /// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A <c>GZipStream</c> /// with <c>CompressionMode.Decompress</c> works only through <c>Read()</c>. /// </para> /// /// <para> /// The <c>GZipStream</c> will use the default compression level. If you want /// to specify the compression level, see <see cref="GZipStream(Stream, /// CompressionMode, CompressionLevel, bool)"/>. /// </para> /// /// <para> /// See the other overloads of this constructor for example code. /// </para> /// /// </remarks> /// /// <param name="stream"> /// The stream which will be read or written. This is called the "captive" /// stream in other places in this documentation. /// </param> /// /// <param name="mode">Indicates whether the GZipStream will compress or decompress. /// </param> /// /// <param name="leaveOpen"> /// true if the application would like the base stream to remain open after /// inflation/deflation. /// </param> public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { } /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and the /// specified <c>CompressionLevel</c>, and explicitly specify whether the /// stream should be left open after Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// memory stream that will be re-read after compressed data has been written /// to it. Specify true for the <paramref name="leaveOpen"/> parameter to /// leave the stream open. /// </para> /// /// <para> /// As noted in the class documentation, the <c>CompressionMode</c> (Compress /// or Decompress) also establishes the "direction" of the stream. A /// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through /// <c>Write()</c>. A <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only /// through <c>Read()</c>. /// </para> /// /// </remarks> /// /// <example> /// This example shows how to use a <c>GZipStream</c> to compress data. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(outputFile)) /// { /// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// <code lang="VB"> /// Dim outputFile As String = (fileToCompress &amp; ".compressed") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(outputFile) /// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, True) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param> /// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.GZIP, leaveOpen); } #region Zlib properties /// <summary> /// This property sets the flush behavior on the stream. /// </summary> virtual public FlushType FlushMode { get { return (this._baseStream._flushMode); } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); this._baseStream._flushMode = value; } } /// <summary> /// The size of the working buffer for the compression codec. /// </summary> /// /// <remarks> /// <para> /// The working buffer is used for all stream operations. The default size is /// 1024 bytes. The minimum size is 128 bytes. You may get better performance /// with a larger buffer. Then again, you might not. You would have to test /// it. /// </para> /// /// <para> /// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the /// stream. If you try to set it afterwards, it will throw. /// </para> /// </remarks> public int BufferSize { get { return this._baseStream._bufferSize; } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); if (this._baseStream._workingBuffer != null) throw new ZlibException("The working buffer is already set."); if (value < ZlibConstants.WorkingBufferSizeMin) throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin)); this._baseStream._bufferSize = value; } } /// <summary> Returns the total number of bytes input so far.</summary> virtual public long TotalIn { get { return this._baseStream._z.TotalBytesIn; } } /// <summary> Returns the total number of bytes output so far.</summary> virtual public long TotalOut { get { return this._baseStream._z.TotalBytesOut; } } #endregion #region Stream methods /// <summary> /// Dispose the stream. /// </summary> /// <remarks> /// This may or may not result in a <c>Close()</c> call on the captive stream. /// See the doc on constructors that take a <c>leaveOpen</c> parameter for more information. /// </remarks> protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && (this._baseStream != null)) { this._baseStream.Close(); this._Crc32 = _baseStream.Crc32; } _disposed = true; } } finally { base.Dispose(disposing); } } /// <summary> /// Indicates whether the stream can be read. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports reading. /// </remarks> public override bool CanRead { get { if (_disposed) throw new ObjectDisposedException("GZipStream"); return _baseStream._stream.CanRead; } } /// <summary> /// Indicates whether the stream supports Seek operations. /// </summary> /// <remarks> /// Always returns false. /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream can be written. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports writing. /// </remarks> public override bool CanWrite { get { if (_disposed) throw new ObjectDisposedException("GZipStream"); return _baseStream._stream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { if (_disposed) throw new ObjectDisposedException("GZipStream"); _baseStream.Flush(); } /// <summary> /// Reading this property always throws a <see cref="NotImplementedException"/>. /// </summary> public override long Length { get { throw new NotImplementedException(); } } /// <summary> /// The position of the stream pointer. /// </summary> /// /// <remarks> /// Setting this property always throws a <see /// cref="NotImplementedException"/>. Reading will return the total bytes /// written out, if used in writing, or the total bytes read in, if used in /// reading. The count may refer to compressed bytes or uncompressed bytes, /// depending on how you've used the stream. /// </remarks> public override long Position { get { if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Writer) return this._baseStream._z.TotalBytesOut + _headerByteCount; if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Reader) return this._baseStream._z.TotalBytesIn + this._baseStream._gzipHeaderByteCount; return 0; } set { throw new NotImplementedException(); } } /// <summary> /// Read and decompress data from the source stream. /// </summary> /// /// <remarks> /// With a <c>GZipStream</c>, decompression is done through reading. /// </remarks> /// /// <example> /// <code> /// byte[] working = new byte[WORKING_BUFFER_SIZE]; /// using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile)) /// { /// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true)) /// { /// using (var output = System.IO.File.Create(_DecompressedFile)) /// { /// int n; /// while ((n= decompressor.Read(working, 0, working.Length)) !=0) /// { /// output.Write(working, 0, n); /// } /// } /// } /// } /// </code> /// </example> /// <param name="buffer">The buffer into which the decompressed data should be placed.</param> /// <param name="offset">the offset within that data array to put the first byte read.</param> /// <param name="count">the number of bytes to read.</param> /// <returns>the number of bytes actually read</returns> public override int Read(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("GZipStream"); int n = _baseStream.Read(buffer, offset, count); // Logger.Log("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n); // Logger.Log( Util.FormatByteArray(buffer, offset, n) ); if (!_firstReadDone) { _firstReadDone = true; FileName = _baseStream._GzipFileName; Comment = _baseStream._GzipComment; } return n; } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="offset">irrelevant; it will always throw!</param> /// <param name="origin">irrelevant; it will always throw!</param> /// <returns>irrelevant!</returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="value">irrelevant; this method will always throw!</param> public override void SetLength(long value) { throw new NotImplementedException(); } /// <summary> /// Write data to the stream. /// </summary> /// /// <remarks> /// <para> /// If you wish to use the <c>GZipStream</c> to compress data while writing, /// you can create a <c>GZipStream</c> with <c>CompressionMode.Compress</c>, and a /// writable output stream. Then call <c>Write()</c> on that <c>GZipStream</c>, /// providing uncompressed data as input. The data sent to the output stream /// will be the compressed form of the data written. /// </para> /// /// <para> /// A <c>GZipStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not /// both. Writing implies compression. Reading implies decompression. /// </para> /// /// </remarks> /// <param name="buffer">The buffer holding data to write to the stream.</param> /// <param name="offset">the offset within that data array to find the first byte to write.</param> /// <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("GZipStream"); if (_baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Undefined) { //Logger.Log("GZipStream: First write"); if (_baseStream._wantCompress) { // first write in compression, therefore, emit the GZIP header _headerByteCount = EmitHeader(); } else { throw new InvalidOperationException(); } } _baseStream.Write(buffer, offset, count); } #endregion internal static readonly System.DateTime _unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); internal static readonly System.Text.Encoding iso8859dash1 = System.Text.Encoding.GetEncoding("iso-8859-1"); private int EmitHeader() { byte[] commentBytes = (Comment == null) ? null : iso8859dash1.GetBytes(Comment); byte[] filenameBytes = (FileName == null) ? null : iso8859dash1.GetBytes(FileName); int cbLength = (Comment == null) ? 0 : commentBytes.Length + 1; int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1; int bufferLength = 10 + cbLength + fnLength; byte[] header = new byte[bufferLength]; int i = 0; // ID header[i++] = 0x1F; header[i++] = 0x8B; // compression method header[i++] = 8; byte flag = 0; if (Comment != null) flag ^= 0x10; if (FileName != null) flag ^= 0x8; // flag header[i++] = flag; // mtime if (!LastModified.HasValue) LastModified = DateTime.Now; System.TimeSpan delta = LastModified.Value - _unixEpoch; Int32 timet = (Int32)delta.TotalSeconds; Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4); i += 4; // xflg header[i++] = 0; // this field is totally useless // OS header[i++] = 0xFF; // 0xFF == unspecified // extra field length - only if FEXTRA is set, which it is not. //header[i++]= 0; //header[i++]= 0; // filename if (fnLength != 0) { Array.Copy(filenameBytes, 0, header, i, fnLength - 1); i += fnLength - 1; header[i++] = 0; // terminate } // comment if (cbLength != 0) { Array.Copy(commentBytes, 0, header, i, cbLength - 1); i += cbLength - 1; header[i++] = 0; // terminate } _baseStream._stream.Write(header, 0, header.Length); return header.Length; // bytes written } /// <summary> /// Compress a string into a byte array using GZip. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="GZipStream.UncompressString(byte[])"/>. /// </remarks> /// /// <seealso cref="GZipStream.UncompressString(byte[])"/> /// <seealso cref="GZipStream.CompressBuffer(byte[])"/> /// /// <param name="s"> /// A string to compress. The string will first be encoded /// using UTF8, then compressed. /// </param> /// /// <returns>The string in compressed form</returns> public static byte[] CompressString(String s) { using (var ms = new MemoryStream()) { System.IO.Stream compressor = new GZipStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressString(s, compressor); return ms.ToArray(); } } /// <summary> /// Compress a byte array into a new byte array using GZip. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="GZipStream.UncompressBuffer(byte[])"/>. /// </remarks> /// /// <seealso cref="GZipStream.CompressString(string)"/> /// <seealso cref="GZipStream.UncompressBuffer(byte[])"/> /// /// <param name="b"> /// A buffer to compress. /// </param> /// /// <returns>The data in compressed form</returns> public static byte[] CompressBuffer(byte[] b) { using (var ms = new MemoryStream()) { System.IO.Stream compressor = new GZipStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression ); ZlibBaseStream.CompressBuffer(b, compressor); return ms.ToArray(); } } /// <summary> /// Uncompress a GZip'ed byte array into a single string. /// </summary> /// /// <seealso cref="GZipStream.CompressString(String)"/> /// <seealso cref="GZipStream.UncompressBuffer(byte[])"/> /// /// <param name="compressed"> /// A buffer containing GZIP-compressed data. /// </param> /// /// <returns>The uncompressed string</returns> public static String UncompressString(byte[] compressed) { using (var input = new MemoryStream(compressed)) { Stream decompressor = new GZipStream(input, CompressionMode.Decompress); return ZlibBaseStream.UncompressString(compressed, decompressor); } } /// <summary> /// Uncompress a GZip'ed byte array into a byte array. /// </summary> /// /// <seealso cref="GZipStream.CompressBuffer(byte[])"/> /// <seealso cref="GZipStream.UncompressString(byte[])"/> /// /// <param name="compressed"> /// A buffer containing data that has been compressed with GZip. /// </param> /// /// <returns>The data in uncompressed form</returns> public static byte[] UncompressBuffer(byte[] compressed) { using (var input = new System.IO.MemoryStream(compressed)) { System.IO.Stream decompressor = new GZipStream( input, CompressionMode.Decompress ); return ZlibBaseStream.UncompressBuffer(compressed, decompressor); } } } }
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> using System; using System.IO; using System.Text; namespace HtmlAgilityPack { /// <summary> /// Represents a document with mixed code and text. ASP, ASPX, JSP, are good example of such documents. /// </summary> public class MixedCodeDocument { #region Fields private int _c; internal MixedCodeDocumentFragmentList _codefragments; private MixedCodeDocumentFragment _currentfragment; internal MixedCodeDocumentFragmentList _fragments; private int _index; private int _line; private int _lineposition; private ParseState _state; private Encoding _streamencoding; internal string _text; internal MixedCodeDocumentFragmentList _textfragments; /// <summary> /// Gets or sets the token representing code end. /// </summary> public string TokenCodeEnd = "%>"; /// <summary> /// Gets or sets the token representing code start. /// </summary> public string TokenCodeStart = "<%"; /// <summary> /// Gets or sets the token representing code directive. /// </summary> public string TokenDirective = "@"; /// <summary> /// Gets or sets the token representing response write directive. /// </summary> public string TokenResponseWrite = "Response.Write "; private string TokenTextBlock = "TextBlock({0})"; #endregion #region Constructors /// <summary> /// Creates a mixed code document instance. /// </summary> public MixedCodeDocument() { _codefragments = new MixedCodeDocumentFragmentList(this); _textfragments = new MixedCodeDocumentFragmentList(this); _fragments = new MixedCodeDocumentFragmentList(this); } #endregion #region Properties /// <summary> /// Gets the code represented by the mixed code document seen as a template. /// </summary> public string Code { get { string s = ""; int i = 0; foreach (MixedCodeDocumentFragment frag in _fragments) { switch (frag._type) { case MixedCodeDocumentFragmentType.Text: s += TokenResponseWrite + string.Format(TokenTextBlock, i) + "\n"; i++; break; case MixedCodeDocumentFragmentType.Code: s += ((MixedCodeDocumentCodeFragment) frag).Code + "\n"; break; } } return s; } } /// <summary> /// Gets the list of code fragments in the document. /// </summary> public MixedCodeDocumentFragmentList CodeFragments { get { return _codefragments; } } /// <summary> /// Gets the list of all fragments in the document. /// </summary> public MixedCodeDocumentFragmentList Fragments { get { return _fragments; } } /// <summary> /// Gets the encoding of the stream used to read the document. /// </summary> public Encoding StreamEncoding { get { return _streamencoding; } } /// <summary> /// Gets the list of text fragments in the document. /// </summary> public MixedCodeDocumentFragmentList TextFragments { get { return _textfragments; } } #endregion #region Public Methods /// <summary> /// Create a code fragment instances. /// </summary> /// <returns>The newly created code fragment instance.</returns> public MixedCodeDocumentCodeFragment CreateCodeFragment() { return (MixedCodeDocumentCodeFragment) CreateFragment(MixedCodeDocumentFragmentType.Code); } /// <summary> /// Create a text fragment instances. /// </summary> /// <returns>The newly created text fragment instance.</returns> public MixedCodeDocumentTextFragment CreateTextFragment() { return (MixedCodeDocumentTextFragment) CreateFragment(MixedCodeDocumentFragmentType.Text); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> public void Load(Stream stream) { Load(new StreamReader(stream)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(Stream stream, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(stream, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> public void Load(Stream stream, Encoding encoding) { Load(new StreamReader(stream, encoding)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> /// <param name="buffersize">The minimum buffer size.</param> public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, buffersize)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> public void Load(string path) { Load(new StreamReader(path)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(string path, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(path, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> public void Load(string path, Encoding encoding) { Load(new StreamReader(path, encoding)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(path, encoding, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> /// <param name="buffersize">The minimum buffer size.</param> public void Load(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { Load(new StreamReader(path, encoding, detectEncodingFromByteOrderMarks, buffersize)); } /// <summary> /// Loads the mixed code document from the specified TextReader. /// </summary> /// <param name="reader">The TextReader used to feed the HTML data into the document.</param> public void Load(TextReader reader) { _codefragments.Clear(); _textfragments.Clear(); // all pseudo constructors get down to this one StreamReader sr = reader as StreamReader; if (sr != null) { _streamencoding = sr.CurrentEncoding; } _text = reader.ReadToEnd(); reader.Close(); Parse(); } /// <summary> /// Loads a mixed document from a text /// </summary> /// <param name="html">The text to load.</param> public void LoadHtml(string html) { Load(new StringReader(html)); } /// <summary> /// Saves the mixed document to the specified stream. /// </summary> /// <param name="outStream">The stream to which you want to save.</param> public void Save(Stream outStream) { StreamWriter sw = new StreamWriter(outStream, GetOutEncoding()); Save(sw); } /// <summary> /// Saves the mixed document to the specified stream. /// </summary> /// <param name="outStream">The stream to which you want to save.</param> /// <param name="encoding">The character encoding to use.</param> public void Save(Stream outStream, Encoding encoding) { StreamWriter sw = new StreamWriter(outStream, encoding); Save(sw); } /// <summary> /// Saves the mixed document to the specified file. /// </summary> /// <param name="filename">The location of the file where you want to save the document.</param> public void Save(string filename) { StreamWriter sw = new StreamWriter(filename, false, GetOutEncoding()); Save(sw); } /// <summary> /// Saves the mixed document to the specified file. /// </summary> /// <param name="filename">The location of the file where you want to save the document.</param> /// <param name="encoding">The character encoding to use.</param> public void Save(string filename, Encoding encoding) { StreamWriter sw = new StreamWriter(filename, false, encoding); Save(sw); } /// <summary> /// Saves the mixed document to the specified StreamWriter. /// </summary> /// <param name="writer">The StreamWriter to which you want to save.</param> public void Save(StreamWriter writer) { Save((TextWriter) writer); } /// <summary> /// Saves the mixed document to the specified TextWriter. /// </summary> /// <param name="writer">The TextWriter to which you want to save.</param> public void Save(TextWriter writer) { writer.Flush(); } #endregion #region Internal Methods internal MixedCodeDocumentFragment CreateFragment(MixedCodeDocumentFragmentType type) { switch (type) { case MixedCodeDocumentFragmentType.Text: return new MixedCodeDocumentTextFragment(this); case MixedCodeDocumentFragmentType.Code: return new MixedCodeDocumentCodeFragment(this); default: throw new NotSupportedException(); } } internal Encoding GetOutEncoding() { if (_streamencoding != null) return _streamencoding; return Encoding.Default; } #endregion #region Private Methods private void IncrementPosition() { _index++; if (_c == 10) { _lineposition = 1; _line++; } else _lineposition++; } private void Parse() { _state = ParseState.Text; _index = 0; _currentfragment = CreateFragment(MixedCodeDocumentFragmentType.Text); while (_index < _text.Length) { _c = _text[_index]; IncrementPosition(); switch (_state) { case ParseState.Text: if (_index + TokenCodeStart.Length < _text.Length) { if (_text.Substring(_index - 1, TokenCodeStart.Length) == TokenCodeStart) { _state = ParseState.Code; _currentfragment.Length = _index - 1 - _currentfragment.Index; _currentfragment = CreateFragment(MixedCodeDocumentFragmentType.Code); SetPosition(); continue; } } break; case ParseState.Code: if (_index + TokenCodeEnd.Length < _text.Length) { if (_text.Substring(_index - 1, TokenCodeEnd.Length) == TokenCodeEnd) { _state = ParseState.Text; _currentfragment.Length = _index + TokenCodeEnd.Length - _currentfragment.Index; _index += TokenCodeEnd.Length; _lineposition += TokenCodeEnd.Length; _currentfragment = CreateFragment(MixedCodeDocumentFragmentType.Text); SetPosition(); continue; } } break; } } _currentfragment.Length = _index - _currentfragment.Index; } private void SetPosition() { _currentfragment.Line = _line; _currentfragment._lineposition = _lineposition; _currentfragment.Index = _index - 1; _currentfragment.Length = 0; } #endregion #region Nested type: ParseState private enum ParseState { Text, Code } #endregion } }
// Deflater.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This is the Deflater class. The deflater class compresses input /// with the deflate algorithm described in RFC 1951. It has several /// compression levels and three different strategies described below. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of deflate and setInput. /// /// author of the original java version : Jochen Hoenicke /// </summary> public class Deflater { #region Deflater Documentation /* * The Deflater can do the following state transitions: * * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---. * / | (2) (5) | * / v (5) | * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3) * \ | (3) | ,--------' * | | | (3) / * v v (5) v v * (1) -> BUSY_STATE ----> FINISHING_STATE * | (6) * v * FINISHED_STATE * \_____________________________________/ * | (7) * v * CLOSED_STATE * * (1) If we should produce a header we start in INIT_STATE, otherwise * we start in BUSY_STATE. * (2) A dictionary may be set only when we are in INIT_STATE, then * we change the state as indicated. * (3) Whether a dictionary is set or not, on the first call of deflate * we change to BUSY_STATE. * (4) -- intentionally left blank -- :) * (5) FINISHING_STATE is entered, when flush() is called to indicate that * there is no more INPUT. There are also states indicating, that * the header wasn't written yet. * (6) FINISHED_STATE is entered, when everything has been flushed to the * internal pending output buffer. * (7) At any time (7) * */ #endregion #region Public Constants /// <summary> /// The best and slowest compression level. This tries to find very /// long and distant string repetitions. /// </summary> public const int BEST_COMPRESSION = 9; /// <summary> /// The worst but fastest compression level. /// </summary> public const int BEST_SPEED = 1; /// <summary> /// The default compression level. /// </summary> public const int DEFAULT_COMPRESSION = -1; /// <summary> /// This level won't compress at all but output uncompressed blocks. /// </summary> public const int NO_COMPRESSION = 0; /// <summary> /// The compression method. This is the only method supported so far. /// There is no need to use this constant at all. /// </summary> public const int DEFLATED = 8; #endregion #region Local Constants private const int IS_SETDICT = 0x01; private const int IS_FLUSHING = 0x04; private const int IS_FINISHING = 0x08; private const int INIT_STATE = 0x00; private const int SETDICT_STATE = 0x01; // private static int INIT_FINISHING_STATE = 0x08; // private static int SETDICT_FINISHING_STATE = 0x09; private const int BUSY_STATE = 0x10; private const int FLUSHING_STATE = 0x14; private const int FINISHING_STATE = 0x1c; private const int FINISHED_STATE = 0x1e; private const int CLOSED_STATE = 0x7f; #endregion #region Constructors /// <summary> /// Creates a new deflater with default compression level. /// </summary> public Deflater() { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION. /// </param> /// <param name="noZlibHeaderOrFooter"> /// true, if we should suppress the Zlib/RFC1950 header at the /// beginning and the adler checksum at the end of the output. This is /// useful for the GZIP/PKZIP formats. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> #endregion /// <summary> /// Resets the deflater. The deflater acts afterwards as if it was /// just created with the same compression level and strategy as it /// had before. /// </summary> public void Reset() { } /// <summary> /// Gets the current adler checksum of the data that was processed so far. /// </summary> public int Adler { get { return (0); } } /// <summary> /// Gets the number of input bytes processed so far. /// </summary> public long TotalIn { get { return (0L); } } /// <summary> /// Gets the number of output bytes so far. /// </summary> public long TotalOut { get { return totalOut; } } /// <summary> /// Flushes the current input block. Further calls to deflate() will /// produce enough output to inflate everything in the current input /// block. This is not part of Sun's JDK so I have made it package /// private. It is used by DeflaterOutputStream to implement /// flush(). /// </summary> public void Flush() { state |= IS_FLUSHING; } /// <summary> /// Finishes the deflater with the current input block. It is an error /// to give more input after this method was called. This method must /// be called to force all bytes to be flushed. /// </summary> public void Finish() { state |= (IS_FLUSHING | IS_FINISHING); } /// <summary> /// Returns true if the stream was finished and no more output bytes /// are available. /// </summary> public bool IsFinished { get { return (state == FINISHED_STATE); } } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method can also return true when the stream /// was finished. /// </summary> public bool IsNeedingInput { get { return (false); } } /// <summary> /// Sets the data which should be compressed next. This should be only /// called when needsInput indicates that more input is needed. /// If you call setInput when needsInput() returns false, the /// previous input that is still pending will be thrown away. /// The given byte array should not be changed, before needsInput() returns /// true again. /// This call is equivalent to <code>setInput(input, 0, input.length)</code>. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was finished() or ended(). /// </exception> public void SetInput(byte[] input) { SetInput(input, 0, input.Length); } /// <summary> /// Sets the data which should be compressed next. This should be /// only called when needsInput indicates that more input is needed. /// The given byte array should not be changed, before needsInput() returns /// true again. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <param name="offset"> /// the start of the data. /// </param> /// <param name="count"> /// the number of data bytes of input. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was Finish()ed or if previous input is still pending. /// </exception> public void SetInput(byte[] input, int offset, int count) { if ((state & IS_FINISHING) != 0) { throw new InvalidOperationException("Finish() already called"); } } /// <summary> /// Sets the compression level. There is no guarantee of the exact /// position of the change, but if you call this when needsInput is /// true the change of compression level will occur somewhere near /// before the end of the so far given input. /// </summary> /// <param name="level"> /// the new compression level. /// </param> public void SetLevel(int level) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException("level"); } if (this.level != level) { this.level = level; } } /// <summary> /// Get current compression level /// </summary> /// <returns>Returns the current compression level</returns> public int GetLevel() { return level; } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>. /// </summary> /// <param name="dictionary"> /// the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// if SetInput () or Deflate () were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary) { SetDictionary(dictionary, 0, dictionary.Length); } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// The dictionary is a byte array containing strings that are /// likely to occur in the data which should be compressed. The /// dictionary is not stored in the compressed output, only a /// checksum. To decompress the output you need to supply the same /// dictionary again. /// </summary> /// <param name="dictionary"> /// The dictionary data /// </param> /// <param name="index"> /// The index where dictionary information commences. /// </param> /// <param name="count"> /// The number of bytes in the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// If SetInput () or Deflate() were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary, int index, int count) { if (state != INIT_STATE) { throw new InvalidOperationException(); } state = SETDICT_STATE; } #region Instance Fields /// <summary> /// Compression level. /// </summary> int level; /// <summary> /// If true no Zlib/RFC1950 headers or footers are generated /// </summary> bool noZlibHeaderOrFooter; /// <summary> /// The current state. /// </summary> int state; /// <summary> /// The total bytes of output written. /// </summary> long totalOut; #endregion } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Globalization; using System.Linq; using System.Management.Automation; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.SqlDatabase.Properties; using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Common; using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Server; using Microsoft.WindowsAzure.Commands.Utilities.Common; namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet { using DatabaseCopyModel = Model.DatabaseCopy; using Microsoft.Azure.Common.Extensions; /// <summary> /// Stop an ongoing copy operation for a Microsoft Azure SQL Database in the given server context. /// </summary> [Cmdlet(VerbsLifecycle.Stop, "AzureSqlDatabaseCopy", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] public class StopAzureSqlDatabaseCopy : AzurePSCmdlet { #region ParameterSetNames internal const string ByInputObject = "ByInputObject"; internal const string ByDatabase = "ByDatabase"; internal const string ByDatabaseName = "ByDatabaseName"; #endregion #region Parameters /// <summary> /// Gets or sets the name of the server upon which to operate /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the server to operate on.")] [ValidateNotNullOrEmpty] public string ServerName { get; set; } /// <summary> /// Gets or sets the sql database copy object. /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByInputObject, ValueFromPipeline = true, HelpMessage = "The database copy operation to stop.")] [ValidateNotNull] public DatabaseCopyModel DatabaseCopy { get; set; } /// <summary> /// Gets or sets the database object to refresh. /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByDatabase, ValueFromPipeline = true, HelpMessage = "The database object to stop a copy from or to.")] [ValidateNotNull] public Services.Server.Database Database { get; set; } /// <summary> /// Gets or sets the name of the database to retrieve. /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByDatabaseName, HelpMessage = "The name of the database to stop copy.")] [ValidateNotNullOrEmpty] public string DatabaseName { get; set; } /// <summary> /// Gets or sets the name of the partner server. /// </summary> [Parameter(Mandatory = false, ParameterSetName = ByDatabase, HelpMessage = "The name of the partner server")] [Parameter(Mandatory = false, ParameterSetName = ByDatabaseName, HelpMessage = "The name of the partner server")] [ValidateNotNullOrEmpty] public string PartnerServer { get; set; } /// <summary> /// Gets or sets the name of the partner database. /// </summary> [Parameter(Mandatory = false, ParameterSetName = ByDatabase, HelpMessage = "The name of the partner database")] [Parameter(Mandatory = false, ParameterSetName = ByDatabaseName, HelpMessage = "The name of the partner database")] [ValidateNotNullOrEmpty] public string PartnerDatabase { get; set; } /// <summary> /// Gets or sets a value indicating whether to forcefully terminate the copy. /// </summary> [Parameter(HelpMessage = "Forcefully terminate the copy operation.")] public SwitchParameter ForcedTermination { get; set; } /// <summary> /// Gets or sets the switch to not confirm on the termination of the database copy. /// </summary> [Parameter(HelpMessage = "Do not confirm on the termination of the database copy")] public SwitchParameter Force { get; set; } #endregion /// <summary> /// Execute the command. /// </summary> public override void ExecuteCmdlet() { // Obtain the database name from the given parameters. string databaseName = null; if (this.MyInvocation.BoundParameters.ContainsKey("Database")) { databaseName = this.Database.Name; } else if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseName")) { databaseName = this.DatabaseName; } // Use the provided ServerDataServiceContext or create one from the // provided ServerName and the active subscription. IServerDataServiceContext context = ServerDataServiceCertAuth.Create(this.ServerName, AzureSession.CurrentContext.Subscription); DatabaseCopyModel databaseCopy; if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseCopy")) { // Refreshes the given copy object databaseCopy = context.GetDatabaseCopy(this.DatabaseCopy); } else { // Retrieve all database copy object with matching parameters DatabaseCopyModel[] copies = context.GetDatabaseCopy( databaseName, this.PartnerServer, this.PartnerDatabase); if (copies.Length == 0) { throw new ApplicationException(Resources.DatabaseCopyNotFoundGeneric); } else if (copies.Length > 1) { throw new ApplicationException(Resources.MoreThanOneDatabaseCopyFound); } databaseCopy = copies.Single(); } // Do nothing if force is not specified and user cancelled the operation string actionDescription = string.Format( CultureInfo.InvariantCulture, Resources.StopAzureSqlDatabaseCopyDescription, databaseCopy.SourceServerName, databaseCopy.SourceDatabaseName, databaseCopy.DestinationServerName, databaseCopy.DestinationDatabaseName); string actionWarning = string.Format( CultureInfo.InvariantCulture, Resources.StopAzureSqlDatabaseCopyWarning, databaseCopy.SourceServerName, databaseCopy.SourceDatabaseName, databaseCopy.DestinationServerName, databaseCopy.DestinationDatabaseName); this.WriteVerbose(actionDescription); if (!this.Force.IsPresent && !this.ShouldProcess( actionDescription, actionWarning, Resources.ShouldProcessCaption)) { return; } try { // Stop the specified database copy context.StopDatabaseCopy( databaseCopy, this.ForcedTermination.IsPresent); } catch (Exception ex) { SqlDatabaseExceptionHandler.WriteErrorDetails( this, context.ClientRequestId, ex); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.InteropServices; namespace System { public partial class String { public bool Contains(string value) { return (IndexOf(value, StringComparison.Ordinal) >= 0); } public bool Contains(string value, StringComparison comparisonType) { return (IndexOf(value, comparisonType) >= 0); } public bool Contains(char value) { return IndexOf(value) != -1; } public bool Contains(char value, StringComparison comparisonType) { return IndexOf(value, comparisonType) != -1; } // Returns the index of the first occurrence of a specified character in the current instance. // The search starts at startIndex and runs thorough the next count characters. // public int IndexOf(char value) { return IndexOf(value, 0, this.Length); } public int IndexOf(char value, int startIndex) { return IndexOf(value, startIndex, this.Length - startIndex); } public int IndexOf(char value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, CompareOptions.IgnoreCase); case StringComparison.Ordinal: return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, CompareOptions.Ordinal); case StringComparison.OrdinalIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, CompareOptions.OrdinalIgnoreCase); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } public unsafe int IndexOf(char value, int startIndex, int count) { if (startIndex < 0 || startIndex > Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || count > Length - startIndex) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count >= 4) { if (*pCh == value) goto ReturnIndex; if (*(pCh + 1) == value) goto ReturnIndex1; if (*(pCh + 2) == value) goto ReturnIndex2; if (*(pCh + 3) == value) goto ReturnIndex3; count -= 4; pCh += 4; } while (count > 0) { if (*pCh == value) goto ReturnIndex; count--; pCh++; } return -1; ReturnIndex3: pCh++; ReturnIndex2: pCh++; ReturnIndex1: pCh++; ReturnIndex: return (int)(pCh - pChars); } } // Returns the index of the first occurrence of any specified character in the current instance. // The search starts at startIndex and runs to startIndex + count - 1. // public int IndexOfAny(char[] anyOf) { return IndexOfAny(anyOf, 0, this.Length); } public int IndexOfAny(char[] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, this.Length - startIndex); } public int IndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException(nameof(anyOf)); if ((uint)startIndex > (uint)Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if ((uint)count > (uint)(Length - startIndex)) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (anyOf.Length == 2) { // Very common optimization for directory separators (/, \), quotes (", '), brackets, etc return IndexOfAny(anyOf[0], anyOf[1], startIndex, count); } else if (anyOf.Length == 3) { return IndexOfAny(anyOf[0], anyOf[1], anyOf[2], startIndex, count); } else if (anyOf.Length > 3) { return IndexOfCharArray(anyOf, startIndex, count); } else if (anyOf.Length == 1) { return IndexOf(anyOf[0], startIndex, count); } else // anyOf.Length == 0 { return -1; } } private unsafe int IndexOfAny(char value1, char value2, int startIndex, int count) { fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count > 0) { char c = *pCh; if (c == value1 || c == value2) return (int)(pCh - pChars); // Possibly reads outside of count and can include null terminator // Handled in the return logic c = *(pCh + 1); if (c == value1 || c == value2) return (count == 1 ? -1 : (int)(pCh - pChars) + 1); pCh += 2; count -= 2; } return -1; } } private unsafe int IndexOfAny(char value1, char value2, char value3, int startIndex, int count) { fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count > 0) { char c = *pCh; if (c == value1 || c == value2 || c == value3) return (int)(pCh - pChars); pCh++; count--; } return -1; } } private unsafe int IndexOfCharArray(char[] anyOf, int startIndex, int count) { // use probabilistic map, see InitializeProbabilisticMap ProbabilisticMap map = default(ProbabilisticMap); uint* charMap = (uint*)&map; InitializeProbabilisticMap(charMap, anyOf); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count > 0) { int thisChar = *pCh; if (IsCharBitSet(charMap, (byte)thisChar) && IsCharBitSet(charMap, (byte)(thisChar >> 8)) && ArrayContains((char)thisChar, anyOf)) { return (int)(pCh - pChars); } count--; pCh++; } return -1; } } private const int PROBABILISTICMAP_BLOCK_INDEX_MASK = 0x7; private const int PROBABILISTICMAP_BLOCK_INDEX_SHIFT = 0x3; private const int PROBABILISTICMAP_SIZE = 0x8; // A probabilistic map is an optimization that is used in IndexOfAny/ // LastIndexOfAny methods. The idea is to create a bit map of the characters we // are searching for and use this map as a "cheap" check to decide if the // current character in the string exists in the array of input characters. // There are 256 bits in the map, with each character mapped to 2 bits. Every // character is divided into 2 bytes, and then every byte is mapped to 1 bit. // The character map is an array of 8 integers acting as map blocks. The 3 lsb // in each byte in the character is used to index into this map to get the // right block, the value of the remaining 5 msb are used as the bit position // inside this block. private static unsafe void InitializeProbabilisticMap(uint* charMap, ReadOnlySpan<char> anyOf) { bool hasAscii = false; uint* charMapLocal = charMap; // https://github.com/dotnet/coreclr/issues/14264 for (int i = 0; i < anyOf.Length; ++i) { int c = anyOf[i]; // Map low bit SetCharBit(charMapLocal, (byte)c); // Map high bit c >>= 8; if (c == 0) { hasAscii = true; } else { SetCharBit(charMapLocal, (byte)c); } } if (hasAscii) { // Common to search for ASCII symbols. Just set the high value once. charMapLocal[0] |= 1u; } } private static bool ArrayContains(char searchChar, char[] anyOf) { for (int i = 0; i < anyOf.Length; i++) { if (anyOf[i] == searchChar) return true; } return false; } private unsafe static bool IsCharBitSet(uint* charMap, byte value) { return (charMap[value & PROBABILISTICMAP_BLOCK_INDEX_MASK] & (1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT))) != 0; } private unsafe static void SetCharBit(uint* charMap, byte value) { charMap[value & PROBABILISTICMAP_BLOCK_INDEX_MASK] |= 1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT); } public int IndexOf(String value) { return IndexOf(value, StringComparison.CurrentCulture); } public int IndexOf(String value, int startIndex) { return IndexOf(value, startIndex, StringComparison.CurrentCulture); } public int IndexOf(String value, int startIndex, int count) { if (startIndex < 0 || startIndex > this.Length) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } if (count < 0 || count > this.Length - startIndex) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } return IndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int IndexOf(String value, StringComparison comparisonType) { return IndexOf(value, 0, this.Length, comparisonType); } public int IndexOf(String value, int startIndex, StringComparison comparisonType) { return IndexOf(value, startIndex, this.Length - startIndex, comparisonType); } public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) { // Validate inputs if (value == null) throw new ArgumentNullException(nameof(value)); if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || startIndex > this.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.Ordinal: return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.Ordinal); case StringComparison.OrdinalIgnoreCase: return TextInfo.IndexOfStringOrdinalIgnoreCase(this, value, startIndex, count); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } // Returns the index of the last occurrence of a specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOf(char value) { return LastIndexOf(value, this.Length - 1, this.Length); } public int LastIndexOf(char value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public unsafe int LastIndexOf(char value, int startIndex, int count) { if (Length == 0) return -1; if (startIndex < 0 || startIndex >= Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || count - 1 > startIndex) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; //We search [startIndex..EndIndex] while (count >= 4) { if (*pCh == value) goto ReturnIndex; if (*(pCh - 1) == value) goto ReturnIndex1; if (*(pCh - 2) == value) goto ReturnIndex2; if (*(pCh - 3) == value) goto ReturnIndex3; count -= 4; pCh -= 4; } while (count > 0) { if (*pCh == value) goto ReturnIndex; count--; pCh--; } return -1; ReturnIndex3: pCh--; ReturnIndex2: pCh--; ReturnIndex1: pCh--; ReturnIndex: return (int)(pCh - pChars); } } // Returns the index of the last occurrence of any specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOfAny(char[] anyOf) { return LastIndexOfAny(anyOf, this.Length - 1, this.Length); } public int LastIndexOfAny(char[] anyOf, int startIndex) { return LastIndexOfAny(anyOf, startIndex, startIndex + 1); } public unsafe int LastIndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException(nameof(anyOf)); if (Length == 0) return -1; if ((uint)startIndex >= (uint)Length) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } if ((count < 0) || ((count - 1) > startIndex)) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } if (anyOf.Length > 1) { return LastIndexOfCharArray(anyOf, startIndex, count); } else if (anyOf.Length == 1) { return LastIndexOf(anyOf[0], startIndex, count); } else // anyOf.Length == 0 { return -1; } } private unsafe int LastIndexOfCharArray(char[] anyOf, int startIndex, int count) { // use probabilistic map, see InitializeProbabilisticMap ProbabilisticMap map = default(ProbabilisticMap); uint* charMap = (uint*)&map; InitializeProbabilisticMap(charMap, anyOf); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count > 0) { int thisChar = *pCh; if (IsCharBitSet(charMap, (byte)thisChar) && IsCharBitSet(charMap, (byte)(thisChar >> 8)) && ArrayContains((char)thisChar, anyOf)) { return (int)(pCh - pChars); } count--; pCh--; } return -1; } } // Returns the index of the last occurrence of any character in value in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOf(String value) { return LastIndexOf(value, this.Length - 1, this.Length, StringComparison.CurrentCulture); } public int LastIndexOf(String value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture); } public int LastIndexOf(String value, int startIndex, int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } return LastIndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int LastIndexOf(String value, StringComparison comparisonType) { return LastIndexOf(value, this.Length - 1, this.Length, comparisonType); } public int LastIndexOf(String value, int startIndex, StringComparison comparisonType) { return LastIndexOf(value, startIndex, startIndex + 1, comparisonType); } public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) { if (value == null) throw new ArgumentNullException(nameof(value)); // Special case for 0 length input strings if (this.Length == 0 && (startIndex == -1 || startIndex == 0)) return (value.Length == 0) ? 0 : -1; // Now after handling empty strings, make sure we're not out of range if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == this.Length if (startIndex == this.Length) { startIndex--; if (count > 0) count--; } // 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); // If we are looking for nothing, just return startIndex if (value.Length == 0) return startIndex; switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.Ordinal: return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.Ordinal); case StringComparison.OrdinalIgnoreCase: return TextInfo.LastIndexOfStringOrdinalIgnoreCase(this, value, startIndex, count); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } [StructLayout(LayoutKind.Explicit, Size = PROBABILISTICMAP_SIZE * sizeof(uint))] private struct ProbabilisticMap { } } }
using System; using System.IO; using System.Net; using System.Text; using System.Collections; using System.Collections.Generic; using System.Security.Cryptography; using System.Web.Script.Serialization; /** * PubNub Customer API TEST CLASS */ public class PubnubTEST { static public void Main() { // ------------------------------------------------ // USE MASTER CUSTOMER PUB/SUB/SEC Keys // ------------------------------------------------ PubnubCustomer pubnub_customer = new PubnubCustomer( "", // Master Account PUBLISH_KEY "", // Master Account SUBSCRIBE_KEY "" // Master Account SECRET_KEY ); // =================================================================== // Customer Create /w Custom Data // =================================================================== Dictionary<object,object> data = new Dictionary<object,object>(); data.Add( "internal_uid", "123456" ); data.Add( "anything", "anything" ); Dictionary<object,object> new_customer = pubnub_customer.Create(data); if ((int)new_customer["status"] != 200) { Console.WriteLine("Error, Unalbe to Create Customer:"); Console.WriteLine(new_customer["message"]); return; } Console.WriteLine("================================================"); Console.WriteLine("NEW CUSTOMER:"); Console.WriteLine("status: " + new_customer["status"]); Console.WriteLine("uid: " + new_customer["uid"]); Console.WriteLine("publish_key: " + new_customer["publish_key"]); Console.WriteLine("subscribe_key: " + new_customer["subscribe_key"]); Console.WriteLine("secret_key: " + new_customer["secret_key"]); Console.WriteLine("CUSTOM VALUES:"); Console.WriteLine("------------------------------------------------"); Console.WriteLine("internal_uid: " + new_customer["internal_uid"]); Console.WriteLine("anything: " + new_customer["anything"]); Console.WriteLine("================================================"); // =================================================================== // Customer Update // =================================================================== Dictionary<object,object> updates = new Dictionary<object,object>(); updates.Add( "anything", "something else" ); updates.Add( "more-data", "more custom data" ); Dictionary<object,object> updated_customer = pubnub_customer.Update( (string)new_customer["uid"], // CUSTOMER'S UID updates // CUSTOM VALUE UPDATES ); if ((int)updated_customer["status"] != 200) { Console.WriteLine("Error, Unalbe to Update Customer:"); Console.WriteLine(updated_customer["message"]); return; } Console.WriteLine("================================================"); Console.WriteLine("UPDATED CUSTOMER:"); Console.WriteLine("status: " + updated_customer["status"]); Console.WriteLine("UPDATED VALUES:"); Console.WriteLine("------------------------------------------------"); Console.WriteLine("internal_uid: " + updated_customer["internal_uid"]); Console.WriteLine("anything: " + updated_customer["anything"]); Console.WriteLine("more-data: " + updated_customer["more-data"]); Console.WriteLine("================================================"); // =================================================================== // Customer Get // =================================================================== Dictionary<object,object> get_customer = pubnub_customer.Get( (string)updated_customer["uid"] // CUSTOMER'S UID ); if ((int)get_customer["status"] != 200) { Console.WriteLine("Error, Unalbe to Get Customer:"); Console.WriteLine(get_customer["message"]); return; } Console.WriteLine("================================================"); Console.WriteLine("GET CUSTOMER:"); Console.WriteLine("status: " + get_customer["status"]); Console.WriteLine("uid: " + get_customer["uid"]); Console.WriteLine("publish_key: " + get_customer["publish_key"]); Console.WriteLine("subscribe_key: " + get_customer["subscribe_key"]); Console.WriteLine("secret_key: " + get_customer["secret_key"]); Console.WriteLine("------------------------------------------------"); Console.WriteLine("BALANCE VALUES:"); Console.WriteLine("------------------------------------------------"); Console.WriteLine("balance: " + get_customer["balance"]); Console.WriteLine("free_credits_used: " + get_customer["free_credits_used"]); Console.WriteLine("total_credits_used: " + get_customer["total_credits_used"]); Console.WriteLine("------------------------------------------------"); Console.WriteLine("CUSTOM VALUES:"); Console.WriteLine("------------------------------------------------"); Console.WriteLine("internal_uid: " + get_customer["internal_uid"]); Console.WriteLine("anything: " + get_customer["anything"]); Console.WriteLine("more-data: " + get_customer["more-data"]); Console.WriteLine("================================================"); // =================================================================== // Disable Customer // =================================================================== Dictionary<object,object> disable_customer = pubnub_customer.Disable( (string)updated_customer["uid"] // CUSTOMER'S UID ); Console.WriteLine("================================================"); Console.WriteLine("DISABLE CUSTOMER:"); Console.WriteLine("status: " + disable_customer["status"]); Console.WriteLine("message: " + disable_customer["message"]); Console.WriteLine("================================================"); // =================================================================== // Enable Customer // =================================================================== Dictionary<object,object> enable_customer = pubnub_customer.Enable( (string)updated_customer["uid"] // CUSTOMER'S UID ); Console.WriteLine("================================================"); Console.WriteLine("ENABLE CUSTOMER:"); Console.WriteLine("status: " + enable_customer["status"]); Console.WriteLine("message: " + enable_customer["message"]); Console.WriteLine("================================================"); } } /** * PubNub Customer API * * @author Stephen Blum * @package PubnubCustomer */ public class PubnubCustomer { private string ORIGIN = "http://pubnub-prod.appspot.com/"; private string PUBLISH_KEY = ""; private string SUBSCRIBE_KEY = ""; private string SECRET_KEY = ""; /** * Constructor * * Prepare PubNub Class State. * * @param string Publish Key. * @param string Subscribe Key. * @param string Secret Key. */ public PubnubCustomer( string publish_key, string subscribe_key, string secret_key ) { this.PUBLISH_KEY = publish_key; this.SUBSCRIBE_KEY = subscribe_key; this.SECRET_KEY = secret_key; } /** * Create Customer * * Create a new customer and receive API Keys * * @param object custom_data with key/value dictionary data. * @return Dictionary<object,object> customer new API keys. */ public Dictionary<object,object> Create( object custom_data ) { List<string> url = new List<string>(); JavaScriptSerializer serializer = new JavaScriptSerializer(); url.Add("customer-api-2.0-create?"); url.Add( "custom-data=" + this.encodeURIcomponent(serializer.Serialize(custom_data)) ); return this.request(url); } /** * Update Customer * * Update a new customer and receive API Keys * * @param string cuuid PubNub Customer ID. * @param object custom_data with key/value dictionary data. * @return Dictionary<object,object> customer with updates and keys. */ public Dictionary<object,object> Update( string cuuid, object custom_data ) { List<string> url = new List<string>(); JavaScriptSerializer serializer = new JavaScriptSerializer(); url.Add("customer-api-2.0-create?"); url.Add("cuuid=" + cuuid); url.Add( "custom-data=" + this.encodeURIcomponent(serializer.Serialize(custom_data)) ); return this.request(url); } /** * Get Customer * * Get a customer and receive API Keys and Custom Data * * @param string cuuid PubNub Customer ID. * @param object custom_data with key/value dictionary data. * @return Dictionary<object,object> customer with updates and keys. */ public Dictionary<object,object> Get( string cuuid ) { List<string> url = new List<string>(); url.Add("customer-api-2.0-get?"); url.Add("cuuid=" + cuuid); return this.request(url); } /** * Enable Customer * * Enable a Customer * * @param string cuuid PubNub Customer ID. * @return Dictionary<object,object> success info. */ public Dictionary<object,object> Enable(string cuuid) { List<string> url = new List<string>(); url.Add("customer-api-2.0-enable?"); url.Add("cuuid=" + cuuid); url.Add("enabled=1"); return this.request(url); } /** * Disable Customer * * Disable a Customer * * @param string cuuid PubNub Customer ID. * @return Dictionary<object,object> success info. */ public Dictionary<object,object> Disable(string cuuid) { List<string> url = new List<string>(); url.Add("customer-api-2.0-enable?"); url.Add("cuuid=" + cuuid); url.Add("enabled=0"); return this.request(url); } /** * Request URL * * @param List<string> request of url directories. * @return Dictionary<object,object> from JSON response. */ private Dictionary<object,object> request(List<string> url_components) { string temp = null; int count = 0; byte[] buf = new byte[8192]; StringBuilder url = new StringBuilder(); StringBuilder sb = new StringBuilder(); long timestamp = this.unixTimeNow(); JavaScriptSerializer serializer = new JavaScriptSerializer(); // Add Origin To The Request url.Append(this.ORIGIN); // Add Signature url_components.Add("pub-key=" + this.PUBLISH_KEY); url_components.Add("timestamp=" + timestamp.ToString()); url_components.Add("signature=" + this.createSignature(timestamp)); url_components.Add("end=1"); // Generate URL with UTF-8 Encoding foreach ( string url_bit in url_components) { url.Append(url_bit); url.Append("&"); } /* Console.WriteLine("REQUEST:"); Console.WriteLine(url.ToString()); */ // Create Request HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url.ToString()); // Receive Response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream resStream = response.GetResponseStream(); // Read do { count = resStream.Read( buf, 0, buf.Length ); if (count != 0) { temp = Encoding.UTF8.GetString( buf, 0, count ); sb.Append(temp); } } while (count > 0); // Parse Response string message = sb.ToString(); /* Console.WriteLine("RESPONSE:"); Console.WriteLine(message); */ return serializer.Deserialize<Dictionary<object,object>>(message); } private string createSignature(long timestamp) { StringBuilder string_to_sign = new StringBuilder(); string_to_sign .Append(this.PUBLISH_KEY) .Append('/') .Append(this.SUBSCRIBE_KEY) .Append('/') .Append(this.SECRET_KEY) .Append('/') .Append(timestamp); return md5(string_to_sign.ToString()); } private long unixTimeNow() { TimeSpan _TimeSpan = ( DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0) ); return (long)_TimeSpan.TotalSeconds; } private string encodeURIcomponent(string s) { StringBuilder o = new StringBuilder(); foreach (char ch in s.ToCharArray()) { if (isUnsafe(ch)) { o.Append('%'); o.Append(toHex(ch / 16)); o.Append(toHex(ch % 16)); } else o.Append(ch); } return o.ToString(); } private char toHex(int ch) { return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10); } private bool isUnsafe(char ch) { return " ~`!@#$%^&*()+=[]\\{}|;':\",./<>?".IndexOf(ch) >= 0; } private static string md5(string text) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] data = Encoding.Default.GetBytes(text); byte[] hash = md5.ComputeHash(data); string hexaHash = ""; foreach (byte b in hash) hexaHash += String.Format("{0:x2}", b); return hexaHash; } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.IO; using System.Net.Sockets; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.WebSockets; namespace Microsoft.VisualStudioTools { public abstract class WebSocketProxyBase : IHttpHandler { private static long _lastId; private static Task _currentSession; // represents the current active debugging session, and completes when it is over private static volatile StringWriter _log; private readonly long _id; public WebSocketProxyBase() { _id = Interlocked.Increment(ref _lastId); } public abstract int DebuggerPort { get; } public abstract bool AllowConcurrentConnections { get; } public abstract void ProcessHelpPageRequest(HttpContext context); public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { if (context.IsWebSocketRequest) { context.AcceptWebSocketRequest(WebSocketRequestHandler); } else { context.Response.ContentType = "text/html"; context.Response.ContentEncoding = Encoding.UTF8; switch (context.Request.QueryString["debug"]) { case "startlog": _log = new StringWriter(); context.Response.Write("Logging is now enabled. <a href='?debug=viewlog'>View</a>. <a href='?debug=stoplog'>Disable</a>."); return; case "stoplog": _log = null; context.Response.Write("Logging is now disabled. <a href='?debug=startlog'>Enable</a>."); return; case "clearlog": { var log = _log; if (log != null) { log.GetStringBuilder().Clear(); } context.Response.Write("Log is cleared. <a href='?debug=viewlog'>View</a>."); return; } case "viewlog": { var log = _log; if (log == null) { context.Response.Write("Logging is disabled. <a href='?debug=startlog'>Enable</a>."); } else { context.Response.Write("Logging is enabled. <a href='?debug=clearlog'>Clear</a>. <a href='?debug=stoplog'>Disable</a>. <p><pre>"); context.Response.Write(HttpUtility.HtmlDecode(log.ToString())); context.Response.Write("</pre>"); } context.Response.End(); return; } } ProcessHelpPageRequest(context); } } private async Task WebSocketRequestHandler(AspNetWebSocketContext context) { Log("Accepted web socket request from {0}.", context.UserHostAddress); TaskCompletionSource<bool> tcs = null; if (!AllowConcurrentConnections) { tcs = new TaskCompletionSource<bool>(); while (true) { var currentSession = Interlocked.CompareExchange(ref _currentSession, tcs.Task, null); if (currentSession == null) { break; } Log("Another session is active, waiting for completion."); await currentSession; Log("The other session completed, proceeding."); } } try { var webSocket = context.WebSocket; using (var tcpClient = new TcpClient("localhost", DebuggerPort)) { try { var stream = tcpClient.GetStream(); var cts = new CancellationTokenSource(); // Start the workers that copy data from one socket to the other in both directions, and wait until either // completes. The workers are fully async, and so their loops are transparently interleaved when running. // Usually end of session is caused by VS dropping its connection on detach, and so it will be // CopyFromWebSocketToStream that returns first; but it can be the other one if debuggee process crashes. Log("Starting copy workers."); var copyFromStreamToWebSocketTask = CopyFromStreamToWebSocketWorker(stream, webSocket, cts.Token); var copyFromWebSocketToStreamTask = CopyFromWebSocketToStreamWorker(webSocket, stream, cts.Token); Task completedTask = null; try { completedTask = await Task.WhenAny(copyFromStreamToWebSocketTask, copyFromWebSocketToStreamTask); } catch (IOException ex) { Log(ex); } catch (WebSocketException ex) { Log(ex); } // Now that one worker is done, try to gracefully terminate the other one by issuing a cancellation request. // it is normally blocked on a read, and this will cancel it if possible, and throw OperationCanceledException. Log("One of the workers completed, shutting down the remaining one."); cts.Cancel(); try { await Task.WhenAny(Task.WhenAll(copyFromStreamToWebSocketTask, copyFromWebSocketToStreamTask), Task.Delay(1000)); } catch (OperationCanceledException ex) { Log(ex); } // Try to gracefully close the websocket if it's still open - this is not necessary, but nice to have. Log("Both workers shut down, trying to close websocket."); try { await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None); } catch (WebSocketException ex) { Log(ex); } } finally { // Gracefully close the TCP socket. This is crucial to avoid "Remote debugger already attached" problems. Log("Shutting down TCP socket."); try { tcpClient.Client.Shutdown(SocketShutdown.Both); tcpClient.Client.Disconnect(false); } catch (SocketException ex) { Log(ex); } Log("All done!"); } } } finally { if (tcs != null) { Volatile.Write(ref _currentSession, null); tcs.SetResult(true); } } } private async Task CopyFromStreamToWebSocketWorker(Stream stream, WebSocket webSocket, CancellationToken ct) { var buffer = new byte[0x10000]; while (webSocket.State == WebSocketState.Open) { ct.ThrowIfCancellationRequested(); Log("TCP -> WS: waiting for packet."); int count = await stream.ReadAsync(buffer, 0, buffer.Length, ct); Log("TCP -> WS: received packet:\n{0}", Encoding.UTF8.GetString(buffer, 0, count)); if (count == 0) { Log("TCP -> WS: zero-length TCP packet received, connection closed."); break; } await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, count), WebSocketMessageType.Binary, true, ct); Log("TCP -> WS: packet relayed."); } } private async Task CopyFromWebSocketToStreamWorker(WebSocket webSocket, Stream stream, CancellationToken ct) { var buffer = new ArraySegment<byte>(new byte[0x10000]); while (webSocket.State == WebSocketState.Open) { ct.ThrowIfCancellationRequested(); Log("WS -> TCP: waiting for packet."); var recv = await webSocket.ReceiveAsync(buffer, ct); Log("WS -> TCP: received packet:\n{0}", Encoding.UTF8.GetString(buffer.Array, 0, recv.Count)); await stream.WriteAsync(buffer.Array, 0, recv.Count, ct); Log("WS -> TCP: packet relayed."); } } private void Log(object o) { var log = _log; if (log != null) { log.WriteLine(_id + " :: " + o); } } private void Log(string format, object arg1) { var log = _log; if (log != null) { log.WriteLine(_id + " :: " + format, arg1); } } } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // Copyright (c) 2010, Nathan Brown // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System.Collections.Generic; using System.Data; using System.Linq; using FluentMigrator.Builders.Execute; using FluentMigrator.Model; using FluentMigrator.Runner; using FluentMigrator.Runner.Processors.SqlServer; namespace FluentMigrator.SchemaDump.SchemaDumpers { public class SqlServerSchemaDumper : ISchemaDumper { public virtual IAnnouncer Announcer { get; set; } public SqlServerProcessor Processor { get; set; } public bool WasCommitted { get; private set; } public SqlServerSchemaDumper(SqlServerProcessor processor, IAnnouncer announcer) { this.Announcer = announcer; this.Processor = processor; } public virtual void Execute(string template, params object[] args) { Processor.Execute(template, args); } public virtual bool Exists(string template, params object[] args) { return Processor.Exists(template, args); } public virtual DataSet ReadTableData(string tableName) { return Processor.Read("SELECT * FROM [{0}]", tableName); } public virtual DataSet Read(string template, params object[] args) { return Processor.Read(template, args); } public virtual void Process(PerformDBOperationExpression expression) { Processor.Process(expression); } protected string FormatSqlEscape(string sql) { return sql.Replace("'", "''"); } public virtual IList<TableDefinition> ReadDbSchema() { IList<TableDefinition> tables = ReadTables(); foreach (TableDefinition table in tables) { table.Indexes = ReadIndexes(table.SchemaName, table.Name); table.ForeignKeys = ReadForeignKeys(table.SchemaName, table.Name); } return tables as IList<TableDefinition>; } protected virtual IList<FluentMigrator.Model.TableDefinition> ReadTables() { string query = @"SELECT OBJECT_SCHEMA_NAME(t.[object_id],DB_ID()) AS [Schema], t.name AS [Table], c.[Name] AS VersionColumnName, t.object_id AS [TableID], c.column_id AS [ColumnID], def.definition AS [DefaultValue], c.[system_type_id] AS [TypeID], c.[user_type_id] AS [UserTypeID], c.[max_length] AS [Length], c.[precision] AS [Precision], c.[scale] AS [Scale], c.[is_identity] AS [IsIdentity], c.[is_nullable] AS [IsNullable], CASE WHEN EXISTS(SELECT 1 FROM sys.foreign_key_columns fkc WHERE t.object_id = fkc.parent_object_id AND c.column_id = fkc.parent_column_id) THEN 1 ELSE 0 END AS IsForeignKey, CASE WHEN EXISTS(select 1 from sys.index_columns ic WHERE t.object_id = ic.object_id AND c.column_id = ic.column_id) THEN 1 ELSE 0 END AS IsIndexed ,CASE WHEN kcu.CONSTRAINT_NAME IS NOT NULL THEN 1 ELSE 0 END AS IsPrimaryKey , CASE WHEN EXISTS(select stc.CONSTRAINT_NAME, skcu.TABLE_NAME, skcu.COLUMN_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS stc JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE skcu ON skcu.CONSTRAINT_NAME = stc.CONSTRAINT_NAME WHERE stc.CONSTRAINT_TYPE = 'UNIQUE' AND skcu.TABLE_NAME = t.name AND skcu.COLUMN_NAME = c.name) THEN 1 ELSE 0 END AS IsUnique ,pk.name AS PrimaryKeyName FROM sys.all_columns c JOIN sys.tables t ON c.object_id = t.object_id AND t.type = 'u' LEFT JOIN sys.default_constraints def ON c.default_object_id = def.object_id LEFT JOIN sys.key_constraints pk ON t.object_id = pk.parent_object_id AND pk.type = 'PK' LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON t.name = kcu.TABLE_NAME AND c.name = kcu.COLUMN_NAME AND pk.name = kcu.CONSTRAINT_NAME ORDER BY t.name, c.name"; DataSet ds = Read(query); DataTable dt = ds.Tables[0]; IList<TableDefinition> tables = new List<TableDefinition>(); foreach (DataRow dr in dt.Rows) { List<TableDefinition> matches = (from t in tables where t.Name == dr["Table"].ToString() && t.SchemaName == dr["Schema"].ToString() select t).ToList(); TableDefinition tableDef = null; if (matches.Count > 0) tableDef = matches[0]; // create the table if not found if (tableDef == null) { tableDef = new TableDefinition() { Name = dr["Table"].ToString(), SchemaName = dr["Schema"].ToString() }; tables.Add(tableDef); } //find the column List<ColumnDefinition> cmatches = (from c in tableDef.Columns where c.Name == dr["VersionColumnName"].ToString() select c).ToList(); ColumnDefinition colDef = null; if (cmatches.Count > 0) colDef = cmatches[0]; if (colDef == null) { //need to create and add the column tableDef.Columns.Add(new ColumnDefinition() { Name = dr["VersionColumnName"].ToString(), CustomType = "", //TODO: set this property DefaultValue = dr.IsNull("DefaultValue") ? "" : dr["DefaultValue"].ToString(), IsForeignKey = dr["IsForeignKey"].ToString() == "1", IsIdentity = dr["IsIdentity"].ToString() == "True", IsIndexed = dr["IsIndexed"].ToString() == "1", IsNullable = dr["IsNullable"].ToString() == "True", IsPrimaryKey = dr["IsPrimaryKey"].ToString() == "1", IsUnique = dr["IsUnique"].ToString() == "1", Precision = int.Parse(dr["Precision"].ToString()), PrimaryKeyName = dr.IsNull("PrimaryKeyName") ? "" : dr["PrimaryKeyName"].ToString(), Size = int.Parse(dr["Length"].ToString()), TableName = dr["Table"].ToString(), Type = GetDbType(int.Parse(dr["TypeID"].ToString())), //TODO: set this property ModificationType = ColumnModificationType.Create }); } } return tables; } protected virtual DbType GetDbType(int typeNum) { switch (typeNum) { case 34: //'byte[]' return DbType.Byte; case 35: //'string' return DbType.String; case 36: //'System.Guid' return DbType.Guid; case 48: //'byte' return DbType.Byte; case 52: //'short' return DbType.Int16; case 56: //'int' return DbType.Int32; case 58: //'System.DateTime' return DbType.DateTime; case 59: //'float' return DbType.Int64; case 60: //'decimal' return DbType.Decimal; case 61: //'System.DateTime' return DbType.DateTime; case 62: //'double' return DbType.Double; case 98: //'object' return DbType.Object; case 99: //'string' return DbType.String; case 104: //'bool' return DbType.Boolean; case 106: //'decimal' return DbType.Decimal; case 108: //'decimal' return DbType.Decimal; case 122: //'decimal' return DbType.Decimal; case 127: //'long' return DbType.Int64; case 165: //'byte[]' return DbType.Byte; case 167: //'string' return DbType.String; case 173: //'byte[]' return DbType.Byte; case 175: //'string' return DbType.String; case 189: //'long' return DbType.Int64; case 231: //'string' case 239: //'string' case 241: //'string' default: return DbType.String; } } protected virtual IList<IndexDefinition> ReadIndexes(string schemaName, string tableName) { string query = @"SELECT OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema], T.[name] AS [table_name], I.[name] AS [index_name], AC.[name] AS [column_name], I.[type_desc], I.[is_unique], I.[data_space_id], I.[ignore_dup_key], I.[is_primary_key], I.[is_unique_constraint], I.[fill_factor], I.[is_padded], I.[is_disabled], I.[is_hypothetical], I.[allow_row_locks], I.[allow_page_locks], IC.[is_descending_key], IC.[is_included_column] FROM sys.[tables] AS T INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id] INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id] INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id] WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP' AND T.object_id = OBJECT_ID('[{0}].[{1}]') ORDER BY T.[name], I.[index_id], IC.[key_ordinal]"; DataSet ds = Read(query, schemaName, tableName); DataTable dt = ds.Tables[0]; IList<IndexDefinition> indexes = new List<IndexDefinition>(); foreach (DataRow dr in dt.Rows) { List<IndexDefinition> matches = (from i in indexes where i.Name == dr["index_name"].ToString() && i.SchemaName == dr["Schema"].ToString() select i).ToList(); IndexDefinition iDef = null; if (matches.Count > 0) iDef = matches[0]; // create the table if not found if (iDef == null) { iDef = new IndexDefinition() { Name = dr["index_name"].ToString(), SchemaName = dr["Schema"].ToString(), IsClustered = dr["type_desc"].ToString() == "CLUSTERED", IsUnique = dr["is_unique"].ToString() == "1", TableName = dr["table_name"].ToString() }; indexes.Add(iDef); } ICollection<IndexColumnDefinition> ms; // columns ms = (from m in iDef.Columns where m.Name == dr["column_name"].ToString() select m).ToList(); if (ms.Count == 0) { iDef.Columns.Add(new IndexColumnDefinition() { Name = dr["column_name"].ToString(), Direction = dr["is_descending_key"].ToString() == "1" ? Direction.Descending : Direction.Ascending }); } } return indexes; } protected virtual IList<ForeignKeyDefinition> ReadForeignKeys(string schemaName, string tableName) { string query = @"SELECT C.CONSTRAINT_SCHEMA AS Contraint_Schema, C.CONSTRAINT_NAME AS Constraint_Name, FK.CONSTRAINT_SCHEMA AS ForeignTableSchema, FK.TABLE_NAME AS FK_Table, CU.COLUMN_NAME AS FK_Column, PK.CONSTRAINT_SCHEMA as PrimaryTableSchema, PK.TABLE_NAME AS PK_Table, PT.COLUMN_NAME AS PK_Column FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN ( SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' ) PT ON PT.TABLE_NAME = PK.TABLE_NAME WHERE PK.TABLE_NAME = '{1}' AND PK.CONSTRAINT_SCHEMA = '{0}' ORDER BY Constraint_Name"; DataSet ds = Read(query, schemaName, tableName); DataTable dt = ds.Tables[0]; IList<ForeignKeyDefinition> keys = new List<ForeignKeyDefinition>(); foreach (DataRow dr in dt.Rows) { List<ForeignKeyDefinition> matches = (from i in keys where i.Name == dr["Constraint_Name"].ToString() select i).ToList(); ForeignKeyDefinition d = null; if (matches.Count > 0) d = matches[0]; // create the table if not found if (d == null) { d = new ForeignKeyDefinition() { Name = dr["Constraint_Name"].ToString(), ForeignTableSchema = dr["ForeignTableSchema"].ToString(), ForeignTable = dr["FK_Table"].ToString(), PrimaryTable = dr["PK_Table"].ToString(), PrimaryTableSchema = dr["PrimaryTableSchema"].ToString() }; keys.Add(d); } ICollection<string> ms; // Foreign Columns ms = (from m in d.ForeignColumns where m == dr["FK_Table"].ToString() select m).ToList(); if (ms.Count == 0) d.ForeignColumns.Add(dr["FK_Table"].ToString()); // Primary Columns ms = (from m in d.PrimaryColumns where m == dr["PK_Table"].ToString() select m).ToList(); if (ms.Count == 0) d.PrimaryColumns.Add(dr["PK_Table"].ToString()); } return keys; } } }
// Copyright (c) Duende Software. All rights reserved. // See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Events; using Duende.IdentityServer.Extensions; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace IdentityServerHost.Quickstart.UI { [Authorize] [SecurityHeaders] public class DeviceController : Controller { private readonly IDeviceFlowInteractionService _interaction; private readonly IEventService _events; private readonly IOptions<IdentityServerOptions> _options; private readonly ILogger<DeviceController> _logger; public DeviceController( IDeviceFlowInteractionService interaction, IEventService eventService, IOptions<IdentityServerOptions> options, ILogger<DeviceController> logger) { _interaction = interaction; _events = eventService; _options = options; _logger = logger; } [HttpGet] public async Task<IActionResult> Index() { string userCodeParamName = _options.Value.UserInteraction.DeviceVerificationUserCodeParameter; string userCode = Request.Query[userCodeParamName]; if (string.IsNullOrWhiteSpace(userCode)) return View("UserCodeCapture"); var vm = await BuildViewModelAsync(userCode); if (vm == null) return View("Error"); vm.ConfirmUserCode = true; return View("UserCodeConfirmation", vm); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> UserCodeCapture(string userCode) { var vm = await BuildViewModelAsync(userCode); if (vm == null) return View("Error"); return View("UserCodeConfirmation", vm); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Callback(DeviceAuthorizationInputModel model) { if (model == null) throw new ArgumentNullException(nameof(model)); var result = await ProcessConsent(model); if (result.HasValidationError) return View("Error"); return View("Success"); } private async Task<ProcessConsentResult> ProcessConsent(DeviceAuthorizationInputModel model) { var result = new ProcessConsentResult(); var request = await _interaction.GetAuthorizationContextAsync(model.UserCode); if (request == null) return result; ConsentResponse grantedConsent = null; // user clicked 'no' - send back the standard 'access_denied' response if (model.Button == "no") { grantedConsent = new ConsentResponse { Error = AuthorizationError.AccessDenied }; // emit event await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues)); } // user clicked 'yes' - validate the data else if (model.Button == "yes") { // if the user consented to some scope, build the response model if (model.ScopesConsented != null && model.ScopesConsented.Any()) { var scopes = model.ScopesConsented; if (ConsentOptions.EnableOfflineAccess == false) { scopes = scopes.Where(x => x != Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess); } grantedConsent = new ConsentResponse { RememberConsent = model.RememberConsent, ScopesValuesConsented = scopes.ToArray(), Description = model.Description }; // emit event await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent)); } else { result.ValidationError = ConsentOptions.MustChooseOneErrorMessage; } } else { result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage; } if (grantedConsent != null) { // communicate outcome of consent back to identityserver await _interaction.HandleRequestAsync(model.UserCode, grantedConsent); // indicate that's it ok to redirect back to authorization endpoint result.RedirectUri = model.ReturnUrl; result.Client = request.Client; } else { // we need to redisplay the consent UI result.ViewModel = await BuildViewModelAsync(model.UserCode, model); } return result; } private async Task<DeviceAuthorizationViewModel> BuildViewModelAsync(string userCode, DeviceAuthorizationInputModel model = null) { var request = await _interaction.GetAuthorizationContextAsync(userCode); if (request != null) { return CreateConsentViewModel(userCode, model, request); } return null; } private DeviceAuthorizationViewModel CreateConsentViewModel(string userCode, DeviceAuthorizationInputModel model, DeviceFlowAuthorizationRequest request) { var vm = new DeviceAuthorizationViewModel { UserCode = userCode, Description = model?.Description, RememberConsent = model?.RememberConsent ?? true, ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(), ClientName = request.Client.ClientName ?? request.Client.ClientId, ClientUrl = request.Client.ClientUri, ClientLogoUrl = request.Client.LogoUri, AllowRememberConsent = request.Client.AllowRememberConsent }; vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray(); var apiScopes = new List<ScopeViewModel>(); foreach (var parsedScope in request.ValidatedResources.ParsedScopes) { var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName); if (apiScope != null) { var scopeVm = CreateScopeViewModel(parsedScope, apiScope, vm.ScopesConsented.Contains(parsedScope.RawValue) || model == null); apiScopes.Add(scopeVm); } } if (ConsentOptions.EnableOfflineAccess && request.ValidatedResources.Resources.OfflineAccess) { apiScopes.Add(GetOfflineAccessScope(vm.ScopesConsented.Contains(Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)); } vm.ApiScopes = apiScopes; return vm; } private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check) { return new ScopeViewModel { Value = identity.Name, DisplayName = identity.DisplayName ?? identity.Name, Description = identity.Description, Emphasize = identity.Emphasize, Required = identity.Required, Checked = check || identity.Required }; } public ScopeViewModel CreateScopeViewModel(ParsedScopeValue parsedScopeValue, ApiScope apiScope, bool check) { return new ScopeViewModel { Value = parsedScopeValue.RawValue, // todo: use the parsed scope value in the display? DisplayName = apiScope.DisplayName ?? apiScope.Name, Description = apiScope.Description, Emphasize = apiScope.Emphasize, Required = apiScope.Required, Checked = check || apiScope.Required }; } private ScopeViewModel GetOfflineAccessScope(bool check) { return new ScopeViewModel { Value = Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess, DisplayName = ConsentOptions.OfflineAccessDisplayName, Description = ConsentOptions.OfflineAccessDescription, Emphasize = true, Checked = check }; } } }
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Linq; using log4net; using log4net.Core; using log4net.Appender; namespace HFMCmd { /// <summary> /// Defines the interface for classes that want to participate in outputting /// tabular information. /// </summary> public interface IOutput { /// <summary> /// Property for setting the current operation that is in progress. /// </summary> string Operation { get; set; } bool Cancelled { get; } /// <summary> /// Write a line of text, using string.Format to combine multiple /// values into a line of text. /// </summary> void WriteLine(string format, params object[] values); /// <summary> /// Called before a table of information is output; identifies the names /// of the fields that will be output (and implicitly, how many fields /// there will be per record). Defined as an array of objects, since /// field names may be followed by an optional int width specification. /// As such, implementations that don't need field widths should ignore /// non-string fields. /// A special case occurs if this method is called with no fields; in /// this case, the output should be formatted as a plain text with no /// headers. /// </summary> void SetHeader(params object[] fields); /// <summary> /// Called for each record that is to be output. /// </summary> void WriteRecord(params object[] values); /// <summary> /// Marker method called to indicate completion of output for the current /// table. /// </summary> void End(bool suppressFooter); /// <summary> /// Instructs the output mechanism to display some form of progress /// indicator, if appropriate. Progress will be measured in units up to /// total, which will be repeated iterations times. /// </summary> void InitProgress(string operation, int iterations, int total); /// <summary> /// Update the current progress completion ratio for the current /// iteration. If the IOutput implementation returns true, the /// operation should be aborted, if possible. /// </summary> bool SetProgress(int progress); /// <summary> /// Update the current progress iteration. /// </summary> bool IterationComplete(); /// <summary> /// Indicates that the operation that was in progress is now complete. /// </summary> void EndProgress(); } /// <summary> /// Helper class providing convenience methods that can be used with any /// IOutput implementations to ease output of common cases, such as: /// - a blank line /// - a single line with no field information /// - a single record with a single field /// - a line per object in an IEnumerable /// </summary> public static class OutputHelper { // Reference to class logger public static readonly ILog _log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Characters at which line breaks can be created public static char[] LINEBREAKS = new char[] { '\n', '\r' }; public static char[] WHITESPACE = new char[] { ' ', '\t' }; public static char[] WORDBREAKS = new char[] { '-', ',', '.', ';', '#', ')', ']', '}' }; /// <summary> /// Converts the object[] passed to SetHeader into field names and /// widths. The field names are returned as a string[], while the field /// widths are returned in an out int[]. /// </summary> public static string[] GetFieldNamesAndWidths(object[] fields, out int[] widths) { int widthIdx = -1; string[] names = fields.OfType<string>().ToArray(); widths = new int[names.Length]; for(var i = 0; i < fields.Length; ++i) { if(fields[i].GetType() == typeof(string)) { widthIdx++; } else if(fields[i].GetType() == typeof(int) && widthIdx >= 0 && widthIdx < names.Length) { widths[widthIdx] = (int)fields[i]; } else { throw new ArgumentException(string.Format("Invalid field specifier: {0}", fields[i])); } } return names; } /// <summary> /// Method for wrapping text to a certain width. /// </summary> public static List<string> WrapText(object value, int width) { List<string> lines = new List<string>(); var sVal = value == null ? "" : value.ToString().Trim(); var nlPos = 0; var wsPos = 0; var wbPos = 0; string chunk; while(sVal.Length > width) { chunk = sVal.Substring(0, width + 1); nlPos = chunk.IndexOfAny(LINEBREAKS); wsPos = chunk.LastIndexOfAny(WHITESPACE); wbPos = chunk.LastIndexOfAny(WORDBREAKS, width - 1); if(nlPos >= 0) { // Break at new-line lines.Add(sVal.Substring(0, nlPos).Trim()); sVal = sVal.Substring(nlPos+1).Trim(); } else if(wsPos > 0 && wsPos > wbPos || (wbPos > 5 && wbPos - 5 < wsPos)) { // Break at whitespace lines.Add(sVal.Substring(0, wsPos).Trim()); sVal = sVal.Substring(wsPos + 1).Trim(); } else if(wbPos > 0) { // Break at word-break character lines.Add(sVal.Substring(0, wbPos + 1)); sVal = sVal.Substring(wbPos + 1).Trim(); } else { // Force a break at width lines.Add(sVal.Substring(0, width)); sVal = sVal.Substring(width); } } lines.Add(sVal); return lines; } /// <summary> /// Eases use of the IOutput interface for cases where we just want to /// output a blank line. /// </summary> public static void WriteLine(this IOutput output) { output.WriteLine(""); } /// <summary> /// Eases use of the IOutput interface for cases where we just want to /// output a single record with a single field. /// </summary> public static void WriteSingleValue(this IOutput output, object value, params object[] field) { output.SetHeader(field); output.WriteRecord(value); output.End(); } /// <summary> /// Eases use of the IOutput interface for cases where we just want to /// output a single record with multiple fields. /// </summary> public static void WriteSingleRecord(this IOutput output, params object[] values) { output.WriteRecord(values); output.End(); } /// <summary> /// Eases use of the IOutput interface for cases where we want to output /// a collection of records with a single column. /// </summary> public static void WriteEnumerable(this IOutput output, IEnumerable enumerable, params object[] header) { output.SetHeader(header); foreach(var item in enumerable) { output.WriteRecord(item); } output.End(); } /// <summary> /// Convenience for the common case of not suppressing footer record /// </summary> public static void End(this IOutput output) { output.End(false); } /// <summary> /// Helper method for initiating an operation whose progress will be /// monitored. Provides defaults for iteration (1) and total (100). /// </summary> public static void InitProgress(this IOutput output, string operation) { output.InitProgress(operation, 1, 100); } /// <summary> /// Helper method for initiating an operation whose progress will be /// monitored. Provides default for total (100). /// </summary> public static void InitProgress(this IOutput output, string operation, int iterations) { output.InitProgress(operation, iterations, 100); } /// <summary> /// Method that can be used by IOutput implementations to determine the /// appropriate value to send for the cancel return value in a call to /// SetProgress. /// </summary> public static bool ShouldCancel() { return CommandLine.UI.Interrupted || CommandLine.UI.EscPressed; } } /// <summary> /// Implementation of IOutput that does not output - like a /dev/nul device, /// it ignores output sent to it. Use this when no output is desired, since /// a valid IOutput (non-null) IOutput instance must be supplied to many /// methods. Use of this class prevents methods that take an IOutput from /// having to check if it is non-null. /// </summary> public class NullOutput : IOutput { public static NullOutput Instance = new NullOutput(); private bool _cancelled = false; public string Operation { get; set; } public bool Cancelled { get { return _cancelled; } } public void WriteLine(string format, params object[] values) { } public void SetHeader(params object[] fields) { } public void WriteRecord(params object[] values) { } public void End(bool suppress) { } public void InitProgress(string operation, int iterations) { _cancelled = false; } public void InitProgress(string operation, int iterations, int total) { _cancelled = false; } public bool SetProgress(int progress) { _cancelled = _cancelled || OutputHelper.ShouldCancel(); return _cancelled; } public bool IterationComplete() { _cancelled = _cancelled || OutputHelper.ShouldCancel(); return _cancelled; } public void EndProgress() { } } /// <summary> /// Base class for IOutput implementations that output data in fixed width /// format. /// </summary> public abstract class FixedWidthOutput : IOutput { /// Maximum width for a line of output private int _maxWidth = -1; private int _indentWidth = 0; private string _indentString = ""; /// Current operation public string Operation { get; set; } /// Whether operation was cancelled public bool Cancelled { get { return _cancelled; } } /// Level of indentation to use public int IndentWidth { get { return _indentWidth; } set { _indentWidth = value; _indentString = new String(' ', _indentWidth); } } public string IndentString { get { return _indentString; } } /// String to use as a field separator public string FieldSeparator = " "; /// Default field width if no width specified for a field public int DefaultFieldWidth = 20; /// Maximum width to constrain a line of output to. If the content /// exceeds this length, it will be wrapped. A value of -1 indicates /// no maximum width. public int MaxWidth { get { return _maxWidth; } set { _maxWidth = value >= 50 ? value : -1; } } /// Names of the current fields protected string[] _fieldNames; /// Actual widths to be used for subsequent calls to WriteRecord protected int[] _widths; /// Format string used to format fields into a line of text protected string _format; /// Number of records output in current table protected int _records; /// Whether current operation has been cancelled protected bool _cancelled; /// Total number of iterations of progress operation to be completed protected int _totalIterations; /// Completed iterations protected int _iteration; /// Total number of steps in a single iteration of the progress operation protected int _total; /// Currently completed number of progress steps in the current iteration protected int _progress; public abstract void WriteLine(string format, params object[] values); public virtual void SetHeader(params object[] fields) { if(fields != null && fields.Length > 0) { _fieldNames = OutputHelper.GetFieldNamesAndWidths(fields, out _widths); var total = IndentWidth; for(var i = 0; i < _widths.Length; total += _widths[i++] + FieldSeparator.Length) { // Last field gets special treatment if(i == _widths.Length - 1 && MaxWidth > 0 && total < MaxWidth && (_widths[i] == 0 ||_widths[i] > (MaxWidth - total))) { _widths[i] = MaxWidth - total; } else if(_widths[i] == 0) { _widths[i] = DefaultFieldWidth; } } var formats = _fieldNames.Select((field, i) => _widths[i] > 0 ? string.Format("{{{0},{1}}}", i, _widths[i] * -1) : "{0}" ).ToArray(); _format = new String(' ', IndentWidth) + string.Join(FieldSeparator, formats); } else { _format = null; } _records = 0; } public virtual void WriteRecord(params object[] values) { _records++; } // Default no-op implementation public virtual void End(bool suppress) { } /// <summary> /// Wraps record values according to the current column widths, and /// returns a List of lines, formatted to line up correctly in the /// fields. /// </summary> public List<string> Wrap(params object[] values) { List<string>[] fields = new List<string>[values.Length]; var i =0; var lineCount = 0; foreach(var val in values) { fields[i] = OutputHelper.WrapText(val, _widths[i]); lineCount = Math.Max(lineCount, fields[i].Count); i++; } List<string> lines = new List<string>(lineCount); var line = 0; string[] record = new string[values.Length]; while(line < lineCount) { record = new string[values.Length]; for(i = 0; i < values.Length; ++i) { if(fields[i].Count > line) { record[i] = fields[i][line]; } } lines.Add(string.Format(_format, record)); line++; } return lines; } public virtual void InitProgress(string operation, int iterations, int total) { Operation = operation; _totalIterations = iterations; _iteration = 0; _total = total; _progress = 0; _cancelled = false; } public virtual bool SetProgress(int progress) { if(Operation == null) { throw new InvalidOperationException("SetProgress called when no operation was supposed to be in progress"); } _progress = progress; _cancelled = _cancelled || OutputHelper.ShouldCancel(); return _cancelled; } public virtual bool IterationComplete() { if(Operation == null) { throw new InvalidOperationException("IterationComplete called when no operation was supposed to be in progress"); } _iteration++; _progress = 0; _cancelled = _cancelled || OutputHelper.ShouldCancel(); return _cancelled; } public virtual void EndProgress() { if(_cancelled) { WriteLine("{0} cancelled", Operation); } Operation = null; } protected virtual int CompletionPct() { int pct = 0; if(_totalIterations * _total > 0) { pct = (_iteration * _total + _progress) * 100 / (_totalIterations * _total); if (pct < 0) { pct = 0; } else if (pct > 100) { pct = 100; } } return pct; } } /// <summary> /// Sends output to the log. /// </summary> public class LogOutput : FixedWidthOutput { // Reference to class logger protected static readonly ILog _log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// Minimum interval that must elapse before we will consider logging a /// progress update public static int MIN_LOG_INTERVAL = 15; /// Maximum interval that should pass without logging a progress update public static int MAX_LOG_INTERVAL = 300; /// Minimum progress that must be made before a new log message is generated public static int MIN_PROGRESS_INCREMENT = 10; // Time the last progress log message was generated protected DateTime _lastLog; /// Constructor public LogOutput() { IndentWidth = 4; } public override void WriteLine(string format, params object[] values) { _log.InfoFormat(format, values); } public override void SetHeader(params object[] fields) { base.SetHeader(fields); // Display the field headers if there is more than one field if(fields.Length > 1) { _log.InfoFormat(_format, _fieldNames.Select((field, i) => new String('-', _widths[i])).ToArray()); _log.InfoFormat(_format, _fieldNames); _log.InfoFormat(_format, _fieldNames.Select((field, i) => new String('-', _widths[i])).ToArray()); } } public override void WriteRecord(params object[] values) { if(_format != null) { foreach(var line in Wrap(values)) { _log.Info(line); } } else if(values.Length > 0) { foreach(var line in values) { _log.Info(line); } } else { _log.Info(""); } ++_records; } public override void End(bool suppress) { if(!suppress && _widths != null && _widths.Length > 0 && _records > 5) { _log.InfoFormat("{0} records output", _records); } } public override void InitProgress(string operation, int iterations, int total) { base.InitProgress(operation, iterations, total); _lastLog = DateTime.MinValue; } public override bool IterationComplete() { int lastPct = CompletionPct(); base.IterationComplete(); UpdateCompletion(lastPct); return _cancelled; } public override bool SetProgress(int progress) { int lastPct = CompletionPct(); base.SetProgress(progress); int pct = CompletionPct(); UpdateCompletion(lastPct); return _cancelled; } protected void UpdateCompletion(int lastPct) { int pct = CompletionPct(); // Log progress messages for (at most) each 10% of progress // Handle cases where progress appears to go backwards e.g. // due to several passes being made in an EA extract. // Log progress only if sufficient (but not too much) time // has passed, and sufficient progress has been made if((DateTime.Now.AddSeconds(-MAX_LOG_INTERVAL) > _lastLog) || (DateTime.Now.AddSeconds(-MIN_LOG_INTERVAL) > _lastLog && (pct < lastPct || (pct - lastPct) >= 10))) { _log.InfoFormat("{0} {1}% complete", Operation.Trim(), pct); _lastLog = DateTime.Now; } } } /// <summary> /// Sends output to the console /// </summary> public class ConsoleOutput : FixedWidthOutput { // Characters used to simulate a spinner private static readonly char[] _spinner = new char[] { '|', '/', '-', '\\' }; // Size of the progress bar private static int BAR_SIZE = 50; // Reference to CommandLine.UI, used to render our output private CommandLine.UI _cui; // Counter used to cause spinner to animate private int _spin; public CommandLine.UI CUI { get { return _cui; } } public ConsoleOutput(CommandLine.UI cui) { _cui = cui; IndentWidth = 7; MaxWidth = cui.ConsoleWidth; } public override void WriteLine(string format, params object[] values) { if(Operation != null && _spin > 0) { _cui.ClearLine(); } if(values.Length == 0) { _cui.WriteLine(format); } else { _cui.WriteLine(string.Format(format, values)); } if(Operation != null && _spin > 0) { RenderProgressBar(); } } public void Write(string text) { if(Operation != null && _spin > 0) { _cui.ClearLine(); } _cui.Write(text); if(Operation != null && _spin > 0) { RenderProgressBar(); } } public override void SetHeader(params object[] fields) { base.SetHeader(fields); _cui.WithColor(ConsoleColor.Cyan, () => { _cui.WriteLine(); if(fields.Length > 1) { _cui.WriteLine(string.Format(_format, _fieldNames)); _cui.WriteLine(string.Format(_format, _fieldNames.Select( (field, i) => new String('-', _widths[i])).ToArray())); } }); } public override void WriteRecord(params object[] values) { _cui.WithColor(ConsoleColor.Cyan, () => { if(_format != null) { foreach(var line in Wrap(values)) { _cui.WriteLine(line); } } else if(values.Length > 0) { foreach(var line in values) { _cui.WriteLine(IndentString + line.ToString()); } } else { _cui.WriteLine(""); } ++_records; }); } public override void End(bool suppress) { _cui.WithColor(ConsoleColor.Cyan, () => { _cui.WriteLine(); if(!suppress && _widths != null && _widths.Length > 0 && _records > 5) { _cui.WriteLine(IndentString + string.Format("{0} records output", _records)); _cui.WriteLine(); } }); } public override void InitProgress(string operation, int iterations, int total) { base.InitProgress(operation, iterations, total); _spin = 0; } public override bool SetProgress(int progress) { base.SetProgress(progress); RenderProgressBar(); return _cancelled; } public override bool IterationComplete() { base.IterationComplete(); RenderProgressBar(); return _cancelled; } public override void EndProgress() { base.EndProgress(); _cui.ClearLine(); } protected void RenderProgressBar() { if(!CommandLine.UI.IsRedirected) { // Determine which character to display next to simulate spinning char spin = _spinner[_spin++ % _spinner.Length]; // Make sure percentage is within range of 0 to 100 int pct = CompletionPct(); // Build up the progress bar var sb = new StringBuilder(Operation.Length + BAR_SIZE + 20); sb.Append(Operation); sb.Append(' '); sb.Append(spin); sb.Append(" ["); var barMid = sb.Length + (BAR_SIZE / 2); for(int i = 1; i <= BAR_SIZE; ++i) { if (i * 100 / BAR_SIZE <= pct) { sb.Append('='); } else { sb.Append(' '); } } sb.Append("] "); if(_cancelled) { sb.Append("Cancelling..."); } else { sb.Append("(Esc to cancel)"); } // Now place the percentage complete inside the bar var pctStr = pct.ToString() + "%"; if (pctStr.Length > 2) { barMid--; } sb.Remove(barMid, pctStr.Length); sb.Insert(barMid, pctStr); _cui.WithColor(ConsoleColor.Green, () => { _cui.ClearLine(); // We may only detect we are redirected at this point if(!CommandLine.UI.IsRedirected) { _cui.Write(sb.ToString()); } }); } } } /// <summary> /// A more intelligent ConsoleAppender, which takes account of the /// console width and wraps messages at word breaks. Also integrates /// better with progress monitoring. /// </summary> public class ConsoleAppender : AppenderSkeleton { ConsoleOutput _console; public ConsoleAppender(ConsoleOutput co) { _console = co; } protected override void Append(LoggingEvent logEvent) { var newColor = _console.CUI.ForegroundColor; switch(logEvent.Level.ToString().ToUpperInvariant()) { case "FATAL": case "ERROR": newColor = ConsoleColor.Red; break; case "WARN": newColor = ConsoleColor.Yellow; break; case "TRACE": case "DEBUG": newColor = ConsoleColor.DarkGray; break; default: break; } _console.CUI.WithColor(newColor, () => _console.Write(RenderLoggingEvent(logEvent))); } } }
// Artificial Intelligence for Humans // Volume 2: Nature-Inspired Algorithms // C# Version // http://www.aifh.org // http://www.jeffheaton.com // // Code repository: // https://github.com/jeffheaton/aifh // // Copyright 2014 by Jeff Heaton // // 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 more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using AIFH_Vol2.Core; using AIFH_Vol2.Core.Distance; using AIFH_Vol2_Capstone_Plants.Milestone1; namespace AIFH_Vol2_Capstone_Plants.Milestone2 { /// <summary> /// This class provides a growth cycle for the plant genome. This class runs the "program" embedded in the plant's /// genome. A plant genome is an array of four vectors. Each vector is of length 4, so the entire genome is /// 4*4 = 16 double values. /// Each of the four vectors corresponds to a cell's info vector. A cell info vector provides information about the /// state of a cell. By cell, I mean a grid cell. The grid cell can be either living (filled) or dead (empty). /// The info vector for a cell is calculated as follows. /// Element 0: The height of the cell. 1.0 for the last row and 0.0 for the first row. /// Element 1: The amount of sunlight (for surface cells) or water (for underground cells) exposure for this cell. /// Element 2: Crowding by neighbors. /// Element 3: Nourishment for this cell. /// The genome's vectors are as follows: /// Vector 0: Stem desired /// Vector 1: Leaf desired /// Vector 2: Growth Option #1 /// Vector 3: Growth Option #2 /// Vectors 0 and 1 go together. For each living cell we see if its info vector is closer to vector 0 or vector 1. /// If it is closer to stem (0), then the leafyness attribute of the cell is decreased. Leaf's can only move towards /// stem. A stem cannot change back into a leaf. /// Vectors 2 and 3 also go together. When a plant cell is eligible for growth, it evaluates all neighbor cells to /// see which it wants to grow into. What ever neighbor cell is closest to ether vector 2 or 3 is chosen. If /// the candidate cell is not lower than a specific threshold to either, then no growth occurs. /// A ratio between how leafy the surface is, and roots must also be maintained for growth to occur. /// </summary> public class PlantGrowth { /// <summary> /// Transformations to move from a cell to the 9 neighboring cells. /// These are the column values. /// </summary> private readonly int[] _colTransform = {0, 0, -1, 1, -1, 1, 1, -1}; /// <summary> /// Euclidean distance is used to calculate distances to the genome vectors. /// </summary> private readonly EuclideanDistance _dist = new EuclideanDistance(); /// <summary> /// Used to hold the new cells that have grown. /// </summary> private readonly bool[][] _newComposition; /// <summary> /// Transformations to move from a cell to the 9 neighboring cells. /// These are the row values. /// </summary> private readonly int[] _rowTransform = {-1, 1, 0, 0, -1, 1, -1, 1}; /// <summary> /// Constructor. /// </summary> public PlantGrowth() { _newComposition = new bool[PlantUniverse.UniverseHeight][]; for (int i = 0; i < _newComposition.Length; i++) { _newComposition[i] = new bool[PlantUniverse.UniverseWidth]; } } /// <summary> /// Calculate the growth potential for a candidate cell. Evaluates the distance between the candidate cell's info /// vector and the two growth vectors in the genome. The minimum of these two vectors will be returned if /// it is below a specified minimum threshold. /// </summary> /// <param name="universe">The universe to evaluate.</param> /// <param name="row">The row to evaluate.</param> /// <param name="col">The column to evaluate.</param> /// <param name="genome">The genome.</param> /// <returns>The minimum distance.</returns> private double GetGrowthPotential(PlantUniverse universe, int row, int col, double[] genome) { double[] cellVec = universe.GetCellInfoVector(row, col); double d1 = _dist.Calculate(cellVec, 0, genome, PlantUniverse.CellVectorLength*2, PlantUniverse.CellVectorLength); double d2 = _dist.Calculate(cellVec, 0, genome, PlantUniverse.CellVectorLength*3, PlantUniverse.CellVectorLength); double result = Math.Min(d1, d2); if (result > PlantUniverse.MinGrowthDist) { result = -1; } return result; } /// <summary> /// Evaluate neighbors to see where to grow into. /// </summary> /// <param name="universe">The universe.</param> /// <param name="row">The row.</param> /// <param name="col">The column.</param> /// <param name="genome">The genome.</param> /// <param name="allowRoot">Are roots allowed?</param> /// <param name="allowSurface">Is surface growth allowed.</param> private void EvaluateNeighbors(PlantUniverse universe, int row, int col, double[] genome, bool allowRoot, bool allowSurface) { int growthTargetRow = row; int growthTargetCol = col; double growthTargetScore = double.PositiveInfinity; for (int i = 0; i < _colTransform.Length; i++) { int evalCol = col + _colTransform[i]; int evalRow = row + _rowTransform[i]; if (!allowRoot && evalRow >= PlantUniverse.GroundLine) { continue; } if (!allowSurface && evalRow < PlantUniverse.GroundLine) { continue; } if (universe.IsValid(evalRow, evalCol)) { double p = GetGrowthPotential(universe, evalRow, evalCol, genome); if (p > 0) { if (p < growthTargetScore) { growthTargetScore = p; growthTargetRow = evalRow; growthTargetCol = evalCol; } } } } // Grow new cell, if requested, did we ever set target row & col to anything? if (growthTargetRow != row || growthTargetCol != col) { _newComposition[growthTargetRow][growthTargetCol] = true; } } /// <summary> /// Run a growth cycle for the universe. /// </summary> /// <param name="universe">The universe.</param> /// <param name="genome">The genome.</param> public void RunGrowth(PlantUniverse universe, double[] genome) { // Does this plant have enough roots to grow? if (universe.SurfaceCount < AIFH.DefaultPrecision) { return; } // The amount of leafy material per root nourishment. A higher number indicates // more root nourishment than leafs. double rootRatio = universe.RootCount/universe.SurfaceCount; bool allowRoot = rootRatio < 0.5; //rootRatio < 0.1; bool allowSurface = rootRatio > 0.5; // Reset the new composition to be the composition of the current universe for (int row = 0; row < PlantUniverse.UniverseHeight; row++) { for (int col = 0; col < PlantUniverse.UniverseWidth; col++) { _newComposition[row][col] = false; } } for (int row = 0; row < PlantUniverse.UniverseHeight; row++) { for (int col = 0; col < PlantUniverse.UniverseWidth; col++) { PlantUniverseCell cell = universe.GetCell(row, col); // see if we want to change the composition if (row < PlantUniverse.GroundLine) { double[] cellVec = universe.GetCellInfoVector(row, col); double d1 = _dist.Calculate(cellVec, 0, genome, 0, PlantUniverse.CellVectorLength); double d2 = _dist.Calculate(cellVec, 0, genome, PlantUniverse.CellVectorLength, PlantUniverse.CellVectorLength); if (d1 < d2) { cell.Leafyness = (cell.Leafyness*PlantUniverse.StemTransition); } } // Evaluate growth into each neighbor cell if (universe.CanGrow(row, col)) { EvaluateNeighbors(universe, row, col, genome, allowRoot, allowSurface); } } } // Copy the new composition back to the universe for (int row = 0; row < PlantUniverse.UniverseHeight; row++) { for (int col = 0; col < PlantUniverse.UniverseWidth; col++) { PlantUniverseCell cell = universe.GetCell(row, col); if (_newComposition[row][col]) { cell.Leafyness = row >= PlantUniverse.GroundLine ? 0 : 1.0; cell.Energy = 1.0; cell.Nourishment = 1.0; } } } } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace MurphyPA.H2D.TestApp { /// <summary> /// Summary description for ProcessComponentFrameExecutionView. /// </summary> public class ProcessComponentFrameExecutionView : System.Windows.Forms.UserControl { private System.Windows.Forms.ComboBox hsmListInput; private System.Windows.Forms.Button injectButton; private System.Windows.Forms.ComboBox eventInput; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox commandInput; private System.Windows.Forms.Button commandExecuteButton; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public ProcessComponentFrameExecutionView() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); InitEditors (); } /// <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.hsmListInput = new System.Windows.Forms.ComboBox(); this.injectButton = new System.Windows.Forms.Button(); this.eventInput = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.commandInput = new System.Windows.Forms.ComboBox(); this.commandExecuteButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // hsmListInput // this.hsmListInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.hsmListInput.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.hsmListInput.Location = new System.Drawing.Point(16, 48); this.hsmListInput.Name = "hsmListInput"; this.hsmListInput.Size = new System.Drawing.Size(416, 21); this.hsmListInput.TabIndex = 0; this.hsmListInput.SelectedIndexChanged += new System.EventHandler(this.hsmListInput_SelectedIndexChanged); // // injectButton // this.injectButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.injectButton.Location = new System.Drawing.Point(360, 120); this.injectButton.Name = "injectButton"; this.injectButton.TabIndex = 2; this.injectButton.Text = "&Inject"; this.injectButton.Click += new System.EventHandler(this.injectButton_Click); // // eventInput // this.eventInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.eventInput.Location = new System.Drawing.Point(16, 120); this.eventInput.Name = "eventInput"; this.eventInput.Size = new System.Drawing.Size(328, 21); this.eventInput.TabIndex = 1; // // label1 // this.label1.Location = new System.Drawing.Point(16, 8); this.label1.Name = "label1"; this.label1.TabIndex = 3; this.label1.Text = "State Model"; // // label2 // this.label2.Location = new System.Drawing.Point(24, 88); this.label2.Name = "label2"; this.label2.TabIndex = 4; this.label2.Text = "Input Events"; // // label3 // this.label3.Location = new System.Drawing.Point(24, 160); this.label3.Name = "label3"; this.label3.TabIndex = 5; this.label3.Text = "Input Commands"; // // commandInput // this.commandInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.commandInput.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.commandInput.Location = new System.Drawing.Point(24, 192); this.commandInput.Name = "commandInput"; this.commandInput.Size = new System.Drawing.Size(320, 21); this.commandInput.TabIndex = 6; // // commandExecuteButton // this.commandExecuteButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.commandExecuteButton.Location = new System.Drawing.Point(360, 192); this.commandExecuteButton.Name = "commandExecuteButton"; this.commandExecuteButton.Size = new System.Drawing.Size(72, 23); this.commandExecuteButton.TabIndex = 7; this.commandExecuteButton.Text = "Exec&ute"; this.commandExecuteButton.Click += new System.EventHandler(this.commandExecuteButton_Click); // // ProcessComponentFrameExecutionView // this.Controls.Add(this.commandExecuteButton); this.Controls.Add(this.commandInput); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.eventInput); this.Controls.Add(this.injectButton); this.Controls.Add(this.hsmListInput); this.Name = "ProcessComponentFrameExecutionView"; this.Size = new System.Drawing.Size(448, 256); this.ResumeLayout(false); } #endregion ProcessComponentFrame _ComponentFrame; public void Init (ProcessComponentFrame componentFrame) { _ComponentFrame = componentFrame; ArrayList list = new ArrayList (); foreach (DictionaryEntry de in _ComponentFrame.ComponentContexts) { list.Add (de.Key.ToString ()); } hsmListInput.DataSource = list; } qf4net.ILQHsm SelectedHSM { get { qf4net.ILQHsm hsm = null; string hsmName = hsmListInput.SelectedItem as string; if (_ComponentFrame.ComponentContexts.Contains (hsmName)) { ProcessComponentFrame.ComponentContext ctx = _ComponentFrame.ComponentContexts [hsmName] as ProcessComponentFrame.ComponentContext; hsm = ctx.Hsm; } return hsm; } } protected Hashtable _Editors = new Hashtable (); protected string _editorsFileName = "editors.txt"; string GetEditorsFileName () { System.Reflection.Assembly entryAssembly = System.Reflection.Assembly.GetEntryAssembly (); string dirLine = entryAssembly.Location; string directory = System.IO.Path.GetDirectoryName (dirLine); string fileName = System.IO.Path.Combine (directory, _editorsFileName); return fileName; } protected void InitEditors () { _Editors.Add (typeof (string), new EditorAttribute (typeof (SimpleStringEditor), typeof (qf4net.IQEventEditor))); string editorsFileName = GetEditorsFileName (); if (System.IO.File.Exists (editorsFileName)) { using (System.IO.StreamReader sr = new System.IO.StreamReader (editorsFileName)) { while (sr.Peek () != -1) { string line = sr.ReadLine ().Trim (); string[] strList = line.Split (new char[] {';'}, 2); if (strList.Length != 2) { throw new ArgumentException ("[" + line + "] does not contain a typename;editorname pair"); } string typeName = strList [0].Trim (); string editorName = strList [1].Trim (); Type type = Type.GetType (typeName); Type editorType = Type.GetType (editorName); EditorAttribute attr = new EditorAttribute (editorType, typeof (qf4net.IQEventEditor)); _Editors [type] = attr; } } } } protected EditorAttribute GetEditorType (qf4net.TransitionEventAttribute te) { if (_Editors.Contains (te.DataType)) { return _Editors [te.DataType] as EditorAttribute; } foreach (EditorAttribute editor in te.DataType.GetCustomAttributes (typeof (EditorAttribute), false)) { return editor; } throw new NotSupportedException (te.ToString () + " TransitionEventAttribute does not have a supported Editor"); } protected qf4net.IQEventEditor GetEditor (qf4net.TransitionEventAttribute te) { EditorAttribute editor = GetEditorType (te); Type editorType = Type.GetType (editor.EditorTypeName); object editorObj = Activator.CreateInstance (editorType); qf4net.IQEventEditor eventEditor = editorObj as qf4net.IQEventEditor; if (eventEditor == null) { throw new ArgumentException (editor.EditorTypeName + " is not a valid IQEventEditor Type"); } return eventEditor; } private void injectButton_Click(object sender, System.EventArgs e) { qf4net.ILQHsm hsm = SelectedHSM; if (hsm == null) { throw new ArgumentException ("No hsm selected"); } if (eventInput.Text.Trim () != "") { string inject = eventInput.Text; inject = inject.Trim (); // if inject matches a TransitionEventAttribute then find its editor an edit! foreach (qf4net.TransitionEventAttribute te in hsm.TransitionEvents) { if (te.HasDataType) { if (te.ToString () == inject) { qf4net.IQEventEditor eventEditor = GetEditor (te); Form frm = new OkCancelForm (); frm.Text = "Event " + te.EventName; qf4net.QEventDefaultEditContext ctx = new qf4net.QEventDefaultEditContext (frm); if (eventEditor.Edit (ctx) == false) { return; } hsm.AsyncDispatch (new qf4net.QEvent (te.EventName, ctx.Instance)); if (eventEditor.SupportsParse) { inject = te + "|" + ctx.Instance; if (!eventInput.Items.Contains (inject)) { eventInput.Items.Add (inject); } } return; } } } // if inject matches a TransitionEventAttribute + extra data then parse the extra data! foreach (qf4net.TransitionEventAttribute te in hsm.TransitionEvents) { if (te.HasDataType) { if (inject.StartsWith (te.ToString () + "|")) { qf4net.IQEventEditor eventEditor = GetEditor (te); if (!eventEditor.SupportsParse) { throw new NotSupportedException (te.ToString () + " editor does not support string parsing"); } string[] strlist = inject.Split (new char[] {'|'}, 2); string eventName = strlist[0].Trim (); System.Diagnostics.Debug.Assert (eventName != "" && eventName == te.ToString ()); string data = null; if (strlist.Length > 1) { data = strlist [1].Trim (); } if (data == null) { throw new ArgumentException ("[" + inject + "] does not contain a Parsable event data string"); } object instance = eventEditor.Parse (data); hsm.AsyncDispatch (new qf4net.QEvent (te.EventName, instance)); return; } } } hsm.AsyncDispatch (new qf4net.QEvent (inject)); } } private void hsmListInput_SelectedIndexChanged_update_EventInput(object sender, System.EventArgs e) { qf4net.ILQHsm hsm = SelectedHSM; eventInput.Text = ""; eventInput.Items.Clear (); if (hsm == null) { return; } qf4net.TransitionEventAttribute[] transitionEventAttributes = hsm.TransitionEvents; foreach (qf4net.TransitionEventAttribute te in transitionEventAttributes) { eventInput.Items.Add (te); } } private void hsmListInput_SelectedIndexChanged_update_CommandInput(object sender, System.EventArgs e) { qf4net.ILQHsm hsm = SelectedHSM; commandInput.Text = ""; commandInput.Items.Clear (); if (hsm == null) { return; } #warning Add command filling code... } private void hsmListInput_SelectedIndexChanged(object sender, System.EventArgs e) { hsmListInput_SelectedIndexChanged_update_EventInput (sender, e); hsmListInput_SelectedIndexChanged_update_CommandInput (sender, e); } private void commandExecuteButton_Click(object sender, System.EventArgs e) { ; } } }
/* * MdiClient.cs - Implementation of the * "System.Windows.Forms.MdiClient" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Windows.Forms { using System.Collections; using System.Drawing; using System.Drawing.Toolkit; using System.ComponentModel; #if CONFIG_COMPONENT_MODEL [ToolboxItem(false)] [DesignTimeVisible(false)] #endif public sealed class MdiClient : Control { // Internal state. private ArrayList controls; private Form activeChild; // Constructor. public MdiClient() { BackColor = SystemColors.AppWorkspace; Dock = DockStyle.Fill; SetStyle(ControlStyles.Selectable, false); controls = new ArrayList(); } // Get the active MDI child. internal Form ActiveChild { get { return activeChild; } } // Get or set the background image. public override Image BackgroundImage { get { return base.BackgroundImage; } set { base.BackgroundImage = value; } } // Get the window creation parameters. protected override CreateParams CreateParams { get { return base.CreateParams; } } // Get the children that are being managed by this MDI client. public Form[] MdiChildren { get { Form[] children = new Form [controls.Count]; controls.CopyTo(children, 0); return children; } } // Create the toolkit window underlying this control. internal override IToolkitWindow CreateToolkitWindow(IToolkitWindow parent) { CreateParams cp = CreateParams; int x = cp.X + ToolkitDrawOrigin.X; int y = cp.Y + ToolkitDrawOrigin.Y; int width = cp.Width - ToolkitDrawSize.Width; int height = cp.Height - ToolkitDrawSize.Height; if(parent != null) { // Use the parent's toolkit to create. if(Parent is Form) { // use ControlToolkitManager to create the window thread safe return ControlToolkitManager.CreateMdiClient( this, parent, x, y, width, height); } else { // use ControlToolkitManager to create the window thread safe return ControlToolkitManager.CreateMdiClient( this, parent, x + Parent.ClientOrigin.X, y + Parent.ClientOrigin.Y, width, height); } } else { // Use the default toolkit to create. // use ControlToolkitManager to create the window thread safe return ControlToolkitManager.CreateMdiClient (this, null, x, y, width, height); } } // Create a new control collection for this instance. protected override Control.ControlCollection CreateControlsInstance() { return new ControlCollection(this); } // Lay out the children in this MDI client. public void LayoutMdi(MdiLayout value) { IToolkitMdiClient mdi = (toolkitWindow as IToolkitMdiClient); if(mdi != null) { switch(value) { case MdiLayout.Cascade: { mdi.Cascade(); } break; case MdiLayout.TileHorizontal: { mdi.TileHorizontally(); } break; case MdiLayout.TileVertical: { mdi.TileVertically(); } break; case MdiLayout.ArrangeIcons: { mdi.ArrangeIcons(); } break; } } } // Handle a resize event. protected override void OnResize(EventArgs e) { base.OnResize(e); } // Inner core of "Scale". protected override void ScaleCore(float dx, float dy) { base.ScaleCore(dx, dy); } // Inner core of "SetBounds". protected override void SetBoundsCore (int x, int y, int width, int height, BoundsSpecified specified) { base.SetBoundsCore(x, y, width, height, specified); } // Receive notification that a particular child was activated. internal override void MdiActivate(IToolkitWindow child) { Activate(child); } internal void Activate(IToolkitWindow child) { if(child == null) { activeChild = null; } else { activeChild = null; foreach(Form form in controls) { if(form.toolkitWindow == child) { activeChild = form; break; } } } } #if !CONFIG_COMPACT_FORMS // Process a message. protected override void WndProc(ref Message m) { base.WndProc(ref m); } #endif // !CONFIG_COMPACT_FORMS // Special purpose control collection for MDI clients. public new class ControlCollection : Control.ControlCollection { // Internal state. private MdiClient mdiClient; // Constructor. public ControlCollection(MdiClient owner) : base(owner) { this.mdiClient = owner; } // Add a control to this collection. public override void Add(Control value) { if(!(value is Form) || !(((Form)value).IsMdiChild)) { throw new ArgumentException (S._("SWF_NotMdiChild")); } mdiClient.controls.Add(value); // TODO: figure out how to add Forms without reparenting //base.Add(value); } // Remove a control from this collection. public override void Remove(Control value) { mdiClient.controls.Remove(value); // TODO: figure out how to add Forms without reparenting //base.Remove(value); } }; // class ControlCollection }; // class MdiClient }; // namespace System.Windows.Forms
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// JobTime /// </summary> [DataContract] public partial class JobTime : IEquatable<JobTime> { /// <summary> /// Initializes a new instance of the <see cref="JobTime" /> class. /// </summary> [JsonConstructorAttribute] protected JobTime() { } /// <summary> /// Initializes a new instance of the <see cref="JobTime" /> class. /// </summary> /// <param name="SecondDuration">SecondDuration (required).</param> /// <param name="UserId">UserId (required).</param> /// <param name="LobId">LobId (required).</param> /// <param name="JobTypeId">JobTypeId (required).</param> /// <param name="Note">Note.</param> public JobTime(int? SecondDuration = null, int? UserId = null, int? LobId = null, int? JobTypeId = null, string Note = null) { // to ensure "SecondDuration" is required (not null) if (SecondDuration == null) { throw new InvalidDataException("SecondDuration is a required property for JobTime and cannot be null"); } else { this.SecondDuration = SecondDuration; } // to ensure "UserId" is required (not null) if (UserId == null) { throw new InvalidDataException("UserId is a required property for JobTime and cannot be null"); } else { this.UserId = UserId; } // to ensure "LobId" is required (not null) if (LobId == null) { throw new InvalidDataException("LobId is a required property for JobTime and cannot be null"); } else { this.LobId = LobId; } // to ensure "JobTypeId" is required (not null) if (JobTypeId == null) { throw new InvalidDataException("JobTypeId is a required property for JobTime and cannot be null"); } else { this.JobTypeId = JobTypeId; } this.Note = Note; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Gets or Sets SecondDuration /// </summary> [DataMember(Name="secondDuration", EmitDefaultValue=false)] public int? SecondDuration { get; set; } /// <summary> /// Gets or Sets Date /// </summary> [DataMember(Name="date", EmitDefaultValue=false)] public DateTime? Date { get; private set; } /// <summary> /// Gets or Sets UserId /// </summary> [DataMember(Name="userId", EmitDefaultValue=false)] public int? UserId { get; set; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; set; } /// <summary> /// Gets or Sets JobTypeId /// </summary> [DataMember(Name="jobTypeId", EmitDefaultValue=false)] public int? JobTypeId { get; set; } /// <summary> /// Gets or Sets Note /// </summary> [DataMember(Name="note", EmitDefaultValue=false)] public string Note { 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 JobTime {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" SecondDuration: ").Append(SecondDuration).Append("\n"); sb.Append(" Date: ").Append(Date).Append("\n"); sb.Append(" UserId: ").Append(UserId).Append("\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" JobTypeId: ").Append(JobTypeId).Append("\n"); sb.Append(" Note: ").Append(Note).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 JobTime); } /// <summary> /// Returns true if JobTime instances are equal /// </summary> /// <param name="other">Instance of JobTime to be compared</param> /// <returns>Boolean</returns> public bool Equals(JobTime 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.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.SecondDuration == other.SecondDuration || this.SecondDuration != null && this.SecondDuration.Equals(other.SecondDuration) ) && ( this.Date == other.Date || this.Date != null && this.Date.Equals(other.Date) ) && ( this.UserId == other.UserId || this.UserId != null && this.UserId.Equals(other.UserId) ) && ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.JobTypeId == other.JobTypeId || this.JobTypeId != null && this.JobTypeId.Equals(other.JobTypeId) ) && ( this.Note == other.Note || this.Note != null && this.Note.Equals(other.Note) ); } /// <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.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.SecondDuration != null) hash = hash * 59 + this.SecondDuration.GetHashCode(); if (this.Date != null) hash = hash * 59 + this.Date.GetHashCode(); if (this.UserId != null) hash = hash * 59 + this.UserId.GetHashCode(); if (this.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.JobTypeId != null) hash = hash * 59 + this.JobTypeId.GetHashCode(); if (this.Note != null) hash = hash * 59 + this.Note.GetHashCode(); return hash; } } } }
// 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: Abstract base class for all Text-only Readers. ** Subclasses will include StreamReader & StringReader. ** ** ===========================================================*/ using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.IO { // This abstract base class represents a reader that can read a sequential // stream of characters. This is not intended for reading bytes - // there are methods on the Stream class to read bytes. // A subclass must minimally implement the Peek() and Read() methods. // // This class is intended for character input, not bytes. // There are methods on the Stream class for reading bytes. [Serializable] internal abstract class TextReader : MarshalByRefObject, IDisposable { public static readonly TextReader Null = new NullTextReader(); protected TextReader() {} // Closes this TextReader and releases any system resources associated with the // TextReader. Following a call to Close, any operations on the TextReader // may raise exceptions. // // This default method is empty, but descendant classes can override the // method to provide the appropriate functionality. public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } // Returns the next available character without actually reading it from // the input stream. The current position of the TextReader is not changed by // this operation. The returned value is -1 if no further characters are // available. // // This default method simply returns -1. // [Pure] public virtual int Peek() { Contract.Ensures(Contract.Result<int>() >= -1); return -1; } // Reads the next character from the input stream. The returned value is // -1 if no further characters are available. // // This default method simply returns -1. // public virtual int Read() { Contract.Ensures(Contract.Result<int>() >= -1); return -1; } // Reads a block of characters. This method will read up to // count characters from this TextReader into the // buffer character array starting at position // index. Returns the actual number of characters read. // public virtual int Read([In, Out] char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(count)); Contract.EndContractBlock(); int n = 0; do { int ch = Read(); if (ch == -1) break; buffer[index + n++] = (char)ch; } while (n < count); return n; } // Reads all characters from the current position to the end of the // TextReader, and returns them as one string. public virtual String ReadToEnd() { Contract.Ensures(Contract.Result<String>() != null); char[] chars = new char[4096]; int len; StringBuilder sb = new StringBuilder(4096); while((len=Read(chars, 0, chars.Length)) != 0) { sb.Append(chars, 0, len); } return sb.ToString(); } // Blocking version of read. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock([In, Out] char[] buffer, int index, int count) { Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= count); int i, n = 0; do { n += (i = Read(buffer, index + n, count - n)); } while (i > 0 && n < count); return n; } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // public virtual String ReadLine() { StringBuilder sb = new StringBuilder(); while (true) { int ch = Read(); if (ch == -1) break; if (ch == '\r' || ch == '\n') { if (ch == '\r' && Peek() == '\n') Read(); return sb.ToString(); } sb.Append((char)ch); } if (sb.Length > 0) return sb.ToString(); return null; } #region Task based Async APIs public virtual Task<String> ReadLineAsync() { return Task<String>.Factory.StartNew(state => { return ((TextReader)state).ReadLine(); }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public async virtual Task<String> ReadToEndAsync() { char[] chars = new char[4096]; int len; StringBuilder sb = new StringBuilder(4096); while((len = await ReadAsyncInternal(chars, 0, chars.Length).ConfigureAwait(false)) != 0) { sb.Append(chars, 0, len); } return sb.ToString(); } public virtual Task<int> ReadAsync(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); return ReadAsyncInternal(buffer, index, count); } internal virtual Task<int> ReadAsyncInternal(char[] buffer, int index, int count) { Contract.Requires(buffer != null); Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(buffer.Length - index >= count); var tuple = new Tuple<TextReader, char[], int, int>(this, buffer, index, count); return Task<int>.Factory.StartNew(state => { var t = (Tuple<TextReader, char[], int, int>)state; return t.Item1.Read(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); return ReadBlockAsyncInternal(buffer, index, count); } private async Task<int> ReadBlockAsyncInternal(char[] buffer, int index, int count) { Contract.Requires(buffer != null); Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(buffer.Length - index >= count); int i, n = 0; do { i = await ReadAsyncInternal(buffer, index + n, count - n).ConfigureAwait(false); n += i; } while (i > 0 && n < count); return n; } #endregion public static TextReader Synchronized(TextReader reader) { if (reader==null) throw new ArgumentNullException(nameof(reader)); Contract.Ensures(Contract.Result<TextReader>() != null); Contract.EndContractBlock(); if (reader is SyncTextReader) return reader; return new SyncTextReader(reader); } [Serializable] private sealed class NullTextReader : TextReader { public NullTextReader(){} [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int Read(char[] buffer, int index, int count) { return 0; } public override String ReadLine() { return null; } } [Serializable] internal sealed class SyncTextReader : TextReader { internal TextReader _in; internal SyncTextReader(TextReader t) { _in = t; } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Close() { // So that any overriden Close() gets run _in.Close(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] protected override void Dispose(bool disposing) { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_in).Dispose(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override int Peek() { return _in.Peek(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override int Read() { return _in.Read(); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. [MethodImplAttribute(MethodImplOptions.Synchronized)] public override int Read([In, Out] char[] buffer, int index, int count) { return _in.Read(buffer, index, count); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override int ReadBlock([In, Out] char[] buffer, int index, int count) { return _in.ReadBlock(buffer, index, count); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override String ReadLine() { return _in.ReadLine(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override String ReadToEnd() { return _in.ReadToEnd(); } // // On SyncTextReader all APIs should run synchronously, even the async ones. // [MethodImplAttribute(MethodImplOptions.Synchronized)] public override Task<String> ReadLineAsync() { return Task.FromResult(ReadLine()); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override Task<String> ReadToEndAsync() { return Task.FromResult(ReadToEnd()); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override Task<int> ReadBlockAsync(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); return Task.FromResult(ReadBlock(buffer, index, count)); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override Task<int> ReadAsync(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); return Task.FromResult(Read(buffer, index, count)); } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ds-2015-04-16.normal.json service model. */ using System; using Amazon.Runtime; namespace Amazon.DirectoryService { /// <summary> /// Constants used for properties of type DirectorySize. /// </summary> public class DirectorySize : ConstantClass { /// <summary> /// Constant Large for DirectorySize /// </summary> public static readonly DirectorySize Large = new DirectorySize("Large"); /// <summary> /// Constant Small for DirectorySize /// </summary> public static readonly DirectorySize Small = new DirectorySize("Small"); /// <summary> /// Default Constructor /// </summary> public DirectorySize(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static DirectorySize FindValue(string value) { return FindValue<DirectorySize>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator DirectorySize(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type DirectoryStage. /// </summary> public class DirectoryStage : ConstantClass { /// <summary> /// Constant Active for DirectoryStage /// </summary> public static readonly DirectoryStage Active = new DirectoryStage("Active"); /// <summary> /// Constant Created for DirectoryStage /// </summary> public static readonly DirectoryStage Created = new DirectoryStage("Created"); /// <summary> /// Constant Creating for DirectoryStage /// </summary> public static readonly DirectoryStage Creating = new DirectoryStage("Creating"); /// <summary> /// Constant Deleted for DirectoryStage /// </summary> public static readonly DirectoryStage Deleted = new DirectoryStage("Deleted"); /// <summary> /// Constant Deleting for DirectoryStage /// </summary> public static readonly DirectoryStage Deleting = new DirectoryStage("Deleting"); /// <summary> /// Constant Failed for DirectoryStage /// </summary> public static readonly DirectoryStage Failed = new DirectoryStage("Failed"); /// <summary> /// Constant Impaired for DirectoryStage /// </summary> public static readonly DirectoryStage Impaired = new DirectoryStage("Impaired"); /// <summary> /// Constant Inoperable for DirectoryStage /// </summary> public static readonly DirectoryStage Inoperable = new DirectoryStage("Inoperable"); /// <summary> /// Constant Requested for DirectoryStage /// </summary> public static readonly DirectoryStage Requested = new DirectoryStage("Requested"); /// <summary> /// Constant RestoreFailed for DirectoryStage /// </summary> public static readonly DirectoryStage RestoreFailed = new DirectoryStage("RestoreFailed"); /// <summary> /// Constant Restoring for DirectoryStage /// </summary> public static readonly DirectoryStage Restoring = new DirectoryStage("Restoring"); /// <summary> /// Default Constructor /// </summary> public DirectoryStage(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static DirectoryStage FindValue(string value) { return FindValue<DirectoryStage>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator DirectoryStage(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type DirectoryType. /// </summary> public class DirectoryType : ConstantClass { /// <summary> /// Constant ADConnector for DirectoryType /// </summary> public static readonly DirectoryType ADConnector = new DirectoryType("ADConnector"); /// <summary> /// Constant SimpleAD for DirectoryType /// </summary> public static readonly DirectoryType SimpleAD = new DirectoryType("SimpleAD"); /// <summary> /// Default Constructor /// </summary> public DirectoryType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static DirectoryType FindValue(string value) { return FindValue<DirectoryType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator DirectoryType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type RadiusAuthenticationProtocol. /// </summary> public class RadiusAuthenticationProtocol : ConstantClass { /// <summary> /// Constant CHAP for RadiusAuthenticationProtocol /// </summary> public static readonly RadiusAuthenticationProtocol CHAP = new RadiusAuthenticationProtocol("CHAP"); /// <summary> /// Constant MSCHAPv1 for RadiusAuthenticationProtocol /// </summary> public static readonly RadiusAuthenticationProtocol MSCHAPv1 = new RadiusAuthenticationProtocol("MS-CHAPv1"); /// <summary> /// Constant MSCHAPv2 for RadiusAuthenticationProtocol /// </summary> public static readonly RadiusAuthenticationProtocol MSCHAPv2 = new RadiusAuthenticationProtocol("MS-CHAPv2"); /// <summary> /// Constant PAP for RadiusAuthenticationProtocol /// </summary> public static readonly RadiusAuthenticationProtocol PAP = new RadiusAuthenticationProtocol("PAP"); /// <summary> /// Default Constructor /// </summary> public RadiusAuthenticationProtocol(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static RadiusAuthenticationProtocol FindValue(string value) { return FindValue<RadiusAuthenticationProtocol>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator RadiusAuthenticationProtocol(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type RadiusStatus. /// </summary> public class RadiusStatus : ConstantClass { /// <summary> /// Constant Completed for RadiusStatus /// </summary> public static readonly RadiusStatus Completed = new RadiusStatus("Completed"); /// <summary> /// Constant Creating for RadiusStatus /// </summary> public static readonly RadiusStatus Creating = new RadiusStatus("Creating"); /// <summary> /// Constant Failed for RadiusStatus /// </summary> public static readonly RadiusStatus Failed = new RadiusStatus("Failed"); /// <summary> /// Default Constructor /// </summary> public RadiusStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static RadiusStatus FindValue(string value) { return FindValue<RadiusStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator RadiusStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type SnapshotStatus. /// </summary> public class SnapshotStatus : ConstantClass { /// <summary> /// Constant Completed for SnapshotStatus /// </summary> public static readonly SnapshotStatus Completed = new SnapshotStatus("Completed"); /// <summary> /// Constant Creating for SnapshotStatus /// </summary> public static readonly SnapshotStatus Creating = new SnapshotStatus("Creating"); /// <summary> /// Constant Failed for SnapshotStatus /// </summary> public static readonly SnapshotStatus Failed = new SnapshotStatus("Failed"); /// <summary> /// Default Constructor /// </summary> public SnapshotStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static SnapshotStatus FindValue(string value) { return FindValue<SnapshotStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator SnapshotStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type SnapshotType. /// </summary> public class SnapshotType : ConstantClass { /// <summary> /// Constant Auto for SnapshotType /// </summary> public static readonly SnapshotType Auto = new SnapshotType("Auto"); /// <summary> /// Constant Manual for SnapshotType /// </summary> public static readonly SnapshotType Manual = new SnapshotType("Manual"); /// <summary> /// Default Constructor /// </summary> public SnapshotType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static SnapshotType FindValue(string value) { return FindValue<SnapshotType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator SnapshotType(string value) { return FindValue(value); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using Xunit; namespace System.Collections.ArrayListTests { public class GetEnumeratorTests { #region "Test Data - Keep the data close to tests so it can vary independently from other tests" string[] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", "Huntress", "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", "Superman", "Thor", "Wildcat", "Wonder Woman", }; string[] strResult = { "Aquaman", "Atom", "Batman", "Superman", "Thor", "Wildcat", "Wonder Woman", }; #endregion [Fact] public void TestArrayListWrappers01() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; int ii = 0; int start = 3; int count = 15; bool bGetNext = false; object[] tempArray1; // // Construct array lists. // arrList = new ArrayList((ICollection)strHeroes); Assert.NotNull(arrList); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { (ArrayList)arrList.Clone(), (ArrayList)ArrayList.Adapter(arrList).Clone(), (ArrayList)ArrayList.FixedSize(arrList).Clone(), (ArrayList)arrList.GetRange(0, arrList.Count).Clone(), (ArrayList)ArrayList.ReadOnly(arrList).Clone(), (ArrayList)ArrayList.Synchronized(arrList).Clone()}; IEnumerator enu; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // Obtain the enumerator for the test range. enu = (IEnumerator)arrList.GetEnumerator(start, count); Assert.NotNull(enu); // Verify the enumerator. for (ii = start; ii < start + count; ++ii) { bGetNext = enu.MoveNext(); if (bGetNext == false) break; Assert.Equal(0, strHeroes[ii].CompareTo((string)enu.Current)); } ii -= start; Assert.Equal(count, ii); bGetNext = enu.MoveNext(); Assert.False(bGetNext); Assert.False(enu.MoveNext()); Assert.False(enu.MoveNext()); Assert.False(enu.MoveNext()); // Obtain and verify enumerator with 0 count"); // Obtain the enumerator for the test range. enu = (IEnumerator)arrList.GetEnumerator(start, 0); Assert.False(enu.MoveNext()); Assert.False(enu.MoveNext()); Assert.False(enu.MoveNext()); enu.Reset(); Assert.Throws<InvalidOperationException>(() => { object test = enu.Current; }); Assert.False(enu.MoveNext()); Assert.False(enu.MoveNext()); Assert.False(enu.MoveNext()); // // [] Make Sure both MoveNext and Reset throw InvalidOperationException if underlying collection has been modified but Current should not throw // if (!arrList.IsReadOnly) { object origValue = arrList[arrList.Count - 1]; // [] MoveNext and Reset throw if collection has been modified try { IEnumerator enu1 = (IEnumerator)arrList.GetEnumerator(start, count); enu1.MoveNext(); arrList[arrList.Count - 1] = "Underdog"; object myValue = enu1.Current; Assert.Throws<InvalidOperationException>(() => enu1.MoveNext()); Assert.Throws<InvalidOperationException>(() => enu1.Reset()); } finally { arrList[arrList.Count - 1] = origValue; } } // // [] Verify Current throws InvalidOperationException when positioned before the first element or after the last // enu = (IEnumerator)arrList.GetEnumerator(start, count); Assert.Throws<InvalidOperationException>(() => { object myValue = enu.Current; }); while (enu.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => { object myValue = enu.Current; }); // // [] Use invalid parameters. // Assert.Throws<ArgumentException>(() => { IEnumerator enu0 = (IEnumerator)arrList.GetEnumerator(0, 10000); }); Assert.Throws<ArgumentOutOfRangeException>(() => { IEnumerator enu1 = (IEnumerator)arrList.GetEnumerator(-1, arrList.Count); }); Assert.Throws<ArgumentOutOfRangeException>(() => { IEnumerator enu2 = (IEnumerator)arrList.GetEnumerator(0, -1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { IEnumerator enu3 = (IEnumerator)arrList.GetEnumerator(-1, arrList.Count); }); //[] Verify the eneumerator works correctly when the ArrayList itself is in the ArrayList if (!arrList.IsFixedSize) { arrList.Insert(0, arrList); arrList.Insert(arrList.Count, arrList); arrList.Insert(arrList.Count / 2, arrList); tempArray1 = new object[strHeroes.Length + 3]; tempArray1[0] = (object)arrList; tempArray1[tempArray1.Length / 2] = arrList; tempArray1[tempArray1.Length - 1] = arrList; Array.Copy(strHeroes, 0, tempArray1, 1, strHeroes.Length / 2); Array.Copy(strHeroes, strHeroes.Length / 2, tempArray1, (tempArray1.Length / 2) + 1, strHeroes.Length - (strHeroes.Length / 2)); //[] Enumerate the entire collection enu = arrList.GetEnumerator(0, tempArray1.Length); for (int loop = 0; loop < 2; ++loop) { for (int i = 0; i < tempArray1.Length; ++i) { enu.MoveNext(); Assert.StrictEqual(tempArray1[i], enu.Current); } Assert.False(enu.MoveNext()); enu.Reset(); } //[] Enumerate only part of the collection enu = arrList.GetEnumerator(1, tempArray1.Length - 2); for (int loop = 0; loop < 2; ++loop) { for (int i = 1; i < tempArray1.Length - 1; ++i) { enu.MoveNext(); Assert.StrictEqual(tempArray1[i], enu.Current); } Assert.False(enu.MoveNext()); enu.Reset(); } } } } [Fact] public void TestArrayListWrappers02() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; int ii = 0; bool bGetNext = false; object o1; IEnumerator ien1; // // Construct array lists. // arrList = new ArrayList((ICollection)strHeroes); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { (ArrayList)arrList.Clone(), (ArrayList)ArrayList.Adapter(arrList).Clone(), (ArrayList)arrList.GetRange(0, arrList.Count).Clone(), (ArrayList)ArrayList.Synchronized(arrList).Clone(), (ArrayList)(new MyArrayList((ICollection) strHeroes))}; IEnumerator enu = null; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // // [] Add the ArrayList itself to the ArrayList // try { arrList.Add(arrList); enu = arrList.GetEnumerator(); int index; index = 0; while (enu.MoveNext()) { Assert.StrictEqual(enu.Current, arrList[index]); ++index; } enu.Reset(); index = 0; while (enu.MoveNext()) { Assert.StrictEqual(enu.Current, arrList[index]); ++index; } } finally { arrList.RemoveAt(arrList.Count - 1); } // // [] Vanila - Obtain and verify enumerator. // // Obtain the enumerator for the test range. enu = arrList.GetEnumerator(); IEnumerator enuClone = arrList.GetEnumerator(); IEnumerator[] enuArray = { enu, enuClone }; //Verify both this instance and the cloned copy foreach (IEnumerator enumerator in enuArray) { enu = enumerator; for (int i = 0; i < 2; i++) { Assert.NotNull(enu); // Verify the enumerator. for (ii = 0; ; ii++) { bGetNext = enu.MoveNext(); if (bGetNext == false) break; Assert.Equal(0, strHeroes[ii].CompareTo((string)enu.Current)); } Assert.Equal(strHeroes.Length, ii); bGetNext = enu.MoveNext(); Assert.False(bGetNext); Assert.False(enu.MoveNext()); Assert.False(enu.MoveNext()); Assert.False(enu.MoveNext()); enu.Reset(); } } //[]we'll make sure that the enumerator throws if the underlying collection is changed with MoveNext() but not at Current arrList.Clear(); for (int i = 0; i < 100; i++) arrList.Add(i); ien1 = arrList.GetEnumerator(); ien1.MoveNext(); ien1.MoveNext(); arrList[10] = 1000; Assert.Equal(1, (int)ien1.Current); Assert.Throws<InvalidOperationException>(() => ien1.MoveNext()); Assert.Throws<InvalidOperationException>(() => ien1.Reset()); //[]we'll make sure that the enumerator throws before and after MoveNext returns false arrList.Clear(); for (int i = 0; i < 100; i++) arrList.Add(i); ien1 = arrList.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => { o1 = ien1.Current; }); while (ien1.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => { o1 = ien1.Current; }); } } } public class MyArrayList : ArrayList { public MyArrayList(ICollection c) : base(c) { } } }
#region File Description //----------------------------------------------------------------------------- // ScreenManager.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Diagnostics; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input.Touch; #endregion namespace MahjongXNA { /// <summary> /// The screen manager is a component which manages one or more GameScreen /// instances. It maintains a stack of screens, calls their Update and Draw /// methods at the appropriate times, and automatically routes input to the /// topmost active screen. /// </summary> public class ScreenManager : DrawableGameComponent { #region Fields List<GameScreen> screens = new List<GameScreen>(); List<GameScreen> screensToUpdate = new List<GameScreen>(); InputState input = new InputState(); SpriteBatch spriteBatch; SpriteFont font; Texture2D blankTexture; bool isInitialized; bool traceEnabled; #endregion #region Properties /// <summary> /// A default SpriteBatch shared by all the screens. This saves /// each screen having to bother creating their own local instance. /// </summary> public SpriteBatch SpriteBatch { get { return spriteBatch; } } /// <summary> /// A default font shared by all the screens. This saves /// each screen having to bother loading their own local copy. /// </summary> public SpriteFont Font { get { return font; } } /// <summary> /// If true, the manager prints out a list of all the screens /// each time it is updated. This can be useful for making sure /// everything is being added and removed at the right times. /// </summary> public bool TraceEnabled { get { return traceEnabled; } set { traceEnabled = value; } } #endregion #region Initialization /// <summary> /// Constructs a new screen manager component. /// </summary> public ScreenManager(Game game) : base(game) { // we must set EnabledGestures before we can query for them, but // we don't assume the game wants to read them. TouchPanel.EnabledGestures = GestureType.None; } /// <summary> /// Initializes the screen manager component. /// </summary> public override void Initialize() { base.Initialize(); isInitialized = true; } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { // Load content belonging to the screen manager. ContentManager content = Game.Content; spriteBatch = new SpriteBatch(GraphicsDevice); font = content.Load<SpriteFont>("menufont"); blankTexture = content.Load<Texture2D>("blank"); // Tell each of the screens to load their content. foreach (GameScreen screen in screens) { screen.LoadContent(); } } /// <summary> /// Unload your graphics content. /// </summary> protected override void UnloadContent() { // Tell each of the screens to unload their content. foreach (GameScreen screen in screens) { screen.UnloadContent(); } } #endregion #region Update and Draw /// <summary> /// Allows each screen to run logic. /// </summary> public override void Update(GameTime gameTime) { // Read the keyboard and gamepad. input.Update(); // Make a copy of the master screen list, to avoid confusion if // the process of updating one screen adds or removes others. screensToUpdate.Clear(); foreach (GameScreen screen in screens) screensToUpdate.Add(screen); bool otherScreenHasFocus = !Game.IsActive; bool coveredByOtherScreen = false; // Loop as long as there are screens waiting to be updated. while (screensToUpdate.Count > 0) { // Pop the topmost screen off the waiting list. GameScreen screen = screensToUpdate[screensToUpdate.Count - 1]; screensToUpdate.RemoveAt(screensToUpdate.Count - 1); // Update the screen. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); if (screen.ScreenState == ScreenState.TransitionOn || screen.ScreenState == ScreenState.Active) { // If this is the first active screen we came across, // give it a chance to handle input. if (!otherScreenHasFocus) { screen.HandleInput(input); otherScreenHasFocus = true; } // If this is an active non-popup, inform any subsequent // screens that they are covered by it. if (!screen.IsPopup) coveredByOtherScreen = true; } } // Print debug trace? if (traceEnabled) TraceScreens(); } /// <summary> /// Prints a list of all the screens, for debugging. /// </summary> void TraceScreens() { List<string> screenNames = new List<string>(); foreach (GameScreen screen in screens) screenNames.Add(screen.GetType().Name); Debug.WriteLine(string.Join(", ", screenNames.ToArray())); } /// <summary> /// Tells each screen to draw itself. /// </summary> public override void Draw(GameTime gameTime) { foreach (GameScreen screen in new List<GameScreen>(screens)) { if (screen.ScreenState == ScreenState.Hidden) continue; screen.Draw(gameTime); } } #endregion #region Public Methods /// <summary> /// Adds a new screen to the screen manager. /// </summary> public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer) { screen.ControllingPlayer = controllingPlayer; screen.ScreenManager = this; screen.IsExiting = false; // If we have a graphics device, tell the screen to load content. if (isInitialized) { screen.LoadContent(); } screens.Add(screen); // update the TouchPanel to respond to gestures this screen is interested in TouchPanel.EnabledGestures = screen.EnabledGestures; } /// <summary> /// Removes a screen from the screen manager. You should normally /// use GameScreen.ExitScreen instead of calling this directly, so /// the screen can gradually transition off rather than just being /// instantly removed. /// </summary> public void RemoveScreen(GameScreen screen) { // If we have a graphics device, tell the screen to unload content. if (isInitialized) { screen.UnloadContent(); } screens.Remove(screen); screensToUpdate.Remove(screen); // if there is a screen still in the manager, update TouchPanel // to respond to gestures that screen is interested in. if (screens.Count > 0) { //TouchPanel.EnabledGestures = screens[screens.Count - 1].EnabledGestures; } } /// <summary> /// Expose an array holding all the screens. We return a copy rather /// than the real master list, because screens should only ever be added /// or removed using the AddScreen and RemoveScreen methods. /// </summary> public GameScreen[] GetScreens() { return screens.ToArray(); } /// <summary> /// Helper draws a translucent black fullscreen sprite, used for fading /// screens in and out, and for darkening the background behind popups. /// </summary> public void FadeBackBufferToBlack(float alpha) { Viewport viewport = GraphicsDevice.Viewport; spriteBatch.Begin(); spriteBatch.Draw(blankTexture, new Rectangle(0, 0, viewport.Width, viewport.Height), Color.Black * alpha); spriteBatch.End(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; namespace ParsecSharp { public static partial class Parser { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> SeparatedBy<TToken, T, TIgnore>(this Parser<TToken, T> parser, Parser<TToken, TIgnore> separator) => Try(parser.SeparatedBy1(separator), Enumerable.Empty<T>()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> SeparatedBy1<TToken, T, TIgnore>(this Parser<TToken, T> parser, Parser<TToken, TIgnore> separator) => parser.Bind(x => ManyRec(separator.Right(parser), new() { x })); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> EndBy<TToken, T, TIgnore>(this Parser<TToken, T> parser, Parser<TToken, TIgnore> separator) => Many(parser.Left(separator)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> EndBy1<TToken, T, TIgnore>(this Parser<TToken, T> parser, Parser<TToken, TIgnore> separator) => Many1(parser.Left(separator)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> SeparatedOrEndBy<TToken, T, TIgnore>(this Parser<TToken, T> parser, Parser<TToken, TIgnore> separator) => Try(parser.SeparatedOrEndBy1(separator), Enumerable.Empty<T>()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> SeparatedOrEndBy1<TToken, T, TIgnore>(this Parser<TToken, T> parser, Parser<TToken, TIgnore> separator) => parser.SeparatedBy1(separator).Left(Optional(separator)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> Except<TToken, T, TIgnore>(this Parser<TToken, T> parser, Parser<TToken, TIgnore> exception) => Not(exception).Right(parser); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> Except<TToken, T, TIgnore>(this Parser<TToken, T> parser, IEnumerable<Parser<TToken, TIgnore>> exceptions) => parser.Except(Choice(exceptions)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> Except<TToken, T, TIgnore>(this Parser<TToken, T> parser, params Parser<TToken, TIgnore>[] exceptions) => parser.Except(exceptions.AsEnumerable()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> Chain<TToken, T>(this Parser<TToken, T> parser, Func<T, Parser<TToken, T>> rest) => parser.Bind(x => ChainRec(rest, x)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> ChainLeft<TToken, T>(this Parser<TToken, T> parser, Parser<TToken, Func<T, T, T>> function) => parser.Chain(x => function.Bind(function => parser.Map(y => function(x, y)))); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> ChainRight<TToken, T>(this Parser<TToken, T> parser, Parser<TToken, Func<T, T, T>> function) => Fix<TToken, T>(self => parser.Bind(x => function.Next(function => self.Next(y => function(x, y), x), x))); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> FoldLeft<TToken, T>(this Parser<TToken, T> parser, Func<T, T, T> function) => parser.Bind(x => parser.FoldLeft(x, function)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, TAccumulator> FoldLeft<TToken, T, TAccumulator>(this Parser<TToken, T> parser, TAccumulator seed, Func<TAccumulator, T, TAccumulator> function) => parser.Next(x => parser.FoldLeft(function(seed, x), function), seed); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, TAccumulator> FoldLeft<TToken, T, TAccumulator>(this Parser<TToken, T> parser, Func<IParsecState<TToken>, TAccumulator> seed, Func<TAccumulator, T, TAccumulator> function) => Pure(seed).Bind(x => parser.FoldLeft(x, function)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> FoldRight<TToken, T>(this Parser<TToken, T> parser, Func<T, T, T> function) => Fix<TToken, T>(self => parser.Bind(x => self.Next(accumulator => function(x, accumulator), x))); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, TAccumulator> FoldRight<TToken, T, TAccumulator>(this Parser<TToken, T> parser, TAccumulator seed, Func<T, TAccumulator, TAccumulator> function) => Fix<TToken, TAccumulator>(self => parser.Next(x => self.Map(accumulator => function(x, accumulator)), seed)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, TAccumulator> FoldRight<TToken, T, TAccumulator>(this Parser<TToken, T> parser, Func<IParsecState<TToken>, TAccumulator> seed, Func<T, TAccumulator, TAccumulator> function) => Pure(seed).Bind(x => parser.FoldRight(x, function)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> Repeat<TToken, T>(this Parser<TToken, T> parser, int count) => Sequence(Enumerable.Repeat(parser, count)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, TLeft> Left<TToken, TLeft, TRight>(this Parser<TToken, TLeft> left, Parser<TToken, TRight> right) => left.Bind(x => right.Map(_ => x)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, TRight> Right<TToken, TLeft, TRight>(this Parser<TToken, TLeft> left, Parser<TToken, TRight> right) => left.Bind(right.Const); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> Between<TToken, T, TIgnore>(this Parser<TToken, T> parser, Parser<TToken, TIgnore> bracket) => parser.Between(bracket, bracket); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> Between<TToken, T, TOpen, TClose>(this Parser<TToken, T> parser, Parser<TToken, TOpen> open, Parser<TToken, TClose> close) => open.Right(parser.Left(close)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> Quote<TToken, T, TIgnore>(this Parser<TToken, T> parser, Parser<TToken, TIgnore> quote) => parser.Quote(quote, quote); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> Quote<TToken, T, TOpen, TClose>(this Parser<TToken, T> parser, Parser<TToken, TOpen> open, Parser<TToken, TClose> close) => open.Right(ManyTill(parser, close)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> Append<TToken, T>(this Parser<TToken, T> left, Parser<TToken, T> right) => left.Bind(x => right.Map(y => new[] { x, y }.AsEnumerable())); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> Append<TToken, T>(this Parser<TToken, T> left, Parser<TToken, IEnumerable<T>> right) => left.Bind(x => right.Map(y => y.Prepend(x))); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> Append<TToken, T>(this Parser<TToken, IEnumerable<T>> left, Parser<TToken, T> right) => left.Bind(x => right.Map(y => x.Append(y))); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> Append<TToken, T>(this Parser<TToken, IEnumerable<T>> left, Parser<TToken, IEnumerable<T>> right) => left.Bind(x => right.Map(y => x.Concat(y))); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> AppendOptional<TToken, T>(this Parser<TToken, T> parser, Parser<TToken, T> optional) => parser.AppendOptional(optional.Singleton()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> AppendOptional<TToken, T>(this Parser<TToken, T> parser, Parser<TToken, IEnumerable<T>> optional) => parser.Append(Try(optional, Enumerable.Empty<T>())); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> AppendOptional<TToken, T>(this Parser<TToken, IEnumerable<T>> parser, Parser<TToken, T> optional) => parser.AppendOptional(optional.Singleton()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> AppendOptional<TToken, T>(this Parser<TToken, IEnumerable<T>> parser, Parser<TToken, IEnumerable<T>> optional) => parser.Append(Try(optional, Enumerable.Empty<T>())); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> Or<TToken, T>(this Parser<TToken, T> first, Parser<TToken, T> second) => first.Alternative(second); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, Unit> Ignore<TToken, TIgnore>(this Parser<TToken, TIgnore> parser) => parser.Map(_ => Unit.Instance); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> End<TToken, T>(this Parser<TToken, T> parser) => parser.Left(EndOfInput<TToken>()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, string> MapToString<TToken, T>(this Parser<TToken, T> parser) => parser.Map(x => x?.ToString() ?? string.Empty); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T[]> ToArray<TToken, T>(this Parser<TToken, IEnumerable<T>> parser) => parser.Map(x => x.ToArray()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> Flatten<TToken, T>(this Parser<TToken, IEnumerable<IEnumerable<T>>> parser) => parser.Map(x => x.Aggregate(Enumerable.Empty<T>(), (accumulator, x) => accumulator.Concat(x))); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IEnumerable<T>> Singleton<TToken, T>(this Parser<TToken, T> parser) => parser.Map(x => new[] { x }.AsEnumerable()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> WithConsume<TToken, T>(this Parser<TToken, T> parser) => parser.WithConsume(_ => "A parser did not consume any input"); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> WithConsume<TToken, T>(this Parser<TToken, T> parser, Func<IPosition, string> message) => GetPosition<TToken>().Bind(start => parser.Left(GetPosition<TToken>().Guard(end => !start.Equals(end), position => $"At {nameof(WithConsume)} -> {message(position)}"))); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> WithMessage<TToken, T>(this Parser<TToken, T> parser, string message) => parser.Alternative(Fail<TToken, T>(message)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> WithMessage<TToken, T>(this Parser<TToken, T> parser, Func<Failure<TToken, T>, string> message) => parser.Alternative(failure => Fail<TToken, T>(message(failure))); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> AbortWhenFail<TToken, T>(this Parser<TToken, T> parser) => parser.AbortWhenFail(failure => failure.ToString()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> AbortWhenFail<TToken, T>(this Parser<TToken, T> parser, Func<Failure<TToken, T>, string> message) => parser.Alternative(failure => Abort<TToken, T>($"At {nameof(AbortWhenFail)} -> {message(failure)}".Const)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> AbortIfEntered<TToken, T>(this Parser<TToken, T> parser) => parser.AbortIfEntered(failure => failure.ToString()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> AbortIfEntered<TToken, T>(this Parser<TToken, T> parser, Func<Failure<TToken, T>, string> message) => parser.Alternative(failure => GetPosition<TToken>() .Bind(position => position.Equals(failure.State.Position) ? Fail<TToken, T>(failure.Message) : Abort<TToken, T>($"At {nameof(AbortIfEntered)} -> {message(failure)}".Const))); } }
using UnityEngine/*<GameObject>*/; using System.Collections.Generic/*<Dictionary>*/; namespace FineGameDesign.Utils { public static class AnimationView { public static bool isVerbose = false; private static Dictionary<Animator, string> states = new Dictionary<Animator, string>(); private static Dictionary<string, float> startTimes = new Dictionary<string, float>(); private static List<Animator> animatorsToDisable = new List<Animator>(); private static List<Animator> animatorsToDisableNow = new List<Animator>(); // Call animator.Play instead of animator.SetTrigger, in case the animator is in transition. // Test case: 2015-11-15 Enter "SAT". Type "RAT". Expect R selected. Got "R" resets to unselected. // http://answers.unity3d.com/questions/801875/mecanim-trigger-getting-stuck-in-true-state.html // // Do not call until initialized. Test case: 2015-11-15 Got warning "Animator has not been initialized" // http://answers.unity3d.com/questions/878896/animator-has-not-been-initialized-1.html // // In editor, deleted and recreated animator state transition. Test case: 2015-11-15 Got error "Transition '' in state 'selcted' uses parameter 'none' which is not compatible with condition type" // http://answers.unity3d.com/questions/1070010/transition-x-in-state-y-uses-parameter-z-which-is.html // // Unity expects not to animate the camera or the root itself. Instead animate the child of the root. The root might not move. // Test case: 2016-02-13 Animate camera position. Play. Camera does not move. Generate root motion curves. Apply root motion curves. Still camera does not move. Assign animator to parent of camera. Animate child. Then camera moves. // // isTrigger: If true, then set trigger. Otherwise play animation. public static void SetState(Animator animator, string state, bool isRestart = false, bool isTrigger = false) { if (null == animator) { DebugUtil.Log("AnimationView.SetState: Does animator exist? " + SceneNodeView.GetPath(animator.gameObject) + ": " + state); return; } if (!animator.isInitialized) { if (isVerbose) { DebugUtil.Log("AnimationView.SetState: Animator is not initialized."); } return; } if (!animator.enabled) { animator.enabled = true; } if (isTrigger) { animator.SetTrigger(state); } else if (isRestart) { animator.Play(state, -1, 0f); } else { animator.Play(state); } bool isChange = !states.ContainsKey(animator) || states[animator] != state; if (isVerbose && (isRestart || isChange)) { DebugUtil.Log("AnimationView.SetState: " + SceneNodeView.GetPath(animator.gameObject) + ": " + state + " at " + Time.time); } if (isChange || isRestart) { states[animator] = state; startTimes[state] = Time.time; MayAddToDisableOnEnd(animator); } } public static void SetStates(List<Animator> animators, List<string> states) { for (int index = 0, end = states.Count; index < end; ++index) { SetState(animators[index], states[index]); } } // It would be higher performance to cache the animator. public static void SetState(GameObject animatorOwner, string state, bool isRestart = false, bool isTrigger = false) { Animator animator = animatorOwner.GetComponent<Animator>(); SetState(animator, state, isRestart, isTrigger); } // It would be higher performance to cache the animators. public static void SetStates(List<GameObject> animatorOwners, List<string> states) { for (int index = 0, end = states.Count; index < end; ++index) { SetState(animatorOwners[index], states[index]); } } // Gotcha: // Trigger is not consumed until listening animation completes. // http://answers.unity3d.com/questions/801875/mecanim-trigger-getting-stuck-in-true-state.html // So if the trigger is in a state that doesn't listen to that trigger, // the trigger sticks around and could trigger as soon as it gets into a listening state. // That can make it appear as if the trigger never fired. // Playing the animation directly, avoids this latent trigger. // Also having the model recognize which states will trigger avoid a latent trigger. public static void SetTrigger(GameObject animatorOwner, string state) { SetState(animatorOwner, state, false, true); } // Does not support the animator transitioning to another state. // Depends on setting state to add animators to disable. // Disables on the next update. // Still, this function's calling order is fragile. // It works when updating disabling before any new animations are set. // // Remarks: // Useful to disable animation at the end of a clip. // Useful to speed up performance if animator update is a hotspot in the profiler. // Unfortunately Unity animations can be slow and take up processing time // even after the last keyframe. // Disabling all animators removes this cost from the profiler. // """Disable idle animations. Avoid design patterns where an animator sits in a loop setting a value to the same thing. There is considerable overhead for this technique, with no effect on the application. Instead, terminate the animation and restart when appropriate.""" // https://developer.microsoft.com/en-us/windows/mixed-reality/performance_recommendations_for_unity // // I didn't find a more performant method in Unity to set an animation to disable on end. // An animation event sends a message, which is hundreds of times slower on that frame. // The update poll has overhead that scales with number of observed animators. // To reduce overhead, updating removes each animator when it disables. public static void UpdateDisableOnEnd(int layer = 0) { for (int index = animatorsToDisableNow.Count - 1; index >= 0; --index) { Animator animator = animatorsToDisableNow[index]; if (animator == null) continue; animator.enabled = false; } animatorsToDisableNow.Clear(); for (int index = animatorsToDisable.Count - 1; index >= 0; --index) { Animator animator = animatorsToDisable[index]; if (animator == null || animator.gameObject == null || !animator.isInitialized || !animator.enabled) { animatorsToDisableNow.Add(animator); animatorsToDisable.RemoveAt(index); continue; } AnimatorStateInfo info = animator.GetCurrentAnimatorStateInfo(layer); if (info.normalizedTime < 1.0f) { continue; } animatorsToDisableNow.Add(animator); animatorsToDisable.RemoveAt(index); } } private static void MayAddToDisableOnEnd(Animator animator, int layer = 0) { if (!WillEnd(animator, layer)) { return; } if (animatorsToDisable.IndexOf(animator) >= 0) { return; } animatorsToDisable.Add(animator); } // When animator is done and would clamp or play once, disables. // NOTE: Get current animator clip info creates garbage. private static bool WillEnd(Animator animator, int layer = 0) { AnimatorClipInfo[] clipInfos = animator.GetCurrentAnimatorClipInfo(layer); for (int index = 0, end = clipInfos.Length; index < end; ++index) { AnimationClip clip = clipInfos[index].clip; if (clip.wrapMode == WrapMode.Loop || clip.wrapMode == WrapMode.PingPong) { return false; } } return true; } // Return name state that was completed now, or null. // Also erases that state, so next time this is called it won't be completed now. // Expects time passed since SetState to avoid race when CompletedNow is not called before SetState in the frame. // Expects animation is on layer 0. // Syncrhonous. Does not depend on event complete animation. // // http://answers.unity3d.com/questions/351534/how-to-get-current-state-on-mecanim.html // // Another way might be to get the currently playing animation. // http://answers.unity3d.com/questions/362629/how-can-i-check-if-an-animation-is-being-played-or.html // // Blubberfish says integers will compare faster than strings. // http://answers.unity3d.com/questions/407186/how-to-get-current-state-name-on-mecanim.html public static string CompletedNow(Animator animator, int layer = 0) { if (null == animator) { DebugUtil.Log("AnimationView.CompletedNow: Does animator exist? " + SceneNodeView.GetPath(animator.gameObject)); return null; } if (!animator.isInitialized) { return null; } if (!states.ContainsKey(animator)) { return null; } string completedNow = states[animator]; if (completedNow == null || startTimes[completedNow] == Time.time) { return null; } AnimatorStateInfo info = animator.GetCurrentAnimatorStateInfo(layer); if (info.normalizedTime < 1.0f) { return null; } states[animator] = null; if (isVerbose) { LogInfo(animator, completedNow, info, layer, "AnimationView.CompletedNow: "); } return completedNow; } public static string CompletedNow(GameObject animatorOwner, int layer = 0) { return CompletedNow(animatorOwner.GetComponent<Animator>(), layer); } // XXX Would be faster with StringBuilder, rather than string concatenation. private static void LogInfo(Animator animator, string completedNow, AnimatorStateInfo info, int layer, string prefix) { string message = prefix + SceneNodeView.GetPath(animator.gameObject) + ": " + completedNow + " at " + Time.time + " info " + info + " IsName " + info.IsName(completedNow) + " length " + info.length + " normalizedTime " + info.normalizedTime ; Animation animationStates = animator.GetComponent<Animation>(); if (null != animationStates) { foreach (AnimationState state in animationStates) { message += "\n state " + state.name + " time " + state.time + " length " + state.length + " weight " + state.weight + " enabled " + state.enabled + " normalizedTime " + state.normalizedTime ; } } AnimatorClipInfo[] clipInfos = animator.GetCurrentAnimatorClipInfo(layer); for (int index = 0, end = clipInfos.Length; index < end; ++index) { AnimationClip clip = clipInfos[index].clip; message += "\n clip " + clip.name + " length " + clip.length; } DebugUtil.Log(message); } } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace System.Web.Services.Configuration { using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Security.Permissions; using System.Threading; using System.Web; using System.Web.Services.Description; using System.Web.Services.Discovery; using System.Web.Services.Protocols; using System.Xml.Serialization; using System.Runtime.CompilerServices; public sealed class WebServicesSection : ConfigurationSection { public WebServicesSection() : base() { this.properties.Add(this.conformanceWarnings); this.properties.Add(this.protocols); this.properties.Add(this.serviceDescriptionFormatExtensionTypes); this.properties.Add(this.soapEnvelopeProcessing); this.properties.Add(this.soapExtensionImporterTypes); this.properties.Add(this.soapExtensionReflectorTypes); this.properties.Add(this.soapExtensionTypes); this.properties.Add(this.soapTransportImporterTypes); this.properties.Add(this.wsdlHelpGenerator); this.properties.Add(this.soapServerProtocolFactoryType); this.properties.Add(this.diagnostics); } static object ClassSyncObject { get { if (classSyncObject == null) { object o = new object(); Interlocked.CompareExchange(ref classSyncObject, o, null); } return classSyncObject; } } [ConfigurationProperty("conformanceWarnings")] public WsiProfilesElementCollection ConformanceWarnings { get { return (WsiProfilesElementCollection)base[this.conformanceWarnings]; } } internal WsiProfiles EnabledConformanceWarnings { get { WsiProfiles retval = WsiProfiles.None; foreach (WsiProfilesElement element in this.ConformanceWarnings) { retval |= element.Name; } return retval; } } public static WebServicesSection Current { get { WebServicesSection retval = null; // check to see if we are running on the server without loading system.web.dll if (Thread.GetDomain().GetData(".appDomain") != null) { retval = GetConfigFromHttpContext(); } if (retval == null) { retval = (WebServicesSection)PrivilegedConfigurationManager.GetSection(WebServicesSection.SectionName); } return retval; } } [ConfigurationPermission(SecurityAction.Assert, Unrestricted = true)] [MethodImplAttribute(MethodImplOptions.NoInlining)] static WebServicesSection GetConfigFromHttpContext() { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); HttpContext context = HttpContext.Current; if (context != null) { return (WebServicesSection)context.GetSection(WebServicesSection.SectionName); } return null; } internal XmlSerializer DiscoveryDocumentSerializer { get { if (this.discoveryDocumentSerializer == null) { lock (WebServicesSection.ClassSyncObject) { if (this.discoveryDocumentSerializer == null) { XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); foreach (Type discoveryReferenceType in this.DiscoveryReferenceTypes) { object[] xmlElementAttribs = discoveryReferenceType.GetCustomAttributes(typeof(XmlRootAttribute), false); if (xmlElementAttribs.Length == 0) { throw new InvalidOperationException(Res.GetString(Res.WebMissingCustomAttribute, discoveryReferenceType.FullName, "XmlRoot")); } string name = ((XmlRootAttribute)xmlElementAttribs[0]).ElementName; string ns = ((XmlRootAttribute)xmlElementAttribs[0]).Namespace; XmlElementAttribute attr = new XmlElementAttribute(name, discoveryReferenceType); attr.Namespace = ns; attrs.XmlElements.Add(attr); } attrOverrides.Add(typeof(DiscoveryDocument), "References", attrs); this.discoveryDocumentSerializer = new DiscoveryDocumentSerializer(); } } } return discoveryDocumentSerializer; } } internal Type[] DiscoveryReferenceTypes { get { return this.discoveryReferenceTypes; } } public WebServiceProtocols EnabledProtocols { get { if (this.enabledProtocols == WebServiceProtocols.Unknown) { lock (WebServicesSection.ClassSyncObject) { if (this.enabledProtocols == WebServiceProtocols.Unknown) { WebServiceProtocols temp = WebServiceProtocols.Unknown; foreach (ProtocolElement element in this.Protocols) { temp |= (WebServiceProtocols)element.Name; } this.enabledProtocols = temp; } } } return this.enabledProtocols; } } internal Type[] GetAllFormatExtensionTypes() { if (this.ServiceDescriptionFormatExtensionTypes.Count == 0) { return this.defaultFormatTypes; } else { Type[] formatTypes = new Type[defaultFormatTypes.Length + this.ServiceDescriptionFormatExtensionTypes.Count]; Array.Copy(defaultFormatTypes, formatTypes, defaultFormatTypes.Length); for (int index = 0; index < this.ServiceDescriptionFormatExtensionTypes.Count; ++index) { formatTypes[index + defaultFormatTypes.Length] = this.ServiceDescriptionFormatExtensionTypes[index].Type; } return formatTypes; } } static XmlFormatExtensionPointAttribute GetExtensionPointAttribute(Type type) { object[] attrs = type.GetCustomAttributes(typeof(XmlFormatExtensionPointAttribute), false); if (attrs.Length == 0) throw new ArgumentException(Res.GetString(Res.TheSyntaxOfTypeMayNotBeExtended1, type.FullName), "type"); return (XmlFormatExtensionPointAttribute)attrs[0]; } [ConfigurationPermission(SecurityAction.Assert, Unrestricted = true)] static public WebServicesSection GetSection(Configuration config) { if (config == null) { throw new ArgumentNullException("config"); } return (WebServicesSection)config.GetSection(WebServicesSection.SectionName); } protected override void InitializeDefault() { this.ConformanceWarnings.SetDefaults(); this.Protocols.SetDefaults(); // check to see if we are running on the server without loading system.web.dll if (Thread.GetDomain().GetData(".appDomain") != null) { this.WsdlHelpGenerator.SetDefaults(); } this.SoapServerProtocolFactoryType.Type = typeof(SoapServerProtocolFactory); } internal static void LoadXmlFormatExtensions(Type[] extensionTypes, XmlAttributeOverrides overrides, XmlSerializerNamespaces namespaces) { Hashtable table = new Hashtable(); table.Add(typeof(ServiceDescription), new XmlAttributes()); table.Add(typeof(Import), new XmlAttributes()); table.Add(typeof(Port), new XmlAttributes()); table.Add(typeof(Service), new XmlAttributes()); table.Add(typeof(FaultBinding), new XmlAttributes()); table.Add(typeof(InputBinding), new XmlAttributes()); table.Add(typeof(OutputBinding), new XmlAttributes()); table.Add(typeof(OperationBinding), new XmlAttributes()); table.Add(typeof(Binding), new XmlAttributes()); table.Add(typeof(OperationFault), new XmlAttributes()); table.Add(typeof(OperationInput), new XmlAttributes()); table.Add(typeof(OperationOutput), new XmlAttributes()); table.Add(typeof(Operation), new XmlAttributes()); table.Add(typeof(PortType), new XmlAttributes()); table.Add(typeof(Message), new XmlAttributes()); table.Add(typeof(MessagePart), new XmlAttributes()); table.Add(typeof(Types), new XmlAttributes()); Hashtable extensions = new Hashtable(); foreach (Type extensionType in extensionTypes) { if (extensions[extensionType] != null) { continue; } extensions.Add(extensionType, extensionType); object[] attrs = extensionType.GetCustomAttributes(typeof(XmlFormatExtensionAttribute), false); if (attrs.Length == 0) { throw new ArgumentException(Res.GetString(Res.RequiredXmlFormatExtensionAttributeIsMissing1, extensionType.FullName), "extensionTypes"); } XmlFormatExtensionAttribute extensionAttr = (XmlFormatExtensionAttribute)attrs[0]; foreach (Type extensionPointType in extensionAttr.ExtensionPoints) { XmlAttributes xmlAttrs = (XmlAttributes)table[extensionPointType]; if (xmlAttrs == null) { xmlAttrs = new XmlAttributes(); table.Add(extensionPointType, xmlAttrs); } XmlElementAttribute xmlAttr = new XmlElementAttribute(extensionAttr.ElementName, extensionType); xmlAttr.Namespace = extensionAttr.Namespace; xmlAttrs.XmlElements.Add(xmlAttr); } attrs = extensionType.GetCustomAttributes(typeof(XmlFormatExtensionPrefixAttribute), false); string[] prefixes = new string[attrs.Length]; Hashtable nsDefs = new Hashtable(); for (int i = 0; i < attrs.Length; i++) { XmlFormatExtensionPrefixAttribute prefixAttr = (XmlFormatExtensionPrefixAttribute)attrs[i]; prefixes[i] = prefixAttr.Prefix; nsDefs.Add(prefixAttr.Prefix, prefixAttr.Namespace); } Array.Sort(prefixes, InvariantComparer.Default); for (int i = 0; i < prefixes.Length; i++) { namespaces.Add(prefixes[i], (string)nsDefs[prefixes[i]]); } } foreach (Type extensionPointType in table.Keys) { XmlFormatExtensionPointAttribute attr = GetExtensionPointAttribute(extensionPointType); XmlAttributes xmlAttrs = (XmlAttributes)table[extensionPointType]; if (attr.AllowElements) { xmlAttrs.XmlAnyElements.Add(new XmlAnyElementAttribute()); } overrides.Add(extensionPointType, attr.MemberName, xmlAttrs); } } internal Type[] MimeImporterTypes { get { return this.mimeImporterTypes; } } internal Type[] MimeReflectorTypes { get { return this.mimeReflectorTypes; } } internal Type[] ParameterReaderTypes { get { return this.parameterReaderTypes; } } protected override ConfigurationPropertyCollection Properties { get { return this.properties; } } internal Type[] ProtocolImporterTypes { get { if (this.protocolImporterTypes.Length == 0) { lock (WebServicesSection.ClassSyncObject) { if (this.protocolImporterTypes.Length == 0) { WebServiceProtocols enabledProtocols = this.EnabledProtocols; List<Type> protocolImporterList = new List<Type>(); // order is important for soap: 1.2 must come after 1.1 if ((enabledProtocols & WebServiceProtocols.HttpSoap) != 0) { protocolImporterList.Add(typeof(SoapProtocolImporter)); } if ((enabledProtocols & WebServiceProtocols.HttpSoap12) != 0) { protocolImporterList.Add(typeof(Soap12ProtocolImporter)); } if ((enabledProtocols & WebServiceProtocols.HttpGet) != 0) { protocolImporterList.Add(typeof(HttpGetProtocolImporter)); } if ((enabledProtocols & WebServiceProtocols.HttpPost) != 0) { protocolImporterList.Add(typeof(HttpPostProtocolImporter)); } this.protocolImporterTypes = protocolImporterList.ToArray(); } } } return this.protocolImporterTypes; } set { this.protocolImporterTypes = value; } } internal Type[] ProtocolReflectorTypes { get { if (this.protocolReflectorTypes.Length == 0) { lock (WebServicesSection.ClassSyncObject) { if (this.protocolReflectorTypes.Length == 0) { WebServiceProtocols enabledProtocols = this.EnabledProtocols; List<Type> protocolReflectorList = new List<Type>(); // order is important for soap: 1.2 must come after 1.1 if ((enabledProtocols & WebServiceProtocols.HttpSoap) != 0) { protocolReflectorList.Add(typeof(SoapProtocolReflector)); } if ((enabledProtocols & WebServiceProtocols.HttpSoap12) != 0) { protocolReflectorList.Add(typeof(Soap12ProtocolReflector)); } if ((enabledProtocols & WebServiceProtocols.HttpGet) != 0) { protocolReflectorList.Add(typeof(HttpGetProtocolReflector)); } if ((enabledProtocols & WebServiceProtocols.HttpPost) != 0) { protocolReflectorList.Add(typeof(HttpPostProtocolReflector)); } this.protocolReflectorTypes = protocolReflectorList.ToArray(); } } } return this.protocolReflectorTypes; } set { this.protocolReflectorTypes = value; } } [ConfigurationProperty("protocols")] public ProtocolElementCollection Protocols { get { return (ProtocolElementCollection)base[this.protocols]; } } [ConfigurationProperty("soapEnvelopeProcessing")] public SoapEnvelopeProcessingElement SoapEnvelopeProcessing { get { return (SoapEnvelopeProcessingElement)base[this.soapEnvelopeProcessing]; } set { base[this.soapEnvelopeProcessing] = value; } } public DiagnosticsElement Diagnostics { get { return (DiagnosticsElement)base[this.diagnostics]; } set { base[this.diagnostics] = value; } } protected override void Reset(ConfigurationElement parentElement) { // Fixes potential race condition where serverProtocolFactories != enabledProtocols settings this.serverProtocolFactories = null; this.enabledProtocols = WebServiceProtocols.Unknown; if (parentElement != null) { WebServicesSection parent = (WebServicesSection)parentElement; this.discoveryDocumentSerializer = parent.discoveryDocumentSerializer; } base.Reset(parentElement); } internal Type[] ReturnWriterTypes { get { return this.returnWriterTypes; } } internal ServerProtocolFactory[] ServerProtocolFactories { get { if (this.serverProtocolFactories == null) { lock (WebServicesSection.ClassSyncObject) { if (this.serverProtocolFactories == null) { WebServiceProtocols enabledProtocols = this.EnabledProtocols; List<ServerProtocolFactory> serverProtocolFactoryList = new List<ServerProtocolFactory>(); // These are order sensitive. We want SOAP to go first for perf // and Discovery (?wsdl and ?disco) should go before Documentation // both soap versions are handled by the same factory if ((enabledProtocols & WebServiceProtocols.AnyHttpSoap) != 0) { serverProtocolFactoryList.Add((ServerProtocolFactory)Activator.CreateInstance(this.SoapServerProtocolFactory)); } if ((enabledProtocols & WebServiceProtocols.HttpPost) != 0) { serverProtocolFactoryList.Add(new HttpPostServerProtocolFactory()); } if ((enabledProtocols & WebServiceProtocols.HttpPostLocalhost) != 0) { serverProtocolFactoryList.Add(new HttpPostLocalhostServerProtocolFactory()); } if ((enabledProtocols & WebServiceProtocols.HttpGet) != 0) { serverProtocolFactoryList.Add(new HttpGetServerProtocolFactory()); } if ((enabledProtocols & WebServiceProtocols.Documentation) != 0) { serverProtocolFactoryList.Add(new DiscoveryServerProtocolFactory()); serverProtocolFactoryList.Add(new DocumentationServerProtocolFactory()); } this.serverProtocolFactories = serverProtocolFactoryList.ToArray(); } } } return this.serverProtocolFactories; } } internal bool ServiceDescriptionExtended { get { return this.ServiceDescriptionFormatExtensionTypes.Count > 0; } } [ConfigurationProperty("serviceDescriptionFormatExtensionTypes")] public TypeElementCollection ServiceDescriptionFormatExtensionTypes { get { return (TypeElementCollection)base[this.serviceDescriptionFormatExtensionTypes]; } } [ConfigurationProperty("soapExtensionImporterTypes")] public TypeElementCollection SoapExtensionImporterTypes { get { return (TypeElementCollection)base[this.soapExtensionImporterTypes]; } } [ConfigurationProperty("soapExtensionReflectorTypes")] public TypeElementCollection SoapExtensionReflectorTypes { get { return (TypeElementCollection)base[this.soapExtensionReflectorTypes]; } } [ConfigurationProperty("soapExtensionTypes")] public SoapExtensionTypeElementCollection SoapExtensionTypes { get { return (SoapExtensionTypeElementCollection)base[this.soapExtensionTypes]; } } [ConfigurationProperty("soapServerProtocolFactory")] public TypeElement SoapServerProtocolFactoryType { get { return (TypeElement)base[this.soapServerProtocolFactoryType]; } } internal Type SoapServerProtocolFactory { get { if (this.soapServerProtocolFactory == null) { lock (WebServicesSection.ClassSyncObject) { if (this.soapServerProtocolFactory == null) { this.soapServerProtocolFactory = this.SoapServerProtocolFactoryType.Type; } } } return this.soapServerProtocolFactory; } } [ConfigurationProperty("soapTransportImporterTypes")] public TypeElementCollection SoapTransportImporterTypes { get { return (TypeElementCollection)base[this.soapTransportImporterTypes]; } } internal Type[] SoapTransportImporters { get { Type[] retval = new Type[1 + this.SoapTransportImporterTypes.Count]; retval[0] = typeof(SoapHttpTransportImporter); for (int i = 0; i < SoapTransportImporterTypes.Count; ++i) { retval[i + 1] = SoapTransportImporterTypes[i].Type; } return retval; } } void TurnOnGetAndPost() { bool needPost = (this.EnabledProtocols & WebServiceProtocols.HttpPost) == 0; bool needGet = (this.EnabledProtocols & WebServiceProtocols.HttpGet) == 0; if (!needGet && !needPost) return; ArrayList importers = new ArrayList(ProtocolImporterTypes); ArrayList reflectors = new ArrayList(ProtocolReflectorTypes); if (needPost) { importers.Add(typeof(HttpPostProtocolImporter)); reflectors.Add(typeof(HttpPostProtocolReflector)); } if (needGet) { importers.Add(typeof(HttpGetProtocolImporter)); reflectors.Add(typeof(HttpGetProtocolReflector)); } ProtocolImporterTypes = (Type[])importers.ToArray(typeof(Type)); ProtocolReflectorTypes = (Type[])reflectors.ToArray(typeof(Type)); enabledProtocols |= WebServiceProtocols.HttpGet | WebServiceProtocols.HttpPost; } [ConfigurationProperty("wsdlHelpGenerator")] public WsdlHelpGeneratorElement WsdlHelpGenerator { get { return (WsdlHelpGeneratorElement)base[this.wsdlHelpGenerator]; } } ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection(); // Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) ) static object classSyncObject = null; const string SectionName = @"system.web/webServices"; readonly ConfigurationProperty conformanceWarnings = new ConfigurationProperty("conformanceWarnings", typeof(WsiProfilesElementCollection), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty protocols = new ConfigurationProperty("protocols", typeof(ProtocolElementCollection), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty serviceDescriptionFormatExtensionTypes = new ConfigurationProperty("serviceDescriptionFormatExtensionTypes", typeof(TypeElementCollection), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty soapEnvelopeProcessing = new ConfigurationProperty("soapEnvelopeProcessing", typeof(SoapEnvelopeProcessingElement), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty soapExtensionImporterTypes = new ConfigurationProperty("soapExtensionImporterTypes", typeof(TypeElementCollection), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty soapExtensionReflectorTypes = new ConfigurationProperty("soapExtensionReflectorTypes", typeof(TypeElementCollection), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty soapExtensionTypes = new ConfigurationProperty("soapExtensionTypes", typeof(SoapExtensionTypeElementCollection), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty soapTransportImporterTypes = new ConfigurationProperty("soapTransportImporterTypes", typeof(TypeElementCollection), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty wsdlHelpGenerator = new ConfigurationProperty("wsdlHelpGenerator", typeof(WsdlHelpGeneratorElement), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty soapServerProtocolFactoryType = new ConfigurationProperty("soapServerProtocolFactory", typeof(TypeElement), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty diagnostics = new ConfigurationProperty("diagnostics", typeof(DiagnosticsElement), null, ConfigurationPropertyOptions.None); Type[] defaultFormatTypes = new Type[] { typeof(HttpAddressBinding), typeof(HttpBinding), typeof(HttpOperationBinding), typeof(HttpUrlEncodedBinding), typeof(HttpUrlReplacementBinding), typeof(MimeContentBinding), typeof(MimeXmlBinding), typeof(MimeMultipartRelatedBinding), typeof(MimeTextBinding), typeof(System.Web.Services.Description.SoapBinding), typeof(SoapOperationBinding), typeof(SoapBodyBinding), typeof(SoapFaultBinding), typeof(SoapHeaderBinding), typeof(SoapAddressBinding), typeof(Soap12Binding), typeof(Soap12OperationBinding), typeof(Soap12BodyBinding), typeof(Soap12FaultBinding), typeof(Soap12HeaderBinding), typeof(Soap12AddressBinding) }; Type[] discoveryReferenceTypes = new Type[] { typeof(DiscoveryDocumentReference), typeof(ContractReference), typeof(SchemaReference), typeof(System.Web.Services.Discovery.SoapBinding) }; XmlSerializer discoveryDocumentSerializer = null; WebServiceProtocols enabledProtocols = WebServiceProtocols.Unknown; Type[] mimeImporterTypes = new Type[] { typeof(MimeXmlImporter), typeof(MimeFormImporter), typeof(MimeTextImporter) }; Type[] mimeReflectorTypes = new Type[] { typeof(MimeXmlReflector), typeof(MimeFormReflector) }; Type[] parameterReaderTypes = new Type[] { typeof(UrlParameterReader), typeof(HtmlFormParameterReader) }; Type[] protocolImporterTypes = new Type[0]; Type[] protocolReflectorTypes = new Type[0]; Type[] returnWriterTypes = new Type[] { typeof(XmlReturnWriter) }; ServerProtocolFactory[] serverProtocolFactories = null; Type soapServerProtocolFactory = null; } }
/* * 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 Mono.Addins; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace OpenSim.Region.CoreModules.World.Archiver { /// <summary> /// This module loads and saves OpenSimulator region archives /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ArchiverModule")] public class ArchiverModule : INonSharedRegionModule, IRegionArchiverModule { /// <value> /// The file used to load and save an opensimulator archive if no filename has been specified /// </value> protected const string DEFAULT_OAR_BACKUP_FILENAME = "region.oar"; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Name { get { return "RegionArchiverModule"; } } public IRegionCombinerModule RegionCombinerModule { get; private set; } public Type ReplaceableInterface { get { return null; } } public Scene Scene { get; private set; } public void AddRegion(Scene scene) { Scene = scene; Scene.RegisterModuleInterface<IRegionArchiverModule>(this); //m_log.DebugFormat("[ARCHIVER]: Enabled for region {0}", scene.RegionInfo.RegionName); } public void ArchiveRegion(string savePath, Dictionary<string, object> options) { ArchiveRegion(savePath, Guid.Empty, options); } public void ArchiveRegion(string savePath, Guid requestId, Dictionary<string, object> options) { m_log.InfoFormat( "[ARCHIVER]: Writing archive for region {0} to {1}", Scene.RegionInfo.RegionName, savePath); new ArchiveWriteRequest(Scene, savePath, requestId).ArchiveRegion(options); } public void ArchiveRegion(Stream saveStream) { ArchiveRegion(saveStream, Guid.Empty); } public void ArchiveRegion(Stream saveStream, Guid requestId) { ArchiveRegion(saveStream, requestId, new Dictionary<string, object>()); } public void ArchiveRegion(Stream saveStream, Guid requestId, Dictionary<string, object> options) { new ArchiveWriteRequest(Scene, saveStream, requestId).ArchiveRegion(options); } public void Close() { } public void DearchiveRegion(string loadPath) { Dictionary<string, object> archiveOptions = new Dictionary<string, object>(); DearchiveRegion(loadPath, Guid.Empty, archiveOptions); } public void DearchiveRegion(string loadPath, Guid requestId, Dictionary<string, object> options) { m_log.InfoFormat( "[ARCHIVER]: Loading archive to region {0} from {1}", Scene.RegionInfo.RegionName, loadPath); new ArchiveReadRequest(Scene, loadPath, requestId, options).DearchiveRegion(); } public void DearchiveRegion(Stream loadStream) { Dictionary<string, object> archiveOptions = new Dictionary<string, object>(); DearchiveRegion(loadStream, Guid.Empty, archiveOptions); } public void DearchiveRegion(Stream loadStream, Guid requestId, Dictionary<string, object> options) { new ArchiveReadRequest(Scene, loadStream, requestId, options).DearchiveRegion(); } /// <summary> /// Load a whole region from an opensimulator archive. /// </summary> /// <param name="cmdparams"></param> public void HandleLoadOarConsoleCommand(string module, string[] cmdparams) { bool mergeOar = false; bool skipAssets = false; bool forceTerrain = false; bool forceParcels = false; bool noObjects = false; Vector3 displacement = new Vector3(0f, 0f, 0f); float rotation = 0f; Vector3 rotationCenter = new Vector3(Constants.RegionSize / 2f, Constants.RegionSize / 2f, 0); OptionSet options = new OptionSet(); options.Add("m|merge", delegate(string v) { mergeOar = (v != null); }); options.Add("s|skip-assets", delegate(string v) { skipAssets = (v != null); }); options.Add("force-terrain", delegate(string v) { forceTerrain = (v != null); }); options.Add("forceterrain", delegate(string v) { forceTerrain = (v != null); }); // downward compatibility options.Add("force-parcels", delegate(string v) { forceParcels = (v != null); }); options.Add("forceparcels", delegate(string v) { forceParcels = (v != null); }); // downward compatibility options.Add("no-objects", delegate(string v) { noObjects = (v != null); }); options.Add("displacement=", delegate(string v) { try { displacement = v == null ? Vector3.Zero : Vector3.Parse(v); } catch { m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing displacement"); m_log.ErrorFormat("[ARCHIVER MODULE] Must be represented as vector3: --displacement \"<128,128,0>\""); return; } }); options.Add("rotation=", delegate(string v) { try { rotation = v == null ? 0f : float.Parse(v); } catch { m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing rotation"); m_log.ErrorFormat("[ARCHIVER MODULE] Must be an angle in degrees between -360 and +360: --rotation 45"); return; } // Convert to radians for internals rotation = Util.Clamp<float>(rotation, -359f, 359f) / 180f * (float)Math.PI; }); options.Add("rotation-center=", delegate(string v) { try { rotationCenter = v == null ? Vector3.Zero : Vector3.Parse(v); } catch { m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing rotation displacement"); m_log.ErrorFormat("[ARCHIVER MODULE] Must be represented as vector3: --rotation-center \"<128,128,0>\""); return; } }); // Send a message to the region ready module /* bluewall* Disable this for the time being IRegionReadyModule rready = m_scene.RequestModuleInterface<IRegionReadyModule>(); if (rready != null) { rready.OarLoadingAlert("load"); } */ List<string> mainParams = options.Parse(cmdparams); // m_log.DebugFormat("MERGE OAR IS [{0}]", mergeOar); // // foreach (string param in mainParams) // m_log.DebugFormat("GOT PARAM [{0}]", param); Dictionary<string, object> archiveOptions = new Dictionary<string, object>(); if (mergeOar) archiveOptions.Add("merge", null); if (skipAssets) archiveOptions.Add("skipAssets", null); if (forceTerrain) archiveOptions.Add("force-terrain", null); if (forceParcels) archiveOptions.Add("force-parcels", null); if (noObjects) archiveOptions.Add("no-objects", null); archiveOptions.Add("displacement", displacement); archiveOptions.Add("rotation", rotation); archiveOptions.Add("rotation-center", rotationCenter); if (mainParams.Count > 2) { DearchiveRegion(mainParams[2], Guid.Empty, archiveOptions); } else { DearchiveRegion(DEFAULT_OAR_BACKUP_FILENAME, Guid.Empty, archiveOptions); } } /// <summary> /// Save a region to a file, including all the assets needed to restore it. /// </summary> /// <param name="cmdparams"></param> public void HandleSaveOarConsoleCommand(string module, string[] cmdparams) { Dictionary<string, object> options = new Dictionary<string, object>(); OptionSet ops = new OptionSet(); // legacy argument [obsolete] ops.Add("p|profile=", delegate(string v) { Console.WriteLine("\n WARNING: -profile option is obsolete and it will not work. Use -home instead.\n"); }); // preferred ops.Add("h|home=", delegate(string v) { options["home"] = v; }); ops.Add("noassets", delegate(string v) { options["noassets"] = v != null; }); ops.Add("publish", v => options["wipe-owners"] = v != null); ops.Add("perm=", delegate(string v) { options["checkPermissions"] = v; }); ops.Add("all", delegate(string v) { options["all"] = v != null; }); List<string> mainParams = ops.Parse(cmdparams); string path; if (mainParams.Count > 2) path = mainParams[2]; else path = DEFAULT_OAR_BACKUP_FILENAME; // Not doing this right now as this causes some problems with auto-backup systems. Maybe a force flag is // needed // if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, path)) // return; ArchiveRegion(path, options); } public void Initialise(IConfigSource source) { //m_log.Debug("[ARCHIVER] Initialising"); } public void RegionLoaded(Scene scene) { RegionCombinerModule = scene.RequestModuleInterface<IRegionCombinerModule>(); } public void RemoveRegion(Scene scene) { } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace NVelocity.Runtime { using System.Collections; using Directive; using Parser.Node; /// <summary> Manages VMs in namespaces. Currently, two namespace modes are /// supported: /// /// <ul> /// <li>flat - all allowable VMs are in the global namespace</li> /// <li>local - inline VMs are added to it's own template namespace</li> /// </ul> /// /// Thanks to <a href="mailto:JFernandez@viquity.com">Jose Alberto Fernandez</a> /// for some ideas incorporated here. /// /// </summary> /// <author> <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:JFernandez@viquity.com">Jose Alberto Fernandez</a> /// </author> /// <version> $Id: VelocimacroManager.java 698376 2008-09-23 22:15:49Z nbubna $ /// </version> public class VelocimacroManager { private void InitBlock() { namespaceHash = new Hashtable(); } /// <summary> public switch to let external user of manager to control namespace /// usage indep of properties. That way, for example, at startup the /// library files are loaded into global namespace /// /// </summary> /// <param name="namespaceOn">True if namespaces should be used. /// </param> public bool NamespaceUsage { set { this.namespacesOn = value; } } /// <summary> Should macros registered from Libraries be marked special?</summary> /// <param name="registerFromLib">True if macros from Libs should be marked. /// </param> public bool RegisterFromLib { set { this.registerFromLib = value; } } /// <summary> Should macros from the same template be inlined? /// /// </summary> /// <param name="inlineLocalMode">True if macros should be inlined on the same template. /// </param> public bool TemplateLocalInlineVM { set { this.inlineLocalMode = value; } } /// <since> 1.6 /// </since> public bool InlineReplacesGlobal { set { inlineReplacesGlobal = value; } } private static string GLOBAL_NAMESPACE = ""; private bool registerFromLib = false; /// <summary>Hash of namespace hashes. </summary> private IDictionary namespaceHash; /// <summary>reference to global namespace hash </summary> private IDictionary globalNamespace; /// <summary>set of names of library tempates/namespaces </summary> private Hashtable libraries = new Hashtable(); /* * big switch for namespaces. If true, then properties control * usage. If false, no. */ private bool namespacesOn = true; private bool inlineLocalMode = false; private bool inlineReplacesGlobal = false; /// <summary> Adds the global namespace to the hash.</summary> internal VelocimacroManager(IRuntimeServices rsvc) { InitBlock(); /* * Add the global namespace to the namespace hash. We always have that. */ globalNamespace = AddNamespace(GLOBAL_NAMESPACE); } /// <summary> Adds a VM definition to the cache. /// /// Called by VelocimacroFactory.addVelociMacro (after parsing and discovery in Macro directive) /// /// </summary> /// <param name="vmName">Name of the new VelociMacro. /// </param> /// <param name="macroBody">String representation of the macro body. /// </param> /// <param name="argArray">Array of macro parameters, first parameter is the macro name. /// </param> /// <param name="namespace">The namespace/template from which this macro has been loaded. /// </param> /// <returns> Whether everything went okay. /// </returns> public bool AddVM(string vmName, INode macroBody, string[] argArray, string namespace_Renamed, bool canReplaceGlobalMacro) { if (macroBody == null) { // happens only if someone uses this class without the Macro directive // and provides a null value as an argument throw new System.SystemException("Null AST for " + vmName + " in " + namespace_Renamed); } MacroEntry me = new MacroEntry(vmName, macroBody, argArray, namespace_Renamed); me.FromLibrary = registerFromLib; /* * the client (VMFactory) will signal to us via * registerFromLib that we are in startup mode registering * new VMs from libraries. Therefore, we want to * addto the library map for subsequent auto reloads */ bool isLib = true; MacroEntry exist = (MacroEntry)globalNamespace[vmName]; if (registerFromLib) { libraries.Add(namespace_Renamed, namespace_Renamed); } else { /* * now, we first want to check to see if this namespace (template) * is actually a library - if so, we need to use the global namespace * we don't have to do this when registering, as namespaces should * be shut off. If not, the default value is true, so we still go * global */ isLib = libraries.Contains(namespace_Renamed); } if (!isLib && UsingNamespaces(namespace_Renamed)) { /* * first, do we have a namespace hash already for this namespace? * if not, Add it to the namespaces, and Add the VM */ IDictionary local = GetNamespace(namespace_Renamed, true); local[vmName] = me; return true; } else { /* * otherwise, Add to global template. First, check if we * already have it to preserve some of the autoload information */ if (exist != null) { me.FromLibrary = exist.FromLibrary; } /* * now Add it */ globalNamespace[vmName] = me; return true; } } /// <summary> Gets a VelocimacroProxy object by the name / source template duple. /// /// </summary> /// <param name="vmName">Name of the VelocityMacro to look up. /// </param> /// <param name="namespace">Namespace in which to look up the macro. /// </param> /// <returns> A proxy representing the Macro. /// </returns> public virtual VelocimacroProxy Get(string vmName, string namespace_Renamed) { return (Get(vmName, namespace_Renamed, null)); } /// <summary> Gets a VelocimacroProxy object by the name / source template duple. /// /// </summary> /// <param name="vmName">Name of the VelocityMacro to look up. /// </param> /// <param name="namespace">Namespace in which to look up the macro. /// </param> /// <param name="renderingTemplate">Name of the template we are currently rendering. /// </param> /// <returns> A proxy representing the Macro. /// </returns> /// <since> 1.6 /// </since> public virtual VelocimacroProxy Get(string vmName, string namespace_Renamed, string renderingTemplate) { if (inlineReplacesGlobal && renderingTemplate != null) { /* * if VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL is true (local macros can * override global macros) and we know which template we are rendering at the * moment, check if local namespace contains a macro we are looking for * if so, return it instead of the global one */ IDictionary local = GetNamespace(renderingTemplate, false); if (local != null) { MacroEntry me = (MacroEntry)local[vmName]; if (me != null) { return me.GetProxy(namespace_Renamed); } } } if (UsingNamespaces(namespace_Renamed)) { IDictionary local = GetNamespace(namespace_Renamed, false); /* * if we have macros defined for this template */ if (local != null) { MacroEntry me = (MacroEntry)local[vmName]; if (me != null) { return me.GetProxy(namespace_Renamed); } } } /* * if we didn't return from there, we need to simply see * if it's in the global namespace */ MacroEntry me2 = (MacroEntry)globalNamespace[vmName]; if (me2 != null) { return me2.GetProxy(namespace_Renamed); } return null; } /// <summary> Removes the VMs and the namespace from the manager. /// Used when a template is reloaded to avoid /// losing memory. /// /// </summary> /// <param name="namespace">namespace to dump /// </param> /// <returns> boolean representing success /// </returns> public bool DumpNamespace(string namespace_Renamed) { lock (this) { if (UsingNamespaces(namespace_Renamed)) { object tempObject; tempObject = namespaceHash[namespace_Renamed]; namespaceHash.Remove(namespace_Renamed); IDictionary h = (IDictionary)tempObject; if (h == null) { return false; } h.Clear(); return true; } return false; } } /// <summary> returns the hash for the specified namespace, and if it doesn't exist /// will create a new one and Add it to the namespaces /// /// </summary> /// <param name="namespace"> name of the namespace :) /// </param> /// <param name="addIfNew"> flag to Add a new namespace if it doesn't exist /// </param> /// <returns> namespace Map of VMs or null if doesn't exist /// </returns> private IDictionary GetNamespace(string namespace_Renamed, bool addIfNew) { IDictionary h = (IDictionary)namespaceHash[namespace_Renamed]; if (h == null && addIfNew) { h = AddNamespace(namespace_Renamed); } return h; } /// <summary> adds a namespace to the namespaces /// /// </summary> /// <param name="namespace">name of namespace to Add /// </param> /// <returns> Hash added to namespaces, ready for use /// </returns> private IDictionary AddNamespace(string namespace_Renamed) { IDictionary h = new Hashtable(17, 0.5f); object oh; object tempObject; tempObject = namespaceHash[namespace_Renamed]; namespaceHash[namespace_Renamed] = h; if ((oh = tempObject) != null) { /* * There was already an entry on the table, restore it! * This condition should never occur, given the code * and the fact that this method is private. * But just in case, this way of testing for it is much * more efficient than testing before hand using Get(). */ namespaceHash[namespace_Renamed] = oh; /* * Should't we be returning the old entry (oh)? * The previous code was just returning null in this case. */ return null; } return h; } /// <summary> determines if currently using namespaces. /// /// </summary> /// <param name="namespace">currently ignored /// </param> /// <returns> true if using namespaces, false if not /// </returns> private bool UsingNamespaces(string namespace_Renamed) { /* * if the big switch turns of namespaces, then ignore the rules */ if (!namespacesOn) { return false; } /* * currently, we only support the local template namespace idea */ if (inlineLocalMode) { return true; } return false; } /// <summary> Return the library name for a given macro.</summary> /// <param name="vmName">Name of the Macro to look up. /// </param> /// <param name="namespace">Namespace to look the macro up. /// </param> /// <returns> The name of the library which registered this macro in a namespace. /// </returns> public virtual string GetLibraryName(string vmName, string namespace_Renamed) { if (UsingNamespaces(namespace_Renamed)) { IDictionary local = GetNamespace(namespace_Renamed, false); /* * if we have this macro defined in this namespace, then * it is masking the global, library-based one, so * just return null */ if (local != null) { MacroEntry me = (MacroEntry)local[vmName]; if (me != null) { return null; } } } /* * if we didn't return from there, we need to simply see * if it's in the global namespace */ MacroEntry me2 = (MacroEntry)globalNamespace[vmName]; if (me2 != null) { return me2.SourceTemplate; } return null; } /// <summary> wrapper class for holding VM information</summary> private class MacroEntry { /// <summary> Returns true if the macro was registered from a library.</summary> /// <returns> True if the macro was registered from a library. /// </returns> /// <summary> Has the macro been registered from a library.</summary> /// <param name="fromLibrary">True if the macro was registered from a Library. /// </param> public bool FromLibrary { get { return fromLibrary; } set { this.fromLibrary = value; } } /// <summary> Returns the node tree for this macro.</summary> /// <returns> The node tree for this macro. /// </returns> public SimpleNode NodeTree { get { return nodeTree; } } /// <summary> Returns the source template name for this macro.</summary> /// <returns> The source template name for this macro. /// </returns> public string SourceTemplate { get { return sourceTemplate; } } private string vmName; private string[] argArray; private string sourceTemplate; private SimpleNode nodeTree = null; private bool fromLibrary = false; private VelocimacroProxy vp; internal MacroEntry(string vmName, INode macro, string[] argArray, string sourceTemplate) { this.vmName = vmName; this.argArray = argArray; this.nodeTree = (SimpleNode)macro; this.sourceTemplate = sourceTemplate; vp = new VelocimacroProxy(); vp.SetName(this.vmName); vp.ArgArray = this.argArray; vp.NodeTree = this.nodeTree; } internal VelocimacroProxy GetProxy(string namespace_Renamed) { /* * FIXME: namespace data is omitted, this probably * breaks some Error reporting? */ return vp; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using OLEDB.Test.ModuleCore; using XmlReaderTest.Common; namespace XmlReaderTest.ReaderSettingsTest { public partial class TCDtdProcessingNonCoreReader : TCXMLReaderBaseGeneral { // Type is XmlReaderTest.ReaderSettingsTest.TCDtdProcessingNonCoreReader // Test Case public override void AddChildren() { // for function v0 { this.AddChild(new CVariation(v0) { Attribute = new Variation("Read xml without DTD.Prohibit") { Param = 0 } }); this.AddChild(new CVariation(v0) { Attribute = new Variation("Read xml without DTD.Ignore") { Param = 1 } }); } // for function v1a { this.AddChild(new CVariation(v1a) { Attribute = new Variation("Wrap with Prohibit, xml w/o DTD.Ignore") { Param = 1 } }); this.AddChild(new CVariation(v1a) { Attribute = new Variation("Wrap with Prohibit, xml w/o DTD.Prohibit") { Param = 0 } }); } // for function v1b { this.AddChild(new CVariation(v1b) { Attribute = new Variation("Wrap with Ignore, xml w/o DTD.Ignore") { Param = 1 } }); this.AddChild(new CVariation(v1b) { Attribute = new Variation("Wrap with Ignore, xml w/o DTD.Prohibit") { Param = 0 } }); } // for function v1d { this.AddChild(new CVariation(v1d) { Attribute = new Variation("Wrap with Prohibit, change RS, xml w/o DTD.Prohibit") { Param = 0 } }); this.AddChild(new CVariation(v1d) { Attribute = new Variation("Wrap with Prohibit, change RS, xml w/o DTD.Ignore") { Param = 1 } }); } // for function v1e { this.AddChild(new CVariation(v1e) { Attribute = new Variation("Wrap with Ignore, change RS, xml w/o DTD.Ignore") { Param = 1 } }); this.AddChild(new CVariation(v1e) { Attribute = new Variation("Wrap with Ignore, change RS, xml w/o DTD.Prohibit") { Param = 0 } }); } // for function v2a { this.AddChild(new CVariation(v2a) { Attribute = new Variation("Wrap with Prohibit, xml with DTD.Prohibit") { Param = 0 } }); this.AddChild(new CVariation(v2a) { Attribute = new Variation("Wrap with Prohibit, xml with DTD.Ignore") { Param = 1 } }); } // for function v2b { this.AddChild(new CVariation(v2b) { Attribute = new Variation("Wrap with Ignore, xml with DTD.Ignore") { Param = 1 } }); this.AddChild(new CVariation(v2b) { Attribute = new Variation("Wrap with Ignore, xml with DTD.Prohibit") { Param = 0 } }); } // for function V3 { this.AddChild(new CVariation(V3) { Attribute = new Variation("Testing default values") }); } // for function V4i { this.AddChild(new CVariation(V4i) { Attribute = new Variation("Read xml with invalid content.Prohibit") { Param = 0 } }); this.AddChild(new CVariation(V4i) { Attribute = new Variation("Read xml with invalid content.Ignore") { Param = 1 } }); } // for function V5 { this.AddChild(new CVariation(V5) { Attribute = new Variation("Changing DtdProcessing to Parse, Prohibit.Prohibit") { Param = 0 } }); this.AddChild(new CVariation(V5) { Attribute = new Variation("Changing DtdProcessing to Parse, Prohibit.Ignore") { Param = 1 } }); } // for function V6 { this.AddChild(new CVariation(V6) { Attribute = new Variation("Changing DtdProcessing to Prohibit,Parse.Ignore") { Param = 1 } }); this.AddChild(new CVariation(V6) { Attribute = new Variation("Changing DtdProcessing to Prohibit,Parse.Prohibit") { Param = 0 } }); } // for function V7 { this.AddChild(new CVariation(V7) { Attribute = new Variation("Changing DtdProcessing to Parse, Ignore.Ignore") { Param = 1 } }); this.AddChild(new CVariation(V7) { Attribute = new Variation("Changing DtdProcessing to Parse, Ignore.Prohibit") { Param = 0 } }); } // for function V7a { this.AddChild(new CVariation(V7a) { Attribute = new Variation("Changing DtdProcessing to Prohibit,Ignore.Prohibit") { Param = 0 } }); this.AddChild(new CVariation(V7a) { Attribute = new Variation("Changing DtdProcessing to Prohibit,Ignore.Ignore") { Param = 1 } }); } // for function V8 { this.AddChild(new CVariation(V8) { Attribute = new Variation("Parse a file with external DTD.Prohibit") { Param = 0 } }); this.AddChild(new CVariation(V8) { Attribute = new Variation("Parse a file with external DTD.Ignore") { Param = 1 } }); } // for function V9 { this.AddChild(new CVariation(V9) { Attribute = new Variation("Parse a file with invalid inline DTD.Ignore") { Param = 1 } }); this.AddChild(new CVariation(V9) { Attribute = new Variation("Parse a file with invalid inline DTD.Prohibit") { Param = 0 } }); } // for function V11 { this.AddChild(new CVariation(V11) { Attribute = new Variation("Parse a valid xml with predefined entities with no DTD.Ignore") { Param = 1 } }); this.AddChild(new CVariation(V11) { Attribute = new Variation("Parse a valid xml with predefined entities with no DTD.Prohibit") { Param = 0 } }); } // for function V11a { this.AddChild(new CVariation(V11a) { Attribute = new Variation("Parse a valid xml with entity and DTD.Ignore") { Param = 1 } }); this.AddChild(new CVariation(V11a) { Attribute = new Variation("Parse a valid xml with entity and DTD.Prohibit") { Param = 0 } }); } // for function V11b { this.AddChild(new CVariation(V11b) { Attribute = new Variation("Parse a valid xml with entity in attribute and DTD.Prohibit") { Param = 0 } }); this.AddChild(new CVariation(V11b) { Attribute = new Variation("Parse a valid xml with entity in attribute and DTD.Ignore") { Param = 1 } }); } // for function V11c { this.AddChild(new CVariation(V11c) { Attribute = new Variation("Parse a invalid xml with entity in attribute and DTD.Prohibit") { Param = 0 } }); this.AddChild(new CVariation(V11c) { Attribute = new Variation("Parse a invalid xml with entity in attribute and DTD.Ignore") { Param = 1 } }); } // for function v12 { this.AddChild(new CVariation(v12) { Attribute = new Variation("Set value to Reader.Settings.DtdProcessing.Ignore") { Param = 1 } }); this.AddChild(new CVariation(v12) { Attribute = new Variation("Set value to Reader.Settings.DtdProcessing.Prohibit") { Param = 0 } }); } // for function V14 { this.AddChild(new CVariation(V14) { Attribute = new Variation("DtdProcessing - ArgumentOutOfRangeException") }); } // for function V15 { this.AddChild(new CVariation(V15) { Attribute = new Variation("DtdProcessing - ArgumentOutOfRangeException.Ignore") { Param = 1 } }); this.AddChild(new CVariation(V15) { Attribute = new Variation("DtdProcessing - ArgumentOutOfRangeException.Prohibit") { Param = 0 } }); } // for function V18 { this.AddChild(new CVariation(V18) { Attribute = new Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Prohibit") { Param = 0 } }); this.AddChild(new CVariation(V18) { Attribute = new Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Ignore") { Param = 1 } }); } // for function V19 { this.AddChild(new CVariation(V19) { Attribute = new Variation("6.Parsing invalid DOCTYPE.Ignore") { Params = new object[] { DtdProcessing.Ignore, 6 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("7.Parsing invalid DOCTYPE.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 7 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("7.Parsing invalid DOCTYPE.Ignore") { Params = new object[] { DtdProcessing.Ignore, 7 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("8.Parsing invalid xml version.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 8 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("8.PParsing invalid xml version.Ignore") { Params = new object[] { DtdProcessing.Ignore, 8 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("9.Parsing invalid xml version.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 9 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("9.Parsing invalid xml version.Ignore") { Params = new object[] { DtdProcessing.Ignore, 9 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("10.Parsing invalid xml version.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 10 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("10.Parsing invalid xml version.Ignore") { Params = new object[] { DtdProcessing.Ignore, 10 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("11.Parsing invalid xml version.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 11 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("11.Parsing invalid xml version.Ignore") { Params = new object[] { DtdProcessing.Ignore, 11 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("12.Parsing invalid xml version.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 12 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("12.Parsing invalid xml version.Ignore") { Params = new object[] { DtdProcessing.Ignore, 12 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("1.Parsing invalid DOCTYPE.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 1 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("1.Parsing invalid DOCTYPE.Ignore") { Params = new object[] { DtdProcessing.Ignore, 1 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("6.Parsing invalid DOCTYPE.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 6 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("2.Parsing invalid DOCTYPE.Ignore") { Params = new object[] { DtdProcessing.Ignore, 2 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("3.Parsing invalid DOCTYPE.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 3 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("3.Parsing invalid DOCTYPE.Ignore") { Params = new object[] { DtdProcessing.Ignore, 3 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("4.Parsing invalid DOCTYPE.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 4 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("4.Parsing invalid DOCTYPE.Ignore") { Params = new object[] { DtdProcessing.Ignore, 4 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("2.Parsing invalid DOCTYPE.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 2 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("5.Parsing invalid DOCTYPE.Prohibit") { Params = new object[] { DtdProcessing.Prohibit, 5 } } }); this.AddChild(new CVariation(V19) { Attribute = new Variation("5.Parsing invalid DOCTYPE.Ignore") { Params = new object[] { DtdProcessing.Ignore, 5 } } }); } } } }
using System; using System.Collections.Generic; using it.unifi.dsi.stlab.networkreasoner.model.gas; using System.IO; using it.unifi.dsi.stlab.utilities.value_holders; using System.Globalization; namespace it.unifi.dsi.stlab.networkreasoner.model.textualinterface { public class TextualGheoNetInputParser { Lazy<List<String>> SpecificationLines{ get; set; } public TextualGheoNetInputParser (List<String> lines) { this.SpecificationLines = new Lazy<List<string>> ( () => { var result = new List<String> (); lines.ForEach (line => result.Add (line.Trim ())); return result; } ); } public TextualGheoNetInputParser (FileInfo file) { this.SpecificationLines = new Lazy<List<string>> ( () => { var lines = new List<String> (File.ReadLines (file.FullName)); var result = new List<String> (); lines.ForEach (line => result.Add (line.Trim ())); return result; } ); } public SystemRunnerFromTextualGheoNetInput parse ( SpecificationAssembler aSpecAssembler) { List<NodeSpecificationLine> nodesSpecificationLines; Dictionary<String, Func<ValueHolder<Double>, GasNodeAbstract>> delayedNodesConstruction = this.parseNodeDelayedConstruction ( out nodesSpecificationLines); SystemRunnerFromTextualGheoNetInput systemRunner = aSpecAssembler.assemble ( delayedNodesConstruction, nodesSpecificationLines, this); return systemRunner; } public virtual List<string> fetchRegion (string regionIdentifier, TableHeaderParser tableHeaderParser) { int startNodesRegionIndex = SpecificationLines.Value.FindIndex ( line => line.StartsWith (string.Format ("* {0}", regionIdentifier))); int endNodesRegionIndex = SpecificationLines.Value.FindIndex ( startNodesRegionIndex + 1, line => line.StartsWith ("*")); var region = SpecificationLines.Value.GetRange ( startNodesRegionIndex + 1, endNodesRegionIndex - startNodesRegionIndex - 1); region = tableHeaderParser.parse (region); region.RemoveAll (aLine => string.IsNullOrEmpty (aLine.Replace ("\t", ""))); return region; } protected virtual Dictionary<String, Func<ValueHolder<Double>, GasNodeAbstract>> parseNodeDelayedConstruction ( out List<NodeSpecificationLine> nodesSpecificationLinesOut) { Dictionary<String, Func<ValueHolder<Double>, GasNodeAbstract>> delayConstructedNodes = new Dictionary<string, Func<ValueHolder<Double>, GasNodeAbstract>> (); var nodesSpecificationLines = new List<NodeSpecificationLine> (); var rawNodesSpecificationLines = fetchRegion ("nodes", new TableHeaderParserIgnoreHeader ()); rawNodesSpecificationLines.ForEach (nodeSpecification => { var splittedSpecification = splitOrgRow (nodeSpecification); NodeSpecificationLine semanticLine = new NodeSpecificationLine (); semanticLine.Identifier = splittedSpecification [0]; semanticLine.Height = Convert.ToInt64 (Double.Parse (splittedSpecification [4])); semanticLine.SplittedSpecification = splittedSpecification; semanticLine.Type = splittedSpecification [1].Equals ("1") ? NodeType.WithSupplyGadget : NodeType.WithLoadGadget; Func<ValueHolder<Double>, GasNodeAbstract> delayedConstruction = aValueHolder => { GasNodeAbstract aNode = new GasNodeTopological { Identifier = semanticLine.Identifier, Height = semanticLine.Height }; if (semanticLine.Type == NodeType.WithSupplyGadget) { aNode = new GasNodeWithGadget { Equipped = aNode, Gadget = new GasNodeGadgetSupply { SetupPressure = aValueHolder.getValue () } }; } else if (semanticLine.Type == NodeType.WithLoadGadget) { // if we set a passive node we forget what the caller of this lambda // gives as aDouble because a passive node is characterized by having // a zero load. var loadGadget = Double.Parse (splittedSpecification [2]) == 0.0 ? new GasNodeGadgetLoad{ Load = 0 } : new GasNodeGadgetLoad{ Load = aValueHolder.getValue () }; aNode = new GasNodeWithGadget { Equipped = aNode, Gadget = loadGadget }; } else { throw new ArgumentException (string.Format ( "The specification for node {0} is not correct: impossible " + "to parse neither supply nor load value.", semanticLine.Identifier) ); } return aNode; }; nodesSpecificationLines.Add (semanticLine); delayConstructedNodes.Add (semanticLine.Identifier, delayedConstruction); } ); nodesSpecificationLinesOut = nodesSpecificationLines; return delayConstructedNodes; } public virtual String[] splitOrgRow (String orgTableRow) { return orgTableRow.Replace (" ", string.Empty).Replace ("\t", string.Empty). Split (new []{ '|' }, StringSplitOptions.RemoveEmptyEntries); } internal virtual Dictionary<string, GasEdgeAbstract> parseEdgesRelating ( Dictionary<string, GasNodeAbstract> nodes) { Dictionary<string, GasEdgeAbstract> parsedEdges = new Dictionary<string, GasEdgeAbstract> (); var edgesSpecificationLines = fetchRegion ("edges", new TableHeaderParserIgnoreHeader ()); edgesSpecificationLines.ForEach (edgeSpecification => { var splittedSpecification = splitOrgRow (edgeSpecification); var edgeIdentifier = splittedSpecification [0]; if (nodes.ContainsKey (splittedSpecification [1]) == false) { Console.WriteLine (string.Format ("Start node key {0} not present in node dictionary", splittedSpecification [1])); } if (nodes.ContainsKey (splittedSpecification [2]) == false) { Console.WriteLine (string.Format ("End node key {0} not present in node dictionary", splittedSpecification [2])); } GasEdgeAbstract anEdge = new GasEdgeTopological { Identifier = edgeIdentifier, StartNode = nodes [splittedSpecification [1]], EndNode = nodes [splittedSpecification [2]] }; if (this.doesLineDefineEdgeWithPressureRegulatorGadget (splittedSpecification)) { anEdge = new GasEdgeWithGadget { Equipped = anEdge, Gadget = new GasEdgeGadgetPressureRegulator { MaxFlow = null, MinFlow = null } }; } else { anEdge = new GasEdgePhysical { Described = anEdge, Diameter = parseDoubleCultureInvariant (splittedSpecification [3]).Value, Length = parseDoubleCultureInvariant (splittedSpecification [4]).Value, Roughness = parseDoubleCultureInvariant (splittedSpecification [5]).Value }; } // 9 is the number of field plus one if we want an edge switched off; // this case for now has never been used in any network. if (splittedSpecification.Length.Equals (9) && splittedSpecification [8].Equals ("off")) { anEdge = new GasEdgeWithGadget { Equipped = anEdge, Gadget = new GasEdgeGadgetSwitchOff () }; } parsedEdges.Add (edgeIdentifier, anEdge); } ); return parsedEdges; } internal virtual AmbientParameters parseAmbientParameters () { AmbientParameters result = new AmbientParametersGas (); var ambientParametersSpecificationLines = fetchRegion ("ambient parameters", new TableHeaderParserIgnoreHeader ()); string ambientParametersLine = ambientParametersSpecificationLines [0]; string[] splittedSpecification = splitOrgRow (ambientParametersLine); // parametriCalcoloGas.pressioneAtmosferica result.AirPressureInBar = parseDoubleCultureInvariant ( splittedSpecification [2]).Value * 1e-3; // parametriCalcoloGas.temperaturaAria result.AirTemperatureInKelvin = parseDoubleCultureInvariant ( splittedSpecification [5]).Value + 273.15; result.ElementName = "methane"; // parametriCalcoloGas.temperaturaGas result.ElementTemperatureInKelvin = parseDoubleCultureInvariant ( splittedSpecification [4]).Value + 273.15; // parametriCalcoloGas.pesoMolecolareGas result.MolWeight = parseDoubleCultureInvariant ( splittedSpecification [6]).Value; result.AirMolWeight = parseDoubleCultureInvariant ( splittedSpecification [7]).Value; result.RefPressureInBar = 1.01325; result.RefTemperatureInKelvin = 288.15; // da interfacciare // parametriCalcoloGas.viscositaGas result.ViscosityInPascalTimesSecond = parseDoubleCultureInvariant ( splittedSpecification [9]).Value * 1e-3; return result; } bool doesLineDefineEdgeWithPressureRegulatorGadget (string[] splittedSpecification) { Func<String, Boolean> trimmer = line => line.Trim ().ToLower ().Equals ("r"); return trimmer (splittedSpecification [3]) && trimmer (splittedSpecification [3]) && trimmer (splittedSpecification [3]); } public virtual Nullable<double> parseDoubleCultureInvariant ( String doubleAsString) { Nullable<Double> result = null; double value; if (Double.TryParse (doubleAsString, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out value)) { result = value; } return result; } public virtual bool existsLineSuchThat (Predicate<String> predicate) { return SpecificationLines.Value.Exists (predicate); } } }
// // FormClient.cs // // Author: // Larry Ewing <lewing@novell.com> // Stephane Delcroix <sdelcroix@src.gnome.org> // Stephen Shaw <sshaw@decriptor.com> // // Copyright (C) 2004-2008 Novell, Inc. // Copyright (C) 2004, 2006 Larry Ewing // Copyright (C) 2008 Stephane Delcroix // Copyright (c) 2012 SUSE LINUX Products GmbH, Nuernberg, Germany. // // 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.IO; using System.Net; using System.Text; using System.Web; using FSpot.Core; using Mono.Unix; namespace FSpot.Exporters.Gallery { public class FormClient { private struct FormItem { public string Name; public object Value; public FormItem (string name, object value) { Name = name; Value = value; } } private StreamWriter stream_writer; private List<FormItem> Items; private string boundary; private string start_boundary; private string end_boundary; private bool multipart = false; public bool Multipart { set { multipart = value; } } private bool first_item; public bool Buffer = false; public bool SuppressCookiePath = false; public bool expect_continue = true; public HttpWebRequest Request; public CookieContainer Cookies; public FSpot.ProgressItem Progress; public FormClient (CookieContainer cookies) { this.Cookies = cookies; this.Items = new List<FormItem> (); } public FormClient () { this.Items = new List<FormItem> (); this.Cookies = new CookieContainer (); } private void GenerateBoundary () { Guid guid = Guid.NewGuid (); boundary = "--------" + guid.ToString () + "-----"; start_boundary = "--" + boundary; end_boundary = start_boundary + "--"; } public void Add (string name, string value) { Items.Add (new FormItem (name, value)); } public void Add (string name, FileInfo fileinfo) { multipart = true; Items.Add (new FormItem (name, fileinfo)); } private void Write (FormItem item) { // The types we check here need to match the // types we allow in .Add if (item.Value == null) { Write (item.Name, (string)String.Empty); } else if (item.Value is FileInfo) { Write (item.Name, (FileInfo)item.Value); } else if (item.Value is string) { Write (item.Name, (string)item.Value); } else { throw new Exception ("Unknown value type"); } } private long MultipartLength (FormItem item) { // The types we check here need to match the // types we allow in .Add if (item.Value == null) { return MultipartLength (item.Name, (string)String.Empty); } else if (item.Value is FileInfo) { return MultipartLength (item.Name, (FileInfo)item.Value); } else if (item.Value is string) { return MultipartLength (item.Name, (string)item.Value); } else { throw new Exception ("Unknown value type"); } } private string MultipartHeader (string name, string value) { return string.Format ("{0}\r\n" + "Content-Disposition: form-data; name=\"{1}\"\r\n" + "\r\n", start_boundary, name); } private long MultipartLength (string name, string value) { long length = MultipartHeader (name, value).Length; length += Encoding.Default.GetBytes (value).Length + 2; return length; } private void Write (string name, string value) { string cmd; if (multipart) { cmd = String.Format ("{0}" + "{1}\r\n", MultipartHeader (name, value), value); } else { name = HttpUtility.UrlEncode (name.Replace(" ", "+")); value = HttpUtility.UrlEncode (value.Replace(" ", "+")); if (first_item) { cmd = string.Format ("{0}={1}", name, value); first_item = false; } else { cmd = string.Format ("&{0}={1}", name, value); } } //Console.WriteLine (cmd); stream_writer.Write (cmd); } private string MultipartHeader (string name, FileInfo file) { string cmd = string.Format ("{0}\r\n" + "Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\n" + "Content-Type: image/jpeg\r\n" + "\r\n", start_boundary, name, file.Name); return cmd; } private long MultipartLength (string name, FileInfo file) { long length = MultipartHeader (name, file).Length; length += file.Length + 2; return length; } private void Write (string name, FileInfo file) { if (multipart) { stream_writer.Write (MultipartHeader (name, file)); stream_writer.Flush (); Stream stream = stream_writer.BaseStream; byte [] data = new byte [32768]; FileStream fs = file.OpenRead (); long total = file.Length; long total_read = 0; int count; while ((count = fs.Read (data, 0, data.Length)) > 0) { stream.Write (data, 0, count); total_read += count; if (Progress != null) Progress.Value = total_read / (double)total; } fs.Close (); stream_writer.Write ("\r\n"); } else { throw new Exception ("Can't write files in url-encoded submissions"); } } public void Clear () { Items.Clear (); multipart = false; } public HttpWebResponse Submit (string url, FSpot.ProgressItem progress_item = null) { return Submit (new Uri (url), progress_item); } public HttpWebResponse Submit (Uri uri, FSpot.ProgressItem progress_item = null) { this.Progress = progress_item; Request = (HttpWebRequest) WebRequest.Create (uri); CookieCollection cookie_collection = Cookies.GetCookies (uri); if (uri.UserInfo != null && uri.UserInfo != String.Empty) { NetworkCredential cred = new NetworkCredential (); cred.GetCredential (uri, "basic"); CredentialCache credcache = new CredentialCache(); credcache.Add(uri, "basic", cred); Request.PreAuthenticate = true; Request.Credentials = credcache; } Request.ServicePoint.Expect100Continue = expect_continue; Request.CookieContainer = new CookieContainer (); foreach (Cookie c in cookie_collection) { if (SuppressCookiePath) Request.CookieContainer.Add (new Cookie (c.Name, c.Value)); else Request.CookieContainer.Add (c); } Request.Method = "POST"; Request.Headers["Accept-Charset"] = "utf-8;"; Request.UserAgent = String.Format("F-Spot {0} (http://www.f-spot.org)", Defines.VERSION); if (multipart) { GenerateBoundary (); Request.ContentType = "multipart/form-data; boundary=" + boundary; Request.Timeout = Request.Timeout * 3; long length = 0; for (int i = 0; i < Items.Count; i++) { FormItem item = Items[i]; length += MultipartLength (item); } length += end_boundary.Length + 2; //Request.Headers["My-Content-Length"] = length.ToString (); if (Buffer == false) { Request.ContentLength = length; Request.AllowWriteStreamBuffering = false; } } else { Request.ContentType = "application/x-www-form-urlencoded"; } stream_writer = new StreamWriter (Request.GetRequestStream ()); first_item = true; for (int i = 0; i < Items.Count; i++) { FormItem item = Items[i]; Write (item); } if (multipart) stream_writer.Write (end_boundary + "\r\n"); stream_writer.Flush (); stream_writer.Close (); HttpWebResponse response; try { response = (HttpWebResponse) Request.GetResponse (); //Console.WriteLine ("found {0} cookies", response.Cookies.Count); foreach (Cookie c in response.Cookies) { Cookies.Add (c); } } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.ExpectationFailed && expect_continue) { e.Response.Close (); expect_continue = false; return Submit (uri, progress_item); } throw new WebException (Catalog.GetString ("Unhandled exception"), e); } return response; } } }
#region License /* Copyright (c) 2006 Leslie Sanford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; namespace Sanford.Multimedia.Midi { /// <summary> /// Represents a collection of Tracks. /// </summary> public sealed class Sequence : IComponent, ICollection<Track> { #region Sequence Members #region Fields // The collection of Tracks for the Sequence. private List<Track> tracks = new List<Track>(); // The Sequence's MIDI file properties. private MidiFileProperties properties = new MidiFileProperties(); private BackgroundWorker loadWorker = new BackgroundWorker(); private BackgroundWorker saveWorker = new BackgroundWorker(); private ISite site = null; private bool disposed = false; #endregion #region Events public event EventHandler<AsyncCompletedEventArgs> LoadCompleted; public event ProgressChangedEventHandler LoadProgressChanged; public event EventHandler<AsyncCompletedEventArgs> SaveCompleted; public event ProgressChangedEventHandler SaveProgressChanged; #endregion #region Construction /// <summary> /// Initializes a new instance of the Sequence class. /// </summary> public Sequence() { InitializeBackgroundWorkers(); } /// <summary> /// Initializes a new instance of the Sequence class with the specified division. /// </summary> /// <param name="division"> /// The Sequence's division value. /// </param> public Sequence(int division) { properties.Division = division; properties.Format = 1; InitializeBackgroundWorkers(); } /// <summary> /// Initializes a new instance of the Sequence class with the specified /// file name of the MIDI file to load. /// </summary> /// <param name="fileName"> /// The name of the MIDI file to load. /// </param> public Sequence(string fileName) { InitializeBackgroundWorkers(); Load(fileName); } /// <summary> /// Initializes a new instance of the Sequence class with the specified /// file stream of the MIDI file to load. /// </summary> /// <param name="fileStream"> /// The stream of the MIDI file to load. /// </param> public Sequence(Stream fileStream) { InitializeBackgroundWorkers(); Load(fileStream); } private void InitializeBackgroundWorkers() { loadWorker.DoWork += new DoWorkEventHandler(LoadDoWork); loadWorker.ProgressChanged += new ProgressChangedEventHandler(OnLoadProgressChanged); loadWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnLoadCompleted); loadWorker.WorkerReportsProgress = true; saveWorker.DoWork += new DoWorkEventHandler(SaveDoWork); saveWorker.ProgressChanged += new ProgressChangedEventHandler(OnSaveProgressChanged); saveWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnSaveCompleted); saveWorker.WorkerReportsProgress = true; } #endregion #region Methods /// <summary> /// Loads a MIDI file into the Sequence. /// </summary> /// <param name="fileName"> /// The MIDI file's name. /// </param> public void Load(string fileName) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(IsBusy) { throw new InvalidOperationException(); } else if(fileName == null) { throw new ArgumentNullException("fileName"); } #endregion FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); using(stream) { MidiFileProperties newProperties = new MidiFileProperties(); TrackReader reader = new TrackReader(); List<Track> newTracks = new List<Track>(); newProperties.Read(stream); for(int i = 0; i < newProperties.TrackCount; i++) { reader.Read(stream); newTracks.Add(reader.Track); } properties = newProperties; tracks = newTracks; } #region Ensure Debug.Assert(Count == properties.TrackCount); #endregion } /// <summary> /// Loads a MIDI stream into the Sequence. /// </summary> /// <param name="fileStream"> /// The MIDI file's stream. /// </param> public void Load(Stream fileStream) { #region Require if (disposed) { throw new ObjectDisposedException("Sequence"); } else if (IsBusy) { throw new InvalidOperationException(); } else if (fileStream == null) { throw new ArgumentNullException("fileStream"); } #endregion using (fileStream) { MidiFileProperties newProperties = new MidiFileProperties(); TrackReader reader = new TrackReader(); List<Track> newTracks = new List<Track>(); newProperties.Read(fileStream); for (int i = 0; i < newProperties.TrackCount; i++) { reader.Read(fileStream); newTracks.Add(reader.Track); } properties = newProperties; tracks = newTracks; } #region Ensure Debug.Assert(Count == properties.TrackCount); #endregion } public void LoadAsync(string fileName) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(IsBusy) { throw new InvalidOperationException(); } else if(fileName == null) { throw new ArgumentNullException("fileName"); } #endregion loadWorker.RunWorkerAsync(fileName); } public void LoadAsyncCancel() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion loadWorker.CancelAsync(); } /// <summary> /// Saves the Sequence as a MIDI file. /// </summary> /// <param name="fileName"> /// The name to use for saving the MIDI file. /// </param> public void Save(string fileName) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(fileName == null) { throw new ArgumentNullException("fileName"); } #endregion FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None); using (stream) { Save(stream); } } /// <summary> /// Saves the Sequence as a Stream. /// </summary> /// <param name="stream"> /// The stream to use for saving the sequence. /// </param> public void Save(Stream stream) { properties.Write(stream); TrackWriter writer = new TrackWriter(); foreach(Track trk in tracks) { writer.Track = trk; writer.Write(stream); } } public void SaveAsync(string fileName) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(IsBusy) { throw new InvalidOperationException(); } else if(fileName == null) { throw new ArgumentNullException("fileName"); } #endregion saveWorker.RunWorkerAsync(fileName); } public void SaveAsyncCancel() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion saveWorker.CancelAsync(); } /// <summary> /// Gets the length in ticks of the Sequence. /// </summary> /// <returns> /// The length in ticks of the Sequence. /// </returns> /// <remarks> /// The length in ticks of the Sequence is represented by the Track /// with the longest length. /// </remarks> public int GetLength() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion int length = 0; foreach(Track t in this) { if(t.Length > length) { length = t.Length; } } return length; } private void OnLoadCompleted(object sender, RunWorkerCompletedEventArgs e) { EventHandler<AsyncCompletedEventArgs> handler = LoadCompleted; if(handler != null) { handler(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, null)); } } private void OnLoadProgressChanged(object sender, ProgressChangedEventArgs e) { ProgressChangedEventHandler handler = LoadProgressChanged; if(handler != null) { handler(this, e); } } private void LoadDoWork(object sender, DoWorkEventArgs e) { string fileName = (string)e.Argument; FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); using(stream) { MidiFileProperties newProperties = new MidiFileProperties(); TrackReader reader = new TrackReader(); List<Track> newTracks = new List<Track>(); newProperties.Read(stream); float percentage; for(int i = 0; i < newProperties.TrackCount && !loadWorker.CancellationPending; i++) { reader.Read(stream); newTracks.Add(reader.Track); percentage = (i + 1f) / newProperties.TrackCount; loadWorker.ReportProgress((int)(100 * percentage)); } if(loadWorker.CancellationPending) { e.Cancel = true; } else { properties = newProperties; tracks = newTracks; } } } private void OnSaveCompleted(object sender, RunWorkerCompletedEventArgs e) { EventHandler<AsyncCompletedEventArgs> handler = SaveCompleted; if(handler != null) { handler(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, null)); } } private void OnSaveProgressChanged(object sender, ProgressChangedEventArgs e) { ProgressChangedEventHandler handler = SaveProgressChanged; if(handler != null) { handler(this, e); } } private void SaveDoWork(object sender, DoWorkEventArgs e) { string fileName = (string)e.Argument; FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None); using(stream) { properties.Write(stream); TrackWriter writer = new TrackWriter(); float percentage; for(int i = 0; i < tracks.Count && !saveWorker.CancellationPending; i++) { writer.Track = tracks[i]; writer.Write(stream); percentage = (i + 1f) / properties.TrackCount; saveWorker.ReportProgress((int)(100 * percentage)); } if(saveWorker.CancellationPending) { e.Cancel = true; } } } #endregion #region Properties /// <summary> /// Gets the Track at the specified index. /// </summary> /// <param name="index"> /// The index of the Track to get. /// </param> /// <returns> /// The Track at the specified index. /// </returns> public Track this[int index] { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", index, "Sequence index out of range."); } #endregion return tracks[index]; } } /// <summary> /// Gets the Sequence's division value. /// </summary> public int Division { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return properties.Division; } } /// <summary> /// Gets or sets the Sequence's format value. /// </summary> public int Format { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return properties.Format; } set { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(IsBusy) { throw new InvalidOperationException(); } #endregion properties.Format = value; } } /// <summary> /// Gets the Sequence's type. /// </summary> public SequenceType SequenceType { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return properties.SequenceType; } } public bool IsBusy { get { return loadWorker.IsBusy || saveWorker.IsBusy; } } #endregion #endregion #region ICollection<Track> Members public void Add(Track item) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(item == null) { throw new ArgumentNullException("item"); } #endregion tracks.Add(item); properties.TrackCount = tracks.Count; } public void Clear() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion tracks.Clear(); properties.TrackCount = tracks.Count; } public bool Contains(Track item) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return tracks.Contains(item); } public void CopyTo(Track[] array, int arrayIndex) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion tracks.CopyTo(array, arrayIndex); } public int Count { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return tracks.Count; } } public bool IsReadOnly { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return false; } } public bool Remove(Track item) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion bool result = tracks.Remove(item); if(result) { properties.TrackCount = tracks.Count; } return result; } #endregion #region IEnumerable<Track> Members public IEnumerator<Track> GetEnumerator() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return tracks.GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return tracks.GetEnumerator(); } #endregion #region IComponent Members public event EventHandler Disposed; public ISite Site { get { return site; } set { site = value; } } #endregion #region IDisposable Members public void Dispose() { #region Guard if(disposed) { return; } #endregion loadWorker.Dispose(); saveWorker.Dispose(); disposed = true; EventHandler handler = Disposed; if(handler != null) { handler(this, EventArgs.Empty); } } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="ConversionValueRuleSetServiceClient"/> instances.</summary> public sealed partial class ConversionValueRuleSetServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ConversionValueRuleSetServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ConversionValueRuleSetServiceSettings"/>.</returns> public static ConversionValueRuleSetServiceSettings GetDefault() => new ConversionValueRuleSetServiceSettings(); /// <summary> /// Constructs a new <see cref="ConversionValueRuleSetServiceSettings"/> object with default settings. /// </summary> public ConversionValueRuleSetServiceSettings() { } private ConversionValueRuleSetServiceSettings(ConversionValueRuleSetServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateConversionValueRuleSetsSettings = existing.MutateConversionValueRuleSetsSettings; OnCopy(existing); } partial void OnCopy(ConversionValueRuleSetServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ConversionValueRuleSetServiceClient.MutateConversionValueRuleSets</c> and /// <c>ConversionValueRuleSetServiceClient.MutateConversionValueRuleSetsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateConversionValueRuleSetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ConversionValueRuleSetServiceSettings"/> object.</returns> public ConversionValueRuleSetServiceSettings Clone() => new ConversionValueRuleSetServiceSettings(this); } /// <summary> /// Builder class for <see cref="ConversionValueRuleSetServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class ConversionValueRuleSetServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConversionValueRuleSetServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ConversionValueRuleSetServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ConversionValueRuleSetServiceClientBuilder() { UseJwtAccessWithScopes = ConversionValueRuleSetServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ConversionValueRuleSetServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConversionValueRuleSetServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ConversionValueRuleSetServiceClient Build() { ConversionValueRuleSetServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ConversionValueRuleSetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ConversionValueRuleSetServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ConversionValueRuleSetServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ConversionValueRuleSetServiceClient.Create(callInvoker, Settings); } private async stt::Task<ConversionValueRuleSetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ConversionValueRuleSetServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ConversionValueRuleSetServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ConversionValueRuleSetServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ConversionValueRuleSetServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>ConversionValueRuleSetService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage conversion value rule sets. /// </remarks> public abstract partial class ConversionValueRuleSetServiceClient { /// <summary> /// The default endpoint for the ConversionValueRuleSetService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default ConversionValueRuleSetService scopes.</summary> /// <remarks> /// The default ConversionValueRuleSetService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="ConversionValueRuleSetServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ConversionValueRuleSetServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ConversionValueRuleSetServiceClient"/>.</returns> public static stt::Task<ConversionValueRuleSetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ConversionValueRuleSetServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ConversionValueRuleSetServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ConversionValueRuleSetServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ConversionValueRuleSetServiceClient"/>.</returns> public static ConversionValueRuleSetServiceClient Create() => new ConversionValueRuleSetServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ConversionValueRuleSetServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="ConversionValueRuleSetServiceSettings"/>.</param> /// <returns>The created <see cref="ConversionValueRuleSetServiceClient"/>.</returns> internal static ConversionValueRuleSetServiceClient Create(grpccore::CallInvoker callInvoker, ConversionValueRuleSetServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ConversionValueRuleSetService.ConversionValueRuleSetServiceClient grpcClient = new ConversionValueRuleSetService.ConversionValueRuleSetServiceClient(callInvoker); return new ConversionValueRuleSetServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC ConversionValueRuleSetService client</summary> public virtual ConversionValueRuleSetService.ConversionValueRuleSetServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateConversionValueRuleSetsResponse MutateConversionValueRuleSets(MutateConversionValueRuleSetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionValueRuleSetsResponse> MutateConversionValueRuleSetsAsync(MutateConversionValueRuleSetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionValueRuleSetsResponse> MutateConversionValueRuleSetsAsync(MutateConversionValueRuleSetsRequest request, st::CancellationToken cancellationToken) => MutateConversionValueRuleSetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion value rule sets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion value rule sets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateConversionValueRuleSetsResponse MutateConversionValueRuleSets(string customerId, scg::IEnumerable<ConversionValueRuleSetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateConversionValueRuleSets(new MutateConversionValueRuleSetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion value rule sets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion value rule sets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionValueRuleSetsResponse> MutateConversionValueRuleSetsAsync(string customerId, scg::IEnumerable<ConversionValueRuleSetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateConversionValueRuleSetsAsync(new MutateConversionValueRuleSetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion value rule sets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion value rule sets. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionValueRuleSetsResponse> MutateConversionValueRuleSetsAsync(string customerId, scg::IEnumerable<ConversionValueRuleSetOperation> operations, st::CancellationToken cancellationToken) => MutateConversionValueRuleSetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ConversionValueRuleSetService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage conversion value rule sets. /// </remarks> public sealed partial class ConversionValueRuleSetServiceClientImpl : ConversionValueRuleSetServiceClient { private readonly gaxgrpc::ApiCall<MutateConversionValueRuleSetsRequest, MutateConversionValueRuleSetsResponse> _callMutateConversionValueRuleSets; /// <summary> /// Constructs a client wrapper for the ConversionValueRuleSetService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="ConversionValueRuleSetServiceSettings"/> used within this client. /// </param> public ConversionValueRuleSetServiceClientImpl(ConversionValueRuleSetService.ConversionValueRuleSetServiceClient grpcClient, ConversionValueRuleSetServiceSettings settings) { GrpcClient = grpcClient; ConversionValueRuleSetServiceSettings effectiveSettings = settings ?? ConversionValueRuleSetServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateConversionValueRuleSets = clientHelper.BuildApiCall<MutateConversionValueRuleSetsRequest, MutateConversionValueRuleSetsResponse>(grpcClient.MutateConversionValueRuleSetsAsync, grpcClient.MutateConversionValueRuleSets, effectiveSettings.MutateConversionValueRuleSetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateConversionValueRuleSets); Modify_MutateConversionValueRuleSetsApiCall(ref _callMutateConversionValueRuleSets); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateConversionValueRuleSetsApiCall(ref gaxgrpc::ApiCall<MutateConversionValueRuleSetsRequest, MutateConversionValueRuleSetsResponse> call); partial void OnConstruction(ConversionValueRuleSetService.ConversionValueRuleSetServiceClient grpcClient, ConversionValueRuleSetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ConversionValueRuleSetService client</summary> public override ConversionValueRuleSetService.ConversionValueRuleSetServiceClient GrpcClient { get; } partial void Modify_MutateConversionValueRuleSetsRequest(ref MutateConversionValueRuleSetsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateConversionValueRuleSetsResponse MutateConversionValueRuleSets(MutateConversionValueRuleSetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateConversionValueRuleSetsRequest(ref request, ref callSettings); return _callMutateConversionValueRuleSets.Sync(request, callSettings); } /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateConversionValueRuleSetsResponse> MutateConversionValueRuleSetsAsync(MutateConversionValueRuleSetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateConversionValueRuleSetsRequest(ref request, ref callSettings); return _callMutateConversionValueRuleSets.Async(request, callSettings); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using JavaJanitor.Areas.HelpPage.ModelDescriptions; using JavaJanitor.Areas.HelpPage.Models; namespace JavaJanitor.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Runtime.Remoting { using System.Globalization; using System.Runtime.Remoting; using System.Runtime.Remoting.Contexts; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Activation; using System.Runtime.Remoting.Lifetime; using System.Security.Cryptography; using Microsoft.Win32; using System.Threading; using System; // Identity is the base class for remoting identities. An instance of Identity (or a derived class) // is associated with each instance of a remoted object. Likewise, an instance of Identity is // associated with each instance of a remoting proxy. // using System.Collections; internal class Identity { // We use a Guid to create a URI from. Each time a new URI is needed we increment // the sequence number and append it to the statically inited Guid. // private static readonly Guid IDGuid = Guid.NewGuid(); internal static String ProcessIDGuid { get { return SharedStatics.Remoting_Identity_IDGuid; } } // We need the original and the configured one because we have to compare // both when looking at a uri since something might be marshalled before // the id is set. private static String s_originalAppDomainGuid = Guid.NewGuid().ToString().Replace('-', '_'); private static String s_configuredAppDomainGuid = null; internal static String AppDomainUniqueId { get { if (s_configuredAppDomainGuid != null) return s_configuredAppDomainGuid; else return s_originalAppDomainGuid; } // get } // AppDomainGuid private static String s_originalAppDomainGuidString = "/" + s_originalAppDomainGuid.ToLower(CultureInfo.InvariantCulture) + "/"; private static String s_configuredAppDomainGuidString = null; private static String s_IDGuidString = "/" + s_originalAppDomainGuid.ToLower(CultureInfo.InvariantCulture) + "/"; // Used to get random numbers private static RNGCryptoServiceProvider s_rng = new RNGCryptoServiceProvider(); internal static String IDGuidString { get { return s_IDGuidString; } } internal static String RemoveAppNameOrAppGuidIfNecessary(String uri) { // uri is assumed to be in lower-case at this point // If the uri starts with either, "/<appname>/" or "/<appdomainguid>/" we // should strip that off. // We only need to look further if the uri starts with a "/". if ((uri == null) || (uri.Length <= 1) || (uri[0] != '/')) return uri; // compare to process guid (guid string already has slash at beginnning and end) String guidStr; if (s_configuredAppDomainGuidString != null) { guidStr = s_configuredAppDomainGuidString; if (uri.Length > guidStr.Length) { if (StringStartsWith(uri, guidStr)) { // remove "/<appdomainguid>/" return uri.Substring(guidStr.Length); } } } // always need to check original guid as well in case the object with this // uri was marshalled before we changed the app domain id guidStr = s_originalAppDomainGuidString; if (uri.Length > guidStr.Length) { if (StringStartsWith(uri, guidStr)) { // remove "/<appdomainguid>/" return uri.Substring(guidStr.Length); } } // compare to application name (application name will never have slashes) String appName = RemotingConfiguration.ApplicationName; if (appName != null) { // add +2 to appName length for surrounding slashes if (uri.Length > (appName.Length + 2)) { if (String.Compare(uri, 1, appName, 0, appName.Length, true, CultureInfo.InvariantCulture) == 0) { // now, make sure there is a slash after "/<appname>" in uri if (uri[appName.Length + 1] == '/') { // remove "/<appname>/" return uri.Substring(appName.Length + 2); } } } } // it didn't start with "/<appname>/" or "/<processguid>/", so just remove the // first slash and return. uri = uri.Substring(1); return uri; } // RemoveAppNameOrAppGuidIfNecessary private static bool StringStartsWith(String s1, String prefix) { // String.StartsWith uses String.Compare instead of String.CompareOrdinal, // so we provide our own implementation of StartsWith. if (s1.Length < prefix.Length) return false; return (String.CompareOrdinal(s1, 0, prefix, 0, prefix.Length) == 0); } // StringStartsWith // DISCONNECTED_FULL denotes that the object is disconnected // from both local & remote (x-appdomain & higher) clients // DISCONNECTED_REM denotes that the object is disconnected // from remote (x-appdomain & higher) clients ... however // x-context proxies continue to work as expected. protected const int IDFLG_DISCONNECTED_FULL= 0x00000001; protected const int IDFLG_DISCONNECTED_REM = 0x00000002; protected const int IDFLG_IN_IDTABLE = 0x00000004; protected const int IDFLG_CONTEXT_BOUND = 0x00000010; protected const int IDFLG_WELLKNOWN = 0x00000100; protected const int IDFLG_SERVER_SINGLECALL= 0x00000200; protected const int IDFLG_SERVER_SINGLETON = 0x00000400; internal int _flags; internal Object _tpOrObject; protected String _ObjURI; protected String _URL; // These have to be "Object" to use Interlocked operations internal Object _objRef; internal Object _channelSink; // Remoting proxy has this field too, we use the latter only for // ContextBoundObject identities. internal Object _envoyChain; // This manages the dynamically registered sinks for the proxy. internal DynamicPropertyHolder _dph; // Lease for object internal Lease _lease; // Set when Identity is initializing and not yet ready for use. private volatile bool _initializing; internal static String ProcessGuid {get {return ProcessIDGuid;}} private static int GetNextSeqNum() { return SharedStatics.Remoting_Identity_GetNextSeqNum(); } private static Byte[] GetRandomBytes() { // PERF? In a situation where objects need URIs at a very fast // rate, we will end up creating too many of these tiny byte-arrays // causing pressure on GC! // One option would be to have a buff in the managed thread class // and use that to get a chunk of random bytes consuming // 18 bytes at a time. // This would avoid the need to have a lock across threads. Byte[] randomBytes = new byte[18]; s_rng.GetBytes(randomBytes); return randomBytes; } // Constructs a new identity using the given the URI. This is used for // creating client side identities. // // internal Identity(String objURI, String URL) { BCLDebug.Assert(objURI!=null,"objURI should not be null here"); if (URL != null) { _flags |= IDFLG_WELLKNOWN; _URL = URL; } SetOrCreateURI(objURI, true /*calling from ID ctor*/); } // Constructs a new identity. This is used for creating server side // identities. The URI for server side identities is lazily generated // during the first call to Marshal because if we associate a URI with the // object at the time of creation then you cannot call Marshal with a // URI of your own choice. // // internal Identity(bool bContextBound) { if(bContextBound) _flags |= IDFLG_CONTEXT_BOUND; } internal bool IsContextBound { get { return (_flags&IDFLG_CONTEXT_BOUND) == IDFLG_CONTEXT_BOUND; } } internal bool IsInitializing { get { return (_initializing); } set { _initializing = value; } } internal bool IsWellKnown() { return (_flags&IDFLG_WELLKNOWN) == IDFLG_WELLKNOWN; } internal void SetInIDTable() { while(true) { int currentFlags = _flags; int newFlags = _flags | IDFLG_IN_IDTABLE; if(currentFlags == Interlocked.CompareExchange(ref _flags, newFlags, currentFlags)) break; } } [System.Security.SecurityCritical] // auto-generated internal void ResetInIDTable(bool bResetURI) { BCLDebug.Assert(IdentityHolder.TableLock.IsWriterLockHeld, "IDTable should be write-locked"); while(true) { int currentFlags = _flags; int newFlags = _flags & (~IDFLG_IN_IDTABLE); if(currentFlags == Interlocked.CompareExchange(ref _flags, newFlags, currentFlags)) break; } // bResetURI is true for the external API call to Disconnect, it is // false otherwise. Thus when a user Disconnects an object // its URI will get reset but if lifetime service times it out // it will not clear out the URIs if (bResetURI) { ((ObjRef)_objRef).URI = null; _ObjURI = null; } } internal bool IsInIDTable() { return((_flags & IDFLG_IN_IDTABLE) == IDFLG_IN_IDTABLE); } internal void SetFullyConnected() { BCLDebug.Assert( this is ServerIdentity, "should be setting these flags for srvIDs only!"); BCLDebug.Assert( (_ObjURI != null), "Object must be assigned a URI to be fully connected!"); while(true) { int currentFlags = _flags; int newFlags = _flags & (~(IDFLG_DISCONNECTED_FULL | IDFLG_DISCONNECTED_REM)); if(currentFlags == Interlocked.CompareExchange(ref _flags, newFlags, currentFlags)) break; } } internal bool IsFullyDisconnected() { BCLDebug.Assert( this is ServerIdentity, "should be setting these flags for srvIDs only!"); return (_flags&IDFLG_DISCONNECTED_FULL) == IDFLG_DISCONNECTED_FULL; } internal bool IsRemoteDisconnected() { BCLDebug.Assert( this is ServerIdentity, "should be setting these flags for srvIDs only!"); return (_flags&IDFLG_DISCONNECTED_REM) == IDFLG_DISCONNECTED_REM; } internal bool IsDisconnected() { BCLDebug.Assert( this is ServerIdentity, "should be setting these flags for srvIDs only!"); return (IsFullyDisconnected() || IsRemoteDisconnected()); } // Get the URI internal String URI { get { if(IsWellKnown()) { return _URL; } else { return _ObjURI; } } } internal String ObjURI { get { return _ObjURI; } } internal MarshalByRefObject TPOrObject { get { return (MarshalByRefObject) _tpOrObject; } } // Set the transparentProxy field protecting against ----s. The returned transparent // proxy could be different than the one the caller is attempting to set. // internal Object RaceSetTransparentProxy(Object tpObj) { if (_tpOrObject == null) Interlocked.CompareExchange(ref _tpOrObject, tpObj, null); return _tpOrObject; } // Get the ObjRef. internal ObjRef ObjectRef { [System.Security.SecurityCritical] // auto-generated get { return (ObjRef) _objRef; } } // Set the objRef field protecting against ----s. The returned objRef // could be different than the one the caller is attempting to set. // [System.Security.SecurityCritical] // auto-generated internal ObjRef RaceSetObjRef(ObjRef objRefGiven) { if (_objRef == null) { Interlocked.CompareExchange(ref _objRef, objRefGiven, null); } return (ObjRef) _objRef; } // Get the ChannelSink. internal IMessageSink ChannelSink { get { return (IMessageSink) _channelSink;} } // Set the channelSink field protecting against ----s. The returned // channelSink proxy could be different than the one the caller is // attempting to set. // internal IMessageSink RaceSetChannelSink(IMessageSink channelSink) { if (_channelSink == null) { Interlocked.CompareExchange( ref _channelSink, channelSink, null); } return (IMessageSink) _channelSink; } // Get/Set the Envoy Sink chain.. internal IMessageSink EnvoyChain { get { return (IMessageSink)_envoyChain; } } // Get/Set Lease internal Lease Lease { get { return _lease; } set { _lease = value; } } // Set the channelSink field protecting against ----s. The returned // channelSink proxy could be different than the one the caller is // attempting to set. // internal IMessageSink RaceSetEnvoyChain( IMessageSink envoyChain) { if (_envoyChain == null) { Interlocked.CompareExchange( ref _envoyChain, envoyChain, null); } return (IMessageSink) _envoyChain; } // A URI is lazily generated for the identity based on a GUID. // Well known objects supply their own URI internal void SetOrCreateURI(String uri) { SetOrCreateURI(uri, false); } internal void SetOrCreateURI(String uri, bool bIdCtor) { if(bIdCtor == false) { // This method is called either from the ID Constructor or // with a writeLock on the ID Table BCLDebug.Assert(IdentityHolder.TableLock.IsWriterLockHeld, "IDTable should be write-locked"); if (null != _ObjURI) { throw new RemotingException( Environment.GetResourceString("Remoting_SetObjectUriForMarshal__UriExists")); } } if(null == uri) { // We insert the tick count, so that the uri is not 100% predictable. // (i.e. perhaps we should consider using a random number as well) String random = System.Convert.ToBase64String(GetRandomBytes()); // Need to replace the '/' with '_' since '/' is not a valid uri char _ObjURI = (IDGuidString + random.Replace('/', '_') + "_" + GetNextSeqNum().ToString(CultureInfo.InvariantCulture.NumberFormat) + ".rem").ToLower(CultureInfo.InvariantCulture); } else { if (this is ServerIdentity) _ObjURI = IDGuidString + uri; else _ObjURI = uri; } } // SetOrCreateURI // This is used by ThreadAffinity/Synchronization contexts // (Shares the seqNum space with URIs) internal static String GetNewLogicalCallID() { return IDGuidString + GetNextSeqNum(); } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.Conditional("_DEBUG")] internal virtual void AssertValid() { if (URI != null) { Identity resolvedIdentity = IdentityHolder.ResolveIdentity(URI); BCLDebug.Assert( (resolvedIdentity == null) || (resolvedIdentity == this), "Server ID mismatch with URI"); } } [System.Security.SecurityCritical] // auto-generated internal bool AddProxySideDynamicProperty(IDynamicProperty prop) { lock(this) { if (_dph == null) { DynamicPropertyHolder dph = new DynamicPropertyHolder(); lock(this) { if (_dph == null) { _dph = dph; } } } return _dph.AddDynamicProperty(prop); } } [System.Security.SecurityCritical] // auto-generated internal bool RemoveProxySideDynamicProperty(String name) { lock(this) { if (_dph == null) { throw new RemotingException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Contexts_NoProperty"), name)); } return _dph.RemoveDynamicProperty(name); } } internal ArrayWithSize ProxySideDynamicSinks { [System.Security.SecurityCritical] // auto-generated get { if (_dph == null) { return null; } else { return _dph.DynamicSinks; } } } #if _DEBUG public override String ToString() { return ("IDENTITY: " + " URI = " + _ObjURI); } #endif } }
using J2N.Text; using System; using System.Diagnostics.CodeAnalysis; using System.Text; using WritableArrayAttribute = Lucene.Net.Support.WritableArrayAttribute; namespace Lucene.Net.Analysis.TokenAttributes { /* * 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 ArrayUtil = Lucene.Net.Util.ArrayUtil; using Attribute = Lucene.Net.Util.Attribute; using BytesRef = Lucene.Net.Util.BytesRef; using IAttribute = Lucene.Net.Util.IAttribute; using IAttributeReflector = Lucene.Net.Util.IAttributeReflector; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using UnicodeUtil = Lucene.Net.Util.UnicodeUtil; /// <summary> /// Default implementation of <see cref="ICharTermAttribute"/>. </summary> public class CharTermAttribute : Attribute, ICharTermAttribute, ITermToBytesRefAttribute, IAppendable #if FEATURE_CLONEABLE , System.ICloneable #endif { private const int MIN_BUFFER_SIZE = 10; private char[] termBuffer = CreateBuffer(MIN_BUFFER_SIZE); private int termLength = 0; /// <summary> /// Initialize this attribute with empty term text </summary> public CharTermAttribute() { } // LUCENENET specific - ICharSequence member from J2N bool ICharSequence.HasValue => termBuffer != null; public void CopyBuffer(char[] buffer, int offset, int length) { GrowTermBuffer(length); Array.Copy(buffer, offset, termBuffer, 0, length); termLength = length; } char[] ICharTermAttribute.Buffer => termBuffer; [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public char[] Buffer => termBuffer; public char[] ResizeBuffer(int newSize) { if (termBuffer.Length < newSize) { // Not big enough; create a new array with slight // over allocation and preserve content // LUCENENET: Resize rather than copy Array.Resize(ref termBuffer, ArrayUtil.Oversize(newSize, RamUsageEstimator.NUM_BYTES_CHAR)); } return termBuffer; } private void GrowTermBuffer(int newSize) { if (termBuffer.Length < newSize) { // Not big enough; create a new array with slight // over allocation: termBuffer = new char[ArrayUtil.Oversize(newSize, RamUsageEstimator.NUM_BYTES_CHAR)]; } } int ICharTermAttribute.Length { get => Length; set => SetLength(value); } int ICharSequence.Length => Length; public int Length { get => termLength; set => SetLength(value); } public CharTermAttribute SetLength(int length) { if (length > termBuffer.Length) { throw new ArgumentException("length " + length + " exceeds the size of the termBuffer (" + termBuffer.Length + ")"); } termLength = length; return this; } public CharTermAttribute SetEmpty() { termLength = 0; return this; } // *** TermToBytesRefAttribute interface *** private BytesRef bytes = new BytesRef(MIN_BUFFER_SIZE); public virtual void FillBytesRef() { UnicodeUtil.UTF16toUTF8(termBuffer, 0, termLength, bytes); } public virtual BytesRef BytesRef => bytes; // *** CharSequence interface *** // LUCENENET specific: Replaced with this[int] to .NETify //public char CharAt(int index) //{ // if (index >= TermLength) // { // throw new IndexOutOfRangeException(); // } // return TermBuffer[index]; //} char ICharSequence.this[int index] => this[index]; char ICharTermAttribute.this[int index] { get => this[index]; set => this[index] = value; } // LUCENENET specific indexer to make CharTermAttribute act more like a .NET type public char this[int index] { get { if (index < 0 || index >= termLength) // LUCENENET: Added better bounds checking { throw new ArgumentOutOfRangeException(nameof(index)); } return termBuffer[index]; } set { if (index < 0 || index >= termLength) { throw new ArgumentOutOfRangeException(nameof(index)); // LUCENENET: Added better bounds checking } termBuffer[index] = value; } } public ICharSequence Subsequence(int startIndex, int length) { // From Apache Harmony String class if (termBuffer == null || (startIndex == 0 && length == termBuffer.Length)) { return new CharArrayCharSequence(termBuffer); } if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); if (startIndex + length > Length) throw new ArgumentOutOfRangeException("", $"{nameof(startIndex)} + {nameof(length)} > {nameof(Length)}"); char[] result = new char[length]; for (int i = 0, j = startIndex; i < length; i++, j++) result[i] = termBuffer[j]; return new CharArrayCharSequence(result); } // *** Appendable interface *** public CharTermAttribute Append(string value, int startIndex, int charCount) { // LUCENENET: Changed semantics to be the same as the StringBuilder in .NET if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount)); if (value == null) { if (startIndex == 0 && charCount == 0) return this; throw new ArgumentNullException(nameof(value)); } if (charCount == 0) return this; if (startIndex > value.Length - charCount) throw new ArgumentOutOfRangeException(nameof(startIndex)); value.CopyTo(startIndex, InternalResizeBuffer(termLength + charCount), termLength, charCount); Length += charCount; return this; } public CharTermAttribute Append(char value) { ResizeBuffer(termLength + 1)[termLength++] = value; return this; } public CharTermAttribute Append(char[] value) { if (value == null) //return AppendNull(); return this; // No-op int len = value.Length; value.CopyTo(InternalResizeBuffer(termLength + len), termLength); Length += len; return this; } public CharTermAttribute Append(char[] value, int startIndex, int charCount) { // LUCENENET: Changed semantics to be the same as the StringBuilder in .NET if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount)); if (value == null) { if (startIndex == 0 && charCount == 0) return this; throw new ArgumentNullException(nameof(value)); } if (charCount == 0) return this; if (startIndex > value.Length - charCount) throw new ArgumentOutOfRangeException(nameof(startIndex)); Array.Copy(value, startIndex, InternalResizeBuffer(termLength + charCount), termLength, charCount); Length += charCount; return this; } public CharTermAttribute Append(string value) { return Append(value, 0, value == null ? 0 : value.Length); } public CharTermAttribute Append(StringBuilder value) { if (value == null) // needed for Appendable compliance { //return AppendNull(); return this; // No-op } return Append(value.ToString()); } public CharTermAttribute Append(StringBuilder value, int startIndex, int charCount) { // LUCENENET: Changed semantics to be the same as the StringBuilder in .NET if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount)); if (value == null) { if (startIndex == 0 && charCount == 0) return this; throw new ArgumentNullException(nameof(value)); } if (charCount == 0) return this; if (startIndex > value.Length - charCount) throw new ArgumentOutOfRangeException(nameof(startIndex)); return Append(value.ToString(startIndex, charCount)); } public CharTermAttribute Append(ICharTermAttribute value) { if (value == null) // needed for Appendable compliance { //return AppendNull(); return this; // No-op } int len = value.Length; Array.Copy(value.Buffer, 0, ResizeBuffer(termLength + len), termLength, len); termLength += len; return this; } public CharTermAttribute Append(ICharSequence value) { if (value == null) //return AppendNull(); return this; // No-op return Append(value, 0, value.Length); } public CharTermAttribute Append(ICharSequence value, int startIndex, int charCount) { // LUCENENET: Changed semantics to be the same as the StringBuilder in .NET if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount)); if (value == null) { if (startIndex == 0 && charCount == 0) return this; throw new ArgumentNullException(nameof(value)); } if (charCount == 0) return this; if (startIndex > value.Length - charCount) throw new ArgumentOutOfRangeException(nameof(startIndex)); ResizeBuffer(termLength + charCount); for (int i = 0; i < charCount; i++) termBuffer[termLength++] = value[startIndex + i]; return this; } private char[] InternalResizeBuffer(int length) { if (termBuffer.Length < length) { char[] newBuffer = CreateBuffer(length); Array.Copy(termBuffer, 0, newBuffer, 0, termBuffer.Length); this.termBuffer = newBuffer; } return termBuffer; } private static char[] CreateBuffer(int length) { return new char[ArrayUtil.Oversize(length, RamUsageEstimator.NUM_BYTES_CHAR)]; } // LUCENENET: Not used - we are doing a no-op when the value is null //private CharTermAttribute AppendNull() //{ // ResizeBuffer(termLength + 4); // termBuffer[termLength++] = 'n'; // termBuffer[termLength++] = 'u'; // termBuffer[termLength++] = 'l'; // termBuffer[termLength++] = 'l'; // return this; //} // *** Attribute *** public override int GetHashCode() { int code = termLength; code = code * 31 + ArrayUtil.GetHashCode(termBuffer, 0, termLength); return code; } public override void Clear() { termLength = 0; } public override object Clone() { CharTermAttribute t = (CharTermAttribute)base.Clone(); // Do a deep clone t.termBuffer = new char[this.termLength]; Array.Copy(this.termBuffer, 0, t.termBuffer, 0, this.termLength); t.bytes = BytesRef.DeepCopyOf(bytes); return t; } public override bool Equals(object other) { if (other == this) { return true; } if (other is CharTermAttribute o) { if (termLength != o.termLength) { return false; } for (int i = 0; i < termLength; i++) { if (termBuffer[i] != o.termBuffer[i]) { return false; } } return true; } return false; } /// <summary> /// Returns solely the term text as specified by the /// <see cref="ICharSequence"/> interface. /// <para/> /// this method changed the behavior with Lucene 3.1, /// before it returned a String representation of the whole /// term with all attributes. /// this affects especially the /// <see cref="Lucene.Net.Analysis.Token"/> subclass. /// </summary> public override string ToString() { return new string(termBuffer, 0, termLength); } public override void ReflectWith(IAttributeReflector reflector) { reflector.Reflect(typeof(ICharTermAttribute), "term", ToString()); FillBytesRef(); reflector.Reflect(typeof(ITermToBytesRefAttribute), "bytes", BytesRef.DeepCopyOf(bytes)); } public override void CopyTo(IAttribute target) { CharTermAttribute t = (CharTermAttribute)target; t.CopyBuffer(termBuffer, 0, termLength); } #region ICharTermAttribute Members void ICharTermAttribute.CopyBuffer(char[] buffer, int offset, int length) => CopyBuffer(buffer, offset, length); char[] ICharTermAttribute.ResizeBuffer(int newSize) => ResizeBuffer(newSize); ICharTermAttribute ICharTermAttribute.SetLength(int length) => SetLength(length); ICharTermAttribute ICharTermAttribute.SetEmpty() => SetEmpty(); ICharTermAttribute ICharTermAttribute.Append(ICharSequence value) => Append(value); ICharTermAttribute ICharTermAttribute.Append(ICharSequence value, int startIndex, int count) => Append(value, startIndex, count); ICharTermAttribute ICharTermAttribute.Append(char value) => Append(value); ICharTermAttribute ICharTermAttribute.Append(char[] value) => Append(value); ICharTermAttribute ICharTermAttribute.Append(char[] value, int startIndex, int count) => Append(value, startIndex, count); ICharTermAttribute ICharTermAttribute.Append(string value) => Append(value); ICharTermAttribute ICharTermAttribute.Append(string value, int startIndex, int count) => Append(value, startIndex, count); ICharTermAttribute ICharTermAttribute.Append(StringBuilder value) => Append(value); ICharTermAttribute ICharTermAttribute.Append(StringBuilder value, int startIndex, int count) => Append(value, startIndex, count); ICharTermAttribute ICharTermAttribute.Append(ICharTermAttribute value) => Append(value); #endregion #region IAppendable Members IAppendable IAppendable.Append(char value) => Append(value); IAppendable IAppendable.Append(string value) => Append(value); IAppendable IAppendable.Append(string value, int startIndex, int count) => Append(value, startIndex, count); IAppendable IAppendable.Append(StringBuilder value) => Append(value); IAppendable IAppendable.Append(StringBuilder value, int startIndex, int count) => Append(value, startIndex, count); IAppendable IAppendable.Append(char[] value) => Append(value); IAppendable IAppendable.Append(char[] value, int startIndex, int count) => Append(value, startIndex, count); IAppendable IAppendable.Append(ICharSequence value) => Append(value); IAppendable IAppendable.Append(ICharSequence value, int startIndex, int count) => Append(value, startIndex, count); #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 provides an implementation of the pieces of the Marshal class which are required by the Interop // API contract but are not provided by the version of Marshal which is part of the Redhawk test library. // This partial class is combined with the version from the Redhawk test library, in order to provide the // Marshal implementation for System.Private.CoreLib. // using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Reflection; #if ENABLE_WINRT using System.Runtime.InteropServices.ComTypes; #endif //ENABLE_WINRT namespace System.Runtime.InteropServices { public static partial class Marshal { private const long HIWORDMASK = unchecked((long)0xffffffffffff0000L); // Win32 has the concept of Atoms, where a pointer can either be a pointer // or an int. If it's less than 64K, this is guaranteed to NOT be a // pointer since the bottom 64K bytes are reserved in a process' page table. // We should be careful about deallocating this stuff. Extracted to // a function to avoid C# problems with lack of support for IntPtr. // We have 2 of these methods for slightly different semantics for NULL. private static bool IsWin32Atom(IntPtr ptr) { long lPtr = (long)ptr; return 0 == (lPtr & HIWORDMASK); } private static bool IsNotWin32Atom(IntPtr ptr) { long lPtr = (long)ptr; return 0 != (lPtr & HIWORDMASK); } //==================================================================== // The default character size for the system. This is always 2 because // the framework only runs on UTF-16 systems. //==================================================================== public static readonly int SystemDefaultCharSize = 2; //==================================================================== // The max DBCS character size for the system. //==================================================================== public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize(); //==================================================================== // Helper method to retrieve the system's maximum DBCS character size. //==================================================================== private static unsafe int GetSystemMaxDBCSCharSize() { ExternalInterop.CPINFO cpInfo; if (ExternalInterop.GetCPInfo(ExternalInterop.Constants.CP_ACP, &cpInfo) != 0) { return cpInfo.MaxCharSize; } else { return 2; } } public unsafe static String PtrToStringAnsi(IntPtr ptr) { if (IntPtr.Zero == ptr) { return null; } else if (IsWin32Atom(ptr)) { return null; } else { int nb = lstrlenA(ptr); if (nb == 0) { return string.Empty; } else { return ConvertToUnicode(ptr, nb); } } } public unsafe static String PtrToStringAnsi(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) throw new ArgumentNullException("ptr"); if (len < 0) throw new ArgumentException("len"); return ConvertToUnicode(ptr, len); } public unsafe static String PtrToStringUni(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) throw new ArgumentNullException("ptr"); if (len < 0) throw new ArgumentException("len"); return new String((char*)ptr, 0, len); } public unsafe static String PtrToStringUni(IntPtr ptr) { if (IntPtr.Zero == ptr) { return null; } else if (IsWin32Atom(ptr)) { return null; } else { return new String((char*)ptr); } } //==================================================================== // SizeOf() //==================================================================== /// <summary> /// Returns the size of an instance of a value type. /// </summary> public static int SizeOf<T>() { return SizeOf(typeof(T)); } public static int SizeOf<T>(T structure) { return SizeOf<T>(); } public static int SizeOf(Object structure) { if (structure == null) throw new ArgumentNullException("structure"); // we never had a check for generics here Contract.EndContractBlock(); return SizeOfHelper(structure.GetType(), true); } [Pure] public static int SizeOf(Type t) { if (t == null) throw new ArgumentNullException("t"); if (t.TypeHandle.IsGenericType()) throw new ArgumentException(SR.Argument_NeedNonGenericType, "t"); Contract.EndContractBlock(); return SizeOfHelper(t, true); } private static int SizeOfHelper(Type t, bool throwIfNotMarshalable) { RuntimeTypeHandle typeHandle = t.TypeHandle; RuntimeTypeHandle unsafeStructType; if (McgModuleManager.TryGetStructUnsafeStructType(typeHandle, out unsafeStructType)) { return unsafeStructType.GetValueTypeSize(); } if (!typeHandle.IsBlittable() && !typeHandle.IsValueType()) { throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t); } else { return typeHandle.GetValueTypeSize(); } } //==================================================================== // OffsetOf() //==================================================================== public static IntPtr OffsetOf(Type t, String fieldName) { if (t == null) throw new ArgumentNullException("t"); if (String.IsNullOrEmpty(fieldName)) throw new ArgumentNullException("fieldName"); if (t.TypeHandle.IsGenericType()) throw new ArgumentException(SR.Argument_NeedNonGenericType, "t"); Contract.EndContractBlock(); return OffsetOfHelper(t, fieldName); } private static IntPtr OffsetOfHelper(Type t, String fieldName) { bool structExists; uint offset; if (McgModuleManager.TryGetStructFieldOffset(t.TypeHandle, fieldName, out structExists, out offset)) { return new IntPtr(offset); } // if we can find the struct but couldn't find its field, throw Argument Exception if (structExists) { throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.TypeHandle.GetDisplayName()), "fieldName"); } else { throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t); } } public static IntPtr OffsetOf<T>(String fieldName) { return OffsetOf(typeof(T), fieldName); } //==================================================================== // Copy blocks from CLR arrays to native memory. //==================================================================== public static void Copy(int[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(char[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(short[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(long[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(float[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(double[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(byte[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } private static void CopyToNative(Array source, int startIndex, IntPtr destination, int length) { InteropExtensions.CopyToNative(source, startIndex, destination, length); } //==================================================================== // Copy blocks from native memory to CLR arrays //==================================================================== public static void Copy(IntPtr source, int[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, char[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, short[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, long[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, float[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, double[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, byte[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } private static void CopyToManaged(IntPtr source, Array destination, int startIndex, int length) { InteropExtensions.CopyToManaged(source, destination, startIndex, length); } //==================================================================== // Read from memory //==================================================================== public static unsafe byte ReadByte(IntPtr ptr, int ofs) { byte* addr = (byte*)ptr + ofs; return *addr; } public static byte ReadByte(IntPtr ptr) { return ReadByte(ptr, 0); } public static unsafe short ReadInt16(IntPtr ptr, int ofs) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x1) == 0) { // aligned read return *((short*)addr); } else { // unaligned read short val; byte* valPtr = (byte*)&val; valPtr[0] = addr[0]; valPtr[1] = addr[1]; return val; } } public static short ReadInt16(IntPtr ptr) { return ReadInt16(ptr, 0); } public static unsafe int ReadInt32(IntPtr ptr, int ofs) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x3) == 0) { // aligned read return *((int*)addr); } else { // unaligned read int val; byte* valPtr = (byte*)&val; valPtr[0] = addr[0]; valPtr[1] = addr[1]; valPtr[2] = addr[2]; valPtr[3] = addr[3]; return val; } } public static int ReadInt32(IntPtr ptr) { return ReadInt32(ptr, 0); } public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) { #if WIN32 return (IntPtr)ReadInt32(ptr, ofs); #else return (IntPtr)ReadInt64(ptr, ofs); #endif } public static IntPtr ReadIntPtr(IntPtr ptr, int ofs) { #if WIN32 return (IntPtr)ReadInt32(ptr, ofs); #else return (IntPtr)ReadInt64(ptr, ofs); #endif } public static IntPtr ReadIntPtr(IntPtr ptr) { #if WIN32 return (IntPtr)ReadInt32(ptr, 0); #else return (IntPtr)ReadInt64(ptr, 0); #endif } public static unsafe long ReadInt64(IntPtr ptr, int ofs) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x7) == 0) { // aligned read return *((long*)addr); } else { // unaligned read long val; byte* valPtr = (byte*)&val; valPtr[0] = addr[0]; valPtr[1] = addr[1]; valPtr[2] = addr[2]; valPtr[3] = addr[3]; valPtr[4] = addr[4]; valPtr[5] = addr[5]; valPtr[6] = addr[6]; valPtr[7] = addr[7]; return val; } } public static long ReadInt64(IntPtr ptr) { return ReadInt64(ptr, 0); } //==================================================================== // Write to memory //==================================================================== public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val) { byte* addr = (byte*)ptr + ofs; *addr = val; } public static void WriteByte(IntPtr ptr, byte val) { WriteByte(ptr, 0, val); } public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x1) == 0) { // aligned write *((short*)addr) = val; } else { // unaligned write byte* valPtr = (byte*)&val; addr[0] = valPtr[0]; addr[1] = valPtr[1]; } } public static void WriteInt16(IntPtr ptr, short val) { WriteInt16(ptr, 0, val); } public static void WriteInt16(IntPtr ptr, int ofs, char val) { WriteInt16(ptr, ofs, (short)val); } public static void WriteInt16([In, Out]Object ptr, int ofs, char val) { WriteInt16(ptr, ofs, (short)val); } public static void WriteInt16(IntPtr ptr, char val) { WriteInt16(ptr, 0, (short)val); } public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x3) == 0) { // aligned write *((int*)addr) = val; } else { // unaligned write byte* valPtr = (byte*)&val; addr[0] = valPtr[0]; addr[1] = valPtr[1]; addr[2] = valPtr[2]; addr[3] = valPtr[3]; } } public static void WriteInt32(IntPtr ptr, int val) { WriteInt32(ptr, 0, val); } public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val) { #if WIN32 WriteInt32(ptr, ofs, (int)val); #else WriteInt64(ptr, ofs, (long)val); #endif } public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, IntPtr val) { #if WIN32 WriteInt32(ptr, ofs, (int)val); #else WriteInt64(ptr, ofs, (long)val); #endif } public static void WriteIntPtr(IntPtr ptr, IntPtr val) { #if WIN32 WriteInt32(ptr, 0, (int)val); #else WriteInt64(ptr, 0, (long)val); #endif } public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x7) == 0) { // aligned write *((long*)addr) = val; } else { // unaligned write byte* valPtr = (byte*)&val; addr[0] = valPtr[0]; addr[1] = valPtr[1]; addr[2] = valPtr[2]; addr[3] = valPtr[3]; addr[4] = valPtr[4]; addr[5] = valPtr[5]; addr[6] = valPtr[6]; addr[7] = valPtr[7]; } } public static void WriteInt64(IntPtr ptr, long val) { WriteInt64(ptr, 0, val); } //==================================================================== // GetHRForLastWin32Error //==================================================================== public static int GetHRForLastWin32Error() { int dwLastError = GetLastWin32Error(); if ((dwLastError & 0x80000000) == 0x80000000) { return dwLastError; } else { return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000); } } public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo) { #if ENABLE_WINRT if (errorInfo != new IntPtr(-1)) { throw new PlatformNotSupportedException(); } return ExceptionHelpers.GetMappingExceptionForHR( errorCode, message: null, createCOMException: false, hasErrorInfo: false); #else throw new PlatformNotSupportedException("GetExceptionForHR"); #endif // ENABLE_WINRT } //==================================================================== // Throws a CLR exception based on the HRESULT. //==================================================================== public static void ThrowExceptionForHR(int errorCode) { ThrowExceptionForHRInternal(errorCode, IntPtr.Zero); } public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo) { ThrowExceptionForHRInternal(errorCode, errorInfo); } private static void ThrowExceptionForHRInternal(int errorCode, IntPtr errorInfo) { if (errorCode < 0) { throw GetExceptionForHR(errorCode, errorInfo); } } //==================================================================== // Memory allocation and deallocation. //==================================================================== public static IntPtr AllocHGlobal(IntPtr cb) { return ExternalInterop.MemAlloc(cb); } public static IntPtr AllocHGlobal(int cb) { return AllocHGlobal((IntPtr)cb); } public static void FreeHGlobal(IntPtr hglobal) { if (IsNotWin32Atom(hglobal)) { ExternalInterop.MemFree(hglobal); } } public unsafe static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb) { return ExternalInterop.MemReAlloc(pv, cb); } private unsafe static void ConvertToAnsi(string source, IntPtr pbNativeBuffer, int cbNativeBuffer) { Contract.Assert(source != null); Contract.Assert(pbNativeBuffer != IntPtr.Zero); Contract.Assert(cbNativeBuffer >= (source.Length + 1) * SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi"); fixed (char* pch = source) { int convertedBytes = ExternalInterop.ConvertWideCharToMultiByte(pch, source.Length, pbNativeBuffer, cbNativeBuffer); ((byte*)pbNativeBuffer)[convertedBytes] = 0; } } private unsafe static string ConvertToUnicode(IntPtr sourceBuffer, int cbSourceBuffer) { if (IsWin32Atom(sourceBuffer)) { throw new ArgumentException(SR.Arg_MustBeStringPtrNotAtom); } if (sourceBuffer == IntPtr.Zero || cbSourceBuffer == 0) { return String.Empty; } // MB_PRECOMPOSED is the default. int charsRequired = ExternalInterop.GetCharCount(sourceBuffer, cbSourceBuffer); if (charsRequired == 0) { throw new ArgumentException(SR.Arg_InvalidANSIString); } char[] wideChars = new char[charsRequired + 1]; fixed (char* pWideChars = wideChars) { int converted = ExternalInterop.ConvertMultiByteToWideChar(sourceBuffer, cbSourceBuffer, new IntPtr(pWideChars), wideChars.Length); if (converted == 0) { throw new ArgumentException(SR.Arg_InvalidANSIString); } wideChars[converted] = '\0'; return new String(pWideChars); } } private static unsafe int lstrlenA(IntPtr sz) { Contract.Requires(sz != IntPtr.Zero); byte* pb = (byte*)sz; byte* start = pb; while (*pb != 0) { ++pb; } return (int)(pb - start); } private static unsafe int lstrlenW(IntPtr wsz) { Contract.Requires(wsz != IntPtr.Zero); char* pc = (char*)wsz; char* start = pc; while (*pc != 0) { ++pc; } return (int)(pc - start); } // Zero out the buffer pointed to by ptr, making sure that the compiler cannot // replace the zeroing with a nop private static unsafe void SecureZeroMemory(IntPtr ptr, int bytes) { Contract.Assert(ptr != IntPtr.Zero); Contract.Assert(bytes >= 0); byte* pBuffer = (byte*)ptr; for (int i = 0; i < bytes; ++i) { Volatile.Write(ref pBuffer[i], 0); } } //==================================================================== // String convertions. //==================================================================== public unsafe static IntPtr StringToHGlobalAnsi(String s) { if (s == null) { return IntPtr.Zero; } else { int nb = (s.Length + 1) * SystemMaxDBCSCharSize; // Overflow checking if (nb < s.Length) throw new ArgumentOutOfRangeException("s"); IntPtr hglobal = ExternalInterop.MemAlloc(new IntPtr(nb)); ConvertToAnsi(s, hglobal, nb); return hglobal; } } public unsafe static IntPtr StringToHGlobalUni(String s) { if (s == null) { return IntPtr.Zero; } else { int nb = (s.Length + 1) * 2; // Overflow checking if (nb < s.Length) throw new ArgumentOutOfRangeException("s"); IntPtr hglobal = ExternalInterop.MemAlloc(new UIntPtr((uint)nb)); fixed (char* firstChar = s) { InteropExtensions.Memcpy(hglobal, new IntPtr(firstChar), nb); } return hglobal; } } //==================================================================== // return the IUnknown* for an Object if the current context // is the one where the RCW was first seen. Will return null // otherwise. //==================================================================== public static IntPtr /* IUnknown* */ GetIUnknownForObject(Object o) { if (o == null) { throw new ArgumentNullException("o"); } return MarshalAdapter.GetIUnknownForObject(o); } //==================================================================== // return an Object for IUnknown //==================================================================== public static Object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk) { if (pUnk == default(IntPtr)) { throw new ArgumentNullException("pUnk"); } return MarshalAdapter.GetObjectForIUnknown(pUnk); } //==================================================================== // check if the object is classic COM component //==================================================================== public static bool IsComObject(Object o) { if (o == null) throw new ArgumentNullException("o", SR.Arg_InvalidHandle); return McgComHelpers.IsComObject(o); } public static unsafe IntPtr AllocCoTaskMem(int cb) { IntPtr pNewMem = new IntPtr(ExternalInterop.CoTaskMemAlloc(new IntPtr(cb))); if (pNewMem == IntPtr.Zero) { throw new OutOfMemoryException(); } return pNewMem; } public unsafe static IntPtr StringToCoTaskMemUni(String s) { if (s == null) { return IntPtr.Zero; } else { int nb = (s.Length + 1) * 2; // Overflow checking if (nb < s.Length) throw new ArgumentOutOfRangeException("s"); IntPtr hglobal = new IntPtr( ExternalInterop.CoTaskMemAlloc(new IntPtr(nb))); if (hglobal == IntPtr.Zero) { throw new OutOfMemoryException(); } else { fixed (char* firstChar = s) { InteropExtensions.Memcpy(hglobal, new IntPtr(firstChar), nb); } return hglobal; } } } public unsafe static IntPtr StringToCoTaskMemAnsi(String s) { if (s == null) { return IntPtr.Zero; } else { int nb = (s.Length + 1) * SystemMaxDBCSCharSize; // Overflow checking if (nb < s.Length) throw new ArgumentOutOfRangeException("s"); IntPtr hglobal = new IntPtr(ExternalInterop.CoTaskMemAlloc(new IntPtr(nb))); if (hglobal == IntPtr.Zero) { throw new OutOfMemoryException(); } else { ConvertToAnsi(s, hglobal, nb); return hglobal; } } } public static unsafe void FreeCoTaskMem(IntPtr ptr) { if (IsNotWin32Atom(ptr)) { ExternalInterop.CoTaskMemFree((void*)ptr); } } //==================================================================== // release the COM component and if the reference hits 0 zombie this object // further usage of this Object might throw an exception //==================================================================== public static int ReleaseComObject(Object o) { if (o == null) throw new ArgumentNullException("o"); __ComObject co = null; // Make sure the obj is an __ComObject. try { co = (__ComObject)o; } catch (InvalidCastException) { throw new ArgumentException(SR.Argument_ObjNotComObject, "o"); } return McgMarshal.Release(co); } //==================================================================== // release the COM component and zombie this object // further usage of this Object might throw an exception //==================================================================== public static Int32 FinalReleaseComObject(Object o) { if (o == null) throw new ArgumentNullException("o"); Contract.EndContractBlock(); __ComObject co = null; // Make sure the obj is an __ComObject. try { co = (__ComObject)o; } catch (InvalidCastException) { throw new ArgumentException(SR.Argument_ObjNotComObject, "o"); } co.FinalReleaseSelf(); return 0; } //==================================================================== // IUnknown Helpers //==================================================================== public static int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv) { if (pUnk == IntPtr.Zero) throw new ArgumentNullException("pUnk"); return McgMarshal.ComQueryInterfaceWithHR(pUnk, ref iid, out ppv); } public static int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk) { if (pUnk == IntPtr.Zero) throw new ArgumentNullException("pUnk"); return McgMarshal.ComAddRef(pUnk); } public static int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk) { if (pUnk == IntPtr.Zero) throw new ArgumentNullException("pUnk"); // This is documented to have "undefined behavior" when the ref count is already zero, so // let's not AV if we can help it return McgMarshal.ComSafeRelease(pUnk); } public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb) { IntPtr pNewMem = ExternalInterop.CoTaskMemRealloc(pv, new IntPtr(cb)); if (pNewMem == IntPtr.Zero && cb != 0) { throw new OutOfMemoryException(); } return pNewMem; } //==================================================================== // BSTR allocation and dealocation. //==================================================================== public static void FreeBSTR(IntPtr ptr) { if (IsNotWin32Atom(ptr)) { ExternalInterop.SysFreeString(ptr); } } public static unsafe IntPtr StringToBSTR(String s) { if (s == null) return IntPtr.Zero; // Overflow checking if (s.Length + 1 < s.Length) throw new ArgumentOutOfRangeException("s"); fixed (char* pch = s) { IntPtr bstr = new IntPtr( ExternalInterop.SysAllocStringLen(pch, (uint)s.Length)); if (bstr == IntPtr.Zero) throw new OutOfMemoryException(); return bstr; } } public static String PtrToStringBSTR(IntPtr ptr) { return PtrToStringUni(ptr, (int)ExternalInterop.SysStringLen(ptr)); } public static void ZeroFreeBSTR(IntPtr s) { SecureZeroMemory(s, (int)ExternalInterop.SysStringLen(s) * 2); FreeBSTR(s); } public static void ZeroFreeCoTaskMemAnsi(IntPtr s) { SecureZeroMemory(s, lstrlenA(s)); FreeCoTaskMem(s); } public static void ZeroFreeCoTaskMemUnicode(IntPtr s) { SecureZeroMemory(s, lstrlenW(s)); FreeCoTaskMem(s); } public static void ZeroFreeGlobalAllocAnsi(IntPtr s) { SecureZeroMemory(s, lstrlenA(s)); FreeHGlobal(s); } public static void ZeroFreeGlobalAllocUnicode(IntPtr s) { SecureZeroMemory(s, lstrlenW(s)); FreeHGlobal(s); } /// <summary> /// Returns the unmanaged function pointer for this delegate /// </summary> public static IntPtr GetFunctionPointerForDelegate(Delegate d) { if (d == null) throw new ArgumentNullException("d"); return McgMarshal.GetStubForPInvokeDelegate(d); } public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d) { return GetFunctionPointerForDelegate((Delegate)(object)d); } //==================================================================== // Marshals data from a native memory block to a preallocated structure class. //==================================================================== private static unsafe void PtrToStructureHelper(IntPtr ptr, Object structure) { RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle; // Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0 int offset = structureTypeHandle.IsValueType() ? 1 : 0; if (structureTypeHandle.IsBlittable() && structureTypeHandle.IsValueType()) { int structSize = Marshal.SizeOf(structure); InteropExtensions.PinObjectAndCall(structure, unboxedStructPtr => { InteropExtensions.Memcpy( (IntPtr)((IntPtr*)unboxedStructPtr + offset), // safe (need to adjust offset as it could be class) ptr, // unsafe (no need to adjust as it is always struct) structSize ); }); return; } IntPtr unmarshalStub; if (McgModuleManager.TryGetStructUnmarshalStub(structureTypeHandle, out unmarshalStub)) { InteropExtensions.PinObjectAndCall(structure, unboxedStructPtr => { CalliIntrinsics.Call<int>( unmarshalStub, (void*)ptr, // unsafe (no need to adjust as it is always struct) ((void*)((IntPtr*)unboxedStructPtr + offset)) // safe (need to adjust offset as it could be class) ); }); return; } throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structure.GetType()); } //==================================================================== // Creates a new instance of "structuretype" and marshals data from a // native memory block to it. //==================================================================== [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Object PtrToStructure(IntPtr ptr, Type structureType) { // Boxing the struct here is important to ensure that the original copy is written to, // not the autoboxed copy if (ptr == IntPtr.Zero) throw new ArgumentNullException("ptr"); if (structureType == null) throw new ArgumentNullException("structureType"); Object boxedStruct = InteropExtensions.RuntimeNewObject(structureType.TypeHandle); PtrToStructureHelper(ptr, boxedStruct); return boxedStruct; } public static T PtrToStructure<T>(IntPtr ptr) { return (T)PtrToStructure(ptr, typeof(T)); } public static void PtrToStructure(IntPtr ptr, Object structure) { if (ptr == IntPtr.Zero) throw new ArgumentNullException("ptr"); if (structure == null) throw new ArgumentNullException("structure"); RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle; if (structureTypeHandle.IsValueType()) { throw new ArgumentException(); } PtrToStructureHelper(ptr, structure); } public static void PtrToStructure<T>(IntPtr ptr, T structure) { PtrToStructure(ptr, (object)structure); } //==================================================================== // Marshals data from a structure class to a native memory block. // If the structure contains pointers to allocated blocks and // "fDeleteOld" is true, this routine will call DestroyStructure() first. //==================================================================== public static unsafe void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld) { if (structure == null) throw new ArgumentNullException("structure"); if (ptr == IntPtr.Zero) throw new ArgumentNullException("ptr"); if (fDeleteOld) { DestroyStructure(ptr, structure.GetType()); } RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle; // Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0 int offset = structureTypeHandle.IsValueType() ? 1 : 0; if (structureTypeHandle.IsBlittable()) { int structSize = Marshal.SizeOf(structure); InteropExtensions.PinObjectAndCall(structure, unboxedStructPtr => { InteropExtensions.Memcpy( ptr, // unsafe (no need to adjust as it is always struct) (IntPtr)((IntPtr*)unboxedStructPtr + offset), // safe (need to adjust offset as it could be class) structSize ); }); return; } IntPtr marshalStub; if (McgModuleManager.TryGetStructMarshalStub(structureTypeHandle, out marshalStub)) { InteropExtensions.PinObjectAndCall(structure, unboxedStructPtr => { CalliIntrinsics.Call<int>( marshalStub, ((void*)((IntPtr*)unboxedStructPtr + offset)), // safe (need to adjust offset as it could be class) (void*)ptr // unsafe (no need to adjust as it is always struct) ); }); return; } throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structure.GetType()); } public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld) { StructureToPtr((object)structure, ptr, fDeleteOld); } //==================================================================== // DestroyStructure() // //==================================================================== public static void DestroyStructure(IntPtr ptr, Type structuretype) { if (ptr == IntPtr.Zero) throw new ArgumentNullException("ptr"); if (structuretype == null) throw new ArgumentNullException("structuretype"); RuntimeTypeHandle structureTypeHandle = structuretype.TypeHandle; if (structureTypeHandle.IsGenericType()) throw new ArgumentException(SR.Argument_NeedNonGenericType, "t"); if (structureTypeHandle.IsEnum() || structureTypeHandle.IsInterface() || InteropExtensions.AreTypesAssignable(typeof(Delegate).TypeHandle, structureTypeHandle)) { throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, structureTypeHandle.GetDisplayName()); } Contract.EndContractBlock(); DestroyStructureHelper(ptr, structuretype); } private static unsafe void DestroyStructureHelper(IntPtr ptr, Type structuretype) { RuntimeTypeHandle structureTypeHandle = structuretype.TypeHandle; // Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0 int offset = structureTypeHandle.IsValueType() ? 1 : 0; if (structureTypeHandle.IsBlittable()) { // ok to call with blittable structure, but no work to do in this case. return; } IntPtr destroyStructureStub; bool hasInvalidLayout; if (McgModuleManager.TryGetDestroyStructureStub(structureTypeHandle, out destroyStructureStub, out hasInvalidLayout)) { if (hasInvalidLayout) throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, structureTypeHandle.GetDisplayName()); // DestroyStructureStub == IntPtr.Zero means its fields don't need to be destroied if (destroyStructureStub != IntPtr.Zero) { CalliIntrinsics.Call<int>( destroyStructureStub, (void*)ptr // unsafe (no need to adjust as it is always struct) ); } return; } // Didn't find struct marshal data throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structuretype); } public static void DestroyStructure<T>(IntPtr ptr) { DestroyStructure(ptr, typeof(T)); } public static IntPtr GetComInterfaceForObject<T, TInterface>(T o) { return GetComInterfaceForObject(o, typeof(TInterface)); } public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T) { return MarshalAdapter.GetComInterfaceForObject(o, T); } public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr) { return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate)); } public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t) { // Validate the parameters if (ptr == IntPtr.Zero) throw new ArgumentNullException("ptr"); if (t == null) throw new ArgumentNullException("t"); Contract.EndContractBlock(); if (t.TypeHandle.IsGenericType()) throw new ArgumentException(SR.Argument_NeedNonGenericType, "t"); bool isDelegateType = InteropExtensions.AreTypesAssignable(t.TypeHandle, typeof(MulticastDelegate).TypeHandle) || InteropExtensions.AreTypesAssignable(t.TypeHandle, typeof(Delegate).TypeHandle); if (!isDelegateType) throw new ArgumentException(SR.Arg_MustBeDelegateType, "t"); return MarshalAdapter.GetDelegateForFunctionPointer(ptr, t); } //==================================================================== // GetNativeVariantForObject() // //==================================================================== public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant) { GetNativeVariantForObject((object)obj, pDstNativeVariant); } public static unsafe void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant) { // Obsolete if (pDstNativeVariant == IntPtr.Zero) throw new ArgumentNullException("pSrcNativeVariant"); if (obj != null && obj.GetType().TypeHandle.IsGenericType()) throw new ArgumentException(SR.Argument_NeedNonGenericObject, "obj"); Contract.EndContractBlock(); Variant* pVariant = (Variant*)pDstNativeVariant; *pVariant = new Variant(obj); } //==================================================================== // GetObjectForNativeVariant() // //==================================================================== public static unsafe T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant) { return (T)GetObjectForNativeVariant(pSrcNativeVariant); } public static unsafe Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant) { // Obsolete if (pSrcNativeVariant == IntPtr.Zero) throw new ArgumentNullException("pSrcNativeVariant"); Contract.EndContractBlock(); Variant* pNativeVar = (Variant*)pSrcNativeVariant; return pNativeVar->ToObject(); } //==================================================================== // GetObjectsForNativeVariants() // //==================================================================== public static unsafe Object[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars) { // Obsolete if (aSrcNativeVariant == IntPtr.Zero) throw new ArgumentNullException("aSrcNativeVariant"); if (cVars < 0) throw new ArgumentOutOfRangeException("cVars", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); Object[] obj = new Object[cVars]; IntPtr aNativeVar = aSrcNativeVariant; for (int i = 0; i < cVars; i++) { obj[i] = GetObjectForNativeVariant(aNativeVar); aNativeVar = aNativeVar + sizeof(Variant); } return obj; } public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars) { object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars); T[] result = null; if (objects != null) { result = new T[objects.Length]; Array.Copy(objects, result, objects.Length); } return result; } //==================================================================== // UnsafeAddrOfPinnedArrayElement() // // IMPORTANT NOTICE: This method does not do any verification on the // array. It must be used with EXTREME CAUTION since passing in // an array that is not pinned or in the fixed heap can cause // unexpected results ! //==================================================================== public static IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index) { if (arr == null) throw new ArgumentNullException("arr"); if (index < 0 || index >= arr.Length) throw new ArgumentOutOfRangeException("index"); Contract.EndContractBlock(); int offset = checked(index * arr.GetElementSize()); return arr.GetAddrOfPinnedArrayFromEETypeField() + offset; } public static IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index) { return UnsafeAddrOfPinnedArrayElement((Array)arr, index); } #if ENABLE_WINRT public static Type GetTypeFromCLSID(Guid clsid) { // @TODO - if this is something we recognize, create a strongly-typed RCW // Otherwise, create a weakly typed RCW throw new PlatformNotSupportedException(); } //==================================================================== // Return a unique Object given an IUnknown. This ensures that you // receive a fresh object (we will not look in the cache to match up this // IUnknown to an already existing object). This is useful in cases // where you want to be able to call ReleaseComObject on a RCW // and not worry about other active uses of said RCW. //==================================================================== public static Object GetUniqueObjectForIUnknown(IntPtr unknown) { throw new PlatformNotSupportedException(); } public static bool AreComObjectsAvailableForCleanup() { throw new PlatformNotSupportedException(); } public static IntPtr CreateAggregatedObject(IntPtr pOuter, Object o) { throw new PlatformNotSupportedException(); } public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o) { return CreateAggregatedObject(pOuter, (object)o); } public static Object CreateWrapperOfType(Object o, Type t) { throw new PlatformNotSupportedException(); } public static TWrapper CreateWrapperOfType<T, TWrapper>(T o) { return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper)); } public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode) { // Obsolete throw new PlatformNotSupportedException(); } public static int GetExceptionCode() { // Obsolete throw new PlatformNotSupportedException(); } /// <summary> /// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on /// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para> /// </summary> public static int GetStartComSlot(Type t) { throw new PlatformNotSupportedException(); } //==================================================================== // Given a managed object that wraps an ITypeInfo, return its name //==================================================================== public static String GetTypeInfoName(ITypeInfo typeInfo) { throw new PlatformNotSupportedException(); } #endif //ENABLE_WINRT public static byte ReadByte(Object ptr, int ofs) { // Obsolete throw new PlatformNotSupportedException("ReadByte"); } public static short ReadInt16(Object ptr, int ofs) { // Obsolete throw new PlatformNotSupportedException("ReadInt16"); } public static int ReadInt32(Object ptr, int ofs) { // Obsolete throw new PlatformNotSupportedException("ReadInt32"); } public static long ReadInt64(Object ptr, int ofs) { // Obsolete throw new PlatformNotSupportedException("ReadInt64"); } public static void WriteByte(Object ptr, int ofs, byte val) { // Obsolete throw new PlatformNotSupportedException("WriteByte"); } public static void WriteInt16(Object ptr, int ofs, short val) { // Obsolete throw new PlatformNotSupportedException("WriteInt16"); } public static void WriteInt32(Object ptr, int ofs, int val) { // Obsolete throw new PlatformNotSupportedException("WriteInt32"); } public static void WriteInt64(Object ptr, int ofs, long val) { // Obsolete throw new PlatformNotSupportedException("WriteInt64"); } } }
// Copyright (c) 2015 Alachisoft // // 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; using Alachisoft.NCache.Common.Logger; using Alachisoft.NCache.Common.Net; namespace Alachisoft.NCache.Caching.Topologies.Clustered { public class DistributionMatrix { Address _address; ArrayList _filteredWeightIdList; long[,] _weightPercentMatrix;//Two-D matrix always of [Height,2] dimension. At 0th index Im keeping %age weight of each row, at 1st index Im keeping the weight corresponding to that %age MatrixDimensions _mDimensions; //Keeps the matrix dimensions long[,] _weightMatrix; int[,] _idMatrix; int _itemsCount; long _totalWeight; long _weightToSacrifice; //weight this node needs to give away int _bucketsToSacrifice; int _percentWeightToSacrifice; //weight to sacrifice in percent. (w.r.t the same node data). int _percentWeightOfCluster; //%age weight of cluster, THIS node is keeping .This helps in calculating this node's share int _cushionFactor; //Cushion +- to be considered as Algorithm is Aprroximate rather Exact. DistributionData _distData; //provide information about buckets and other calculations. public static int WeightBalanceThresholdPercent = 10; //Percent weight threshold before balancing weight private long _maxCacheSize = 1073741824; //Default One GB = 1024 * 1024 * 1024 (Byte * KB * MB = GB) User provided in if specified at UI. private long _weightBalanceThreshold = 0 ; //at what weight should the node be treated as contributor to incoming nodes. public DistributionMatrix(ArrayList weightIdList, Address address, DistributionData distData, ILogger NCacheLog) { _address = address; _distData = distData; _filteredWeightIdList = new ArrayList(); _itemsCount = weightIdList.Count; _totalWeight = 1; _weightToSacrifice = 0; _cushionFactor = 10; _percentWeightToSacrifice = 0; _weightBalanceThreshold = Convert.ToInt32((_maxCacheSize * WeightBalanceThresholdPercent) / 100); //10%, threshold at which we feel to balance weight for incoming nodes. its value is percent of MaxCacheSize if (NCacheLog.IsInfoEnabled) NCacheLog.Error("DistributionMatrix.ctor", "Address->" + address.ToString() + ", DistributionData->" + distData.ToString()); //muds: //this is the temp code just to put some trace... int bucketCount = 0; foreach (WeightIdPair wiPair in weightIdList) { if (wiPair.Address.compare(address) == 0) { if(NCacheLog.IsInfoEnabled) NCacheLog.Info("DistributionMatrix.ctor", "waitPair" + wiPair.Address.ToString() + ", wiPait->" + wiPair.BucketId); _filteredWeightIdList.Add(wiPair); bucketCount++; } } if (NCacheLog.IsInfoEnabled) NCacheLog.Info("DistributionMatrix..ctor", address + " owns " + bucketCount + " buckets"); _filteredWeightIdList.Sort(); if (NCacheLog.IsInfoEnabled) NCacheLog.Info("DistributionMatrix.ctor", "_filterWeightIdList.Count:" + _filteredWeightIdList.Count + ", distData.BucketPerNode: " + distData.BucketsPerNode); //Current bucket count - bucketss count after division gives buckets count to be sacrificed. _bucketsToSacrifice = _filteredWeightIdList.Count - distData.BucketsPerNode; if (_bucketsToSacrifice <= 0) { NCacheLog.Error("DistributionMatrix", "Address::" + address.ToString() + " cant sacrifice any bucket. Buckets/Node = " + distData.BucketsPerNode + " My Buckets Count = " + _filteredWeightIdList.Count); return; } int rows = Convert.ToInt32(Math.Ceiling((double)((decimal)_filteredWeightIdList.Count /(decimal)_bucketsToSacrifice))); int cols = _bucketsToSacrifice; InitializeMatrix(rows, cols); } private void InitializeMatrix(int rows, int cols) { _mDimensions = new MatrixDimensions(rows, cols); _weightMatrix = new long[rows, cols]; _idMatrix = new int[rows, cols]; _weightPercentMatrix = new long[rows, 2]; int nLoopCount = 0; for (int i = 0; i < rows; i++) { long rowSum = 0; for (int j = 0; j < cols; j++) { if (nLoopCount < _filteredWeightIdList.Count) { WeightIdPair tmpPair = (WeightIdPair)_filteredWeightIdList[nLoopCount]; _weightMatrix[i,j] = tmpPair.Weight; _idMatrix[i,j] = tmpPair.BucketId; rowSum += tmpPair.Weight; } else { _weightMatrix[i,j] = -1; _idMatrix[i,j] = -1; } nLoopCount++; } _weightPercentMatrix[i, 1] = rowSum; //populate weightPercent Matrix while populating the weight and Id matrices. _totalWeight += rowSum; } //Here I am calculationg sum along with %age weight each row is keeping in. This would help while finding the right // set of buckets to be given off. for (int i = 0; i < _mDimensions.Rows; i++) { _weightPercentMatrix[i, 0] = Convert.ToInt64(Math.Ceiling(((double)_weightPercentMatrix[i, 1] / (double)_totalWeight) * 100)); } //Calculate how much %age weight THIS NODE is keeping w.r.t overall cluster. _percentWeightOfCluster = Convert.ToInt32(((_totalWeight * 100) / _distData.CacheDataSum)); // Although buckets are sacrificed equally, but data is not. // Every node would share w.r.t the percentage that it is keeping in the Cluster. // If a node is keeping 50% share of the data, it would give away 50% of the required weight for the coming node. _weightToSacrifice = Convert.ToInt64(Math.Ceiling(((double)_distData.WeightPerNode * (double)_percentWeightOfCluster) / 100)); _percentWeightToSacrifice = Convert.ToInt32(Math.Ceiling(((double)_weightToSacrifice /(double)_totalWeight) * 100)); } public long[,] WeightPercentMatrix { get { return _weightPercentMatrix; } } public int[,] IdMatrix { get { return _idMatrix; } } public long[,] Matrix { get { return _weightMatrix; } } public long WeightToSacrifice { get { return _weightToSacrifice; } set { _weightToSacrifice = value; } } public int PercentWeightToSacrifice { get { return _percentWeightToSacrifice; } } public long TotalWeight { get { return _totalWeight; } } public int PercentWeightOfCluster { get { return _percentWeightOfCluster; } } public int CushionFactor { get { return Convert.ToInt32(Math.Ceiling((double)((double)_percentWeightToSacrifice /(double)_cushionFactor))); } } public MatrixDimensions MatrixDimension { get { return _mDimensions; } } //Do we really need to balance the weight while a node joins ?. This would let us know. //Addition of this property is to deal with the case when buckets are sequentially assigned while the cluster is in start. public bool DoWeightBalance { get { if (_totalWeight > this.WeightBalanceThreshold) return true; return false; } } public long MaxCacheSize { get { return _maxCacheSize;} set { if (value > 0) _maxCacheSize = value; } } public long WeightBalanceThreshold { get { //10%, threshold at which we feel to balance weight for incoming nodes. its value is percent of MaxCacheSize ; _weightBalanceThreshold = Convert.ToInt64((_maxCacheSize * WeightBalanceThresholdPercent) / 100); return _weightBalanceThreshold; } set { _weightBalanceThreshold = value; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace ProstateBioBank.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// 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.Xml.Serialization.Configuration; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.Versioning; using System.Xml; using System.Xml.Serialization; public struct XmlDeserializationEvents { private XmlNodeEventHandler _onUnknownNode; private XmlAttributeEventHandler _onUnknownAttribute; private XmlElementEventHandler _onUnknownElement; private UnreferencedObjectEventHandler _onUnreferencedObject; internal object sender; public XmlNodeEventHandler OnUnknownNode { get { return _onUnknownNode; } set { _onUnknownNode = value; } } public XmlAttributeEventHandler OnUnknownAttribute { get { return _onUnknownAttribute; } set { _onUnknownAttribute = value; } } public XmlElementEventHandler OnUnknownElement { get { return _onUnknownElement; } set { _onUnknownElement = value; } } public UnreferencedObjectEventHandler OnUnreferencedObject { get { return _onUnreferencedObject; } set { _onUnreferencedObject = value; } } } public abstract class XmlSerializerImplementation { public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } } public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } } public virtual Hashtable ReadMethods { get { throw new NotSupportedException(); } } public virtual Hashtable WriteMethods { get { throw new NotSupportedException(); } } public virtual Hashtable TypedSerializers { get { throw new NotSupportedException(); } } public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); } public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); } } // This enum is intentionally kept outside of the XmlSerializer class since if it would be a subclass // of XmlSerializer, then any access to this enum would be treated by AOT compilers as access to the XmlSerializer // as well, which has a large static ctor which brings in a lot of code. So keeping the enum separate // makes sure that using just the enum itself doesn't bring in the whole of serialization code base. #if FEATURE_SERIALIZATION_UAPAOT public enum SerializationMode #else internal enum SerializationMode #endif { CodeGenOnly, ReflectionOnly, ReflectionAsBackup, PreGenOnly } public class XmlSerializer { #if FEATURE_SERIALIZATION_UAPAOT public static SerializationMode Mode { get; set; } = SerializationMode.ReflectionAsBackup; #else internal static SerializationMode Mode { get; set; } = SerializationMode.ReflectionAsBackup; #endif private static 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 FEATURE_SERIALIZATION_UAPAOT private XmlSerializer innerSerializer; public string DefaultNamespace = null; #else internal string DefaultNamespace = null; #endif private Type _rootType; private bool _isReflectionBasedSerializer = false; 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>>(); protected XmlSerializer() { } public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) : this(type, overrides, extraTypes, root, defaultNamespace, null) { } public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null) { } public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null) { } public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null) { } public XmlSerializer(XmlTypeMapping xmlTypeMapping) { if (xmlTypeMapping == null) throw new ArgumentNullException(nameof(xmlTypeMapping)); #if !FEATURE_SERIALIZATION_UAPAOT _tempAssembly = GenerateTempAssembly(xmlTypeMapping); #endif _mapping = xmlTypeMapping; } public XmlSerializer(Type type) : this(type, (string)null) { } 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 !FEATURE_SERIALIZATION_UAPAOT _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { lock (s_cache) { _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { { XmlSerializerImplementation contract = null; Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract); if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) { AssemblyName name = type.Assembly.GetName(); var serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace); throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); } else { // we found the pre-generated assembly, now make sure that the assembly has the right serializer // try to avoid the reflection step, need to get ElementName, namespace and the Key form the type _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); _tempAssembly = new TempAssembly(new XmlMapping[] { _mapping }, assembly, contract); } } } 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); } #endif } public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location) { if (type == null) throw new ArgumentNullException(nameof(type)); DefaultNamespace = defaultNamespace; _rootType = type; _mapping = GenerateXmlTypeMapping(type, overrides, extraTypes, root, defaultNamespace); #if !FEATURE_SERIALIZATION_UAPAOT _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location); #endif } private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) { XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) { for (int i = 0; i < extraTypes.Length; i++) importer.IncludeType(extraTypes[i]); } return importer.ImportTypeMapping(type, root, defaultNamespace); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping) { return GenerateTempAssembly(xmlMapping, null, null); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace) { return GenerateTempAssembly(xmlMapping, type, defaultNamespace, null); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace, string location) { if (xmlMapping == null) { throw new ArgumentNullException(nameof(xmlMapping)); } xmlMapping.CheckShallow(); if (xmlMapping.IsSoap) { return null; } return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, location); } public void Serialize(TextWriter textWriter, object o) { Serialize(textWriter, o, null); } 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); } public void Serialize(Stream stream, object o) { Serialize(stream, o, null); } 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); } public void Serialize(XmlWriter xmlWriter, object o) { Serialize(xmlWriter, o, null); } public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) { Serialize(xmlWriter, o, namespaces, null); } public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle) { Serialize(xmlWriter, o, namespaces, encodingStyle, null); } 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); } else if (ShouldUseReflectionBasedSerialization(_mapping) || _isReflectionBasedSerializer) { SerializeUsingReflection(xmlWriter, o, namespaces, encodingStyle, id); } #if !FEATURE_SERIALIZATION_UAPAOT 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) { SerializeUsingReflection(xmlWriter, o, namespaces, encodingStyle, id); } 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(); } private void SerializeUsingReflection(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { XmlMapping mapping = GetMapping(); var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); writer.WriteObject(o); } private XmlMapping GetMapping() { if (_mapping == null || !_mapping.GenerateSerializer) { _mapping = GenerateXmlTypeMapping(_rootType, null, null, null, DefaultNamespace); } return _mapping; } public object Deserialize(Stream stream) { XmlTextReader xmlReader = new XmlTextReader(stream); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; xmlReader.Normalization = true; xmlReader.XmlResolver = null; return Deserialize(xmlReader, null); } public object Deserialize(TextReader textReader) { XmlTextReader xmlReader = new XmlTextReader(textReader); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; xmlReader.Normalization = true; xmlReader.XmlResolver = null; return Deserialize(xmlReader, null); } public object Deserialize(XmlReader xmlReader) { return Deserialize(xmlReader, null); } public object Deserialize(XmlReader xmlReader, XmlDeserializationEvents events) { return Deserialize(xmlReader, null, events); } public object Deserialize(XmlReader xmlReader, string encodingStyle) { return Deserialize(xmlReader, encodingStyle, _events); } 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); } else if (ShouldUseReflectionBasedSerialization(_mapping) || _isReflectionBasedSerializer) { return DeserializeUsingReflection(xmlReader, encodingStyle, events); } #if !FEATURE_SERIALIZATION_UAPAOT 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, events, encodingStyle); try { return this.innerSerializer.Deserialize(reader); } finally { reader.Dispose(); } } else if (ReflectionMethodEnabled) { return DeserializeUsingReflection(xmlReader, encodingStyle, events); } 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); } } } private object DeserializeUsingReflection(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) { XmlMapping mapping = GetMapping(); var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle); return reader.ReadObject(); } private static bool ShouldUseReflectionBasedSerialization(XmlMapping mapping) { return Mode == SerializationMode.ReflectionOnly || (mapping != null && mapping.IsSoap); } public virtual bool CanDeserialize(XmlReader xmlReader) { if (_primitiveType != null) { TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]; return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty); } #if !FEATURE_SERIALIZATION_UAPAOT 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 } public static XmlSerializer[] FromMappings(XmlMapping[] mappings) { return FromMappings(mappings, (Type)null); } public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>(); #if FEATURE_SERIALIZATION_UAPAOT XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type); return serializers; #else bool anySoapMapping = false; foreach (var mapping in mappings) { if (mapping.IsSoap) { anySoapMapping = true; } } if ((anySoapMapping && ReflectionMethodEnabled) || Mode == SerializationMode.ReflectionOnly) { XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type); return serializers; } XmlSerializerImplementation contract = null; Assembly assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); TempAssembly tempAssembly = null; if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) { AssemblyName name = type.Assembly.GetName(); string serializerName = Compiler.GetTempAssemblyName(name, null); throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } if (XmlMapping.IsShallow(mappings)) { return Array.Empty<XmlSerializer>(); } else { if (type == null) { tempAssembly = new TempAssembly(mappings, new Type[] { type }, 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[] GetReflectionBasedSerializers(XmlMapping[] mappings, Type type) { var serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) { serializers[i] = new XmlSerializer(); serializers[i]._rootType = type; serializers[i]._mapping = mappings[i]; serializers[i]._isReflectionBasedSerializer = true; } return serializers; } #if !FEATURE_SERIALIZATION_UAPAOT internal static bool GenerateSerializer(Type[] types, XmlMapping[] mappings, Stream stream) { if (types == null || types.Length == 0) return false; if (mappings == null) throw new ArgumentNullException(nameof(mappings)); if (stream == null) throw new ArgumentNullException(nameof(stream)); 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.Assembly; } else if (type.Assembly != assembly) { throw new ArgumentException(SR.Format(SR.XmlPregenOrphanType, type.FullName, assembly.Location), nameof(types)); } } return TempAssembly.GenerateSerializerToStream(mappings, types, null, assembly, new Hashtable(), stream); } #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); 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; } public static XmlSerializer[] FromTypes(Type[] types) { if (types == null) return Array.Empty<XmlSerializer>(); #if FEATURE_SERIALIZATION_UAPAOT 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 FEATURE_SERIALIZATION_UAPAOT // 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 public static string GetXmlSerializerAssemblyName(Type type) { return GetXmlSerializerAssemblyName(type, null); } public static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace) { if (type == null) { throw new ArgumentNullException(nameof(type)); } return Compiler.GetTempAssemblyName(type.Assembly.GetName(), defaultNamespace); } public event XmlNodeEventHandler UnknownNode { add { _events.OnUnknownNode += value; } remove { _events.OnUnknownNode -= value; } } public event XmlAttributeEventHandler UnknownAttribute { add { _events.OnUnknownAttribute += value; } remove { _events.OnUnknownAttribute -= value; } } public event XmlElementEventHandler UnknownElement { add { _events.OnUnknownElement += value; } remove { _events.OnUnknownElement -= value; } } public event UnreferencedObjectEventHandler UnreferencedObject { add { _events.OnUnreferencedObject += value; } remove { _events.OnUnreferencedObject -= value; } } protected virtual XmlSerializationReader CreateReader() { throw new NotImplementedException(); } protected virtual object Deserialize(XmlSerializationReader reader) { throw new NotImplementedException(); } protected virtual XmlSerializationWriter CreateWriter() { throw new NotImplementedException(); } protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new NotImplementedException(); } 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; } } } }
using System; using System.Linq.Expressions; using System.Threading.Tasks; using Attest.Fake.Setup.Contracts; namespace Attest.Fake.Setup { /// <summary> /// Base class for async method calls with return value. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="TCallback">The type of the callback.</typeparam> /// <typeparam name="TResult">The type of the return value.</typeparam> public abstract class MethodCallWithResultBaseAsync<TService, TCallback, TResult> : MethodCallbacksContainerBase<TCallback>, IAddCallbackWithResultShared<TCallback>, IMethodCallWithResultAsync<TService, TCallback, TResult> where TService : class { /// <summary> /// Method to be called /// </summary> public Expression<Func<TService, Task<TResult>>> RunMethod { get; private set; } /// <summary> /// Gets the run method description. /// </summary> /// <value> /// The run method description. /// </value> public override sealed string RunMethodDescription { get; protected set; } /// <summary> /// Initializes a new instance of the <see cref="MethodCallWithResultBase{TService, TCallback, TResult}"/> class. /// </summary> /// <param name="runMethod">The run method.</param> protected MethodCallWithResultBaseAsync(Expression<Func<TService, Task<TResult>>> runMethod) { RunMethod = runMethod; RunMethodDescription = RunMethod.ToString(); } /// <summary> /// Accepts the specified visitor. /// </summary> /// <param name="visitor">The visitor.</param> public abstract void Accept(IMethodCallWithResultVisitorAsync<TService> visitor); } /// <summary> /// Represents async method call with return value. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="TResult">The type of the return value.</typeparam> public class MethodCallWithResultAsync<TService, TResult> : MethodCallWithResultBaseAsync<TService, IMethodCallbackWithResult<TResult>, TResult>, IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<TResult>, TResult>, IHaveNoCallbacksWithResult<IMethodCallbackWithResult<TResult>, TResult> where TService : class { private MethodCallWithResultAsync(Expression<Func<TService, Task<TResult>>> runMethod) : base(runMethod) { } /// <summary> /// Creates the method call using the specified run method. /// </summary> /// <param name="runMethod">The specified run method.</param> /// <returns></returns> public static IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<TResult>, TResult> CreateMethodCall(Expression<Func<TService, Task<TResult>>> runMethod) { return new MethodCallWithResultAsync<TService, TResult>(runMethod); } /// <summary> /// Adds custom callback to the callbacks container /// </summary> /// <param name="methodCallback">Custom callback</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<TResult>, TResult> AddCallback(IMethodCallbackWithResult<TResult> methodCallback) { AddCallbackInternal(methodCallback); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="result">Successful completion return value</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<TResult>, TResult> Complete(TResult result) { Callbacks.Add(new OnCompleteCallbackWithResult<TResult>(result)); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="valueFunction">Successful completion return value's function</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<TResult>, TResult> Complete(Func<TResult> valueFunction) { Callbacks.Add(new OnCompleteCallbackWithResult<TResult>(valueFunction)); return this; } /// <summary> /// Adds exception throwing callback to the callbacks container /// </summary> /// <param name="exception">Exception to be thrown</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<TResult>, TResult> Throw(Exception exception) { Callbacks.Add(new OnErrorCallbackWithResult<TResult>(exception)); return this; } /// <summary> /// Adds never-ending callback to the callbacks container /// </summary> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<TResult>, TResult> WithoutCallback() { Callbacks.Add(ProgressCallbackWithResult<TResult>.Create().WithoutCallback().AsMethodCallback()); return this; } /// <summary> /// Accepts the specified visitor. /// </summary> /// <param name="visitor">The visitor.</param> public override void Accept(IMethodCallWithResultVisitorAsync<TService> visitor) { visitor.Visit(this); } /// <summary> /// Builds the method call with return value from the specified build callbacks. /// </summary> /// <param name="buildCallbacks">The build callbacks.</param> /// <returns></returns> public IMethodCallWithResultAsync<TService, IMethodCallbackWithResult<TResult>, TResult> BuildCallbacks(Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<TResult>, TResult>, IHaveCallbacks<IMethodCallbackWithResult<TResult>>> buildCallbacks) { buildCallbacks(this); return this; } } /// <summary> /// Represents async method call with return value and one parameter. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="T">The type of the parameter.</typeparam> /// <typeparam name="TResult">The type of the return value.</typeparam> public class MethodCallWithResultAsync<TService, T, TResult> : MethodCallWithResultBaseAsync<TService, IMethodCallbackWithResult<T, TResult>, TResult>, IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T, TResult>, T, TResult>, IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult>, IGenerateMethodCallbackWithResult<T> where TService : class { private Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult>, T, IHaveCallbacks<IMethodCallbackWithResult<T, TResult>>> _callbacksProducer; private MethodCallWithResultAsync(Expression<Func<TService, Task<TResult>>> runMethod) : base(runMethod) { } /// <summary> /// Creates the method call using the specified run method. /// </summary> /// <param name="runMethod">The specified run method.</param> /// <returns></returns> public static IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T, TResult>, T, TResult> CreateMethodCall(Expression<Func<TService, Task<TResult>>> runMethod) { return new MethodCallWithResultAsync<TService, T, TResult>(runMethod); } /// <summary> /// Adds custom callback to the callbacks container /// </summary> /// <param name="methodCallback">Custom callback</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult> AddCallback(IMethodCallbackWithResult<T, TResult> methodCallback) { AddCallbackInternal(methodCallback); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="result">Successful completion return value</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult> Complete(TResult result) { Callbacks.Add(new OnCompleteCallbackWithResult<T, TResult>(result)); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="valueFunction">Successful completion return value's function</param> public IAddCallbackWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult> Complete(Func<T, TResult> valueFunction) { Callbacks.Add(new OnCompleteCallbackWithResult<T, TResult>(valueFunction)); return this; } /// <summary> /// Adds exception throwing callback to the callbacks container /// </summary> /// <param name="exception">Exception to be thrown</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult> Throw(Exception exception) { Callbacks.Add(new OnErrorCallbackWithResult<T, TResult>(exception)); return this; } /// <summary> /// Adds never-ending callback to the callbacks container /// </summary> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult> WithoutCallback() { Callbacks.Add(ProgressCallbackWithResult<T, TResult>.Create().WithoutCallback().AsMethodCallback()); return this; } /// <summary> /// Accepts the specified visitor. /// </summary> /// <param name="visitor">The visitor.</param> public override void Accept(IMethodCallWithResultVisitorAsync<TService> visitor) { visitor.Visit(this); } /// <summary> /// Builds the method call with return value from the specified build callbacks. /// </summary> /// <param name="buildCallbacks">The build callbacks.</param> /// <returns></returns> public IMethodCallWithResultAsync<TService, IMethodCallbackWithResult<T, TResult>, TResult> BuildCallbacks(Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T, TResult>>> buildCallbacks) { buildCallbacks(this); return this; } IMethodCallWithResultAsync<TService, IMethodCallbackWithResult<T, TResult>, TResult> IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T, TResult>, T, TResult> .BuildCallbacks(Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult>, T, IHaveCallbacks<IMethodCallbackWithResult<T, TResult>>> callbacksProducer) { _callbacksProducer = callbacksProducer; return this; } bool IGenerateMethodCallbackConditionChecker.CanGenerateCallback { get { return _callbacksProducer != null; } } void IGenerateMethodCallbackWithResult<T>.GenerateCallback(T arg) { _callbacksProducer(this, arg); } } /// <summary> /// Represents async method call with return value and two parameters. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="TResult">The type of the return value.</typeparam> public class MethodCallWithResultAsync<TService, T1, T2, TResult> : MethodCallWithResultBaseAsync<TService, IMethodCallbackWithResult<T1, T2, TResult>, TResult>, IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult>, IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult>, IGenerateMethodCallbackWithResult<T1, T2> where TService : class { private Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult>, T1, T2, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, TResult>>> _callbacksProducer; private MethodCallWithResultAsync(Expression<Func<TService, Task<TResult>>> runMethod) : base(runMethod) { } /// <summary> /// Creates the method call using the specified run method. /// </summary> /// <param name="runMethod">The specified run method.</param> /// <returns></returns> public static IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult> CreateMethodCall(Expression<Func<TService, Task<TResult>>> runMethod) { return new MethodCallWithResultAsync<TService, T1, T2, TResult>(runMethod); } /// <summary> /// Adds custom callback to the callbacks container /// </summary> /// <param name="methodCallback">Custom callback</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult> AddCallback( IMethodCallbackWithResult<T1, T2, TResult> methodCallback) { AddCallbackInternal(methodCallback); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="result">Successful completion return value</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult> Complete(TResult result) { Callbacks.Add(new OnCompleteCallbackWithResult<T1, T2, TResult>(result)); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="valueFunction">Successful completion return value's function</param> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult> Complete(Func<T1, T2, TResult> valueFunction) { Callbacks.Add(new OnCompleteCallbackWithResult<T1, T2, TResult>(valueFunction)); return this; } /// <summary> /// Adds exception throwing callback to the callbacks container /// </summary> /// <param name="exception">Exception to be thrown</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult> Throw(Exception exception) { Callbacks.Add(new OnErrorCallbackWithResult<T1, T2, TResult>(exception)); return this; } /// <summary> /// Adds never-ending callback to the callbacks container /// </summary> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult> WithoutCallback() { Callbacks.Add(ProgressCallbackWithResult<T1, T2, TResult>.Create().WithoutCallback().AsMethodCallback()); return this; } /// <summary> /// Accepts the specified visitor. /// </summary> /// <param name="visitor">The visitor.</param> public override void Accept(IMethodCallWithResultVisitorAsync<TService> visitor) { visitor.Visit(this); } /// <summary> /// Builds the method call with return value from the specified build callbacks. /// </summary> /// <param name="buildCallbacks">The build callbacks.</param> /// <returns></returns> public IMethodCallWithResultAsync<TService, IMethodCallbackWithResult<T1, T2, TResult>, TResult> BuildCallbacks(Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, TResult>>> buildCallbacks) { buildCallbacks(this); return this; } IMethodCallWithResultAsync<TService, IMethodCallbackWithResult<T1, T2, TResult>, TResult> IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult> .BuildCallbacks(Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult>, T1, T2, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, TResult>>> callbacksProducer) { _callbacksProducer = callbacksProducer; return this; } bool IGenerateMethodCallbackConditionChecker.CanGenerateCallback { get { return _callbacksProducer != null; } } void IGenerateMethodCallbackWithResult<T1, T2>.GenerateCallback(T1 arg1, T2 arg2) { _callbacksProducer(this, arg1, arg2); } } /// <summary> /// Represents async method call with return value and three parameters. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> /// <typeparam name="TResult">The type of the return value.</typeparam> public class MethodCallWithResultAsync<TService, T1, T2, T3, TResult> : MethodCallWithResultBaseAsync<TService, IMethodCallbackWithResult<T1, T2, T3, TResult>, TResult>, IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult>, IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult>, IGenerateMethodCallbackWithResult<T1, T2, T3> where TService : class { private Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult>, T1, T2, T3, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, TResult>>> _callbacksProducer; private MethodCallWithResultAsync(Expression<Func<TService, Task<TResult>>> runMethod) : base(runMethod) { } /// <summary> /// Creates the method call using the specified run method. /// </summary> /// <param name="runMethod">The specified run method.</param> /// <returns></returns> public static IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult> CreateMethodCall(Expression<Func<TService, Task<TResult>>> runMethod) { return new MethodCallWithResultAsync<TService, T1, T2, T3, TResult>(runMethod); } /// <summary> /// Adds custom callback to the callbacks container /// </summary> /// <param name="methodCallback">Custom callback</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult> AddCallback( IMethodCallbackWithResult<T1, T2, T3, TResult> methodCallback) { AddCallbackInternal(methodCallback); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="result">Successful completion return value</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult> Complete(TResult result) { Callbacks.Add(new OnCompleteCallbackWithResult<T1, T2, T3, TResult>(result)); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="valueFunction">Successful completion return value's function</param> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult> Complete(Func<T1, T2, T3, TResult> valueFunction) { Callbacks.Add(new OnCompleteCallbackWithResult<T1, T2, T3, TResult>(valueFunction)); return this; } /// <summary> /// Adds exception throwing callback to the callbacks container /// </summary> /// <param name="exception">Exception to be thrown</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult> Throw(Exception exception) { Callbacks.Add(new OnErrorCallbackWithResult<T1, T2, T3, TResult>(exception)); return this; } /// <summary> /// Adds never-ending callback to the callbacks container /// </summary> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult> WithoutCallback() { Callbacks.Add(ProgressCallbackWithResult<T1, T2, T3, TResult>.Create().WithoutCallback().AsMethodCallback()); return this; } /// <summary> /// Accepts the specified visitor. /// </summary> /// <param name="visitor">The visitor.</param> public override void Accept(IMethodCallWithResultVisitorAsync<TService> visitor) { visitor.Visit(this); } /// <summary> /// Builds the method call with return value from the specified build callbacks. /// </summary> /// <param name="buildCallbacks">The build callbacks.</param> /// <returns></returns> public IMethodCallWithResultAsync<TService, IMethodCallbackWithResult<T1, T2, T3, TResult>, TResult> BuildCallbacks( Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, TResult>>> buildCallbacks) { buildCallbacks(this); return this; } IMethodCallWithResultAsync<TService, IMethodCallbackWithResult<T1, T2, T3, TResult>, TResult> IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult>.BuildCallbacks( Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult>, T1, T2, T3, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, TResult>>> callbacksProducer) { _callbacksProducer = callbacksProducer; return this; } bool IGenerateMethodCallbackConditionChecker.CanGenerateCallback { get { return _callbacksProducer != null; } } void IGenerateMethodCallbackWithResult<T1, T2, T3>.GenerateCallback(T1 arg1, T2 arg2, T3 arg3) { _callbacksProducer(this, arg1, arg2, arg3); } } /// <summary> /// Represents async method call with return value and four parameters. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> /// <typeparam name="T4">The type of the fourth parameter.</typeparam> /// <typeparam name="TResult">The type of the return value.</typeparam> public class MethodCallWithResultAsync<TService, T1, T2, T3, T4, TResult> : MethodCallWithResultBaseAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, TResult>, IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>, IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>, IGenerateMethodCallbackWithResult<T1, T2, T3, T4> where TService : class { private Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>, T1, T2, T3, T4, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>>> _callbacksProducer; private MethodCallWithResultAsync(Expression<Func<TService, Task<TResult>>> runMethod) : base(runMethod) { } /// <summary> /// Creates the method call using the specified run method. /// </summary> /// <param name="runMethod">The specified run method.</param> /// <returns></returns> public static IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult> CreateMethodCall(Expression<Func<TService, Task<TResult>>> runMethod) { return new MethodCallWithResultAsync<TService, T1, T2, T3, T4, TResult>(runMethod); } /// <summary> /// Adds custom callback to the callbacks container /// </summary> /// <param name="methodCallback">Custom callback</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult> AddCallback( IMethodCallbackWithResult<T1, T2, T3, T4, TResult> methodCallback) { AddCallbackInternal(methodCallback); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="result">Successful completion return value</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult> Complete(TResult result) { Callbacks.Add(new OnCompleteCallbackWithResult<T1, T2, T3, T4, TResult>(result)); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="valueFunction">Successful completion return value's function</param> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult> Complete(Func<T1, T2, T3, T4, TResult> valueFunction) { Callbacks.Add(new OnCompleteCallbackWithResult<T1, T2, T3, T4, TResult>(valueFunction)); return this; } /// <summary> /// Adds exception throwing callback to the callbacks container /// </summary> /// <param name="exception">Exception to be thrown</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult> Throw(Exception exception) { Callbacks.Add(new OnErrorCallbackWithResult<T1, T2, T3, T4, TResult>(exception)); return this; } /// <summary> /// Adds never-ending callback to the callbacks container /// </summary> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult> WithoutCallback() { Callbacks.Add(ProgressCallbackWithResult<T1, T2, T3, T4, TResult>.Create().WithoutCallback().AsMethodCallback()); return this; } /// <summary> /// Accepts the specified visitor. /// </summary> /// <param name="visitor">The visitor.</param> public override void Accept(IMethodCallWithResultVisitorAsync<TService> visitor) { visitor.Visit(this); } /// <summary> /// Builds the method call with return value from the specified build callbacks. /// </summary> /// <param name="buildCallbacks">The build callbacks.</param> /// <returns></returns> public IMethodCallWithResultAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, TResult> BuildCallbacks( Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>>> buildCallbacks) { buildCallbacks(this); return this; } IMethodCallWithResultAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, TResult> IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>.BuildCallbacks(Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>, T1, T2, T3, T4, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>>> callbacksProducer) { _callbacksProducer = callbacksProducer; return this; } bool IGenerateMethodCallbackConditionChecker.CanGenerateCallback { get { return _callbacksProducer != null; } } void IGenerateMethodCallbackWithResult<T1, T2, T3, T4>.GenerateCallback(T1 arg1, T2 arg2, T3 arg3, T4 arg4) { _callbacksProducer(this, arg1, arg2, arg3, arg4); } } /// <summary> /// Represents async method call with return value and five parameters. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> /// <typeparam name="T4">The type of the fourth parameter.</typeparam> /// <typeparam name="T5">The type of the fifth parameter.</typeparam> /// <typeparam name="TResult">The type of the return value.</typeparam> public class MethodCallWithResultAsync<TService, T1, T2, T3, T4, T5, TResult> : MethodCallWithResultBaseAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, TResult>, IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>, IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>, IGenerateMethodCallbackWithResult<T1, T2, T3, T4, T5> where TService : class { private Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>>> _callbacksProducer; private MethodCallWithResultAsync(Expression<Func<TService, Task<TResult>>> runMethod) : base(runMethod) { } /// <summary> /// Creates the method call using the specified run method. /// </summary> /// <param name="runMethod">The specified run method.</param> /// <returns></returns> public static IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult> CreateMethodCall(Expression<Func<TService, Task<TResult>>> runMethod) { return new MethodCallWithResultAsync<TService, T1, T2, T3, T4, T5, TResult>(runMethod); } /// <summary> /// Adds custom callback to the callbacks container /// </summary> /// <param name="methodCallback">Custom callback</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult> AddCallback( IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult> methodCallback) { AddCallbackInternal(methodCallback); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="result">Successful completion return value</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult> Complete(TResult result) { Callbacks.Add(new OnCompleteCallbackWithResult<T1, T2, T3, T4, T5, TResult>(result)); return this; } /// <summary> /// Adds successful completion callback to the callbacks container /// </summary> /// <param name="valueFunction">Successful completion return value's function</param> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult> Complete(Func<T1, T2, T3, T4, T5, TResult> valueFunction) { Callbacks.Add(new OnCompleteCallbackWithResult<T1, T2, T3, T4, T5, TResult>(valueFunction)); return this; } /// <summary> /// Adds exception throwing callback to the callbacks container /// </summary> /// <param name="exception">Exception to be thrown</param> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult> Throw(Exception exception) { Callbacks.Add(new OnErrorCallbackWithResult<T1, T2, T3, T4, T5, TResult>(exception)); return this; } /// <summary> /// Adds never-ending callback to the callbacks container /// </summary> /// <returns>Callbacks container</returns> public IAddCallbackWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult> WithoutCallback() { Callbacks.Add(ProgressCallbackWithResult<T1, T2, T3, T4, T5, TResult>.Create().WithoutCallback().AsMethodCallback()); return this; } /// <summary> /// Accepts the specified visitor. /// </summary> /// <param name="visitor">The visitor.</param> public override void Accept(IMethodCallWithResultVisitorAsync<TService> visitor) { visitor.Visit(this); } /// <summary> /// Builds the method call with return value from the specified build callbacks. /// </summary> /// <param name="buildCallbacks">The build callbacks.</param> /// <returns></returns> public IMethodCallWithResultAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, TResult> BuildCallbacks( Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>>> buildCallbacks) { buildCallbacks(this); return this; } IMethodCallWithResultAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, TResult> IMethodCallWithResultInitialTemplateAsync<TService, IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>.BuildCallbacks( Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>>> callbacksProducer) { _callbacksProducer = callbacksProducer; return this; } bool IGenerateMethodCallbackConditionChecker.CanGenerateCallback { get { return _callbacksProducer != null; } } void IGenerateMethodCallbackWithResult<T1, T2, T3, T4, T5>.GenerateCallback(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { _callbacksProducer(this, arg1, arg2, arg3, arg4, arg5); } } }
// 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.Test.ModuleCore; using System; using System.IO; using System.Text; using System.Xml; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { public partial class TCReadContentAsBinHex : BridgeHelpers { public const string ST_ELEM_NAME1 = "ElemAll"; public const string ST_ELEM_NAME2 = "ElemEmpty"; public const string ST_ELEM_NAME3 = "ElemNum"; public const string ST_ELEM_NAME4 = "ElemText"; public const string ST_ELEM_NAME5 = "ElemNumText"; public const string ST_ELEM_NAME6 = "ElemLong"; public const string strTextBinHex = "ABCDEF"; public const string strNumBinHex = "0123456789"; public override void Init() { base.Init(); CreateBinHexTestFile(pBinHexXml); } public override void Terminate() { base.Terminate(); } private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType) { bool bPassed = false; byte[] buffer = new byte[iBufferSize]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME1); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return true; try { DataReader.ReadContentAsBinHex(buffer, iIndex, iCount); } catch (Exception e) { bPassed = (e.GetType().ToString() == exceptionType.ToString()); if (!bPassed) { TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString()); TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString()); } } return bPassed; } protected void TestInvalidNodeType(XmlNodeType nt) { XmlReader DataReader = GetReader(pBinHexXml); PositionOnNodeType(DataReader, nt); string name = DataReader.Name; string value = DataReader.Value; byte[] buffer = new byte[1]; if (!DataReader.CanReadBinaryContent) return; try { int nBytes = DataReader.ReadContentAsBinHex(buffer, 0, 1); } catch (InvalidOperationException) { return; } TestLog.Compare(false, "Invalid OP exception not thrown on wrong nodetype"); } //[Variation("ReadBinHex Element with all valid value")] public void TestReadBinHex_1() { int binhexlen = 0; byte[] binhex = new byte[1000]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME1); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; binhexlen = DataReader.ReadContentAsBinHex(binhex, 0, binhex.Length); string strActbinhex = ""; for (int i = 0; i < binhexlen; i = i + 2) { strActbinhex += System.BitConverter.ToChar(binhex, i); } TestLog.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex"); } //[Variation("ReadBinHex Element with all valid Num value", Priority = 0)] public void TestReadBinHex_2() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME3); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } TestLog.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex"); } //[Variation("ReadBinHex Element with all valid Text value")] public void TestReadBinHex_3() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME4); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } TestLog.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex"); } //[Variation("ReadBinHex Element on CDATA", Priority = 0)] public void TestReadBinHex_4() { int BinHexlen = 0; byte[] BinHex = new byte[3]; string xmlStr = "<root><![CDATA[ABCDEF]]></root>"; XmlReader DataReader = GetReader(new StringReader(xmlStr)); PositionOnElement(DataReader, "root"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); TestLog.Compare(BinHexlen, 3, "BinHex"); BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); TestLog.Compare(BinHexlen, 0, "BinHex"); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.None, "Not on none"); } //[Variation("ReadBinHex Element with all valid value (from concatenation), Priority=0")] public void TestReadBinHex_5() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME5); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } TestLog.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex"); } //[Variation("ReadBinHex Element with all long valid value (from concatenation)")] public void TestReadBinHex_6() { int BinHexlen = 0; byte[] BinHex = new byte[2000]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME6); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } string strExpBinHex = ""; for (int i = 0; i < 10; i++) strExpBinHex += (strNumBinHex + strTextBinHex); TestLog.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex"); } //[Variation("ReadBinHex with count > buffer size")] public void TestReadBinHex_7() { BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBinHex with count < 0")] public void TestReadBinHex_8() { BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBinHex with index > buffer size")] public void vReadBinHex_9() { BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBinHex with index < 0")] public void TestReadBinHex_10() { BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBinHex with index + count exceeds buffer")] public void TestReadBinHex_11() { BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBinHex index & count =0")] public void TestReadBinHex_12() { byte[] buffer = new byte[5]; int iCount = 0; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME1); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; try { iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0); } catch (Exception e) { TestLog.WriteLine(e.ToString()); throw new TestException(TestResult.Failed, ""); } TestLog.Compare(iCount, 0, "has to be zero"); } //[Variation("ReadBinHex Element multiple into same buffer (using offset), Priority=0")] public void TestReadBinHex_13() { int BinHexlen = 10; byte[] BinHex = new byte[BinHexlen]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME4); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; string strActbinhex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { DataReader.ReadContentAsBinHex(BinHex, i, 2); strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString(); TestLog.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64"); } } //[Variation("ReadBinHex with buffer == null")] public void TestReadBinHex_14() { XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME4); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; try { DataReader.ReadContentAsBinHex(null, 0, 0); } catch (ArgumentNullException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadBinHex after failed ReadBinHex")] public void TestReadBinHex_15() { XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, "ElemErr"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[10]; int nRead = 0; try { nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1); throw new TestException(TestResult.Failed, ""); } catch (XmlException e) { int idx = e.Message.IndexOf("a&"); TestLog.Compare(idx >= 0, "msg"); CheckXmlException("Xml_UserException", e, 1, 968); } } //[Variation("Read after partial ReadBinHex")] public void TestReadBinHex_16() { XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, "ElemNum"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[10]; int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 8); TestLog.Compare(nRead, 8, "0"); DataReader.Read(); TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "ElemText", String.Empty), "1vn"); } //[Variation("Current node on multiple calls")] public void TestReadBinHex_17() { XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, "ElemNum"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[30]; int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 2); TestLog.Compare(nRead, 2, "0"); nRead = DataReader.ReadContentAsBinHex(buffer, 0, 19); TestLog.Compare(nRead, 18, "1"); TestLog.Compare(VerifyNode(DataReader, XmlNodeType.EndElement, "ElemNum", String.Empty), "1vn"); } //[Variation("ReadBinHex with whitespace")] public void TestTextReadBinHex_21() { byte[] buffer = new byte[1]; string strxml = "<abc> 1 1 B </abc>"; XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "abc"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; int result = 0; int nRead; while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; TestLog.Compare(result, 1, "res"); TestLog.Compare(buffer[0], (byte)17, "buffer[0]"); } //[Variation("ReadBinHex with odd number of chars")] public void TestTextReadBinHex_22() { byte[] buffer = new byte[1]; string strxml = "<abc>11B</abc>"; XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "abc"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; int result = 0; int nRead; while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; TestLog.Compare(result, 1, "res"); TestLog.Compare(buffer[0], (byte)17, "buffer[0]"); } //[Variation("ReadBinHex when end tag doesn't exist")] public void TestTextReadBinHex_23() { byte[] buffer = new byte[5000]; string strxml = "<B>" + new string('A', 5000); try { XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "B"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; DataReader.ReadContentAsBinHex(buffer, 0, 5000); TestLog.WriteLine("Accepted incomplete element"); throw new TestException(TestResult.Failed, ""); } catch (XmlException e) { CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004); } } //[Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going Whidbey to Everett")] public void TestTextReadBinHex_24() { string filename = Path.Combine("TestData", "XmlReader", "Common", "Bug99148.xml"); XmlReader DataReader = GetReader(filename); DataReader.MoveToContent(); int bytes = -1; DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; StringBuilder output = new StringBuilder(); while (bytes != 0) { byte[] bbb = new byte[1024]; bytes = DataReader.ReadContentAsBinHex(bbb, 0, bbb.Length); for (int i = 0; i < bytes; i++) { output.AppendFormat(bbb[i].ToString()); } } if (TestLog.Compare(output.ToString().Length, 1735, "Expected Length : 1735")) return; else throw new TestException(TestResult.Failed, ""); } //[Variation("DebugAssert in ReadContentAsBinHex")] public void DebugAssertInReadContentAsBinHex() { XmlReader DataReader = GetReaderStr(@"<root> <boo>hey</boo> </root>"); byte[] buffer = new byte[5]; int iCount = 0; while (DataReader.Read()) { if (DataReader.NodeType == XmlNodeType.Element) break; } if (!DataReader.CanReadBinaryContent) return; DataReader.Read(); iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0); } } //[TestCase(Name = "ReadElementContentAsBinHex", Desc = "ReadElementContentAsBinHex")] public partial class TCReadElementContentAsBinHex : BridgeHelpers { public const string ST_ELEM_NAME1 = "ElemAll"; public const string ST_ELEM_NAME2 = "ElemEmpty"; public const string ST_ELEM_NAME3 = "ElemNum"; public const string ST_ELEM_NAME4 = "ElemText"; public const string ST_ELEM_NAME5 = "ElemNumText"; public const string ST_ELEM_NAME6 = "ElemLong"; public const string strTextBinHex = "ABCDEF"; public const string strNumBinHex = "0123456789"; public override void Init() { base.Init(); CreateBinHexTestFile(pBinHexXml); } public override void Terminate() { base.Terminate(); } private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType) { bool bPassed = false; byte[] buffer = new byte[iBufferSize]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME1); if (!DataReader.CanReadBinaryContent) return true; try { DataReader.ReadElementContentAsBinHex(buffer, iIndex, iCount); } catch (Exception e) { bPassed = (e.GetType().ToString() == exceptionType.ToString()); if (!bPassed) { TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString()); TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString()); } } return bPassed; } protected void TestInvalidNodeType(XmlNodeType nt) { XmlReader DataReader = GetReader(pBinHexXml); PositionOnNodeType(DataReader, nt); string name = DataReader.Name; string value = DataReader.Value; if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[1]; try { int nBytes = DataReader.ReadElementContentAsBinHex(buffer, 0, 1); } catch (InvalidOperationException) { return; } TestLog.Compare(false, "Invalid OP exception not thrown on wrong nodetype"); } //[Variation("ReadBinHex Element with all valid value")] public void TestReadBinHex_1() { int binhexlen = 0; byte[] binhex = new byte[1000]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME1); if (!DataReader.CanReadBinaryContent) return; binhexlen = DataReader.ReadElementContentAsBinHex(binhex, 0, binhex.Length); string strActbinhex = ""; for (int i = 0; i < binhexlen; i = i + 2) { strActbinhex += System.BitConverter.ToChar(binhex, i); } TestLog.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex"); } //[Variation("ReadBinHex Element with all valid Num value", Priority = 0)] public void TestReadBinHex_2() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME3); if (!DataReader.CanReadBinaryContent) return; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } TestLog.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex"); } //[Variation("ReadBinHex Element with all valid Text value")] public void TestReadBinHex_3() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME4); if (!DataReader.CanReadBinaryContent) return; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } TestLog.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex"); } //[Variation("ReadBinHex Element with Comments and PIs", Priority = 0)] public void TestReadBinHex_4() { int BinHexlen = 0; byte[] BinHex = new byte[3]; XmlReader DataReader = GetReader(new StringReader("<root>AB<!--Comment-->CD<?pi target?>EF</root>")); PositionOnElement(DataReader, "root"); if (!DataReader.CanReadBinaryContent) return; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); TestLog.Compare(BinHexlen, 3, "BinHex"); } //[Variation("ReadBinHex Element with all valid value (from concatenation), Priority=0")] public void TestReadBinHex_5() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME5); if (!DataReader.CanReadBinaryContent) return; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } TestLog.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex"); } //[Variation("ReadBinHex Element with all long valid value (from concatenation)")] public void TestReadBinHex_6() { int BinHexlen = 0; byte[] BinHex = new byte[2000]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME6); if (!DataReader.CanReadBinaryContent) return; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } string strExpBinHex = ""; for (int i = 0; i < 10; i++) strExpBinHex += (strNumBinHex + strTextBinHex); TestLog.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex"); } //[Variation("ReadBinHex with count > buffer size")] public void TestReadBinHex_7() { BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBinHex with count < 0")] public void TestReadBinHex_8() { BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBinHex with index > buffer size")] public void vReadBinHex_9() { BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBinHex with index < 0")] public void TestReadBinHex_10() { BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBinHex with index + count exceeds buffer")] public void TestReadBinHex_11() { BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBinHex index & count =0")] public void TestReadBinHex_12() { byte[] buffer = new byte[5]; int iCount = 0; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME1); if (!DataReader.CanReadBinaryContent) return; try { iCount = DataReader.ReadElementContentAsBinHex(buffer, 0, 0); } catch (Exception e) { TestLog.WriteLine(e.ToString()); throw new TestException(TestResult.Failed, ""); } TestLog.Compare(iCount, 0, "has to be zero"); } //[Variation("ReadBinHex Element multiple into same buffer (using offset), Priority=0")] public void TestReadBinHex_13() { int BinHexlen = 10; byte[] BinHex = new byte[BinHexlen]; XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME4); if (!DataReader.CanReadBinaryContent) return; string strActbinhex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { DataReader.ReadElementContentAsBinHex(BinHex, i, 2); strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString(); TestLog.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64"); } } //[Variation("ReadBinHex with buffer == null")] public void TestReadBinHex_14() { XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, ST_ELEM_NAME4); if (!DataReader.CanReadBinaryContent) return; try { DataReader.ReadElementContentAsBinHex(null, 0, 0); } catch (ArgumentNullException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadBinHex after failed ReadBinHex")] public void TestReadBinHex_15() { XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, "ElemErr"); if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[10]; int nRead = 0; try { nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1); throw new TestException(TestResult.Failed, ""); } catch (XmlException e) { int idx = e.Message.IndexOf("a&"); TestLog.Compare(idx >= 0, "msg"); CheckXmlException("Xml_UserException", e, 1, 968); } } //[Variation("Read after partial ReadBinHex")] public void TestReadBinHex_16() { XmlReader DataReader = GetReader(pBinHexXml); PositionOnElement(DataReader, "ElemNum"); if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[10]; int nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 8); TestLog.Compare(nRead, 8, "0"); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on text node"); } //[Variation("ReadBinHex with whitespace")] public void TestTextReadBinHex_21() { byte[] buffer = new byte[1]; string strxml = "<abc> 1 1 B </abc>"; XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "abc"); if (!DataReader.CanReadBinaryContent) return; int result = 0; int nRead; while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; TestLog.Compare(result, 1, "res"); TestLog.Compare(buffer[0], (byte)17, "buffer[0]"); } //[Variation("ReadBinHex with odd number of chars")] public void TestTextReadBinHex_22() { byte[] buffer = new byte[1]; string strxml = "<abc>11B</abc>"; XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "abc"); if (!DataReader.CanReadBinaryContent) return; int result = 0; int nRead; while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; TestLog.Compare(result, 1, "res"); TestLog.Compare(buffer[0], (byte)17, "buffer[0]"); } //[Variation("ReadBinHex when end tag doesn't exist")] public void TestTextReadBinHex_23() { byte[] buffer = new byte[5000]; string strxml = "<B>" + new string('A', 5000); try { XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "B"); DataReader.ReadElementContentAsBinHex(buffer, 0, 5000); TestLog.WriteLine("Accepted incomplete element"); throw new TestException(TestResult.Failed, ""); } catch (XmlException e) { CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004); } } //[Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going Whidbey to Everett")] public void TestTextReadBinHex_24() { string filename = Path.Combine("TestData", "XmlReader", "Common", "Bug99148.xml"); XmlReader DataReader = GetReader(filename); DataReader.MoveToContent(); if (!DataReader.CanReadBinaryContent) return; int bytes = -1; StringBuilder output = new StringBuilder(); while (bytes != 0) { byte[] bbb = new byte[1024]; bytes = DataReader.ReadElementContentAsBinHex(bbb, 0, bbb.Length); for (int i = 0; i < bytes; i++) { output.AppendFormat(bbb[i].ToString()); } } if (TestLog.Compare(output.ToString().Length, 1735, "Expected Length : 1735")) return; else throw new TestException(TestResult.Failed, ""); } //[Variation("SubtreeReader inserted attributes don't work with ReadContentAsBinHex")] public void TestTextReadBinHex_25() { string strxml = "<root xmlns='0102030405060708090a0B0c'><bar/></root>"; using (XmlReader r = GetReader(new StringReader(strxml))) { r.Read(); r.Read(); using (XmlReader sr = r.ReadSubtree()) { if (!sr.CanReadBinaryContent) return; sr.Read(); sr.MoveToFirstAttribute(); sr.MoveToFirstAttribute(); byte[] bytes = new byte[4]; while ((sr.ReadContentAsBinHex(bytes, 0, bytes.Length)) > 0) { } } } } } } } }
#region License //============================================================================= // Velox.DB - Portable .NET ORM // // Copyright (c) 2015 Philippe Leybaert // // 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.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace Velox.DB { internal class AsyncDataSet<T> : IAsyncDataSet<T> { private readonly IDataSet<T> _dataSet; public AsyncDataSet(IDataSet<T> dataSet) { _dataSet = dataSet; } public IAsyncDataSet<T> Where(Expression<Func<T, bool>> whereExpression) { return new AsyncDataSet<T>(_dataSet.Where(whereExpression)); } public IAsyncDataSet<T> OrderBy<TKey>(Expression<Func<T, TKey>> keySelector) { return new AsyncDataSet<T>(_dataSet.OrderBy(keySelector)); } public IAsyncDataSet<T> OrderByDescending<TKey>(Expression<Func<T, TKey>> keySelector) { return new AsyncDataSet<T>(_dataSet.OrderByDescending(keySelector)); } public IAsyncDataSet<T> ThenBy<TKey>(Expression<Func<T, TKey>> keySelector) { return new AsyncDataSet<T>(_dataSet.ThenBy(keySelector)); } public IAsyncDataSet<T> ThenByDescending<TKey>(Expression<Func<T, TKey>> keySelector) { return new AsyncDataSet<T>(_dataSet.ThenByDescending(keySelector)); } public IAsyncDataSet<T> OrderBy(QueryExpression expression, SortOrder sortOrder) { return new AsyncDataSet<T>(_dataSet.OrderBy(expression, sortOrder)); } public IAsyncDataSet<T> WithRelations(params Expression<Func<T, object>>[] relationsToLoad) { return new AsyncDataSet<T>(_dataSet.WithRelations(relationsToLoad)); } public IAsyncDataSet<T> Where(QueryExpression filterExpression) { return new AsyncDataSet<T>(_dataSet.Where(filterExpression)); } public IAsyncDataSet<T> Skip(int n) { return new AsyncDataSet<T>(_dataSet.Skip(n)); } public IAsyncDataSet<T> Take(int n) { return new AsyncDataSet<T>(_dataSet.Take(n)); } public IDataSet<T> Sync() { return _dataSet; } public Task<T> Read(object key, params Expression<Func<T, object>>[] relationsToLoad) { return Task.Factory.StartNew( () => _dataSet.Read(key, relationsToLoad)); } public Task<T> Read(Expression<Func<T, bool>> condition, params Expression<Func<T, object>>[] relationsToLoad) { return Task.Factory.StartNew(() => _dataSet.Read(condition, relationsToLoad)); } public Task<T> Load(T obj, object key, params Expression<Func<T, object>>[] relationsToLoad) { return Task.Factory.StartNew( () => _dataSet.Load(obj, key, relationsToLoad)); } public Task<bool> Save(T obj, bool saveRelations = false, bool? create = null) { return Task.Factory.StartNew(() => _dataSet.Save(obj, saveRelations, create)); } public Task<bool> InsertOrUpdate(T obj, bool saveRelations = false) { return Task.Factory.StartNew( () => _dataSet.InsertOrUpdate(obj, saveRelations)); } public Task<bool> Insert(T obj, bool saveRelations = false) { return Task.Factory.StartNew( () => _dataSet.Insert(obj, saveRelations)); } public Task<bool> Update(T obj, bool saveRelations = false) { return Task.Factory.StartNew(() => _dataSet.Update(obj, saveRelations)); } public Task<bool> Delete(T obj) { return Task.Factory.StartNew( () => _dataSet.Delete(obj)); } public Task<bool> DeleteAll() { return Task.Factory.StartNew(() => _dataSet.DeleteAll()); } public Task<bool> Delete(Expression<Func<T, bool>> filter) { return Task.Factory.StartNew( () => _dataSet.Delete(filter)); } public Task<bool> Delete(QueryExpression filterExpression) { return Task.Factory.StartNew(() => _dataSet.Delete(filterExpression)); } public Task<T> First() { return Task.Factory.StartNew(() => _dataSet.First()); } public Task<T> First(Expression<Func<T, bool>> filter) { return Task.Factory.StartNew(() => _dataSet.First(filter)); } public Task<T> FirstOrDefault() { return Task.Factory.StartNew(() => _dataSet.FirstOrDefault()); } public Task<T> FirstOrDefault(Expression<Func<T, bool>> filter) { return Task.Factory.StartNew(() => _dataSet.FirstOrDefault(filter)); } public Task<long> Count() { return Task.Factory.StartNew(() => _dataSet.Count()); } public Task<long> Count(Expression<Func<T, bool>> filter) { return Task.Factory.StartNew(() => _dataSet.Count(filter)); } public Task<TScalar> Max<TScalar>(Expression<Func<T, TScalar>> expression, Expression<Func<T, bool>> filter) { return Task.Factory.StartNew(() => _dataSet.Max(expression, filter)); } public Task<TScalar> Min<TScalar>(Expression<Func<T, TScalar>> expression, Expression<Func<T, bool>> filter) { return Task.Factory.StartNew(() => _dataSet.Min(expression, filter)); } public Task<TScalar> Sum<TScalar>(Expression<Func<T, TScalar>> expression, Expression<Func<T, bool>> filter) { return Task.Factory.StartNew(() => _dataSet.Sum(expression, filter)); } public Task<bool> All(Expression<Func<T, bool>> filter) { return Task.Factory.StartNew(() => _dataSet.All(filter)); } public Task<TScalar> Max<TScalar>(Expression<Func<T, TScalar>> expression) { return Task.Factory.StartNew(() => _dataSet.Max(expression)); } public Task<TScalar> Min<TScalar>(Expression<Func<T, TScalar>> expression) { return Task.Factory.StartNew(() => _dataSet.Min(expression)); } public Task<TScalar> Sum<TScalar>(Expression<Func<T, TScalar>> expression) { return Task.Factory.StartNew(() => _dataSet.Sum(expression)); } public Task<TScalar> Average<TScalar>(Expression<Func<T, TScalar>> expression) { return Task.Factory.StartNew(() => _dataSet.Average(expression)); } public Task<bool> Any() { return Task.Factory.StartNew(() => _dataSet.Any()); } public Task<TScalar> Average<TScalar>(Expression<Func<T, TScalar>> expression, Expression<Func<T, bool>> filter) { return Task.Factory.StartNew(() => _dataSet.Average(expression, filter)); } public Task<bool> Any(Expression<Func<T, bool>> filter) { return Task.Factory.StartNew(() => _dataSet.Any(filter)); } public Task<T> ElementAt(int index) { return Task.Factory.StartNew(() => _dataSet.ElementAt(index)); } public Task<List<T>> ToList() { return Task.Factory.StartNew(() => _dataSet.ToList()); } public Task<T[]> ToArray() { return Task.Factory.StartNew(() => _dataSet.ToArray()); } public Task<Dictionary<TKey, T>> ToDictionary<TKey>(Func<T, TKey> keySelector) { return Task.Factory.StartNew(() => _dataSet.ToDictionary(keySelector)); } public Task<Dictionary<TKey, T>> ToDictionary<TKey>(Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer) { return Task.Factory.StartNew(() => _dataSet.ToDictionary(keySelector, comparer)); } public Task<Dictionary<TKey, TValue>> ToDictionary<TKey, TValue>(Func<T, TKey> keySelector, Func<T, TValue> valueSelector) { return Task.Factory.StartNew(() => _dataSet.ToDictionary(keySelector, valueSelector)); } public Task<Dictionary<TKey, TValue>> ToDictionary<TKey, TValue>(Func<T, TKey> keySelector, Func<T, TValue> valueSelector, IEqualityComparer<TKey> comparer) { return Task.Factory.StartNew(() => _dataSet.ToDictionary(keySelector, valueSelector, comparer)); } public Task<ILookup<TKey, T>> ToLookup<TKey>(Func<T, TKey> keySelector) { return Task.Factory.StartNew(() => _dataSet.ToLookup(keySelector)); } public Task<ILookup<TKey, T>> ToLookup<TKey>(Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer) { return Task.Factory.StartNew(() => _dataSet.ToLookup(keySelector, comparer)); } public Task<ILookup<TKey, TValue>> ToLookup<TKey,TValue>(Func<T, TKey> keySelector, Func<T, TValue> valueSelector) { return Task.Factory.StartNew(() => _dataSet.ToLookup(keySelector, valueSelector)); } public Task<ILookup<TKey, TValue>> ToLookup<TKey, TValue>(Func<T, TKey> keySelector, Func<T, TValue> valueSelector, IEqualityComparer<TKey> comparer) { return Task.Factory.StartNew(() => _dataSet.ToLookup(keySelector, valueSelector, comparer)); } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class OpenRead : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(testDir); Directory.SetCurrentDirectory(testDir); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string file1Name = "file1.tmp"; private const string file2Name = "file2.txt"; private const string testDir = "OpenRead"; #endregion Local vars #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { MFTestResults result = MFTestResults.Pass; FileStream file = null; try { try { Log.Comment("Null"); file = File.OpenRead(null); Log.Exception( "Expected ArgumentException, but got " + file.Name ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("String.Empty"); file = File.OpenRead(String.Empty); Log.Exception( "Expected ArgumentException, but got " + file.Name ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("White Space"); file = File.OpenRead(" "); Log.Exception( "Expected ArgumentException, but got " + file.Name ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } finally { if (file != null) file.Close(); } return result; } [TestMethod] public MFTestResults IOExceptionTests() { MFTestResults result = MFTestResults.Pass; FileStream fs = null; try { Log.Comment("Current Directory: " + Directory.GetCurrentDirectory()); try { Log.Comment("non-existent file"); fs = File.OpenRead("non-existent.file"); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCase() { MFTestResults result = MFTestResults.Pass; FileStream fs1 = null; byte[] writebytes = Encoding.UTF8.GetBytes(file2Name); byte[] readbytes = new byte[writebytes.Length + 10]; try { Log.Comment("Create file, and write string to it"); fs1 = new FileStream(file2Name, FileMode.Create); fs1.Write(writebytes, 0, writebytes.Length); fs1.Close(); Log.Comment("OpenRead file"); fs1 = File.OpenRead(file2Name); Log.Comment("Try to read from file"); if (!fs1.CanRead) { Log.Exception( "Expected CanRead to be true!" ); return MFTestResults.Fail; } int read = fs1.Read(readbytes, 0, readbytes.Length); if (read != writebytes.Length) { Log.Exception( "Expected " + writebytes.Length + " bytes, but read " + read + " bytes" ); return MFTestResults.Fail; } string readStr = new string(UTF8Encoding.UTF8.GetChars(readbytes, 0, read)); if (file2Name != readStr) { Log.Exception( "Unexpected read data string: " + readStr + " - Expected: " + file2Name ); return MFTestResults.Fail; } Log.Comment("Try to write to file"); if (fs1.CanWrite) { Log.Exception( "Expected CanWrite to be false!" ); return MFTestResults.Fail; } try { fs1.Write(writebytes, 0, writebytes.Length); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); Log.Exception("Stack: " + ex.Message); return MFTestResults.Fail; } finally { if (fs1 != null) fs1.Close(); } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( IOExceptionTests, "IOExceptionTests" ), new MFTestMethod( ValidCase, "ValidCase" ), }; } } } }
using System; using System.Threading.Tasks; using System.Web; using System.Net; using System.Text; using System.IO; using System.Threading; using System.Collections.Generic; using System.Security.Cryptography; using System.ComponentModel; using SteamBot.SteamGroups; using SteamKit2; using SteamTrade; using SteamKit2.Internal; using SteamTrade.TradeOffer; using System.Globalization; using System.Text.RegularExpressions; namespace SteamBot { public class Bot : IDisposable { #region Bot delegates public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id); #endregion #region Private readonly variables private readonly SteamUser.LogOnDetails logOnDetails; private readonly string schemaLang; private readonly string logFile; private readonly Dictionary<SteamID, UserHandler> userHandlers; private readonly Log.LogLevel consoleLogLevel; private readonly Log.LogLevel fileLogLevel; private readonly UserHandlerCreator createHandler; private readonly bool isProccess; private readonly BackgroundWorker botThread; #endregion #region Private variables private Task<Inventory> myInventoryTask; private TradeManager tradeManager; private TradeOfferManager tradeOfferManager; private int tradePollingInterval; private string myUserNonce; private string myUniqueId; private bool cookiesAreInvalid = true; private List<SteamID> friends; private bool disposed = false; private string consoleInput; #endregion #region Public readonly variables /// <summary> /// Userhandler class bot is running. /// </summary> public readonly string BotControlClass; /// <summary> /// The display name of bot to steam. /// </summary> public readonly string DisplayName; /// <summary> /// The chat response from the config file. /// </summary> public readonly string ChatResponse; /// <summary> /// An array of admins for bot. /// </summary> public readonly IEnumerable<SteamID> Admins; public readonly SteamClient SteamClient; public readonly SteamUser SteamUser; public readonly SteamFriends SteamFriends; public readonly SteamTrading SteamTrade; public readonly SteamGameCoordinator SteamGameCoordinator; public readonly SteamNotifications SteamNotifications; /// <summary> /// The amount of time the bot will trade for. /// </summary> public readonly int MaximumTradeTime; /// <summary> /// The amount of time the bot will wait between user interactions with trade. /// </summary> public readonly int MaximumActionGap; /// <summary> /// The api key of bot. /// </summary> public readonly string ApiKey; public readonly SteamWeb SteamWeb; /// <summary> /// The prefix shown before bot's display name. /// </summary> public readonly string DisplayNamePrefix; /// <summary> /// The instance of the Logger for the bot. /// </summary> public readonly Log Log; #endregion #region Public variables public string AuthCode; public bool IsRunning; /// <summary> /// Is bot fully Logged in. /// Set only when bot did successfully Log in. /// </summary> public bool IsLoggedIn { get; private set; } /// <summary> /// The current trade the bot is in. /// </summary> public Trade CurrentTrade { get; private set; } /// <summary> /// The current game bot is in. /// Default: 0 = No game. /// </summary> public int CurrentGame { get; private set; } public SteamAuth.SteamGuardAccount SteamGuardAccount; #endregion public IEnumerable<SteamID> FriendsList { get { CreateFriendsListIfNecessary(); return friends; } } public Inventory MyInventory { get { myInventoryTask.Wait(); return myInventoryTask.Result; } } /// <summary> /// Compatibility sanity. /// </summary> [Obsolete("Refactored to be Log instead of log")] public Log log { get { return Log; } } public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false) { userHandlers = new Dictionary<SteamID, UserHandler>(); logOnDetails = new SteamUser.LogOnDetails { Username = config.Username, Password = config.Password }; DisplayName = config.DisplayName; ChatResponse = config.ChatResponse; MaximumTradeTime = config.MaximumTradeTime; MaximumActionGap = config.MaximumActionGap; DisplayNamePrefix = config.DisplayNamePrefix; tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval; schemaLang = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en"; Admins = config.Admins; ApiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey; isProccess = process; try { if( config.LogLevel != null ) { consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true); Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName); } else consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true); } catch (ArgumentException) { Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName); consoleLogLevel = Log.LogLevel.Info; } try { fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true); } catch (ArgumentException) { Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName); fileLogLevel = Log.LogLevel.Info; } logFile = config.LogFile; Log = new Log(logFile, DisplayName, consoleLogLevel, fileLogLevel); createHandler = handlerCreator; BotControlClass = config.BotControlClass; SteamWeb = new SteamWeb(); // Hacking around https ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate; Log.Debug ("Initializing Steam Bot..."); SteamClient = new SteamClient(); SteamClient.AddHandler(new SteamNotifications()); SteamTrade = SteamClient.GetHandler<SteamTrading>(); SteamUser = SteamClient.GetHandler<SteamUser>(); SteamFriends = SteamClient.GetHandler<SteamFriends>(); SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>(); SteamNotifications = SteamClient.GetHandler<SteamNotifications>(); botThread = new BackgroundWorker { WorkerSupportsCancellation = true }; botThread.DoWork += BackgroundWorkerOnDoWork; botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted; botThread.RunWorkerAsync(); } ~Bot() { Dispose(false); } private void CreateFriendsListIfNecessary() { if (friends != null) return; friends = new List<SteamID>(); for (int i = 0; i < SteamFriends.GetFriendCount(); i++) friends.Add(SteamFriends.GetFriendByIndex(i)); } /// <summary> /// Occurs when the bot needs the SteamGuard authentication code. /// </summary> /// <remarks> /// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/> /// </remarks> public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired; /// <summary> /// Starts the callback thread and connects to Steam via SteamKit2. /// </summary> /// <remarks> /// THIS NEVER RETURNS. /// </remarks> /// <returns><c>true</c>. See remarks</returns> public bool StartBot() { IsRunning = true; Log.Info("Connecting..."); if (!botThread.IsBusy) botThread.RunWorkerAsync(); SteamClient.Connect(); Log.Success("Done Loading Bot!"); return true; // never get here } /// <summary> /// Disconnect from the Steam network and stop the callback /// thread. /// </summary> public void StopBot() { IsRunning = false; Log.Debug("Trying to shut down bot thread."); SteamClient.Disconnect(); botThread.CancelAsync(); while (botThread.IsBusy) Thread.Yield(); userHandlers.Clear(); } /// <summary> /// Creates a new trade with the given partner. /// </summary> /// <returns> /// <c>true</c>, if trade was opened, /// <c>false</c> if there is another trade that must be closed first. /// </returns> public bool OpenTrade (SteamID other) { if (CurrentTrade != null || CheckCookies() == false) return false; SteamTrade.Trade(other); return true; } /// <summary> /// Closes the current active trade. /// </summary> public void CloseTrade() { if (CurrentTrade == null) return; UnsubscribeTrade (GetUserHandler (CurrentTrade.OtherSID), CurrentTrade); tradeManager.StopTrade (); CurrentTrade = null; } void OnTradeTimeout(object sender, EventArgs args) { // ignore event params and just null out the trade. GetUserHandler(CurrentTrade.OtherSID).OnTradeTimeout(); } /// <summary> /// Create a new trade offer with the specified partner /// </summary> /// <param name="other">SteamId of the partner</param> /// <returns></returns> public TradeOffer NewTradeOffer(SteamID other) { return tradeOfferManager.NewOffer(other); } /// <summary> /// Try to get a specific trade offer using the offerid /// </summary> /// <param name="offerId"></param> /// <param name="tradeOffer"></param> /// <returns></returns> public bool TryGetTradeOffer(string offerId, out TradeOffer tradeOffer) { return tradeOfferManager.GetOffer(offerId, out tradeOffer); } public void HandleBotCommand(string command) { try { if (command == "linkauth") { LinkMobileAuth(); } else if (command == "getauth") { try { Log.Success("Generated Steam Guard code: " + SteamGuardAccount.GenerateSteamGuardCode()); } catch (NullReferenceException) { Log.Error("Unable to generate Steam Guard code."); } } else if (command == "unlinkauth") { if (SteamGuardAccount == null) { Log.Error("Mobile authenticator is not active on this bot."); } else if (SteamGuardAccount.DeactivateAuthenticator()) { Log.Success("Deactivated authenticator on this account."); } else { Log.Error("Failed to deactivate authenticator on this account."); } } else { GetUserHandler(SteamClient.SteamID).OnBotCommand(command); } } catch (ObjectDisposedException e) { // Writing to console because odds are the error was caused by a disposed Log. Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); if (!this.IsRunning) { Console.WriteLine("The Bot is no longer running and could not write to the Log. Try Starting this bot first."); } } catch (Exception e) { Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); } } public void HandleInput(string input) { consoleInput = input; } public string WaitForInput() { consoleInput = null; while (true) { if (consoleInput != null) { return consoleInput; } Thread.Sleep(5); } } bool HandleTradeSessionStart (SteamID other) { if (CurrentTrade != null) return false; try { tradeManager.InitializeTrade(SteamUser.SteamID, other); CurrentTrade = tradeManager.CreateTrade(SteamUser.SteamID, other); CurrentTrade.OnClose += CloseTrade; SubscribeTrade(CurrentTrade, GetUserHandler(other)); tradeManager.StartTradeThread(CurrentTrade); return true; } catch (SteamTrade.Exceptions.InventoryFetchException) { // we shouldn't get here because the inv checks are also // done in the TradeProposedCallback handler. /*string response = String.Empty; if (ie.FailingSteamId.ConvertToUInt64() == other.ConvertToUInt64()) { response = "Trade failed. Could not correctly fetch your backpack. Either the inventory is inaccessible or your backpack is private."; } else { response = "Trade failed. Could not correctly fetch my backpack."; } SteamFriends.SendChatMessage(other, EChatEntryType.ChatMsg, response); Log.Info ("Bot sent other: {0}", response); CurrentTrade = null;*/ return false; } } public void SetGamePlaying(int id) { var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed); if (id != 0) gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed { game_id = new GameID(id), }); SteamClient.Send(gamePlaying); CurrentGame = id; } void HandleSteamMessage(ICallbackMsg msg) { Log.Debug(msg.ToString()); #region Login msg.Handle<SteamClient.ConnectedCallback> (callback => { Log.Debug ("Connection Callback: {0}", callback.Result); if (callback.Result == EResult.OK) { UserLogOn(); } else { Log.Error ("Failed to connect to Steam Community, trying again..."); SteamClient.Connect (); } }); msg.Handle<SteamUser.LoggedOnCallback> (callback => { Log.Debug("Logged On Callback: {0}", callback.Result); if (callback.Result == EResult.OK) { myUserNonce = callback.WebAPIUserNonce; } else { Log.Error("Login Error: {0}", callback.Result); } if (callback.Result == EResult.AccountLogonDeniedNeedTwoFactorCode) { var mobileAuthCode = GetMobileAuthCode(); if (string.IsNullOrEmpty(mobileAuthCode)) { Log.Error("Failed to generate 2FA code. Make sure you have linked the authenticator via SteamBot."); } else { logOnDetails.TwoFactorCode = mobileAuthCode; Log.Success("Generated 2FA code."); } } else if (callback.Result == EResult.TwoFactorCodeMismatch) { SteamAuth.TimeAligner.AlignTime(); logOnDetails.TwoFactorCode = SteamGuardAccount.GenerateSteamGuardCode(); Log.Success("Regenerated 2FA code."); } else if (callback.Result == EResult.AccountLogonDenied) { Log.Interface ("This account is SteamGuard enabled. Enter the code via the `auth' command."); // try to get the steamguard auth code from the event callback var eva = new SteamGuardRequiredEventArgs(); FireOnSteamGuardRequired(eva); if (!String.IsNullOrEmpty(eva.SteamGuard)) logOnDetails.AuthCode = eva.SteamGuard; else logOnDetails.AuthCode = Console.ReadLine(); } else if (callback.Result == EResult.InvalidLoginAuthCode) { Log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command."); logOnDetails.AuthCode = Console.ReadLine(); } }); msg.Handle<SteamUser.LoginKeyCallback> (callback => { myUniqueId = callback.UniqueID.ToString(); UserWebLogOn(); if (Trade.CurrentSchema == null) { Log.Info ("Downloading Schema..."); Trade.CurrentSchema = Schema.FetchSchema (ApiKey, schemaLang); Log.Success ("Schema Downloaded!"); } SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName); SteamFriends.SetPersonaState (EPersonaState.Online); Log.Success ("Steam Bot Logged In Completely!"); GetUserHandler(SteamClient.SteamID).OnLoginCompleted(); }); msg.Handle<SteamUser.WebAPIUserNonceCallback>(webCallback => { Log.Debug("Received new WebAPIUserNonce."); if (webCallback.Result == EResult.OK) { myUserNonce = webCallback.Nonce; UserWebLogOn(); } else { Log.Error("WebAPIUserNonce Error: " + webCallback.Result); } }); msg.Handle<SteamUser.UpdateMachineAuthCallback>( authCallback => OnUpdateMachineAuthCallback(authCallback) ); #endregion #region Friends msg.Handle<SteamFriends.FriendsListCallback>(callback => { foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList) { switch (friend.SteamID.AccountType) { case EAccountType.Clan: if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnGroupAdd()) { AcceptGroupInvite(friend.SteamID); } else { DeclineGroupInvite(friend.SteamID); } } break; default: CreateFriendsListIfNecessary(); if (friend.Relationship == EFriendRelationship.None) { friends.Remove(friend.SteamID); GetUserHandler(friend.SteamID).OnFriendRemove(); RemoveUserHandler(friend.SteamID); } else if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnFriendAdd()) { if (!friends.Contains(friend.SteamID)) { friends.Add(friend.SteamID); } else { Log.Error("Friend was added who was already in friends list: " + friend.SteamID); } SteamFriends.AddFriend(friend.SteamID); } else { SteamFriends.RemoveFriend(friend.SteamID); RemoveUserHandler(friend.SteamID); } } break; } } }); msg.Handle<SteamFriends.FriendMsgCallback> (callback => { EChatEntryType type = callback.EntryType; if (callback.EntryType == EChatEntryType.ChatMsg) { Log.Info ("Chat Message from {0}: {1}", SteamFriends.GetFriendPersonaName (callback.Sender), callback.Message ); GetUserHandler(callback.Sender).OnMessageHandler(callback.Message, type); } }); #endregion #region Group Chat msg.Handle<SteamFriends.ChatMsgCallback>(callback => { GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message); }); #endregion #region Trading msg.Handle<SteamTrading.SessionStartCallback> (callback => { bool started = HandleTradeSessionStart (callback.OtherClient); if (!started) Log.Error ("Could not start the trade session."); else Log.Debug ("SteamTrading.SessionStartCallback handled successfully. Trade Opened."); }); msg.Handle<SteamTrading.TradeProposedCallback> (callback => { if (CheckCookies() == false) { SteamTrade.RespondToTrade(callback.TradeID, false); return; } try { tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient); } catch (WebException we) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade error: " + we.Message); SteamTrade.RespondToTrade(callback.TradeID, false); return; } catch (Exception) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade declined. Could not correctly fetch your backpack."); SteamTrade.RespondToTrade(callback.TradeID, false); return; } //if (tradeManager.OtherInventory.IsPrivate) //{ // SteamFriends.SendChatMessage(callback.OtherClient, // EChatEntryType.ChatMsg, // "Trade declined. Your backpack cannot be private."); // SteamTrade.RespondToTrade (callback.TradeID, false); // return; //} if (CurrentTrade == null && GetUserHandler (callback.OtherClient).OnTradeRequest ()) SteamTrade.RespondToTrade (callback.TradeID, true); else SteamTrade.RespondToTrade (callback.TradeID, false); }); msg.Handle<SteamTrading.TradeResultCallback> (callback => { if (callback.Response == EEconTradeResponse.Accepted) { Log.Debug("Trade Status: {0}", callback.Response); Log.Info ("Trade Accepted!"); GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString()); } else { Log.Warn("Trade failed: {0}", callback.Response); CloseTrade (); GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString()); } }); #endregion #region Disconnect msg.Handle<SteamUser.LoggedOffCallback> (callback => { IsLoggedIn = false; Log.Warn("Logged off Steam. Reason: {0}", callback.Result); }); msg.Handle<SteamClient.DisconnectedCallback> (callback => { if(IsLoggedIn) { IsLoggedIn = false; CloseTrade(); Log.Warn("Disconnected from Steam Network!"); } SteamClient.Connect (); }); #endregion #region Notifications msg.Handle<SteamBot.SteamNotifications.NotificationCallback>(callback => { //currently only appears to be of trade offer if (callback.Notifications.Count != 0) { foreach (var notification in callback.Notifications) { Log.Info(notification.UserNotificationType + " notification"); } } // Get offers only if cookies are valid if (CheckCookies()) tradeOfferManager.GetOffers(); }); msg.Handle<SteamBot.SteamNotifications.CommentNotificationCallback>(callback => { //various types of comment notifications on profile/activity feed etc //Log.Info("received CommentNotificationCallback"); //Log.Info("New Commments " + callback.CommentNotifications.CountNewComments); //Log.Info("New Commments Owners " + callback.CommentNotifications.CountNewCommentsOwner); //Log.Info("New Commments Subscriptions" + callback.CommentNotifications.CountNewCommentsSubscriptions); }); #endregion } string GetMobileAuthCode() { var authFile = Path.Combine("authfiles", String.Format("{0}.auth", logOnDetails.Username)); if (File.Exists(authFile)) { SteamGuardAccount = Newtonsoft.Json.JsonConvert.DeserializeObject<SteamAuth.SteamGuardAccount>(File.ReadAllText(authFile)); return SteamGuardAccount.GenerateSteamGuardCode(); } return string.Empty; } /// <summary> /// Link a mobile authenticator to bot account, using SteamTradeOffersBot as the authenticator. /// Called from bot manager console. Usage: "exec [index] linkauth" /// If successful, 2FA will be required upon the next login. /// Use "exec [index] getauth" if you need to get a Steam Guard code for the account. /// To deactivate the authenticator, use "exec [index] unlinkauth". /// </summary> void LinkMobileAuth() { new Thread(() => { var login = new SteamAuth.UserLogin(logOnDetails.Username, logOnDetails.Password); var loginResult = login.DoLogin(); if (loginResult == SteamAuth.LoginResult.NeedEmail) { while (loginResult == SteamAuth.LoginResult.NeedEmail) { Log.Interface("Enter Steam Guard code from email (type \"input [index] [code]\"):"); var emailCode = WaitForInput(); login.EmailCode = emailCode; loginResult = login.DoLogin(); } } if (loginResult == SteamAuth.LoginResult.LoginOkay) { Log.Info("Linking mobile authenticator..."); var authLinker = new SteamAuth.AuthenticatorLinker(login.Session); var addAuthResult = authLinker.AddAuthenticator(); if (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.MustProvidePhoneNumber) { while (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.MustProvidePhoneNumber) { Log.Interface("Enter phone number with country code, e.g. +1XXXXXXXXXXX (type \"input [index] [number]\"):"); var phoneNumber = WaitForInput(); authLinker.PhoneNumber = phoneNumber; addAuthResult = authLinker.AddAuthenticator(); } } if (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.AwaitingFinalization) { SteamGuardAccount = authLinker.LinkedAccount; try { var authFile = Path.Combine("authfiles", String.Format("{0}.auth", logOnDetails.Username)); Directory.CreateDirectory(Path.Combine(System.Windows.Forms.Application.StartupPath, "authfiles")); File.WriteAllText(authFile, Newtonsoft.Json.JsonConvert.SerializeObject(SteamGuardAccount)); Log.Interface("Enter SMS code (type \"input [index] [code]\"):"); var smsCode = WaitForInput(); var authResult = authLinker.FinalizeAddAuthenticator(smsCode); if (authResult == SteamAuth.AuthenticatorLinker.FinalizeResult.Success) { Log.Success("Linked authenticator."); } else { Log.Error("Error linking authenticator: " + authResult); } } catch (IOException) { Log.Error("Failed to save auth file. Aborting authentication."); } } else { Log.Error("Error adding authenticator: " + addAuthResult); } } else { if (loginResult == SteamAuth.LoginResult.Need2FA) { Log.Error("Mobile authenticator has already been linked!"); } else { Log.Error("Error performing mobile login: " + loginResult); } } }).Start(); } void UserLogOn() { // get sentry file which has the machine hw info saved // from when a steam guard code was entered Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); FileInfo fi = new FileInfo(System.IO.Path.Combine("sentryfiles",String.Format("{0}.sentryfile", logOnDetails.Username))); if (fi.Exists && fi.Length > 0) logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName)); else logOnDetails.SentryFileHash = null; SteamUser.LogOn(logOnDetails); } void UserWebLogOn() { do { IsLoggedIn = SteamWeb.Authenticate(myUniqueId, SteamClient, myUserNonce); if(!IsLoggedIn) { Log.Warn("Authentication failed, retrying in 2s..."); Thread.Sleep(2000); } } while(!IsLoggedIn); Log.Success("User Authenticated!"); tradeManager = new TradeManager(ApiKey, SteamWeb); tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximumActionGap, tradePollingInterval); tradeManager.OnTimeout += OnTradeTimeout; tradeOfferManager = new TradeOfferManager(ApiKey, SteamWeb); SubscribeTradeOffer(tradeOfferManager); cookiesAreInvalid = false; // Success, check trade offers which we have received while we were offline tradeOfferManager.GetOffers(); } /// <summary> /// Checks if sessionId and token cookies are still valid. /// Sets cookie flag if they are invalid. /// </summary> /// <returns>true if cookies are valid; otherwise false</returns> bool CheckCookies() { // We still haven't re-authenticated if (cookiesAreInvalid) return false; try { if (!SteamWeb.VerifyCookies()) { // Cookies are no longer valid Log.Warn("Cookies are invalid. Need to re-authenticate."); cookiesAreInvalid = true; SteamUser.RequestWebAPIUserNonce(); return false; } } catch { // Even if exception is caught, we should still continue. Log.Warn("Cookie check failed. http://steamcommunity.com is possibly down."); } return true; } UserHandler GetUserHandler(SteamID sid) { if (!userHandlers.ContainsKey(sid)) userHandlers[sid] = createHandler(this, sid); return userHandlers[sid]; } void RemoveUserHandler(SteamID sid) { if (userHandlers.ContainsKey(sid)) userHandlers.Remove(sid); } static byte [] SHAHash (byte[] input) { SHA1Managed sha = new SHA1Managed(); byte[] output = sha.ComputeHash( input ); sha.Clear(); return output; } void OnUpdateMachineAuthCallback(SteamUser.UpdateMachineAuthCallback machineAuth) { byte[] hash = SHAHash (machineAuth.Data); Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); File.WriteAllBytes (System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data); var authResponse = new SteamUser.MachineAuthDetails { BytesWritten = machineAuth.BytesToWrite, FileName = machineAuth.FileName, FileSize = machineAuth.BytesToWrite, Offset = machineAuth.Offset, SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs LastError = 0, // result from win32 GetLastError Result = EResult.OK, // if everything went okay, otherwise ~who knows~ JobID = machineAuth.JobID, // so we respond to the correct server job }; // send off our response SteamUser.SendMachineAuthResponse (authResponse); } /// <summary> /// Gets the bot's inventory and stores it in MyInventory. /// </summary> /// <example> This sample shows how to find items in the bot's inventory from a user handler. /// <code> /// Bot.GetInventory(); // Get the inventory first /// foreach (var item in Bot.MyInventory.Items) /// { /// if (item.Defindex == 5021) /// { /// // Bot has a key in its inventory /// } /// } /// </code> /// </example> public void GetInventory() { myInventoryTask = Task.Factory.StartNew((Func<Inventory>) FetchBotsInventory); } public void TradeOfferRouter(TradeOffer offer) { if (offer.OfferState == TradeOfferState.TradeOfferStateActive) { GetUserHandler(offer.PartnerSteamId).OnNewTradeOffer(offer); } } public void SubscribeTradeOffer(TradeOfferManager tradeOfferManager) { tradeOfferManager.OnNewTradeOffer += TradeOfferRouter; } //todo: should unsubscribe eventually... public void UnsubscribeTradeOffer(TradeOfferManager tradeOfferManager) { tradeOfferManager.OnNewTradeOffer -= TradeOfferRouter; } /// <summary> /// Subscribes all listeners of this to the trade. /// </summary> public void SubscribeTrade (Trade trade, UserHandler handler) { trade.OnSuccess += handler.OnTradeSuccess; trade.OnAwaitingConfirmation += handler._OnTradeAwaitingConfirmation; trade.OnClose += handler.OnTradeClose; trade.OnError += handler.OnTradeError; trade.OnStatusError += handler.OnStatusError; //trade.OnTimeout += OnTradeTimeout; trade.OnAfterInit += handler.OnTradeInit; trade.OnUserAddItem += handler.OnTradeAddItem; trade.OnUserRemoveItem += handler.OnTradeRemoveItem; trade.OnMessage += handler.OnTradeMessageHandler; trade.OnUserSetReady += handler.OnTradeReadyHandler; trade.OnUserAccept += handler.OnTradeAcceptHandler; } /// <summary> /// Unsubscribes all listeners of this from the current trade. /// </summary> public void UnsubscribeTrade (UserHandler handler, Trade trade) { trade.OnSuccess -= handler.OnTradeSuccess; trade.OnAwaitingConfirmation -= handler._OnTradeAwaitingConfirmation; trade.OnClose -= handler.OnTradeClose; trade.OnError -= handler.OnTradeError; trade.OnStatusError -= handler.OnStatusError; //Trade.OnTimeout -= OnTradeTimeout; trade.OnAfterInit -= handler.OnTradeInit; trade.OnUserAddItem -= handler.OnTradeAddItem; trade.OnUserRemoveItem -= handler.OnTradeRemoveItem; trade.OnMessage -= handler.OnTradeMessageHandler; trade.OnUserSetReady -= handler.OnTradeReadyHandler; trade.OnUserAccept -= handler.OnTradeAcceptHandler; } /// <summary> /// Fetch the Bot's inventory and log a warning if it's private /// </summary> private Inventory FetchBotsInventory() { var inventory = Inventory.FetchInventory(SteamUser.SteamID, ApiKey, SteamWeb); if(inventory.IsPrivate) { log.Warn("The bot's backpack is private! If your bot adds any items it will fail! Your bot's backpack should be Public."); } return inventory; } public void AcceptAllMobileTradeConfirmations() { if (SteamGuardAccount == null) { Log.Warn("Bot account does not have 2FA enabled."); } else { SteamGuardAccount.Session.SteamLogin = SteamWeb.Token; SteamGuardAccount.Session.SteamLoginSecure = SteamWeb.TokenSecure; try { foreach (var confirmation in SteamGuardAccount.FetchConfirmations()) { if (SteamGuardAccount.AcceptConfirmation(confirmation)) { Log.Success("Confirmed {0}. (Confirmation ID #{1})", confirmation.ConfirmationDescription, confirmation.ConfirmationID); } } } catch (SteamAuth.SteamGuardAccount.WGTokenInvalidException) { Log.Error("Invalid session when trying to fetch trade confirmations."); } } } /// <summary> /// Get duration of escrow in days. Call this before sending a trade offer. /// Credit to: https://www.reddit.com/r/SteamBot/comments/3w8j7c/code_getescrowduration_for_c/ /// </summary> /// <param name="steamId">Steam ID of user you want to send a trade offer to</param> /// <param name="token">User's trade token. Can be an empty string if user is on bot's friends list.</param> /// <returns>TradeOfferEscrowDuration</returns> public TradeOfferEscrowDuration GetEscrowDuration(SteamID steamId, string token) { var url = "https://steamcommunity.com/tradeoffer/new/"; var data = new System.Collections.Specialized.NameValueCollection(); data.Add("partner", steamId.AccountID.ToString()); if (!string.IsNullOrEmpty(token)) { data.Add("token", token); } var resp = SteamWeb.Fetch(url, "GET", data, false); if (string.IsNullOrWhiteSpace(resp)) { throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration."); } return ParseEscrowResponse(resp); } /// <summary> /// Get duration of escrow in days. Call this after receiving a trade offer. /// </summary> /// <param name="tradeOfferId">The ID of the trade offer</param> /// <returns>TradeOfferEscrowDuration</returns> public TradeOfferEscrowDuration GetEscrowDuration(string tradeOfferId) { var url = "http://steamcommunity.com/tradeoffer/" + tradeOfferId; var resp = SteamWeb.Fetch(url, "GET", null, false); if (string.IsNullOrWhiteSpace(resp)) { throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration."); } return ParseEscrowResponse(resp); } private TradeOfferEscrowDuration ParseEscrowResponse(string resp) { var myM = Regex.Match(resp, @"g_daysMyEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase); var theirM = Regex.Match(resp, @"g_daysTheirEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase); if (!myM.Groups["days"].Success || !theirM.Groups["days"].Success) { throw new TradeOfferEscrowDurationParseException(); } return new TradeOfferEscrowDuration() { DaysMyEscrow = int.Parse(myM.Groups["days"].Value), DaysTheirEscrow = int.Parse(theirM.Groups["days"].Value) }; } public class TradeOfferEscrowDuration { public int DaysMyEscrow { get; set; } public int DaysTheirEscrow { get; set; } } public class TradeOfferEscrowDurationParseException : Exception { } #region Background Worker Methods private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { if (runWorkerCompletedEventArgs.Error != null) { Exception ex = runWorkerCompletedEventArgs.Error; Log.Error("Unhandled exceptions in bot {0} callback thread: {1} {2}", DisplayName, Environment.NewLine, ex); Log.Info("This bot died. Stopping it.."); //backgroundWorker.RunWorkerAsync(); //Thread.Sleep(10000); StopBot(); //StartBot(); } } private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { ICallbackMsg msg; while (!botThread.CancellationPending) { try { msg = SteamClient.WaitForCallback(true); HandleSteamMessage(msg); } catch (WebException e) { Log.Error("URI: {0} >> {1}", (e.Response != null && e.Response.ResponseUri != null ? e.Response.ResponseUri.ToString() : "unknown"), e.ToString()); System.Threading.Thread.Sleep(45000);//Steam is down, retry in 45 seconds. } catch (Exception e) { Log.Error(e.ToString()); Log.Warn("Restarting bot..."); } } } #endregion Background Worker Methods private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e) { // Set to null in case this is another attempt this.AuthCode = null; EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired; if (handler != null) handler(this, e); else { while (true) { if (this.AuthCode != null) { e.SteamGuard = this.AuthCode; break; } Thread.Sleep(5); } } } #region Group Methods /// <summary> /// Accepts the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to accept the invite from.</param> private void AcceptGroupInvite(SteamID group) { var AcceptInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); AcceptInvite.Body.GroupID = group.ConvertToUInt64(); AcceptInvite.Body.AcceptInvite = true; this.SteamClient.Send(AcceptInvite); } /// <summary> /// Declines the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to decline the invite from.</param> private void DeclineGroupInvite(SteamID group) { var DeclineInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); DeclineInvite.Body.GroupID = group.ConvertToUInt64(); DeclineInvite.Body.AcceptInvite = false; this.SteamClient.Send(DeclineInvite); } /// <summary> /// Invites a use to the specified Steam Group /// </summary> /// <param name="user">SteamID of the user to invite.</param> /// <param name="groupId">SteamID of the group to invite the user to.</param> public void InviteUserToGroup(SteamID user, SteamID groupId) { var InviteUser = new ClientMsg<CMsgInviteUserToGroup>((int)EMsg.ClientInviteUserToClan); InviteUser.Body.GroupID = groupId.ConvertToUInt64(); InviteUser.Body.Invitee = user.ConvertToUInt64(); InviteUser.Body.UnknownInfo = true; this.SteamClient.Send(InviteUser); } #endregion public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposed) return; StopBot(); if (disposing) Log.Dispose(); disposed = true; } } }
using System; using System.Collections; using Xml = System.Xml; using IO = System.IO; // 16/6/03 /// <summary> /// Stores key-value configuration pairs in an xml file. /// </summary> public class XmlStorage : IStorage { private const string rootName = "storage"; private const string keyName = "key"; private const string subsectionName = "subsection"; private bool isRoot = false; private string fileName = string.Empty; private Hashtable keyTable = new Hashtable(); private Hashtable subsectionTable = new Hashtable(); private XmlStorage root = null; private string name; /// <summary> /// Constructs an XmlStorage. /// This is used to create sub-sections /// </summary> /// <param name="root">Root XmlStorage instance</param> /// <param name="name">Name of subsection</param> private XmlStorage(XmlStorage root, string name) { this.isRoot = false; this.root = root; this.name = name; } /// <summary> /// Constructs an XmlStorage. /// This is used to create sub-sections /// </summary> /// <param name="root">Root XmlStorage instance</param> /// <param name="name">Name of subsection</param> /// <param name="reader">Xml reader to read elements from</param> private XmlStorage(XmlStorage root, string name, Xml.XmlTextReader reader) { this.isRoot = false; this.root = root; this.name = name; ReadElements(reader); } /// <summary> /// Reads the xml elements from the reader and stores them in the hashtable /// </summary> /// <param name="reader"></param> private void ReadElements(Xml.XmlTextReader reader) { try { while (reader.Read()) { switch (reader.NodeType) { case Xml.XmlNodeType.Element: // we've hit a value, so read it in if (reader.Name == keyName) { string name = reader.GetAttribute("name"); if (name == string.Empty || name == "") throw new ApplicationException(); if (!reader.IsEmptyElement && reader.Read()) { // System.Diagnostics.Debug.WriteLine("Read: " + this.name + " " + name + " = " + reader.Value); this.keyTable.Add(name, reader.Value); } else this.keyTable.Add(name, string.Empty); } // hit a subsection, read in the name of it else if (reader.Name == subsectionName) { if (!reader.IsEmptyElement) { string name = reader.GetAttribute("name"); if (name == string.Empty || name == "") throw new ApplicationException(); this.subsectionTable.Add(name, new XmlStorage(this.root, name, reader)); } } break; case Xml.XmlNodeType.EndElement: // end of subsection, party is over if (reader.Name == subsectionName && !this.isRoot) return; break; } } } catch (Exception e) { throw new ApplicationException("Malformed xml storage file", e); } } /// <summary> /// Constructs an XmlStorage class /// </summary> /// <param name="fileName">Xml file to use</param> public XmlStorage(string fileName) { this.isRoot = true; this.root = this; this.fileName = fileName; this.name = "Root"; try { IO.FileStream stream = new IO.FileStream(fileName, IO.FileMode.Open, IO.FileAccess.Read); Xml.XmlTextReader reader = new Xml.XmlTextReader(stream); try { this.ReadElements(reader); } finally { reader.Close(); stream.Close(); } } catch (IO.FileNotFoundException) {} } #region Close methods /// <summary> /// Closes the Xml file /// </summary> public void Close() { Flush(); } /// <summary> /// Flushes the hashtable to the xml file /// </summary> public void Flush() { if (isRoot) { Xml.XmlTextWriter writer = new Xml.XmlTextWriter(this.fileName, System.Text.Encoding.ASCII); try { // writer.Formatting = Xml.Formatting.Indented; writer.WriteStartDocument(true); writer.WriteStartElement(rootName); WriteElements(writer); writer.WriteEndElement(); } finally { writer.Close(); } } } /// <summary> /// Writes elements to an xml writer /// </summary> /// <param name="writer"></param> private void WriteElements(Xml.XmlTextWriter writer) { // iterate across all keys in this section and write them to the xml file IDictionaryEnumerator enumerator = this.keyTable.GetEnumerator(); while (enumerator.MoveNext()) { writer.WriteStartElement(keyName); writer.WriteAttributeString("name", (string)enumerator.Key); writer.WriteString((string)enumerator.Value); // System.Diagnostics.Debug.WriteLine( //"Wrote: " + this.name + " " + (string)enumerator.Key + " = " + (string)enumerator.Value); writer.WriteEndElement(); } // then do it for all sub sections foreach (XmlStorage xml in this.subsectionTable.Values) { writer.WriteStartElement(subsectionName); writer.WriteAttributeString("name", xml.name); xml.WriteElements(writer); writer.WriteEndElement(); } } #endregion #region Sub-section methods /// <summary> /// Creates a subsection /// </summary> IStorage IStorage.CreateSubSection(string name) { return this.CreateSubSection(name); } /// <summary> /// Creates an Xml subsection /// </summary> /// <param name="name">Name of subsection</param> /// <returns></returns> public XmlStorage CreateSubSection(string name) { if (this.subsectionTable.Contains(name)) return (XmlStorage)this.subsectionTable[name]; else { XmlStorage sub = new XmlStorage(this.root, name); this.subsectionTable.Add(name, sub); return sub; } } #endregion #region Write methods /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, bool val) { if (!this.keyTable.Contains(name)) this.keyTable.Add(name, Xml.XmlConvert.ToString(val)); else this.keyTable[name] = Xml.XmlConvert.ToString(val); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, char val) { if (!this.keyTable.Contains(name)) this.keyTable.Add(name, Xml.XmlConvert.ToString(val)); else this.keyTable[name] = Xml.XmlConvert.ToString(val); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, byte val) { if (!this.keyTable.Contains(name)) this.keyTable.Add(name, Xml.XmlConvert.ToString(val)); else this.keyTable[name] = Xml.XmlConvert.ToString(val); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, string val) { if (val == string.Empty || val == "") val = ""; if (!this.keyTable.Contains(name)) this.keyTable.Add(name, val); else this.keyTable[name] = val; } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, Single val) { if (!this.keyTable.Contains(name)) this.keyTable.Add(name, Xml.XmlConvert.ToString(val)); else this.keyTable[name] = Xml.XmlConvert.ToString(val); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, Double val) { if (!this.keyTable.Contains(name)) this.keyTable.Add(name, Xml.XmlConvert.ToString(val)); else this.keyTable[name] = Xml.XmlConvert.ToString(val); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, Int16 val) { if (!this.keyTable.Contains(name)) this.keyTable.Add(name, Xml.XmlConvert.ToString(val)); else this.keyTable[name] = Xml.XmlConvert.ToString(val); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, Int32 val) { if (!this.keyTable.Contains(name)) this.keyTable.Add(name, Xml.XmlConvert.ToString(val)); else this.keyTable[name] = Xml.XmlConvert.ToString(val); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, Int64 val) { if (!this.keyTable.Contains(name)) this.keyTable.Add(name, Xml.XmlConvert.ToString(val)); else this.keyTable[name] = Xml.XmlConvert.ToString(val); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, UInt16 val) { if (!this.keyTable.Contains(name)) this.keyTable.Add(name, Xml.XmlConvert.ToString(val)); else this.keyTable[name] = Xml.XmlConvert.ToString(val); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, UInt32 val) { if (!this.keyTable.Contains(name)) this.keyTable.Add(name, Xml.XmlConvert.ToString(val)); else this.keyTable[name] = Xml.XmlConvert.ToString(val); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void Write(string name, UInt64 val) { if (!this.keyTable.Contains(name)) this.keyTable.Add(name, Xml.XmlConvert.ToString(val)); else this.keyTable[name] = Xml.XmlConvert.ToString(val); } #endregion #region Read methods /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public bool ReadBool(string name, bool def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return Xml.XmlConvert.ToBoolean((string)this.keyTable[name]); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public char ReadChar(string name, char def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return Xml.XmlConvert.ToChar((string)this.keyTable[name]); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public byte ReadByte(string name, byte def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return Xml.XmlConvert.ToByte((string)this.keyTable[name]); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public string ReadString(string name, string def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return (string)this.keyTable[name]; } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public Single ReadSingle(string name, Single def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return Xml.XmlConvert.ToSingle((string)this.keyTable[name]); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public Double ReadDouble(string name, Double def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return Xml.XmlConvert.ToDouble((string)this.keyTable[name]); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public Int16 ReadInt16(string name, Int16 def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return Xml.XmlConvert.ToInt16((string)this.keyTable[name]); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public Int32 ReadInt32(string name, Int32 def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return Xml.XmlConvert.ToInt32((string)this.keyTable[name]); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public Int64 ReadInt64(string name, Int64 def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return Xml.XmlConvert.ToInt64((string)this.keyTable[name]); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public UInt16 ReadUInt16(string name, UInt16 def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return Xml.XmlConvert.ToUInt16((string)this.keyTable[name]); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public UInt32 ReadUInt32(string name, UInt32 def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return Xml.XmlConvert.ToUInt32((string)this.keyTable[name]); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="def"></param> /// <returns></returns> public UInt64 ReadUInt64(string name, UInt64 def) { if (!this.keyTable.Contains(name)) { Write(name, def); return def; } else return Xml.XmlConvert.ToUInt64((string)this.keyTable[name]); } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace System.Net.Http.Headers { // The purpose of this type is to extract the handling of general headers in one place rather than duplicating // functionality in both HttpRequestHeaders and HttpResponseHeaders. internal sealed class HttpGeneralHeaders { private HttpHeaderValueCollection<string> _connection; private HttpHeaderValueCollection<string> _trailer; private HttpHeaderValueCollection<TransferCodingHeaderValue> _transferEncoding; private HttpHeaderValueCollection<ProductHeaderValue> _upgrade; private HttpHeaderValueCollection<ViaHeaderValue> _via; private HttpHeaderValueCollection<WarningHeaderValue> _warning; private HttpHeaderValueCollection<NameValueHeaderValue> _pragma; private HttpHeaders _parent; private bool _transferEncodingChunkedSet; private bool _connectionCloseSet; public CacheControlHeaderValue CacheControl { get { return (CacheControlHeaderValue)_parent.GetParsedValues(HttpKnownHeaderNames.CacheControl); } set { _parent.SetOrRemoveParsedValue(HttpKnownHeaderNames.CacheControl, value); } } public HttpHeaderValueCollection<string> Connection { get { return ConnectionCore; } } public bool? ConnectionClose { get { if (ConnectionCore.IsSpecialValueSet) { return true; } if (_connectionCloseSet) { return false; } return null; } set { if (value == true) { _connectionCloseSet = true; ConnectionCore.SetSpecialValue(); } else { _connectionCloseSet = value != null; ConnectionCore.RemoveSpecialValue(); } } } public DateTimeOffset? Date { get { return HeaderUtilities.GetDateTimeOffsetValue(HttpKnownHeaderNames.Date, _parent); } set { _parent.SetOrRemoveParsedValue(HttpKnownHeaderNames.Date, value); } } public HttpHeaderValueCollection<NameValueHeaderValue> Pragma { get { if (_pragma == null) { _pragma = new HttpHeaderValueCollection<NameValueHeaderValue>(HttpKnownHeaderNames.Pragma, _parent); } return _pragma; } } public HttpHeaderValueCollection<string> Trailer { get { if (_trailer == null) { _trailer = new HttpHeaderValueCollection<string>(HttpKnownHeaderNames.Trailer, _parent, HeaderUtilities.TokenValidator); } return _trailer; } } public HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncoding { get { return TransferEncodingCore; } } public bool? TransferEncodingChunked { get { if (TransferEncodingCore.IsSpecialValueSet) { return true; } if (_transferEncodingChunkedSet) { return false; } return null; } set { if (value == true) { _transferEncodingChunkedSet = true; TransferEncodingCore.SetSpecialValue(); } else { _transferEncodingChunkedSet = value != null; TransferEncodingCore.RemoveSpecialValue(); } } } public HttpHeaderValueCollection<ProductHeaderValue> Upgrade { get { if (_upgrade == null) { _upgrade = new HttpHeaderValueCollection<ProductHeaderValue>(HttpKnownHeaderNames.Upgrade, _parent); } return _upgrade; } } public HttpHeaderValueCollection<ViaHeaderValue> Via { get { if (_via == null) { _via = new HttpHeaderValueCollection<ViaHeaderValue>(HttpKnownHeaderNames.Via, _parent); } return _via; } } public HttpHeaderValueCollection<WarningHeaderValue> Warning { get { if (_warning == null) { _warning = new HttpHeaderValueCollection<WarningHeaderValue>(HttpKnownHeaderNames.Warning, _parent); } return _warning; } } private HttpHeaderValueCollection<string> ConnectionCore { get { if (_connection == null) { _connection = new HttpHeaderValueCollection<string>(HttpKnownHeaderNames.Connection, _parent, HeaderUtilities.ConnectionClose, HeaderUtilities.TokenValidator); } return _connection; } } private HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncodingCore { get { if (_transferEncoding == null) { _transferEncoding = new HttpHeaderValueCollection<TransferCodingHeaderValue>( HttpKnownHeaderNames.TransferEncoding, _parent, HeaderUtilities.TransferEncodingChunked); } return _transferEncoding; } } internal HttpGeneralHeaders(HttpHeaders parent) { Debug.Assert(parent != null); _parent = parent; } internal static void AddParsers(Dictionary<string, HttpHeaderParser> parserStore) { Debug.Assert(parserStore != null); parserStore.Add(HttpKnownHeaderNames.CacheControl, CacheControlHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.Connection, GenericHeaderParser.TokenListParser); parserStore.Add(HttpKnownHeaderNames.Date, DateHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.Pragma, GenericHeaderParser.MultipleValueNameValueParser); parserStore.Add(HttpKnownHeaderNames.Trailer, GenericHeaderParser.TokenListParser); parserStore.Add(HttpKnownHeaderNames.TransferEncoding, TransferCodingHeaderParser.MultipleValueParser); parserStore.Add(HttpKnownHeaderNames.Upgrade, GenericHeaderParser.MultipleValueProductParser); parserStore.Add(HttpKnownHeaderNames.Via, GenericHeaderParser.MultipleValueViaParser); parserStore.Add(HttpKnownHeaderNames.Warning, GenericHeaderParser.MultipleValueWarningParser); } internal static void AddKnownHeaders(HashSet<string> headerSet) { Debug.Assert(headerSet != null); headerSet.Add(HttpKnownHeaderNames.CacheControl); headerSet.Add(HttpKnownHeaderNames.Connection); headerSet.Add(HttpKnownHeaderNames.Date); headerSet.Add(HttpKnownHeaderNames.Pragma); headerSet.Add(HttpKnownHeaderNames.Trailer); headerSet.Add(HttpKnownHeaderNames.TransferEncoding); headerSet.Add(HttpKnownHeaderNames.Upgrade); headerSet.Add(HttpKnownHeaderNames.Via); headerSet.Add(HttpKnownHeaderNames.Warning); } internal void AddSpecialsFrom(HttpGeneralHeaders sourceHeaders) { // Copy special values, but do not overwrite bool? chunked = TransferEncodingChunked; if (!chunked.HasValue) { TransferEncodingChunked = sourceHeaders.TransferEncodingChunked; } bool? close = ConnectionClose; if (!close.HasValue) { ConnectionClose = sourceHeaders.ConnectionClose; } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Collections; using System.Windows.Forms; using log4net; using Axiom.Core; using Axiom.Input; using Axiom.Graphics; using Microsoft.DirectX; using Microsoft.DirectX.DirectInput; using DInput = Microsoft.DirectX.DirectInput; namespace Axiom.Platforms.Win32 { /// <summary> /// Win32 input implementation using Managed DirectInput (tm). /// </summary> public class Win32InputReader : InputReader { #region Fields // Create a logger for use in this class private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Win32InputReader)); /// <summary> /// Holds a snapshot of DirectInput keyboard state. /// </summary> protected KeyboardState keyboardState; /// <summary> /// Holds a snapshot of DirectInput mouse state. /// </summary> protected MouseState mouseState; /// <summary> /// DirectInput keyboard device. /// </summary> protected DInput.Device keyboardDevice; /// <summary> /// DirectInput mouse device. /// </summary> protected DInput.Device mouseDevice; protected int mouseRelX, mouseRelY, mouseRelZ; protected int mouseAbsX, mouseAbsY, mouseAbsZ; protected bool isInitialized; protected bool useMouse, useKeyboard, useGamepad; protected int mouseButtons; /// <summary> /// Active host control that reserves control over the input. /// </summary> protected System.Windows.Forms.Control control; /// <summary> /// Do we want exclusive use of the mouse? /// </summary> protected bool ownMouse; /// <summary> /// Do we want exclusive use of the keyboard? /// </summary> protected bool ownKeyboard; /// <summary> /// Do we want to collect mouse input when we are in the background? /// </summary> /// <remarks> /// For security reasons, if ownMouse is set, we will only collect /// mouse input when we are in the foreground. /// </remarks> protected bool backgroundMouse = true; /// <summary> /// Do we want to collect keyboard input when we are in the background? /// </summary> /// <remarks> /// For security reasons, if ownKeyboard is set, we will only collect /// keyboard input when we are in the foreground. /// </remarks> protected bool backgroundKeyboard = false; /// <summary> /// Reference to the render window that is the target of the input. /// </summary> protected RenderWindow window; /// <summary> /// Flag used to remember the state of the render window the last time input was captured. /// </summary> protected bool lastWindowActive; protected bool cursorEnabled = true; protected Point cursorDisabledPosition = new Point(0, 0); protected bool hardwareCursor = true; // Is the mouse over our control? protected bool mouseInControl; #endregion Fields #region Constants /// <summary> /// Size to use for DirectInput's input buffer. /// </summary> const int BufferSize = 1000; #endregion Constants #region InputReader Members #region Properties public override bool CursorEnabled { get { return cursorEnabled; } set { log.DebugFormat("Got Win32InputReader.CursorEnabled set to {0} (was {1})", value, cursorEnabled); if (cursorEnabled == value) return; if (!value) { // If we just turned off the cursor, stash the position of the mouse. // Each time we check the input, we will update the Cursor.Position Point pt = new Point(mouseAbsX, mouseAbsY); // if our point is no longer in our control, don't disable // the cursor. If we don't have focus, return if (!control.Bounds.Contains(pt) || !HasFocus()) return; cursorDisabledPosition = pt; // Also, make sure we get the mouse data control.Capture = true; log.DebugFormat("After capture; capture = {0}", control.Capture); } cursorEnabled = value; } } /// <summary> /// Retrieves the relative (compared to the last input poll) mouse movement /// on the X (horizontal) axis. /// </summary> public override int RelativeMouseX { get { return mouseRelX; } } /// <summary> /// Retrieves the relative (compared to the last input poll) mouse movement /// on the Y (vertical) axis. /// </summary> public override int RelativeMouseY { get { return mouseRelY; } } /// <summary> /// Retrieves the relative (compared to the last input poll) mouse movement /// on the Z (mouse wheel) axis. /// </summary> public override int RelativeMouseZ { get { return mouseRelZ; } } /// <summary> /// Retrieves the absolute mouse position on the X (horizontal) axis. /// </summary> public override int AbsoluteMouseX { get { return mouseAbsX; } } /// <summary> /// Retrieves the absolute mouse position on the Y (vertical) axis. /// </summary> public override int AbsoluteMouseY { get { return mouseAbsY; } } /// <summary> /// Retrieves the absolute mouse position on the Z (mouse wheel) axis. /// </summary> public override int AbsoluteMouseZ { get { return mouseAbsZ; } } /// <summary> /// Get/Set whether or not to use event based keyboard input notification. /// </summary> /// <value> /// When true, events will be fired when keyboard input occurs on a call to <see cref="Capture"/>. /// When false, the current keyboard state will be available via <see cref="IsKeyPressed"/> . /// </value> public override bool UseKeyboardEvents { get { return useKeyboardEvents; } set { if(useKeyboardEvents != value) { useKeyboardEvents = value; // dump the current keyboard device (if any) if(keyboardDevice != null) { keyboardDevice.Unacquire(); keyboardDevice.Dispose(); } // re-init the keyboard InitializeKeyboard(); } } } /// <summary> /// Get/Set whether or not to use event based mouse input notification. /// </summary> /// <value> /// When true, events will be fired when mouse input occurs on a call to <see cref="Capture"/>. /// When false, the current mouse state will be available via <see cref="IsMousePressed"/> . /// </value> public override bool UseMouseEvents { get { return useMouseEvents; } set { if(useMouseEvents != value) { useMouseEvents = value; // dump the current mouse device (if any) if(mouseDevice != null) { mouseDevice.Unacquire(); mouseDevice.Dispose(); } // re-init the mouse InitializeMouse(); } } } public override bool OwnMouse { get { return ownMouse; } set { ownMouse = value; // re-init the mouse InitializeMouse(); } } public override bool OwnKeyboard { get { return ownKeyboard; } set { ownKeyboard = value; // re-init the keyboard InitializeKeyboard(); } } public bool BackgroundMouse { get { return backgroundMouse; } set { backgroundMouse = value; // re-init the mouse InitializeMouse(); } } public bool BackgroundKeyboard { get { return backgroundKeyboard; } set { backgroundKeyboard = value; // re-init the keyboard InitializeKeyboard(); } } #endregion Properties #region Methods public override bool HasFocus() { if (control is Form) return control.Focused; return mouseInControl; } /// <summary> /// Captures the state of all active input controllers. /// </summary> public override void Capture() { try { if (!window.IsActive) { // if we were active, but are no longer active, trigger the // mouse lost event if (lastWindowActive) { OnMouseLost(new EventArgs()); lastWindowActive = false; CursorEnabled = true; } } else { // Grab the input, acquiring if we weren't active. if (VerifyInputAcquired()) { if (useKeyboard) { if (useKeyboardEvents) { ReadBufferedKeyboardData(); } else { // TODO: Grab keyboard modifiers CaptureKeyboard(); } } if (useMouse) { if (useMouseEvents) { ReadBufferedMouseData(); } else { CaptureMouse(); } } if (!control.ContainsFocus) control.Focus(); } if (hardwareCursor && control != null) { // Usually, we would not capture if we are not active, but // I do still want the app to track the cursor position. HandleMouseMoved(control.PointToClient(Cursor.Position)); } } } catch (InputLostException) { if (lastWindowActive) { OnMouseLost(new EventArgs()); lastWindowActive = false; CursorEnabled = true; } throw; } catch (NotAcquiredException) { lastWindowActive = false; CursorEnabled = true; throw; } } /// <summary> /// Intializes DirectInput for use on Win32 platforms. /// </summary> /// <param name="window"></param> /// <param name="useKeyboard"></param> /// <param name="useMouse"></param> /// <param name="useGamepad"></param> public override void Initialize(RenderWindow window, bool useKeyboard, bool useMouse, bool useGamepad, bool ownMouse, bool ownKeyboard) { this.useKeyboard = useKeyboard; this.useMouse = useMouse; this.useGamepad = useGamepad; this.ownMouse = ownMouse; this.ownKeyboard = ownKeyboard; this.window = window; this.useMouseEvents = true; this.useKeyboardEvents = true; log.InfoFormat("Initialized input with parameters {0}:{1}:{2}:{3}:{4}:{5}", window, useKeyboard, useMouse, useGamepad, ownMouse, ownKeyboard); // for Windows, this should be a S.W.F.Control control = window.Handle as System.Windows.Forms.Control; if (control == null) throw new AxiomException("Win32InputReader requires the RenderWindow to have an associated handle of either a PictureBox or a Form."); control.MouseEnter += new System.EventHandler(this.control_MouseEnter); control.MouseLeave += new System.EventHandler(this.control_MouseLeave); // initialize keyboard if needed if(useKeyboard) { InitializeKeyboard(); } // initialize the mouse if needed if(useMouse) { InitializeMouse(); } Point pt = control.PointToClient(Cursor.Position); if (control.Bounds.Contains(pt)) mouseInControl = true; // we are initialized isInitialized = true; mouseAbsX = pt.X; mouseAbsY = pt.Y; } public bool ContainsMouse { get { return mouseInControl; } } private void control_MouseEnter(object sender, EventArgs e) { mouseInControl = true; } private void control_MouseLeave(object sender, EventArgs e) { mouseInControl = false; } /// <summary> /// /// </summary> /// <param name="key"></param> /// <returns></returns> public override bool IsKeyPressed(KeyCodes key) { if(keyboardState != null) { // get the DInput.Key enum from the System.Windows.Forms.Keys enum passed in DInput.Key daKey = ConvertKeyEnum(key); if(keyboardState[daKey]) { return true; } } return false; } /// <summary> /// Returns true if the specified mouse button is currently down. /// </summary> /// <param name="button">Mouse button to query.</param> /// <returns>True if the mouse button is down, false otherwise.</returns> public override bool IsMousePressed(Axiom.Input.MouseButtons button) { if (button == Axiom.Input.MouseButtons.Left) return (modifiers & ModifierKeys.MouseButton0) != 0; else if (button == Axiom.Input.MouseButtons.Right) return (modifiers & ModifierKeys.MouseButton1) != 0; else if (button == Axiom.Input.MouseButtons.Middle) return (modifiers & ModifierKeys.MouseButton2) != 0; return false; } /// <summary> /// Called when the platform manager is shutting down. /// </summary> public override void Dispose() { if (keyboardDevice != null) { keyboardDevice.Unacquire(); keyboardDevice.Dispose(); keyboardDevice = null; } if (mouseDevice != null) { mouseDevice.Unacquire(); mouseDevice.Dispose(); mouseDevice = null; } control.MouseEnter -= new System.EventHandler(this.control_MouseEnter); control.MouseLeave -= new System.EventHandler(this.control_MouseLeave); } #endregion Methods #endregion InputReader implementation #region Helper Methods /// <summary> /// Initializes the keyboard using either immediate mode or event based input. /// </summary> private void InitializeKeyboard() { if(useKeyboardEvents) { InitializeBufferedKeyboard(); } else { InitializeImmediateKeyboard(); } } /// <summary> /// Initializes the mouse using either immediate mode or event based input. /// </summary> private void InitializeMouse() { if(useMouseEvents) { InitializeBufferedMouse(); } else { InitializeImmediateMouse(); } } /// <summary> /// Initializes DirectInput for immediate input. /// </summary> private void InitializeImmediateKeyboard() { // Create the device. keyboardDevice = new DInput.Device(SystemGuid.Keyboard); // grab the keyboard CooperativeLevelFlags excl = ownKeyboard ? CooperativeLevelFlags.Exclusive : CooperativeLevelFlags.NonExclusive; CooperativeLevelFlags background = (backgroundKeyboard && !ownKeyboard) ? CooperativeLevelFlags.Background : CooperativeLevelFlags.Foreground; keyboardDevice.SetCooperativeLevel(control.FindForm(), excl | background); // Set the data format to the keyboard pre-defined format. keyboardDevice.SetDataFormat(DeviceDataFormat.Keyboard); try { keyboardDevice.Acquire(); } catch { throw new Exception("Unable to acquire a keyboard using DirectInput."); } } /// <summary> /// Prepares DirectInput for non-immediate input capturing. /// </summary> private void InitializeBufferedKeyboard() { // create the device keyboardDevice = new DInput.Device(SystemGuid.Keyboard); // Set the data format to the keyboard pre-defined format. keyboardDevice.SetDataFormat(DeviceDataFormat.Keyboard); // grab the keyboard // For debugging, use the background flag so we don't lose input when we are in the debugger. // For release, use the foreground flag, so input to other apps doesn't show up here CooperativeLevelFlags excl = ownKeyboard ? CooperativeLevelFlags.Exclusive : CooperativeLevelFlags.NonExclusive; CooperativeLevelFlags background = (backgroundKeyboard && !ownKeyboard) ? CooperativeLevelFlags.Background : CooperativeLevelFlags.Foreground; keyboardDevice.SetCooperativeLevel(control.FindForm(), excl | background); // set the buffer size to use for input keyboardDevice.Properties.BufferSize = BufferSize; // note: dont acquire yet, wait till capture //try { // keyboardDevice.Acquire(); //} //catch { // throw new Exception("Unable to acquire a keyboard using DirectInput."); //} } /// <summary> /// Prepares DirectInput for immediate mouse input. /// </summary> private void InitializeImmediateMouse() { // create the device mouseDevice = new DInput.Device(SystemGuid.Mouse); mouseDevice.Properties.AxisModeAbsolute = true; // set the device format so DInput knows this device is a mouse mouseDevice.SetDataFormat(DeviceDataFormat.Mouse); CooperativeLevelFlags excl = ownMouse ? CooperativeLevelFlags.Exclusive : CooperativeLevelFlags.NonExclusive; CooperativeLevelFlags background = (backgroundMouse && !ownMouse) ? CooperativeLevelFlags.Background : CooperativeLevelFlags.Foreground; // set cooperation level mouseDevice.SetCooperativeLevel(control.FindForm(), excl | background); // note: dont acquire yet, wait till capture } /// <summary> /// /// </summary> private void InitializeBufferedMouse() { // create the device mouseDevice = new DInput.Device(SystemGuid.Mouse); mouseDevice.Properties.AxisModeAbsolute = true; // set the device format so DInput knows this device is a mouse mouseDevice.SetDataFormat(DeviceDataFormat.Mouse); // set the buffer size to use for input mouseDevice.Properties.BufferSize = BufferSize; CooperativeLevelFlags excl = ownMouse ? CooperativeLevelFlags.Exclusive : CooperativeLevelFlags.NonExclusive; CooperativeLevelFlags background = (backgroundMouse && !ownMouse) ? CooperativeLevelFlags.Background : CooperativeLevelFlags.Foreground; // set cooperation level mouseDevice.SetCooperativeLevel(control.FindForm(), excl | background); // note: dont acquire yet, wait till capture? //try { // mouseDevice.Acquire(); //} catch { // throw new Exception("Unable to acquire a mouse using DirectInput."); //} } /// <summary> /// Reads buffered input data when in buffered mode. /// </summary> private void ReadBufferedKeyboardData() { // grab the collection of buffered data BufferedDataCollection bufferedData = keyboardDevice.GetBufferedData(); // please tell me why this would ever come back null, rather than an empty collection... if (bufferedData == null) return; if (bufferedData.Count >= BufferSize - 1) log.Warn("Exceeded keyboard buffer. Input data lost"); for (int i = 0; i < bufferedData.Count; i++) { BufferedData data = bufferedData[i]; KeyCodes key = ConvertKeyEnum((DInput.Key)data.Offset); // is the key being pressed down, or released? bool down = (data.ButtonPressedData == 1); KeyChanged(key, down); } } /// <summary> /// Reads buffered input data when in buffered mode. /// </summary> private void ReadMouseEvent(List<BufferedData> bufferedDataList, MouseData mouseData) { foreach (BufferedData data in bufferedDataList) { mouseData.timeStamp = data.TimeStamp; switch ((DInput.MouseOffset)data.Offset) { case MouseOffset.X: mouseData.relativeX = data.Data; break; case MouseOffset.Y: mouseData.relativeY = data.Data; break; case MouseOffset.Z: mouseData.relativeZ = data.Data; break; case MouseOffset.Button0: mouseData.button = Axiom.Input.MouseButtons.Left; mouseData.down = (data.ButtonPressedData == 1); break; case MouseOffset.Button1: mouseData.button = Axiom.Input.MouseButtons.Right; mouseData.down = (data.ButtonPressedData == 1); break; case MouseOffset.Button2: mouseData.button = Axiom.Input.MouseButtons.Middle; mouseData.down = (data.ButtonPressedData == 1); break; } } return; } /// <summary> /// Reads buffered input data when in buffered mode. /// </summary> private void ReadBufferedMouseData() { // grab the collection of buffered data BufferedDataCollection bufferedData = mouseDevice.GetBufferedData(); if (bufferedData == null) return; if (bufferedData.Count >= BufferSize - 1) log.Warn("Exceeded mouse buffer. Input data lost"); bufferedData.SortBySequence(); Dictionary<int, List<BufferedData>> bufferedDataDict = new Dictionary<int, List<BufferedData>>(); List<int> sequenceNumbers = new List<int>(); int currentSequence = -1; List<BufferedData> currentData = null; foreach (BufferedData data in bufferedData) { if (currentSequence != data.Sequence) { currentData = new List<BufferedData>(); currentSequence = data.Sequence; bufferedDataDict[currentSequence] = currentData; sequenceNumbers.Add(currentSequence); } currentData.Add(data); } foreach (int eventSequence in sequenceNumbers) { MouseData mouseData = new MouseData(); // Grab all the events with that sequence number, and use them to // populate the mouseData and down structures. ReadMouseEvent(bufferedDataDict[eventSequence], mouseData); //if (control != null && !control.Capture) // return; Point mousePoint = new Point(0, 0); if (!hardwareCursor) { // If we are using a software cursor, use the relative // data from the event and our previous position to // compute the current position. mousePoint.X = mouseAbsX + (int)mouseData.relativeX; mousePoint.Y = mouseAbsY + (int)mouseData.relativeY; HandleMouseMoved(mousePoint); } mouseAbsZ += (int)mouseData.relativeZ; mouseData.x = mouseAbsX; mouseData.y = mouseAbsY; mouseData.z = mouseAbsZ; MouseChanged(mouseData); } } /// <summary> /// If the cursor is enabled, set our mouseAbs variables based /// on the data in mousePoint. If the cursor is disabled and /// we are using the hardware cursor, move the cursor back to the /// point where the cursor was disabled. /// </summary> /// <param name="mousePoint"></param> public void HandleMouseMoved(Point mousePoint) { // If we are using a hardware cursor, ignore the relative // data from the event, and regenerate the relative data // based on the current position and our previous position. if (this.CursorEnabled) { if (mouseAbsX != mousePoint.X || mouseAbsY != mousePoint.Y) { // Inject the mouse event that will go beyond our buffered data // to adjust the cursor to its current position. MouseData mouseData = new MouseData(); mouseData.x = mousePoint.X; mouseData.y = mousePoint.Y; mouseData.relativeX = mousePoint.X - mouseAbsX; mouseData.relativeY = mousePoint.Y - mouseAbsY; Axiom.Input.MouseEventArgs e = new Axiom.Input.MouseEventArgs(mouseData, modifiers); OnMouseMoved(e); } mouseAbsX = mousePoint.X; mouseAbsY = mousePoint.Y; // Now that the cursor size has been scaled to 32x32 in full // screen mode, I don't ever expect to not be able to rely on // the operating system to update the cursor. Nonetheless, // it's possible that there are still cases out there. Until // we encounter one of those cases though, I'm leaving this // ifdeffed out because I hate to waste the work updating the // cursor if I don't need to. #if UPDATE_CURSOR_MANUALLY // If we can't use the operating system to update our cursor, we will // need to do it ourselves. if (hardwareCursor) { Point screenPoint = control.PointToScreen(mousePoint); Root.Instance.RenderSystem.SetCursorPosition(screenPoint.X, screenPoint.Y); } #endif } else { if (HasFocus()) { if (hardwareCursor && control != null && control.Capture) { log.DebugFormat("Restoring cursor to: {0}", cursorDisabledPosition); Cursor.Position = control.PointToScreen(cursorDisabledPosition); } else if (hardwareCursor && control != null) { // Our app has focus, but doesn't have mouse capture (and should).. grab it. control.Capture = true; log.DebugFormat("Restoring cursor (and recapturing) to: {0}", cursorDisabledPosition); Cursor.Position = control.PointToScreen(cursorDisabledPosition); } else { log.DebugFormat("Cannot restore cursor; control {0}; {1}", control, (control == null) ? false : control.Capture); } } } } /// <summary> /// Captures an immediate keyboard state snapshot (for non-buffered data). /// </summary> private void CaptureKeyboard() { if (useKeyboardEvents) // throw away the collection of buffered data keyboardDevice.GetBufferedData(); keyboardState = keyboardDevice.GetCurrentKeyboardState(); // Set Alt/Ctrl/Shift modifiers &= ~ModifierKeys.Alt; modifiers &= ~ModifierKeys.Control; modifiers &= ~ModifierKeys.Shift; if (keyboardState[Key.LeftAlt] || keyboardState[Key.RightAlt]) modifiers |= ModifierKeys.Alt; if (keyboardState[Key.LeftControl] || keyboardState[Key.RightControl]) modifiers |= ModifierKeys.Control; if (keyboardState[Key.LeftShift] || keyboardState[Key.RightShift]) modifiers |= ModifierKeys.Shift; } /// <summary> /// Captures the immediate mouse state (for non-buffered data). /// </summary> private void CaptureMouse() { CaptureImmediateMouse(); #if NOT // This code should be in place if we really want to track mouse // buttons in the modifiers structure, but our base class doesn't // ever put these in the modifiers (despite their presence in the // enumeration). // Set MouseButton flags modifiers &= ~ModifierKeys.MouseButton0; modifiers &= ~ModifierKeys.MouseButton1; modifiers &= ~ModifierKeys.MouseButton2; if (IsMousePressed(MouseButtons.Left)) modifiers |= ModifierKeys.MouseButton0; if (IsMousePressed(MouseButtons.Right)) modifiers |= ModifierKeys.MouseButton1; if (IsMousePressed(MouseButtons.Middle)) modifiers |= ModifierKeys.MouseButton2; #endif } /// <summary> /// Takes a snapshot of the mouse state for immediate input checking. /// </summary> private void CaptureImmediateMouse() { // throw away the collection of buffered data if (useMouseEvents) mouseDevice.GetBufferedData(); // capture the current mouse state mouseState = mouseDevice.CurrentMouseState; // store the updated absolute values mouseAbsX += mouseState.X; mouseAbsY += mouseState.Y; mouseAbsZ += mouseState.Z; // calc relative deviance from center mouseRelX = mouseState.X; mouseRelY = mouseState.Y; mouseRelZ = mouseState.Z; byte[] buttons = mouseState.GetMouseButtons(); // clear the flags mouseButtons = 0; for(int i = 0; i < buttons.Length; i++) { if((buttons[i] & 0x80) != 0) { mouseButtons |= (1 << i); } } } /// <summary> /// Verifies the state of the host window and reacquires input if the window was /// previously minimized and has been brought back into focus. /// </summary> /// <returns>True if the input devices are acquired and input capturing can proceed, false otherwise.</returns> protected bool VerifyInputAcquired() { // if the window is coming back from being deactivated, lets grab input again if (window.IsActive && !lastWindowActive) { try { // acquire and capture keyboard input if (useKeyboard) { keyboardDevice.Acquire(); CaptureKeyboard(); } // acquire and capture mouse input if (useMouse) { mouseDevice.Acquire(); CaptureMouse(); } lastWindowActive = true; } catch (Microsoft.DirectX.DirectInput.OtherApplicationHasPriorityException) { // we probably weren't able to capture the input - // this is ok since we will try again later, but // don't mark us as the last window active so that // we will try to acquire again later ; } } return lastWindowActive; } #region Keycode Conversions /// <summary> /// Used to convert an Axiom.Input.KeyCodes enum val to a DirectInput.Key enum val. /// </summary> /// <param name="key">Axiom keyboard code to query.</param> /// <returns>The equivalent enum value in the DInput.Key enum.</returns> private DInput.Key ConvertKeyEnum(KeyCodes key) { // TODO: Quotes DInput.Key dinputKey = 0; switch(key) { case KeyCodes.A: dinputKey = DInput.Key.A; break; case KeyCodes.B: dinputKey = DInput.Key.B; break; case KeyCodes.C: dinputKey = DInput.Key.C; break; case KeyCodes.D: dinputKey = DInput.Key.D; break; case KeyCodes.E: dinputKey = DInput.Key.E; break; case KeyCodes.F: dinputKey = DInput.Key.F; break; case KeyCodes.G: dinputKey = DInput.Key.G; break; case KeyCodes.H: dinputKey = DInput.Key.H; break; case KeyCodes.I: dinputKey = DInput.Key.I; break; case KeyCodes.J: dinputKey = DInput.Key.J; break; case KeyCodes.K: dinputKey = DInput.Key.K; break; case KeyCodes.L: dinputKey = DInput.Key.L; break; case KeyCodes.M: dinputKey = DInput.Key.M; break; case KeyCodes.N: dinputKey = DInput.Key.N; break; case KeyCodes.O: dinputKey = DInput.Key.O; break; case KeyCodes.P: dinputKey = DInput.Key.P; break; case KeyCodes.Q: dinputKey = DInput.Key.Q; break; case KeyCodes.R: dinputKey = DInput.Key.R; break; case KeyCodes.S: dinputKey = DInput.Key.S; break; case KeyCodes.T: dinputKey = DInput.Key.T; break; case KeyCodes.U: dinputKey = DInput.Key.U; break; case KeyCodes.V: dinputKey = DInput.Key.V; break; case KeyCodes.W: dinputKey = DInput.Key.W; break; case KeyCodes.X: dinputKey = DInput.Key.X; break; case KeyCodes.Y: dinputKey = DInput.Key.Y; break; case KeyCodes.Z: dinputKey = DInput.Key.Z; break; case KeyCodes.Left : dinputKey = DInput.Key.LeftArrow; break; case KeyCodes.Right: dinputKey = DInput.Key.RightArrow; break; case KeyCodes.Up: dinputKey = DInput.Key.UpArrow; break; case KeyCodes.Down: dinputKey = DInput.Key.DownArrow; break; case KeyCodes.Escape: dinputKey = DInput.Key.Escape; break; case KeyCodes.F1: dinputKey = DInput.Key.F1; break; case KeyCodes.F2: dinputKey = DInput.Key.F2; break; case KeyCodes.F3: dinputKey = DInput.Key.F3; break; case KeyCodes.F4: dinputKey = DInput.Key.F4; break; case KeyCodes.F5: dinputKey = DInput.Key.F5; break; case KeyCodes.F6: dinputKey = DInput.Key.F6; break; case KeyCodes.F7: dinputKey = DInput.Key.F7; break; case KeyCodes.F8: dinputKey = DInput.Key.F8; break; case KeyCodes.F9: dinputKey = DInput.Key.F9; break; case KeyCodes.F10: dinputKey = DInput.Key.F10; break; case KeyCodes.D0: dinputKey = DInput.Key.D0; break; case KeyCodes.D1: dinputKey = DInput.Key.D1; break; case KeyCodes.D2: dinputKey = DInput.Key.D2; break; case KeyCodes.D3: dinputKey = DInput.Key.D3; break; case KeyCodes.D4: dinputKey = DInput.Key.D4; break; case KeyCodes.D5: dinputKey = DInput.Key.D5; break; case KeyCodes.D6: dinputKey = DInput.Key.D6; break; case KeyCodes.D7: dinputKey = DInput.Key.D7; break; case KeyCodes.D8: dinputKey = DInput.Key.D8; break; case KeyCodes.D9: dinputKey = DInput.Key.D9; break; case KeyCodes.F11: dinputKey = DInput.Key.F11; break; case KeyCodes.F12: dinputKey = DInput.Key.F12; break; case KeyCodes.Enter: dinputKey = DInput.Key.Return; break; case KeyCodes.Tab: dinputKey = DInput.Key.Tab; break; case KeyCodes.LeftShift: dinputKey = DInput.Key.LeftShift; break; case KeyCodes.RightShift: dinputKey = DInput.Key.RightShift; break; case KeyCodes.LeftControl: dinputKey = DInput.Key.LeftControl; break; case KeyCodes.RightControl: dinputKey = DInput.Key.RightControl; break; case KeyCodes.Period: dinputKey = DInput.Key.Period; break; case KeyCodes.Comma: dinputKey = DInput.Key.Comma; break; case KeyCodes.Home: dinputKey = DInput.Key.Home; break; case KeyCodes.PageUp: dinputKey = DInput.Key.PageUp; break; case KeyCodes.PageDown: dinputKey = DInput.Key.PageDown; break; case KeyCodes.End: dinputKey = DInput.Key.End; break; case KeyCodes.Semicolon: dinputKey = DInput.Key.SemiColon; break; case KeyCodes.Subtract: dinputKey = DInput.Key.Subtract; break; case KeyCodes.Add: dinputKey = DInput.Key.Add; break; case KeyCodes.Backspace: dinputKey = DInput.Key.BackSpace; break; case KeyCodes.Delete: dinputKey = DInput.Key.Delete; break; case KeyCodes.Insert: dinputKey = DInput.Key.Insert; break; case KeyCodes.LeftAlt: dinputKey = DInput.Key.LeftAlt; break; case KeyCodes.RightAlt: dinputKey = DInput.Key.RightAlt; break; case KeyCodes.Space: dinputKey = DInput.Key.Space; break; case KeyCodes.Tilde: dinputKey = DInput.Key.Grave; break; case KeyCodes.OpenBracket: dinputKey = DInput.Key.LeftBracket; break; case KeyCodes.CloseBracket: dinputKey = DInput.Key.RightBracket; break; case KeyCodes.Plus: dinputKey = DInput.Key.Equals; break; case KeyCodes.QuestionMark: dinputKey = DInput.Key.Slash; break; case KeyCodes.Quotes: dinputKey = DInput.Key.Apostrophe; break; case KeyCodes.Backslash: dinputKey = DInput.Key.BackSlash; break; case KeyCodes.NumPad0: dinputKey = DInput.Key.NumPad0; break; case KeyCodes.NumPad1: dinputKey = DInput.Key.NumPad1; break; case KeyCodes.NumPad2: dinputKey = DInput.Key.NumPad2; break; case KeyCodes.NumPad3: dinputKey = DInput.Key.NumPad3; break; case KeyCodes.NumPad4: dinputKey = DInput.Key.NumPad4; break; case KeyCodes.NumPad5: dinputKey = DInput.Key.NumPad5; break; case KeyCodes.NumPad6: dinputKey = DInput.Key.NumPad6; break; case KeyCodes.NumPad7: dinputKey = DInput.Key.NumPad7; break; case KeyCodes.NumPad8: dinputKey = DInput.Key.NumPad8; break; case KeyCodes.NumPad9: dinputKey = DInput.Key.NumPad9; break; case KeyCodes.NumLock: dinputKey = DInput.Key.Numlock; break; case KeyCodes.PrintScreen: dinputKey = DInput.Key.SysRq; break; } return dinputKey; } /// <summary> /// Used to convert a DirectInput.Key enum val to a Axiom.Input.KeyCodes enum val. /// </summary> /// <param name="key">DirectInput.Key code to query.</param> /// <returns>The equivalent enum value in the Axiom.KeyCodes enum.</returns> private Axiom.Input.KeyCodes ConvertKeyEnum(DInput.Key key) { // TODO: Quotes Axiom.Input.KeyCodes axiomKey = 0; switch(key) { case DInput.Key.SysRq: axiomKey = Axiom.Input.KeyCodes.PrintScreen; break; case DInput.Key.A: axiomKey = Axiom.Input.KeyCodes.A; break; case DInput.Key.B: axiomKey = Axiom.Input.KeyCodes.B; break; case DInput.Key.C: axiomKey = Axiom.Input.KeyCodes.C; break; case DInput.Key.D: axiomKey = Axiom.Input.KeyCodes.D; break; case DInput.Key.E: axiomKey = Axiom.Input.KeyCodes.E; break; case DInput.Key.F: axiomKey = Axiom.Input.KeyCodes.F; break; case DInput.Key.G: axiomKey = Axiom.Input.KeyCodes.G; break; case DInput.Key.H: axiomKey = Axiom.Input.KeyCodes.H; break; case DInput.Key.I: axiomKey = Axiom.Input.KeyCodes.I; break; case DInput.Key.J: axiomKey = Axiom.Input.KeyCodes.J; break; case DInput.Key.K: axiomKey = Axiom.Input.KeyCodes.K; break; case DInput.Key.L: axiomKey = Axiom.Input.KeyCodes.L; break; case DInput.Key.M: axiomKey = Axiom.Input.KeyCodes.M; break; case DInput.Key.N: axiomKey = Axiom.Input.KeyCodes.N; break; case DInput.Key.O: axiomKey = Axiom.Input.KeyCodes.O; break; case DInput.Key.P: axiomKey = Axiom.Input.KeyCodes.P; break; case DInput.Key.Q: axiomKey = Axiom.Input.KeyCodes.Q; break; case DInput.Key.R: axiomKey = Axiom.Input.KeyCodes.R; break; case DInput.Key.S: axiomKey = Axiom.Input.KeyCodes.S; break; case DInput.Key.T: axiomKey = Axiom.Input.KeyCodes.T; break; case DInput.Key.U: axiomKey = Axiom.Input.KeyCodes.U; break; case DInput.Key.V: axiomKey = Axiom.Input.KeyCodes.V; break; case DInput.Key.W: axiomKey = Axiom.Input.KeyCodes.W; break; case DInput.Key.X: axiomKey = Axiom.Input.KeyCodes.X; break; case DInput.Key.Y: axiomKey = Axiom.Input.KeyCodes.Y; break; case DInput.Key.Z: axiomKey = Axiom.Input.KeyCodes.Z; break; case DInput.Key.LeftArrow : axiomKey = Axiom.Input.KeyCodes.Left; break; case DInput.Key.RightArrow: axiomKey = Axiom.Input.KeyCodes.Right; break; case DInput.Key.UpArrow: axiomKey = Axiom.Input.KeyCodes.Up; break; case DInput.Key.DownArrow: axiomKey = Axiom.Input.KeyCodes.Down; break; case DInput.Key.Escape: axiomKey = Axiom.Input.KeyCodes.Escape; break; case DInput.Key.F1: axiomKey = Axiom.Input.KeyCodes.F1; break; case DInput.Key.F2: axiomKey = Axiom.Input.KeyCodes.F2; break; case DInput.Key.F3: axiomKey = Axiom.Input.KeyCodes.F3; break; case DInput.Key.F4: axiomKey = Axiom.Input.KeyCodes.F4; break; case DInput.Key.F5: axiomKey = Axiom.Input.KeyCodes.F5; break; case DInput.Key.F6: axiomKey = Axiom.Input.KeyCodes.F6; break; case DInput.Key.F7: axiomKey = Axiom.Input.KeyCodes.F7; break; case DInput.Key.F8: axiomKey = Axiom.Input.KeyCodes.F8; break; case DInput.Key.F9: axiomKey = Axiom.Input.KeyCodes.F9; break; case DInput.Key.F10: axiomKey = Axiom.Input.KeyCodes.F10; break; case DInput.Key.D0: axiomKey = Axiom.Input.KeyCodes.D0; break; case DInput.Key.D1: axiomKey = Axiom.Input.KeyCodes.D1; break; case DInput.Key.D2: axiomKey = Axiom.Input.KeyCodes.D2; break; case DInput.Key.D3: axiomKey = Axiom.Input.KeyCodes.D3; break; case DInput.Key.D4: axiomKey = Axiom.Input.KeyCodes.D4; break; case DInput.Key.D5: axiomKey = Axiom.Input.KeyCodes.D5; break; case DInput.Key.D6: axiomKey = Axiom.Input.KeyCodes.D6; break; case DInput.Key.D7: axiomKey = Axiom.Input.KeyCodes.D7; break; case DInput.Key.D8: axiomKey = Axiom.Input.KeyCodes.D8; break; case DInput.Key.D9: axiomKey = Axiom.Input.KeyCodes.D9; break; case DInput.Key.F11: axiomKey = Axiom.Input.KeyCodes.F11; break; case DInput.Key.F12: axiomKey = Axiom.Input.KeyCodes.F12; break; case DInput.Key.Return: axiomKey = Axiom.Input.KeyCodes.Enter; break; case DInput.Key.Tab: axiomKey = Axiom.Input.KeyCodes.Tab; break; case DInput.Key.LeftShift: axiomKey = Axiom.Input.KeyCodes.LeftShift; break; case DInput.Key.RightShift: axiomKey = Axiom.Input.KeyCodes.RightShift; break; case DInput.Key.LeftControl: axiomKey = Axiom.Input.KeyCodes.LeftControl; break; case DInput.Key.RightControl: axiomKey = Axiom.Input.KeyCodes.RightControl; break; case DInput.Key.Period: axiomKey = Axiom.Input.KeyCodes.Period; break; case DInput.Key.Comma: axiomKey = Axiom.Input.KeyCodes.Comma; break; case DInput.Key.Home: axiomKey = Axiom.Input.KeyCodes.Home; break; case DInput.Key.PageUp: axiomKey = Axiom.Input.KeyCodes.PageUp; break; case DInput.Key.PageDown: axiomKey = Axiom.Input.KeyCodes.PageDown; break; case DInput.Key.End: axiomKey = Axiom.Input.KeyCodes.End; break; case DInput.Key.SemiColon: axiomKey = Axiom.Input.KeyCodes.Semicolon; break; case DInput.Key.Subtract: axiomKey = Axiom.Input.KeyCodes.Subtract; break; case DInput.Key.Add: axiomKey = Axiom.Input.KeyCodes.Add; break; case DInput.Key.BackSpace: axiomKey = Axiom.Input.KeyCodes.Backspace; break; case DInput.Key.Delete: axiomKey = Axiom.Input.KeyCodes.Delete; break; case DInput.Key.Insert: axiomKey = Axiom.Input.KeyCodes.Insert; break; case DInput.Key.LeftAlt: axiomKey = Axiom.Input.KeyCodes.LeftAlt; break; case DInput.Key.RightAlt: axiomKey = Axiom.Input.KeyCodes.RightAlt; break; case DInput.Key.Space: axiomKey = Axiom.Input.KeyCodes.Space; break; case DInput.Key.Grave: axiomKey = Axiom.Input.KeyCodes.Tilde; break; case DInput.Key.LeftBracket: axiomKey = Axiom.Input.KeyCodes.OpenBracket; break; case DInput.Key.RightBracket: axiomKey = Axiom.Input.KeyCodes.CloseBracket; break; case DInput.Key.Equals: axiomKey = KeyCodes.Plus; break; case DInput.Key.Minus: axiomKey = KeyCodes.Subtract; break; case DInput.Key.Slash: axiomKey = KeyCodes.QuestionMark; break; case DInput.Key.Apostrophe: axiomKey = KeyCodes.Quotes; break; case DInput.Key.BackSlash: axiomKey = KeyCodes.Backslash; break; case DInput.Key.NumPad0: axiomKey = Axiom.Input.KeyCodes.NumPad0; break; case DInput.Key.NumPad1: axiomKey = Axiom.Input.KeyCodes.NumPad1; break; case DInput.Key.NumPad2: axiomKey = Axiom.Input.KeyCodes.NumPad2; break; case DInput.Key.NumPad3: axiomKey = Axiom.Input.KeyCodes.NumPad3; break; case DInput.Key.NumPad4: axiomKey = Axiom.Input.KeyCodes.NumPad4; break; case DInput.Key.NumPad5: axiomKey = Axiom.Input.KeyCodes.NumPad5; break; case DInput.Key.NumPad6: axiomKey = Axiom.Input.KeyCodes.NumPad6; break; case DInput.Key.NumPad7: axiomKey = Axiom.Input.KeyCodes.NumPad7; break; case DInput.Key.NumPad8: axiomKey = Axiom.Input.KeyCodes.NumPad8; break; case DInput.Key.NumPad9: axiomKey = Axiom.Input.KeyCodes.NumPad9; break; case DInput.Key.Numlock: axiomKey = Axiom.Input.KeyCodes.NumLock; break; } return axiomKey; } #endregion Keycode Conversions #endregion Helper Methods } }
//----------------------------------------------------------------------------- //Cortex //Copyright (c) 2010-2015, Joshua Scoggins //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 Cortex 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 Joshua Scoggins BE LIABLE FOR ANY //DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES //(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND //ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT //(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS //SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Runtime; using System.Text; using System.Text.RegularExpressions; using System.Reflection; using System.IO; using System.Linq; namespace Cortex.Grammar { public class AdvanceableProduction : ICloneable, IEnumerable<string>, IAdvanceableProduction { #if GATHERING_STATS public static long DeleteCount = 0L; public static long InstanceCount = 0L; #endif private int current, min; private Production prod; public int Max { get { return prod.Count; } } public int Min { get { return min; } } public int Position { get { return current; } } public SemanticRule Rule { get { return prod.Rule; } } public string Current { get { if(current < Max && current >= min) return prod[current]; else return null; } } public int Count { get { return prod.Count; } } public Production Target { get { return prod; } } public bool HasNext { get { return current < Max; } } public bool HasPrevious { get { return current >= min; } } public AdvanceableProduction(Production p, int start) { #if GATHERING_STATS InstanceCount++; #endif current = start; min = start; prod = p; } public AdvanceableProduction(Production p) : this(p, 0) { } public AdvanceableProduction(AdvanceableProduction adv) : this(adv.Target, adv.Min) { current = adv.Position; } #if GATHERING_STATS ~AdvanceableProduction() { DeleteCount++; } #endif public object Clone() { return new AdvanceableProduction(this); } public override bool Equals(object other) { AdvanceableProduction p = (AdvanceableProduction)other; return p.current == current && p.min == min && p.Max == Max && p.prod.Equals(this.prod); } public override int GetHashCode() { return min.GetHashCode() + current.GetHashCode() + Max.GetHashCode() + prod.GetHashCode(); } public string this[int index] { get { if(index < min || index > Max) throw new ArgumentException("Given index is out of range"); else return prod[index]; } } IAdvanceableProduction IAdvanceableProduction.FunctionalNext() { return FunctionalNext(); } IAdvanceableProduction IAdvanceableProduction.FunctionalPrevious() { return FunctionalPrevious(); } public AdvanceableProduction FunctionalNext() { var adp = (AdvanceableProduction)Clone(); adp.Next(); return adp; } public AdvanceableProduction FunctionalPrevious() { var adp = (AdvanceableProduction)Clone(); adp.Previous(); return adp; } public bool Next() { bool result = HasNext; if(result) current++; return result && current < Max; } public bool Previous() { bool result = HasPrevious; if(result) current--; return result && current >= min; } public void Reset() { current = min; } public IEnumerator<string> GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public class Enumerator : IEnumerator<string> { #if GATHERING_STATS public static long InstanceCount = 0L, DeleteCount = 0L; #endif private int min; private int start; private int max; private Production target; public Enumerator(AdvanceableProduction prod) { #if GATHERING_STATS InstanceCount++; #endif min = prod.Min; start = prod.Min - 1; max = prod.Max; target = prod.prod; } #if GATHERING_STATS ~Enumerator() { DeleteCount++; } #endif object IEnumerator.Current { get { return Current; } } public string Current { get { return target[start]; } } public bool MoveNext() { start++; return start < max; } public void Reset() { start = min - 1; } public void Dispose() { min = -1; start = -1; max = -1; target = null; } } public static implicit operator Production(AdvanceableProduction prod) { return prod.prod; } public override string ToString() { StringBuilder sb = new StringBuilder(); for(int i = 0; i < Min; i++) sb.Append(prod[i]); sb.Append("!"); for(int i = Min; i < current; i++) sb.AppendFormat("{0} ", prod[i]); sb.Append("@"); for(int i = current; i < Max; i++) sb.AppendFormat("{0} ", prod[i]); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using PopcornNetFrameworkExample.Areas.HelpPage.ModelDescriptions; using PopcornNetFrameworkExample.Areas.HelpPage.Models; namespace PopcornNetFrameworkExample.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation accounts. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for more /// information) /// </summary> internal partial class AutomationAccountOperations : IServiceOperations<AutomationManagementClient>, IAutomationAccountOperations { /// <summary> /// Initializes a new instance of the AutomationAccountOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal AutomationAccountOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create or update automation /// account. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the create or update account operation. /// </returns> public async Task<AutomationAccountCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, AutomationAccountCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; if (parameters.Name != null) { url = url + Uri.EscapeDataString(parameters.Name); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject automationAccountCreateOrUpdateParametersValue = new JObject(); requestDoc = automationAccountCreateOrUpdateParametersValue; if (parameters.Properties != null) { JObject propertiesValue = new JObject(); automationAccountCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.Sku != null) { JObject skuValue = new JObject(); propertiesValue["sku"] = skuValue; if (parameters.Properties.Sku.Name != null) { skuValue["name"] = parameters.Properties.Sku.Name; } if (parameters.Properties.Sku.Family != null) { skuValue["family"] = parameters.Properties.Sku.Family; } skuValue["capacity"] = parameters.Properties.Sku.Capacity; } } if (parameters.Name != null) { automationAccountCreateOrUpdateParametersValue["name"] = parameters.Name; } if (parameters.Location != null) { automationAccountCreateOrUpdateParametersValue["location"] = parameters.Location; } if (parameters.Tags != null) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } automationAccountCreateOrUpdateParametersValue["tags"] = tagsDictionary; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AutomationAccountCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AutomationAccountCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { AutomationAccount automationAccountInstance = new AutomationAccount(); result.AutomationAccount = automationAccountInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { AutomationAccountProperties propertiesInstance = new AutomationAccountProperties(); automationAccountInstance.Properties = propertiesInstance; JToken skuValue2 = propertiesValue2["sku"]; if (skuValue2 != null && skuValue2.Type != JTokenType.Null) { Sku skuInstance = new Sku(); propertiesInstance.Sku = skuInstance; JToken nameValue = skuValue2["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); skuInstance.Name = nameInstance; } JToken familyValue = skuValue2["family"]; if (familyValue != null && familyValue.Type != JTokenType.Null) { string familyInstance = ((string)familyValue); skuInstance.Family = familyInstance; } JToken capacityValue = skuValue2["capacity"]; if (capacityValue != null && capacityValue.Type != JTokenType.Null) { int capacityInstance = ((int)capacityValue); skuInstance.Capacity = capacityInstance; } } JToken lastModifiedByValue = propertiesValue2["lastModifiedBy"]; if (lastModifiedByValue != null && lastModifiedByValue.Type != JTokenType.Null) { string lastModifiedByInstance = ((string)lastModifiedByValue); propertiesInstance.LastModifiedBy = lastModifiedByInstance; } JToken stateValue = propertiesValue2["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken creationTimeValue = propertiesValue2["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue2["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); automationAccountInstance.Id = idInstance; } JToken nameValue2 = responseDoc["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); automationAccountInstance.Name = nameInstance2; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); automationAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); automationAccountInstance.Tags.Add(tagsKey2, tagsValue2); } } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); automationAccountInstance.Type = typeInstance; } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); automationAccountInstance.Etag = etagInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccountName'> /// Required. Automation account name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccountName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccountName == null) { throw new ArgumentNullException("automationAccountName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccountName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the account by account name. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get account operation. /// </returns> public async Task<AutomationAccountGetResponse> GetAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AutomationAccountGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AutomationAccountGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { AutomationAccount automationAccountInstance = new AutomationAccount(); result.AutomationAccount = automationAccountInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { AutomationAccountProperties propertiesInstance = new AutomationAccountProperties(); automationAccountInstance.Properties = propertiesInstance; JToken skuValue = propertiesValue["sku"]; if (skuValue != null && skuValue.Type != JTokenType.Null) { Sku skuInstance = new Sku(); propertiesInstance.Sku = skuInstance; JToken nameValue = skuValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); skuInstance.Name = nameInstance; } JToken familyValue = skuValue["family"]; if (familyValue != null && familyValue.Type != JTokenType.Null) { string familyInstance = ((string)familyValue); skuInstance.Family = familyInstance; } JToken capacityValue = skuValue["capacity"]; if (capacityValue != null && capacityValue.Type != JTokenType.Null) { int capacityInstance = ((int)capacityValue); skuInstance.Capacity = capacityInstance; } } JToken lastModifiedByValue = propertiesValue["lastModifiedBy"]; if (lastModifiedByValue != null && lastModifiedByValue.Type != JTokenType.Null) { string lastModifiedByInstance = ((string)lastModifiedByValue); propertiesInstance.LastModifiedBy = lastModifiedByInstance; } JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); automationAccountInstance.Id = idInstance; } JToken nameValue2 = responseDoc["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); automationAccountInstance.Name = nameInstance2; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); automationAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); automationAccountInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); automationAccountInstance.Type = typeInstance; } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); automationAccountInstance.Etag = etagInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve a list of accounts. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='resourceGroupName'> /// Optional. The name of the resource group /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list account operation. /// </returns> public async Task<AutomationAccountListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/"; if (resourceGroupName != null) { url = url + "resourceGroups/" + Uri.EscapeDataString(resourceGroupName) + "/"; } url = url + "providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AutomationAccountListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AutomationAccountListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { AutomationAccount automationAccountInstance = new AutomationAccount(); result.AutomationAccounts.Add(automationAccountInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { AutomationAccountProperties propertiesInstance = new AutomationAccountProperties(); automationAccountInstance.Properties = propertiesInstance; JToken skuValue = propertiesValue["sku"]; if (skuValue != null && skuValue.Type != JTokenType.Null) { Sku skuInstance = new Sku(); propertiesInstance.Sku = skuInstance; JToken nameValue = skuValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); skuInstance.Name = nameInstance; } JToken familyValue = skuValue["family"]; if (familyValue != null && familyValue.Type != JTokenType.Null) { string familyInstance = ((string)familyValue); skuInstance.Family = familyInstance; } JToken capacityValue = skuValue["capacity"]; if (capacityValue != null && capacityValue.Type != JTokenType.Null) { int capacityInstance = ((int)capacityValue); skuInstance.Capacity = capacityInstance; } } JToken lastModifiedByValue = propertiesValue["lastModifiedBy"]; if (lastModifiedByValue != null && lastModifiedByValue.Type != JTokenType.Null) { string lastModifiedByInstance = ((string)lastModifiedByValue); propertiesInstance.LastModifiedBy = lastModifiedByInstance; } JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); automationAccountInstance.Id = idInstance; } JToken nameValue2 = valueValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); automationAccountInstance.Name = nameInstance2; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); automationAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); automationAccountInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); automationAccountInstance.Type = typeInstance; } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); automationAccountInstance.Etag = etagInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve next list of accounts. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list account operation. /// </returns> public async Task<AutomationAccountListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AutomationAccountListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AutomationAccountListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { AutomationAccount automationAccountInstance = new AutomationAccount(); result.AutomationAccounts.Add(automationAccountInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { AutomationAccountProperties propertiesInstance = new AutomationAccountProperties(); automationAccountInstance.Properties = propertiesInstance; JToken skuValue = propertiesValue["sku"]; if (skuValue != null && skuValue.Type != JTokenType.Null) { Sku skuInstance = new Sku(); propertiesInstance.Sku = skuInstance; JToken nameValue = skuValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); skuInstance.Name = nameInstance; } JToken familyValue = skuValue["family"]; if (familyValue != null && familyValue.Type != JTokenType.Null) { string familyInstance = ((string)familyValue); skuInstance.Family = familyInstance; } JToken capacityValue = skuValue["capacity"]; if (capacityValue != null && capacityValue.Type != JTokenType.Null) { int capacityInstance = ((int)capacityValue); skuInstance.Capacity = capacityInstance; } } JToken lastModifiedByValue = propertiesValue["lastModifiedBy"]; if (lastModifiedByValue != null && lastModifiedByValue.Type != JTokenType.Null) { string lastModifiedByInstance = ((string)lastModifiedByValue); propertiesInstance.LastModifiedBy = lastModifiedByInstance; } JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); automationAccountInstance.Id = idInstance; } JToken nameValue2 = valueValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); automationAccountInstance.Name = nameInstance2; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); automationAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); automationAccountInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); automationAccountInstance.Type = typeInstance; } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); automationAccountInstance.Etag = etagInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the patch automation account. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the create account operation. /// </returns> public async Task<AutomationAccountPatchResponse> PatchAsync(string resourceGroupName, AutomationAccountPatchParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; if (parameters.Name != null) { url = url + Uri.EscapeDataString(parameters.Name); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject automationAccountPatchParametersValue = new JObject(); requestDoc = automationAccountPatchParametersValue; JObject propertiesValue = new JObject(); automationAccountPatchParametersValue["properties"] = propertiesValue; if (parameters.Properties.Sku != null) { JObject skuValue = new JObject(); propertiesValue["sku"] = skuValue; if (parameters.Properties.Sku.Name != null) { skuValue["name"] = parameters.Properties.Sku.Name; } if (parameters.Properties.Sku.Family != null) { skuValue["family"] = parameters.Properties.Sku.Family; } skuValue["capacity"] = parameters.Properties.Sku.Capacity; } if (parameters.Name != null) { automationAccountPatchParametersValue["name"] = parameters.Name; } if (parameters.Location != null) { automationAccountPatchParametersValue["location"] = parameters.Location; } if (parameters.Tags != null) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } automationAccountPatchParametersValue["tags"] = tagsDictionary; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AutomationAccountPatchResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AutomationAccountPatchResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { AutomationAccount automationAccountInstance = new AutomationAccount(); result.AutomationAccount = automationAccountInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { AutomationAccountProperties propertiesInstance = new AutomationAccountProperties(); automationAccountInstance.Properties = propertiesInstance; JToken skuValue2 = propertiesValue2["sku"]; if (skuValue2 != null && skuValue2.Type != JTokenType.Null) { Sku skuInstance = new Sku(); propertiesInstance.Sku = skuInstance; JToken nameValue = skuValue2["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); skuInstance.Name = nameInstance; } JToken familyValue = skuValue2["family"]; if (familyValue != null && familyValue.Type != JTokenType.Null) { string familyInstance = ((string)familyValue); skuInstance.Family = familyInstance; } JToken capacityValue = skuValue2["capacity"]; if (capacityValue != null && capacityValue.Type != JTokenType.Null) { int capacityInstance = ((int)capacityValue); skuInstance.Capacity = capacityInstance; } } JToken lastModifiedByValue = propertiesValue2["lastModifiedBy"]; if (lastModifiedByValue != null && lastModifiedByValue.Type != JTokenType.Null) { string lastModifiedByInstance = ((string)lastModifiedByValue); propertiesInstance.LastModifiedBy = lastModifiedByInstance; } JToken stateValue = propertiesValue2["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken creationTimeValue = propertiesValue2["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue2["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); automationAccountInstance.Id = idInstance; } JToken nameValue2 = responseDoc["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); automationAccountInstance.Name = nameInstance2; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); automationAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); automationAccountInstance.Tags.Add(tagsKey2, tagsValue2); } } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); automationAccountInstance.Type = typeInstance; } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); automationAccountInstance.Etag = etagInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using SteamBot.SteamGroups; using SteamKit2; using SteamKit2.Internal; using SteamTrade; using SteamTrade.TradeOffer; using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace SteamBot { public class Bot : IDisposable, INotifyPropertyChanged { #region Bot delegates public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id); #endregion #region Private readonly variables private readonly SteamUser.LogOnDetails logOnDetails; private readonly string schemaLang; private readonly string logFile; private readonly Dictionary<SteamID, UserHandler> userHandlers; private readonly Log.LogLevel consoleLogLevel; private readonly Log.LogLevel fileLogLevel; private readonly UserHandlerCreator createHandler; private readonly bool isProccess; private readonly BackgroundWorker botThread; private readonly string sentryFilesDirectoryName; private readonly string authFilesDirectoryName; private readonly CallbackManager steamCallbackManager; #endregion #region Private variables private TradeManager tradeManager; private TradeOfferManager tradeOfferManager; private int tradePollingInterval; private int tradeOfferPollingIntervalSecs; private string myUserNonce; private string myUniqueId; private bool cookiesAreInvalid = true; private List<SteamID> friends; private bool disposed = false; private string consoleInput; private Thread tradeOfferThread; private bool pollTradeOffers = true; #endregion #region Public readonly variables /// <summary> /// Userhandler class bot is running. /// </summary> public readonly string BotControlClass; /// <summary> /// The display name of bot to steam. /// </summary> public readonly string DisplayName; /// <summary> /// The chat response from the config file. /// </summary> public readonly string ChatResponse; /// <summary> /// An array of admins for bot. /// </summary> public readonly IEnumerable<SteamID> Admins; public readonly SteamClient SteamClient; public readonly SteamUser SteamUser; public readonly SteamFriends SteamFriends; public readonly SteamTrading SteamTrade; public readonly SteamGameCoordinator SteamGameCoordinator; public readonly SteamNotifications SteamNotifications; /// <summary> /// The amount of time the bot will trade for. /// </summary> public readonly int MaximumTradeTime; /// <summary> /// The amount of time the bot will wait between user interactions with trade. /// </summary> public readonly int MaximumActionGap; /// <summary> /// The api key of bot. /// </summary> public readonly string ApiKey; public readonly SteamWeb SteamWeb; /// <summary> /// The prefix shown before bot's display name. /// </summary> public readonly string DisplayNamePrefix; #endregion #region Public variables public string AuthCode; public bool IsRunning; /// <summary> /// Is bot fully Logged in. /// Set only when bot did successfully Log in. /// </summary> public bool IsLoggedIn { get { return isLoggedIn; } set { isLoggedIn = value; RaisePropertyChanged(nameof(IsLoggedIn)); } } private bool isLoggedIn; /// <summary> /// The current trade the bot is in. /// </summary> public Trade CurrentTrade { get; private set; } /// <summary> /// The current game bot is in. /// Default: 0 = No game. /// </summary> public int CurrentGame { get; private set; } /// <summary> /// The instance of the Logger for the bot. You may change it while bot is running. /// </summary> public ILog Log { get; set; } public SteamAuth.SteamGuardAccount SteamGuardAccount; private CultureInfo culture; #endregion public IEnumerable<SteamID> FriendsList { get { CreateFriendsListIfNecessary(); return friends; } } public CallbackManager SteamCallbackManager { get { return steamCallbackManager; } } public string SentryFilesDirectoryName => sentryFilesDirectoryName; public string AuthFilesDirectoryName => authFilesDirectoryName; /// <summary> /// Compatibility sanity. /// </summary> [Obsolete("Refactored to be Log instead of log")] public ILog log { get { return Log; } } public bool PollTradeOffers { get { return pollTradeOffers; } set { if (pollTradeOffers == value) return; if (value) { pollTradeOffers = true; InitializeTradeOfferPolling(); } else { pollTradeOffers = false; if (tradeOfferManager != null) { UnsubscribeTradeOffer(tradeOfferManager); tradeOfferManager = null; } tradeOfferThread = null; } } } /// <summary> /// Initialize a new instance of <see cref="Bot"/>. /// </summary> /// <param name="config"></param> /// <param name="apiKey">If an API Key exists in parameter <paramref name="config"/>, the one in <paramref name="config"/> takes precedence.</param> /// <param name="sentryFilesDirectoryName">Sentry files will be saved under this directory.</param> /// <param name="authFilesDirectoryName">Auth files will be saved under this directory.</param> /// <param name="handlerCreator">A delegate to create <see cref="UserHandler"/>. All user handlers will be created using this.</param> /// <param name="process">This parameter indicates if the bot is launched in a seperate process. However, this value, in fact, is simply a marker and is not used anywhere.</param> public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool process = false, bool useTwoFactorByDefault = false, ILog log = null, string sentryFilesDirectoryName = null, string authFilesDirectoryName = null, SteamConfiguration steamConfiguration = null) { this.sentryFilesDirectoryName = sentryFilesDirectoryName ?? Path.Combine(Directory.GetCurrentDirectory() + "sentryfiles"); this.authFilesDirectoryName = authFilesDirectoryName ?? Path.Combine(Directory.GetCurrentDirectory() + "authfiles"); userHandlers = new Dictionary<SteamID, UserHandler>(); logOnDetails = new SteamUser.LogOnDetails { Username = config.Username, Password = config.Password }; DisplayName = config.DisplayName; ChatResponse = config.ChatResponse; MaximumTradeTime = config.MaximumTradeTime; MaximumActionGap = config.MaximumActionGap; DisplayNamePrefix = config.DisplayNamePrefix; tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval; tradeOfferPollingIntervalSecs = (config.TradeOfferPollingIntervalSecs == 0 ? 30 : config.TradeOfferPollingIntervalSecs); schemaLang = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en"; Admins = config.Admins; ApiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey; isProccess = process; try { if (config.LogLevel != null) { consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true); Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName); } else consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true); } catch (ArgumentException) { Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName); consoleLogLevel = SteamBot.Log.LogLevel.Info; } try { fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true); } catch (ArgumentException) { Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName); fileLogLevel = SteamBot.Log.LogLevel.Info; } logFile = config.LogFile; if (log == null) Log = new Log(logFile, DisplayName, consoleLogLevel, fileLogLevel); else Log = log; if (useTwoFactorByDefault) { var mobileAuthCode = GetMobileAuthCode(); if (string.IsNullOrEmpty(mobileAuthCode)) { Log.Error("Failed to generate 2FA code. Make sure you have linked the authenticator via SteamBot."); } else { logOnDetails.TwoFactorCode = mobileAuthCode; Log.Success("Generated 2FA code."); } } createHandler = handlerCreator; BotControlClass = config.BotControlClass; SteamWeb = new SteamWeb(); // Hacking around https ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate; Log.Debug("Initializing Steam Bot..."); if (steamConfiguration == null) SteamClient = new SteamClient(); else SteamClient = new SteamClient(steamConfiguration); steamCallbackManager = new CallbackManager(SteamClient); SubscribeSteamCallbacks(); SteamClient.AddHandler(new SteamNotifications()); SteamTrade = SteamClient.GetHandler<SteamTrading>(); SteamUser = SteamClient.GetHandler<SteamUser>(); SteamFriends = SteamClient.GetHandler<SteamFriends>(); SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>(); SteamNotifications = SteamClient.GetHandler<SteamNotifications>(); botThread = new BackgroundWorker { WorkerSupportsCancellation = true }; botThread.DoWork += BackgroundWorkerOnDoWork; botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted; } private void CreateFriendsListIfNecessary() { if (friends != null) return; friends = new List<SteamID>(); for (int i = 0; i < SteamFriends.GetFriendCount(); i++) friends.Add(SteamFriends.GetFriendByIndex(i)); } /// <summary> /// Occurs when the bot needs the SteamGuard authentication code. /// </summary> /// <remarks> /// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/> /// </remarks> public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired; public event PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Starts the callback thread and connects to Steam via SteamKit2. /// </summary> /// <returns><c>true</c>. See remarks</returns> public void StartBot() { StartBot(Thread.CurrentThread.CurrentCulture); } /// <summary> /// Starts the callback thread and connects to Steam via SteamKit2. /// </summary> /// <returns><c>true</c>. See remarks</returns> public void StartBot(CultureInfo culture) { this.culture = culture; IsRunning = true; Log.Info(Properties.Resources.Connecting); if (!botThread.IsBusy) botThread.RunWorkerAsync(); SteamClient.Connect(); Log.Success(Properties.Resources.DoneLoadingBot); } /// <summary> /// Disconnect from the Steam network and stop the callback /// thread. /// </summary> public void StopBot() { IsRunning = false; Log.Debug("Trying to shut down bot thread."); SteamClient.Disconnect(); botThread.CancelAsync(); while (botThread.IsBusy) Thread.Yield(); userHandlers.Clear(); } /// <summary> /// Creates a new trade with the given partner. /// </summary> /// <returns> /// <c>true</c>, if trade was opened, /// <c>false</c> if there is another trade that must be closed first. /// </returns> public bool OpenTrade(SteamID other) { if (CurrentTrade != null || CheckCookies() == false) return false; SteamTrade.Trade(other); return true; } /// <summary> /// Closes the current active trade. /// </summary> public void CloseTrade() { if (CurrentTrade == null) return; UnsubscribeTrade(GetUserHandler(CurrentTrade.OtherSID), CurrentTrade); tradeManager.StopTrade(); CurrentTrade = null; } void OnTradeTimeout(object sender, EventArgs args) { // ignore event params and just null out the trade. GetUserHandler(CurrentTrade.OtherSID).OnTradeTimeout(); } /// <summary> /// Create a new trade offer with the specified partner /// </summary> /// <param name="other">SteamId of the partner</param> /// <returns></returns> public TradeOffer NewTradeOffer(SteamID other) { return tradeOfferManager.NewOffer(other); } /// <summary> /// Try to get a specific trade offer using the offerid /// </summary> /// <param name="offerId"></param> /// <param name="tradeOffer"></param> /// <returns></returns> public bool TryGetTradeOffer(string offerId, out TradeOffer tradeOffer) { return tradeOfferManager.TryGetOffer(offerId, out tradeOffer); } public void HandleBotCommand(string command) { try { if (command == "linkauth") { LinkMobileAuth(); } else if (command == "getauth") { try { Log.Success("Generated Steam Guard code: " + SteamGuardAccount.GenerateSteamGuardCode()); } catch (NullReferenceException) { Log.Error("Unable to generate Steam Guard code."); } } else if (command == "unlinkauth") { if (SteamGuardAccount == null) { Log.Error("Mobile authenticator is not active on this bot."); } else if (SteamGuardAccount.DeactivateAuthenticator()) { Log.Success("Deactivated authenticator on this account."); } else { Log.Error("Failed to deactivate authenticator on this account."); } } else { GetUserHandler(SteamClient.SteamID).OnBotCommand(command); } } catch (ObjectDisposedException e) { // Writing to console because odds are the error was caused by a disposed Log. Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); if (!this.IsRunning) { Console.WriteLine("The Bot is no longer running and could not write to the Log. Try Starting this bot first."); } } catch (Exception e) { Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); } } protected void SpawnTradeOfferPollingThread() { if (tradeOfferThread == null) { tradeOfferThread = new Thread(TradeOfferPollingFunction); tradeOfferThread.Start(); } } protected void CancelTradeOfferPollingThread() { tradeOfferThread = null; } protected void TradeOfferPollingFunction() { while (tradeOfferThread == Thread.CurrentThread) { try { tradeOfferManager.EnqueueUpdatedOffers(); } catch (Exception e) { Log.Error("Error while polling trade offers: " + e); } Thread.Sleep(tradeOfferPollingIntervalSecs * 1000); } } public void HandleInput(string input) { consoleInput = input; } public string WaitForInput() { consoleInput = null; while (true) { if (consoleInput != null) { return consoleInput; } Thread.Sleep(5); } } bool HandleTradeSessionStart(SteamID other) { if (CurrentTrade != null) return false; try { CurrentTrade = tradeManager.CreateTrade(SteamUser.SteamID, other); CurrentTrade.OnClose += CloseTrade; SubscribeTrade(CurrentTrade, GetUserHandler(other)); tradeManager.StartTradeThread(CurrentTrade); return true; } catch (SteamTrade.Exceptions.InventoryFetchException) { // we shouldn't get here because the inv checks are also // done in the TradeProposedCallback handler. /*string response = String.Empty; if (ie.FailingSteamId.ConvertToUInt64() == other.ConvertToUInt64()) { response = "Trade failed. Could not correctly fetch your backpack. Either the inventory is inaccessible or your backpack is private."; } else { response = "Trade failed. Could not correctly fetch my backpack."; } SteamFriends.SendChatMessage(other, EChatEntryType.ChatMsg, response); Log.Info ("Bot sent other: {0}", response); CurrentTrade = null;*/ return false; } } private void SubscribeSteamCallbacks() { #region Login SteamCallbackManager.Subscribe<SteamClient.ConnectedCallback>(callback => { UserLogOn(); }); SteamCallbackManager.Subscribe<SteamUser.LoggedOnCallback>(callback => { Log.Debug(Properties.Resources.LoggedOnCallback + "{0}", callback.Result); if (callback.Result == EResult.OK) { myUserNonce = callback.WebAPIUserNonce; } else { Log.Error(Properties.Resources.LoginError + "{0}", callback.Result); } if (callback.Result == EResult.AccountLoginDeniedNeedTwoFactor) { var mobileAuthCode = GetMobileAuthCode(); if (string.IsNullOrEmpty(mobileAuthCode)) { var eva = new SteamGuardRequiredEventArgs(); FireOnSteamGuardRequired(eva); if (!string.IsNullOrEmpty(eva.SteamGuard)) logOnDetails.TwoFactorCode = eva.SteamGuard; else Log.Error("Failed to generate 2FA code. Make sure you have linked the authenticator via SteamBot."); } else { logOnDetails.TwoFactorCode = mobileAuthCode; Log.Success(Properties.Resources.Regenerated2FACode); } } else if (callback.Result == EResult.TwoFactorCodeMismatch) { SteamAuth.TimeAligner.AlignTime(); if (SteamGuardAccount != null) { Log.Warn(Properties.Resources.TwoFACodeMismatchRetryIn15Seconds); Thread.Sleep(15000); logOnDetails.TwoFactorCode = SteamGuardAccount.GenerateSteamGuardCode(); Log.Success(Properties.Resources.Regenerated2FACode); } else { var eva = new SteamGuardRequiredEventArgs(); FireOnSteamGuardRequired(eva); logOnDetails.TwoFactorCode = eva.SteamGuard; if(string.IsNullOrEmpty(eva.SteamGuard)) Log.Warn(Properties.Resources.TwoFACodeMismatchRetryIn15Seconds); } } else if (callback.Result == EResult.AccountLogonDenied) { Log.Interface("This account is SteamGuard enabled. Enter the code via the `auth' command."); // try to get the steamguard auth code from the event callback var eva = new SteamGuardRequiredEventArgs(); FireOnSteamGuardRequired(eva); if (!String.IsNullOrEmpty(eva.SteamGuard)) logOnDetails.AuthCode = eva.SteamGuard; else logOnDetails.AuthCode = Console.ReadLine(); } else if (callback.Result == EResult.InvalidLoginAuthCode) { Log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command."); logOnDetails.AuthCode = Console.ReadLine(); } }); SteamCallbackManager.Subscribe<SteamUser.LoginKeyCallback>(callback => { myUniqueId = callback.UniqueID.ToString(); UserWebLogOn(); SteamFriends.SetPersonaName(DisplayNamePrefix + DisplayName); SteamFriends.SetPersonaState(EPersonaState.Online); Log.Success("Steam Bot Logged In Completely!"); GetUserHandler(SteamClient.SteamID).OnLoginCompleted(); }); SteamCallbackManager.Subscribe<SteamUser.WebAPIUserNonceCallback>(webCallback => { Log.Debug(Properties.Resources.ReceivedNewWebAPIUserNonce); if (webCallback.Result == EResult.OK) { myUserNonce = webCallback.Nonce; UserWebLogOn(); } else { Log.Error(Properties.Resources.WebAPIUserNonceError + webCallback.Result); } }); SteamCallbackManager.Subscribe<SteamUser.UpdateMachineAuthCallback>( authCallback => OnUpdateMachineAuthCallback(authCallback) ); #endregion #region Friends SteamCallbackManager.Subscribe<SteamFriends.FriendsListCallback>(callback => { foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList) { switch (friend.SteamID.AccountType) { case EAccountType.Clan: if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnGroupAdd()) { AcceptGroupInvite(friend.SteamID); } else { DeclineGroupInvite(friend.SteamID); } } break; default: CreateFriendsListIfNecessary(); if (friend.Relationship == EFriendRelationship.None) { friends.Remove(friend.SteamID); GetUserHandler(friend.SteamID).OnFriendRemove(); RemoveUserHandler(friend.SteamID); } else if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnFriendAdd()) { if (!friends.Contains(friend.SteamID)) { friends.Add(friend.SteamID); } SteamFriends.AddFriend(friend.SteamID); } else { if (friends.Contains(friend.SteamID)) { friends.Remove(friend.SteamID); } SteamFriends.RemoveFriend(friend.SteamID); RemoveUserHandler(friend.SteamID); } } break; } } }); SteamCallbackManager.Subscribe<SteamFriends.FriendMsgCallback>(callback => { EChatEntryType type = callback.EntryType; if (callback.EntryType == EChatEntryType.ChatMsg) { Log.Info(Properties.Resources.ChatMessageFrom, SteamFriends.GetFriendPersonaName(callback.Sender), callback.Message ); GetUserHandler(callback.Sender).OnMessageHandler(callback.Message, type); } }); #endregion #region Group Chat SteamCallbackManager.Subscribe<SteamFriends.ChatMsgCallback>(callback => { GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message); }); #endregion #region Trading SteamCallbackManager.Subscribe<SteamTrading.SessionStartCallback>(callback => { bool started = HandleTradeSessionStart(callback.OtherClient); if (!started) Log.Error(Properties.Resources.CouldNotStartTheTradeSession); else Log.Debug(Properties.Resources.TradeOpened); }); SteamCallbackManager.Subscribe<SteamTrading.TradeProposedCallback>(callback => { if (CheckCookies() == false) { SteamTrade.RespondToTrade(callback.TradeID, false); return; } if (CurrentTrade == null && GetUserHandler(callback.OtherClient).OnTradeRequest()) SteamTrade.RespondToTrade(callback.TradeID, true); else SteamTrade.RespondToTrade(callback.TradeID, false); }); SteamCallbackManager.Subscribe<SteamTrading.TradeResultCallback>(callback => { if (callback.Response == EEconTradeResponse.Accepted) { Log.Debug(Properties.Resources.TradeStatus + "{0}", callback.Response); Log.Info(Properties.Resources.TradeAccepted); GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString()); } else { Log.Warn(Properties.Resources.TradeFailed, callback.Response); CloseTrade(); GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString()); } }); #endregion #region Disconnect SteamCallbackManager.Subscribe<SteamUser.LoggedOffCallback>(callback => { IsLoggedIn = false; Log.Warn(Properties.Resources.LoggedOffSteamReason + "{0}", callback.Result); CancelTradeOfferPollingThread(); }); SteamCallbackManager.Subscribe<SteamClient.DisconnectedCallback>(callback => { if (IsLoggedIn) { IsLoggedIn = false; CloseTrade(); Log.Warn(Properties.Resources.DisconnectedFromSteamNetwork); CancelTradeOfferPollingThread(); } SteamClient.Connect(); }); #endregion #region Notifications SteamCallbackManager.Subscribe<SteamBot.SteamNotifications.CommentNotificationCallback>(callback => { //various types of comment notifications on profile/activity feed etc //Log.Info("received CommentNotificationCallback"); //Log.Info("New Commments " + callback.CommentNotifications.CountNewComments); //Log.Info("New Commments Owners " + callback.CommentNotifications.CountNewCommentsOwner); //Log.Info("New Commments Subscriptions" + callback.CommentNotifications.CountNewCommentsSubscriptions); }); #endregion } public void SetGamePlaying(int id) { var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed); if (id != 0) gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed { game_id = new GameID(id), }); SteamClient.Send(gamePlaying); CurrentGame = id; } string GetMobileAuthCode() { var authFile = Path.Combine(authFilesDirectoryName, String.Format("{0}.auth", logOnDetails.Username)); if (File.Exists(authFile)) SteamGuardAccount = Newtonsoft.Json.JsonConvert.DeserializeObject<SteamAuth.SteamGuardAccount>(File.ReadAllText(authFile)); if (SteamGuardAccount != null) return SteamGuardAccount.GenerateSteamGuardCode(); else return string.Empty; } /// <summary> /// Link a mobile authenticator to bot account, using SteamTradeOffersBot as the authenticator. /// Called from bot manager console. Usage: "exec [index] linkauth" /// If successful, 2FA will be required upon the next login. /// Use "exec [index] getauth" if you need to get a Steam Guard code for the account. /// To deactivate the authenticator, use "exec [index] unlinkauth". /// </summary> void LinkMobileAuth() { new Thread(() => { var login = new SteamAuth.UserLogin(logOnDetails.Username, logOnDetails.Password); var loginResult = login.DoLogin(); if (loginResult == SteamAuth.LoginResult.NeedEmail) { while (loginResult == SteamAuth.LoginResult.NeedEmail) { Log.Interface("Enter Steam Guard code from email (type \"input [index] [code]\"):"); var emailCode = WaitForInput(); login.EmailCode = emailCode; loginResult = login.DoLogin(); } } if (loginResult == SteamAuth.LoginResult.LoginOkay) { Log.Info("Linking mobile authenticator..."); var authLinker = new SteamAuth.AuthenticatorLinker(login.Session); var addAuthResult = authLinker.AddAuthenticator(); if (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.MustProvidePhoneNumber) { while (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.MustProvidePhoneNumber) { Log.Interface("Enter phone number with country code, e.g. +1XXXXXXXXXXX (type \"input [index] [number]\"):"); var phoneNumber = WaitForInput(); authLinker.PhoneNumber = phoneNumber; addAuthResult = authLinker.AddAuthenticator(); } } if (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.AwaitingFinalization) { SteamGuardAccount = authLinker.LinkedAccount; try { var authFile = Path.Combine(authFilesDirectoryName, String.Format("{0}.auth", logOnDetails.Username)); Directory.CreateDirectory(authFilesDirectoryName); File.WriteAllText(authFile, Newtonsoft.Json.JsonConvert.SerializeObject(SteamGuardAccount)); Log.Interface("Enter SMS code (type \"input [index] [code]\"):"); var smsCode = WaitForInput(); var authResult = authLinker.FinalizeAddAuthenticator(smsCode); if (authResult == SteamAuth.AuthenticatorLinker.FinalizeResult.Success) { Log.Success("Linked authenticator."); } else { Log.Error("Error linking authenticator: " + authResult); } } catch (IOException) { Log.Error("Failed to save auth file. Aborting authentication."); } } else { Log.Error("Error adding authenticator: " + addAuthResult); } } else { if (loginResult == SteamAuth.LoginResult.Need2FA) { Log.Error("Mobile authenticator has already been linked!"); } else { Log.Error("Error performing mobile login: " + loginResult); } } }).Start(); } void UserLogOn() { // get sentry file which has the machine hw info saved // from when a steam guard code was entered Directory.CreateDirectory(sentryFilesDirectoryName); FileInfo fi = new FileInfo(System.IO.Path.Combine(sentryFilesDirectoryName, String.Format("{0}.sentryfile", logOnDetails.Username))); if (fi.Exists && fi.Length > 0) logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName)); else logOnDetails.SentryFileHash = null; SteamUser.LogOn(logOnDetails); } void UserWebLogOn() { do { IsLoggedIn = SteamWeb.Authenticate(myUniqueId, SteamClient, myUserNonce); if (!IsLoggedIn) { Log.Warn(Properties.Resources.AuthenticationFailedRetryingIn2s); Thread.Sleep(2000); } } while (!IsLoggedIn); Log.Success(Properties.Resources.UserAuthenticated); tradeManager = new TradeManager(ApiKey, SteamWeb); tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximumActionGap, tradePollingInterval); tradeManager.OnTimeout += OnTradeTimeout; cookiesAreInvalid = false; if (PollTradeOffers) { InitializeTradeOfferPolling(); } } private void InitializeTradeOfferPolling() { tradeOfferManager = new TradeOfferManager(ApiKey, SteamWeb); SubscribeTradeOffer(tradeOfferManager); // Success, check trade offers which we have received while we were offline SpawnTradeOfferPollingThread(); } /// <summary> /// Checks if sessionId and token cookies are still valid. /// Sets cookie flag if they are invalid. /// </summary> /// <returns>true if cookies are valid; otherwise false</returns> bool CheckCookies() { // We still haven't re-authenticated if (cookiesAreInvalid) return false; try { if (!SteamWeb.VerifyCookies()) { // Cookies are no longer valid Log.Warn("Cookies are invalid. Need to re-authenticate."); cookiesAreInvalid = true; SteamUser.RequestWebAPIUserNonce(); return false; } } catch { // Even if exception is caught, we should still continue. Log.Warn("Cookie check failed. https://steamcommunity.com is possibly down."); } return true; } public UserHandler GetUserHandler(SteamID sid) { if (!userHandlers.ContainsKey(sid)) userHandlers[sid] = createHandler(this, sid); return userHandlers[sid]; } void RemoveUserHandler(SteamID sid) { if (userHandlers.ContainsKey(sid)) userHandlers.Remove(sid); } static byte[] SHAHash(byte[] input) { SHA1Managed sha = new SHA1Managed(); byte[] output = sha.ComputeHash(input); sha.Clear(); return output; } void OnUpdateMachineAuthCallback(SteamUser.UpdateMachineAuthCallback machineAuth) { byte[] hash = SHAHash(machineAuth.Data); Directory.CreateDirectory(sentryFilesDirectoryName); File.WriteAllBytes(System.IO.Path.Combine(sentryFilesDirectoryName, String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data); var authResponse = new SteamUser.MachineAuthDetails { BytesWritten = machineAuth.BytesToWrite, FileName = machineAuth.FileName, FileSize = machineAuth.BytesToWrite, Offset = machineAuth.Offset, SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs LastError = 0, // result from win32 GetLastError Result = EResult.OK, // if everything went okay, otherwise ~who knows~ JobID = machineAuth.JobID, // so we respond to the correct server job }; // send off our response SteamUser.SendMachineAuthResponse(authResponse); } public void TradeOfferRouter(TradeOffer offer) { GetUserHandler(offer.PartnerSteamId).OnTradeOfferUpdated(offer); } public void SubscribeTradeOffer(TradeOfferManager tradeOfferManager) { tradeOfferManager.OnTradeOfferUpdated += TradeOfferRouter; } //todo: should unsubscribe eventually... public void UnsubscribeTradeOffer(TradeOfferManager tradeOfferManager) { tradeOfferManager.OnTradeOfferUpdated -= TradeOfferRouter; } /// <summary> /// Subscribes all listeners of this to the trade. /// </summary> public void SubscribeTrade(Trade trade, UserHandler handler) { trade.OnAwaitingConfirmation += handler._OnTradeAwaitingConfirmation; trade.OnClose += handler.OnTradeClose; trade.OnError += handler.OnTradeError; trade.OnStatusError += handler.OnStatusError; //trade.OnTimeout += OnTradeTimeout; trade.OnAfterInit += handler.OnTradeInit; trade.OnMessage += handler.OnTradeMessageHandler; trade.OnUserSetReady += handler.OnTradeReadyHandler; trade.OnUserAccept += handler.OnTradeAcceptHandler; } /// <summary> /// Unsubscribes all listeners of this from the current trade. /// </summary> public void UnsubscribeTrade(UserHandler handler, Trade trade) { trade.OnAwaitingConfirmation -= handler._OnTradeAwaitingConfirmation; trade.OnClose -= handler.OnTradeClose; trade.OnError -= handler.OnTradeError; trade.OnStatusError -= handler.OnStatusError; //Trade.OnTimeout -= OnTradeTimeout; trade.OnAfterInit -= handler.OnTradeInit; trade.OnMessage -= handler.OnTradeMessageHandler; trade.OnUserSetReady -= handler.OnTradeReadyHandler; trade.OnUserAccept -= handler.OnTradeAcceptHandler; } /// <summary> /// This method pulls and confirm all mobile confirmations. It will be called by <see cref="TradeManager"/> after every successful trade. /// </summary> public virtual void AcceptAllMobileTradeConfirmations() { if (SteamGuardAccount == null) { Log.Warn("Bot account does not have 2FA enabled."); } else { SteamGuardAccount.Session.SteamLoginSecure = SteamWeb.TokenSecure; try { foreach (var confirmation in SteamGuardAccount.FetchConfirmations()) { if (SteamGuardAccount.AcceptConfirmation(confirmation)) { Log.Success("Confirmed {0}. (Confirmation ID #{1})", confirmation.ConfType, confirmation.ID); } } } catch (SteamAuth.SteamGuardAccount.WGTokenInvalidException) { Log.Error("Invalid session when trying to fetch trade confirmations."); } } } /// <summary> /// Get duration of escrow in days. Call this before sending a trade offer. /// Credit to: https://www.reddit.com/r/SteamBot/comments/3w8j7c/code_getescrowduration_for_c/ /// </summary> /// <param name="steamId">Steam ID of user you want to send a trade offer to</param> /// <param name="token">User's trade token. Can be an empty string if user is on bot's friends list.</param> /// <exception cref="NullReferenceException">Thrown when Steam returns an empty response.</exception> /// <exception cref="TradeOfferEscrowDurationParseException">Thrown when the user is unavailable for trade or Steam returns invalid data.</exception> /// <returns>TradeOfferEscrowDuration</returns> public TradeOfferEscrowDuration GetEscrowDuration(SteamID steamId, string token) { var url = "https://steamcommunity.com/tradeoffer/new/"; var data = new System.Collections.Specialized.NameValueCollection(); data.Add("partner", steamId.AccountID.ToString()); if (!string.IsNullOrEmpty(token)) { data.Add("token", token); } var resp = SteamWeb.Fetch(url, "GET", data, false); if (string.IsNullOrWhiteSpace(resp)) { throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration."); } return ParseEscrowResponse(resp); } /// <summary> /// Get duration of escrow in days. Call this after receiving a trade offer. /// </summary> /// <param name="tradeOfferId">The ID of the trade offer</param> /// <exception cref="NullReferenceException">Thrown when Steam returns an empty response.</exception> /// <exception cref="TradeOfferEscrowDurationParseException">Thrown when the user is unavailable for trade or Steam returns invalid data.</exception> /// <returns>TradeOfferEscrowDuration</returns> public TradeOfferEscrowDuration GetEscrowDuration(string tradeOfferId) { var url = "https://steamcommunity.com/tradeoffer/" + tradeOfferId; var resp = SteamWeb.Fetch(url, "GET", null, false); if (string.IsNullOrWhiteSpace(resp)) { throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration."); } return ParseEscrowResponse(resp); } private TradeOfferEscrowDuration ParseEscrowResponse(string resp) { var myM = Regex.Match(resp, @"g_daysMyEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase); var theirM = Regex.Match(resp, @"g_daysTheirEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase); if (!myM.Groups["days"].Success || !theirM.Groups["days"].Success) { var steamErrorM = Regex.Match(resp, @"<div id=""error_msg"">([^>]+)<\/div>", RegexOptions.IgnoreCase); if (steamErrorM.Groups.Count > 1) { var steamError = Regex.Replace(steamErrorM.Groups[1].Value.Trim(), @"\t|\n|\r", ""); ; throw new TradeOfferEscrowDurationParseException(steamError); } else { throw new TradeOfferEscrowDurationParseException(string.Empty); } } return new TradeOfferEscrowDuration() { DaysMyEscrow = int.Parse(myM.Groups["days"].Value), DaysTheirEscrow = int.Parse(theirM.Groups["days"].Value) }; } public class TradeOfferEscrowDuration { public int DaysMyEscrow { get; set; } public int DaysTheirEscrow { get; set; } } public class TradeOfferEscrowDurationParseException : Exception { public TradeOfferEscrowDurationParseException() : base() { } public TradeOfferEscrowDurationParseException(string message) : base(message) { } } #region Background Worker Methods private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { if (runWorkerCompletedEventArgs.Error != null) { Exception ex = runWorkerCompletedEventArgs.Error; Log.Error("Unhandled exceptions in bot {0} callback thread: {1} {2}", DisplayName, Environment.NewLine, ex); Log.Info("This bot died. Stopping it.."); //backgroundWorker.RunWorkerAsync(); //Thread.Sleep(10000); StopBot(); //StartBot(); } } private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; while (!botThread.CancellationPending) { try { SteamCallbackManager.RunCallbacks(); if (tradeOfferManager != null) { tradeOfferManager.HandleNextPendingTradeOfferUpdate(); } Thread.Sleep(1); } catch (WebException e) { Log.Error("URI: {0} >> {1}", (e.Response != null && e.Response.ResponseUri != null ? e.Response.ResponseUri.ToString() : "unknown"), e.ToString()); System.Threading.Thread.Sleep(45000);//Steam is down, retry in 45 seconds. } catch (Exception e) { Log.Error("Unhandled exception occurred in bot: " + e); } } } #endregion Background Worker Methods private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e) { // Set to null in case this is another attempt this.AuthCode = null; EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired; if (handler != null) handler(this, e); else { while (true) { if (this.AuthCode != null) { e.SteamGuard = this.AuthCode; break; } Thread.Sleep(5); } } } #region Group Methods /// <summary> /// Accepts the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to accept the invite from.</param> private void AcceptGroupInvite(SteamID group) { var AcceptInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); AcceptInvite.Body.GroupID = group.ConvertToUInt64(); AcceptInvite.Body.AcceptInvite = true; this.SteamClient.Send(AcceptInvite); } /// <summary> /// Declines the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to decline the invite from.</param> private void DeclineGroupInvite(SteamID group) { var DeclineInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); DeclineInvite.Body.GroupID = group.ConvertToUInt64(); DeclineInvite.Body.AcceptInvite = false; this.SteamClient.Send(DeclineInvite); } /// <summary> /// Invites a use to the specified Steam Group /// </summary> /// <param name="user">SteamID of the user to invite.</param> /// <param name="groupId">SteamID of the group to invite the user to.</param> public void InviteUserToGroup(SteamID user, SteamID groupId) { var InviteUser = new ClientMsg<CMsgInviteUserToGroup>((int)EMsg.ClientInviteUserToClan); InviteUser.Body.GroupID = groupId.ConvertToUInt64(); InviteUser.Body.Invitee = user.ConvertToUInt64(); InviteUser.Body.UnknownInfo = true; this.SteamClient.Send(InviteUser); } #endregion public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { StopBot(); if (Log != null) Log.Dispose(); CancelTradeOfferPollingThread(); disposed = true; } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; namespace DotSpatial.Data { /// <summary> /// A list that also includes several events during its existing activities. /// List is fussy about inheritance, unfortunately, so this wraps a list /// and then makes this class much more inheritable /// </summary> /// <typeparam name="T">The type of the items in the list.</typeparam> public class ChangeEventList<T> : CopyList<T>, IChangeEventList<T> where T : class, IChangeItem { #region Fields private bool _hasChanged; private int _suspension; #endregion #region Events /// <summary> /// This event is for when it is necessary to do something if any of the internal /// members changes. It will also forward the original item calling the message. /// </summary> public event EventHandler ItemChanged; /// <summary> /// Occurs when this list should be removed from its container. /// </summary> public event EventHandler RemoveItem; #endregion #region Properties /// <summary> /// Gets a value indicating whether or not the list is currently suspended. /// </summary> public bool EventsSuspended => _suspension > 0; #endregion #region Methods /// <summary> /// Adds the elements of the specified collection to the end of the System.Collections.Generic.List&lt;T&gt; /// </summary> /// <param name="collection">collection: The collection whose elements should be added to the end of the /// System.Collections.Generic.List&lt;T&gt;. The collection itself cannot be null, but it can contain elements that are null, /// if type T is a reference type.</param> /// <exception cref="System.ApplicationException">Unable to add while the ReadOnly property is set to true.</exception> public virtual void AddRange(IEnumerable<T> collection) { SuspendEvents(); foreach (T item in collection) { Add(item); } ResumeEvents(); } /// <summary> /// Searches the entire sorted System.Collections.Generic.List&lt;T&gt; for an element using the default comparer and returns the zero-based index of the element. /// </summary> /// <param name="item">The object to locate. The value can be null for reference types.</param> /// <returns>The zero-based index of item in the sorted System.Collections.Generic.List&lt;T&gt;, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of System.Collections.Generic.List&lt;T&gt;.Count.</returns> /// <exception cref="System.InvalidOperationException">The default comparer System.Collections.Generic.Comparer&lt;T&gt;.Default cannot find an implementation of the System.IComparable&lt;T&gt; generic interface or the System.IComparable interface for type T.</exception> public virtual int BinarySearch(T item) { return InnerList.BinarySearch(item); } /// <summary> /// Inserts the elements of a collection into the EventList&lt;T&gt; at the specified index. /// </summary> /// <param name="index">The zero-based index at which the new elements should be inserted.</param> /// <param name="collection">The collection whose elements should be inserted into the EventList&lt;T&gt;. The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.</param> /// <exception cref="System.ArgumentOutOfRangeException">index is less than 0.-or-index is greater than EventList&lt;T&gt;.Count.</exception> /// <exception cref="System.ArgumentNullException">collection is null.</exception> /// <exception cref="System.ApplicationException">Unable to insert while the ReadOnly property is set to true.</exception> public virtual void InsertRange(int index, IEnumerable<T> collection) { int c = index; SuspendEvents(); foreach (T item in collection) { Include(item); InnerList.Insert(c, item); c++; } ResumeEvents(); } /// <summary> /// Removes a range of elements from the EventList&lt;T&gt;. /// </summary> /// <param name="index">The zero-based starting index of the range of elements to remove.</param> /// <param name="count">The number of elements to remove.</param> /// <exception cref="System.ArgumentOutOfRangeException">index is less than 0.-or-count is less than 0.</exception> /// <exception cref="System.ArgumentException">index and count do not denote a valid range of elements in the EventList&lt;T&gt;.</exception> /// <exception cref="System.ApplicationException">Unable to remove while the ReadOnly property is set to true.</exception> public virtual void RemoveRange(int index, int count) { T[] temp = new T[count]; InnerList.CopyTo(index, temp, 0, count); InnerList.RemoveRange(index, count); SuspendEvents(); foreach (T item in temp) { Exclude(item); } ResumeEvents(); } /// <summary> /// Resumes event sending and fires a ListChanged event if any changes have taken place. /// This will not track all the individual changes that may have fired in the meantime. /// </summary> public void ResumeEvents() { _suspension--; if (_suspension == 0) { OnResumeEvents(); if (_hasChanged) { OnListChanged(); } } if (_suspension < 0) _suspension = 0; } /// <summary> /// Reverses the order of the elements in the specified range. /// </summary> /// <param name="index">The zero-based starting index of the range to reverse.</param> /// <param name="count">The number of elements in the range to reverse.</param> /// <exception cref="System.ArgumentException">index and count do not denote a valid range of elements in the EventList&lt;T&gt;.</exception> /// <exception cref="System.ArgumentOutOfRangeException">index is less than 0.-or-count is less than 0.</exception> /// <exception cref="System.ApplicationException">Unable to reverse while the ReadOnly property is set to true.</exception> public virtual void Reverse(int index, int count) { InnerList.Reverse(index, count); OnListChanged(); } /// <summary> /// Reverses the order of the elements in the entire EventList&lt;T&gt;. /// </summary> /// <exception cref="System.ApplicationException">Unable to reverse while the ReadOnly property is set to true.</exception> public virtual void Reverse() { InnerList.Reverse(); OnListChanged(); } /// <summary> /// Temporarilly suspends notice events, allowing a large number of changes. /// </summary> public void SuspendEvents() { if (_suspension == 0) _hasChanged = false; _suspension++; } /// <summary> /// Overrides the normal clear situation so that we only update after all the members are cleared. /// </summary> protected override void OnClear() { SuspendEvents(); base.OnClear(); ResumeEvents(); } /// <summary> /// Occurs during the copy process and overrides the base behavior so that events are suspended. /// </summary> /// <param name="copy">The copy.</param> protected override void OnCopy(CopyList<T> copy) { ChangeEventList<T> myCopy = copy as ChangeEventList<T>; if (myCopy != null) { RemoveHandlers(myCopy); myCopy.SuspendEvents(); } base.OnCopy(copy); myCopy?.ResumeEvents(); } /// <summary> /// Occurs when unwiring events on new items. /// </summary> /// <param name="item">The item that gets excluded.</param> protected override void OnExclude(T item) { item.ItemChanged -= ItemItemChanged; item.RemoveItem -= ItemRemoveItem; OnListChanged(); } /// <summary> /// Occurs when wiring events on a new item. /// </summary> /// <param name="item">The item that gets included.</param> protected override void OnInclude(T item) { item.ItemChanged += ItemItemChanged; item.RemoveItem += ItemRemoveItem; OnListChanged(); } /// <summary> /// An overriding event handler so that we can signfiy the list has changed /// when the inner list has been set to a new list. /// </summary> protected override void OnInnerListSet() { OnItemChanged(this); } /// <summary> /// Occurs when the item is changed. If this list is not suspended, it will forward the change event /// on. Otherwise, it will ensure that when resume events is called that the on change method /// is fired at that time. /// </summary> /// <param name="sender">The sender that raised the event.</param> protected virtual void OnItemChanged(object sender) { if (EventsSuspended) { _hasChanged = true; } else { ItemChanged?.Invoke(sender, EventArgs.Empty); } } /// <summary> /// Fires the ListChanged Event. /// </summary> protected virtual void OnListChanged() { if (!EventsSuspended) { // activate this remarked code to test if the handlers are getting copied somewhere. // int count = ItemChanged.GetInvocationList().Length; // if (count > 1) Debug.WriteLine(this + " has " + count + " item changed handlers."); ItemChanged?.Invoke(this, EventArgs.Empty); } else { _hasChanged = true; } } /// <summary> /// This is either a layer collection or a colorbreak collection, and so /// this won't be called by us, but someone might want to override this for their own reasons. /// </summary> protected virtual void OnRemoveItem() { RemoveItem?.Invoke(this, EventArgs.Empty); } /// <summary> /// Occurs when ResumeEvents has been called enough times so that events are re-enabled. /// </summary> protected virtual void OnResumeEvents() { } private static void RemoveHandlers(ChangeEventList<T> myCopy) { if (myCopy.ItemChanged != null) { foreach (var handler in myCopy.ItemChanged.GetInvocationList()) { myCopy.ItemChanged -= (EventHandler)handler; } } if (myCopy.RemoveItem != null) { foreach (var handler in myCopy.RemoveItem.GetInvocationList()) { myCopy.RemoveItem -= (EventHandler)handler; } } } /// <summary> /// This is a notification that characteristics of one of the members of the list may have changed, /// requiring a refresh, but may not involve a change to the the list itself /// </summary> /// <param name="sender">Sender that raised the event.</param> /// <param name="e">The event args.</param> private void ItemItemChanged(object sender, EventArgs e) { OnItemChanged(sender); } private void ItemRemoveItem(object sender, EventArgs e) { Remove((T)sender); OnListChanged(); } #endregion } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// ParcelAccount /// </summary> [DataContract] public partial class ParcelAccount : IEquatable<ParcelAccount> { /// <summary> /// Initializes a new instance of the <see cref="ParcelAccount" /> class. /// </summary> [JsonConstructorAttribute] protected ParcelAccount() { } /// <summary> /// Initializes a new instance of the <see cref="ParcelAccount" /> class. /// </summary> /// <param name="Carrier">Carrier (required).</param> /// <param name="AccountNo">AccountNo (required).</param> /// <param name="Name">Name (required).</param> /// <param name="ManifestPartnerId">ManifestPartnerId (required).</param> public ParcelAccount(string Carrier = null, string AccountNo = null, string Name = null, string ManifestPartnerId = null) { // to ensure "Carrier" is required (not null) if (Carrier == null) { throw new InvalidDataException("Carrier is a required property for ParcelAccount and cannot be null"); } else { this.Carrier = Carrier; } // to ensure "AccountNo" is required (not null) if (AccountNo == null) { throw new InvalidDataException("AccountNo is a required property for ParcelAccount and cannot be null"); } else { this.AccountNo = AccountNo; } // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for ParcelAccount and cannot be null"); } else { this.Name = Name; } // to ensure "ManifestPartnerId" is required (not null) if (ManifestPartnerId == null) { throw new InvalidDataException("ManifestPartnerId is a required property for ParcelAccount and cannot be null"); } else { this.ManifestPartnerId = ManifestPartnerId; } } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Gets or Sets Carrier /// </summary> [DataMember(Name="carrier", EmitDefaultValue=false)] public string Carrier { get; set; } /// <summary> /// Gets or Sets AccountNo /// </summary> [DataMember(Name="accountNo", EmitDefaultValue=false)] public string AccountNo { get; set; } /// <summary> /// Gets or Sets Client /// </summary> [DataMember(Name="client", EmitDefaultValue=false)] public int? Client { get; private set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets ManifestPartnerId /// </summary> [DataMember(Name="manifestPartnerId", EmitDefaultValue=false)] public string ManifestPartnerId { 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 ParcelAccount {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" Carrier: ").Append(Carrier).Append("\n"); sb.Append(" AccountNo: ").Append(AccountNo).Append("\n"); sb.Append(" Client: ").Append(Client).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" ManifestPartnerId: ").Append(ManifestPartnerId).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 ParcelAccount); } /// <summary> /// Returns true if ParcelAccount instances are equal /// </summary> /// <param name="other">Instance of ParcelAccount to be compared</param> /// <returns>Boolean</returns> public bool Equals(ParcelAccount 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.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.Carrier == other.Carrier || this.Carrier != null && this.Carrier.Equals(other.Carrier) ) && ( this.AccountNo == other.AccountNo || this.AccountNo != null && this.AccountNo.Equals(other.AccountNo) ) && ( this.Client == other.Client || this.Client != null && this.Client.Equals(other.Client) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.ManifestPartnerId == other.ManifestPartnerId || this.ManifestPartnerId != null && this.ManifestPartnerId.Equals(other.ManifestPartnerId) ); } /// <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.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.Carrier != null) hash = hash * 59 + this.Carrier.GetHashCode(); if (this.AccountNo != null) hash = hash * 59 + this.AccountNo.GetHashCode(); if (this.Client != null) hash = hash * 59 + this.Client.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.ManifestPartnerId != null) hash = hash * 59 + this.ManifestPartnerId.GetHashCode(); return hash; } } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; //using ActiveWave.RfidDb; using ActiveWave.Controls; namespace ActiveWave.CarTracker { public class AssetImageView : System.Windows.Forms.UserControl { private ActiveWave.Controls.TitleBar m_titleBar; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label m_lblTagId; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.PictureBox m_picImage; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.ComboBox comboBox2; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; #region Constructor public AssetImageView() { InitializeComponent(); this.Tag = null; //m_rfid.TagChanged += new RfidDb.TagEventHandler(OnTagChanged); //m_rfid.TagRemoved += new RfidDb.TagEventHandler(OnTagRemoved); } #endregion /*#region Properties public new IRfidTag Tag { get { return m_tag; } set { // Always reset tracking for now m_chkTrack.Checked = false; m_chkTrack.Enabled = (value != null); m_tag = value; RefreshTag(); } } #endregion*/ /// <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.m_titleBar = new ActiveWave.Controls.TitleBar(); this.panel1 = new System.Windows.Forms.Panel(); this.comboBox2 = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.m_lblTagId = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.m_picImage = new System.Windows.Forms.PictureBox(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // m_titleBar // this.m_titleBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_titleBar.BackColor = System.Drawing.Color.Navy; this.m_titleBar.BorderColor = System.Drawing.Color.White; this.m_titleBar.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.m_titleBar.ForeColor = System.Drawing.Color.White; this.m_titleBar.GradientColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(0)), ((System.Byte)(192))); this.m_titleBar.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical; this.m_titleBar.Location = new System.Drawing.Point(0, 0); this.m_titleBar.Name = "m_titleBar"; this.m_titleBar.ShadowColor = System.Drawing.Color.Black; this.m_titleBar.ShadowOffset = new System.Drawing.Size(1, 1); this.m_titleBar.Size = new System.Drawing.Size(212, 23); this.m_titleBar.TabIndex = 0; this.m_titleBar.Text = "Plate Nr: "; // // panel1 // this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.comboBox2); this.panel1.Controls.Add(this.label3); this.panel1.Controls.Add(this.label4); this.panel1.Controls.Add(this.m_lblTagId); this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.m_picImage); this.panel1.Location = new System.Drawing.Point(8, 32); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(192, 188); this.panel1.TabIndex = 22; // // comboBox2 // this.comboBox2.Location = new System.Drawing.Point(62, 44); this.comboBox2.Name = "comboBox2"; this.comboBox2.Size = new System.Drawing.Size(124, 21); this.comboBox2.TabIndex = 29; // // label3 // this.label3.AutoSize = true; this.label3.FlatStyle = System.Windows.Forms.FlatStyle.System; this.label3.Location = new System.Drawing.Point(6, 26); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(59, 16); this.label3.TabIndex = 28; this.label3.Text = "Car Brand:"; // // label4 // this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label4.FlatStyle = System.Windows.Forms.FlatStyle.System; this.label4.Location = new System.Drawing.Point(68, 26); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(118, 16); this.label4.TabIndex = 27; // // m_lblTagId // this.m_lblTagId.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_lblTagId.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_lblTagId.Location = new System.Drawing.Point(49, 8); this.m_lblTagId.Name = "m_lblTagId"; this.m_lblTagId.Size = new System.Drawing.Size(137, 16); this.m_lblTagId.TabIndex = 26; // // label2 // this.label2.AutoSize = true; this.label2.FlatStyle = System.Windows.Forms.FlatStyle.System; this.label2.Location = new System.Drawing.Point(6, 46); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(54, 16); this.label2.TabIndex = 25; this.label2.Text = "Owner(s):"; // // label1 // this.label1.AutoSize = true; this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.label1.Location = new System.Drawing.Point(6, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(41, 16); this.label1.TabIndex = 23; this.label1.Text = "Tag ID:"; // // m_picImage // this.m_picImage.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.m_picImage.Location = new System.Drawing.Point(40, 74); this.m_picImage.Name = "m_picImage"; this.m_picImage.Size = new System.Drawing.Size(114, 100); this.m_picImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.m_picImage.TabIndex = 22; this.m_picImage.TabStop = false; // // comboBox1 // this.comboBox1.Location = new System.Drawing.Point(0, 0); this.comboBox1.Name = "comboBox1"; this.comboBox1.TabIndex = 0; // // AssetImageView // this.Controls.Add(this.panel1); this.Controls.Add(this.m_titleBar); this.Name = "AssetImageView"; this.Size = new System.Drawing.Size(212, 234); this.panel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion #region User events private void Track_CheckedChanged(object sender, System.EventArgs e) { /*if (m_tag != null) { if (m_chkTrack.Checked && TagTrackOn != null) TagTrackOn(m_tag); if (!m_chkTrack.Checked && TagTrackOff != null) TagTrackOff(m_tag); }*/ } #endregion /*#region RFID events private void OnTagChanged(IRfidTag tag) { if (m_tag == tag) { RefreshTag(); } } private void OnTagRemoved(IRfidTag tag) { if (m_tag == tag) { this.Tag = null; } } #endregion */ private void RefreshTag() { /*if (m_tag != null) { IRfidReader reader = m_rfid.GetReader(m_tag.ReaderId); m_titleBar.Text = m_tag.Name; m_lblTagId.Text = m_tag.Id; m_lblLocation.Text = (reader != null) ? reader.Name : string.Empty; m_lblTimestamp.Text = (m_tag.Timestamp != DateTime.MinValue) ? m_tag.Timestamp.ToString("MM/dd/yyyy hh:mm:ss tt") : string.Empty; m_picImage.Image = GetScaledImage(m_tag.Image); } else { m_titleBar.Text = string.Empty; m_lblTagId.Text = string.Empty; m_lblLocation.Text = string.Empty; m_lblTimestamp.Text = string.Empty; m_picImage.Image = null; } this.Visible = (m_tag != null);*/ } private Image GetScaledImage(Image image) { if (image != null) { // Get image sized to picture box, but maintain aspect ratio Size size = m_picImage.Size; float ar1 = (float)size.Width / (float)size.Height; float ar2 = (float)image.Width / (float)image.Height; if (ar1 > ar2) size.Width = Convert.ToInt32(size.Height * ar2); else if (ar2 > ar1) size.Height = Convert.ToInt32(size.Width / ar2); return new Bitmap(image, size); } return null; } private void groupBox1_Enter(object sender, System.EventArgs e) { } } }
/* LICENSE ------- Copyright (C) 2007-2010 Ray Molenkamp This source code is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this source code or the software it produces. Permission is granted to anyone to use this source code for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Collections.Generic; using System.Text; using CoreAudioApi.Interfaces; using System.Runtime.InteropServices; namespace CoreAudioApi { public class MMDevice { #region Variables private IMMDevice _RealDevice; private PropertyStore _PropertyStore; private AudioMeterInformation _AudioMeterInformation; private AudioEndpointVolume _AudioEndpointVolume; private AudioSessionManager _AudioSessionManager; private AudioClient _audioClient = null; #endregion #region Guids private static Guid IID_IAudioMeterInformation = typeof(IAudioMeterInformation).GUID; private static Guid IID_IAudioEndpointVolume = typeof(IAudioEndpointVolume).GUID; private static Guid IID_IAudioSessionManager = typeof(IAudioSessionManager2).GUID; private static Guid IID_IAudioClient = typeof(IAudioClient).GUID; #endregion #region Init private void GetPropertyInformation() { IPropertyStore propstore; Marshal.ThrowExceptionForHR(_RealDevice.OpenPropertyStore(EStgmAccess.STGM_READ, out propstore)); _PropertyStore = new PropertyStore(propstore); } private void GetAudioSessionManager() { object result; Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioSessionManager, CLSCTX.ALL, IntPtr.Zero, out result)); _AudioSessionManager = new AudioSessionManager(result as IAudioSessionManager2); } private AudioClient GetAudioClient() { object result; Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioClient, CLSCTX.ALL, IntPtr.Zero, out result)); return new AudioClient(result as IAudioClient); } private void GetAudioMeterInformation() { object result; Marshal.ThrowExceptionForHR( _RealDevice.Activate(ref IID_IAudioMeterInformation, CLSCTX.ALL, IntPtr.Zero, out result)); _AudioMeterInformation = new AudioMeterInformation( result as IAudioMeterInformation); } private void GetAudioEndpointVolume() { object result; Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioEndpointVolume, CLSCTX.ALL, IntPtr.Zero, out result)); _AudioEndpointVolume = new AudioEndpointVolume(result as IAudioEndpointVolume); } #endregion #region Properties public AudioSessionManager AudioSessionManager { get { if (_AudioSessionManager == null) GetAudioSessionManager(); return _AudioSessionManager; } } public AudioMeterInformation AudioMeterInformation { get { if (_AudioMeterInformation == null) GetAudioMeterInformation(); return _AudioMeterInformation; } } public AudioEndpointVolume AudioEndpointVolume { get { if (_AudioEndpointVolume == null) GetAudioEndpointVolume(); return _AudioEndpointVolume; } } public PropertyStore Properties { get { if (_PropertyStore == null) GetPropertyInformation(); return _PropertyStore; } } public string FriendlyName { get { if (_PropertyStore == null) GetPropertyInformation(); if (_PropertyStore.Contains(PKEY.PKEY_DeviceInterface_FriendlyName)) { return (string)_PropertyStore[PKEY.PKEY_DeviceInterface_FriendlyName].Value; } else return "Unknown"; } } public AudioClient AudioClient { get { if (_audioClient == null) _audioClient = GetAudioClient(); return _audioClient; } } public DevicePeriod DevicePeriod { get { if (_audioClient == null) _audioClient = GetAudioClient(); return _audioClient.GetDevicePeriod(); } } public string ID { get { string Result; Marshal.ThrowExceptionForHR(_RealDevice.GetId(out Result)); return Result; } } public EDataFlow DataFlow { get { EDataFlow Result; IMMEndpoint ep = _RealDevice as IMMEndpoint ; ep.GetDataFlow(out Result); return Result; } } public EDeviceState State { get { EDeviceState Result; Marshal.ThrowExceptionForHR(_RealDevice.GetState(out Result)); return Result; } } #endregion #region Constructor internal MMDevice(IMMDevice realDevice) { _RealDevice = realDevice; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Security; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Linq; namespace System.IO.IsolatedStorage { public sealed class IsolatedStorageFile : IDisposable { private string _appFilesPath; private bool _disposed; private bool _closed; private readonly object _internalLock = new object(); private static string s_RootFromHost; private static string s_IsolatedStorageRoot; /* * Constructors */ internal IsolatedStorageFile() { } internal bool Disposed { get { return _disposed; } } internal static string IsolatedStorageRoot { get { if (s_IsolatedStorageRoot == null) { // No need to lock here, FetchOrCreateRoot is idempotent. s_IsolatedStorageRoot = FetchOrCreateRoot(); } return s_IsolatedStorageRoot; } private set { s_IsolatedStorageRoot = value; } } internal bool IsDeleted { get { try { return !Directory.Exists(IsolatedStorageRoot); } catch (IOException) { // It's better to assume the IsoStore is gone if we can't prove it is there. return true; } catch (UnauthorizedAccessException) { // It's better to assume the IsoStore is gone if we can't prove it is there. return true; } } } internal void Close() { lock (_internalLock) { if (!_closed) { _closed = true; GC.SuppressFinalize(this); } } } public void DeleteFile(String file) { if (file == null) throw new ArgumentNullException("file"); Contract.EndContractBlock(); EnsureStoreIsValid(); try { String fullPath = GetFullPath(file); File.Delete(fullPath); } catch (Exception e) { throw GetIsolatedStorageException(SR.IsolatedStorage_DeleteFile, e); } } public bool FileExists(string path) { if (path == null) { throw new ArgumentNullException("path"); } EnsureStoreIsValid(); return File.Exists(GetFullPath(path)); } public bool DirectoryExists(string path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); EnsureStoreIsValid(); return Directory.Exists(GetFullPath(path)); } public void CreateDirectory(String dir) { if (dir == null) throw new ArgumentNullException("dir"); Contract.EndContractBlock(); EnsureStoreIsValid(); String isPath = GetFullPath(dir); // Prepend IS root // We can save a bunch of work if the directory we want to create already exists. This also // saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the // final path is accessable and the directory already exists. For example, consider trying // to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo // and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar // and fail to due so, causing an exception to be thrown. This is not what we want. if (Directory.Exists(isPath)) { return; } try { Directory.CreateDirectory(isPath); } catch (Exception e) { // We have a slightly different behavior here in comparison to the traditional IsolatedStorage // which tries to remove any partial directories created in case of failure. // However providing that behavior required we could not reply on FileSystem APIs in general // and had to keep tabs on what all directories needed to be created and at what point we failed // and back-track from there. It is unclear how many apps would depend on this behavior and if required // we could add the behavior as a bug-fix later. throw GetIsolatedStorageException(SR.IsolatedStorage_CreateDirectory, e); } } public void DeleteDirectory(String dir) { if (dir == null) throw new ArgumentNullException("dir"); Contract.EndContractBlock(); EnsureStoreIsValid(); try { string fullPath = GetFullPath(dir); Directory.Delete(fullPath, false); } catch (Exception e) { throw GetIsolatedStorageException(SR.IsolatedStorage_DeleteDirectory, e); } } public String[] GetFileNames() { return GetFileNames("*"); } /* * foo\abc*.txt will give all abc*.txt files in foo directory */ public String[] GetFileNames(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); EnsureStoreIsValid(); try { // FileSystem APIs return the complete path of the matching files however Iso store only provided the FileName // and hid the IsoStore root. Hence we find all the matching files from the fileSystem and simply return the fileNames. return Directory.EnumerateFiles(_appFilesPath, searchPattern).Select(f => Path.GetFileName(f)).ToArray(); } catch (UnauthorizedAccessException e) { throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e); } } public String[] GetDirectoryNames() { return GetDirectoryNames("*"); } /* * foo\data* will give all directory names in foo directory that * starts with data */ public String[] GetDirectoryNames(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); EnsureStoreIsValid(); try { // FileSystem APIs return the complete path of the matching directories however Iso store only provided the directory name // and hid the IsoStore root. Hence we find all the matching directories from the fileSystem and simply return their names. return Directory.EnumerateDirectories(_appFilesPath, searchPattern).Select(m => m.Substring(Path.GetDirectoryName(m).Length + 1)).ToArray(); } catch (UnauthorizedAccessException e) { throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e); } } public IsolatedStorageFileStream OpenFile(string path, FileMode mode) { EnsureStoreIsValid(); return new IsolatedStorageFileStream(path, mode, this); } public IsolatedStorageFileStream OpenFile(string path, FileMode mode, FileAccess access) { EnsureStoreIsValid(); return new IsolatedStorageFileStream(path, mode, access, this); } public IsolatedStorageFileStream OpenFile(string path, FileMode mode, FileAccess access, FileShare share) { EnsureStoreIsValid(); return new IsolatedStorageFileStream(path, mode, access, share, this); } public IsolatedStorageFileStream CreateFile(string path) { EnsureStoreIsValid(); return new IsolatedStorageFileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, this); } public DateTimeOffset GetCreationTime(string path) { if (path == null) throw new ArgumentNullException("path"); if (path == String.Empty) { throw new ArgumentException(SR.Argument_EmptyPath, "path"); } Contract.EndContractBlock(); EnsureStoreIsValid(); try { return new DateTimeOffset(File.GetCreationTime(GetFullPath(path))); } catch (UnauthorizedAccessException) { return new DateTimeOffset(1601, 1, 1, 0, 0, 0, TimeSpan.Zero).ToLocalTime(); } } public DateTimeOffset GetLastAccessTime(string path) { if (path == null) throw new ArgumentNullException("path"); if (path == String.Empty) { throw new ArgumentException(SR.Argument_EmptyPath, "path"); } Contract.EndContractBlock(); EnsureStoreIsValid(); try { return new DateTimeOffset(File.GetLastAccessTime(GetFullPath(path))); } catch (UnauthorizedAccessException) { return new DateTimeOffset(1601, 1, 1, 0, 0, 0, TimeSpan.Zero).ToLocalTime(); } } public DateTimeOffset GetLastWriteTime(string path) { if (path == null) throw new ArgumentNullException("path"); if (path == String.Empty) { throw new ArgumentException(SR.Argument_EmptyPath, "path"); } Contract.EndContractBlock(); EnsureStoreIsValid(); try { return new DateTimeOffset(File.GetLastWriteTime(GetFullPath(path))); } catch (UnauthorizedAccessException) { return new DateTimeOffset(1601, 1, 1, 0, 0, 0, TimeSpan.Zero).ToLocalTime(); } } public void CopyFile(string sourceFileName, string destinationFileName) { if (sourceFileName == null) throw new ArgumentNullException("sourceFileName"); if (destinationFileName == null) throw new ArgumentNullException("destinationFileName"); if (sourceFileName == String.Empty) { throw new ArgumentException(SR.Argument_EmptyPath, "sourceFileName"); } if (destinationFileName == String.Empty) { throw new ArgumentException(SR.Argument_EmptyPath, "destinationFileName"); } Contract.EndContractBlock(); CopyFile(sourceFileName, destinationFileName, false); } public void CopyFile(string sourceFileName, string destinationFileName, bool overwrite) { if (sourceFileName == null) throw new ArgumentNullException("sourceFileName"); if (destinationFileName == null) throw new ArgumentNullException("destinationFileName"); if (sourceFileName == String.Empty) { throw new ArgumentException(SR.Argument_EmptyPath, "sourceFileName"); } if (destinationFileName == String.Empty) { throw new ArgumentException(SR.Argument_EmptyPath, "destinationFileName"); } Contract.EndContractBlock(); EnsureStoreIsValid(); String sourceFileNameFullPath = GetFullPath(sourceFileName); String destinationFileNameFullPath = GetFullPath(destinationFileName); try { File.Copy(sourceFileNameFullPath, destinationFileNameFullPath, overwrite); } catch (FileNotFoundException) { throw new FileNotFoundException(String.Format(SR.PathNotFound_Path, sourceFileName)); } catch (PathTooLongException) { throw; } catch (Exception e) { throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e); } } public void MoveFile(string sourceFileName, string destinationFileName) { if (sourceFileName == null) throw new ArgumentNullException("sourceFileName"); if (destinationFileName == null) throw new ArgumentNullException("destinationFileName"); if (sourceFileName == String.Empty) { throw new ArgumentException(SR.Argument_EmptyPath, "sourceFileName"); } if (destinationFileName == String.Empty) { throw new ArgumentException(SR.Argument_EmptyPath, "destinationFileName"); } Contract.EndContractBlock(); EnsureStoreIsValid(); String sourceFileNameFullPath = GetFullPath(sourceFileName); String destinationFileNameFullPath = GetFullPath(destinationFileName); try { File.Move(sourceFileNameFullPath, destinationFileNameFullPath); } catch (FileNotFoundException) { throw new FileNotFoundException(String.Format(SR.PathNotFound_Path, sourceFileName)); } catch (PathTooLongException) { throw; } catch (Exception e) { throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e); } } public void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName) { if (sourceDirectoryName == null) throw new ArgumentNullException("sourceDirectoryName"); if (destinationDirectoryName == null) throw new ArgumentNullException("destinationDirectoryName"); if (sourceDirectoryName == String.Empty) { throw new ArgumentException(SR.Argument_EmptyPath, "sourceDirectoryName"); } if (destinationDirectoryName == String.Empty) { throw new ArgumentException(SR.Argument_EmptyPath, "destinationDirectoryName"); } Contract.EndContractBlock(); EnsureStoreIsValid(); String sourceDirectoryNameFullPath = GetFullPath(sourceDirectoryName); String destinationDirectoryNameFullPath = GetFullPath(destinationDirectoryName); try { Directory.Move(sourceDirectoryNameFullPath, destinationDirectoryNameFullPath); } catch (DirectoryNotFoundException) { throw new DirectoryNotFoundException(String.Format(SR.PathNotFound_Path, sourceDirectoryName)); } catch (PathTooLongException) { throw; } catch (Exception e) { throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e); } } /* * Public Static Methods */ public static IsolatedStorageFile GetUserStoreForApplication() { return GetUserStore(); } internal static IsolatedStorageFile GetUserStore() { IsolatedStorageRoot = FetchOrCreateRoot(); IsolatedStorageFile isf = new IsolatedStorageFile(); isf._appFilesPath = IsolatedStorageRoot; return isf; } /* * Private Instance Methods */ internal string GetFullPath(string partialPath) { Debug.Assert(partialPath != null, "partialPath should be non null"); int i; // Chop off directory separator characters at the start of the string because they counfuse Path.Combine. for (i = 0; i < partialPath.Length; i++) { if (partialPath[i] != Path.DirectorySeparatorChar && partialPath[i] != Path.AltDirectorySeparatorChar) { break; } } partialPath = partialPath.Substring(i); return Path.Combine(_appFilesPath, partialPath); } /* * Private Static Methods */ private static void CreatePathPrefixIfNeeded(string path) { string root = Path.GetPathRoot(path); Debug.Assert(!String.IsNullOrEmpty(root), "Path.GetPathRoot returned null or empty for: " + path); try { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } catch (IOException e) { throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e); } catch (UnauthorizedAccessException e) { throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e); } } internal static string FetchOrCreateRoot() { string rootFromHost = s_RootFromHost; if (s_RootFromHost == null) { string root = IsolatedStorageSecurityState.GetRootUserDirectory(); s_RootFromHost = root; } CreatePathPrefixIfNeeded(s_RootFromHost); return s_RootFromHost; } internal void EnsureStoreIsValid() { if (Disposed) throw new ObjectDisposedException(null, SR.IsolatedStorage_StoreNotOpen); Contract.EndContractBlock(); if (IsDeleted) { throw new IsolatedStorageException(SR.IsolatedStorage_StoreNotOpen); } if (_closed) throw new InvalidOperationException(SR.IsolatedStorage_StoreNotOpen); } public void Dispose() { Close(); _disposed = true; } [SecurityCritical] internal static Exception GetIsolatedStorageException(string exceptionMsg, Exception rootCause) { IsolatedStorageException e = new IsolatedStorageException(exceptionMsg, rootCause); e._underlyingException = rootCause; return e; } } }
using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core; namespace Umbraco.Core.Publishing { /// <summary> /// Currently acts as an interconnection between the new public api and the legacy api for publishing /// </summary> public class PublishingStrategy : BasePublishingStrategy { /// <summary> /// Publishes a single piece of Content /// </summary> /// <param name="content"><see cref="IContent"/> to publish</param> /// <param name="userId">Id of the User issueing the publish operation</param> internal Attempt<PublishStatus> PublishInternal(IContent content, int userId) { if (Publishing.IsRaisedEventCancelled(new PublishEventArgs<IContent>(content), this)) { LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' will not be published, the event was cancelled.", content.Name, content.Id)); return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedCancelledByEvent)); } //Check if the Content is Expired to verify that it can in fact be published if (content.Status == ContentStatus.Expired) { LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' has expired and could not be published.", content.Name, content.Id)); return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedHasExpired)); } //Check if the Content is Awaiting Release to verify that it can in fact be published if (content.Status == ContentStatus.AwaitingRelease) { LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' is awaiting release and could not be published.", content.Name, content.Id)); return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedAwaitingRelease)); } //Check if the Content is Trashed to verify that it can in fact be published if (content.Status == ContentStatus.Trashed) { LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' is trashed and could not be published.", content.Name, content.Id)); return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedIsTrashed)); } content.ChangePublishedState(PublishedState.Published); LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' has been published.", content.Name, content.Id)); return Attempt.Succeed(new PublishStatus(content)); } /// <summary> /// Publishes a single piece of Content /// </summary> /// <param name="content"><see cref="IContent"/> to publish</param> /// <param name="userId">Id of the User issueing the publish operation</param> /// <returns>True if the publish operation was successfull and not cancelled, otherwise false</returns> public override bool Publish(IContent content, int userId) { return PublishInternal(content, userId).Success; } /// <summary> /// Publishes a list of content items /// </summary> /// <param name="content"></param> /// <param name="userId"></param> /// <param name="includeUnpublishedDocuments"> /// By default this is set to true which means that it will publish any content item in the list that is completely unpublished and /// not visible on the front-end. If set to false, this will only publish content that is live on the front-end but has new versions /// that have yet to be published. /// </param> /// <returns></returns> /// <remarks> /// /// This method becomes complex once we start to be able to cancel events or stop publishing a content item in any way because if a /// content item is not published then it's children shouldn't be published either. This rule will apply for the following conditions: /// * If a document fails to be published, do not proceed to publish it's children if: /// ** The document does not have a publish version /// ** The document does have a published version but the includeUnpublishedDocuments = false /// /// In order to do this, we will order the content by level and begin by publishing each item at that level, then proceed to the next /// level and so on. If we detect that the above rule applies when the document publishing is cancelled we'll add it to the list of /// parentsIdsCancelled so that it's children don't get published. /// /// Its important to note that all 'root' documents included in the list *will* be published regardless of the rules mentioned /// above (unless it is invalid)!! By 'root' documents we are referring to documents in the list with the minimum value for their 'level'. /// In most cases the 'root' documents will only be one document since under normal circumstance we only publish one document and /// its children. The reason we have to do this is because if a user is publishing a document and it's children, it is implied that /// the user definitely wants to publish it even if it has never been published before. /// /// </remarks> internal IEnumerable<Attempt<PublishStatus>> PublishWithChildrenInternal( IEnumerable<IContent> content, int userId, bool includeUnpublishedDocuments = true) { var statuses = new List<Attempt<PublishStatus>>(); //a list of all document ids that had their publishing cancelled during these iterations. //this helps us apply the rule listed in the notes above by checking if a document's parent id //matches one in this list. var parentsIdsCancelled = new List<int>(); //group by levels and iterate over the sorted ascending level. //TODO: This will cause all queries to execute, they will not be lazy but I'm not really sure being lazy actually made // much difference because we iterate over them all anyways?? Morten? // Because we're grouping I think this will execute all the queries anyways so need to fetch it all first. var fetchedContent = content.ToArray(); //We're going to populate the statuses with all content that is already published because below we are only going to iterate over // content that is not published. We'll set the status to "AlreadyPublished" statuses.AddRange(fetchedContent.Where(x => x.Published) .Select(x => Attempt.Succeed(new PublishStatus(x, PublishStatusType.SuccessAlreadyPublished)))); int? firstLevel = null; //group by level and iterate over each level (sorted ascending) var levelGroups = fetchedContent.GroupBy(x => x.Level); foreach (var level in levelGroups.OrderBy(x => x.Key)) { //set the first level flag, used to ensure that all documents at the first level will //be published regardless of the rules mentioned in the remarks. if (!firstLevel.HasValue) { firstLevel = level.Key; } /* Only update content thats not already been published - we want to loop through * all unpublished content to write skipped content (expired and awaiting release) to log. */ foreach (var item in level.Where(x => x.Published == false)) { //Check if this item should be excluded because it's parent's publishing has failed/cancelled if (parentsIdsCancelled.Contains(item.ParentId)) { LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' will not be published because it's parent's publishing action failed or was cancelled.", item.Name, item.Id)); //if this cannot be published, ensure that it's children can definitely not either! parentsIdsCancelled.Add(item.Id); continue; } //Check if this item has never been published (and that it is not at the root level) if (item.Level != firstLevel && !includeUnpublishedDocuments && !item.HasPublishedVersion()) { //this item does not have a published version and the flag is set to not include them parentsIdsCancelled.Add(item.Id); continue; } //Fire Publishing event if (Publishing.IsRaisedEventCancelled(new PublishEventArgs<IContent>(item), this)) { //the publishing has been cancelled. LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' will not be published, the event was cancelled.", item.Name, item.Id)); statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedCancelledByEvent))); //Does this document apply to our rule to cancel it's children being published? CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments); continue; } //Check if the content is valid if the flag is set to check if (!item.IsValid()) { LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' will not be published because some of it's content is not passing validation rules.", item.Name, item.Id)); statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedContentInvalid))); //Does this document apply to our rule to cancel it's children being published? CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments); continue; } //Check if the Content is Expired to verify that it can in fact be published if (item.Status == ContentStatus.Expired) { LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' has expired and could not be published.", item.Name, item.Id)); statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedHasExpired))); //Does this document apply to our rule to cancel it's children being published? CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments); continue; } //Check if the Content is Awaiting Release to verify that it can in fact be published if (item.Status == ContentStatus.AwaitingRelease) { LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' is awaiting release and could not be published.", item.Name, item.Id)); statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedAwaitingRelease))); //Does this document apply to our rule to cancel it's children being published? CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments); continue; } //Check if the Content is Trashed to verify that it can in fact be published if (item.Status == ContentStatus.Trashed) { LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' is trashed and could not be published.", item.Name, item.Id)); statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedIsTrashed))); //Does this document apply to our rule to cancel it's children being published? CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments); continue; } item.ChangePublishedState(PublishedState.Published); LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' has been published.", item.Name, item.Id)); statuses.Add(Attempt.Succeed(new PublishStatus(item))); } } return statuses; } /// <summary> /// Based on the information provider we'll check if we should cancel the publishing of this document's children /// </summary> /// <param name="content"></param> /// <param name="parentsIdsCancelled"></param> /// <param name="includeUnpublishedDocuments"></param> /// <remarks> /// See remarks on method: PublishWithChildrenInternal /// </remarks> private void CheckCancellingOfChildPublishing(IContent content, List<int> parentsIdsCancelled, bool includeUnpublishedDocuments) { //Does this document apply to our rule to cancel it's children being published? //TODO: We're going back to the service layer here... not sure how to avoid this? And this will add extra overhead to // any document that fails to publish... var hasPublishedVersion = ApplicationContext.Current.Services.ContentService.HasPublishedVersion(content.Id); if (hasPublishedVersion && !includeUnpublishedDocuments) { //it has a published version but our flag tells us to not include un-published documents and therefore we should // not be forcing decendant/child documents to be published if their parent fails. parentsIdsCancelled.Add(content.Id); } else if (!hasPublishedVersion) { //it doesn't have a published version so we certainly cannot publish it's children. parentsIdsCancelled.Add(content.Id); } } /// <summary> /// Publishes a list of Content /// </summary> /// <param name="content">An enumerable list of <see cref="IContent"/></param> /// <param name="userId">Id of the User issueing the publish operation</param> /// <returns>True if the publish operation was successfull and not cancelled, otherwise false</returns> public override bool PublishWithChildren(IEnumerable<IContent> content, int userId) { var result = PublishWithChildrenInternal(content, userId); //NOTE: This previously always returned true so I've left it that way. It returned true because (from Morten)... // ... if one item couldn't be published it wouldn't be correct to return false. // in retrospect it should have returned a list of with Ids and Publish Status // come to think of it ... the cache would still be updated for a failed item or at least tried updated. // It would call the Published event for the entire list, but if the Published property isn't set to True it // wouldn't actually update the cache for that item. But not really ideal nevertheless... return true; } /// <summary> /// Unpublishes a single piece of Content /// </summary> /// <param name="content"><see cref="IContent"/> to unpublish</param> /// <param name="userId">Id of the User issueing the unpublish operation</param> /// <returns>True if the unpublish operation was successfull and not cancelled, otherwise false</returns> public override bool UnPublish(IContent content, int userId) { if (UnPublishing.IsRaisedEventCancelled(new PublishEventArgs<IContent>(content), this)) { LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' will not be un-published, the event was cancelled.", content.Name, content.Id)); return false; } //If Content has a release date set to before now, it should be removed so it doesn't interrupt an unpublish //Otherwise it would remain released == published if (content.ReleaseDate.HasValue && content.ReleaseDate.Value <= DateTime.Now) { content.ReleaseDate = null; LogHelper.Info<PublishingStrategy>( string.Format( "Content '{0}' with Id '{1}' had its release date removed, because it was unpublished.", content.Name, content.Id)); } content.ChangePublishedState(PublishedState.Unpublished); LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' has been unpublished.", content.Name, content.Id)); return true; } /// <summary> /// Unpublishes a list of Content /// </summary> /// <param name="content">An enumerable list of <see cref="IContent"/></param> /// <param name="userId">Id of the User issueing the unpublish operation</param> /// <returns>A list of publish statuses</returns> internal IEnumerable<Attempt<PublishStatus>> UnPublishInternal(IEnumerable<IContent> content, int userId) { var result = new List<Attempt<PublishStatus>>(); //Only update content thats already been published foreach (var item in content.Where(x => x.Published == true)) { //Fire UnPublishing event if (UnPublishing.IsRaisedEventCancelled(new PublishEventArgs<IContent>(item), this)) { LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' will not be published, the event was cancelled.", item.Name, item.Id)); result.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedCancelledByEvent))); continue; } //If Content has a release date set to before now, it should be removed so it doesn't interrupt an unpublish //Otherwise it would remain released == published if (item.ReleaseDate.HasValue && item.ReleaseDate.Value <= DateTime.Now) { item.ReleaseDate = null; LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' had its release date removed, because it was unpublished.", item.Name, item.Id)); } item.ChangePublishedState(PublishedState.Unpublished); LogHelper.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' has been unpublished.", item.Name, item.Id)); result.Add(Attempt.Succeed(new PublishStatus(item))); } return result; } /// <summary> /// Unpublishes a list of Content /// </summary> /// <param name="content">An enumerable list of <see cref="IContent"/></param> /// <param name="userId">Id of the User issueing the unpublish operation</param> /// <returns>True if the unpublish operation was successfull and not cancelled, otherwise false</returns> public override bool UnPublish(IEnumerable<IContent> content, int userId) { var result = UnPublishInternal(content, userId); //NOTE: This previously always returned true so I've left it that way. It returned true because (from Morten)... // ... if one item couldn't be published it wouldn't be correct to return false. // in retrospect it should have returned a list of with Ids and Publish Status // come to think of it ... the cache would still be updated for a failed item or at least tried updated. // It would call the Published event for the entire list, but if the Published property isn't set to True it // wouldn't actually update the cache for that item. But not really ideal nevertheless... return true; } /// <summary> /// Call to fire event that updating the published content has finalized. /// </summary> /// <remarks> /// This seperation of the OnPublished event is done to ensure that the Content /// has been properly updated (committed unit of work) and xml saved in the db. /// </remarks> /// <param name="content"><see cref="IContent"/> thats being published</param> public override void PublishingFinalized(IContent content) { Published.RaiseEvent(new PublishEventArgs<IContent>(content, false, false), this); } /// <summary> /// Call to fire event that updating the published content has finalized. /// </summary> /// <param name="content">An enumerable list of <see cref="IContent"/> thats being published</param> /// <param name="isAllRepublished">Boolean indicating whether its all content that is republished</param> public override void PublishingFinalized(IEnumerable<IContent> content, bool isAllRepublished) { Published.RaiseEvent(new PublishEventArgs<IContent>(content, false, isAllRepublished), this); } /// <summary> /// Call to fire event that updating the unpublished content has finalized. /// </summary> /// <param name="content"><see cref="IContent"/> thats being unpublished</param> public override void UnPublishingFinalized(IContent content) { UnPublished.RaiseEvent(new PublishEventArgs<IContent>(content, false, false), this); } /// <summary> /// Call to fire event that updating the unpublished content has finalized. /// </summary> /// <param name="content">An enumerable list of <see cref="IContent"/> thats being unpublished</param> public override void UnPublishingFinalized(IEnumerable<IContent> content) { UnPublished.RaiseEvent(new PublishEventArgs<IContent>(content, false, false), this); } /// <summary> /// Occurs before publish /// </summary> public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> Publishing; /// <summary> /// Occurs after publish /// </summary> public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> Published; /// <summary> /// Occurs before unpublish /// </summary> public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> UnPublishing; /// <summary> /// Occurs after unpublish /// </summary> public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> UnPublished; } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.DataFactories; using Microsoft.Azure.Management.DataFactories.Models; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.DataFactories { /// <summary> /// Operations for managing data slices. /// </summary> internal partial class DataSliceOperations : IServiceOperations<DataPipelineManagementClient>, IDataSliceOperations { /// <summary> /// Initializes a new instance of the DataSliceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DataSliceOperations(DataPipelineManagementClient client) { this._client = client; } private DataPipelineManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.DataFactories.DataPipelineManagementClient. /// </summary> public DataPipelineManagementClient Client { get { return this._client; } } /// <summary> /// Gets the first page of data slice instances with the link to the /// next page. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='tableName'> /// Required. A unique table instance name. /// </param> /// <param name='dataSliceRangeStartTime'> /// Required. The data slice range start time in round-trip ISO 8601 /// format. /// </param> /// <param name='dataSliceRangeEndTime'> /// Required. The data slice range end time in round-trip ISO 8601 /// format. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data slices operation response. /// </returns> public async Task<DataSliceListResponse> ListAsync(string resourceGroupName, string dataFactoryName, string tableName, string dataSliceRangeStartTime, string dataSliceRangeEndTime, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (tableName == null) { throw new ArgumentNullException("tableName"); } if (dataSliceRangeStartTime == null) { throw new ArgumentNullException("dataSliceRangeStartTime"); } if (dataSliceRangeEndTime == null) { throw new ArgumentNullException("dataSliceRangeEndTime"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("tableName", tableName); tracingParameters.Add("dataSliceRangeStartTime", dataSliceRangeStartTime); tracingParameters.Add("dataSliceRangeEndTime", dataSliceRangeEndTime); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/providers/Microsoft.DataFactory/datafactories/" + dataFactoryName.Trim() + "/tables/" + tableName.Trim() + "/slices?"; url = url + "start=" + Uri.EscapeDataString(dataSliceRangeStartTime.Trim()); url = url + "&end=" + Uri.EscapeDataString(dataSliceRangeEndTime.Trim()); url = url + "&api-version=2014-12-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result DataSliceListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataSliceListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DataSlice dataSliceInstance = new DataSlice(); result.DataSlices.Add(dataSliceInstance); JToken startValue = valueValue["start"]; if (startValue != null && startValue.Type != JTokenType.Null) { DateTime startInstance = ((DateTime)startValue); dataSliceInstance.Start = startInstance; } JToken endValue = valueValue["end"]; if (endValue != null && endValue.Type != JTokenType.Null) { DateTime endInstance = ((DateTime)endValue); dataSliceInstance.End = endInstance; } JToken statusValue = valueValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); dataSliceInstance.Status = statusInstance; } JToken latencyStatusValue = valueValue["latencyStatus"]; if (latencyStatusValue != null && latencyStatusValue.Type != JTokenType.Null) { string latencyStatusInstance = ((string)latencyStatusValue); dataSliceInstance.LatencyStatus = latencyStatusInstance; } JToken retryCountValue = valueValue["retryCount"]; if (retryCountValue != null && retryCountValue.Type != JTokenType.Null) { int retryCountInstance = ((int)retryCountValue); dataSliceInstance.RetryCount = retryCountInstance; } JToken longRetryCountValue = valueValue["longRetryCount"]; if (longRetryCountValue != null && longRetryCountValue.Type != JTokenType.Null) { int longRetryCountInstance = ((int)longRetryCountValue); dataSliceInstance.LongRetryCount = longRetryCountInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the next page of data slice instances with the link to the /// next page. /// </summary> /// <param name='nextLink'> /// Required. The url to the next data slices page. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data slices operation response. /// </returns> public async Task<DataSliceListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); Tracing.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = nextLink.Trim(); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result DataSliceListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataSliceListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DataSlice dataSliceInstance = new DataSlice(); result.DataSlices.Add(dataSliceInstance); JToken startValue = valueValue["start"]; if (startValue != null && startValue.Type != JTokenType.Null) { DateTime startInstance = ((DateTime)startValue); dataSliceInstance.Start = startInstance; } JToken endValue = valueValue["end"]; if (endValue != null && endValue.Type != JTokenType.Null) { DateTime endInstance = ((DateTime)endValue); dataSliceInstance.End = endInstance; } JToken statusValue = valueValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); dataSliceInstance.Status = statusInstance; } JToken latencyStatusValue = valueValue["latencyStatus"]; if (latencyStatusValue != null && latencyStatusValue.Type != JTokenType.Null) { string latencyStatusInstance = ((string)latencyStatusValue); dataSliceInstance.LatencyStatus = latencyStatusInstance; } JToken retryCountValue = valueValue["retryCount"]; if (retryCountValue != null && retryCountValue.Type != JTokenType.Null) { int retryCountInstance = ((int)retryCountValue); dataSliceInstance.RetryCount = retryCountInstance; } JToken longRetryCountValue = valueValue["longRetryCount"]; if (longRetryCountValue != null && longRetryCountValue.Type != JTokenType.Null) { int longRetryCountInstance = ((int)longRetryCountValue); dataSliceInstance.LongRetryCount = longRetryCountInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Sets status of data slices over a time range for a specific table. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='tableName'> /// Required. A unique table instance name. /// </param> /// <param name='parameters'> /// Required. The parameters required to set status of data slices. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<OperationResponse> SetStatusAsync(string resourceGroupName, string dataFactoryName, string tableName, DataSliceSetStatusParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (tableName == null) { throw new ArgumentNullException("tableName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("tableName", tableName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "SetStatusAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/providers/Microsoft.DataFactory/datafactories/" + dataFactoryName.Trim() + "/tables/" + tableName.Trim() + "/slices/setstatus?"; if (parameters.DataSliceRangeStartTime != null) { url = url + "start=" + Uri.EscapeDataString(parameters.DataSliceRangeStartTime != null ? parameters.DataSliceRangeStartTime.Trim() : ""); } if (parameters.DataSliceRangeEndTime != null) { url = url + "&end=" + Uri.EscapeDataString(parameters.DataSliceRangeEndTime != null ? parameters.DataSliceRangeEndTime.Trim() : ""); } url = url + "&api-version=2014-12-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject dataSliceSetStatusParametersValue = new JObject(); requestDoc = dataSliceSetStatusParametersValue; if (parameters.SliceStatus != null) { dataSliceSetStatusParametersValue["SliceStatus"] = parameters.SliceStatus; } if (parameters.UpdateType != null) { dataSliceSetStatusParametersValue["UpdateType"] = parameters.UpdateType; } requestContent = requestDoc.ToString(Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using UnityEngine.Serialization; using System; using System.Collections; using Leap.Unity.Attributes; namespace Leap.Unity { // To use the LeapImageRetriever you must be on version 2.1+ // and enable "Allow Images" in the Leap Motion settings. /** LeapImageRetriever acquires images from a LeapServiceProvider and uploads them to gpu for use by shaders */ [RequireComponent(typeof(Camera))] public class LeapImageRetriever : MonoBehaviour { public const string GLOBAL_COLOR_SPACE_GAMMA_NAME = "_LeapGlobalColorSpaceGamma"; public const string GLOBAL_GAMMA_CORRECTION_EXPONENT_NAME = "_LeapGlobalGammaCorrectionExponent"; public const string GLOBAL_CAMERA_PROJECTION_NAME = "_LeapGlobalProjection"; public const int IMAGE_WARNING_WAIT = 10; public const int LEFT_IMAGE_INDEX = 0; public const int RIGHT_IMAGE_INDEX = 1; public const float IMAGE_SETTING_POLL_RATE = 2.0f; [SerializeField] LeapServiceProvider _provider; [SerializeField] [FormerlySerializedAs("gammaCorrection")] private float _gammaCorrection = 1.0f; [MinValue(0)] [SerializeField] protected long ImageTimeout = 9000; //microseconds private EyeTextureData _eyeTextureData = new EyeTextureData(); //Image that we have requested from the service. Are requested in Update and retrieved in OnPreRender protected Image _requestedImage = new Image(); protected bool imagesEnabled = true; private bool checkingImageState = false; public EyeTextureData TextureData { get { return _eyeTextureData; } } public class LeapTextureData { private Texture2D _combinedTexture = null; private byte[] _intermediateArray = null; public Texture2D CombinedTexture { get { return _combinedTexture; } } public bool CheckStale(Image image) { if (_combinedTexture == null || _intermediateArray == null) { return true; } if (image.Width != _combinedTexture.width || image.Height * 2 != _combinedTexture.height) { return true; } if (_combinedTexture.format != getTextureFormat(image)) { return true; } return false; } public void Reconstruct(Image image, string globalShaderName, string pixelSizeName) { int combinedWidth = image.Width; int combinedHeight = image.Height * 2; TextureFormat format = getTextureFormat(image); if (_combinedTexture != null) { DestroyImmediate(_combinedTexture); } _combinedTexture = new Texture2D(combinedWidth, combinedHeight, format, false, true); _combinedTexture.wrapMode = TextureWrapMode.Clamp; _combinedTexture.filterMode = FilterMode.Bilinear; _combinedTexture.name = globalShaderName; _combinedTexture.hideFlags = HideFlags.DontSave; _intermediateArray = new byte[combinedWidth * combinedHeight * bytesPerPixel(format)]; Shader.SetGlobalTexture(globalShaderName, _combinedTexture); Shader.SetGlobalVector(pixelSizeName, new Vector2(1.0f / image.Width, 1.0f / image.Height)); } public void UpdateTexture(Image image) { Array.Copy(image.Data, 0, _intermediateArray, 0, _intermediateArray.Length); _combinedTexture.LoadRawTextureData(_intermediateArray); _combinedTexture.Apply(); } private TextureFormat getTextureFormat(Image image) { switch (image.Format) { case Image.FormatType.INFRARED: return TextureFormat.Alpha8; case Image.FormatType.IBRG: case (Image.FormatType)4: //Hack, Dragonfly still reports a weird format type return TextureFormat.RGBA32; default: throw new System.Exception("Unexpected image format " + image.Format + "!"); } } private int bytesPerPixel(TextureFormat format) { switch (format) { case TextureFormat.Alpha8: return 1; case TextureFormat.RGBA32: case TextureFormat.BGRA32: case TextureFormat.ARGB32: return 4; default: throw new System.Exception("Unexpected texture format " + format); } } } public class LeapDistortionData { private Texture2D _combinedTexture = null; public Texture2D CombinedTexture { get { return _combinedTexture; } } public bool CheckStale() { return _combinedTexture == null; } public void Reconstruct(Image image, string shaderName) { int combinedWidth = image.DistortionWidth / 2; int combinedHeight = image.DistortionHeight * 2; if (_combinedTexture != null) { DestroyImmediate(_combinedTexture); } Color32[] colorArray = new Color32[combinedWidth * combinedHeight]; _combinedTexture = new Texture2D(combinedWidth, combinedHeight, TextureFormat.RGBA32, false, true); _combinedTexture.filterMode = FilterMode.Bilinear; _combinedTexture.wrapMode = TextureWrapMode.Clamp; _combinedTexture.hideFlags = HideFlags.DontSave; addDistortionData(image, colorArray, 0); _combinedTexture.SetPixels32(colorArray); _combinedTexture.Apply(); Shader.SetGlobalTexture(shaderName, _combinedTexture); } private void addDistortionData(Image image, Color32[] colors, int startIndex) { float[] distortionData = image.Distortion; for (int i = 0; i < distortionData.Length; i += 2) { byte b0, b1, b2, b3; encodeFloat(distortionData[i], out b0, out b1); encodeFloat(distortionData[i + 1], out b2, out b3); colors[i / 2 + startIndex] = new Color32(b0, b1, b2, b3); } } private void encodeFloat(float value, out byte byte0, out byte byte1) { // The distortion range is -0.6 to +1.7. Normalize to range [0..1). value = (value + 0.6f) / 2.3f; float enc_0 = value; float enc_1 = value * 255.0f; enc_0 = enc_0 - (int)enc_0; enc_1 = enc_1 - (int)enc_1; enc_0 -= 1.0f / 255.0f * enc_1; byte0 = (byte)(enc_0 * 256.0f); byte1 = (byte)(enc_1 * 256.0f); } } public class EyeTextureData { private const string IR_SHADER_VARIANT_NAME = "LEAP_FORMAT_IR"; private const string RGB_SHADER_VARIANT_NAME = "LEAP_FORMAT_RGB"; private const string GLOBAL_BRIGHT_TEXTURE_NAME = "_LeapGlobalBrightnessTexture"; private const string GLOBAL_RAW_TEXTURE_NAME = "_LeapGlobalRawTexture"; private const string GLOBAL_DISTORTION_TEXTURE_NAME = "_LeapGlobalDistortion"; private const string GLOBAL_BRIGHT_PIXEL_SIZE_NAME = "_LeapGlobalBrightnessPixelSize"; private const string GLOBAL_RAW_PIXEL_SIZE_NAME = "_LeapGlobalRawPixelSize"; public readonly LeapTextureData BrightTexture; public readonly LeapTextureData RawTexture; public readonly LeapDistortionData Distortion; private bool _isStale = false; public static void ResetGlobalShaderValues() { Texture2D empty = new Texture2D(1, 1, TextureFormat.ARGB32, false, false); empty.name = "EmptyTexture"; empty.hideFlags = HideFlags.DontSave; empty.SetPixel(0, 0, new Color(0, 0, 0, 0)); Shader.SetGlobalTexture(GLOBAL_BRIGHT_TEXTURE_NAME, empty); Shader.SetGlobalTexture(GLOBAL_RAW_TEXTURE_NAME, empty); Shader.SetGlobalTexture(GLOBAL_DISTORTION_TEXTURE_NAME, empty); } public EyeTextureData() { BrightTexture = new LeapTextureData(); RawTexture = new LeapTextureData(); Distortion = new LeapDistortionData(); } public bool CheckStale(Image bright, Image raw) { return BrightTexture.CheckStale(bright) || RawTexture.CheckStale(raw) || Distortion.CheckStale() || _isStale; } public void MarkStale() { _isStale = true; } public void Reconstruct(Image bright, Image raw) { BrightTexture.Reconstruct(bright, GLOBAL_BRIGHT_TEXTURE_NAME, GLOBAL_BRIGHT_PIXEL_SIZE_NAME); RawTexture.Reconstruct(raw, GLOBAL_RAW_TEXTURE_NAME, GLOBAL_RAW_PIXEL_SIZE_NAME); Distortion.Reconstruct(raw, GLOBAL_DISTORTION_TEXTURE_NAME); switch (raw.Format) { case Image.FormatType.INFRARED: Shader.DisableKeyword(RGB_SHADER_VARIANT_NAME); Shader.EnableKeyword(IR_SHADER_VARIANT_NAME); break; case (Image.FormatType)4: Shader.DisableKeyword(IR_SHADER_VARIANT_NAME); Shader.EnableKeyword(RGB_SHADER_VARIANT_NAME); break; default: Debug.LogWarning("Unexpected format type " + raw.Format); break; } _isStale = false; } public void UpdateTextures(Image bright, Image raw) { BrightTexture.UpdateTexture(bright); RawTexture.UpdateTexture(raw); } } #if UNITY_EDITOR void OnValidate() { if (Application.isPlaying) { ApplyGammaCorrectionValues(); } else { EyeTextureData.ResetGlobalShaderValues(); } } #endif void Start() { if (_provider == null) { Debug.LogWarning("Cannot use LeapImageRetriever if there is no LeapProvider!"); enabled = false; return; } ApplyGammaCorrectionValues(); ApplyCameraProjectionValues(GetComponent<Camera>()); } void OnEnable() { Controller controller = _provider.GetLeapController(); if (controller != null) { onController(controller); } else { StartCoroutine(waitForController()); } LeapVRCameraControl.OnLeftPreRender += ApplyCameraProjectionValues; LeapVRCameraControl.OnRightPreRender += ApplyCameraProjectionValues; } void OnDisable() { StopAllCoroutines(); Controller controller = _provider.GetLeapController(); if (controller != null) { _provider.GetLeapController().DistortionChange -= onDistortionChange; } LeapVRCameraControl.OnLeftPreRender -= ApplyCameraProjectionValues; LeapVRCameraControl.OnRightPreRender -= ApplyCameraProjectionValues; } void OnDestroy() { StopAllCoroutines(); Controller controller = _provider.GetLeapController(); if (controller != null) { _provider.GetLeapController().DistortionChange -= onDistortionChange; } } void OnPreRender() { if (imagesEnabled) { Controller controller = _provider.GetLeapController(); long start = controller.Now(); while (!_requestedImage.IsComplete) { if (controller.Now() - start > ImageTimeout) break; } if (_requestedImage.IsComplete) { if (_eyeTextureData.CheckStale(_requestedImage, _requestedImage)) { _eyeTextureData.Reconstruct(_requestedImage, _requestedImage); } _eyeTextureData.UpdateTextures(_requestedImage, _requestedImage); } else if (!checkingImageState) { StartCoroutine(checkImageMode()); } } } void Update() { if (imagesEnabled) { Frame imageFrame = _provider.CurrentFrame; Controller controller = _provider.GetLeapController(); _requestedImage = controller.RequestImages(imageFrame.Id, Image.ImageType.DEFAULT); } else if (!checkingImageState) { StartCoroutine(checkImageMode()); } } private IEnumerator waitForController() { Controller controller = null; do { controller = _provider.GetLeapController(); yield return null; } while (controller == null); onController(controller); } private IEnumerator checkImageMode() { checkingImageState = true; yield return new WaitForSeconds(IMAGE_SETTING_POLL_RATE); _provider.GetLeapController().Config.Get<Int32>("images_mode", delegate (Int32 enabled) { this.imagesEnabled = enabled == 0 ? false : true; checkingImageState = false; }); } private void onController(Controller controller) { controller.DistortionChange += onDistortionChange; controller.Connect += delegate { _provider.GetLeapController().Config.Get("images_mode", (Int32 enabled) => { this.imagesEnabled = enabled == 0 ? false : true; }); }; if (!checkingImageState) { StartCoroutine(checkImageMode()); } } public void ApplyGammaCorrectionValues() { float gamma = 1f; if (QualitySettings.activeColorSpace != ColorSpace.Linear) { gamma = -Mathf.Log10(Mathf.GammaToLinearSpace(0.1f)); } Shader.SetGlobalFloat(GLOBAL_COLOR_SPACE_GAMMA_NAME, gamma); Shader.SetGlobalFloat(GLOBAL_GAMMA_CORRECTION_EXPONENT_NAME, 1.0f / _gammaCorrection); } public void ApplyCameraProjectionValues(Camera camera) { //These parameters are used during undistortion of the images to ensure they //line up properly with the scene Vector4 projection = new Vector4(); projection.x = camera.projectionMatrix[0, 2]; projection.y = 0f; projection.z = camera.projectionMatrix[0, 0]; projection.w = camera.projectionMatrix[1, 1]; Shader.SetGlobalVector(GLOBAL_CAMERA_PROJECTION_NAME, projection); } void onDistortionChange(object sender, LeapEventArgs args) { _eyeTextureData.MarkStale(); } } }
// ReSharper disable once CheckNamespace namespace Should { using System; using System.Collections.Generic; using Core.Assertions; using Core.Exceptions; /// <summary> /// Extensions which provide assertions to classes derived from <see cref="object"/>. /// </summary> public static class ObjectAssertExtensions { /// <summary>Verifies that an object is greater than the exclusive minimum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="object">The object to be evaluated (left side of the comparison).</param> /// <param name="value">The (exclusive) minimum value of the <paramref name="object"/>. (The right side of the comparison.)</param> public static void ShouldBeGreaterThan<T>(this T @object, T value) { Assert.GreaterThan(@object, value); } /// <summary>Verifies that an object is greater than the exclusive minimum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="object">The object to be evaluated (left side of the comparison).</param> /// <param name="value">The (exclusive) minimum value of the <paramref name="object"/>. (The right side of the comparison.)</param> /// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param> public static void ShouldBeGreaterThan<T>(this T @object, T value, IComparer<T> comparer) { Assert.GreaterThan(@object, value, comparer); } /// <summary>Verifies that an object is greater than the inclusive minimum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="object">The object to be evaluated (left side of the comparison).</param> /// <param name="value">The (inclusive) minimum value of the <paramref name="object"/>. (The right side of the comparison.)</param> public static void ShouldBeGreaterThanOrEqualTo<T>(this T @object, T value) { Assert.GreaterThanOrEqual(@object, value); } /// <summary>Verifies that an object is greater than the inclusive minimum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="object">The object to be evaluated (left side of the comparison).</param> /// <param name="value">The (inclusive) minimum value of the <paramref name="object"/>. (The right side of the comparison.)</param> /// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param> public static void ShouldBeGreaterThanOrEqualTo<T>(this T @object, T value, IComparer<T> comparer) { Assert.GreaterThanOrEqual(@object, value, comparer); } /// <summary> /// Verifies that a value is within a given range. /// </summary> /// <typeparam name="T">The type of the value to be compared</typeparam> /// <param name="actual">The actual value to be evaluated</param> /// <param name="low">The (inclusive) low value of the range</param> /// <param name="high">The (inclusive) high value of the range</param> /// <exception cref="InRangeException">Thrown when the value is not in the given range</exception> public static void ShouldBeInRange<T>(this T actual, T low, T high) { Assert.InRange(actual, low, high); } /// <summary> /// Verifies that a value is within a given range, using a comparer. /// </summary> /// <typeparam name="T">The type of the value to be compared</typeparam> /// <param name="actual">The actual value to be evaluated</param> /// <param name="low">The (inclusive) low value of the range</param> /// <param name="high">The (inclusive) high value of the range</param> /// <param name="comparer">The comparer used to evaluate the value's range</param> /// <exception cref="InRangeException">Thrown when the value is not in the given range</exception> public static void ShouldBeInRange<T>(this T actual, T low, T high, IComparer<T> comparer) { Assert.InRange(actual, low, high, comparer); } /// <summary>Verifies that an object is less than the exclusive maximum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="object">The object to be evaluated (left side of the comparison).</param> /// <param name="value">The (exclusive) maximum value of the <paramref name="object"/>. (The right side of the comparison.)</param> public static void ShouldBeLessThan<T>(this T @object, T value) { Assert.LessThan(@object, value); } /// <summary>Verifies that an object is less than the exclusive maximum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="object">The object to be evaluated (left side of the comparison).</param> /// <param name="value">The (exclusive) maximum value of the <paramref name="object"/>. (The right side of the comparison.)</param> /// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param> public static void ShouldBeLessThan<T>(this T @object, T value, IComparer<T> comparer) { Assert.LessThan(@object, value, comparer); } /// <summary>Verifies that an object is less than the inclusive maximum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="object">The object to be evaluated (left side of the comparison).</param> /// <param name="value">The (inclusive) maximum value of the <paramref name="object"/>. (The right side of the comparison.)</param> public static void ShouldBeLessThanOrEqualTo<T>(this T @object, T value) { Assert.LessThanOrEqual(@object, value); } /// <summary>Verifies that an object is less than the inclusive maximum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="object">The object to be evaluated (left side of the comparison).</param> /// <param name="value">The (inclusive) maximum value of the <paramref name="object"/>. (The right side of the comparison.)</param> /// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param> public static void ShouldBeLessThanOrEqualTo<T>(this T @object, T value, IComparer<T> comparer) { Assert.LessThanOrEqual(@object, value, comparer); } /// <summary> /// Verifies that an object reference is null. /// </summary> /// <param name="object">The object to be inspected</param> /// <exception cref="NullException">Thrown when the object reference is not null</exception> public static void ShouldBeNull(this object @object) { Assert.Null(@object); } /// <summary> /// Verifies that two objects are the same instance. /// </summary> /// <param name="actual">The actual object instance</param> /// <param name="expected">The expected object instance</param> /// <exception cref="SameException">Thrown when the objects are not the same instance</exception> public static void ShouldBeSameAs(this object actual, object expected) { Assert.Same(expected, actual); } /// <summary> /// Verifies that an object is exactly the given type (and not a derived type). /// </summary> /// <typeparam name="T">The type the object should be</typeparam> /// <param name="object">The object to be evaluated</param> /// <returns>The object, casted to type T when successful</returns> /// <exception cref="IsTypeException">Thrown when the object is not the given type</exception> public static T ShouldBeType<T>(this object @object) { return Assert.IsType<T>(@object); } /// <summary> /// Verifies that an object is exactly the given type (and not a derived type). /// </summary> /// <param name="object">The object to be evaluated</param> /// <param name="expectedType">The type the object should be</param> /// <exception cref="IsTypeException">Thrown when the object is not the given type</exception> public static void ShouldBeType(this object @object, Type expectedType) { Assert.IsType(expectedType, @object); } /// <summary> /// Verifies that an object is of the given type or a derived type /// </summary> /// <typeparam name="T">The type the object should implement</typeparam> /// <param name="object">The object to be evaluated</param> /// <returns>The object, casted to type T when successful</returns> /// <exception cref="IsTypeException">Thrown when the object is not the given type</exception> public static T ShouldImplement<T>(this object @object) { return Assert.IsAssignableFrom<T>(@object); } /// <summary> /// Verifies that an object is of the given type or a derived type /// </summary> /// <param name="object">The object to be evaluated</param> /// <param name="expectedType">The type the object should implement</param> /// <exception cref="IsTypeException">Thrown when the object is not the given type</exception> public static void ShouldImplement(this object @object, Type expectedType) { Assert.IsAssignableFrom(expectedType, @object); } /// <summary> /// Verifies that an object is of the given type or a derived type /// </summary> /// <typeparam name="T">The type the object should implement</typeparam> /// <param name="object">The object to be evaluated</param> /// <param name="userMessage">The user message to show on failure</param> /// <returns>The object, casted to type T when successful</returns> /// <exception cref="IsTypeException">Thrown when the object is not the given type</exception> public static T ShouldImplement<T>(this object @object, string userMessage) { return Assert.IsAssignableFrom<T>(@object, userMessage); } /// <summary> /// Verifies that an object is of the given type or a derived type /// </summary> /// <param name="object">The object to be evaluated</param> /// <param name="expectedType">The type the object should implement</param> /// <param name="userMessage">The user message to show on failure</param> /// <exception cref="IsTypeException">Thrown when the object is not the given type</exception> public static void ShouldImplement(this object @object, Type expectedType, string userMessage) { Assert.IsAssignableFrom(expectedType, @object, userMessage); } /// <summary> /// Verifies that two objects are equal, using a default comparer. /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> /// <param name="actual">The value to be compared against</param> /// <param name="expected">The expected value</param> /// <exception cref="EqualException">Thrown when the objects are not equal</exception> public static void ShouldEqual<T>(this T actual, T expected) { Assert.Equal(expected, actual); } /// <summary> /// Verifies that two objects are equal, using a default comparer, with a custom error message /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> /// <param name="actual">The value to be compared against</param> /// <param name="expected">The expected value</param> /// <param name="userMessage">The user message to show on failure</param> /// <exception cref="EqualException">Thrown when the objects are not equal</exception> public static void ShouldEqual<T>(this T actual, T expected, string userMessage) { Assert.Equal(expected, actual, userMessage); } /// <summary> /// Verifies that two objects are equal, using a custom comparer. /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> /// <param name="actual">The value to be compared against</param> /// <param name="expected">The expected value</param> /// <param name="comparer">The comparer used to compare the two objects</param> /// <exception cref="EqualException">Thrown when the objects are not equal</exception> public static void ShouldEqual<T>(this T actual, T expected, IEqualityComparer<T> comparer) { Assert.Equal(expected, actual, comparer); } /// <summary> /// Verifies that a value is not within a given range, using the default comparer. /// </summary> /// <typeparam name="T">The type of the value to be compared</typeparam> /// <param name="actual">The actual value to be evaluated</param> /// <param name="low">The (inclusive) low value of the range</param> /// <param name="high">The (inclusive) high value of the range</param> /// <exception cref="NotInRangeException">Thrown when the value is in the given range</exception> public static void ShouldNotBeInRange<T>(this T actual, T low, T high) { Assert.NotInRange(actual, low, high); } /// <summary> /// Verifies that a value is not within a given range, using a comparer. /// </summary> /// <typeparam name="T">The type of the value to be compared</typeparam> /// <param name="actual">The actual value to be evaluated</param> /// <param name="low">The (inclusive) low value of the range</param> /// <param name="high">The (inclusive) high value of the range</param> /// <param name="comparer">The comparer used to evaluate the value's range</param> /// <exception cref="NotInRangeException">Thrown when the value is in the given range</exception> public static void ShouldNotBeInRange<T>(this T actual, T low, T high, IComparer<T> comparer) { Assert.NotInRange(actual, low, high, comparer); } /// <summary> /// Verifies that an object reference is not null. /// </summary> /// <param name="object">The object to be validated</param> /// <exception cref="NotNullException">Thrown when the object is not null</exception> public static T ShouldNotBeNull<T>(this T @object) where T : class { Assert.NotNull(@object); return @object; } /// <summary> /// Verifies that an object reference is not null. /// </summary> /// <param name="object">The object to be validated</param> /// <param name="message">The message to show on failure</param> /// <exception cref="NotNullException">Thrown when the object reference is null</exception> public static T ShouldNotBeNull<T>(this T @object, string message) where T : class { Assert.NotNull(@object, message); return @object; } /// <summary> /// Verifies that two objects are not the same instance. /// </summary> /// <param name="actual">The actual object instance</param> /// <param name="expected">The expected object instance</param> /// <exception cref="NotSameException">Thrown when the objects are the same instance</exception> public static void ShouldNotBeSameAs(this object actual, object expected) { Assert.NotSame(expected, actual); } /// <summary> /// Verifies that an object is not exactly the given type. /// </summary> /// <typeparam name="T">The type the object should not be</typeparam> /// <param name="object">The object to be evaluated</param> /// <exception cref="IsTypeException">Thrown when the object is the given type</exception> public static void ShouldNotBeType<T>(this object @object) { Assert.IsNotType<T>(@object); } /// <summary> /// Verifies that an object is not exactly the given type. /// </summary> /// <param name="object">The object to be evaluated</param> /// <param name="expectedType">The type the object should not be</param> /// <exception cref="IsTypeException">Thrown when the object is the given type</exception> public static void ShouldNotBeType(this object @object, Type expectedType) { Assert.IsNotType(expectedType, @object); } /// <summary> /// Verifies that two objects are not equal, using a default comparer. /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> /// <param name="actual">The actual object</param> /// <param name="expected">The expected object</param> /// <exception cref="NotEqualException">Thrown when the objects are equal</exception> public static void ShouldNotEqual<T>(this T actual, T expected) { Assert.NotEqual(expected, actual); } /// <summary> /// Verifies that two objects are not equal, using a custom comparer. /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> /// <param name="actual">The actual object</param> /// <param name="expected">The expected object</param> /// <param name="comparer">The comparer used to examine the objects</param> /// <exception cref="NotEqualException">Thrown when the objects are equal</exception> public static void ShouldNotEqual<T>(this T actual, T expected, IEqualityComparer<T> comparer) { Assert.NotEqual(expected, actual, comparer); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="actual"></param> /// <param name="spec"></param> public static T ShouldMeet<T>(this T actual, Action<T> spec) { Assert.NotNull(spec); spec(actual); return actual; } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="actual"></param> /// <param name="other"></param> /// <param name="spec"></param> public static T ShouldCompareWith<T>(this T actual, T other, Action<T, T> spec) { Assert.NotNull(spec); spec(actual, other); return actual; } } }
using System; using System.Diagnostics.Contracts; namespace PartitionableArray { public class PartitionableArray<T> { #region Internal private struct Element { public T value; // Keep track of this element in the list of interesting elements public bool interesting; public int prev; public int next; } private Element[] arr; private PartitionFn test; private int sentinel { get { return arr.Length - 1; } } [ContractInvariantMethod] private void invariant() { Contract.Invariant(test != null); Contract.Invariant(arr != null); Contract.Invariant(arr.Length >= 1); Contract.Invariant(sentinel == arr.Length - 1); Contract.Invariant(Length == arr.Length - 1); Contract.Invariant(0 <= count); Contract.Invariant(count <= Length); Contract.Invariant(count < arr.Length); Contract.Invariant(Count == count); } // Remove an interesting element from the list private void remove(int index) { Contract.Requires<IndexOutOfRangeException>( 0 <= index && index < Length, "The index must be within the bounds of the array."); Contract.Requires(arr[index].interesting == true); Contract.Requires(test(arr[index].value) == true); Contract.Ensures(arr[index].interesting == false); Contract.Ensures(Contract.OldValue(Count) - 1 == Count); count--; arr[index].interesting = false; arr[arr[index].prev].next = arr[index].next; arr[arr[index].next].prev = arr[index].prev; } // Add an interesting element to the list private void add(int index) { Contract.Requires<IndexOutOfRangeException>( 0 <= index && index < Length, "The index must be within the bounds of the array."); Contract.Requires(arr[index].interesting == false); Contract.Requires(test(arr[index].value) == true); Contract.Ensures(arr[index].interesting == true); Contract.Ensures(Contract.OldValue(Count) + 1 == Count); count++; arr[index].interesting = true; arr[index].next = sentinel; arr[index].prev = arr[sentinel].prev; arr[arr[sentinel].prev].next = index; arr[sentinel].prev = index; } #endregion #region Public /// <summary> /// Given a value, decide if it is interesting. /// </summary> [Pure] public delegate bool PartitionFn(T val); /// <summary> /// Gets maximum the number of elements in the array. /// </summary> /// <value> /// The maximum number of elements in the array. /// </value> public int Length { get { return arr.Length - 1; } } int count = 0; /// <summary> /// Gets the number of interesting elements in the array. /// </summary> /// <value> /// The number of interesting elements in the array. /// </value> public int Count { get { return count; } } /// <summary> /// Initializes a new instance of the PartitionableArray class. /// </summary> /// <param name='fn'> /// A partition function to use to determine if the elements of the /// array are interesting. /// </param> /// <param name='length'> /// The fixed maximum number of elements in the array. /// </param> public PartitionableArray(PartitionFn fn, int length) { Contract.Requires<ArgumentOutOfRangeException>(0 <= length, "Length must be a non-negative integer."); Contract.Ensures(test == fn); Contract.Ensures(Length == length); Contract.Ensures( // If default value is interesting, all elements are interesting (test(arr[sentinel].value) && Count == length) // Otherwise, no elements are interesting || Count == 0); test = fn; arr = new Element[length + 1]; // One extra element for sentinel arr[sentinel].prev = arr[sentinel].next = sentinel; // Set up the sentinel for (int i = 0; i < Length; i++) // Check for interesting default values if (test(arr[i].value)) add(i); } /// <summary> /// Gets the index of an interesting element. /// <para>No guarantees are made as to which element's index will be /// returned, just that the index will be that of an interesting /// element.</para> /// </summary> /// <returns> /// The index of an interesting element. /// </returns> public int AnyInteresting() { Contract.Requires<NullReferenceException>(Count > 0, "The array must contain interesting elements."); Contract.Ensures(0 <= Contract.Result<int>() && Contract.Result<int>() < Length, "The returned index must be within the bounds of the array."); Contract.Ensures(test(this[Contract.Result<int>()]), "The returned index must be that of an interesting element."); return arr[sentinel].next; } /// <summary> /// Gets or sets the value at a certain index in the array. /// </summary> /// <param name='index'> /// The index in the array. /// </param> public T this[int index] { get { Contract.Requires<IndexOutOfRangeException>( 0 <= index && index < Length, "Index must be within array bounds."); Contract.Assume(index < this.arr.Length); return arr[index].value; } set { Contract.Requires<IndexOutOfRangeException>( 0 <= index && index < Length, "Index must be within array bounds."); Contract.Ensures( // If old and new values are interesting, Count is unchanged ((test(Contract.OldValue(arr[index].value)) == test(arr[index].value)) && Contract.OldValue(Count) == Count) // If old was uninteresting and new value is interesting, Count increments || (!test(Contract.OldValue(arr[index].value)) && test(arr[index].value) && Contract.OldValue(Count) + 1 == Count) // If old value was interesting and new value is uninteresting, Count decrements || (test(Contract.OldValue(arr[index].value)) && !test(arr[index].value) && Contract.OldValue(Count) - 1 == Count)); Contract.Assume(index < arr.Length); if (test(arr[index].value)) remove(index); arr[index].value = value; if (test(arr[index].value)) add(index); } } #endregion } }
// // System.Data.SqlTypes.SqlGuid // // Author: // Tim Coleman <tim@timcoleman.com> // Ville Palo <vi64pa@koti.soon.fi> // // (C) Copyright 2002 Tim Coleman // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; namespace System.Data.SqlTypes { public struct SqlGuid : INullable, IComparable { #region Fields Guid value; private bool notNull; public static readonly SqlGuid Null; #endregion #region Constructors public SqlGuid (byte[] value) { this.value = new Guid (value); notNull = true; } public SqlGuid (Guid g) { this.value = g; notNull = true; } public SqlGuid (string s) { this.value = new Guid (s); notNull = true; } public SqlGuid (int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { this.value = new Guid (a, b, c, d, e, f, g, h, i, j, k); notNull = true; } #endregion #region Properties public bool IsNull { get { return !notNull; } } public Guid Value { get { if (this.IsNull) throw new SqlNullValueException ("The property contains Null."); else return value; } } private byte[] GetLastSixBytes() { byte [] lastSixBytes = new byte[6]; byte[] guidArray = value.ToByteArray(); lastSixBytes[0] = guidArray[10]; lastSixBytes[1] = guidArray[11]; lastSixBytes[2] = guidArray[12]; lastSixBytes[3] = guidArray[13]; lastSixBytes[4] = guidArray[14]; lastSixBytes[5] = guidArray[15]; return lastSixBytes; } #endregion #region Methods public int CompareTo (object value) { if (value == null) return 1; else if (!(value is SqlGuid)) throw new ArgumentException (Locale.GetText ("Value is not a System.Data.SqlTypes.SqlGuid")); else if (((SqlGuid)value).IsNull) return 1; else // LAMESPEC : ms.net implementation actually compares all the 16 bytes. // This code is kept for future changes, if required. /* { //MSDN documentation says that CompareTo is different from //Guid's CompareTo. It uses the SQL Server behavior where //only the last 6 bytes of value are evaluated byte[] compareValue = ((SqlGuid)value).GetLastSixBytes(); byte[] currentValue = GetLastSixBytes(); for (int i = 0; i < 6; i++) { if (currentValue[i] != compareValue[i]) { return Compare(currentValue[i], compareValue[i]); } } return 0; } */ return this.value.CompareTo (((SqlGuid)value).Value); } private static int Compare (uint x, uint y) { if (x < y) { return -1; } else { return 1; } } public override bool Equals (object value) { if (!(value is SqlGuid)) return false; else if (this.IsNull && ((SqlGuid)value).IsNull) return true; else if (((SqlGuid)value).IsNull) return false; else return (bool) (this == (SqlGuid)value); } public static SqlBoolean Equals (SqlGuid x, SqlGuid y) { return (x == y); } public override int GetHashCode () { byte [] bytes = this.ToByteArray (); int result = 10; foreach (byte b in bytes) { result = 91 * result + b.GetHashCode (); } return result; } public static SqlBoolean GreaterThan (SqlGuid x, SqlGuid y) { return (x > y); } public static SqlBoolean GreaterThanOrEqual (SqlGuid x, SqlGuid y) { return (x >= y); } public static SqlBoolean LessThan (SqlGuid x, SqlGuid y) { return (x < y); } public static SqlBoolean LessThanOrEqual (SqlGuid x, SqlGuid y) { return (x <= y); } public static SqlBoolean NotEquals (SqlGuid x, SqlGuid y) { return (x != y); } public static SqlGuid Parse (string s) { return new SqlGuid (s); } public byte[] ToByteArray() { return value.ToByteArray (); } public SqlBinary ToSqlBinary () { return ((SqlBinary)this); } public SqlString ToSqlString () { return ((SqlString)this); } public override string ToString () { if (!notNull) return "Null"; else return value.ToString (); } public static SqlBoolean operator == (SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; return new SqlBoolean (x.Value == y.Value); } public static SqlBoolean operator > (SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; if (x.Value.CompareTo (y.Value) > 0) return new SqlBoolean (true); else return new SqlBoolean (false); } public static SqlBoolean operator >= (SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; if (x.Value.CompareTo (y.Value) >= 0) return new SqlBoolean (true); else return new SqlBoolean (false); } public static SqlBoolean operator != (SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; return new SqlBoolean (!(x.Value == y.Value)); } public static SqlBoolean operator < (SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; if (x.Value.CompareTo (y.Value) < 0) return new SqlBoolean (true); else return new SqlBoolean (false); } public static SqlBoolean operator <= (SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; if (x.Value.CompareTo (y.Value) <= 0) return new SqlBoolean (true); else return new SqlBoolean (false); } public static explicit operator SqlGuid (SqlBinary x) { return new SqlGuid (x.Value); } public static explicit operator Guid (SqlGuid x) { return x.Value; } public static explicit operator SqlGuid (SqlString x) { return new SqlGuid (x.Value); } public static implicit operator SqlGuid (Guid x) { return new SqlGuid (x); } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; // Dungeon class. Singleton. public class Dungeon : MonoBehaviour, VoxelStream { // Dungeon Parameters public int MAP_COLS = 128; public int MAP_HEIGHT = 5; public int MAP_ROWS = 128; // Room Parameters public int ROOM_MAX_SIZE = 24; public int ROOM_MIN_SIZE = 4; public int ROOM_WALL_BORDER = 1; public bool ROOM_UGLY_ENABLED = true; public float ROOM_MAX_RATIO = 5.0f; public int ROOM_TO_EXIT_LENGTH = 6; // Generation Parameters public static int MAX_DEPTH = 10; public static int CHANCE_STOP = 5; public static int SLICE_TRIES = 10; public int CORRIDOR_WIDTH = 2; public int MAX_NUM_BARRIERS = 5; // Tilemap private byte[,,] tiles; private Vector3 tileBounds; // The Random Seed public int seed = -1; // QuadTreeMapLayer for dungeon distribution private QuadTreeMapLayer quadTree; // List of rooms private List<Room_2D> rooms; public byte GetBlockAtRelativeCoords (int x, int y, int z) { if (x >= MAP_COLS || x < 0 || y >= MAP_HEIGHT || y < 0 || z >= MAP_ROWS || z < 0) { return (byte)0; } return tiles [z, y, x]; } public Vector3 getBounds () { return new Vector3 (tiles.GetLength (0), tiles.GetLength (1), tiles.GetLength (2)); } public byte[,,] GetAllBlocks () { Debug.Log ("dungeon returning all blocks"); return tiles; } private void resetBlocks () { tiles = new byte[MAP_ROWS, MAP_HEIGHT, MAP_COLS]; for (int x = 0; x < MAP_COLS; x++) for (int y = 0; y < MAP_HEIGHT; y++) for (int z = 0; z < MAP_ROWS; z++) //Draw the floor if (y == 0) { tiles [z, y, x] = 1; } else { tiles [z, y, x] = 2; } } // On Awake public void create () { // Initialize the tilemap resetBlocks (); // Init QuadTree quadTree = new QuadTreeMapLayer (new AABB (new XY (MAP_COLS / 2.0f, MAP_ROWS / 2.0f), new XY (MAP_COLS / 2.0f, MAP_ROWS / 2.0f)), this); // List of rooms rooms = new List<Room_2D> (); //barriers = new List<GameObject> (); // Set the randome seed //Random.seed = seed; // Generate Dungeon Debug.Log ("Dungeon Generation Started"); GenerateDungeon (seed); } // Generate a new dungeon with the given seed public void GenerateDungeon (int seed) { Debug.Log ("Generating QuadTreeMapLayer"); // Generate QuadTreeMapLayer GenerateQuadTree (ref quadTree); Debug.Log ("Generating Rooms"); // Generate Rooms GenerateRooms (ref rooms, quadTree); Debug.Log ("Generating Corridors"); // Generate Corridors GenerateCorridors (); Debug.Log ("Generating Exits"); DigExits (); //GenerateWalls (); Debug.Log ("Finished generating Dungeon!"); } // Generate the quadtree system void GenerateQuadTree (ref QuadTreeMapLayer _quadTree) { _quadTree.GenerateQuadTree (seed); } // Generate the list of rooms and dig them public void GenerateRooms (ref List<Room_2D> _rooms, QuadTreeMapLayer _quadTree) { // Childless node if (_quadTree.northWest == null && _quadTree.northEast == null && _quadTree.southWest == null && _quadTree.southEast == null) { _rooms.Add (GenerateRoom (_quadTree)); return; } // Recursive call if (_quadTree.northWest != null) GenerateRooms (ref _rooms, _quadTree.northWest); if (_quadTree.northEast != null) GenerateRooms (ref _rooms, _quadTree.northEast); if (_quadTree.southWest != null) GenerateRooms (ref _rooms, _quadTree.southWest); if (_quadTree.southEast != null) GenerateRooms (ref _rooms, _quadTree.southEast); } // Generate a single room public Room_2D GenerateRoom (QuadTreeMapLayer _quadTree) { // Center of the room XY roomCenter = new XY (); roomCenter.x = Random.Range (ROOM_WALL_BORDER + _quadTree.boundary.Left () + ROOM_MIN_SIZE / 2.0f, _quadTree.boundary.Right () - ROOM_MIN_SIZE / 2.0f - ROOM_WALL_BORDER); roomCenter.y = Random.Range (ROOM_WALL_BORDER + _quadTree.boundary.Bottom () + ROOM_MIN_SIZE / 2.0f, _quadTree.boundary.Top () - ROOM_MIN_SIZE / 2.0f - ROOM_WALL_BORDER); // Half size of the room XY roomHalf = new XY (); float halfX = (_quadTree.boundary.Right () - roomCenter.x - ROOM_WALL_BORDER); float halfX2 = (roomCenter.x - _quadTree.boundary.Left () - ROOM_WALL_BORDER); if (halfX2 < halfX) halfX = halfX2; if (halfX > ROOM_MAX_SIZE / 2.0f) halfX = ROOM_MAX_SIZE / 2.0f; float halfY = (_quadTree.boundary.Top () - roomCenter.y - ROOM_WALL_BORDER); float halfY2 = (roomCenter.y - _quadTree.boundary.Bottom () - ROOM_WALL_BORDER); if (halfY2 < halfY) halfY = halfY2; if (halfY > ROOM_MAX_SIZE / 2.0f) halfY = ROOM_MAX_SIZE / 2.0f; roomHalf.x = Random.Range ((float)ROOM_MIN_SIZE / 2.0f, halfX); roomHalf.y = Random.Range ((float)ROOM_MIN_SIZE / 2.0f, halfY); // Eliminate ugly zones if (ROOM_UGLY_ENABLED == false) { float aspect_ratio = roomHalf.x / roomHalf.y; if (aspect_ratio > ROOM_MAX_RATIO || aspect_ratio < 1.0f / ROOM_MAX_RATIO) return GenerateRoom (_quadTree); } // Create AABB AABB randomAABB = new AABB (roomCenter, roomHalf); // Dig the room in our tilemap DigRoom (randomAABB.BottomTile (), randomAABB.LeftTile (), randomAABB.TopTile () - 1, randomAABB.RightTile () - 1); // Return the room return new Room_2D (randomAABB, _quadTree); } void GenerateCorridors () { quadTree.GenerateCorridors (); } // Generate walls when there's something near public void GenerateWalls () { // Place walls for (int i = 0; i < MAP_ROWS; i++) { for (int j = 0; j < MAP_COLS; j++) { bool room_near = false; if (IsPassable (i, j)) continue; if (i > 0) if (IsPassable (i - 1, j)) room_near = true; if (i < MAP_ROWS - 1) if (IsPassable (i + 1, j)) room_near = true; if (j > 0) if (IsPassable (i, j - 1)) room_near = true; if (j < MAP_COLS - 1) if (IsPassable (i, j + 1)) room_near = true; if (room_near) SetWall (i, j); } } } // Helper Methods public bool IsEmpty (int row, int col) { return tiles [row, MAP_HEIGHT / 2, col] == 0; } public bool IsPassable (int row, int col) { return tiles [row, MAP_HEIGHT / 2, col] == 0; } public bool IsPassable (XY xy) { return IsPassable ((int)xy.y, (int)xy.x); } public void SetWall (int row, int col) { for (int y = 0; y < MAP_HEIGHT; y++) { tiles [row, y, col] = 2; } } // Dig a room, placing floor tiles public void DigRoom (int row_bottom, int col_left, int row_top, int col_right) { // Out of range if (row_top < row_bottom) { int tmp = row_top; row_top = row_bottom; row_bottom = tmp; } // Out of range if (col_right < col_left) { int tmp = col_right; col_right = col_left; col_left = tmp; } if (row_top > MAP_ROWS - 1) return; if (row_bottom < 0) return; if (col_right > MAP_COLS - 1) return; if (col_left < 0) return; // Dig floor for (int row = row_bottom; row <= row_top; row++) for (int col = col_left; col <= col_right; col++) DigRoom (row, col); } public void DigRoom (int row, int col) { for (int y = 1; y < MAP_HEIGHT; y++) { tiles [row, y, col] = 0; } } public void DigCorridor (int row, int col) { for (int y = 1; y < MAP_HEIGHT; y++) { tiles [row, y, col] = 0; } } public void DigCorridor (XY p1, XY p2) { int row1 = Mathf.RoundToInt (p1.y); int row2 = Mathf.RoundToInt (p2.y); int col1 = Mathf.RoundToInt (p1.x); int col2 = Mathf.RoundToInt (p2.x); DigCorridor (row1, col1, row2, col2); } private void DigCorridor (int row1, int col1, int row2, int col2) { if (row1 <= row2) { // source is below the dest for (int col = col1; col < col1 + CORRIDOR_WIDTH; col++) for (int row = row1; row <= row2; row++) DigCorridor (row, col); } else { // source is above the dest for (int col = col1; col < col1 + CORRIDOR_WIDTH; col++) for (int row = row2; row <= row1; row++) DigCorridor (row, col); } if (col1 <= col2) { // source is to the left of the dest. for (int row = row2; row < row2 + CORRIDOR_WIDTH; row++) for (int col = col1; col <= col2; col++) DigCorridor (row, col); } else { // source is to the right of the dest. for (int row = row2; row < row2 + CORRIDOR_WIDTH; row++) for (int col = col2; col <= col1; col++) DigCorridor (row, col); } } public void DigExits () { //Find all the eligable exits LinkedList<Room_2D> eligableRooms = new LinkedList<Room_2D> (); foreach (Room_2D room in rooms) { int col = Mathf.RoundToInt (room.boundary.center.x); int row = Mathf.RoundToInt (room.boundary.center.y); if (Mathf.Abs (MAP_ROWS - row) <= ROOM_TO_EXIT_LENGTH || row <= ROOM_TO_EXIT_LENGTH || Mathf.Abs (MAP_COLS - col) <= ROOM_TO_EXIT_LENGTH || col <= ROOM_TO_EXIT_LENGTH) { eligableRooms.AddLast (room); } } //Choose a random number of exits/entrances int roomCount = eligableRooms.Count; if (roomCount > 0) { int index = Random.Range (0, roomCount); Room_2D room = eligableRooms.ElementAt (index); int col = Mathf.RoundToInt (room.boundary.center.x); int row = Mathf.RoundToInt (room.boundary.center.y); if (Mathf.Abs (MAP_ROWS - row) <= ROOM_TO_EXIT_LENGTH || row <= ROOM_TO_EXIT_LENGTH) { if (row > MAP_ROWS / 2) { DigExit (row, col, MAP_ROWS - 1, col); } else { DigExit (row, col, 0, col); } } else if (Mathf.Abs (MAP_COLS - col) <= ROOM_TO_EXIT_LENGTH || col <= ROOM_TO_EXIT_LENGTH) { if (col > MAP_COLS / 2) { DigExit (row, col, row, MAP_COLS - 1); } else { DigExit (row, col, row, 0); } } } } private void DigExit (int row1, int col1, int row2, int col2) { if (col1 == col2) { if (row1 <= row2) { // source is below the dest for (int col = col1; col < col1 + CORRIDOR_WIDTH; col++) for (int row = row1; row <= row2; row++) DigCorridor (row, col); } else { // source is above the dest for (int col = col1; col < col1 + CORRIDOR_WIDTH; col++) for (int row = row2; row <= row1; row++) DigCorridor (row, col); } } else { if (col1 <= col2) { // source is to the left of the dest. for (int row = row2; row < row2 + CORRIDOR_WIDTH; row++) for (int col = col1; col <= col2; col++) DigCorridor (row, col); } else { // source is to the right of the dest. for (int row = row2; row < row2 + CORRIDOR_WIDTH; row++) for (int col = col2; col <= col1; col++) DigCorridor (row, col); } } } }
/* 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.Drawing; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using ESRI.ArcGIS.ADF; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.esriSystem; namespace TriangleElement { [ComVisible(true)] [Guid("DC8482C9-5DD6-44dc-BF3C-54B18AB813C9")] public interface ITriangleElement { ISimpleFillSymbol FillSymbol { get; set;} double Size { get; set;} double Angle { get; set;} } [Guid(TriangleElementClass.CLASSGUID)] [ClassInterface(ClassInterfaceType.None)] [ProgId("TriangleElement.TriangleElementClass")] public sealed class TriangleElementClass : ITriangleElement, IElement, IElementProperties, IElementProperties2, IElementProperties3, IBoundsProperties, ITransform2D, IGraphicElement, IPersistVariant, IClone, IDocumentVersionSupportGEN { #region class members //some win32 imports and constants [System.Runtime.InteropServices.DllImport("gdi32", EntryPoint = "GetDeviceCaps", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Ansi, SetLastError = true)] public static extern int GetDeviceCaps(int hDC, int nIndex); private const double c_Cosine30 = 0.866025403784439; private const double c_Deg2Rad = (Math.PI / 180.0); private const double c_Rad2Deg = (180.0 / Math.PI); private const int c_Version = 2; public const string CLASSGUID = "cbf943e2-ce6d-49f4-a4a7-ce16f02379ad"; public const int LOGPIXELSX = 88; public const int LOGPIXELSY = 90; private IPolygon m_triangle = null; private IPoint m_pointGeometry = null; private ISimpleFillSymbol m_fillSymbol = null; private double m_rotation = 0.0; private double m_size = 20.0; private ISelectionTracker m_selectionTracker = null; private IDisplay m_cachedDisplay = null; private ISpatialReference m_nativeSR = null; private string m_elementName = string.Empty; private string m_elementType = "TriangleElement"; private object m_customProperty = null; private bool m_autoTrans = true; private double m_scaleRef = 0.0; private esriAnchorPointEnum m_anchorPointType = esriAnchorPointEnum.esriCenterPoint; private double m_dDeviceRatio = 0; #endregion #region class constructor public TriangleElementClass() { //initialize the element's geometry m_triangle = new PolygonClass(); m_triangle.SetEmpty(); InitMembers(); } #endregion #region ITriangleElement Members public ISimpleFillSymbol FillSymbol { get { return m_fillSymbol; } set { m_fillSymbol = value; } } public double Size { get { return m_size; } set { m_size = value; } } public double Angle { get { return m_rotation; } set { m_rotation = value; } } #endregion #region IElement Members public void Activate(IDisplay Display) { //cache the display m_cachedDisplay = Display; SetupDeviceRatio(Display.hDC, Display); //need to calculate the points of the triangle polygon if(m_triangle.IsEmpty) BuildTriangleGeometry(m_pointGeometry); //need to refresh the element's tracker RefreshTracker(); } public void Deactivate() { m_cachedDisplay = null; } public void Draw(IDisplay Display, ITrackCancel TrackCancel) { if (null != m_triangle && null != m_fillSymbol) { Display.SetSymbol((ISymbol)m_fillSymbol); Display.DrawPolygon(m_triangle); } } public IGeometry Geometry { get { return Clone(m_pointGeometry) as IGeometry; } set { try { m_pointGeometry = Clone(value) as IPoint; UpdateElementSpatialRef(); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } } public bool HitTest(double x, double y, double Tolerance) { if (null == m_cachedDisplay) return false; IPoint point = new PointClass(); point.PutCoords(x,y); return ((IRelationalOperator)m_triangle).Contains((IGeometry)point); } public bool Locked { get { return false; } set { } } public void QueryBounds(IDisplay Display, IEnvelope Bounds) { //return a bounding envelope IPolygon polygon = new PolygonClass(); polygon.SetEmpty(); ((ISymbol)m_fillSymbol).QueryBoundary(Display.hDC, Display.DisplayTransformation, m_triangle, polygon); Bounds.XMin = polygon.Envelope.XMin; Bounds.XMax = polygon.Envelope.XMax; Bounds.YMin = polygon.Envelope.YMin; Bounds.YMax = polygon.Envelope.YMax; Bounds.SpatialReference = polygon.Envelope.SpatialReference; } public void QueryOutline(IDisplay Display, IPolygon Outline) { //return a polygon which is the outline of the element IPolygon polygon = new PolygonClass(); polygon.SetEmpty(); ((ISymbol)m_fillSymbol).QueryBoundary(Display.hDC, Display.DisplayTransformation, m_triangle, polygon); ((IPointCollection)Outline).AddPointCollection((IPointCollection)polygon); } public ISelectionTracker SelectionTracker { get { return m_selectionTracker; } } #endregion #region IElementProperties Members /// <summary> /// Indicates if transform is applied to symbols and other parts of element. /// False = only apply transform to geometry. /// Update font size in ITransform2D routines /// </summary> public bool AutoTransform { get { return m_autoTrans; } set { m_autoTrans = value; } } public object CustomProperty { get { return m_customProperty; } set { m_customProperty = value; } } public string Name { get { return m_elementName; } set { m_elementName = value; } } public string Type { get { return m_elementType; } set { m_elementType = value; } } #endregion #region IElementProperties2 Members public bool CanRotate() { return true; } public double ReferenceScale { get { return m_scaleRef; } set { m_scaleRef = value; } } #endregion #region IElementProperties3 Members public esriAnchorPointEnum AnchorPoint { get { return m_anchorPointType; } set { m_anchorPointType = value; } } #endregion #region IBoundsProperties Members public bool FixedAspectRatio { get { return true; } set { throw new Exception("The method or operation is not implemented."); } } public bool FixedSize { get { return true; } } #endregion #region ITransform2D Members public void Move(double dx, double dy) { if (null == m_triangle) return; ((ITransform2D)m_triangle).Move(dx, dy); ((ITransform2D)m_pointGeometry).Move(dx, dy); RefreshTracker(); } public void MoveVector(ILine v) { if (null == m_triangle) return; ((ITransform2D)m_triangle).MoveVector(v); ((ITransform2D)m_pointGeometry).MoveVector(v); RefreshTracker(); } public void Rotate(IPoint Origin, double rotationAngle) { if (null == m_triangle) return; ((ITransform2D)m_triangle).Rotate(Origin, rotationAngle); ((ITransform2D)m_pointGeometry).Rotate(Origin, rotationAngle); m_rotation = rotationAngle * c_Rad2Deg; RefreshTracker(); } public void Scale(IPoint Origin, double sx, double sy) { if (null == m_triangle) return; ((ITransform2D)m_triangle).Scale(Origin, sx, sy); ((ITransform2D)m_pointGeometry).Scale(Origin, sx, sy); if (m_autoTrans) { m_size *= Math.Max(sx, sy); } RefreshTracker(); } public void Transform(esriTransformDirection direction, ITransformation transformation) { if (null == m_triangle) return; //Geometry ((ITransform2D)m_triangle).Transform(direction, transformation); IAffineTransformation2D affineTrans = (IAffineTransformation2D)transformation; if (affineTrans.YScale != 1.0) m_size *= Math.Max(affineTrans.YScale, affineTrans.XScale); RefreshTracker(); } #endregion #region IGraphicElement Members public ISpatialReference SpatialReference { get { return m_nativeSR; } set { m_nativeSR = value; UpdateElementSpatialRef(); } } #endregion #region IPersistVariant Members public UID ID { get { UID uid = new UIDClass(); uid.Value = "{" + TriangleElementClass.CLASSGUID + "}"; return uid; } } public void Load(IVariantStream Stream) { int ver = (int)Stream.Read(); if (ver > c_Version || ver <= 0) throw new Exception("Wrong version!"); InitMembers(); m_size = (double)Stream.Read(); m_scaleRef = (double)Stream.Read(); m_anchorPointType = (esriAnchorPointEnum)Stream.Read(); m_autoTrans = (bool)Stream.Read(); m_elementType = (string)Stream.Read(); m_elementName = (string)Stream.Read(); m_nativeSR = Stream.Read() as ISpatialReference; m_fillSymbol = Stream.Read() as ISimpleFillSymbol; m_pointGeometry = Stream.Read() as IPoint; m_triangle = Stream.Read() as IPolygon; if (ver == 2) { m_rotation = (double)Stream.Read(); } } public void Save(IVariantStream Stream) { Stream.Write(c_Version); Stream.Write(m_size); Stream.Write(m_scaleRef); Stream.Write(m_anchorPointType); Stream.Write(m_autoTrans); Stream.Write(m_elementType); Stream.Write(m_elementName); Stream.Write(m_nativeSR); Stream.Write(m_fillSymbol); Stream.Write(m_pointGeometry); Stream.Write(m_triangle); Stream.Write(m_rotation); } #endregion #region IClone Members public void Assign(IClone src) { //1. make sure that src is pointing to a valid object if (null == src) { throw new COMException("Invalid object."); } //2. make sure that the type of src is of type 'TriangleElementClass' if (!(src is TriangleElementClass)) { throw new COMException("Bad object type."); } //3. assign the properties of src to the current instance TriangleElementClass srcTriangle = (TriangleElementClass)src; m_elementName = srcTriangle.Name; m_elementType = srcTriangle.Type; m_autoTrans = srcTriangle.AutoTransform; m_scaleRef = srcTriangle.ReferenceScale; m_rotation = srcTriangle.Angle; m_size = srcTriangle.Size; m_anchorPointType = srcTriangle.AnchorPoint; IObjectCopy objCopy = new ObjectCopyClass(); //take care of the custom property if (null != srcTriangle.CustomProperty) { if (srcTriangle.CustomProperty is IClone) m_customProperty = (object)((IClone)srcTriangle.CustomProperty).Clone(); else if (srcTriangle.CustomProperty is IPersistStream) { m_customProperty = objCopy.Copy((object)srcTriangle.CustomProperty); } else if (srcTriangle.CustomProperty.GetType().IsSerializable) { //serialize to a memory stream MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, srcTriangle.CustomProperty); byte[] bytes = memoryStream.ToArray(); memoryStream = new MemoryStream(bytes); m_customProperty = binaryFormatter.Deserialize(memoryStream); } } if (null != srcTriangle.SpatialReference) m_nativeSR = objCopy.Copy(srcTriangle.SpatialReference) as ISpatialReference; else m_nativeSR = null; if (null != srcTriangle.FillSymbol) { m_fillSymbol = objCopy.Copy(srcTriangle.FillSymbol) as ISimpleFillSymbol; } else m_fillSymbol = null; if (null != srcTriangle.Geometry) { m_triangle = objCopy.Copy(srcTriangle.Geometry) as IPolygon; m_pointGeometry = objCopy.Copy(((IArea)m_triangle).Centroid) as IPoint; } else { m_triangle = null; m_pointGeometry = null; } } public IClone Clone() { TriangleElementClass triangle = new TriangleElementClass(); triangle.Assign((IClone)this); return (IClone)triangle; } public bool IsEqual(IClone other) { //1. make sure that the 'other' object is pointing to a valid object if (null == other) throw new COMException("Invalid object."); //2. verify the type of 'other' if (!(other is TriangleElementClass)) throw new COMException("Bad object type."); TriangleElementClass otherTriangle = (TriangleElementClass)other; //test that all of the object's properties are the same. //please note the usage of IsEqual when using ArcObjects components that //supports cloning if (otherTriangle.Name == m_elementName && otherTriangle.Type == m_elementType && otherTriangle.AutoTransform == m_autoTrans && otherTriangle.ReferenceScale == m_scaleRef && otherTriangle.Angle == m_rotation && otherTriangle.Size == m_size && otherTriangle.AnchorPoint == m_anchorPointType && ((IClone)otherTriangle.Geometry).IsEqual((IClone)m_triangle) && ((IClone)otherTriangle.FillSymbol).IsEqual((IClone)m_fillSymbol) && ((IClone)otherTriangle.SpatialReference).IsEqual((IClone)m_nativeSR)) return true; return false; } public bool IsIdentical(IClone other) { //1. make sure that the 'other' object is pointing to a valid object if (null == other) throw new COMException("Invalid object."); //2. verify the type of 'other' if (!(other is TriangleElementClass)) throw new COMException("Bad object type."); //3. test if the other is the 'this' if ((TriangleElementClass)other == this) return true; return false; } #endregion #region IDocumentVersionSupportGEN Members public object ConvertToSupportedObject(esriArcGISVersion docVersion) { //in case of 8.3, create a character marker element and use a triangle marker... ICharacterMarkerSymbol charMarkerSymbol = new CharacterMarkerSymbolClass(); charMarkerSymbol.Color = m_fillSymbol.Color; charMarkerSymbol.Angle = m_rotation; charMarkerSymbol.Size = m_size; charMarkerSymbol.Font = ESRI.ArcGIS.ADF.Connection.Local.Converter.ToStdFont(new Font("ESRI Default Marker", (float)m_size, FontStyle.Regular)); charMarkerSymbol.CharacterIndex = 184; IMarkerElement markerElement = new MarkerElementClass(); markerElement.Symbol = (IMarkerSymbol)charMarkerSymbol; IPoint point = ((IClone)m_pointGeometry).Clone() as IPoint; IElement element = (IElement)markerElement; element.Geometry = (IGeometry)point; return element; } public bool IsSupportedAtVersion(esriArcGISVersion docVersion) { //support all versions except 8.3 if (esriArcGISVersion.esriArcGISVersion83 == docVersion) return false; else return true; } #endregion #region private methods private IClone Clone(object obj) { if (null == obj || !(obj is IClone)) return null; return ((IClone)obj).Clone(); } private int TwipsPerPixelX() { return 16; } private int TwipsPerPixelY() { return 16; } private void SetupDeviceRatio(int hDC, ESRI.ArcGIS.Display.IDisplay display) { if (display.DisplayTransformation != null) { if (display.DisplayTransformation.Resolution != 0) { m_dDeviceRatio = display.DisplayTransformation.Resolution / 72; // Check the ReferenceScale of the display transformation. If not zero, we need to // adjust the Size, XOffset and YOffset of the Symbol we hold internally before drawing. if (display.DisplayTransformation.ReferenceScale != 0) m_dDeviceRatio = m_dDeviceRatio * display.DisplayTransformation.ReferenceScale / display.DisplayTransformation.ScaleRatio; } } else { // If we don't have a display transformation, calculate the resolution // from the actual device. if (display.hDC != 0) { // Get the resolution from the device context hDC. m_dDeviceRatio = System.Convert.ToDouble(GetDeviceCaps(hDC, LOGPIXELSX)) / 72; } else { // If invalid hDC assume we're drawing to the screen. m_dDeviceRatio = 1 / (TwipsPerPixelX() / 20); // 1 Point = 20 Twips. } } } private double PointsToMap(IDisplayTransformation displayTransform, double dPointSize) { double tempPointsToMap = 0; if (displayTransform == null) tempPointsToMap = dPointSize * m_dDeviceRatio; else { tempPointsToMap = displayTransform.FromPoints(dPointSize); } return tempPointsToMap; } private void BuildTriangleGeometry(IPoint pointGeometry) { try { if (null == m_triangle || null == pointGeometry || null == m_cachedDisplay) return; m_triangle.SpatialReference = pointGeometry.SpatialReference; m_triangle.SetEmpty(); object missing = System.Reflection.Missing.Value; IPointCollection pointCollection = (IPointCollection)m_triangle; double radius = PointsToMap(m_cachedDisplay.DisplayTransformation, m_size); double X = pointGeometry.X; double Y = pointGeometry.Y; IPoint point = new PointClass(); point.X = X + radius * c_Cosine30; point.Y = Y - 0.5 * radius; pointCollection.AddPoint(point, ref missing, ref missing); point = new PointClass(); point.X = X; point.Y = Y + radius; pointCollection.AddPoint(point, ref missing, ref missing); point = new PointClass(); point.X = X - radius * c_Cosine30; point.Y = Y - 0.5 * radius; pointCollection.AddPoint(point, ref missing, ref missing); m_triangle.Close(); if (m_rotation != 0.0) { ((ITransform2D)pointCollection).Rotate(pointGeometry, m_rotation * c_Deg2Rad); } return; } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } private void SetDefaultDymbol() { IColor color = (IColor)ESRI.ArcGIS.ADF.Connection.Local.Converter.ToRGBColor(Color.Black); ISimpleLineSymbol lineSymbol = new SimpleLineSymbolClass(); lineSymbol.Style = esriSimpleLineStyle.esriSLSSolid; lineSymbol.Width = 1.0; lineSymbol.Color = color; color = (IColor)ESRI.ArcGIS.ADF.Connection.Local.Converter.ToRGBColor(Color.Navy); if (null == m_fillSymbol) m_fillSymbol = new SimpleFillSymbolClass(); m_fillSymbol.Color = color; m_fillSymbol.Style = esriSimpleFillStyle.esriSFSSolid; m_fillSymbol.Outline = (ILineSymbol)lineSymbol; } /// <summary> /// assign the triangle's geometry to the selection tracker /// </summary> private void RefreshTracker() { if (null == m_cachedDisplay) return; m_selectionTracker.Display = (IScreenDisplay)m_cachedDisplay; IPolygon outline = new PolygonClass(); this.QueryOutline(m_cachedDisplay, outline); m_selectionTracker.Geometry = (IGeometry)outline; } private void UpdateElementSpatialRef() { if (null == m_cachedDisplay || null == m_nativeSR || null == m_triangle || null == m_cachedDisplay.DisplayTransformation.SpatialReference) return; if (null == m_triangle.SpatialReference) m_triangle.SpatialReference = m_cachedDisplay.DisplayTransformation.SpatialReference; m_triangle.Project(m_nativeSR); RefreshTracker(); } private void InitMembers() { //initialize the selection tracker m_selectionTracker = new PolygonTrackerClass(); m_selectionTracker.Locked = false; m_selectionTracker.ShowHandles = true; //set a default symbol SetDefaultDymbol(); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Simple.Mocking.SetUp.Proxies { public class Invocation : IInvocation { IProxy target; MethodInfo method; IList<Type> genericArguments; IList<object> parameterValues; object returnValue; long invocationOrder; internal Invocation(IProxy target, MethodInfo method, IList<Type> genericArguments, IList<object> parameterValues, object returnValue, long invocationOrder) { this.target = target; this.method = method; this.genericArguments = (genericArguments != null ? new GenericArgumentsList(genericArguments) : null); this.parameterValues = new ParameterList(this, parameterValues); this.returnValue = returnValue; this.invocationOrder = invocationOrder; } public IProxy Target { get { return target; } } public MethodInfo Method { get { return method; } } public IList<Type> GenericArguments { get { return genericArguments; } } public IList<object> ParameterValues { get { return parameterValues; } } public object ReturnValue { set { AssertMethodReturnValueIsAssignable(value); returnValue = value; } internal get { return returnValue; } } public long InvocationOrder { get { return invocationOrder; } } public static object HandleInvocation( IProxy target, InvocationFactory invocationFactory, Type[] genericArguments, object[] parameterValues, object returnValue) { var invocation = invocationFactory.CreateInvocation(target, genericArguments, parameterValues, returnValue); var invocationInterceptor = target.InvocationInterceptor; invocationInterceptor.OnInvocation(invocation); return invocation.returnValue; } void AssertMethodParameterIsAssignable(int index, object value) { var parameterType = GetNonGenericMethod(this).GetParameters()[index].ParameterType; if (!parameterType.IsByRef) { throw new InvalidOperationException( string.Format("Can not set parameter {0} of method '{1}' (not an out or ref parameter)", index, method)); } if (!parameterType.GetElementType().IsAssignable(value)) { throw new InvalidOperationException( string.Format("Can not set parameter {0} of method '{1}' (value '{2}' is not assignable)", index, method, value)); } } void AssertMethodReturnValueIsAssignable(object value) { var returnType = GetNonGenericMethod(this).ReturnType; if (returnType == typeof(void)) { throw new InvalidOperationException( string.Format("Can not return value from method '{0}' (return type is void)", method)); } if (!returnType.IsAssignable(value)) { throw new InvalidOperationException( string.Format("Can not return value of method '{0}' (value '{1}' is not assignable)", method, value)); } } public override string ToString() { return InvocationFormatter.Format(target, method, genericArguments, parameterValues); } public static MethodInfo GetNonGenericMethod(IInvocation invocation) { var method = invocation.Method; var genericArguments = invocation.GenericArguments; return (genericArguments != null ? method.MakeGenericMethod(genericArguments.ToArray()) : method); } class ListWithRestrictedAccess<T> : IList<T> { private IList<T> list; protected ListWithRestrictedAccess(IList<T> list) { this.list = list; } public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public virtual void Add(T item) { throw new NotSupportedException(); } public virtual void Clear() { throw new NotSupportedException(); } public bool Contains(T item) { return list.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } public virtual bool Remove(T item) { throw new NotSupportedException(); } public int Count { get { return list.Count; } } public virtual bool IsReadOnly { get { return list.IsReadOnly; } } public int IndexOf(T item) { return list.IndexOf(item); } public virtual void Insert(int index, T item) { throw new NotSupportedException(); } public virtual void RemoveAt(int index) { throw new NotSupportedException(); } public virtual T this[int index] { get { return list[index]; } set { SetItem(index, value); } } protected virtual void SetItem(int index, T value) { list[index] = value; } } class GenericArgumentsList : ListWithRestrictedAccess<Type> { public GenericArgumentsList(IList<Type> list) : base(list) { } protected override void SetItem(int index, Type value) { throw new NotSupportedException(); } } class ParameterList : ListWithRestrictedAccess<object> { Invocation invocation; public ParameterList(Invocation invocation, IList<object> list) : base(list) { this.invocation = invocation; } protected override void SetItem(int index, object value) { invocation.AssertMethodParameterIsAssignable(index, value); base.SetItem(index, value); } } } }