context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.IO; using System.Text; using Rhapsody.Core.Tags.Id3v2.Frames; using Rhapsody.Utilities; namespace Rhapsody.Core.Tags.Id3v2 { internal class Id3Tagv2 { private static readonly byte[] Id3TagV2Signature = {0x49, 0x44, 0x33}; // ID3 public FrameCollection Frames { get; private set; } public Version Version { get; set; } public bool Unsynchronise { get; set; } public int PaddingSize { get; set; } public Id3Tagv2() { Frames = new FrameCollection(); } public void WriteTo(Stream stream) { if (Version.Major == 3) { if (Version.Minor != 0) throw new NotSupportedException(); WriteV3To(stream); return; } throw new NotSupportedException(); } private void WriteV3To(Stream stream) { if (Frames.Count == 0) throw new Exception("There must be at least one frame in the tag."); var writer = new BinaryWriter(stream); var framesBytes = GetFramesBytesV3(); var headerFlags = TagHeaderFlags.None; if (Unsynchronise) { if (UnsynchroniseBuffer(ref framesBytes)) headerFlags |= TagHeaderFlags.Unsynchronisation; } writer.Write(Id3TagV2Signature); writer.Write((byte)Version.Major); writer.Write((byte)Version.Minor); writer.Write((byte)headerFlags); writer.Write(EndianHelper.LittleToBigEndianInt32(framesBytes.Length, true)); writer.Write(framesBytes); var padding = new byte[PaddingSize]; writer.Write(padding); writer.Flush(); } private byte[] GetFramesBytesV3() { using (var stream = new MemoryStream()) { using (var writer = new BinaryWriter(stream)) { foreach (var frame in Frames) { var flags = FrameHeaderFlagsV3.None; var frameData = frame.GetBytes(); if (frameData.Length == 0) throw new Exception("A frame must be at least one byte big."); writer.Write(Encoding.ASCII.GetBytes(frame.Id)); writer.Write(EndianHelper.LittleToBigEndianInt32(frameData.Length)); writer.Write(EndianHelper.LittleToBigEndianInt16((short)flags)); writer.Write(frameData); } } return stream.ToArray(); } } private static bool UnsynchroniseBuffer(ref byte[] data) { var stream = new MemoryStream(data.Length); byte lastByte = 0; var unsynchronised = false; foreach (byte b in data) { if (lastByte == 0xFF) { if (b == 0 || (b & 0xE0) == 0xE0) { stream.WriteByte(0); unsynchronised = true; } } stream.WriteByte(b); lastByte = b; } if (unsynchronised) data = stream.ToArray(); return unsynchronised; } public static Id3Tagv2 Load(string path) { using (var stream = File.OpenRead(path)) return Load(stream); } public static Id3Tagv2 Load(Stream stream) { var reader = new BinaryReader(stream); var signature = reader.ReadBytes(3); if (!ArrayHelper.CompareArray(signature, Id3TagV2Signature)) return null; var versionMajor = reader.ReadByte(); var versionMinor = reader.ReadByte(); if (versionMajor == 0xff || versionMinor == 0xff) return null; if (versionMajor == 4) return LoadV4(reader, versionMinor); if (versionMajor == 3) return LoadV3(reader, versionMinor); return null; } private static Id3Tagv2 LoadV4(BinaryReader reader, byte versionMinor) { var tag = new Id3Tagv2(); tag.Version = new Version(4, versionMinor); var headerFlags = (TagHeaderFlags)reader.ReadByte(); if (headerFlags.HasFlag(TagHeaderFlags.Unsynchronisation)) throw new NotSupportedException(); if (headerFlags.HasFlag(TagHeaderFlags.ExtendedHeader)) throw new NotSupportedException(); if (headerFlags.HasFlag(TagHeaderFlags.FooterPresent)) throw new NotSupportedException(); var tagSize = EndianHelper.BigToLittleEndianInt32(reader.ReadBytes(4), true); var offset = 0; while (offset < tagSize) { if (reader.PeekChar() == 0) { tag.PaddingSize = tagSize - offset; break; } var frameId = new string(reader.ReadChars(4)); var frameSize = EndianHelper.BigToLittleEndianInt32(reader.ReadBytes(4), true); var frameFlags = (FrameHeaderFlagsV4)EndianHelper.BigToLittleEndianInt16(reader.ReadBytes(2)); if (frameFlags.HasFlag(FrameHeaderFlagsV4.GroupingIdentity)) throw new NotSupportedException(); if (frameFlags.HasFlag(FrameHeaderFlagsV4.Compression)) throw new NotSupportedException(); if (frameFlags.HasFlag(FrameHeaderFlagsV4.Encryption)) throw new NotSupportedException(); if (frameFlags.HasFlag(FrameHeaderFlagsV4.Unsynchronisation)) throw new NotSupportedException(); if (frameFlags.HasFlag(FrameHeaderFlagsV4.DataLengthIndicator)) throw new NotSupportedException(); var frameData = reader.ReadBytes(frameSize); var frame = GetFrame(frameId, frameData); tag.Frames.Add(frame); offset += frameSize + 10; } return tag; } private static Id3Tagv2 LoadV3(BinaryReader reader, byte versionMinor) { var tag = new Id3Tagv2(); tag.Version = new Version(3, versionMinor); var headerFlags = (TagHeaderFlags)reader.ReadByte(); if (headerFlags.HasFlag(TagHeaderFlags.Unsynchronisation)) throw new NotSupportedException(); if (headerFlags.HasFlag(TagHeaderFlags.ExtendedHeader)) throw new NotSupportedException(); var tagSize = EndianHelper.BigToLittleEndianInt32(reader.ReadBytes(4), true); var offset = 0; while (offset < tagSize) { if (reader.PeekChar() == 0) { tag.PaddingSize = tagSize - offset; break; } var frameId = new string(reader.ReadChars(4)); var frameSize = EndianHelper.BigToLittleEndianInt32(reader.ReadBytes(4)); var frameFlags = (FrameHeaderFlagsV3)EndianHelper.BigToLittleEndianInt16(reader.ReadBytes(2)); if (frameFlags.HasFlag(FrameHeaderFlagsV3.Compression)) throw new NotSupportedException(); if (frameFlags.HasFlag(FrameHeaderFlagsV3.Encryption)) throw new NotSupportedException(); if (frameFlags.HasFlag(FrameHeaderFlagsV3.GroupingIdentity)) throw new NotSupportedException(); var frameData = reader.ReadBytes(frameSize); var frame = GetFrame(frameId, frameData); tag.Frames.Add(frame); offset += frameSize + 10; } return tag; } private static Frame GetFrame(string frameId, byte[] frameData) { if (frameId == TrckFrame.FrameId) return new TrckFrame(frameData); if (frameId == Tit2Frame.FrameId) return new Tit2Frame(frameData); if (frameId == TyerFrame.FrameId) return new TyerFrame(frameData); if (frameId == TalbFrame.FrameId) return new TalbFrame(frameData); if (frameId == Tpe1Frame.FrameId) return new Tpe1Frame(frameData); if (frameId == TsstFrame.FrameId) return new TsstFrame(frameData); if (frameId.StartsWith("T")) return new TextFrame(frameId, frameData); if (frameId == ApicFrame.FrameId) return new ApicFrame(frameData); if (frameId == PrivFrame.FrameId) return new PrivFrame(frameData); return new UnknownFrame(frameId, frameData); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using Avalonia.Data; #nullable enable namespace Avalonia.Animation { /// <summary> /// Base class for all animatable objects. /// </summary> public class Animatable : AvaloniaObject { /// <summary> /// Defines the <see cref="Clock"/> property. /// </summary> public static readonly StyledProperty<IClock> ClockProperty = AvaloniaProperty.Register<Animatable, IClock>(nameof(Clock), inherits: true); /// <summary> /// Defines the <see cref="Transitions"/> property. /// </summary> public static readonly StyledProperty<Transitions?> TransitionsProperty = AvaloniaProperty.Register<Animatable, Transitions?>(nameof(Transitions)); private bool _transitionsEnabled = true; private Dictionary<ITransition, TransitionState>? _transitionState; /// <summary> /// Gets or sets the clock which controls the animations on the control. /// </summary> public IClock Clock { get => GetValue(ClockProperty); set => SetValue(ClockProperty, value); } /// <summary> /// Gets or sets the property transitions for the control. /// </summary> public Transitions? Transitions { get => GetValue(TransitionsProperty); set => SetValue(TransitionsProperty, value); } /// <summary> /// Enables transitions for the control. /// </summary> /// <remarks> /// This method should not be called from user code, it will be called automatically by the framework /// when a control is added to the visual tree. /// </remarks> protected void EnableTransitions() { if (!_transitionsEnabled) { _transitionsEnabled = true; if (Transitions is object) { AddTransitions(Transitions); } } } /// <summary> /// Disables transitions for the control. /// </summary> /// <remarks> /// This method should not be called from user code, it will be called automatically by the framework /// when a control is added to the visual tree. /// </remarks> protected void DisableTransitions() { if (_transitionsEnabled) { _transitionsEnabled = false; if (Transitions is object) { RemoveTransitions(Transitions); } } } protected sealed override void OnPropertyChangedCore<T>(AvaloniaPropertyChangedEventArgs<T> change) { if (change.Property == TransitionsProperty && change.IsEffectiveValueChange) { var oldTransitions = change.OldValue.GetValueOrDefault<Transitions>(); var newTransitions = change.NewValue.GetValueOrDefault<Transitions>(); // When transitions are replaced, we add the new transitions before removing the old // transitions, so that when the old transition being disposed causes the value to // change, there is a corresponding entry in `_transitionStates`. This means that we // need to account for any transitions present in both the old and new transitions // collections. if (newTransitions is object) { var toAdd = (IList)newTransitions; if (newTransitions.Count > 0 && oldTransitions?.Count > 0) { toAdd = newTransitions.Except(oldTransitions).ToList(); } newTransitions.CollectionChanged += TransitionsCollectionChanged; AddTransitions(toAdd); } if (oldTransitions is object) { var toRemove = (IList)oldTransitions; if (oldTransitions.Count > 0 && newTransitions?.Count > 0) { toRemove = oldTransitions.Except(newTransitions).ToList(); } oldTransitions.CollectionChanged -= TransitionsCollectionChanged; RemoveTransitions(toRemove); } } else if (_transitionsEnabled && Transitions is object && _transitionState is object && !change.Property.IsDirect && change.Priority > BindingPriority.Animation) { for (var i = Transitions.Count -1; i >= 0; --i) { var transition = Transitions[i]; if (transition.Property == change.Property && _transitionState.TryGetValue(transition, out var state)) { var oldValue = state.BaseValue; var newValue = GetAnimationBaseValue(transition.Property); if (!Equals(oldValue, newValue)) { state.BaseValue = newValue; // We need to transition from the current animated value if present, // instead of the old base value. var animatedValue = GetValue(transition.Property); if (!Equals(newValue, animatedValue)) { oldValue = animatedValue; } state.Instance?.Dispose(); state.Instance = transition.Apply( this, Clock ?? AvaloniaLocator.Current.GetService<IGlobalClock>(), oldValue, newValue); return; } } } } base.OnPropertyChangedCore(change); } private void TransitionsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (!_transitionsEnabled) { return; } switch (e.Action) { case NotifyCollectionChangedAction.Add: AddTransitions(e.NewItems); break; case NotifyCollectionChangedAction.Remove: RemoveTransitions(e.OldItems); break; case NotifyCollectionChangedAction.Replace: RemoveTransitions(e.OldItems); AddTransitions(e.NewItems); break; case NotifyCollectionChangedAction.Reset: throw new NotSupportedException("Transitions collection cannot be reset."); } } private void AddTransitions(IList items) { if (!_transitionsEnabled) { return; } _transitionState ??= new Dictionary<ITransition, TransitionState>(); for (var i = 0; i < items.Count; ++i) { var t = (ITransition)items[i]; _transitionState.Add(t, new TransitionState { BaseValue = GetAnimationBaseValue(t.Property), }); } } private void RemoveTransitions(IList items) { if (_transitionState is null) { return; } for (var i = 0; i < items.Count; ++i) { var t = (ITransition)items[i]; if (_transitionState.TryGetValue(t, out var state)) { state.Instance?.Dispose(); _transitionState.Remove(t); } } } private object GetAnimationBaseValue(AvaloniaProperty property) { var value = this.GetBaseValue(property, BindingPriority.LocalValue); if (value == AvaloniaProperty.UnsetValue) { value = GetValue(property); } return value; } private class TransitionState { public IDisposable? Instance { get; set; } public object? BaseValue { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans.Runtime; using Orleans.Streams; using Orleans.TestingHost; using Orleans.TestingHost.Utils; using UnitTests.GrainInterfaces; using Xunit; namespace UnitTests.StreamingTests { public class SubscriptionMultiplicityTestRunner { private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); private readonly string streamProviderName; private readonly ILogger logger; private readonly TestCluster testCluster; public SubscriptionMultiplicityTestRunner(string streamProviderName, TestCluster testCluster) { if (string.IsNullOrWhiteSpace(streamProviderName)) { throw new ArgumentNullException("streamProviderName"); } this.streamProviderName = streamProviderName; this.logger = testCluster.Client.ServiceProvider.GetRequiredService<ILogger<SubscriptionMultiplicityTestRunner>>(); this.testCluster = testCluster; } public async Task MultipleParallelSubscriptionTest(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = this.testCluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = this.testCluster.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); // setup two subscriptions StreamSubscriptionHandle<int> firstSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); StreamSubscriptionHandle<int> secondSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); // produce some messages await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); // check await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 2, lastTry), Timeout); // unsubscribe await consumer.StopConsuming(firstSubscriptionHandle); await consumer.StopConsuming(secondSubscriptionHandle); } public async Task MultipleLinearSubscriptionTest(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = this.testCluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = this.testCluster.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); // setup one subscription and send messsages StreamSubscriptionHandle<int> firstSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // clear counts await consumer.ClearNumberConsumed(); await producer.ClearNumberProduced(); // remove first subscription and send messages await consumer.StopConsuming(firstSubscriptionHandle); // setup second subscription and send messages StreamSubscriptionHandle<int> secondSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // remove second subscription await consumer.StopConsuming(secondSubscriptionHandle); } public async Task MultipleSubscriptionTest_AddRemove(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = this.testCluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = this.testCluster.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); // setup one subscription and send messsages StreamSubscriptionHandle<int> firstSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // clear counts await consumer.ClearNumberConsumed(); await producer.ClearNumberProduced(); // setup second subscription and send messages StreamSubscriptionHandle<int> secondSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 2, lastTry), Timeout); // clear counts await consumer.ClearNumberConsumed(); await producer.ClearNumberProduced(); // remove first subscription and send messages await consumer.StopConsuming(firstSubscriptionHandle); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // remove second subscription await consumer.StopConsuming(secondSubscriptionHandle); } public async Task ResubscriptionTest(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = this.testCluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = this.testCluster.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); // setup one subscription and send messsages StreamSubscriptionHandle<int> firstSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // Resume StreamSubscriptionHandle<int> resumeHandle = await consumer.Resume(firstSubscriptionHandle); Assert.Equal(firstSubscriptionHandle, resumeHandle); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // remove subscription await consumer.StopConsuming(resumeHandle); } public async Task ResubscriptionAfterDeactivationTest(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = this.testCluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = this.testCluster.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); // setup one subscription and send messsages StreamSubscriptionHandle<int> firstSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // Deactivate grain await consumer.Deactivate(); // make sure grain has time to deactivate. await Task.Delay(TimeSpan.FromMilliseconds(100)); // clear producer counts await producer.ClearNumberProduced(); // Resume StreamSubscriptionHandle<int> resumeHandle = await consumer.Resume(firstSubscriptionHandle); Assert.Equal(firstSubscriptionHandle, resumeHandle); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // remove subscription await consumer.StopConsuming(resumeHandle); } public async Task ActiveSubscriptionTest(Guid streamGuid, string streamNamespace) { const int subscriptionCount = 10; // get producer and consumer var consumer = this.testCluster.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); // create expected subscriptions IEnumerable<Task<StreamSubscriptionHandle<int>>> subscriptionTasks = Enumerable.Range(0, subscriptionCount) .Select(async i => await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName)); List<StreamSubscriptionHandle<int>> expectedSubscriptions = (await Task.WhenAll(subscriptionTasks)).ToList(); // query actuall subscriptions IList<StreamSubscriptionHandle<int>> actualSubscriptions = await consumer.GetAllSubscriptions(streamGuid, streamNamespace, streamProviderName); // validate Assert.Equal(subscriptionCount, actualSubscriptions.Count); Assert.Equal(subscriptionCount, expectedSubscriptions.Count); foreach (StreamSubscriptionHandle<int> subscription in actualSubscriptions) { Assert.True(expectedSubscriptions.Contains(subscription), "Subscription Match"); } // unsubscribe from one of the subscriptions StreamSubscriptionHandle<int> firstHandle = expectedSubscriptions.First(); await consumer.StopConsuming(firstHandle); expectedSubscriptions.Remove(firstHandle); // query actuall subscriptions again actualSubscriptions = await consumer.GetAllSubscriptions(streamGuid, streamNamespace, streamProviderName); // validate Assert.Equal(subscriptionCount-1, actualSubscriptions.Count); Assert.Equal(subscriptionCount-1, expectedSubscriptions.Count); foreach (StreamSubscriptionHandle<int> subscription in actualSubscriptions) { Assert.True(expectedSubscriptions.Contains(subscription), "Subscription Match"); } // unsubscribe from the rest of the subscriptions expectedSubscriptions.ForEach( async h => await consumer.StopConsuming(h)); // query actuall subscriptions again actualSubscriptions = await consumer.GetAllSubscriptions(streamGuid, streamNamespace, streamProviderName); // validate Assert.Equal(0, actualSubscriptions.Count); } public async Task TwoIntermitentStreamTest(Guid streamGuid) { const string streamNamespace1 = "streamNamespace1"; const string streamNamespace2 = "streamNamespace2"; // send events on first stream ///////////////////////////// var producer = this.testCluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = this.testCluster.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamGuid, streamNamespace1, streamProviderName); StreamSubscriptionHandle<int> handle = await consumer.BecomeConsumer(streamGuid, streamNamespace1, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // send some events on second stream ///////////////////////////// var producer2 = this.testCluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer2 = this.testCluster.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer2.BecomeProducer(streamGuid, streamNamespace2, streamProviderName); StreamSubscriptionHandle<int> handle2 = await consumer2.BecomeConsumer(streamGuid, streamNamespace2, streamProviderName); await producer2.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer2.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer2, consumer2, 1, lastTry), Timeout); // send some events on first stream again ///////////////////////////// await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); await consumer.StopConsuming(handle); await consumer2.StopConsuming(handle2); } public async Task SubscribeFromClientTest(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = this.testCluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); int eventCount = 0; var provider = this.testCluster.Client.ServiceProvider.GetServiceByName<IStreamProvider>(streamProviderName); var stream = provider.GetStream<int>(streamGuid, streamNamespace); var handle = await stream.SubscribeAsync((e,t) => { eventCount++; return Task.CompletedTask; }); // produce some messages await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); // check await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, () => eventCount, lastTry), Timeout); // unsubscribe await handle.UnsubscribeAsync(); } private async Task<bool> CheckCounters(ISampleStreaming_ProducerGrain producer, IMultipleSubscriptionConsumerGrain consumer, int consumerCount, bool assertIsTrue) { var numProduced = await producer.GetNumberProduced(); var numConsumed = await consumer.GetNumberConsumed(); if (assertIsTrue) { Assert.True(numConsumed.Values.All(v => v.Item2 == 0), "Errors"); Assert.True(numProduced > 0, "Events were not produced"); Assert.Equal(consumerCount, numConsumed.Count); foreach (int consumed in numConsumed.Values.Select(v => v.Item1)) { Assert.Equal(numProduced, consumed); } } else if (numProduced <= 0 || // no events produced? consumerCount != numConsumed.Count || // subscription counts are wrong? numConsumed.Values.Any(consumedCount => consumedCount.Item1 != numProduced) ||// consumed events don't match produced events for any subscription? numConsumed.Values.Any(v => v.Item2 != 0)) // stream errors { if (numProduced <= 0) { logger.Info("numProduced <= 0: Events were not produced"); } if (consumerCount != numConsumed.Count) { logger.Info("consumerCount != numConsumed.Count: Incorrect number of consumers. consumerCount = {0}, numConsumed.Count = {1}", consumerCount, numConsumed.Count); } foreach (var consumed in numConsumed) { if (numProduced != consumed.Value.Item1) { logger.Info("numProduced != consumed: Produced and consumed counts do not match. numProduced = {0}, consumed = {1}", numProduced, consumed.Key.HandleId + " -> " + consumed.Value); //numProduced, Utils.DictionaryToString(numConsumed)); } } return false; } logger.Info("All counts are equal. numProduced = {0}, numConsumed = {1}", numProduced, Utils.EnumerableToString(numConsumed, kvp => kvp.Key.HandleId.ToString() + "->" + kvp.Value.ToString())); return true; } private async Task<bool> CheckCounters(ISampleStreaming_ProducerGrain producer, Func<int> eventCount, bool assertIsTrue) { var numProduced = await producer.GetNumberProduced(); var numConsumed = eventCount(); if (assertIsTrue) { Assert.True(numProduced > 0, "Events were not produced"); Assert.Equal(numProduced, numConsumed); } else if (numProduced <= 0 || // no events produced? numProduced != numConsumed) { if (numProduced <= 0) { logger.Info("numProduced <= 0: Events were not produced"); } if (numProduced != numConsumed) { logger.Info("numProduced != numConsumed: Produced and consumed counts do not match. numProduced = {0}, consumed = {1}", numProduced, numConsumed); } return false; } logger.Info("All counts are equal. numProduced = {0}, numConsumed = {1}", numProduced, numConsumed); return true; } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Transactions { using System; using System.Diagnostics.CodeAnalysis; using System.Runtime; using System.ServiceModel.Channels; using System.ServiceModel; using System.IO; using System.Net; using System.Security; using System.ServiceModel.ComIntegration; using System.ServiceModel.Security; using System.Transactions; using Microsoft.Transactions.Wsat.Messaging; using Microsoft.Transactions.Wsat.Protocol; using Microsoft.Transactions.Wsat.Recovery; class TransactionManagerConfigurationException : TransactionException { public TransactionManagerConfigurationException(string error, Exception e) : base(error, e) { } public TransactionManagerConfigurationException(string error) : base(error) { } } class WsatConfiguration { static readonly string DisabledRegistrationPath; const string WsatKey = @"Software\Microsoft\WSAT\3.0"; const string OleTxUpgradeEnabledValue = "OleTxUpgradeEnabled"; const bool OleTxUpgradeEnabledDefault = true; bool oleTxUpgradeEnabled; EndpointAddress localActivationService10; EndpointAddress localActivationService11; EndpointAddress remoteActivationService10; EndpointAddress remoteActivationService11; Uri registrationServiceAddress10; Uri registrationServiceAddress11; bool protocolService10Enabled = false; bool protocolService11Enabled = false; bool inboundEnabled; bool issuedTokensEnabled; TimeSpan maxTimeout; [SuppressMessage(FxCop.Category.Security, FxCop.Rule.AptcaMethodsShouldOnlyCallAptcaMethods, Justification = "The calls to BindingStrings are safe.")] static WsatConfiguration() { DisabledRegistrationPath = string.Concat(BindingStrings.AddressPrefix, "/", BindingStrings.RegistrationCoordinatorSuffix(ProtocolVersion.Version10), BindingStrings.DisabledSuffix); } [SuppressMessage(FxCop.Category.Security, FxCop.Rule.AptcaMethodsShouldOnlyCallAptcaMethods, Justification = "The calls to ProtocolInformationReader.IsV10Enabled and IsV11Enabled are safe.")] public WsatConfiguration() { // Get whereabouts WhereaboutsReader whereabouts = GetWhereabouts(); ProtocolInformationReader protocol = whereabouts.ProtocolInformation; if (protocol != null) { this.protocolService10Enabled = protocol.IsV10Enabled; this.protocolService11Enabled = protocol.IsV11Enabled; } Initialize(whereabouts); // Read local registry flag this.oleTxUpgradeEnabled = ReadFlag(WsatKey, OleTxUpgradeEnabledValue, OleTxUpgradeEnabledDefault); } void Initialize(WhereaboutsReader whereabouts) { // MB 47153: don't throw system exception if whereabouts data is broken try { InitializeForUnmarshal(whereabouts); InitializeForMarshal(whereabouts); } catch (UriFormatException e) { // UriBuilder.Uri can throw this if the URI is ultimately invalid throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new TransactionManagerConfigurationException(SR.GetString(SR.WsatUriCreationFailed), e)); } catch (ArgumentOutOfRangeException e) { // UriBuilder constructor can throw this if port < 0 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new TransactionManagerConfigurationException(SR.GetString(SR.WsatUriCreationFailed), e)); } } public bool OleTxUpgradeEnabled { get { return this.oleTxUpgradeEnabled; } } public TimeSpan MaxTimeout { get { return this.maxTimeout; } } public bool IssuedTokensEnabled { get { return this.issuedTokensEnabled; } } public bool InboundEnabled { get { return this.inboundEnabled; } } public bool IsProtocolServiceEnabled(ProtocolVersion protocolVersion) { switch (protocolVersion) { case ProtocolVersion.Version10: return this.protocolService10Enabled; case ProtocolVersion.Version11: return this.protocolService11Enabled; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentException(SR.GetString(SR.InvalidWsatProtocolVersion))); } } public EndpointAddress LocalActivationService(ProtocolVersion protocolVersion) { switch (protocolVersion) { case ProtocolVersion.Version10: return this.localActivationService10; case ProtocolVersion.Version11: return this.localActivationService11; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentException(SR.GetString(SR.InvalidWsatProtocolVersion))); } } public EndpointAddress RemoteActivationService(ProtocolVersion protocolVersion) { switch (protocolVersion) { case ProtocolVersion.Version10: return this.remoteActivationService10; case ProtocolVersion.Version11: return this.remoteActivationService11; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentException(SR.GetString(SR.InvalidWsatProtocolVersion))); } } public EndpointAddress CreateRegistrationService(AddressHeader refParam, ProtocolVersion protocolVersion) { switch (protocolVersion) { case ProtocolVersion.Version10: return new EndpointAddress(this.registrationServiceAddress10, refParam); case ProtocolVersion.Version11: return new EndpointAddress(this.registrationServiceAddress11, refParam); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentException(SR.GetString(SR.InvalidWsatProtocolVersion))); } } public bool IsLocalRegistrationService(EndpointAddress endpoint, ProtocolVersion protocolVersion) { if (endpoint.Uri == null) return false; switch (protocolVersion) { case ProtocolVersion.Version10: return endpoint.Uri == this.registrationServiceAddress10; case ProtocolVersion.Version11: return endpoint.Uri == this.registrationServiceAddress11; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentException(SR.GetString(SR.InvalidWsatProtocolVersion))); } } public bool IsDisabledRegistrationService(EndpointAddress endpoint) { return endpoint.Uri.AbsolutePath == DisabledRegistrationPath; } // // Internals // WhereaboutsReader GetWhereabouts() { try { return new WhereaboutsReader(TransactionInterop.GetWhereabouts()); } catch (SerializationException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new TransactionManagerConfigurationException(SR.GetString(SR.WhereaboutsReadFailed), e)); } // If GetWhereabouts throws TransactionException, let it propagate } [SuppressMessage(FxCop.Category.Security, FxCop.Rule.AptcaMethodsShouldOnlyCallAptcaMethods, Justification = "The calls to the ProtocolInformationReader properties and to BindingStrings.RegistrationCoordinatorSuffix(..) are safe.")] void InitializeForUnmarshal(WhereaboutsReader whereabouts) { ProtocolInformationReader protocol = whereabouts.ProtocolInformation; if (protocol != null && protocol.NetworkInboundAccess) { this.inboundEnabled = true; bool isTmLocal = string.Compare(Environment.MachineName, protocol.NodeName, StringComparison.OrdinalIgnoreCase) == 0; string spnIdentity; string activationCoordinatorSuffix10 = BindingStrings.ActivationCoordinatorSuffix(ProtocolVersion.Version10); string activationCoordinatorSuffix11 = BindingStrings.ActivationCoordinatorSuffix(ProtocolVersion.Version11); if (protocol.IsClustered || (protocol.NetworkClientAccess && !isTmLocal)) { if (protocol.IsClustered) { // We cannot reliably perform mutual authentication against a clustered resource // See MB 43523 for more details on this spnIdentity = null; } else { spnIdentity = "host/" + protocol.HostName; } if (protocol.IsV10Enabled) { this.remoteActivationService10 = CreateActivationEndpointAddress(protocol, activationCoordinatorSuffix10, spnIdentity, true); } if (protocol.IsV11Enabled) { this.remoteActivationService11 = CreateActivationEndpointAddress(protocol, activationCoordinatorSuffix11, spnIdentity, true); } } if (isTmLocal) { spnIdentity = "host/" + protocol.NodeName; // The net.pipe Activation endpoint uses the host name as a discriminant // for cluster scenarios with more than one service on a node. if (protocol.IsV10Enabled) { this.localActivationService10 = CreateActivationEndpointAddress(protocol, activationCoordinatorSuffix10, spnIdentity, false); } if (protocol.IsV11Enabled) { this.localActivationService11 = CreateActivationEndpointAddress(protocol, activationCoordinatorSuffix11, spnIdentity, false); } } } } [SuppressMessage(FxCop.Category.Security, FxCop.Rule.AptcaMethodsShouldOnlyCallAptcaMethods, Justification = "The calls to the ProtocolInformationReader properties (HostName, HttpsPort, BasePath) are safe.")] EndpointAddress CreateActivationEndpointAddress(ProtocolInformationReader protocol, string suffix, string spnIdentity, bool isRemote) { string uriScheme; string host; int port; string path; if (isRemote) { uriScheme = Uri.UriSchemeHttps; host = protocol.HostName; port = protocol.HttpsPort; path = protocol.BasePath + "/" + suffix + BindingStrings.RemoteProxySuffix; } else { uriScheme = Uri.UriSchemeNetPipe; host = "localhost"; port = -1; path = protocol.HostName + "/" + protocol.BasePath + "/" + suffix; } UriBuilder builder = new UriBuilder(uriScheme, host, port, path); if (spnIdentity != null) { EndpointIdentity identity = EndpointIdentity.CreateSpnIdentity(spnIdentity); return new EndpointAddress(builder.Uri, identity); } else { return new EndpointAddress(builder.Uri); } } [SuppressMessage(FxCop.Category.Security, FxCop.Rule.AptcaMethodsShouldOnlyCallAptcaMethods, Justification = "The calls to the ProtocolInformationReader properties and to BindingStrings.RegistrationCoordinatorSuffix(..) are safe.")] void InitializeForMarshal(WhereaboutsReader whereabouts) { ProtocolInformationReader protocol = whereabouts.ProtocolInformation; if (protocol != null && protocol.NetworkOutboundAccess) { // We can marshal outgoing transactions using a valid address if (protocol.IsV10Enabled) { UriBuilder builder10 = new UriBuilder(Uri.UriSchemeHttps, protocol.HostName, protocol.HttpsPort, protocol.BasePath + "/" + BindingStrings.RegistrationCoordinatorSuffix(ProtocolVersion.Version10)); this.registrationServiceAddress10 = builder10.Uri; } // when we have a WSAT1.1 coordinator if (protocol.IsV11Enabled) { UriBuilder builder11 = new UriBuilder(Uri.UriSchemeHttps, protocol.HostName, protocol.HttpsPort, protocol.BasePath + "/" + BindingStrings.RegistrationCoordinatorSuffix(ProtocolVersion.Version11)); this.registrationServiceAddress11 = builder11.Uri; } this.issuedTokensEnabled = protocol.IssuedTokensEnabled; this.maxTimeout = protocol.MaxTimeout; } else { // Generate an address that will not work // We do this in order to generate coordination contexts that can be propagated // between processes on the same node even if WS-AT is disabled UriBuilder builder = new UriBuilder(Uri.UriSchemeHttps, whereabouts.HostName, 443, DisabledRegistrationPath); this.registrationServiceAddress10 = builder.Uri; this.registrationServiceAddress11 = builder.Uri; this.issuedTokensEnabled = false; this.maxTimeout = TimeSpan.FromMinutes(5); } } static object ReadValue(string key, string value) { try { using (RegistryHandle regKey = RegistryHandle.GetNativeHKLMSubkey(key, false)) { if (regKey == null) return null; return regKey.GetValue(value); } } catch (SecurityException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new TransactionManagerConfigurationException(SR.GetString(SR.WsatRegistryValueReadError, value), e)); } catch (IOException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new TransactionManagerConfigurationException(SR.GetString(SR.WsatRegistryValueReadError, value), e)); } } static int ReadInt(string key, string value, int defaultValue) { object regValue = ReadValue(key, value); if (regValue == null || !(regValue is Int32)) return defaultValue; return (int)regValue; } static bool ReadFlag(string key, string value, bool defaultValue) { return (int)ReadInt(key, value, defaultValue ? 1 : 0) != 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Text.RegularExpressions { public partial class Capture { internal Capture() { } public int Index { get { throw null; } } public int Length { get { throw null; } } public string Value { get { throw null; } } public override string ToString() { throw null; } } public partial class CaptureCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Capture>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { internal CaptureCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Text.RegularExpressions.Capture this[int i] { get { throw null; } } public object SyncRoot { get { throw null; } } System.Text.RegularExpressions.Capture System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.this[int index] { get { throw null; } set { } } bool System.Collections.IList.IsFixedSize { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public void CopyTo(System.Array array, int arrayIndex) { } public void CopyTo(System.Text.RegularExpressions.Capture[] array, int arrayIndex) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Add(System.Text.RegularExpressions.Capture item) { } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Clear() { } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Contains(System.Text.RegularExpressions.Capture item) { throw null; } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Remove(System.Text.RegularExpressions.Capture item) { throw null; } System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Capture> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Capture>.GetEnumerator() { throw null; } int System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.IndexOf(System.Text.RegularExpressions.Capture item) { throw null; } void System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.Insert(int index, System.Text.RegularExpressions.Capture item) { } void System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.RemoveAt(int index) { } int System.Collections.IList.Add(object value) { throw null; } void System.Collections.IList.Clear() { } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } void System.Collections.IList.RemoveAt(int index) { } } public partial class Group : System.Text.RegularExpressions.Capture { internal Group() { } public System.Text.RegularExpressions.CaptureCollection Captures { get { throw null; } } public string Name { get { throw null; } } public bool Success { get { throw null; } } public static System.Text.RegularExpressions.Group Synchronized(System.Text.RegularExpressions.Group inner) { throw null; } } public partial class GroupCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Text.RegularExpressions.Group>>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group>, System.Collections.Generic.IList<System.Text.RegularExpressions.Group>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<string, System.Text.RegularExpressions.Group>>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Group>, System.Collections.Generic.IReadOnlyDictionary<string, System.Text.RegularExpressions.Group>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Group>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { internal GroupCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Text.RegularExpressions.Group this[int groupnum] { get { throw null; } } public System.Text.RegularExpressions.Group this[string groupname] { get { throw null; } } public System.Collections.Generic.IEnumerable<string> Keys { get { throw null; } } public object SyncRoot { get { throw null; } } System.Text.RegularExpressions.Group System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.this[int index] { get { throw null; } set { } } bool System.Collections.IList.IsFixedSize { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group> Values { get { throw null; } } public bool ContainsKey(string key) { throw null; } public void CopyTo(System.Array array, int arrayIndex) { } public void CopyTo(System.Text.RegularExpressions.Group[] array, int arrayIndex) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Add(System.Text.RegularExpressions.Group item) { } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Clear() { } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Contains(System.Text.RegularExpressions.Group item) { throw null; } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Remove(System.Text.RegularExpressions.Group item) { throw null; } System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, System.Text.RegularExpressions.Group>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String,System.Text.RegularExpressions.Group>>.GetEnumerator() { throw null; } System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Group> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group>.GetEnumerator() { throw null; } int System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.IndexOf(System.Text.RegularExpressions.Group item) { throw null; } void System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.Insert(int index, System.Text.RegularExpressions.Group item) { } void System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.RemoveAt(int index) { } int System.Collections.IList.Add(object value) { throw null; } void System.Collections.IList.Clear() { } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } void System.Collections.IList.RemoveAt(int index) { } public bool TryGetValue(string key, out System.Text.RegularExpressions.Group value) { throw null; } } public partial class Match : System.Text.RegularExpressions.Group { internal Match() { } public static System.Text.RegularExpressions.Match Empty { get { throw null; } } public virtual System.Text.RegularExpressions.GroupCollection Groups { get { throw null; } } public System.Text.RegularExpressions.Match NextMatch() { throw null; } public virtual string Result(string replacement) { throw null; } public static System.Text.RegularExpressions.Match Synchronized(System.Text.RegularExpressions.Match inner) { throw null; } } public partial class MatchCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Match>, System.Collections.Generic.IList<System.Text.RegularExpressions.Match>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Match>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Match>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { internal MatchCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public virtual System.Text.RegularExpressions.Match this[int i] { get { throw null; } } public object SyncRoot { get { throw null; } } System.Text.RegularExpressions.Match System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.this[int index] { get { throw null; } set { } } bool System.Collections.IList.IsFixedSize { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public void CopyTo(System.Array array, int arrayIndex) { } public void CopyTo(System.Text.RegularExpressions.Match[] array, int arrayIndex) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Add(System.Text.RegularExpressions.Match item) { } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Clear() { } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Contains(System.Text.RegularExpressions.Match item) { throw null; } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Remove(System.Text.RegularExpressions.Match item) { throw null; } System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Match> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Match>.GetEnumerator() { throw null; } int System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.IndexOf(System.Text.RegularExpressions.Match item) { throw null; } void System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.Insert(int index, System.Text.RegularExpressions.Match item) { } void System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.RemoveAt(int index) { } int System.Collections.IList.Add(object value) { throw null; } void System.Collections.IList.Clear() { } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } void System.Collections.IList.RemoveAt(int index) { } } public delegate string MatchEvaluator(System.Text.RegularExpressions.Match match); public partial class Regex : System.Runtime.Serialization.ISerializable { protected internal System.Collections.Hashtable capnames; protected internal System.Collections.Hashtable caps; protected internal int capsize; protected internal string[] capslist; protected internal System.Text.RegularExpressions.RegexRunnerFactory factory; public static readonly System.TimeSpan InfiniteMatchTimeout; protected internal System.TimeSpan internalMatchTimeout; protected internal string pattern; protected internal System.Text.RegularExpressions.RegexOptions roptions; protected Regex() { } protected Regex(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public Regex(string pattern) { } public Regex(string pattern, System.Text.RegularExpressions.RegexOptions options) { } public Regex(string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { } public static int CacheSize { get { throw null; } set { } } [System.CLSCompliantAttribute(false)] protected System.Collections.IDictionary CapNames { get { throw null; } set { } } [System.CLSCompliantAttribute(false)] protected System.Collections.IDictionary Caps { get { throw null; } set { } } public System.TimeSpan MatchTimeout { get { throw null; } } public System.Text.RegularExpressions.RegexOptions Options { get { throw null; } } public bool RightToLeft { get { throw null; } } public static string Escape(string str) { throw null; } public string[] GetGroupNames() { throw null; } public int[] GetGroupNumbers() { throw null; } public string GroupNameFromNumber(int i) { throw null; } public int GroupNumberFromName(string name) { throw null; } protected void InitializeReferences() { } public bool IsMatch(string input) { throw null; } public bool IsMatch(string input, int startat) { throw null; } public static bool IsMatch(string input, string pattern) { throw null; } public static bool IsMatch(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static bool IsMatch(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } public System.Text.RegularExpressions.Match Match(string input) { throw null; } public System.Text.RegularExpressions.Match Match(string input, int startat) { throw null; } public System.Text.RegularExpressions.Match Match(string input, int beginning, int length) { throw null; } public static System.Text.RegularExpressions.Match Match(string input, string pattern) { throw null; } public static System.Text.RegularExpressions.Match Match(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static System.Text.RegularExpressions.Match Match(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } public System.Text.RegularExpressions.MatchCollection Matches(string input) { throw null; } public System.Text.RegularExpressions.MatchCollection Matches(string input, int startat) { throw null; } public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern) { throw null; } public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } public string Replace(string input, string replacement) { throw null; } public string Replace(string input, string replacement, int count) { throw null; } public string Replace(string input, string replacement, int count, int startat) { throw null; } public static string Replace(string input, string pattern, string replacement) { throw null; } public static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator) { throw null; } public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator) { throw null; } public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count) { throw null; } public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count, int startat) { throw null; } public string[] Split(string input) { throw null; } public string[] Split(string input, int count) { throw null; } public string[] Split(string input, int count, int startat) { throw null; } public static string[] Split(string input, string pattern) { throw null; } public static string[] Split(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static string[] Split(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } public static string Unescape(string str) { throw null; } protected bool UseOptionC() { throw null; } protected bool UseOptionR() { throw null; } protected internal static void ValidateMatchTimeout(System.TimeSpan matchTimeout) { } } public partial class RegexCompilationInfo { public RegexCompilationInfo(string pattern, System.Text.RegularExpressions.RegexOptions options, string name, string fullnamespace, bool ispublic) { } public RegexCompilationInfo(string pattern, System.Text.RegularExpressions.RegexOptions options, string name, string fullnamespace, bool ispublic, System.TimeSpan matchTimeout) { } public bool IsPublic { get { throw null; } set { } } public System.TimeSpan MatchTimeout { get { throw null; } set { } } public string Name { get { throw null; } set { } } public string Namespace { get { throw null; } set { } } public System.Text.RegularExpressions.RegexOptions Options { get { throw null; } set { } } public string Pattern { get { throw null; } set { } } } public partial class RegexMatchTimeoutException : System.TimeoutException, System.Runtime.Serialization.ISerializable { public RegexMatchTimeoutException() { } protected RegexMatchTimeoutException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public RegexMatchTimeoutException(string message) { } public RegexMatchTimeoutException(string message, System.Exception inner) { } public RegexMatchTimeoutException(string regexInput, string regexPattern, System.TimeSpan matchTimeout) { } public string Input { get { throw null; } } public System.TimeSpan MatchTimeout { get { throw null; } } public string Pattern { get { throw null; } } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { } } [System.FlagsAttribute] public enum RegexOptions { None = 0, IgnoreCase = 1, Multiline = 2, ExplicitCapture = 4, Compiled = 8, Singleline = 16, IgnorePatternWhitespace = 32, RightToLeft = 64, ECMAScript = 256, CultureInvariant = 512, } public abstract partial class RegexRunner { protected internal int[] runcrawl; protected internal int runcrawlpos; protected internal System.Text.RegularExpressions.Match runmatch; protected internal System.Text.RegularExpressions.Regex runregex; protected internal int[] runstack; protected internal int runstackpos; protected internal string runtext; protected internal int runtextbeg; protected internal int runtextend; protected internal int runtextpos; protected internal int runtextstart; protected internal int[] runtrack; protected internal int runtrackcount; protected internal int runtrackpos; protected internal RegexRunner() { } protected void Capture(int capnum, int start, int end) { } protected static bool CharInClass(char ch, string charClass) { throw null; } protected static bool CharInSet(char ch, string @set, string category) { throw null; } protected void CheckTimeout() { } protected void Crawl(int i) { } protected int Crawlpos() { throw null; } protected void DoubleCrawl() { } protected void DoubleStack() { } protected void DoubleTrack() { } protected void EnsureStorage() { } protected abstract bool FindFirstChar(); protected abstract void Go(); protected abstract void InitTrackCount(); protected bool IsBoundary(int index, int startpos, int endpos) { throw null; } protected bool IsECMABoundary(int index, int startpos, int endpos) { throw null; } protected bool IsMatched(int cap) { throw null; } protected int MatchIndex(int cap) { throw null; } protected int MatchLength(int cap) { throw null; } protected int Popcrawl() { throw null; } protected internal System.Text.RegularExpressions.Match Scan(System.Text.RegularExpressions.Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick) { throw null; } protected internal System.Text.RegularExpressions.Match Scan(System.Text.RegularExpressions.Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick, System.TimeSpan timeout) { throw null; } protected void TransferCapture(int capnum, int uncapnum, int start, int end) { } protected void Uncapture() { } } public abstract partial class RegexRunnerFactory { protected RegexRunnerFactory() { } protected internal abstract System.Text.RegularExpressions.RegexRunner CreateInstance(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Reflection.Metadata.Ecma335 { public readonly struct ExceptionRegionEncoder { private const int TableHeaderSize = 4; private const int SmallRegionSize = sizeof(short) + // Flags sizeof(short) + // TryOffset sizeof(byte) + // TryLength sizeof(short) + // HandlerOffset sizeof(byte) + // HandleLength sizeof(int); // ClassToken | FilterOffset private const int FatRegionSize = sizeof(int) + // Flags sizeof(int) + // TryOffset sizeof(int) + // TryLength sizeof(int) + // HandlerOffset sizeof(int) + // HandleLength sizeof(int); // ClassToken | FilterOffset private const int ThreeBytesMaxValue = 0xffffff; internal const int MaxSmallExceptionRegions = (byte.MaxValue - TableHeaderSize) / SmallRegionSize; internal const int MaxExceptionRegions = (ThreeBytesMaxValue - TableHeaderSize) / FatRegionSize; /// <summary> /// The underlying builder. /// </summary> public BlobBuilder Builder { get; } /// <summary> /// True if the encoder uses small format. /// </summary> public bool HasSmallFormat { get; } internal ExceptionRegionEncoder(BlobBuilder builder, bool hasSmallFormat) { Builder = builder; HasSmallFormat = hasSmallFormat; } /// <summary> /// Returns true if the number of exception regions first small format. /// </summary> /// <param name="exceptionRegionCount">Number of exception regions.</param> public static bool IsSmallRegionCount(int exceptionRegionCount) => unchecked((uint)exceptionRegionCount) <= MaxSmallExceptionRegions; /// <summary> /// Returns true if the region fits small format. /// </summary> /// <param name="startOffset">Start offset of the region.</param> /// <param name="length">Length of the region.</param> public static bool IsSmallExceptionRegion(int startOffset, int length) => unchecked((uint)startOffset) <= ushort.MaxValue && unchecked((uint)length) <= byte.MaxValue; internal static bool IsSmallExceptionRegionFromBounds(int startOffset, int endOffset) => IsSmallExceptionRegion(startOffset, endOffset - startOffset); internal static int GetExceptionTableSize(int exceptionRegionCount, bool isSmallFormat) => TableHeaderSize + exceptionRegionCount * (isSmallFormat ? SmallRegionSize : FatRegionSize); internal static bool IsExceptionRegionCountInBounds(int exceptionRegionCount) => unchecked((uint)exceptionRegionCount) <= MaxExceptionRegions; internal static bool IsValidCatchTypeHandle(EntityHandle catchType) { return !catchType.IsNil && (catchType.Kind == HandleKind.TypeDefinition || catchType.Kind == HandleKind.TypeSpecification || catchType.Kind == HandleKind.TypeReference); } internal static ExceptionRegionEncoder SerializeTableHeader(BlobBuilder builder, int exceptionRegionCount, bool hasSmallRegions) { Debug.Assert(exceptionRegionCount > 0); const byte EHTableFlag = 0x01; const byte FatFormatFlag = 0x40; bool hasSmallFormat = hasSmallRegions && IsSmallRegionCount(exceptionRegionCount); int dataSize = GetExceptionTableSize(exceptionRegionCount, hasSmallFormat); builder.Align(4); if (hasSmallFormat) { builder.WriteByte(EHTableFlag); builder.WriteByte(unchecked((byte)dataSize)); builder.WriteInt16(0); } else { Debug.Assert(dataSize <= 0x00ffffff); builder.WriteByte(EHTableFlag | FatFormatFlag); builder.WriteByte(unchecked((byte)dataSize)); builder.WriteUInt16(unchecked((ushort)(dataSize >> 8))); } return new ExceptionRegionEncoder(builder, hasSmallFormat); } /// <summary> /// Adds a finally clause. /// </summary> /// <param name="tryOffset">Try block start offset.</param> /// <param name="tryLength">Try block length.</param> /// <param name="handlerOffset">Handler start offset.</param> /// <param name="handlerLength">Handler length.</param> /// <returns>Encoder for the next clause.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="tryOffset"/>, <paramref name="tryLength"/>, <paramref name="handlerOffset"/> or <paramref name="handlerLength"/> is out of range. /// </exception> /// <exception cref="InvalidOperationException">Method body was not declared to have exception regions.</exception> public ExceptionRegionEncoder AddFinally(int tryOffset, int tryLength, int handlerOffset, int handlerLength) { return Add(ExceptionRegionKind.Finally, tryOffset, tryLength, handlerOffset, handlerLength, default(EntityHandle), 0); } /// <summary> /// Adds a fault clause. /// </summary> /// <param name="tryOffset">Try block start offset.</param> /// <param name="tryLength">Try block length.</param> /// <param name="handlerOffset">Handler start offset.</param> /// <param name="handlerLength">Handler length.</param> /// <returns>Encoder for the next clause.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="tryOffset"/>, <paramref name="tryLength"/>, <paramref name="handlerOffset"/> or <paramref name="handlerLength"/> is out of range. /// </exception> /// <exception cref="InvalidOperationException">Method body was not declared to have exception regions.</exception> public ExceptionRegionEncoder AddFault(int tryOffset, int tryLength, int handlerOffset, int handlerLength) { return Add(ExceptionRegionKind.Fault, tryOffset, tryLength, handlerOffset, handlerLength, default(EntityHandle), 0); } /// <summary> /// Adds a fault clause. /// </summary> /// <param name="tryOffset">Try block start offset.</param> /// <param name="tryLength">Try block length.</param> /// <param name="handlerOffset">Handler start offset.</param> /// <param name="handlerLength">Handler length.</param> /// <param name="catchType"> /// <see cref="TypeDefinitionHandle"/>, <see cref="TypeReferenceHandle"/> or <see cref="TypeSpecificationHandle"/>. /// </param> /// <returns>Encoder for the next clause.</returns> /// <exception cref="ArgumentException"><paramref name="catchType"/> is invalid.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="tryOffset"/>, <paramref name="tryLength"/>, <paramref name="handlerOffset"/> or <paramref name="handlerLength"/> is out of range. /// </exception> /// <exception cref="InvalidOperationException">Method body was not declared to have exception regions.</exception> public ExceptionRegionEncoder AddCatch(int tryOffset, int tryLength, int handlerOffset, int handlerLength, EntityHandle catchType) { return Add(ExceptionRegionKind.Catch, tryOffset, tryLength, handlerOffset, handlerLength, catchType, 0); } /// <summary> /// Adds a fault clause. /// </summary> /// <param name="tryOffset">Try block start offset.</param> /// <param name="tryLength">Try block length.</param> /// <param name="handlerOffset">Handler start offset.</param> /// <param name="handlerLength">Handler length.</param> /// <param name="filterOffset">Offset of the filter block.</param> /// <returns>Encoder for the next clause.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="tryOffset"/>, <paramref name="tryLength"/>, <paramref name="handlerOffset"/> or <paramref name="handlerLength"/> is out of range. /// </exception> /// <exception cref="InvalidOperationException">Method body was not declared to have exception regions.</exception> public ExceptionRegionEncoder AddFilter(int tryOffset, int tryLength, int handlerOffset, int handlerLength, int filterOffset) { return Add(ExceptionRegionKind.Filter, tryOffset, tryLength, handlerOffset, handlerLength, default(EntityHandle), filterOffset); } /// <summary> /// Adds an exception clause. /// </summary> /// <param name="kind">Clause kind.</param> /// <param name="tryOffset">Try block start offset.</param> /// <param name="tryLength">Try block length.</param> /// <param name="handlerOffset">Handler start offset.</param> /// <param name="handlerLength">Handler length.</param> /// <param name="catchType"> /// <see cref="TypeDefinitionHandle"/>, <see cref="TypeReferenceHandle"/> or <see cref="TypeSpecificationHandle"/>, /// or nil if <paramref name="kind"/> is not <see cref="ExceptionRegionKind.Catch"/> /// </param> /// <param name="filterOffset"> /// Offset of the filter block, or 0 if the <paramref name="kind"/> is not <see cref="ExceptionRegionKind.Filter"/>. /// </param> /// <returns>Encoder for the next clause.</returns> /// <exception cref="ArgumentException"><paramref name="catchType"/> is invalid.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="kind"/> has invalid value.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="tryOffset"/>, <paramref name="tryLength"/>, <paramref name="handlerOffset"/> or <paramref name="handlerLength"/> is out of range. /// </exception> /// <exception cref="InvalidOperationException">Method body was not declared to have exception regions.</exception> public ExceptionRegionEncoder Add( ExceptionRegionKind kind, int tryOffset, int tryLength, int handlerOffset, int handlerLength, EntityHandle catchType = default(EntityHandle), int filterOffset = 0) { if (Builder == null) { Throw.InvalidOperation(SR.MethodHasNoExceptionRegions); } if (HasSmallFormat) { if (unchecked((ushort)tryOffset) != tryOffset) Throw.ArgumentOutOfRange(nameof(tryOffset)); if (unchecked((byte)tryLength) != tryLength) Throw.ArgumentOutOfRange(nameof(tryLength)); if (unchecked((ushort)handlerOffset) != handlerOffset) Throw.ArgumentOutOfRange(nameof(handlerOffset)); if (unchecked((byte)handlerLength) != handlerLength) Throw.ArgumentOutOfRange(nameof(handlerLength)); } else { if (tryOffset < 0) Throw.ArgumentOutOfRange(nameof(tryOffset)); if (tryLength < 0) Throw.ArgumentOutOfRange(nameof(tryLength)); if (handlerOffset < 0) Throw.ArgumentOutOfRange(nameof(handlerOffset)); if (handlerLength < 0) Throw.ArgumentOutOfRange(nameof(handlerLength)); } int catchTokenOrOffset; switch (kind) { case ExceptionRegionKind.Catch: if (!IsValidCatchTypeHandle(catchType)) { Throw.InvalidArgument_Handle(nameof(catchType)); } catchTokenOrOffset = MetadataTokens.GetToken(catchType); break; case ExceptionRegionKind.Filter: if (filterOffset < 0) { Throw.ArgumentOutOfRange(nameof(filterOffset)); } catchTokenOrOffset = filterOffset; break; case ExceptionRegionKind.Finally: case ExceptionRegionKind.Fault: catchTokenOrOffset = 0; break; default: throw new ArgumentOutOfRangeException(nameof(kind)); } AddUnchecked(kind, tryOffset, tryLength, handlerOffset, handlerLength, catchTokenOrOffset); return this; } internal void AddUnchecked( ExceptionRegionKind kind, int tryOffset, int tryLength, int handlerOffset, int handlerLength, int catchTokenOrOffset) { if (HasSmallFormat) { Builder.WriteUInt16((ushort)kind); Builder.WriteUInt16((ushort)tryOffset); Builder.WriteByte((byte)tryLength); Builder.WriteUInt16((ushort)handlerOffset); Builder.WriteByte((byte)handlerLength); } else { Builder.WriteInt32((int)kind); Builder.WriteInt32(tryOffset); Builder.WriteInt32(tryLength); Builder.WriteInt32(handlerOffset); Builder.WriteInt32(handlerLength); } Builder.WriteInt32(catchTokenOrOffset); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Threading; using System.Diagnostics.Contracts; // // Data table for encoding classes. Used by System.Text.Encoding. // This class contains two hashtables to allow System.Text.Encoding // to retrieve the data item either by codepage value or by webName. // // Only statics, does not need to be marked with the serializable attribute internal static class EncodingTable { //This number is the size of the table in native. The value is retrieved by //calling the native GetNumEncodingItems(). private static int lastEncodingItem = GetNumEncodingItems() - 1; //This number is the size of the code page table. Its generated when we walk the table the first time. private static volatile int lastCodePageItem; // // This points to a native data table which maps an encoding name to the correct code page. // [SecurityCritical] unsafe internal static InternalEncodingDataItem *encodingDataPtr = GetEncodingData(); // // This points to a native data table which stores the properties for the code page, and // the table is indexed by code page. // [SecurityCritical] unsafe internal static InternalCodePageDataItem *codePageDataPtr = GetCodePageData(); // // This caches the mapping of an encoding name to a code page. // private static Hashtable hashByName = Hashtable.Synchronized(new Hashtable(StringComparer.OrdinalIgnoreCase)); // // THe caches the data item which is indexed by the code page value. // private static Hashtable hashByCodePage = Hashtable.Synchronized(new Hashtable()); [System.Security.SecuritySafeCritical] // static constructors should be safe to call static EncodingTable() { } // Find the data item by binary searching the table that we have in native. // nativeCompareOrdinalWC is an internal-only function. [System.Security.SecuritySafeCritical] // auto-generated unsafe private static int internalGetCodePageFromName(String name) { int left = 0; int right = lastEncodingItem; int index; int result; //Binary search the array until we have only a couple of elements left and then //just walk those elements. while ((right - left)>3) { index = ((right - left)/2) + left; result = String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[index].webName); if (result == 0) { //We found the item, return the associated codepage. return (encodingDataPtr[index].codePage); } else if (result<0) { //The name that we're looking for is less than our current index. right = index; } else { //The name that we're looking for is greater than our current index left = index; } } //Walk the remaining elements (it'll be 3 or fewer). for (; left<=right; left++) { if (String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[left].webName) == 0) { return (encodingDataPtr[left].codePage); } } // The encoding name is not valid. throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_EncodingNotSupported"), name), "name"); } // Return a list of all EncodingInfo objects describing all of our encodings [System.Security.SecuritySafeCritical] // auto-generated internal static unsafe EncodingInfo[] GetEncodings() { if (lastCodePageItem == 0) { int count; for (count = 0; codePageDataPtr[count].codePage != 0; count++) { // Count them } lastCodePageItem = count; } EncodingInfo[] arrayEncodingInfo = new EncodingInfo[lastCodePageItem]; int i; for (i = 0; i < lastCodePageItem; i++) { arrayEncodingInfo[i] = new EncodingInfo(codePageDataPtr[i].codePage, CodePageDataItem.CreateString(codePageDataPtr[i].Names, 0), Environment.GetResourceString("Globalization.cp_" + codePageDataPtr[i].codePage)); } return arrayEncodingInfo; } /*=================================GetCodePageFromName========================== **Action: Given a encoding name, return the correct code page number for this encoding. **Returns: The code page for the encoding. **Arguments: ** name the name of the encoding **Exceptions: ** ArgumentNullException if name is null. ** internalGetCodePageFromName will throw ArgumentException if name is not a valid encoding name. ============================================================================*/ internal static int GetCodePageFromName(String name) { if (name==null) { throw new ArgumentNullException("name"); } Contract.EndContractBlock(); Object codePageObj; // // The name is case-insensitive, but ToLower isn't free. Check for // the code page in the given capitalization first. // codePageObj = hashByName[name]; if (codePageObj!=null) { return ((int)codePageObj); } //Okay, we didn't find it in the hash table, try looking it up in the //unmanaged data. int codePage = internalGetCodePageFromName(name); hashByName[name] = codePage; return codePage; } [System.Security.SecuritySafeCritical] // auto-generated unsafe internal static CodePageDataItem GetCodePageDataItem(int codepage) { CodePageDataItem dataItem; // We synchronize around dictionary gets/sets. There's still a possibility that two threads // will create a CodePageDataItem and the second will clobber the first in the dictionary. // However, that's acceptable because the contents are correct and we make no guarantees // other than that. //Look up the item in the hashtable. dataItem = (CodePageDataItem)hashByCodePage[codepage]; //If we found it, return it. if (dataItem!=null) { return dataItem; } //If we didn't find it, try looking it up now. //If we find it, add it to the hashtable. //This is a linear search, but we probably won't be doing it very often. // int i = 0; int data; while ((data = codePageDataPtr[i].codePage) != 0) { if (data == codepage) { dataItem = new CodePageDataItem(i); hashByCodePage[codepage] = dataItem; return (dataItem); } i++; } //Nope, we didn't find it. return null; } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] // Returns a pointer to a process-wide instance [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern InternalEncodingDataItem *GetEncodingData(); // // Return the number of encoding data items. // [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int GetNumEncodingItems(); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] // Returns a pointer to a process-wide instance [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern InternalCodePageDataItem* GetCodePageData(); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal unsafe static extern byte* nativeCreateOpenFileMapping( String inSectionName, int inBytesToAllocate, out IntPtr mappedFileHandle); } /*=================================InternalEncodingDataItem========================== **Action: This is used to map a encoding name to a correct code page number. By doing this, ** we can get the properties of this encoding via the InternalCodePageDataItem. ** ** We use this structure to access native data exposed by the native side. ============================================================================*/ [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] internal unsafe struct InternalEncodingDataItem { [SecurityCritical] internal sbyte * webName; internal UInt16 codePage; } /*=================================InternalCodePageDataItem========================== **Action: This is used to access the properties related to a code page. ** We use this structure to access native data exposed by the native side. ============================================================================*/ [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] internal unsafe struct InternalCodePageDataItem { internal UInt16 codePage; internal UInt16 uiFamilyCodePage; internal uint flags; [SecurityCritical] internal sbyte * Names; } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PhotonHandler.cs" company="Exit Games GmbH"> // Part of: Photon Unity Networking // </copyright> // -------------------------------------------------------------------------------------------------------------------- #if UNITY_5 && (!UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2 && !UNITY_5_3) || UNITY_6 #define UNITY_MIN_5_4 #endif using System; using System.Collections; using System.Diagnostics; using ExitGames.Client.Photon; using UnityEngine; using Debug = UnityEngine.Debug; using Hashtable = ExitGames.Client.Photon.Hashtable; using SupportClassPun = ExitGames.Client.Photon.SupportClass; /// <summary> /// Internal Monobehaviour that allows Photon to run an Update loop. /// </summary> internal class PhotonHandler : Photon.MonoBehaviour { public static PhotonHandler SP; public int updateInterval; // time [ms] between consecutive SendOutgoingCommands calls public int updateIntervalOnSerialize; // time [ms] between consecutive RunViewUpdate calls (sending syncs, etc) private int nextSendTickCount = 0; private int nextSendTickCountOnSerialize = 0; private static bool sendThreadShouldRun; private static Stopwatch timerToStopConnectionInBackground; protected internal static bool AppQuits; protected internal static Type PingImplementation = null; protected void Awake() { if (SP != null && SP != this && SP.gameObject != null) { GameObject.DestroyImmediate(SP.gameObject); } SP = this; DontDestroyOnLoad(this.gameObject); this.updateInterval = 1000 / PhotonNetwork.sendRate; this.updateIntervalOnSerialize = 1000 / PhotonNetwork.sendRateOnSerialize; PhotonHandler.StartFallbackSendAckThread(); } #if UNITY_MIN_5_4 protected void Start() { UnityEngine.SceneManagement.SceneManager.sceneLoaded += (scene, loadingMode) => { PhotonNetwork.networkingPeer.NewSceneLoaded(); PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(SceneManagerHelper.ActiveSceneName); }; } #else /// <summary>Called by Unity after a new level was loaded.</summary> protected void OnLevelWasLoaded(int level) { PhotonNetwork.networkingPeer.NewSceneLoaded(); PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(SceneManagerHelper.ActiveSceneName); } #endif /// <summary>Called by Unity when the application is closed. Disconnects.</summary> protected void OnApplicationQuit() { PhotonHandler.AppQuits = true; PhotonHandler.StopFallbackSendAckThread(); PhotonNetwork.Disconnect(); } /// <summary> /// Called by Unity when the application gets paused (e.g. on Android when in background). /// </summary> /// <remarks> /// Some versions of Unity will give false values for pause on Android (and possibly on other platforms). /// Sets a disconnect timer when PhotonNetwork.BackgroundTimeout > 0.001f. /// </remarks> /// <param name="pause"></param> protected void OnApplicationPause(bool pause) { if (PhotonNetwork.BackgroundTimeout > 0.001f) { if (timerToStopConnectionInBackground == null) { timerToStopConnectionInBackground = new Stopwatch(); } timerToStopConnectionInBackground.Reset(); if (pause) { timerToStopConnectionInBackground.Start(); } else { timerToStopConnectionInBackground.Stop(); } } } /// <summary>Called by Unity when the play mode ends. Used to cleanup.</summary> protected void OnDestroy() { //Debug.Log("OnDestroy on PhotonHandler."); PhotonHandler.StopFallbackSendAckThread(); //PhotonNetwork.Disconnect(); } protected void Update() { if (PhotonNetwork.networkingPeer == null) { Debug.LogError("NetworkPeer broke!"); return; } if (PhotonNetwork.connectionStateDetailed == ClientState.PeerCreated || PhotonNetwork.connectionStateDetailed == ClientState.Disconnected || PhotonNetwork.offlineMode) { return; } // the messageQueue might be paused. in that case a thread will send acknowledgements only. nothing else to do here. if (!PhotonNetwork.isMessageQueueRunning) { return; } bool doDispatch = true; while (PhotonNetwork.isMessageQueueRunning && doDispatch) { // DispatchIncomingCommands() returns true of it found any command to dispatch (event, result or state change) Profiler.BeginSample("DispatchIncomingCommands"); doDispatch = PhotonNetwork.networkingPeer.DispatchIncomingCommands(); Profiler.EndSample(); } int currentMsSinceStart = (int)(Time.realtimeSinceStartup * 1000); // avoiding Environment.TickCount, which could be negative on long-running platforms if (PhotonNetwork.isMessageQueueRunning && currentMsSinceStart > this.nextSendTickCountOnSerialize) { PhotonNetwork.networkingPeer.RunViewUpdate(); this.nextSendTickCountOnSerialize = currentMsSinceStart + this.updateIntervalOnSerialize; this.nextSendTickCount = 0; // immediately send when synchronization code was running } currentMsSinceStart = (int)(Time.realtimeSinceStartup * 1000); if (currentMsSinceStart > this.nextSendTickCount) { bool doSend = true; while (PhotonNetwork.isMessageQueueRunning && doSend) { // Send all outgoing commands Profiler.BeginSample("SendOutgoingCommands"); doSend = PhotonNetwork.networkingPeer.SendOutgoingCommands(); Profiler.EndSample(); } this.nextSendTickCount = currentMsSinceStart + this.updateInterval; } } protected void OnJoinedRoom() { PhotonNetwork.networkingPeer.LoadLevelIfSynced(); } protected void OnCreatedRoom() { PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(SceneManagerHelper.ActiveSceneName); } public static void StartFallbackSendAckThread() { #if !UNITY_WEBGL if (sendThreadShouldRun) { return; } sendThreadShouldRun = true; SupportClassPun.CallInBackground(FallbackSendAckThread); // thread will call this every 100ms until method returns false #endif } public static void StopFallbackSendAckThread() { #if !UNITY_WEBGL sendThreadShouldRun = false; #endif } public static bool FallbackSendAckThread() { if (sendThreadShouldRun && PhotonNetwork.networkingPeer != null) { // check if the client should disconnect after some seconds in background if (timerToStopConnectionInBackground != null && PhotonNetwork.BackgroundTimeout > 0.001f) { if (timerToStopConnectionInBackground.ElapsedMilliseconds > PhotonNetwork.BackgroundTimeout * 1000) { return sendThreadShouldRun; } } PhotonNetwork.networkingPeer.SendAcksOnly(); } return sendThreadShouldRun; } #region Photon Cloud Ping Evaluation private const string PlayerPrefsKey = "PUNCloudBestRegion"; internal static CloudRegionCode BestRegionCodeCurrently = CloudRegionCode.none; // default to none internal static CloudRegionCode BestRegionCodeInPreferences { get { string prefsRegionCode = PlayerPrefs.GetString(PlayerPrefsKey, ""); if (!string.IsNullOrEmpty(prefsRegionCode)) { CloudRegionCode loadedRegion = Region.Parse(prefsRegionCode); return loadedRegion; } return CloudRegionCode.none; } set { if (value == CloudRegionCode.none) { PlayerPrefs.DeleteKey(PlayerPrefsKey); } else { PlayerPrefs.SetString(PlayerPrefsKey, value.ToString()); } } } internal protected static void PingAvailableRegionsAndConnectToBest() { SP.StartCoroutine(SP.PingAvailableRegionsCoroutine(true)); } internal IEnumerator PingAvailableRegionsCoroutine(bool connectToBest) { BestRegionCodeCurrently = CloudRegionCode.none; while (PhotonNetwork.networkingPeer.AvailableRegions == null) { if (PhotonNetwork.connectionStateDetailed != ClientState.ConnectingToNameServer && PhotonNetwork.connectionStateDetailed != ClientState.ConnectedToNameServer) { Debug.LogError("Call ConnectToNameServer to ping available regions."); yield break; // break if we don't connect to the nameserver at all } Debug.Log("Waiting for AvailableRegions. State: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.Server + " PhotonNetwork.networkingPeer.AvailableRegions " + (PhotonNetwork.networkingPeer.AvailableRegions != null)); yield return new WaitForSeconds(0.25f); // wait until pinging finished (offline mode won't ping) } if (PhotonNetwork.networkingPeer.AvailableRegions == null || PhotonNetwork.networkingPeer.AvailableRegions.Count == 0) { Debug.LogError("No regions available. Are you sure your appid is valid and setup?"); yield break; // break if we don't get regions at all } PhotonPingManager pingManager = new PhotonPingManager(); foreach (Region region in PhotonNetwork.networkingPeer.AvailableRegions) { SP.StartCoroutine(pingManager.PingSocket(region)); } while (!pingManager.Done) { yield return new WaitForSeconds(0.1f); // wait until pinging finished (offline mode won't ping) } Region best = pingManager.BestRegion; PhotonHandler.BestRegionCodeCurrently = best.Code; PhotonHandler.BestRegionCodeInPreferences = best.Code; Debug.Log("Found best region: " + best.Code + " ping: " + best.Ping + ". Calling ConnectToRegionMaster() is: " + connectToBest); if (connectToBest) { PhotonNetwork.networkingPeer.ConnectToRegionMaster(best.Code); } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Xml.Linq; using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; using Microsoft.AspNetCore.DataProtection.Internal; using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Microsoft.Win32; using Xunit; namespace Microsoft.AspNetCore.DataProtection { public class RegistryPolicyResolverTests { [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_NoEntries_ResultsInNoPolicies() { // Arrange var registryEntries = new Dictionary<string, object>(); // Act var context = RunTestWithRegValues(registryEntries); // Assert Assert.Null(context.EncryptorConfiguration); Assert.Null(context.DefaultKeyLifetime); Assert.Empty(context.KeyEscrowSinks); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_KeyEscrowSinks() { // Arrange var registryEntries = new Dictionary<string, object>() { ["KeyEscrowSinks"] = String.Join(" ;; ; ", new Type[] { typeof(MyKeyEscrowSink1), typeof(MyKeyEscrowSink2) }.Select(t => t.AssemblyQualifiedName)) }; // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualKeyEscrowSinks = context.KeyEscrowSinks.ToArray(); Assert.Equal(2, actualKeyEscrowSinks.Length); Assert.IsType<MyKeyEscrowSink1>(actualKeyEscrowSinks[0]); Assert.IsType<MyKeyEscrowSink2>(actualKeyEscrowSinks[1]); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_DefaultKeyLifetime() { // Arrange var registryEntries = new Dictionary<string, object>() { ["DefaultKeyLifetime"] = 1024 // days }; // Act var context = RunTestWithRegValues(registryEntries); // Assert Assert.Equal(1024, context.DefaultKeyLifetime); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_CngCbcEncryption_WithoutExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "cng-cbc" }; var expectedConfiguration = new CngCbcAuthenticatedEncryptorConfiguration(); // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (CngCbcAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal(expectedConfiguration.EncryptionAlgorithm, actualConfiguration.EncryptionAlgorithm); Assert.Equal(expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize); Assert.Equal(expectedConfiguration.EncryptionAlgorithmProvider, actualConfiguration.EncryptionAlgorithmProvider); Assert.Equal(expectedConfiguration.HashAlgorithm, actualConfiguration.HashAlgorithm); Assert.Equal(expectedConfiguration.HashAlgorithmProvider, actualConfiguration.HashAlgorithmProvider); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_CngCbcEncryption_WithExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "cng-cbc", ["EncryptionAlgorithm"] = "enc-alg", ["EncryptionAlgorithmKeySize"] = 2048, ["EncryptionAlgorithmProvider"] = "my-enc-alg-provider", ["HashAlgorithm"] = "hash-alg", ["HashAlgorithmProvider"] = "my-hash-alg-provider" }; var expectedConfiguration = new CngCbcAuthenticatedEncryptorConfiguration() { EncryptionAlgorithm = "enc-alg", EncryptionAlgorithmKeySize = 2048, EncryptionAlgorithmProvider = "my-enc-alg-provider", HashAlgorithm = "hash-alg", HashAlgorithmProvider = "my-hash-alg-provider" }; // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (CngCbcAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal(expectedConfiguration.EncryptionAlgorithm, actualConfiguration.EncryptionAlgorithm); Assert.Equal(expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize); Assert.Equal(expectedConfiguration.EncryptionAlgorithmProvider, actualConfiguration.EncryptionAlgorithmProvider); Assert.Equal(expectedConfiguration.HashAlgorithm, actualConfiguration.HashAlgorithm); Assert.Equal(expectedConfiguration.HashAlgorithmProvider, actualConfiguration.HashAlgorithmProvider); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_CngGcmEncryption_WithoutExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "cng-gcm" }; var expectedConfiguration = new CngGcmAuthenticatedEncryptorConfiguration(); // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (CngGcmAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal(expectedConfiguration.EncryptionAlgorithm, actualConfiguration.EncryptionAlgorithm); Assert.Equal(expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize); Assert.Equal(expectedConfiguration.EncryptionAlgorithmProvider, actualConfiguration.EncryptionAlgorithmProvider); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_CngGcmEncryption_WithExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "cng-gcm", ["EncryptionAlgorithm"] = "enc-alg", ["EncryptionAlgorithmKeySize"] = 2048, ["EncryptionAlgorithmProvider"] = "my-enc-alg-provider" }; var expectedConfiguration = new CngGcmAuthenticatedEncryptorConfiguration() { EncryptionAlgorithm = "enc-alg", EncryptionAlgorithmKeySize = 2048, EncryptionAlgorithmProvider = "my-enc-alg-provider" }; // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (CngGcmAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal(expectedConfiguration.EncryptionAlgorithm, actualConfiguration.EncryptionAlgorithm); Assert.Equal(expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize); Assert.Equal(expectedConfiguration.EncryptionAlgorithmProvider, actualConfiguration.EncryptionAlgorithmProvider); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_ManagedEncryption_WithoutExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "managed" }; var expectedConfiguration = new ManagedAuthenticatedEncryptorConfiguration(); // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (ManagedAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal(expectedConfiguration.EncryptionAlgorithmType, actualConfiguration.EncryptionAlgorithmType); Assert.Equal(expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize); Assert.Equal(expectedConfiguration.ValidationAlgorithmType, actualConfiguration.ValidationAlgorithmType); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_ManagedEncryption_WithExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "managed", ["EncryptionAlgorithmType"] = typeof(TripleDES).AssemblyQualifiedName, ["EncryptionAlgorithmKeySize"] = 2048, ["ValidationAlgorithmType"] = typeof(HMACSHA1).AssemblyQualifiedName }; var expectedConfiguration = new ManagedAuthenticatedEncryptorConfiguration() { EncryptionAlgorithmType = typeof(TripleDES), EncryptionAlgorithmKeySize = 2048, ValidationAlgorithmType = typeof(HMACSHA1) }; // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (ManagedAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal(expectedConfiguration.EncryptionAlgorithmType, actualConfiguration.EncryptionAlgorithmType); Assert.Equal(expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize); Assert.Equal(expectedConfiguration.ValidationAlgorithmType, actualConfiguration.ValidationAlgorithmType); } private static RegistryPolicy RunTestWithRegValues(Dictionary<string, object> regValues) { return WithUniqueTempRegKey(registryKey => { foreach (var entry in regValues) { registryKey.SetValue(entry.Key, entry.Value); } var policyResolver = new RegistryPolicyResolver( registryKey, activator: SimpleActivator.DefaultWithoutServices); return policyResolver.ResolvePolicy(); }); } /// <summary> /// Runs a test and cleans up the registry key afterward. /// </summary> private static RegistryPolicy WithUniqueTempRegKey(Func<RegistryKey, RegistryPolicy> testCode) { string uniqueName = Guid.NewGuid().ToString(); var uniqueSubkey = LazyHkcuTempKey.Value.CreateSubKey(uniqueName); try { return testCode(uniqueSubkey); } finally { // clean up when test is done LazyHkcuTempKey.Value.DeleteSubKeyTree(uniqueName, throwOnMissingSubKey: false); } } private static readonly Lazy<RegistryKey> LazyHkcuTempKey = new Lazy<RegistryKey>(() => { try { return Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\ASP.NET\temp"); } catch { // swallow all failures return null; } }); private class ConditionalRunTestOnlyIfHkcuRegistryAvailable : Attribute, ITestCondition { public bool IsMet => (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && LazyHkcuTempKey.Value != null); public string SkipReason { get; } = "HKCU registry couldn't be opened."; } private class MyKeyEscrowSink1 : IKeyEscrowSink { public void Store(Guid keyId, XElement element) { throw new NotImplementedException(); } } private class MyKeyEscrowSink2 : IKeyEscrowSink { public void Store(Guid keyId, XElement element) { throw new NotImplementedException(); } } } }
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public sealed class ExpressionBodiedPropertyTests : CSharpTestBase { [Fact(Skip = "973907")] public void Syntax01() { // Language feature enabled by default var comp = CreateCompilationWithMscorlib(@" class C { public int P => 1; }"); comp.VerifyDiagnostics(); } [Fact] public void Syntax02() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P { get; } => 1; }"); comp.VerifyDiagnostics( // (4,5): error CS8056: Properties cannot combine accessor lists with expression bodies. // public int P { get; } => 1; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "public int P { get; } => 1;").WithLocation(4, 5) ); } [Fact] public void Syntax03() { var comp = CreateCompilationWithMscorlib45(@" interface C { int P => 1; }"); comp.VerifyDiagnostics( // (4,14): error CS0531: 'C.P.get': interface members cannot have a definition // int P => 1; Diagnostic(ErrorCode.ERR_InterfaceMemberHasBody, "1").WithArguments("C.P.get").WithLocation(4, 14)); } [Fact] public void Syntax04() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,28): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 28)); } [Fact] public void Syntax05() { var comp = CreateCompilationWithMscorlib45(@" class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,29): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 29), // (4,29): error CS0513: 'C.P.get' is abstract but it is contained in non-abstract class 'C' // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "1").WithArguments("C.P.get", "C").WithLocation(4, 29)); } [Fact] public void Syntax06() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,17): error CS0621: 'C.P': virtual or abstract members cannot be private // abstract int P => 1; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P").WithArguments("C.P").WithLocation(4, 17), // (4,22): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 22)); } [Fact] public void Syntax07() { // The '=' here parses as part of the expression body, not the property var comp = CreateCompilationWithMscorlib45(@" class C { public int P => 1 = 2; }"); comp.VerifyDiagnostics( // (4,21): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // public int P => 1 = 2; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "1").WithLocation(4, 21)); } [Fact] public void Syntax08() { CreateCompilationWithMscorlib45(@" interface I { int P { get; }; }").VerifyDiagnostics( // (4,19): error CS1597: Semicolon after method or accessor block is not valid // int P { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 19)); } [Fact] public void Syntax09() { CreateCompilationWithMscorlib45(@" class C { int P => 2 }").VerifyDiagnostics( // (4,15): error CS1002: ; expected // int P => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 15)); } [Fact] public void Syntax10() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i] Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i] Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax11() { CreateCompilationWithMscorlib45(@" interface I { int this[int i]; }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i]; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(4, 20), // (4,20): error CS1014: A get or set accessor expected // int this[int i]; Diagnostic(ErrorCode.ERR_GetOrSetExpected, ";").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i]; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax12() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] { get; }; }").VerifyDiagnostics( // (4,29): error CS1597: Semicolon after method or accessor block is not valid // int this[int i] { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 29)); } [Fact] public void Syntax13() { // End the property declaration at the semicolon after the accessor list CreateCompilationWithMscorlib45(@" class C { int P { get; set; }; => 2; }").VerifyDiagnostics( // (4,24): error CS1597: Semicolon after method or accessor block is not valid // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 24), // (4,26): error CS1519: Invalid token '=>' in class, struct, or interface member declaration // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(4, 26)); } [Fact] public void Syntax14() { CreateCompilationWithMscorlib45(@" class C { int this[int i] => 2 }").VerifyDiagnostics( // (4,25): error CS1002: ; expected // int this[int i] => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 25)); } [Fact] public void LambdaTest01() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public Func<int, Func<int, int>> P => x => y => x + y; }"); comp.VerifyDiagnostics(); } [Fact] public void SimpleTest() { var text = @" class C { public int P => 2 * 2; public int this[int i, int j] => i * j * P; }"; var comp = CreateCompilationWithMscorlib45(text); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); var indexer = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(indexer.SetMethod); Assert.NotNull(indexer.GetMethod); Assert.False(indexer.GetMethod.IsImplicitlyDeclared); Assert.True(indexer.IsExpressionBodied); Assert.True(indexer.IsIndexer); Assert.Equal(2, indexer.ParameterCount); var i = indexer.Parameters[0]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("i", i.Name); var j = indexer.Parameters[1]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("j", j.Name); } [Fact] public void Override01() { var comp = CreateCompilationWithMscorlib45(@" class B { public virtual int P { get; set; } } class C : B { public override int P => 1; }").VerifyDiagnostics(); } [Fact] public void Override02() { CreateCompilationWithMscorlib45(@" class B { public int P => 10; public int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics( // (10,25): error CS0506: 'C.this[int]': cannot override inherited member 'B.this[int]' because it is not marked virtual, abstract, or override // public override int this[int i] => i * 2; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "this").WithArguments("C.this[int]", "B.this[int]").WithLocation(10, 25), // (9,25): error CS0506: 'C.P': cannot override inherited member 'B.P' because it is not marked virtual, abstract, or override // public override int P => 20; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "P").WithArguments("C.P", "B.P").WithLocation(9, 25)); } [Fact] public void Override03() { CreateCompilationWithMscorlib45(@" class B { public virtual int P => 10; public virtual int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics(); } [Fact] public void VoidExpression() { var comp = CreateCompilationWithMscorlib45(@" class C { public void P => System.Console.WriteLine(""foo""); }").VerifyDiagnostics( // (4,17): error CS0547: 'C.P': property or indexer cannot have void type // public void P => System.Console.WriteLine("foo"); Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "P").WithArguments("C.P").WithLocation(4, 17)); } [Fact] public void VoidExpression2() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P => System.Console.WriteLine(""foo""); }").VerifyDiagnostics( // (4,21): error CS0029: Cannot implicitly convert type 'void' to 'int' // public int P => System.Console.WriteLine("foo"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"System.Console.WriteLine(""foo"")").WithArguments("void", "int").WithLocation(4, 21)); } [Fact] public void InterfaceImplementation01() { var comp = CreateCompilationWithMscorlib45(@" interface I { int P { get; } string Q { get; } } internal interface J { string Q { get; } } internal interface K { decimal D { get; } } class C : I, J, K { public int P => 10; string I.Q { get { return ""foo""; } } string J.Q { get { return ""bar""; } } public decimal D { get { return P; } } }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var i = global.GetTypeMember("I"); var j = global.GetTypeMember("J"); var k = global.GetTypeMember("K"); var c = global.GetTypeMember("C"); var iP = i.GetMember<SourcePropertySymbol>("P"); var prop = c.GetMember<SourcePropertySymbol>("P"); Assert.True(prop.IsReadOnly); var implements = prop.ContainingType.FindImplementationForInterfaceMember(iP); Assert.Equal(prop, implements); prop = (SourcePropertySymbol)c.GetProperty("I.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = (SourcePropertySymbol)c.GetProperty("J.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = c.GetMember<SourcePropertySymbol>("D"); Assert.True(prop.IsReadOnly); } [ClrOnlyFact] public void Emit01() { var comp = CreateCompilationWithMscorlib45(@" abstract class A { protected abstract string Z { get; } } abstract class B : A { protected sealed override string Z => ""foo""; protected abstract string Y { get; } } class C : B { public const int X = 2; public static int P => C.X * C.X; public int Q => X; private int R => P * Q; protected sealed override string Y => Z + R; public int this[int i] => R + i; public static void Main() { System.Console.WriteLine(C.X); System.Console.WriteLine(C.P); var c = new C(); System.Console.WriteLine(c.Q); System.Console.WriteLine(c.R); System.Console.WriteLine(c.Z); System.Console.WriteLine(c.Y); System.Console.WriteLine(c[10]); } }", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal)); var verifier = CompileAndVerify(comp, expectedOutput: @"2 4 2 8 foo foo8 18"); } [ClrOnlyFact] public void AccessorInheritsVisibility() { var comp = CreateCompilationWithMscorlib45(@" class C { private int P => 1; private int this[int i] => i; }", options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); Action<ModuleSymbol> srcValidator = m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var p = c.GetMember<PropertySymbol>("P"); var indexer = c.Indexers[0]; Assert.Equal(Accessibility.Private, p.DeclaredAccessibility); Assert.Equal(Accessibility.Private, indexer.DeclaredAccessibility); }; var verifier = CompileAndVerify(comp, sourceSymbolValidator: srcValidator); } [Fact] public void StaticIndexer() { var comp = CreateCompilationWithMscorlib45(@" class C { static int this[int i] => i; }"); comp.VerifyDiagnostics( // (4,16): error CS0106: The modifier 'static' is not valid for this item // static int this[int i] => i; Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(4, 16)); } [Fact] public void RefReturningExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref int P => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.Ref, p.GetMethod.RefKind); } } }
/* * 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 copyrightD * 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.Text; using OpenSim.Framework; using OpenSim.Region.Framework; using OpenSim.Region.PhysicsModules.SharedBase; using Nini.Config; using log4net; using OpenMetaverse; namespace OpenSim.Region.PhysicsModule.BulletS { public sealed class BSTerrainMesh : BSTerrainPhys { static string LogHeader = "[BULLETSIM TERRAIN MESH]"; private float[] m_savedHeightMap; int m_sizeX; int m_sizeY; BulletShape m_terrainShape; BulletBody m_terrainBody; public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize) : base(physicsScene, regionBase, id) { } public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id /* parameters for making mesh */) : base(physicsScene, regionBase, id) { } // Create terrain mesh from a heightmap. public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap, Vector3 minCoords, Vector3 maxCoords) : base(physicsScene, regionBase, id) { int indicesCount; int[] indices; int verticesCount; float[] vertices; m_savedHeightMap = initialMap; m_sizeX = (int)(maxCoords.X - minCoords.X); m_sizeY = (int)(maxCoords.Y - minCoords.Y); bool meshCreationSuccess = false; if (BSParam.TerrainMeshMagnification == 1) { // If a magnification of one, use the old routine that is tried and true. meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh(m_physicsScene, initialMap, m_sizeX, m_sizeY, // input size Vector3.Zero, // base for mesh out indicesCount, out indices, out verticesCount, out vertices); } else { // Other magnifications use the newer routine meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh2(m_physicsScene, initialMap, m_sizeX, m_sizeY, // input size BSParam.TerrainMeshMagnification, physicsScene.TerrainManager.DefaultRegionSize, Vector3.Zero, // base for mesh out indicesCount, out indices, out verticesCount, out vertices); } if (!meshCreationSuccess) { // DISASTER!! m_physicsScene.DetailLog("{0},BSTerrainMesh.create,failedConversionOfHeightmap,id={1}", BSScene.DetailLogZero, ID); m_physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh! base={1}", LogHeader, TerrainBase); // Something is very messed up and a crash is in our future. return; } m_physicsScene.DetailLog("{0},BSTerrainMesh.create,meshed,id={1},indices={2},indSz={3},vertices={4},vertSz={5}", BSScene.DetailLogZero, ID, indicesCount, indices.Length, verticesCount, vertices.Length); m_terrainShape = m_physicsScene.PE.CreateMeshShape(m_physicsScene.World, indicesCount, indices, verticesCount, vertices); if (!m_terrainShape.HasPhysicalShape) { // DISASTER!! m_physicsScene.DetailLog("{0},BSTerrainMesh.create,failedCreationOfShape,id={1}", BSScene.DetailLogZero, ID); m_physicsScene.Logger.ErrorFormat("{0} Failed creation of terrain mesh! base={1}", LogHeader, TerrainBase); // Something is very messed up and a crash is in our future. return; } Vector3 pos = regionBase; Quaternion rot = Quaternion.Identity; m_terrainBody = m_physicsScene.PE.CreateBodyWithDefaultMotionState(m_terrainShape, ID, pos, rot); if (!m_terrainBody.HasPhysicalBody) { // DISASTER!! m_physicsScene.Logger.ErrorFormat("{0} Failed creation of terrain body! base={1}", LogHeader, TerrainBase); // Something is very messed up and a crash is in our future. return; } physicsScene.PE.SetShapeCollisionMargin(m_terrainShape, BSParam.TerrainCollisionMargin); // Set current terrain attributes m_physicsScene.PE.SetFriction(m_terrainBody, BSParam.TerrainFriction); m_physicsScene.PE.SetHitFraction(m_terrainBody, BSParam.TerrainHitFraction); m_physicsScene.PE.SetRestitution(m_terrainBody, BSParam.TerrainRestitution); m_physicsScene.PE.SetContactProcessingThreshold(m_terrainBody, BSParam.TerrainContactProcessingThreshold); m_physicsScene.PE.SetCollisionFlags(m_terrainBody, CollisionFlags.CF_STATIC_OBJECT); // Static objects are not very massive. m_physicsScene.PE.SetMassProps(m_terrainBody, 0f, Vector3.Zero); // Put the new terrain to the world of physical objects m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, m_terrainBody); // Redo its bounding box now that it is in the world m_physicsScene.PE.UpdateSingleAabb(m_physicsScene.World, m_terrainBody); m_terrainBody.collisionType = CollisionType.Terrain; m_terrainBody.ApplyCollisionMask(m_physicsScene); if (BSParam.UseSingleSidedMeshes) { m_physicsScene.DetailLog("{0},BSTerrainMesh.settingCustomMaterial,id={1}", BSScene.DetailLogZero, id); m_physicsScene.PE.AddToCollisionFlags(m_terrainBody, CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); } // Make it so the terrain will not move or be considered for movement. m_physicsScene.PE.ForceActivationState(m_terrainBody, ActivationState.DISABLE_SIMULATION); } public override void Dispose() { if (m_terrainBody.HasPhysicalBody) { m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, m_terrainBody); // Frees both the body and the shape. m_physicsScene.PE.DestroyObject(m_physicsScene.World, m_terrainBody); m_terrainBody.Clear(); m_terrainShape.Clear(); } } public override float GetTerrainHeightAtXYZ(Vector3 pos) { // For the moment use the saved heightmap to get the terrain height. // TODO: raycast downward to find the true terrain below the position. float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; int mapIndex = (int)pos.Y * m_sizeY + (int)pos.X; try { ret = m_savedHeightMap[mapIndex]; } catch { // Sometimes they give us wonky values of X and Y. Give a warning and return something. m_physicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, pos={2}", LogHeader, TerrainBase, pos); ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; } return ret; } // The passed position is relative to the base of the region. public override float GetWaterLevelAtXYZ(Vector3 pos) { return m_physicsScene.SimpleWaterLevel; } // Convert the passed heightmap to mesh information suitable for CreateMeshShape2(). // Return 'true' if successfully created. public static bool ConvertHeightmapToMesh( BSScene physicsScene, float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap Vector3 extentBase, // base to be added to all vertices out int indicesCountO, out int[] indicesO, out int verticesCountO, out float[] verticesO) { bool ret = false; int indicesCount = 0; int verticesCount = 0; int[] indices = new int[0]; float[] vertices = new float[0]; // Simple mesh creation which assumes magnification == 1. // TODO: do a more general solution that scales, adds new vertices and smoothes the result. // Create an array of vertices that is sizeX+1 by sizeY+1 (note the loop // from zero to <= sizeX). The triangle indices are then generated as two triangles // per heightmap point. There are sizeX by sizeY of these squares. The extra row and // column of vertices are used to complete the triangles of the last row and column // of the heightmap. try { // One vertice per heightmap value plus the vertices off the side and bottom edge. int totalVertices = (sizeX + 1) * (sizeY + 1); vertices = new float[totalVertices * 3]; int totalIndices = sizeX * sizeY * 6; indices = new int[totalIndices]; if (physicsScene != null) physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,totVert={1},totInd={2},extentBase={3}", BSScene.DetailLogZero, totalVertices, totalIndices, extentBase); float minHeight = float.MaxValue; // Note that sizeX+1 vertices are created since there is land between this and the next region. for (int yy = 0; yy <= sizeY; yy++) { for (int xx = 0; xx <= sizeX; xx++) // Hint: the "<=" means we go around sizeX + 1 times { int offset = yy * sizeX + xx; // Extend the height with the height from the last row or column if (yy == sizeY) offset -= sizeX; if (xx == sizeX) offset -= 1; float height = heightMap[offset]; minHeight = Math.Min(minHeight, height); vertices[verticesCount + 0] = (float)xx + extentBase.X; vertices[verticesCount + 1] = (float)yy + extentBase.Y; vertices[verticesCount + 2] = height + extentBase.Z; verticesCount += 3; } } verticesCount = verticesCount / 3; for (int yy = 0; yy < sizeY; yy++) { for (int xx = 0; xx < sizeX; xx++) { int offset = yy * (sizeX + 1) + xx; // Each vertices is presumed to be the upper left corner of a box of two triangles indices[indicesCount + 0] = offset; indices[indicesCount + 1] = offset + 1; indices[indicesCount + 2] = offset + sizeX + 1; // accounting for the extra column indices[indicesCount + 3] = offset + 1; indices[indicesCount + 4] = offset + sizeX + 2; indices[indicesCount + 5] = offset + sizeX + 1; indicesCount += 6; } } ret = true; } catch (Exception e) { if (physicsScene != null) physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. For={1}/{2}, e={3}", LogHeader, physicsScene.RegionName, extentBase, e); } indicesCountO = indicesCount; indicesO = indices; verticesCountO = verticesCount; verticesO = vertices; return ret; } private class HeightMapGetter { private float[] m_heightMap; private int m_sizeX; private int m_sizeY; public HeightMapGetter(float[] pHeightMap, int pSizeX, int pSizeY) { m_heightMap = pHeightMap; m_sizeX = pSizeX; m_sizeY = pSizeY; } // The heightmap is extended as an infinite plane at the last height public float GetHeight(int xx, int yy) { int offset = 0; // Extend the height with the height from the last row or column if (yy >= m_sizeY) if (xx >= m_sizeX) offset = (m_sizeY - 1) * m_sizeX + (m_sizeX - 1); else offset = (m_sizeY - 1) * m_sizeX + xx; else if (xx >= m_sizeX) offset = yy * m_sizeX + (m_sizeX - 1); else offset = yy * m_sizeX + xx; return m_heightMap[offset]; } } // Convert the passed heightmap to mesh information suitable for CreateMeshShape2(). // Version that handles magnification. // Return 'true' if successfully created. public static bool ConvertHeightmapToMesh2( BSScene physicsScene, float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap int magnification, // number of vertices per heighmap step Vector3 extent, // dimensions of the output mesh Vector3 extentBase, // base to be added to all vertices out int indicesCountO, out int[] indicesO, out int verticesCountO, out float[] verticesO) { bool ret = false; int indicesCount = 0; int verticesCount = 0; int[] indices = new int[0]; float[] vertices = new float[0]; HeightMapGetter hmap = new HeightMapGetter(heightMap, sizeX, sizeY); // The vertices dimension of the output mesh int meshX = sizeX * magnification; int meshY = sizeY * magnification; // The output size of one mesh step float meshXStep = extent.X / meshX; float meshYStep = extent.Y / meshY; // Create an array of vertices that is meshX+1 by meshY+1 (note the loop // from zero to <= meshX). The triangle indices are then generated as two triangles // per heightmap point. There are meshX by meshY of these squares. The extra row and // column of vertices are used to complete the triangles of the last row and column // of the heightmap. try { // Vertices for the output heightmap plus one on the side and bottom to complete triangles int totalVertices = (meshX + 1) * (meshY + 1); vertices = new float[totalVertices * 3]; int totalIndices = meshX * meshY * 6; indices = new int[totalIndices]; if (physicsScene != null) physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh2,inSize={1},outSize={2},totVert={3},totInd={4},extentBase={5}", BSScene.DetailLogZero, new Vector2(sizeX, sizeY), new Vector2(meshX, meshY), totalVertices, totalIndices, extentBase); float minHeight = float.MaxValue; // Note that sizeX+1 vertices are created since there is land between this and the next region. // Loop through the output vertices and compute the mediun height in between the input vertices for (int yy = 0; yy <= meshY; yy++) { for (int xx = 0; xx <= meshX; xx++) // Hint: the "<=" means we go around sizeX + 1 times { float offsetY = (float)yy * (float)sizeY / (float)meshY; // The Y that is closest to the mesh point int stepY = (int)offsetY; float fractionalY = offsetY - (float)stepY; float offsetX = (float)xx * (float)sizeX / (float)meshX; // The X that is closest to the mesh point int stepX = (int)offsetX; float fractionalX = offsetX - (float)stepX; // physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh2,xx={1},yy={2},offX={3},stepX={4},fractX={5},offY={6},stepY={7},fractY={8}", // BSScene.DetailLogZero, xx, yy, offsetX, stepX, fractionalX, offsetY, stepY, fractionalY); // get the four corners of the heightmap square the mesh point is in float heightUL = hmap.GetHeight(stepX , stepY ); float heightUR = hmap.GetHeight(stepX + 1, stepY ); float heightLL = hmap.GetHeight(stepX , stepY + 1); float heightLR = hmap.GetHeight(stepX + 1, stepY + 1); // bilinear interplolation float height = heightUL * (1 - fractionalX) * (1 - fractionalY) + heightUR * fractionalX * (1 - fractionalY) + heightLL * (1 - fractionalX) * fractionalY + heightLR * fractionalX * fractionalY; // physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh2,heightUL={1},heightUR={2},heightLL={3},heightLR={4},heightMap={5}", // BSScene.DetailLogZero, heightUL, heightUR, heightLL, heightLR, height); minHeight = Math.Min(minHeight, height); vertices[verticesCount + 0] = (float)xx * meshXStep + extentBase.X; vertices[verticesCount + 1] = (float)yy * meshYStep + extentBase.Y; vertices[verticesCount + 2] = height + extentBase.Z; verticesCount += 3; } } // The number of vertices generated verticesCount /= 3; // Loop through all the heightmap squares and create indices for the two triangles for that square for (int yy = 0; yy < meshY; yy++) { for (int xx = 0; xx < meshX; xx++) { int offset = yy * (meshX + 1) + xx; // Each vertices is presumed to be the upper left corner of a box of two triangles indices[indicesCount + 0] = offset; indices[indicesCount + 1] = offset + 1; indices[indicesCount + 2] = offset + meshX + 1; // accounting for the extra column indices[indicesCount + 3] = offset + 1; indices[indicesCount + 4] = offset + meshX + 2; indices[indicesCount + 5] = offset + meshX + 1; indicesCount += 6; } } ret = true; } catch (Exception e) { if (physicsScene != null) physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. For={1}/{2}, e={3}", LogHeader, physicsScene.RegionName, extentBase, e); } indicesCountO = indicesCount; indicesO = indices; verticesCountO = verticesCount; verticesO = vertices; return ret; } } }
/* * 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 Tools; namespace Aurora.ScriptEngine.AuroraDotNetEngine.CompilerTools { public class LSL2CSCodeTransformer { private SYMBOL m_astRoot = null; private static Dictionary<string, string> m_datatypeLSL2OpenSim = null; /// <summary> /// Pass the new CodeTranformer an abstract syntax tree. /// </summary> /// <param name="astRoot">The root node of the AST.</param> public LSL2CSCodeTransformer(SYMBOL astRoot) { m_astRoot = astRoot; // let's populate the dictionary if (null == m_datatypeLSL2OpenSim) { m_datatypeLSL2OpenSim = new Dictionary<string, string>(); m_datatypeLSL2OpenSim.Add("integer", "LSL_Types.LSLInteger"); m_datatypeLSL2OpenSim.Add("float", "LSL_Types.LSLFloat"); m_datatypeLSL2OpenSim.Add("key", "LSL_Types.LSLString"); m_datatypeLSL2OpenSim.Add("string", "LSL_Types.LSLString"); m_datatypeLSL2OpenSim.Add("vector", "LSL_Types.Vector3"); m_datatypeLSL2OpenSim.Add("rotation", "LSL_Types.Quaternion"); m_datatypeLSL2OpenSim.Add("list", "LSL_Types.list"); } } /// <summary> /// Transform the code in the AST we have. /// </summary> /// <returns>The root node of the transformed AST</returns> public SYMBOL Transform() { return Transform(null, null); } public SYMBOL Transform(Dictionary<string, string> GlobalMethods, Dictionary<string, ObjectList> MethodArguements) { foreach (SYMBOL s in m_astRoot.kids) TransformNode(s, GlobalMethods, MethodArguements); return m_astRoot; } /// <summary> /// Recursively called to transform each type of node. Will transform this /// node, then all it's children. /// </summary> /// <param name="s">The current node to transform.</param> private void TransformNode(SYMBOL s, Dictionary<string, string> GlobalMethods, Dictionary<string, ObjectList> MethodArguements) { // make sure to put type lower in the inheritance hierarchy first // ie: since IdentConstant and StringConstant inherit from Constant, // put IdentConstant and StringConstant before Constant if (s is Declaration) ((Declaration)s).Datatype = m_datatypeLSL2OpenSim[((Declaration)s).Datatype]; else if (s is Constant) ((Constant)s).Type = m_datatypeLSL2OpenSim[((Constant)s).Type]; else if (s is TypecastExpression) ((TypecastExpression)s).TypecastType = m_datatypeLSL2OpenSim[((TypecastExpression)s).TypecastType]; else if (s is GlobalFunctionDefinition) { if ("void" == ((GlobalFunctionDefinition)s).ReturnType) // we don't need to translate "void" { if (GlobalMethods != null && !GlobalMethods.ContainsKey(((GlobalFunctionDefinition)s).Name)) GlobalMethods.Add(((GlobalFunctionDefinition)s).Name, "void"); } else { ((GlobalFunctionDefinition)s).ReturnType = m_datatypeLSL2OpenSim[((GlobalFunctionDefinition)s).ReturnType]; if (GlobalMethods != null && !GlobalMethods.ContainsKey(((GlobalFunctionDefinition)s).Name)) { GlobalMethods.Add(((GlobalFunctionDefinition)s).Name, ((GlobalFunctionDefinition)s).ReturnType); MethodArguements.Add(((GlobalFunctionDefinition)s).Name, ((GlobalFunctionDefinition)s).kids); } } } for (int i = 0; i < s.kids.Count; i++) { // It's possible that a child is null, for instance when the // assignment part in a for-loop is left out, ie: // // for (; i < 10; i++) // { // ... // } // // We need to check for that here. if (null != s.kids[i]) { if (!(s is Assignment || s is ArgumentDeclarationList) && s.kids[i] is Declaration) AddImplicitInitialization(s, i); TransformNode((SYMBOL)s.kids[i], null, null); } } } /// <summary> /// Replaces an instance of the node at s.kids[didx] with an assignment /// node. The assignment node has the Declaration node on the left hand /// side and a default initializer on the right hand side. /// </summary> /// <param name="s"> /// The node containing the Declaration node that needs replacing. /// </param> /// <param name="didx">Index of the Declaration node to replace.</param> private void AddImplicitInitialization(SYMBOL s, int didx) { // We take the kids for a while to play with them. int sKidSize = s.kids.Count; object [] sKids = new object[sKidSize]; for (int i = 0; i < sKidSize; i++) sKids[i] = s.kids.Pop(); // The child to be changed. Declaration currentDeclaration = (Declaration) sKids[didx]; // We need an assignment node. Assignment newAssignment = new Assignment(currentDeclaration.yyps, currentDeclaration, GetZeroConstant(currentDeclaration.yyps, currentDeclaration.Datatype), "="); sKids[didx] = newAssignment; // Put the kids back where they belong. for (int i = 0; i < sKidSize; i++) s.kids.Add(sKids[i]); } /// <summary> /// Generates the node structure required to generate a default /// initialization. /// </summary> /// <param name="p"> /// Tools.Parser instance to use when instantiating nodes. /// </param> /// <param name="constantType">String describing the datatype.</param> /// <returns> /// A SYMBOL node conaining the appropriate structure for intializing a /// constantType. /// </returns> private SYMBOL GetZeroConstant(Parser p, string constantType) { switch (constantType) { case "integer": return new Constant(p, constantType, "0"); case "float": return new Constant(p, constantType, "0.0"); case "string": case "key": return new Constant(p, constantType, ""); case "list": ArgumentList al = new ArgumentList(p); return new ListConstant(p, al); case "vector": Constant vca = new Constant(p, "float", "0.0"); Constant vcb = new Constant(p, "float", "0.0"); Constant vcc = new Constant(p, "float", "0.0"); ConstantExpression vcea = new ConstantExpression(p, vca); ConstantExpression vceb = new ConstantExpression(p, vcb); ConstantExpression vcec = new ConstantExpression(p, vcc); return new VectorConstant(p, vcea, vceb, vcec); case "rotation": Constant rca = new Constant(p, "float", "0.0"); Constant rcb = new Constant(p, "float", "0.0"); Constant rcc = new Constant(p, "float", "0.0"); Constant rcd = new Constant(p, "float", "0.0"); ConstantExpression rcea = new ConstantExpression(p, rca); ConstantExpression rceb = new ConstantExpression(p, rcb); ConstantExpression rcec = new ConstantExpression(p, rcc); ConstantExpression rced = new ConstantExpression(p, rcd); return new RotationConstant(p, rcea, rceb, rcec, rced); default: return null; // this will probably break stuff } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// CountryResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Pricing.V1.Voice { public class CountryResource : Resource { private static Request BuildReadRequest(ReadCountryOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Pricing, "/v1/Voice/Countries", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Country parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Country </returns> public static ResourceSet<CountryResource> Read(ReadCountryOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<CountryResource>.FromJson("countries", response.Content); return new ResourceSet<CountryResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Country parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Country </returns> public static async System.Threading.Tasks.Task<ResourceSet<CountryResource>> ReadAsync(ReadCountryOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<CountryResource>.FromJson("countries", response.Content); return new ResourceSet<CountryResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Country </returns> public static ResourceSet<CountryResource> Read(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadCountryOptions(){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Country </returns> public static async System.Threading.Tasks.Task<ResourceSet<CountryResource>> ReadAsync(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadCountryOptions(){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<CountryResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<CountryResource>.FromJson("countries", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<CountryResource> NextPage(Page<CountryResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Pricing) ); var response = client.Request(request); return Page<CountryResource>.FromJson("countries", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<CountryResource> PreviousPage(Page<CountryResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Pricing) ); var response = client.Request(request); return Page<CountryResource>.FromJson("countries", response.Content); } private static Request BuildFetchRequest(FetchCountryOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Pricing, "/v1/Voice/Countries/" + options.PathIsoCountry + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Country parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Country </returns> public static CountryResource Fetch(FetchCountryOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Country parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Country </returns> public static async System.Threading.Tasks.Task<CountryResource> FetchAsync(FetchCountryOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathIsoCountry"> The ISO country code </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Country </returns> public static CountryResource Fetch(string pathIsoCountry, ITwilioRestClient client = null) { var options = new FetchCountryOptions(pathIsoCountry); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathIsoCountry"> The ISO country code </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Country </returns> public static async System.Threading.Tasks.Task<CountryResource> FetchAsync(string pathIsoCountry, ITwilioRestClient client = null) { var options = new FetchCountryOptions(pathIsoCountry); return await FetchAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a CountryResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> CountryResource object represented by the provided JSON </returns> public static CountryResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<CountryResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The name of the country /// </summary> [JsonProperty("country")] public string Country { get; private set; } /// <summary> /// The ISO country code /// </summary> [JsonProperty("iso_country")] public string IsoCountry { get; private set; } /// <summary> /// The list of OutboundPrefixPrice records /// </summary> [JsonProperty("outbound_prefix_prices")] public List<OutboundPrefixPrice> OutboundPrefixPrices { get; private set; } /// <summary> /// The list of InboundCallPrice records /// </summary> [JsonProperty("inbound_call_prices")] public List<InboundCallPrice> InboundCallPrices { get; private set; } /// <summary> /// The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) /// </summary> [JsonProperty("price_unit")] public string PriceUnit { get; private set; } /// <summary> /// The absolute URL of the resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private CountryResource() { } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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.IO; namespace Contoso.Compression.LZ { /// <summary> /// BinTree /// </summary> public class BinTree : InWindow, IMatchFinder { private const uint Hash2Size = 1 << 10; private const uint Hash3Size = 1 << 16; private const uint BT2HashSize = 1 << 16; private const uint StartMaxLen = 1; private const uint Hash3Offset = Hash2Size; private const uint EmptyHashValue = 0; private const uint MaxValForNormalize = ((uint)1 << 31) - 1; private uint _cyclicBufferPos; private uint _cyclicBufferSize = 0; private uint _matchMaxLen; private uint[] _son; private uint[] _hash; private uint _cutValue = 0xFF; private uint _hashMask; private uint _hashSizeSum = 0; private bool HASH_ARRAY = true; private uint kNumHashDirectBytes = 0; private uint kMinMatchCheck = 4; private uint kFixHashSize = Hash2Size + Hash3Size; /// <summary> /// Sets the type. /// </summary> /// <param name="numHashBytes">The num hash bytes.</param> public void SetType(int numHashBytes) { HASH_ARRAY = (numHashBytes > 2); if (HASH_ARRAY) { kNumHashDirectBytes = 0; kMinMatchCheck = 4; kFixHashSize = Hash2Size + Hash3Size; } else { kNumHashDirectBytes = 2; kMinMatchCheck = 2 + 1; kFixHashSize = 0; } } /// <summary> /// Sets the stream. /// </summary> /// <param name="stream">The stream.</param> public new void SetStream(Stream stream) { base.SetStream(stream); } /// <summary> /// Releases the stream. /// </summary> public new void ReleaseStream() { base.ReleaseStream(); } /// <summary> /// Inits this instance. /// </summary> public new void Init() { base.Init(); for (uint i = 0; i < _hashSizeSum; i++) _hash[i] = EmptyHashValue; _cyclicBufferPos = 0; ReduceOffsets(-1); } /// <summary> /// Moves the pos. /// </summary> public new void MovePos() { if (++_cyclicBufferPos >= _cyclicBufferSize) _cyclicBufferPos = 0; base.MovePos(); if (_pos == MaxValForNormalize) Normalize(); } /// <summary> /// Gets the index byte. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> public new Byte GetIndexByte(int index) { return base.GetIndexByte(index); } /// <summary> /// Gets the match len. /// </summary> /// <param name="index">The index.</param> /// <param name="distance">The distance.</param> /// <param name="limit">The limit.</param> /// <returns></returns> public new uint GetMatchLen(int index, uint distance, uint limit) { return base.GetMatchLen(index, distance, limit); } /// <summary> /// Gets the num available bytes. /// </summary> /// <returns></returns> public new uint GetNumAvailableBytes() { return base.GetNumAvailableBytes(); } /// <summary> /// Creates the specified history size. /// </summary> /// <param name="historySize">Size of the history.</param> /// <param name="keepAddBufferBefore">The keep add buffer before.</param> /// <param name="matchMaxLen">The match max len.</param> /// <param name="keepAddBufferAfter">The keep add buffer after.</param> public void Create(uint historySize, uint keepAddBufferBefore, uint matchMaxLen, uint keepAddBufferAfter) { if (historySize > MaxValForNormalize - 256) throw new Exception(); _cutValue = 16 + (matchMaxLen >> 1); uint windowReservSize = (historySize + keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + 256; base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); _matchMaxLen = matchMaxLen; uint cyclicBufferSize = historySize + 1; if (_cyclicBufferSize != cyclicBufferSize) _son = new uint[(_cyclicBufferSize = cyclicBufferSize) * 2]; uint hs = BT2HashSize; if (HASH_ARRAY) { hs = historySize - 1; hs |= (hs >> 1); hs |= (hs >> 2); hs |= (hs >> 4); hs |= (hs >> 8); hs >>= 1; hs |= 0xFFFF; if (hs > (1 << 24)) hs >>= 1; _hashMask = hs; hs++; hs += kFixHashSize; } if (hs != _hashSizeSum) _hash = new uint[_hashSizeSum = hs]; } /// <summary> /// Gets the matches. /// </summary> /// <param name="distances">The distances.</param> /// <returns></returns> public uint GetMatches(uint[] distances) { uint lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); return 0; } } uint offset = 0; uint matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; uint cur = _bufferOffset + _pos; uint maxLen = StartMaxLen; // to avoid items for len < hashSize; uint hashValue, hash2Value = 0, hash3Value = 0; if (HASH_ARRAY) { uint temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; hash2Value = temp & (Hash2Size - 1); temp ^= ((uint)(_bufferBase[cur + 2]) << 8); hash3Value = temp & (Hash3Size - 1); hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; } else hashValue = _bufferBase[cur] ^ ((uint)(_bufferBase[cur + 1]) << 8); uint curMatch = _hash[kFixHashSize + hashValue]; if (HASH_ARRAY) { uint curMatch2 = _hash[hash2Value]; uint curMatch3 = _hash[Hash3Offset + hash3Value]; _hash[hash2Value] = _pos; _hash[Hash3Offset + hash3Value] = _pos; if (curMatch2 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) { distances[offset++] = maxLen = 2; distances[offset++] = _pos - curMatch2 - 1; } if (curMatch3 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) { if (curMatch3 == curMatch2) offset -= 2; distances[offset++] = maxLen = 3; distances[offset++] = _pos - curMatch3 - 1; curMatch2 = curMatch3; } if (offset != 0 && curMatch2 == curMatch) { offset -= 2; maxLen = StartMaxLen; } } _hash[kFixHashSize + hashValue] = _pos; uint ptr0 = (_cyclicBufferPos << 1) + 1; uint ptr1 = (_cyclicBufferPos << 1); uint len0, len1; len0 = len1 = kNumHashDirectBytes; if (kNumHashDirectBytes != 0) if (curMatch > matchMinPos) if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != _bufferBase[cur + kNumHashDirectBytes]) { distances[offset++] = maxLen = kNumHashDirectBytes; distances[offset++] = _pos - curMatch - 1; } uint count = _cutValue; while (true) { if (curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = EmptyHashValue; break; } uint delta = _pos - curMatch; uint cyclicPos = (delta <= _cyclicBufferPos ? _cyclicBufferPos - delta : _cyclicBufferPos - delta + _cyclicBufferSize) << 1; uint pby1 = _bufferOffset + curMatch; uint len = Math.Min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while (++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (maxLen < len) { distances[offset++] = maxLen = len; distances[offset++] = delta - 1; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } } if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); return offset; } /// <summary> /// Skips the specified num. /// </summary> /// <param name="num">The num.</param> public void Skip(uint num) { do { uint lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); continue; } } uint matchMinPos = (_pos > _cyclicBufferSize ? _pos - _cyclicBufferSize : 0); uint cur = _bufferOffset + _pos; uint hashValue; if (HASH_ARRAY) { uint temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; uint hash2Value = temp & (Hash2Size - 1); _hash[hash2Value] = _pos; temp ^= ((uint)(_bufferBase[cur + 2]) << 8); uint hash3Value = temp & (Hash3Size - 1); _hash[Hash3Offset + hash3Value] = _pos; hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; } else hashValue = _bufferBase[cur] ^ ((uint)(_bufferBase[cur + 1]) << 8); uint curMatch = _hash[kFixHashSize + hashValue]; _hash[kFixHashSize + hashValue] = _pos; uint ptr0 = (_cyclicBufferPos << 1) + 1; uint ptr1 = (_cyclicBufferPos << 1); uint len0, len1; len0 = len1 = kNumHashDirectBytes; uint count = _cutValue; while (true) { if (curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = EmptyHashValue; break; } uint delta = _pos - curMatch; uint cyclicPos = (delta <= _cyclicBufferPos ? _cyclicBufferPos - delta : _cyclicBufferPos - delta + _cyclicBufferSize) << 1; uint pby1 = _bufferOffset + curMatch; uint len = Math.Min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while (++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); } while (--num != 0); } private void NormalizeLinks(uint[] items, uint numItems, uint subValue) { for (uint i = 0; i < numItems; i++) { uint value = items[i]; if (value <= subValue) value = EmptyHashValue; else value -= subValue; items[i] = value; } } private void Normalize() { uint subValue = _pos - _cyclicBufferSize; NormalizeLinks(_son, _cyclicBufferSize * 2, subValue); NormalizeLinks(_hash, _hashSizeSum, subValue); ReduceOffsets((int)subValue); } /// <summary> /// Sets the cut value. /// </summary> /// <param name="cutValue">The cut value.</param> public void SetCutValue(uint cutValue) { _cutValue = cutValue; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G02Level1 (editable root object).<br/> /// This is a generated base class of <see cref="G02Level1"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="G03Level11Objects"/> of type <see cref="G03Level11Coll"/> (1:M relation to <see cref="G04Level11"/>) /// </remarks> [Serializable] public partial class G02Level1 : BusinessBase<G02Level1> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Level_1_IDProperty = RegisterProperty<int>(p => p.Level_1_ID, "Level_1 ID"); /// <summary> /// Gets the Level_1 ID. /// </summary> /// <value>The Level_1 ID.</value> public int Level_1_ID { get { return GetProperty(Level_1_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Level_1_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_NameProperty = RegisterProperty<string>(p => p.Level_1_Name, "Level_1 Name"); /// <summary> /// Gets or sets the Level_1 Name. /// </summary> /// <value>The Level_1 Name.</value> public string Level_1_Name { get { return GetProperty(Level_1_NameProperty); } set { SetProperty(Level_1_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G03Level11SingleObject"/> property. /// </summary> public static readonly PropertyInfo<G03Level11Child> G03Level11SingleObjectProperty = RegisterProperty<G03Level11Child>(p => p.G03Level11SingleObject, "A3 Level11 Single Object", RelationshipTypes.Child); /// <summary> /// Gets the G03 Level11 Single Object ("self load" child property). /// </summary> /// <value>The G03 Level11 Single Object.</value> public G03Level11Child G03Level11SingleObject { get { return GetProperty(G03Level11SingleObjectProperty); } private set { LoadProperty(G03Level11SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G03Level11ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<G03Level11ReChild> G03Level11ASingleObjectProperty = RegisterProperty<G03Level11ReChild>(p => p.G03Level11ASingleObject, "A3 Level11 ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the G03 Level11 ASingle Object ("self load" child property). /// </summary> /// <value>The G03 Level11 ASingle Object.</value> public G03Level11ReChild G03Level11ASingleObject { get { return GetProperty(G03Level11ASingleObjectProperty); } private set { LoadProperty(G03Level11ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G03Level11Objects"/> property. /// </summary> public static readonly PropertyInfo<G03Level11Coll> G03Level11ObjectsProperty = RegisterProperty<G03Level11Coll>(p => p.G03Level11Objects, "A3 Level11 Objects", RelationshipTypes.Child); /// <summary> /// Gets the G03 Level11 Objects ("self load" child property). /// </summary> /// <value>The G03 Level11 Objects.</value> public G03Level11Coll G03Level11Objects { get { return GetProperty(G03Level11ObjectsProperty); } private set { LoadProperty(G03Level11ObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G02Level1"/> object. /// </summary> /// <returns>A reference to the created <see cref="G02Level1"/> object.</returns> public static G02Level1 NewG02Level1() { return DataPortal.Create<G02Level1>(); } /// <summary> /// Factory method. Loads a <see cref="G02Level1"/> object, based on given parameters. /// </summary> /// <param name="level_1_ID">The Level_1_ID parameter of the G02Level1 to fetch.</param> /// <returns>A reference to the fetched <see cref="G02Level1"/> object.</returns> public static G02Level1 GetG02Level1(int level_1_ID) { return DataPortal.Fetch<G02Level1>(level_1_ID); } /// <summary> /// Factory method. Marks the <see cref="G02Level1"/> object for deletion. /// The object will be deleted as part of the next save operation. /// </summary> /// <param name="level_1_ID">The Level_1_ID of the G02Level1 to delete.</param> public static void DeleteG02Level1(int level_1_ID) { DataPortal.Delete<G02Level1>(level_1_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G02Level1"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private G02Level1() { // Prevent direct creation } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G02Level1"/> object properties. /// </summary> [Csla.RunLocal] protected override void DataPortal_Create() { LoadProperty(Level_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(G03Level11SingleObjectProperty, DataPortal.CreateChild<G03Level11Child>()); LoadProperty(G03Level11ASingleObjectProperty, DataPortal.CreateChild<G03Level11ReChild>()); LoadProperty(G03Level11ObjectsProperty, DataPortal.CreateChild<G03Level11Coll>()); var args = new DataPortalHookArgs(); OnCreate(args); base.DataPortal_Create(); } /// <summary> /// Loads a <see cref="G02Level1"/> object from the database, based on given criteria. /// </summary> /// <param name="level_1_ID">The Level_1 ID.</param> protected void DataPortal_Fetch(int level_1_ID) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetG02Level1", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", level_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, level_1_ID); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } FetchChildren(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } BusinessRules.CheckRules(); } } /// <summary> /// Loads a <see cref="G02Level1"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_IDProperty, dr.GetInt32("Level_1_ID")); LoadProperty(Level_1_NameProperty, dr.GetString("Level_1_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> private void FetchChildren() { LoadProperty(G03Level11SingleObjectProperty, G03Level11Child.GetG03Level11Child(Level_1_ID)); LoadProperty(G03Level11ASingleObjectProperty, G03Level11ReChild.GetG03Level11ReChild(Level_1_ID)); LoadProperty(G03Level11ObjectsProperty, G03Level11Coll.GetG03Level11Coll(Level_1_ID)); } /// <summary> /// Inserts a new <see cref="G02Level1"/> object in the database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddG02Level1", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", ReadProperty(Level_1_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Level_1_Name", ReadProperty(Level_1_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(Level_1_IDProperty, (int) cmd.Parameters["@Level_1_ID"].Value); } FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="G02Level1"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateG02Level1", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", ReadProperty(Level_1_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_Name", ReadProperty(Level_1_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="G02Level1"/> object. /// </summary> protected override void DataPortal_DeleteSelf() { DataPortal_Delete(Level_1_ID); } /// <summary> /// Deletes the <see cref="G02Level1"/> object from database. /// </summary> /// <param name="level_1_ID">The delete criteria.</param> [Transactional(TransactionalTypes.TransactionScope)] protected void DataPortal_Delete(int level_1_ID) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteG02Level1", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", level_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, level_1_ID); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(G03Level11SingleObjectProperty, DataPortal.CreateChild<G03Level11Child>()); LoadProperty(G03Level11ASingleObjectProperty, DataPortal.CreateChild<G03Level11ReChild>()); LoadProperty(G03Level11ObjectsProperty, DataPortal.CreateChild<G03Level11Coll>()); } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Collections.Generic; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Rest.Supersim.V1; namespace Twilio.Tests.Rest.Supersim.V1 { [TestFixture] public class SimTest : TwilioTest { [Test] public void TestCreateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Supersim, "/v1/Sims", "" ); request.AddPostParam("Iccid", Serialize("iccid")); request.AddPostParam("RegistrationCode", Serialize("registration_code")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { SimResource.Create("iccid", "registration_code", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestCreateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.Created, "{\"sid\": \"HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"\",\"status\": \"new\",\"fleet_sid\": null,\"iccid\": \"89883070000123456789\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"links\": {\"billing_periods\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BillingPeriods\"}}" )); var response = SimResource.Create("iccid", "registration_code", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestFetchRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Supersim, "/v1/Sims/HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { SimResource.Fetch("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestFetchResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"My SIM\",\"status\": \"new\",\"fleet_sid\": null,\"iccid\": \"89883070000123456789\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"links\": {\"billing_periods\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BillingPeriods\"}}" )); var response = SimResource.Fetch("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Supersim, "/v1/Sims/HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { SimResource.Update("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestUpdateUniqueNameResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"MySIM\",\"status\": \"new\",\"fleet_sid\": null,\"iccid\": \"89883070000123456789\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"links\": {\"billing_periods\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BillingPeriods\"}}" )); var response = SimResource.Update("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateStatusResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": null,\"status\": \"scheduled\",\"fleet_sid\": null,\"iccid\": \"89883070000123456789\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"links\": {\"billing_periods\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BillingPeriods\"}}" )); var response = SimResource.Update("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateFleetWithSidResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": null,\"status\": \"new\",\"fleet_sid\": \"HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"iccid\": \"89883070000123456789\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"links\": {\"billing_periods\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BillingPeriods\"}}" )); var response = SimResource.Update("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateFleetWithUniqueNameResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": null,\"status\": \"new\",\"fleet_sid\": \"HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"iccid\": \"89883070000123456789\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"links\": {\"billing_periods\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BillingPeriods\"}}" )); var response = SimResource.Update("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestTransferSimToAnotherAccountResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"unique_name\": null,\"status\": \"new\",\"fleet_sid\": \"HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"iccid\": \"89883070000123456789\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"links\": {\"billing_periods\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BillingPeriods\"}}" )); var response = SimResource.Update("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Supersim, "/v1/Sims", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { SimResource.Read(client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestReadEmptyResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sims\": [],\"meta\": {\"first_page_url\": \"https://supersim.twilio.com/v1/Sims?Status=new&Fleet=HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0\",\"key\": \"sims\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://supersim.twilio.com/v1/Sims?Status=new&Fleet=HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0\"}}" )); var response = SimResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadFullByFleetSidResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"meta\": {\"first_page_url\": \"https://supersim.twilio.com/v1/Sims?Status=new&Fleet=HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0\",\"key\": \"sims\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://supersim.twilio.com/v1/Sims?Status=new&Fleet=HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0\"},\"sims\": [{\"sid\": \"HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"My SIM\",\"status\": \"new\",\"fleet_sid\": \"HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"iccid\": \"89883070000123456789\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"links\": {\"billing_periods\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BillingPeriods\"}}]}" )); var response = SimResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadFullByFleetNameResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"meta\": {\"first_page_url\": \"https://supersim.twilio.com/v1/Sims?Status=new&Fleet=MyFleet&PageSize=50&Page=0\",\"key\": \"sims\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://supersim.twilio.com/v1/Sims?Status=new&Fleet=MyFleet&PageSize=50&Page=0\"},\"sims\": [{\"sid\": \"HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"My SIM\",\"status\": \"new\",\"fleet_sid\": \"HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"iccid\": \"89883070000123456789\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"links\": {\"billing_periods\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BillingPeriods\"}}]}" )); var response = SimResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadByIccidResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"meta\": {\"first_page_url\": \"https://supersim.twilio.com/v1/Sims?Iccid=89883070000123456789&PageSize=50&Page=0\",\"key\": \"sims\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://supersim.twilio.com/v1/Sims?Iccid=89883070000123456789&PageSize=50&Page=0\"},\"sims\": [{\"sid\": \"HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"My SIM\",\"status\": \"new\",\"fleet_sid\": null,\"iccid\": \"89883070000123456789\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"links\": {\"billing_periods\": \"https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BillingPeriods\"}}]}" )); var response = SimResource.Read(client: twilioRestClient); Assert.NotNull(response); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using Avalonia.Controls.Generators; using Avalonia.Controls.Platform; using Avalonia.Controls.Primitives; using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.Controls.Templates; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Layout; using Avalonia.Styling; #nullable enable namespace Avalonia.Controls { /// <summary> /// A control context menu. /// </summary> public class ContextMenu : MenuBase, ISetterValue { /// <summary> /// Defines the <see cref="HorizontalOffset"/> property. /// </summary> public static readonly StyledProperty<double> HorizontalOffsetProperty = Popup.HorizontalOffsetProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="VerticalOffset"/> property. /// </summary> public static readonly StyledProperty<double> VerticalOffsetProperty = Popup.VerticalOffsetProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementAnchor"/> property. /// </summary> public static readonly StyledProperty<PopupAnchor> PlacementAnchorProperty = Popup.PlacementAnchorProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementConstraintAdjustment"/> property. /// </summary> public static readonly StyledProperty<PopupPositionerConstraintAdjustment> PlacementConstraintAdjustmentProperty = Popup.PlacementConstraintAdjustmentProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementGravity"/> property. /// </summary> public static readonly StyledProperty<PopupGravity> PlacementGravityProperty = Popup.PlacementGravityProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementMode"/> property. /// </summary> public static readonly StyledProperty<PlacementMode> PlacementModeProperty = Popup.PlacementModeProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementRect"/> property. /// </summary> public static readonly StyledProperty<Rect?> PlacementRectProperty = AvaloniaProperty.Register<Popup, Rect?>(nameof(PlacementRect)); /// <summary> /// Defines the <see cref="WindowManagerAddShadowHint"/> property. /// </summary> public static readonly StyledProperty<bool> WindowManagerAddShadowHintProperty = Popup.WindowManagerAddShadowHintProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementTarget"/> property. /// </summary> public static readonly StyledProperty<Control?> PlacementTargetProperty = Popup.PlacementTargetProperty.AddOwner<ContextMenu>(); private static readonly ITemplate<IPanel> DefaultPanel = new FuncTemplate<IPanel>(() => new StackPanel { Orientation = Orientation.Vertical }); private Popup? _popup; private List<Control>? _attachedControls; private IInputElement? _previousFocus; /// <summary> /// Initializes a new instance of the <see cref="ContextMenu"/> class. /// </summary> public ContextMenu() : this(new DefaultMenuInteractionHandler(true)) { } /// <summary> /// Initializes a new instance of the <see cref="ContextMenu"/> class. /// </summary> /// <param name="interactionHandler">The menu interaction handler.</param> public ContextMenu(IMenuInteractionHandler interactionHandler) : base(interactionHandler) { } /// <summary> /// Initializes static members of the <see cref="ContextMenu"/> class. /// </summary> static ContextMenu() { ItemsPanelProperty.OverrideDefaultValue<ContextMenu>(DefaultPanel); PlacementModeProperty.OverrideDefaultValue<ContextMenu>(PlacementMode.Pointer); ContextMenuProperty.Changed.Subscribe(ContextMenuChanged); } /// <summary> /// Gets or sets the Horizontal offset of the context menu in relation to the <see cref="PlacementTarget"/>. /// </summary> public double HorizontalOffset { get { return GetValue(HorizontalOffsetProperty); } set { SetValue(HorizontalOffsetProperty, value); } } /// <summary> /// Gets or sets the Vertical offset of the context menu in relation to the <see cref="PlacementTarget"/>. /// </summary> public double VerticalOffset { get { return GetValue(VerticalOffsetProperty); } set { SetValue(VerticalOffsetProperty, value); } } /// <summary> /// Gets or sets the anchor point on the <see cref="PlacementRect"/> when <see cref="PlacementMode"/> /// is <see cref="PlacementMode.AnchorAndGravity"/>. /// </summary> public PopupAnchor PlacementAnchor { get { return GetValue(PlacementAnchorProperty); } set { SetValue(PlacementAnchorProperty, value); } } /// <summary> /// Gets or sets a value describing how the context menu position will be adjusted if the /// unadjusted position would result in the context menu being partly constrained. /// </summary> public PopupPositionerConstraintAdjustment PlacementConstraintAdjustment { get { return GetValue(PlacementConstraintAdjustmentProperty); } set { SetValue(PlacementConstraintAdjustmentProperty, value); } } /// <summary> /// Gets or sets a value which defines in what direction the context menu should open /// when <see cref="PlacementMode"/> is <see cref="PlacementMode.AnchorAndGravity"/>. /// </summary> public PopupGravity PlacementGravity { get { return GetValue(PlacementGravityProperty); } set { SetValue(PlacementGravityProperty, value); } } /// <summary> /// Gets or sets the placement mode of the context menu in relation to the<see cref="PlacementTarget"/>. /// </summary> public PlacementMode PlacementMode { get { return GetValue(PlacementModeProperty); } set { SetValue(PlacementModeProperty, value); } } public bool WindowManagerAddShadowHint { get { return GetValue(WindowManagerAddShadowHintProperty); } set { SetValue(WindowManagerAddShadowHintProperty, value); } } /// <summary> /// Gets or sets the the anchor rectangle within the parent that the context menu will be placed /// relative to when <see cref="PlacementMode"/> is <see cref="PlacementMode.AnchorAndGravity"/>. /// </summary> /// <remarks> /// The placement rect defines a rectangle relative to <see cref="PlacementTarget"/> around /// which the popup will be opened, with <see cref="PlacementAnchor"/> determining which edge /// of the placement target is used. /// /// If unset, the anchor rectangle will be the bounds of the <see cref="PlacementTarget"/>. /// </remarks> public Rect? PlacementRect { get { return GetValue(PlacementRectProperty); } set { SetValue(PlacementRectProperty, value); } } /// <summary> /// Gets or sets the control that is used to determine the popup's position. /// </summary> public Control? PlacementTarget { get { return GetValue(PlacementTargetProperty); } set { SetValue(PlacementTargetProperty, value); } } /// <summary> /// Occurs when the value of the /// <see cref="P:Avalonia.Controls.ContextMenu.IsOpen" /> /// property is changing from false to true. /// </summary> public event CancelEventHandler? ContextMenuOpening; /// <summary> /// Occurs when the value of the /// <see cref="P:Avalonia.Controls.ContextMenu.IsOpen" /> /// property is changing from true to false. /// </summary> public event CancelEventHandler? ContextMenuClosing; /// <summary> /// Called when the <see cref="Control.ContextMenu"/> property changes on a control. /// </summary> /// <param name="e">The event args.</param> private static void ContextMenuChanged(AvaloniaPropertyChangedEventArgs e) { var control = (Control)e.Sender; if (e.OldValue is ContextMenu oldMenu) { control.PointerReleased -= ControlPointerReleased; oldMenu._attachedControls?.Remove(control); ((ISetLogicalParent?)oldMenu._popup)?.SetParent(null); } if (e.NewValue is ContextMenu newMenu) { newMenu._attachedControls ??= new List<Control>(); newMenu._attachedControls.Add(control); control.PointerReleased += ControlPointerReleased; } } /// <summary> /// Opens the menu. /// </summary> public override void Open() => throw new NotSupportedException(); /// <summary> /// Opens a context menu on the specified control. /// </summary> /// <param name="control">The control.</param> public void Open(Control? control) { if (control is null && (_attachedControls is null || _attachedControls.Count == 0)) { throw new ArgumentNullException(nameof(control)); } if (control is object && _attachedControls is object && !_attachedControls.Contains(control)) { throw new ArgumentException( "Cannot show ContentMenu on a different control to the one it is attached to.", nameof(control)); } control ??= _attachedControls![0]; if (IsOpen) { return; } if (_popup == null) { _popup = new Popup { HorizontalOffset = HorizontalOffset, VerticalOffset = VerticalOffset, PlacementAnchor = PlacementAnchor, PlacementConstraintAdjustment = PlacementConstraintAdjustment, PlacementGravity = PlacementGravity, PlacementMode = PlacementMode, PlacementRect = PlacementRect, PlacementTarget = PlacementTarget ?? control, IsLightDismissEnabled = true, OverlayDismissEventPassThrough = true, WindowManagerAddShadowHint = WindowManagerAddShadowHint, }; _popup.Opened += PopupOpened; _popup.Closed += PopupClosed; } if (_popup.Parent != control) { ((ISetLogicalParent)_popup).SetParent(null); ((ISetLogicalParent)_popup).SetParent(control); } if (PlacementTarget is null && _popup.PlacementTarget != control) { _popup.PlacementTarget = control; } _popup.Child = this; IsOpen = true; _popup.IsOpen = true; RaiseEvent(new RoutedEventArgs { RoutedEvent = MenuOpenedEvent, Source = this, }); } /// <summary> /// Closes the menu. /// </summary> public override void Close() { if (!IsOpen) { return; } if (_popup != null && _popup.IsVisible) { _popup.IsOpen = false; } } void ISetterValue.Initialize(ISetter setter) { // ContextMenu can be assigned to the ContextMenu property in a setter. This overrides // the behavior defined in Control which requires controls to be wrapped in a <template>. if (!(setter is Setter s && s.Property == ContextMenuProperty)) { throw new InvalidOperationException( "Cannot use a control as a Setter value. Wrap the control in a <Template>."); } } protected override IItemContainerGenerator CreateItemContainerGenerator() { return new MenuItemContainerGenerator(this); } private void PopupOpened(object sender, EventArgs e) { _previousFocus = FocusManager.Instance?.Current; Focus(); } private void PopupClosed(object sender, EventArgs e) { foreach (var i in LogicalChildren) { if (i is MenuItem menuItem) { menuItem.IsSubMenuOpen = false; } } SelectedIndex = -1; IsOpen = false; if (_attachedControls is null || _attachedControls.Count == 0) { ((ISetLogicalParent)_popup!).SetParent(null); } // HACK: Reset the focus when the popup is closed. We need to fix this so it's automatic. FocusManager.Instance?.Focus(_previousFocus); RaiseEvent(new RoutedEventArgs { RoutedEvent = MenuClosedEvent, Source = this, }); } private static void ControlPointerReleased(object sender, PointerReleasedEventArgs e) { var control = (Control)sender; var contextMenu = control.ContextMenu; if (control.ContextMenu.IsOpen) { if (contextMenu.CancelClosing()) return; control.ContextMenu.Close(); e.Handled = true; } if (e.InitialPressMouseButton == MouseButton.Right) { if (contextMenu.CancelOpening()) return; contextMenu.Open(control); e.Handled = true; } } private bool CancelClosing() { var eventArgs = new CancelEventArgs(); ContextMenuClosing?.Invoke(this, eventArgs); return eventArgs.Cancel; } private bool CancelOpening() { var eventArgs = new CancelEventArgs(); ContextMenuOpening?.Invoke(this, eventArgs); return eventArgs.Cancel; } } }
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using FizzWare.NBuilder; using Moq; using NUnit.Framework; using ReMi.Common.Constants.ProductRequests; using ReMi.Common.Utils; using ReMi.Common.Utils.Repository; using ReMi.TestUtils.UnitTests; using ReMi.DataAccess.BusinessEntityGateways.ProductRequests; using ReMi.DataAccess.Exceptions; using ReMi.DataEntities.Auth; using ReMi.DataEntities.ProductRequests; namespace ReMi.DataAccess.Tests.ProductRequests { public class ProductRequestRegistrationGatewayTests : TestClassFor<ProductRequestRegistrationGateway> { private Mock<IRepository<Account>> _accountRepositoryMock; private Mock<IRepository<ProductRequestRegistration>> _productRequestRegistrationRepositoryMock; private Mock<IRepository<ProductRequestRegistrationTask>> _productRequestRegistrationTaskRepositoryMock; private Mock<IRepository<ProductRequestType>> _productRequestTypeRepositoryMock; private Mock<IMappingEngine> _mappingEngineMock; protected override ProductRequestRegistrationGateway ConstructSystemUnderTest() { return new ProductRequestRegistrationGateway { AccountRepository = _accountRepositoryMock.Object, ProductRequestRegistrationRepository = _productRequestRegistrationRepositoryMock.Object, ProductRequestRegistrationTaskRepository = _productRequestRegistrationTaskRepositoryMock.Object, ProductRequestTypeRepository = _productRequestTypeRepositoryMock.Object, MappingEngine = _mappingEngineMock.Object }; } protected override void TestInitialize() { _accountRepositoryMock = new Mock<IRepository<Account>>(); _productRequestRegistrationRepositoryMock = new Mock<IRepository<ProductRequestRegistration>>(); _productRequestRegistrationTaskRepositoryMock = new Mock<IRepository<ProductRequestRegistrationTask>>(); _productRequestTypeRepositoryMock = new Mock<IRepository<ProductRequestType>>(); _mappingEngineMock = new Mock<IMappingEngine>(); _mappingEngineMock .Setup(o => o.Map<BusinessEntities.ProductRequests.ProductRequestRegistration, ProductRequestRegistration>(It.IsAny<BusinessEntities.ProductRequests.ProductRequestRegistration>())) .Returns<BusinessEntities.ProductRequests.ProductRequestRegistration>(r => new ProductRequestRegistration { ExternalId = r.ExternalId }); base.TestInitialize(); } [Test] public void GetRegistrations_ShouldThrowException_WhenRegistrationAlreadyExists() { var entities = new[] { new ProductRequestRegistration{Deleted = true}, new ProductRequestRegistration{Deleted = false}, new ProductRequestRegistration{Deleted = null} }; _productRequestRegistrationRepositoryMock.SetupEntities(entities); Sut.GetRegistrations(); _mappingEngineMock.Verify(x => x.Map<IEnumerable<ProductRequestRegistration>, IEnumerable<BusinessEntities.ProductRequests.ProductRequestRegistration>>( It.Is<IEnumerable<ProductRequestRegistration>>(e => e.Count() == 2)), Times.Once); } [Test] [ExpectedException(typeof(EntityAlreadyExistsException))] public void CreateProductRequestRegistration_ShouldThrowException_WhenRegistrationAlreadyExists() { var registrationId = Guid.NewGuid(); var reg = CreateRegistration(registrationId); _productRequestRegistrationRepositoryMock.SetupEntities(new[] { Builder<ProductRequestRegistration>.CreateNew() .With(o => o.ExternalId, registrationId) .Build() }); Sut.CreateProductRequestRegistration(reg); } [Test] [ExpectedException(typeof(EntityNotFoundException))] public void CreateProductRequestRegistration_ShouldThrowException_WhenRequestTypeNotFound() { var reg = CreateRegistration(); Sut.CreateProductRequestRegistration(reg); } [Test] [ExpectedException(typeof(AccountNotFoundException))] public void CreateProductRequestRegistration_ShouldThrowException_WhenAccountNotFound() { var reg = CreateRegistration(); SetupRequestType(reg.ProductRequestTypeId); Sut.CreateProductRequestRegistration(reg); } [Test] public void CreateProductRequestRegistration_ShouldCallMapping_WhenInvoked() { var reg = CreateRegistration(); SetupRequestType(reg.ProductRequestTypeId); SetupAccount(reg.CreatedByAccountId); Sut.CreateProductRequestRegistration(reg); _mappingEngineMock.Verify(o => o.Map<BusinessEntities.ProductRequests.ProductRequestRegistration, ProductRequestRegistration>(reg)); } [Test] public void CreateProductRequestRegistration_ShouldInsertToRepository_WhenInvoked() { var reg = CreateRegistration(); var requestType = SetupRequestType(reg.ProductRequestTypeId); var account = SetupAccount(reg.CreatedByAccountId); var dt = DateTime.UtcNow; SystemTime.Mock(dt); Sut.CreateProductRequestRegistration(reg); _productRequestRegistrationRepositoryMock.Verify(o => o.Insert(It.Is<ProductRequestRegistration>(x => x.CreatedOn == dt && x.ProductRequestTypeId == requestType.ProductRequestTypeId && x.CreatedByAccountId == account.AccountId))); } [Test] public void CreateProductRequestRegistration_ShouldInsertChildTasksToRepository_WhenInvoked() { var taskId = Guid.NewGuid(); var reg = CreateRegistration(taskId: taskId); SetupRequestType(reg.ProductRequestTypeId, taskId); var account = SetupAccount(reg.CreatedByAccountId); var dt = DateTime.UtcNow; SystemTime.Mock(dt); var registrationId = RandomData.RandomInt(1, int.MaxValue); _productRequestRegistrationRepositoryMock.Setup(o => o.Insert(It.IsAny<ProductRequestRegistration>())) .Callback<ProductRequestRegistration>(registration => registration.ProductRequestRegistrationId = registrationId); Sut.CreateProductRequestRegistration(reg); _productRequestRegistrationTaskRepositoryMock.Verify(o => o.Insert(It.Is<ProductRequestRegistrationTask>(x => x.LastChangedOn == dt && x.ProductRequestRegistrationId == registrationId && x.LastChangedByAccountId == account.AccountId))); } [Test] [ExpectedException(typeof(EntityNotFoundException))] public void UpdateProductRequestRegistration_ShouldThrowException_WhenRegistrationNotFound() { var registrationId = Guid.NewGuid(); var reg = CreateRegistration(registrationId); Sut.UpdateProductRequestRegistration(reg); } [Test] [ExpectedException(typeof(EntityNotFoundException))] public void UpdateProductRequestRegistration_ShouldThrowException_WhenRequestTypeNotFound() { var reg = CreateRegistration(); SetupRegistration(reg.ExternalId); Sut.UpdateProductRequestRegistration(reg); } [Test] [ExpectedException(typeof(AccountNotFoundException))] public void UpdateProductRequestRegistration_ShouldThrowException_WhenAccountNotFound() { var reg = CreateRegistration(); SetupRegistration(reg.ExternalId); SetupRequestType(reg.ProductRequestTypeId); Sut.UpdateProductRequestRegistration(reg); } [Test] public void UpdateProductRequestRegistration_ShouldInsertToRepository_WhenInvoked() { var reg = CreateRegistration(); SetupRegistration(reg.ExternalId); SetupRequestType(reg.ProductRequestTypeId); SetupAccount(reg.CreatedByAccountId); Sut.UpdateProductRequestRegistration(reg); _productRequestRegistrationRepositoryMock.Verify(o => o.Update(It.Is<ProductRequestRegistration>(x => x.Description == reg.Description))); } [Test] public void UpdateProductRequestRegistration_ShouldInsertChildTasksToRepository_WhenInvoked() { var taskId = Guid.NewGuid(); var reg = CreateRegistration(taskId: taskId); SetupRegistration(reg.ExternalId); SetupRequestType(reg.ProductRequestTypeId, taskId); var account = SetupAccount(reg.CreatedByAccountId); var dt = DateTime.UtcNow; SystemTime.Mock(dt); _productRequestRegistrationTaskRepositoryMock.SetupEntities(new[] { Builder<ProductRequestRegistrationTask>.CreateNew() .With(o => o.ProductRequestRegistration, Builder<ProductRequestRegistration>.CreateNew().With(x => x.ExternalId, reg.ExternalId).Build()) .With(o => o.ProductRequestTask, Builder<ProductRequestTask>.CreateNew().With(x => x.ExternalId, taskId).Build()) .Build() }); Sut.UpdateProductRequestRegistration(reg); _productRequestRegistrationTaskRepositoryMock.Verify(o => o.Update(It.Is<ProductRequestRegistrationTask>(x => x.LastChangedOn == dt && x.LastChangedByAccountId == account.AccountId && x.IsCompleted == reg.Tasks.ElementAt(0).IsCompleted))); } [Test] [ExpectedException(typeof(EntityNotFoundException))] public void DeleteProductRequestRegistration_ShouldThrowException_WhenRegistrationNotFound() { var registrationId = Guid.NewGuid(); var reg = CreateRegistration(registrationId); Sut.DeleteProductRequestRegistration(reg.ExternalId, RemovingReason.ClosedAndLive, null); } [Test] public void DeleteProductRequestRegistration_ShouldMarkEntityAsDeletedAndAddRemovingReason_WhenInvoked() { var registrationId = Guid.NewGuid(); var removingReason = RandomData.RandomEnum<RemovingReason>(); var comment = RandomData.RandomString(100); var reg = CreateRegistration(registrationId); SetupRegistration(registrationId); Sut.DeleteProductRequestRegistration(reg.ExternalId, removingReason, comment); _productRequestRegistrationRepositoryMock.Verify(o => o.Update(It.Is<ProductRequestRegistration>(x => x.ExternalId == reg.ExternalId && x.Deleted == true && x.RemovingReason.Comment == comment && x.RemovingReason.RemovingReason == removingReason))); } [Test] public void OnDisposing_ShouldDisposeAllObject_WhenInvoked() { Sut.OnDisposing(); _productRequestTypeRepositoryMock.Verify(o => o.Dispose()); _productRequestRegistrationRepositoryMock.Verify(o => o.Dispose()); _productRequestRegistrationTaskRepositoryMock.Verify(o => o.Dispose()); _mappingEngineMock.Verify(o => o.Dispose()); _accountRepositoryMock.Verify(o => o.Dispose()); } #region Helpers private BusinessEntities.ProductRequests.ProductRequestRegistration CreateRegistration(Guid? externalId = null, Guid? taskId = null, bool isCompleted = true) { return Builder<BusinessEntities.ProductRequests.ProductRequestRegistration>.CreateNew() .With(o => o.ExternalId, externalId ?? Guid.NewGuid()) .With(o => o.CreatedByAccountId, Guid.NewGuid()) .With(o => o.ProductRequestTypeId, Guid.NewGuid()) .With(o => o.Tasks, !taskId.HasValue ? null : new[] { Builder<BusinessEntities.ProductRequests.ProductRequestRegistrationTask>.CreateNew() .With(o => o.ProductRequestTaskId, taskId.Value) .With(o => o.IsCompleted, isCompleted) .Build() }) .Build(); } private ProductRequestRegistration SetupRegistration(Guid? externalId = null, Guid? taskId = null, bool isCompleted = false) { var registration = Builder<ProductRequestRegistration>.CreateNew() .With(o => o.ExternalId, externalId ?? Guid.NewGuid()) .With(o => o.Description, null) .With(x => x.ProductRequestRegistrationId, RandomData.RandomInt(int.MaxValue)) .With(o => o.Tasks, !taskId.HasValue ? null : new[]{ Builder<ProductRequestRegistrationTask>.CreateNew() .With(x => x.ProductRequestTask, Builder<ProductRequestTask>.CreateNew().With(x => x.ExternalId, taskId.Value).Build()) .With(x => x.IsCompleted, isCompleted) .Build() }.ToList()) .Build(); _productRequestRegistrationRepositoryMock.SetupEntities(new[] { registration }); return registration; } private ProductRequestType SetupRequestType(Guid? externalId = null, Guid? taskId = null) { var result = Builder<ProductRequestType>.CreateNew() .With(o => o.ExternalId, externalId ?? Guid.NewGuid()) .With(o => o.ProductRequestTypeId, RandomData.RandomInt(1, int.MaxValue)) .With(o => o.RequestGroups, !taskId.HasValue ? null : new[] { Builder<ProductRequestGroup>.CreateNew() .With(o => o.ExternalId, Guid.NewGuid()) .With(o => o.RequestTasks, new[]{ Builder<ProductRequestTask>.CreateNew() .With(o => o.ExternalId, taskId.Value) .With(o => o.Question, RandomData.RandomString(1, 1024)) .Build() }) .Build() }) .Build(); _productRequestTypeRepositoryMock.SetupEntities(new[] { result }); return result; } private Account SetupAccount(Guid? externalId = null) { var result = Builder<Account>.CreateNew() .With(o => o.ExternalId, externalId ?? Guid.NewGuid()) .With(o => o.AccountId, RandomData.RandomInt(1, int.MaxValue)) .Build(); _accountRepositoryMock.SetupEntities(new[] { result }); return result; } #endregion } }
// // 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.Globalization; 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 System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Storage; using Microsoft.WindowsAzure.Management.Storage.Models; namespace Microsoft.WindowsAzure.Management.Storage { /// <summary> /// The Service Management API includes operations for managing the storage /// accounts beneath your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460790.aspx for /// more information) /// </summary> internal partial class StorageAccountOperations : IServiceOperations<StorageManagementClient>, IStorageAccountOperations { /// <summary> /// Initializes a new instance of the StorageAccountOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal StorageAccountOperations(StorageManagementClient client) { this._client = client; } private StorageManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Storage.StorageManagementClient. /// </summary> public StorageManagementClient Client { get { return this._client; } } /// <summary> /// The Create Storage Account operation creates a new storage account /// in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Storage Account operation. /// </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> BeginCreatingAsync(StorageAccountCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Description != null && parameters.Description.Length > 1024) { throw new ArgumentOutOfRangeException("parameters.Description"); } if (parameters.Label == null) { throw new ArgumentNullException("parameters.Label"); } if (parameters.Label.Length > 100) { throw new ArgumentOutOfRangeException("parameters.Label"); } if (parameters.ServiceName == null) { throw new ArgumentNullException("parameters.ServiceName"); } if (parameters.ServiceName.Length < 3) { throw new ArgumentOutOfRangeException("parameters.ServiceName"); } if (parameters.ServiceName.Length > 24) { throw new ArgumentOutOfRangeException("parameters.ServiceName"); } foreach (char serviceNameChar in parameters.ServiceName) { if (char.IsLower(serviceNameChar) == false && char.IsDigit(serviceNameChar) == false) { throw new ArgumentOutOfRangeException("parameters.ServiceName"); } } // TODO: Validate parameters.ServiceName is a valid DNS name. int locationCount = (parameters.AffinityGroup != null ? 1 : 0) + (parameters.Location != null ? 1 : 0); if (locationCount != 1) { throw new ArgumentException("Only one of parameters.AffinityGroup, parameters.Location may be provided."); } // 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("parameters", parameters); Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/storageservices"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement createStorageServiceInputElement = new XElement(XName.Get("CreateStorageServiceInput", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(createStorageServiceInputElement); XElement serviceNameElement = new XElement(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure")); serviceNameElement.Value = parameters.ServiceName; createStorageServiceInputElement.Add(serviceNameElement); XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = TypeConversion.ToBase64String(parameters.Label); createStorageServiceInputElement.Add(labelElement); if (parameters.Description != null) { XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); descriptionElement.Value = parameters.Description; createStorageServiceInputElement.Add(descriptionElement); } else { XElement emptyElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); XAttribute nilAttribute = new XAttribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"), ""); nilAttribute.Value = "true"; emptyElement.Add(nilAttribute); createStorageServiceInputElement.Add(emptyElement); } if (parameters.Location != null) { XElement locationElement = new XElement(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); locationElement.Value = parameters.Location; createStorageServiceInputElement.Add(locationElement); } if (parameters.AffinityGroup != null) { XElement affinityGroupElement = new XElement(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure")); affinityGroupElement.Value = parameters.AffinityGroup; createStorageServiceInputElement.Add(affinityGroupElement); } XElement geoReplicationEnabledElement = new XElement(XName.Get("GeoReplicationEnabled", "http://schemas.microsoft.com/windowsazure")); geoReplicationEnabledElement.Value = parameters.GeoReplicationEnabled.ToString().ToLower(); createStorageServiceInputElement.Add(geoReplicationEnabledElement); if (parameters.ExtendedProperties != null) { XElement extendedPropertiesDictionaryElement = new XElement(XName.Get("ExtendedProperties", "http://schemas.microsoft.com/windowsazure")); foreach (KeyValuePair<string, string> pair in parameters.ExtendedProperties) { string extendedPropertiesKey = pair.Key; string extendedPropertiesValue = pair.Value; XElement extendedPropertiesElement = new XElement(XName.Get("ExtendedProperty", "http://schemas.microsoft.com/windowsazure")); extendedPropertiesDictionaryElement.Add(extendedPropertiesElement); XElement extendedPropertiesKeyElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); extendedPropertiesKeyElement.Value = extendedPropertiesKey; extendedPropertiesElement.Add(extendedPropertiesKeyElement); XElement extendedPropertiesValueElement = new XElement(XName.Get("Value", "http://schemas.microsoft.com/windowsazure")); extendedPropertiesValueElement.Value = extendedPropertiesValue; extendedPropertiesElement.Add(extendedPropertiesValueElement); } createStorageServiceInputElement.Add(extendedPropertiesDictionaryElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml"); // 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.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); 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(); } } } /// <summary> /// The Check Name Availability operation checks if a storage account /// name is available for use in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154125.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The desired storage account name to check for availability. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response to a storage account check name availability request. /// </returns> public async Task<CheckNameAvailabilityResponse> CheckNameAvailabilityAsync(string serviceName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // 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("serviceName", serviceName); Tracing.Enter(invocationId, this, "CheckNameAvailabilityAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/storageservices/operations/isavailable/" + serviceName; // 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-version", "2013-03-01"); // 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), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result CheckNameAvailabilityResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new CheckNameAvailabilityResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement availabilityResponseElement = responseDoc.Element(XName.Get("AvailabilityResponse", "http://schemas.microsoft.com/windowsazure")); if (availabilityResponseElement != null) { XElement resultElement = availabilityResponseElement.Element(XName.Get("Result", "http://schemas.microsoft.com/windowsazure")); if (resultElement != null) { bool resultInstance = bool.Parse(resultElement.Value); result.IsAvailable = resultInstance; } XElement reasonElement = availabilityResponseElement.Element(XName.Get("Reason", "http://schemas.microsoft.com/windowsazure")); if (reasonElement != null) { bool isNil = false; XAttribute nilAttribute = reasonElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance")); if (nilAttribute != null) { isNil = nilAttribute.Value == "true"; } if (isNil == false) { string reasonInstance = reasonElement.Value; result.Reason = reasonInstance; } } } 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> /// The Create Storage Account operation creates a new storage account /// in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Storage Account operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<StorageOperationStatusResponse> CreateAsync(StorageAccountCreateParameters parameters, CancellationToken cancellationToken) { StorageManagementClient client = this.Client; 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("parameters", parameters); Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); OperationResponse response = await client.StorageAccounts.BeginCreatingAsync(parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); StorageOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; } if (shouldTrace) { Tracing.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.ErrorCode = result.Error.Code; ex.ErrorMessage = result.Error.Message; if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } return result; } finally { if (client != null && shouldTrace) { client.Dispose(); } } } /// <summary> /// The Delete Storage Account operation deletes the specifiedstorage /// account from Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh264517.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the storage account. /// </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> DeleteAsync(string serviceName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // 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("serviceName", serviceName); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/storageservices/" + serviceName; // 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", "2013-03-01"); // 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), CloudExceptionType.Xml); 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(); } } } /// <summary> /// The Get Storage Account Properties operation returns system /// properties for the specified storage account. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460802.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Name of the storage account to get. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Storage Account Properties operation response. /// </returns> public async Task<StorageServiceGetResponse> GetAsync(string serviceName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // 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("serviceName", serviceName); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/storageservices/" + serviceName; // 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-version", "2013-03-01"); // 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), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result StorageServiceGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new StorageServiceGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement storageServiceElement = responseDoc.Element(XName.Get("StorageService", "http://schemas.microsoft.com/windowsazure")); if (storageServiceElement != null) { XElement urlElement = storageServiceElement.Element(XName.Get("Url", "http://schemas.microsoft.com/windowsazure")); if (urlElement != null) { Uri urlInstance = TypeConversion.TryParseUri(urlElement.Value); result.Uri = urlInstance; } XElement serviceNameElement = storageServiceElement.Element(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure")); if (serviceNameElement != null) { string serviceNameInstance = serviceNameElement.Value; result.ServiceName = serviceNameInstance; } XElement storageServicePropertiesElement = storageServiceElement.Element(XName.Get("StorageServiceProperties", "http://schemas.microsoft.com/windowsazure")); if (storageServicePropertiesElement != null) { StorageServiceProperties storageServicePropertiesInstance = new StorageServiceProperties(); result.Properties = storageServicePropertiesInstance; XElement descriptionElement = storageServicePropertiesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { bool isNil = false; XAttribute nilAttribute = descriptionElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance")); if (nilAttribute != null) { isNil = nilAttribute.Value == "true"; } if (isNil == false) { string descriptionInstance = descriptionElement.Value; storageServicePropertiesInstance.Description = descriptionInstance; } } XElement affinityGroupElement = storageServicePropertiesElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure")); if (affinityGroupElement != null) { string affinityGroupInstance = affinityGroupElement.Value; storageServicePropertiesInstance.AffinityGroup = affinityGroupInstance; } XElement locationElement = storageServicePropertiesElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); if (locationElement != null) { string locationInstance = locationElement.Value; storageServicePropertiesInstance.Location = locationInstance; } XElement labelElement = storageServicePropertiesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = TypeConversion.FromBase64String(labelElement.Value); storageServicePropertiesInstance.Label = labelInstance; } XElement statusElement = storageServicePropertiesElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { StorageServiceStatus statusInstance = (StorageServiceStatus)Enum.Parse(typeof(StorageServiceStatus), statusElement.Value, false); storageServicePropertiesInstance.Status = statusInstance; } XElement endpointsSequenceElement = storageServicePropertiesElement.Element(XName.Get("Endpoints", "http://schemas.microsoft.com/windowsazure")); if (endpointsSequenceElement != null) { foreach (XElement endpointsElement in endpointsSequenceElement.Elements(XName.Get("Endpoint", "http://schemas.microsoft.com/windowsazure"))) { storageServicePropertiesInstance.Endpoints.Add(TypeConversion.TryParseUri(endpointsElement.Value)); } } XElement geoReplicationEnabledElement = storageServicePropertiesElement.Element(XName.Get("GeoReplicationEnabled", "http://schemas.microsoft.com/windowsazure")); if (geoReplicationEnabledElement != null) { bool geoReplicationEnabledInstance = bool.Parse(geoReplicationEnabledElement.Value); storageServicePropertiesInstance.GeoReplicationEnabled = geoReplicationEnabledInstance; } XElement geoPrimaryRegionElement = storageServicePropertiesElement.Element(XName.Get("GeoPrimaryRegion", "http://schemas.microsoft.com/windowsazure")); if (geoPrimaryRegionElement != null) { string geoPrimaryRegionInstance = geoPrimaryRegionElement.Value; storageServicePropertiesInstance.GeoPrimaryRegion = geoPrimaryRegionInstance; } XElement statusOfPrimaryElement = storageServicePropertiesElement.Element(XName.Get("StatusOfPrimary", "http://schemas.microsoft.com/windowsazure")); if (statusOfPrimaryElement != null && string.IsNullOrEmpty(statusOfPrimaryElement.Value) == false) { GeoRegionStatus statusOfPrimaryInstance = (GeoRegionStatus)Enum.Parse(typeof(GeoRegionStatus), statusOfPrimaryElement.Value, false); storageServicePropertiesInstance.StatusOfGeoPrimaryRegion = statusOfPrimaryInstance; } XElement lastGeoFailoverTimeElement = storageServicePropertiesElement.Element(XName.Get("LastGeoFailoverTime", "http://schemas.microsoft.com/windowsazure")); if (lastGeoFailoverTimeElement != null && string.IsNullOrEmpty(lastGeoFailoverTimeElement.Value) == false) { DateTime lastGeoFailoverTimeInstance = DateTime.Parse(lastGeoFailoverTimeElement.Value, CultureInfo.InvariantCulture); storageServicePropertiesInstance.LastGeoFailoverTime = lastGeoFailoverTimeInstance; } XElement geoSecondaryRegionElement = storageServicePropertiesElement.Element(XName.Get("GeoSecondaryRegion", "http://schemas.microsoft.com/windowsazure")); if (geoSecondaryRegionElement != null) { string geoSecondaryRegionInstance = geoSecondaryRegionElement.Value; storageServicePropertiesInstance.GeoSecondaryRegion = geoSecondaryRegionInstance; } XElement statusOfSecondaryElement = storageServicePropertiesElement.Element(XName.Get("StatusOfSecondary", "http://schemas.microsoft.com/windowsazure")); if (statusOfSecondaryElement != null && string.IsNullOrEmpty(statusOfSecondaryElement.Value) == false) { GeoRegionStatus statusOfSecondaryInstance = (GeoRegionStatus)Enum.Parse(typeof(GeoRegionStatus), statusOfSecondaryElement.Value, false); storageServicePropertiesInstance.StatusOfGeoSecondaryRegion = statusOfSecondaryInstance; } } XElement extendedPropertiesSequenceElement = storageServiceElement.Element(XName.Get("ExtendedProperties", "http://schemas.microsoft.com/windowsazure")); if (extendedPropertiesSequenceElement != null) { foreach (XElement extendedPropertiesElement in extendedPropertiesSequenceElement.Elements(XName.Get("ExtendedProperty", "http://schemas.microsoft.com/windowsazure"))) { string extendedPropertiesKey = extendedPropertiesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")).Value; string extendedPropertiesValue = extendedPropertiesElement.Element(XName.Get("Value", "http://schemas.microsoft.com/windowsazure")).Value; result.ExtendedProperties.Add(extendedPropertiesKey, extendedPropertiesValue); } } XElement capabilitiesSequenceElement = storageServiceElement.Element(XName.Get("Capabilities", "http://schemas.microsoft.com/windowsazure")); if (capabilitiesSequenceElement != null) { foreach (XElement capabilitiesElement in capabilitiesSequenceElement.Elements(XName.Get("Capability", "http://schemas.microsoft.com/windowsazure"))) { result.Capabilities.Add(capabilitiesElement.Value); } } } 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> /// The Get Storage Keys operation returns the primary and secondary /// access keys for the specified storage account. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460785.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the desired storage account. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The primary and secondary access keys for a storage account. /// </returns> public async Task<StorageAccountGetKeysResponse> GetKeysAsync(string serviceName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // 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("serviceName", serviceName); Tracing.Enter(invocationId, this, "GetKeysAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/storageservices/" + serviceName + "/keys"; // 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-version", "2013-03-01"); // 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), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result StorageAccountGetKeysResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new StorageAccountGetKeysResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement storageServiceElement = responseDoc.Element(XName.Get("StorageService", "http://schemas.microsoft.com/windowsazure")); if (storageServiceElement != null) { XElement urlElement = storageServiceElement.Element(XName.Get("Url", "http://schemas.microsoft.com/windowsazure")); if (urlElement != null) { Uri urlInstance = TypeConversion.TryParseUri(urlElement.Value); result.Uri = urlInstance; } XElement storageServiceKeysElement = storageServiceElement.Element(XName.Get("StorageServiceKeys", "http://schemas.microsoft.com/windowsazure")); if (storageServiceKeysElement != null) { XElement primaryElement = storageServiceKeysElement.Element(XName.Get("Primary", "http://schemas.microsoft.com/windowsazure")); if (primaryElement != null) { string primaryInstance = primaryElement.Value; result.PrimaryKey = primaryInstance; } XElement secondaryElement = storageServiceKeysElement.Element(XName.Get("Secondary", "http://schemas.microsoft.com/windowsazure")); if (secondaryElement != null) { string secondaryInstance = secondaryElement.Value; result.SecondaryKey = secondaryInstance; } } } 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> /// The List Storage Accounts operation lists the storage accounts /// available under the current subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460787.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Storage Accounts operation response. /// </returns> public async Task<StorageServiceListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/storageservices"; // 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-version", "2013-03-01"); // 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), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result StorageServiceListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new StorageServiceListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement storageServicesSequenceElement = responseDoc.Element(XName.Get("StorageServices", "http://schemas.microsoft.com/windowsazure")); if (storageServicesSequenceElement != null) { foreach (XElement storageServicesElement in storageServicesSequenceElement.Elements(XName.Get("StorageService", "http://schemas.microsoft.com/windowsazure"))) { StorageServiceListResponse.StorageService storageServiceInstance = new StorageServiceListResponse.StorageService(); result.StorageServices.Add(storageServiceInstance); XElement urlElement = storageServicesElement.Element(XName.Get("Url", "http://schemas.microsoft.com/windowsazure")); if (urlElement != null) { Uri urlInstance = TypeConversion.TryParseUri(urlElement.Value); storageServiceInstance.Uri = urlInstance; } XElement serviceNameElement = storageServicesElement.Element(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure")); if (serviceNameElement != null) { string serviceNameInstance = serviceNameElement.Value; storageServiceInstance.ServiceName = serviceNameInstance; } XElement storageServicePropertiesElement = storageServicesElement.Element(XName.Get("StorageServiceProperties", "http://schemas.microsoft.com/windowsazure")); if (storageServicePropertiesElement != null) { StorageServiceProperties storageServicePropertiesInstance = new StorageServiceProperties(); storageServiceInstance.Properties = storageServicePropertiesInstance; XElement descriptionElement = storageServicePropertiesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { bool isNil = false; XAttribute nilAttribute = descriptionElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance")); if (nilAttribute != null) { isNil = nilAttribute.Value == "true"; } if (isNil == false) { string descriptionInstance = descriptionElement.Value; storageServicePropertiesInstance.Description = descriptionInstance; } } XElement affinityGroupElement = storageServicePropertiesElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure")); if (affinityGroupElement != null) { string affinityGroupInstance = affinityGroupElement.Value; storageServicePropertiesInstance.AffinityGroup = affinityGroupInstance; } XElement locationElement = storageServicePropertiesElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); if (locationElement != null) { string locationInstance = locationElement.Value; storageServicePropertiesInstance.Location = locationInstance; } XElement labelElement = storageServicePropertiesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = TypeConversion.FromBase64String(labelElement.Value); storageServicePropertiesInstance.Label = labelInstance; } XElement statusElement = storageServicePropertiesElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { StorageServiceStatus statusInstance = (StorageServiceStatus)Enum.Parse(typeof(StorageServiceStatus), statusElement.Value, false); storageServicePropertiesInstance.Status = statusInstance; } XElement endpointsSequenceElement = storageServicePropertiesElement.Element(XName.Get("Endpoints", "http://schemas.microsoft.com/windowsazure")); if (endpointsSequenceElement != null) { foreach (XElement endpointsElement in endpointsSequenceElement.Elements(XName.Get("Endpoint", "http://schemas.microsoft.com/windowsazure"))) { storageServicePropertiesInstance.Endpoints.Add(TypeConversion.TryParseUri(endpointsElement.Value)); } } XElement geoReplicationEnabledElement = storageServicePropertiesElement.Element(XName.Get("GeoReplicationEnabled", "http://schemas.microsoft.com/windowsazure")); if (geoReplicationEnabledElement != null) { bool geoReplicationEnabledInstance = bool.Parse(geoReplicationEnabledElement.Value); storageServicePropertiesInstance.GeoReplicationEnabled = geoReplicationEnabledInstance; } XElement geoPrimaryRegionElement = storageServicePropertiesElement.Element(XName.Get("GeoPrimaryRegion", "http://schemas.microsoft.com/windowsazure")); if (geoPrimaryRegionElement != null) { string geoPrimaryRegionInstance = geoPrimaryRegionElement.Value; storageServicePropertiesInstance.GeoPrimaryRegion = geoPrimaryRegionInstance; } XElement statusOfPrimaryElement = storageServicePropertiesElement.Element(XName.Get("StatusOfPrimary", "http://schemas.microsoft.com/windowsazure")); if (statusOfPrimaryElement != null && string.IsNullOrEmpty(statusOfPrimaryElement.Value) == false) { GeoRegionStatus statusOfPrimaryInstance = (GeoRegionStatus)Enum.Parse(typeof(GeoRegionStatus), statusOfPrimaryElement.Value, false); storageServicePropertiesInstance.StatusOfGeoPrimaryRegion = statusOfPrimaryInstance; } XElement lastGeoFailoverTimeElement = storageServicePropertiesElement.Element(XName.Get("LastGeoFailoverTime", "http://schemas.microsoft.com/windowsazure")); if (lastGeoFailoverTimeElement != null && string.IsNullOrEmpty(lastGeoFailoverTimeElement.Value) == false) { DateTime lastGeoFailoverTimeInstance = DateTime.Parse(lastGeoFailoverTimeElement.Value, CultureInfo.InvariantCulture); storageServicePropertiesInstance.LastGeoFailoverTime = lastGeoFailoverTimeInstance; } XElement geoSecondaryRegionElement = storageServicePropertiesElement.Element(XName.Get("GeoSecondaryRegion", "http://schemas.microsoft.com/windowsazure")); if (geoSecondaryRegionElement != null) { string geoSecondaryRegionInstance = geoSecondaryRegionElement.Value; storageServicePropertiesInstance.GeoSecondaryRegion = geoSecondaryRegionInstance; } XElement statusOfSecondaryElement = storageServicePropertiesElement.Element(XName.Get("StatusOfSecondary", "http://schemas.microsoft.com/windowsazure")); if (statusOfSecondaryElement != null && string.IsNullOrEmpty(statusOfSecondaryElement.Value) == false) { GeoRegionStatus statusOfSecondaryInstance = (GeoRegionStatus)Enum.Parse(typeof(GeoRegionStatus), statusOfSecondaryElement.Value, false); storageServicePropertiesInstance.StatusOfGeoSecondaryRegion = statusOfSecondaryInstance; } } XElement extendedPropertiesSequenceElement = storageServicesElement.Element(XName.Get("ExtendedProperties", "http://schemas.microsoft.com/windowsazure")); if (extendedPropertiesSequenceElement != null) { foreach (XElement extendedPropertiesElement in extendedPropertiesSequenceElement.Elements(XName.Get("ExtendedProperty", "http://schemas.microsoft.com/windowsazure"))) { string extendedPropertiesKey = extendedPropertiesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")).Value; string extendedPropertiesValue = extendedPropertiesElement.Element(XName.Get("Value", "http://schemas.microsoft.com/windowsazure")).Value; storageServiceInstance.ExtendedProperties.Add(extendedPropertiesKey, extendedPropertiesValue); } } } } 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> /// The Regenerate Keys operation regenerates the primary or secondary /// access key for the specified storage account. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460795.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Parameters supplied to the Regenerate Keys operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The primary and secondary access keys for a storage account. /// </returns> public async Task<StorageAccountRegenerateKeysResponse> RegenerateKeysAsync(StorageAccountRegenerateKeysParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ServiceName == null) { throw new ArgumentNullException("parameters.ServiceName"); } // 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("parameters", parameters); Tracing.Enter(invocationId, this, "RegenerateKeysAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/storageservices/" + parameters.ServiceName + "/keys?action=regenerate"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement regenerateKeysElement = new XElement(XName.Get("RegenerateKeys", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(regenerateKeysElement); XElement keyTypeElement = new XElement(XName.Get("KeyType", "http://schemas.microsoft.com/windowsazure")); keyTypeElement.Value = parameters.KeyType.ToString(); regenerateKeysElement.Add(keyTypeElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml"); // 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), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result StorageAccountRegenerateKeysResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new StorageAccountRegenerateKeysResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement storageServiceElement = responseDoc.Element(XName.Get("StorageService", "http://schemas.microsoft.com/windowsazure")); if (storageServiceElement != null) { XElement urlElement = storageServiceElement.Element(XName.Get("Url", "http://schemas.microsoft.com/windowsazure")); if (urlElement != null) { Uri urlInstance = TypeConversion.TryParseUri(urlElement.Value); result.Uri = urlInstance; } XElement storageServiceKeysElement = storageServiceElement.Element(XName.Get("StorageServiceKeys", "http://schemas.microsoft.com/windowsazure")); if (storageServiceKeysElement != null) { XElement primaryElement = storageServiceKeysElement.Element(XName.Get("Primary", "http://schemas.microsoft.com/windowsazure")); if (primaryElement != null) { string primaryInstance = primaryElement.Value; result.PrimaryKey = primaryInstance; } XElement secondaryElement = storageServiceKeysElement.Element(XName.Get("Secondary", "http://schemas.microsoft.com/windowsazure")); if (secondaryElement != null) { string secondaryInstance = secondaryElement.Value; result.SecondaryKey = secondaryInstance; } } } 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> /// The Update Storage Account operation updates the label, the /// description, and enables or disables the geo-replication status /// for a storage account in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh264516.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Name of the storage account to update. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Storage Account operation. /// </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> UpdateAsync(string serviceName, StorageAccountUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (serviceName.Length < 3) { throw new ArgumentOutOfRangeException("serviceName"); } if (serviceName.Length > 24) { throw new ArgumentOutOfRangeException("serviceName"); } foreach (char serviceNameChar in serviceName) { if (char.IsLower(serviceNameChar) == false && char.IsDigit(serviceNameChar) == false) { throw new ArgumentOutOfRangeException("serviceName"); } } // TODO: Validate serviceName is a valid DNS name. if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Description != null && parameters.Description.Length > 1024) { throw new ArgumentOutOfRangeException("parameters.Description"); } // 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("serviceName", serviceName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/storageservices/" + serviceName; // 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", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement updateStorageServiceInputElement = new XElement(XName.Get("UpdateStorageServiceInput", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(updateStorageServiceInputElement); if (parameters.Description != null) { XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); descriptionElement.Value = parameters.Description; updateStorageServiceInputElement.Add(descriptionElement); } else { XElement emptyElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); XAttribute nilAttribute = new XAttribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"), ""); nilAttribute.Value = "true"; emptyElement.Add(nilAttribute); updateStorageServiceInputElement.Add(emptyElement); } if (parameters.Label != null) { XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = TypeConversion.ToBase64String(parameters.Label); updateStorageServiceInputElement.Add(labelElement); } if (parameters.GeoReplicationEnabled != null) { XElement geoReplicationEnabledElement = new XElement(XName.Get("GeoReplicationEnabled", "http://schemas.microsoft.com/windowsazure")); geoReplicationEnabledElement.Value = parameters.GeoReplicationEnabled.ToString().ToLower(); updateStorageServiceInputElement.Add(geoReplicationEnabledElement); } if (parameters.ExtendedProperties != null) { XElement extendedPropertiesDictionaryElement = new XElement(XName.Get("ExtendedProperties", "http://schemas.microsoft.com/windowsazure")); foreach (KeyValuePair<string, string> pair in parameters.ExtendedProperties) { string extendedPropertiesKey = pair.Key; string extendedPropertiesValue = pair.Value; XElement extendedPropertiesElement = new XElement(XName.Get("ExtendedProperty", "http://schemas.microsoft.com/windowsazure")); extendedPropertiesDictionaryElement.Add(extendedPropertiesElement); XElement extendedPropertiesKeyElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); extendedPropertiesKeyElement.Value = extendedPropertiesKey; extendedPropertiesElement.Add(extendedPropertiesKeyElement); XElement extendedPropertiesValueElement = new XElement(XName.Get("Value", "http://schemas.microsoft.com/windowsazure")); extendedPropertiesValueElement.Value = extendedPropertiesValue; extendedPropertiesElement.Add(extendedPropertiesValueElement); } updateStorageServiceInputElement.Add(extendedPropertiesDictionaryElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml"); // 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), CloudExceptionType.Xml); 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) Microsoft Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; namespace Microsoft.Research.Tools { /// <summary> /// Deals with the plane representation of a graph. /// </summary> public class GraphLayout { /// <summary> /// Drawing style. /// </summary> public enum Style { /// <summary> /// Normal style. /// </summary> Normal, /// <summary> /// Bold drawing. /// </summary> Bold, /// <summary> /// Fill with color, mostly for nodes. /// </summary> Filled, /// <summary> /// Dotted line. /// </summary> Dotted, /// <summary> /// Solid edge. /// </summary> Solid, } /// <summary> /// A node in the graph. /// </summary> public class GraphNode : IName { /// <summary> /// One of the node shapes. /// </summary> public enum NodeShape { /// <summary> /// Rectangle. /// </summary> Box, /// <summary> /// Ellipse. /// </summary> Ellipse, /// <summary> /// House upside-down. /// </summary> Invhouse, }; /// <summary> /// Node name. /// </summary> public string ObjectName { get; set; } /// <summary> /// Node position and size. /// </summary> public Rectangle2D Position { get; protected set; } /// <summary> /// Line color. /// </summary> public Color LineColor { get; set; } /// <summary> /// Node style. /// </summary> public Style Style { get; set; } /// <summary> /// Node shape. /// </summary> public NodeShape Shape { get; set; } /// <summary> /// Node label. /// </summary> public string Label { get; set; } /// <summary> /// Name of stage described by the plan node. /// </summary> public string Stage { get; set; } /// <summary> /// For each color a percentage, showing how much of the node to fill with that color. /// </summary> public List<Tuple<double, Color>> FillColors { get; set; } private static Pen blackPen = new Pen(Color.Black); private static Pen thickBlackPen = new Pen(Color.Black, 4); /// <summary> /// Create a graph node at a specified position. /// </summary> /// <param name="x">X coordinate.</param> /// <param name="y">Y coordinate.</param> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public GraphNode(double x, double y, double width, double height) { this.Position = new Rectangle2D(x, y, x + width, y + height); this.FillColors = new List<Tuple<double, Color>>(); this.LineColor = Color.Black; } /// <summary> /// True if the node is selected on the plot. /// </summary> public bool Selected { get; set; } /// <summary> /// Draw the node on a panel surface. /// </summary> /// <param name="surface">Surface to draw on.</param> internal void Draw(DrawingSurface2D surface) { if (this.Position.Width > 0) { // Fill colors in bands from left to right double offset = 0; foreach (Tuple<double, Color> band in this.FillColors) { if (band.Item1 <= 0) continue; Color c = band.Item2; var brush = new SolidBrush(c); Point2D left = new Point2D(this.Position.Corner1.X + offset * this.Position.Width, this.Position.Corner1.Y); offset += band.Item1; Point2D right = new Point2D(this.Position.Corner1.X + offset * this.Position.Width, this.Position.Corner2.Y); surface.FillRectangle(brush, new Rectangle2D(left, right)); } Font font = new Font("Arial", 12, FontStyle.Regular); // let's shrink the position for the text to leave some border if (this.Label != null) { const double borderFraction = 8; // reserve 1/8 of the rectangle for border Rectangle2D box = new Rectangle2D( this.Position.Corner1.Translate(this.Position.Width / borderFraction, this.Position.Height / borderFraction), this.Position.Corner2.Translate(-this.Position.Width / borderFraction, -this.Position.Height / borderFraction)); surface.DrawTextInRectangle(this.Label, Brushes.Black, font, box); } } Pen pen = this.Selected ? thickBlackPen : blackPen; switch (this.Shape) { default: case NodeShape.Box: surface.DrawRectangle(this.Position, pen); break; case NodeShape.Ellipse: surface.DrawEllipse(this.LineColor, this.Position, pen, false); break; case NodeShape.Invhouse: { Point2D[] points = new Point2D[5]; points[0] = new Point2D(this.Position.Corner1.X, this.Position.Corner1.Y + this.Position.Height / 3); points[1] = new Point2D(this.Position.Corner1.X, this.Position.Corner2.Y - this.Position.Height / 8); points[2] = new Point2D(this.Position.Corner2.X, this.Position.Corner2.Y - this.Position.Height / 8); points[3] = new Point2D(this.Position.Corner2.X, this.Position.Corner1.Y + this.Position.Height / 3); points[4] = new Point2D(this.Position.Corner1.X + this.Position.Width / 2, this.Position.Corner1.Y); surface.DrawPolygon(this.LineColor, points, pen, false); break; } } } } /// <summary> /// An edge in the graph. /// </summary> public class GraphEdge { /// <summary> /// Name of tail node of edge. /// </summary> public string Tail { get; protected set; } /// <summary> /// Name of head node of edge. /// </summary> public string Head { get; protected set; } /// <summary> /// List of points. /// </summary> public List<Point2D> Spline { get; protected set; } /// <summary> /// Edge style. /// </summary> public Style Style { get; protected set; } /// <summary> /// Line color. /// </summary> public Color Color { get; protected set; } /// <summary> /// Create a simple one-segment edge. /// </summary> /// <param name="xstart">Start of edge x.</param> /// <param name="ystart">Start of edge y.</param> /// <param name="xend">End of edge x.</param> /// <param name="yend">End of edge y.</param> public GraphEdge(double xstart, double ystart, double xend, double yend) { this.Spline = new List<Point2D>(); this.Spline.Add(new Point2D(xstart, ystart)); this.Spline.Add(new Point2D(xend, yend)); this.Color = Color.Black; } /// <summary> /// Draw the edge on the specified surface. /// </summary> /// <param name="surface">Surface to draw on.</param> internal void Draw(DrawingSurface2D surface) { var previous = Spline[0]; int width = this.Style == Style.Bold ? 3 : 1; Pen pen = new Pen(this.Color); pen.Width = width; for (int i = 1; i < Spline.Count; i++) { Point2D point = Spline[i]; if (i == Spline.Count - 1) { // adjust for arrow size at the end of the edge. const double absoluteArrowSize = 0.15; double dx = point.X - previous.X; double dy = point.Y - previous.Y; double len = Math.Sqrt(dx * dx + dy * dy); double adx = absoluteArrowSize * dx / len; double ady = absoluteArrowSize * dy / len; point = new Point2D(point.X + adx, point.Y + ady); //pen.EndCap = LineCap.ArrowAnchor; AdjustableArrowCap cap = new AdjustableArrowCap(4, 6); pen.CustomEndCap = cap; } surface.DrawLine(pen, previous, point, false); previous = point; } } } /// <summary> /// The nodes in the graph. /// </summary> List<GraphNode> nodes; /// <summary> /// The edges in the graph. /// </summary> List<GraphEdge> edges; /// <summary> /// Size of box containing graph layout. /// </summary> Point2D size; /// <summary> /// The list of all nodes in the graph. /// </summary> public IEnumerable<GraphNode> AllNodes { get { return this.nodes; } } /// <summary> /// Create an empty graph layout. /// <param name="height">Height of graph to draw, in some arbitrary unit of measure; node and edge coordinates are relative to these.</param> /// <param name="width">Width of graph to draw, in some arbitrary unit of measure; node and edge coordinates are relative to these.</param> /// </summary> public GraphLayout(double width, double height) { this.size = new Point2D(width, height); this.edges = new List<GraphEdge>(); this.nodes = new List<GraphNode>(); } /// <summary> /// Draw the graph on the specified surface. /// </summary> /// <param name="surface">Surface to draw graph on.</param> public void Draw(DrawingSurface2D surface) { foreach (GraphNode n in this.nodes) n.Draw(surface); foreach (GraphEdge e in this.edges) e.Draw(surface); } /// <summary> /// Coordinates of lower-right point for the layout. /// </summary> public Point2D Size { get { return this.size; } } /// <summary> /// Add a node to the graph. /// </summary> /// <param name="node">Node to add to the graph.</param> public void Add(GraphNode node) { this.nodes.Add(node); } /// <summary> /// Add an edge to the graph. /// </summary> /// <param name="edge">Edge to add.</param> public void Add(GraphEdge edge) { this.edges.Add(edge); } /// <summary> /// Find node which contains the given coordinates. Return null if none. /// </summary> /// <param name="xo">X coordinate where mouse was clicked.</param> /// <param name="yo">Y coordinate where mouse was clicked.</param> /// <returns>Node which contains specified coordinates, or null.</returns> public GraphNode FindNode(double xo, double yo) { Point2D p = new Point2D(xo, yo); foreach (GraphNode node in this.nodes) if (node.Position.Inside(p)) return node; return null; } /// <summary> /// Clear the selection on all nodes. /// </summary> public void ClearSelectedNodes() { foreach (GraphNode n in this.nodes) n.Selected = false; } } }
// 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 Xunit; namespace System.IO.Tests { public class DirectoryInfo_CreateSubDirectory : FileSystemTest { #region UniversalTests [Fact] public void NullAsPath_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(null)); } [Fact] public void EmptyAsPath_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(string.Empty)); } [Fact] public void PathAlreadyExistsAsFile() { string path = GetTestFileName(); File.Create(Path.Combine(TestDirectory, path)).Dispose(); Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path)); Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.AddTrailingSlashIfNeeded(path))); Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.RemoveTrailingSlash(path))); } [Theory] [InlineData(FileAttributes.Hidden)] [InlineData(FileAttributes.ReadOnly)] [InlineData(FileAttributes.Normal)] public void PathAlreadyExistsAsDirectory(FileAttributes attributes) { string path = GetTestFileName(); DirectoryInfo testDir = Directory.CreateDirectory(Path.Combine(TestDirectory, path)); FileAttributes original = testDir.Attributes; try { testDir.Attributes = attributes; Assert.Equal(testDir.FullName, new DirectoryInfo(TestDirectory).CreateSubdirectory(path).FullName); } finally { testDir.Attributes = original; } } [Fact] public void DotIsCurrentDirectory() { string path = GetTestFileName(); DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, ".")); Assert.Equal(IOServices.RemoveTrailingSlash(Path.Combine(TestDirectory, path)), result.FullName); result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, ".") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(Path.Combine(TestDirectory, path)), result.FullName); } [Fact] public void Conflicting_Parent_Directory() { string path = Path.Combine(TestDirectory, GetTestFileName(), "c"); Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path)); } [Fact] public void DotDotIsParentDirectory() { DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), "..")); Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName); result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), "..") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName); } [Fact] public void SubDirectoryIsParentDirectory_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(TestDirectory, ".."))); Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory + "/path").CreateSubdirectory("../../path2")); } [Fact] public void ValidPathWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = IOServices.AddTrailingSlashIfNeeded(component); DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path); Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] public void ValidPathWithoutTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = component; DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path); Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] public void ValidPathWithMultipleSubdirectories() { string dirName = Path.Combine(GetTestFileName(), "Test", "Test", "Test"); DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName); Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName)); } [Fact] public void AllowedSymbols() { string dirName = Path.GetRandomFileName() + "!@#$%^&"; DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName); Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName)); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsControWhiteSpace() { // CreateSubdirectory will throw when passed a path with control whitespace e.g. "\t" var components = IOInputs.GetControlWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(GetTestFileName()); Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(component)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsSimpleWhiteSpace() { // CreateSubdirectory trims all simple whitespace, returning us the parent directory // that called CreateSubdirectory var components = IOInputs.GetSimpleWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(GetTestFileName()); DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(component); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(TestDirectory, IOServices.RemoveTrailingSlash(result.FullName)); }); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixWhiteSpaceAsPath_Allowed() { var paths = IOInputs.GetWhiteSpace(); Assert.All(paths, (path) => { new DirectoryInfo(TestDirectory).CreateSubdirectory(path); Assert.True(Directory.Exists(Path.Combine(TestDirectory, path))); }); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixNonSignificantTrailingWhiteSpace() { // Unix treats trailing/prename whitespace as significant and a part of the name. DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(testDir.Name) + component; DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(path); Assert.True(Directory.Exists(result.FullName)); Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void ExtendedPathSubdirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); Assert.True(testDir.Exists); DirectoryInfo subDir = testDir.CreateSubdirectory("Foo"); Assert.True(subDir.Exists); Assert.StartsWith(IOInputs.ExtendedPrefix, subDir.FullName); } [Fact] [PlatformSpecific(PlatformID.Windows)] // UNC shares public void UNCPathWithOnlySlashes() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<ArgumentException>(() => testDir.CreateSubdirectory("//")); } #endregion } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // // File: UniformGrid.cs // // Description: Implementation of a UniformGrid that evenly distributes // space among its children // // NewsClient is defining this Panel because it wants a // multi-row, multi-column display of news items in the Pod; // Grid can be databound, but it does not do auto-indexing, // meaning that all of the generated items would be laid out // on top of each other. Rather than subclassing Grid to // introduce this auto-indexing behavior, it seemed more // straightforward to construct this straightforward panel. // // NOTE: this is grabed from JeffBog's NewsClient under // windows\wcp\DevTest\Demos\NewsClient\Core and add a FirstColumn property. // //--------------------------------------------------------------------------- using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace System.Windows.Controls.Primitives { /// <summary> /// UniformGrid is used to arrange children in a grid with all equal cell sizes. /// </summary> public class UniformGrid : Panel { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors /// <summary> /// Default constructor. /// </summary> public UniformGrid() : base() { } #endregion Constructors //------------------------------------------------------------------- // // Public Properties // //------------------------------------------------------------------- #region Public Properties /// <summary> /// the start column to arrange children. Leave first 'FirstColumn' /// cells blank. /// </summary> public int FirstColumn { get { return (int)GetValue(FirstColumnProperty); } set { SetValue(FirstColumnProperty, value); } } /// <summary> /// FirstColumnProperty /// </summary> public static readonly DependencyProperty FirstColumnProperty = DependencyProperty.Register( "FirstColumn", typeof(int), typeof(UniformGrid), new FrameworkPropertyMetadata( (int)0, FrameworkPropertyMetadataOptions.AffectsMeasure), new ValidateValueCallback(ValidateFirstColumn)); private static bool ValidateFirstColumn(object o) { return (int)o >= 0; } /// <summary> /// Specifies the number of columns in the grid /// A value of 0 indicates that the column count should be dynamically /// computed based on the number of rows (if specified) and the /// number of non-collapsed children in the grid /// </summary> public int Columns { get { return (int)GetValue(ColumnsProperty); } set { SetValue(ColumnsProperty, value); } } /// <summary> /// DependencyProperty for <see cref="Columns" /> property. /// </summary> public static readonly DependencyProperty ColumnsProperty = DependencyProperty.Register( "Columns", typeof(int), typeof(UniformGrid), new FrameworkPropertyMetadata( (int)0, FrameworkPropertyMetadataOptions.AffectsMeasure), new ValidateValueCallback(ValidateColumns)); private static bool ValidateColumns(object o) { return (int)o >= 0; } /// <summary> /// Specifies the number of rows in the grid /// A value of 0 indicates that the row count should be dynamically /// computed based on the number of columns (if specified) and the /// number of non-collapsed children in the grid /// </summary> public int Rows { get { return (int)GetValue(RowsProperty); } set { SetValue(RowsProperty, value); } } /// <summary> /// DependencyProperty for <see cref="Rows" /> property. /// </summary> public static readonly DependencyProperty RowsProperty = DependencyProperty.Register( "Rows", typeof(int), typeof(UniformGrid), new FrameworkPropertyMetadata( (int)0, FrameworkPropertyMetadataOptions.AffectsMeasure), new ValidateValueCallback(ValidateRows)); private static bool ValidateRows(object o) { return (int)o >= 0; } #endregion Public Properties //------------------------------------------------------------------- // // Protected Methods // //------------------------------------------------------------------- #region Protected Methods /// <summary> /// Compute the desired size of this UniformGrid by measuring all of the /// children with a constraint equal to a cell's portion of the given /// constraint (e.g. for a 2 x 4 grid, the child constraint would be /// constraint.Width*0.5 x constraint.Height*0.25). The maximum child /// width and maximum child height are tracked, and then the desired size /// is computed by multiplying these maximums by the row and column count /// (e.g. for a 2 x 4 grid, the desired size for the UniformGrid would be /// maxChildDesiredWidth*2 x maxChildDesiredHeight*4). /// </summary> /// <param name="constraint">Constraint</param> /// <returns>Desired size</returns> protected override Size MeasureOverride(Size constraint) { UpdateComputedValues(); Size childConstraint = new Size(constraint.Width / _columns, constraint.Height / _rows); double maxChildDesiredWidth = 0.0; double maxChildDesiredHeight = 0.0; // Measure each child, keeping track of maximum desired width and height. for (int i = 0, count = InternalChildren.Count; i < count; ++i) { UIElement child = InternalChildren[i]; // Measure the child. child.Measure(childConstraint); Size childDesiredSize = child.DesiredSize; if (maxChildDesiredWidth < childDesiredSize.Width) { maxChildDesiredWidth = childDesiredSize.Width; } if (maxChildDesiredHeight < childDesiredSize.Height) { maxChildDesiredHeight = childDesiredSize.Height; } } return new Size((maxChildDesiredWidth * _columns),(maxChildDesiredHeight * _rows)); } /// <summary> /// Arrange the children of this UniformGrid by distributing space evenly /// among all of the children, making each child the size equal to a cell's /// portion of the given arrangeSize (e.g. for a 2 x 4 grid, the child size /// would be arrangeSize*0.5 x arrangeSize*0.25) /// </summary> /// <param name="arrangeSize">Arrange size</param> protected override Size ArrangeOverride(Size arrangeSize) { Rect childBounds = new Rect(0, 0, arrangeSize.Width / _columns, arrangeSize.Height / _rows); double xStep = childBounds.Width; double xBound = arrangeSize.Width - 1.0; childBounds.X += childBounds.Width * FirstColumn; // Arrange and Position each child to the same cell size foreach (UIElement child in InternalChildren) { child.Arrange(childBounds); // only advance to the next grid cell if the child was not collapsed if (child.Visibility != Visibility.Collapsed) { childBounds.X += xStep; if (childBounds.X >= xBound) { childBounds.Y += childBounds.Height; childBounds.X = 0; } } } return arrangeSize; } #endregion Protected Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods /// <summary> /// If either Rows or Columns are set to 0, then dynamically compute these /// values based on the actual number of non-collapsed children. /// /// In the case when both Rows and Columns are set to 0, then make Rows /// and Columns be equal, thus laying out in a square grid. /// </summary> private void UpdateComputedValues() { _columns = Columns; _rows = Rows; //parameter checking. if (FirstColumn >= _columns) { //NOTE: maybe we shall throw here. But this is somewhat out of //the MCC itself. We need a whole new panel spec. FirstColumn = 0; } if ((_rows == 0) || (_columns == 0)) { int nonCollapsedCount = 0; // First compute the actual # of non-collapsed children to be laid out for (int i = 0, count = InternalChildren.Count; i < count; ++i) { UIElement child = InternalChildren[i]; if (child.Visibility != Visibility.Collapsed) { nonCollapsedCount++; } } // to ensure that we have at leat one row & column, make sure // that nonCollapsedCount is at least 1 if (nonCollapsedCount == 0) { nonCollapsedCount = 1; } if (_rows == 0) { if (_columns > 0) { // take FirstColumn into account, because it should really affect the result _rows = (nonCollapsedCount + FirstColumn + (_columns - 1)) / _columns; } else { // both rows and columns are unset -- lay out in a square _rows = (int)Math.Sqrt(nonCollapsedCount); if ((_rows * _rows) < nonCollapsedCount) { _rows++; } _columns = _rows; } } else if (_columns == 0) { // guaranteed that _rows is not 0, because we're in the else clause of the check for _rows == 0 _columns = (nonCollapsedCount + (_rows - 1)) / _rows; } } } #endregion Private Properties private int _rows; private int _columns; } }
#if !FEATURE_PAL && !FEATURE_CORECLR // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // <OWNER>AlfreMen</OWNER> // #if MONO #undef FEATURE_COMINTEROP #endif using System; using System.Security; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; using WFD = Windows.Foundation.Diagnostics; namespace System.Threading.Tasks { [FriendAccessAllowed] internal enum CausalityTraceLevel { Required = WFD.CausalityTraceLevel.Required, Important = WFD.CausalityTraceLevel.Important, Verbose = WFD.CausalityTraceLevel.Verbose } [FriendAccessAllowed] internal enum AsyncCausalityStatus { Canceled = WFD.AsyncCausalityStatus.Canceled, Completed = WFD.AsyncCausalityStatus.Completed, Error = WFD.AsyncCausalityStatus.Error, Started = WFD.AsyncCausalityStatus.Started } internal enum CausalityRelation { AssignDelegate = WFD.CausalityRelation.AssignDelegate, Join = WFD.CausalityRelation.Join, Choice = WFD.CausalityRelation.Choice, Cancel = WFD.CausalityRelation.Cancel, Error = WFD.CausalityRelation.Error } internal enum CausalitySynchronousWork { CompletionNotification = WFD.CausalitySynchronousWork.CompletionNotification, ProgressNotification = WFD.CausalitySynchronousWork.ProgressNotification, Execution = WFD.CausalitySynchronousWork.Execution } [FriendAccessAllowed] internal static class AsyncCausalityTracer { static internal void EnableToETW(bool enabled) { #if !MONO if (enabled) f_LoggingOn |= Loggers.ETW; else f_LoggingOn &= ~Loggers.ETW; #endif } [FriendAccessAllowed] internal static bool LoggingOn { [FriendAccessAllowed] get { #if FEATURE_COMINTEROP return f_LoggingOn != 0; #else return false; #endif } } #if FEATURE_COMINTEROP //s_PlatformId = {4B0171A6-F3D0-41A0-9B33-02550652B995} private static readonly Guid s_PlatformId = new Guid(0x4B0171A6, 0xF3D0, 0x41A0, 0x9B, 0x33, 0x02, 0x55, 0x06, 0x52, 0xB9, 0x95); //Indicates this information comes from the BCL Library private const WFD.CausalitySource s_CausalitySource = WFD.CausalitySource.Library; //Lazy initialize the actual factory private static WFD.IAsyncCausalityTracerStatics s_TracerFactory; //We receive the actual value for these as a callback private static bool f_LoggingOn; //assumes false by default [FriendAccessAllowed] internal static bool LoggingOn { [FriendAccessAllowed] get { if (!f_FactoryInitialized) FactoryInitialized(); return f_LoggingOn; } } private static bool f_FactoryInitialized; //assumes false by default private static object _InitializationLock = new object(); //explicit cache private static readonly Func<WFD.IAsyncCausalityTracerStatics> s_loadFactoryDelegate = LoadFactory; [SecuritySafeCritical] private static WFD.IAsyncCausalityTracerStatics LoadFactory() { if (!Environment.IsWinRTSupported) return null; //COM Class Id string ClassId = "Windows.Foundation.Diagnostics.AsyncCausalityTracer"; //COM Interface GUID {50850B26-267E-451B-A890-AB6A370245EE} Guid guid = new Guid(0x50850B26, 0x267E, 0x451B, 0xA8, 0x90, 0XAB, 0x6A, 0x37, 0x02, 0x45, 0xEE); Object factory = null; WFD.IAsyncCausalityTracerStatics validFactory = null; try { int hresult = Microsoft.Win32.UnsafeNativeMethods.RoGetActivationFactory(ClassId, ref guid, out factory); if (hresult < 0 || factory == null) return null; //This prevents having an exception thrown in case IAsyncCausalityTracerStatics isn't registered. validFactory = (WFD.IAsyncCausalityTracerStatics)factory; EventRegistrationToken token = validFactory.add_TracingStatusChanged(new EventHandler<WFD.TracingStatusChangedEventArgs>(TracingStatusChangedHandler)); Contract.Assert(token != null, "EventRegistrationToken is null"); } catch (Exception) { // Although catching generic Exception is not recommended, this file is one exception // since we don't want to propagate any kind of exception to the user since all we are // doing here depends on internal state. return null; } return validFactory; } private static bool FactoryInitialized() { return (LazyInitializer.EnsureInitialized(ref s_TracerFactory, ref f_FactoryInitialized, ref _InitializationLock, s_loadFactoryDelegate) != null); } [SecuritySafeCritical] private static void TracingStatusChangedHandler(Object sender, WFD.TracingStatusChangedEventArgs args) { f_LoggingOn = args.Enabled; } [FriendAccessAllowed] internal static void TraceOperationCreation(CausalityTraceLevel traceLevel, int taskId, string operationName, ulong relatedContext) { if (LoggingOn) { s_TracerFactory.TraceOperationCreation((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), operationName, relatedContext); } } [FriendAccessAllowed] internal static void TraceOperationCompletion(CausalityTraceLevel traceLevel, int taskId, AsyncCausalityStatus status) { if (LoggingOn) { s_TracerFactory.TraceOperationCompletion((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.AsyncCausalityStatus)status); } } internal static void TraceOperationRelation(CausalityTraceLevel traceLevel, int taskId, CausalityRelation relation) { if (LoggingOn) { s_TracerFactory.TraceOperationRelation((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalityRelation)relation); } } internal static void TraceSynchronousWorkStart(CausalityTraceLevel traceLevel, int taskId, CausalitySynchronousWork work) { if (LoggingOn) { s_TracerFactory.TraceSynchronousWorkStart((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalitySynchronousWork)work); } } internal static void TraceSynchronousWorkCompletion(CausalityTraceLevel traceLevel, CausalitySynchronousWork work) { if (LoggingOn) { s_TracerFactory.TraceSynchronousWorkCompletion((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, (WFD.CausalitySynchronousWork)work); } } private static ulong GetOperationId(uint taskId) { return (((ulong)AppDomain.CurrentDomain.Id) << 32) + taskId; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; using System.Net; using System.Security.Principal; using System.Security; namespace System.DirectoryServices.AccountManagement { internal class Utils { // To stop the compiler from autogenerating a constructor for this class private Utils() { } // // byte utilities // /// <summary> /// Performs bytewise comparison of two byte[] arrays /// </summary> /// <param name="src">Array to compare</param> /// <param name="tgt">Array to compare against src</param> /// <returns>true if identical, false otherwise</returns> internal static bool AreBytesEqual(byte[] src, byte[] tgt) { if (src.Length != tgt.Length) return false; for (int i = 0; i < src.Length; i++) { if (src[i] != tgt[i]) return false; } return true; } internal static void ClearBit(ref int value, uint bitmask) { value = (int)(((uint)value) & ((uint)(~bitmask))); } internal static void SetBit(ref int value, uint bitmask) { value = (int)(((uint)value) | ((uint)bitmask)); } // {0xa2, 0x3f,...} --> "a23f..." internal static string ByteArrayToString(byte[] byteArray) { StringBuilder stringizedArray = new StringBuilder(); foreach (byte b in byteArray) { stringizedArray.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } return stringizedArray.ToString(); } // Use this for ldap search filter string... internal static string SecurityIdentifierToLdapHexFilterString(SecurityIdentifier sid) { return (ADUtils.HexStringToLdapHexString(SecurityIdentifierToLdapHexBindingString(sid))); } // use this for binding string... internal static string SecurityIdentifierToLdapHexBindingString(SecurityIdentifier sid) { byte[] sidB = new byte[sid.BinaryLength]; sid.GetBinaryForm(sidB, 0); StringBuilder stringizedBinarySid = new StringBuilder(); foreach (byte b in sidB) { stringizedBinarySid.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } return stringizedBinarySid.ToString(); } internal static byte[] StringToByteArray(string s) { if (s.Length % 2 != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Utils", "StringToByteArray: string has bad length " + s.Length); return null; } byte[] bytes = new byte[s.Length / 2]; for (int i = 0; i < (s.Length) / 2; i++) { char firstChar = s[i * 2]; char secondChar = s[(i * 2) + 1]; if (((firstChar >= '0' && firstChar <= '9') || (firstChar >= 'A' && firstChar <= 'F') || (firstChar >= 'a' && firstChar <= 'f')) && ((secondChar >= '0' && secondChar <= '9') || (secondChar >= 'A' && secondChar <= 'F') || (secondChar >= 'a' && secondChar <= 'f'))) { byte b = byte.Parse(s.Substring(i * 2, 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); bytes[i] = b; } else { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Utils", "StringToByteArray: invalid string: " + s); return null; } } return bytes; } // // SID Utilities // internal static string ConvertSidToSDDL(byte[] sid) { string sddlSid = null; // To put the byte[] SID into SDDL, we use ConvertSidToStringSid. // Calling that requires we first copy the SID into native memory. IntPtr pSid = IntPtr.Zero; try { pSid = ConvertByteArrayToIntPtr(sid); if (UnsafeNativeMethods.ConvertSidToStringSid(pSid, ref sddlSid)) { return sddlSid; } else { int lastErrorCode = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf( GlobalDebug.Warn, "Utils", "ConvertSidToSDDL: ConvertSidToStringSid failed, " + lastErrorCode); return null; } } finally { if (pSid != IntPtr.Zero) Marshal.FreeHGlobal(pSid); } } // The caller must call Marshal.FreeHGlobal on the returned // value to free it. internal static IntPtr ConvertByteArrayToIntPtr(byte[] bytes) { IntPtr pBytes = IntPtr.Zero; pBytes = Marshal.AllocHGlobal(bytes.Length); try { Marshal.Copy(bytes, 0, pBytes, bytes.Length); } catch (Exception e) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "ConvertByteArrayToIntPtr: caught exception of type " + e.GetType().ToString() + " and message " + e.Message); Marshal.FreeHGlobal(pBytes); throw; } Debug.Assert(pBytes != IntPtr.Zero); return pBytes; } internal static byte[] ConvertNativeSidToByteArray(IntPtr pSid) { int sidLength = UnsafeNativeMethods.GetLengthSid(pSid); byte[] sid = new byte[sidLength]; Marshal.Copy(pSid, sid, 0, sidLength); return sid; } internal static SidType ClassifySID(byte[] sid) { IntPtr pSid = IntPtr.Zero; try { pSid = ConvertByteArrayToIntPtr(sid); return ClassifySID(pSid); } finally { if (pSid != IntPtr.Zero) Marshal.FreeHGlobal(pSid); } } internal static SidType ClassifySID(IntPtr pSid) { Debug.Assert(UnsafeNativeMethods.IsValidSid(pSid)); // Get the issuing authority and the first RID IntPtr pIdentAuth = UnsafeNativeMethods.GetSidIdentifierAuthority(pSid); UnsafeNativeMethods.SID_IDENTIFIER_AUTHORITY identAuth = (UnsafeNativeMethods.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(UnsafeNativeMethods.SID_IDENTIFIER_AUTHORITY)); IntPtr pRid = UnsafeNativeMethods.GetSidSubAuthority(pSid, 0); int rid = Marshal.ReadInt32(pRid); // These bit signify that the sid was issued by ADAM. If so then it can't be a fake sid. if ((identAuth.b3 & 0xF0) == 0x10) return SidType.RealObject; // Is it S-1-5-...? if (!(identAuth.b1 == 0) && (identAuth.b2 == 0) && (identAuth.b3 == 0) && (identAuth.b4 == 0) && (identAuth.b5 == 0) && (identAuth.b6 == 5)) { // No, so it can't be an account or builtin SID. // Probably something like \Everyone or \LOCAL. return SidType.FakeObject; } return rid switch { 21 => SidType.RealObject, // Account SID 32 => SidType.RealObjectFakeDomain, // BUILTIN SID _ => SidType.FakeObject, }; } internal static int GetLastRidFromSid(IntPtr pSid) { IntPtr pRidCount = UnsafeNativeMethods.GetSidSubAuthorityCount(pSid); int ridCount = Marshal.ReadByte(pRidCount); IntPtr pLastRid = UnsafeNativeMethods.GetSidSubAuthority(pSid, ridCount - 1); int lastRid = Marshal.ReadInt32(pLastRid); return lastRid; } internal static int GetLastRidFromSid(byte[] sid) { IntPtr pSid = IntPtr.Zero; try { pSid = Utils.ConvertByteArrayToIntPtr(sid); int rid = GetLastRidFromSid(pSid); return rid; } finally { if (pSid != IntPtr.Zero) Marshal.FreeHGlobal(pSid); } } // // // internal static bool IsSamUser() { // // Basic algorithm // // Get SID of current user (via OpenThreadToken/GetTokenInformation/CloseHandle for TokenUser) // // Is the user SID of the form S-1-5-21-... (does GetSidIdentityAuthority(u) == 5 and GetSidSubauthority(u, 0) == 21)? // If NO ---> is local user // If YES ---> // Get machine domain SID (via LsaOpenPolicy/LsaQueryInformationPolicy for PolicyAccountDomainInformation/LsaClose) // Does EqualDomainSid indicate the current user SID and the machine domain SID have the same domain? // If YES --> // IS the local machine a DC // If NO --> is local user // If YES --> is _not_ local user // If NO --> is _not_ local user // IntPtr pCopyOfUserSid = IntPtr.Zero; IntPtr pMachineDomainSid = IntPtr.Zero; try { // Get the user's SID pCopyOfUserSid = GetCurrentUserSid(); // Is it of S-1-5-21 form: Is the issuing authority NT_AUTHORITY and the RID NT_NOT_UNIQUE? SidType sidType = ClassifySID(pCopyOfUserSid); if (sidType == SidType.RealObject) { // It's a domain SID. Now, is the domain portion for the local machine, or something else? // Get the machine domain SID pMachineDomainSid = GetMachineDomainSid(); // Does the user SID have the same domain as the machine SID? bool sameDomain = false; bool success = UnsafeNativeMethods.EqualDomainSid(pCopyOfUserSid, pMachineDomainSid, ref sameDomain); // Since both pCopyOfUserSid and pMachineDomainSid should always be account SIDs Debug.Assert(success == true); // If user SID is the same domain as the machine domain, and the machine is not a DC then the user is a local (machine) user return sameDomain ? !IsMachineDC(null) : false; } else { // It's not a domain SID, must be local (e.g., NT AUTHORITY\foo, or BUILTIN\foo) return true; } } finally { if (pCopyOfUserSid != IntPtr.Zero) Marshal.FreeHGlobal(pCopyOfUserSid); if (pMachineDomainSid != IntPtr.Zero) Marshal.FreeHGlobal(pMachineDomainSid); } } internal static IntPtr GetCurrentUserSid() { IntPtr pTokenHandle = IntPtr.Zero; IntPtr pBuffer = IntPtr.Zero; try { // // Get the current user's SID // int error = 0; // Get the current thread's token if (!UnsafeNativeMethods.OpenThreadToken( UnsafeNativeMethods.GetCurrentThread(), 0x8, // TOKEN_QUERY true, ref pTokenHandle )) { if ((error = Marshal.GetLastWin32Error()) == 1008) // ERROR_NO_TOKEN { Debug.Assert(pTokenHandle == IntPtr.Zero); // Current thread doesn't have a token, try the process if (!UnsafeNativeMethods.OpenProcessToken( UnsafeNativeMethods.GetCurrentProcess(), 0x8, // TOKEN_QUERY ref pTokenHandle )) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: OpenProcessToken failed, gle=" + lastError); throw new PrincipalOperationException(SR.Format(SR.UnableToOpenToken, lastError)); } } else { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: OpenThreadToken failed, gle=" + error); throw new PrincipalOperationException(SR.Format(SR.UnableToOpenToken, error)); } } Debug.Assert(pTokenHandle != IntPtr.Zero); int neededBufferSize = 0; // Retrieve the user info from the current thread's token // First, determine how big a buffer we need. bool success = UnsafeNativeMethods.GetTokenInformation( pTokenHandle, 1, // TokenUser IntPtr.Zero, 0, ref neededBufferSize); int getTokenInfoError = 0; if ((getTokenInfoError = Marshal.GetLastWin32Error()) != 122) // ERROR_INSUFFICIENT_BUFFER { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: GetTokenInformation (1st try) failed, gle=" + getTokenInfoError); throw new PrincipalOperationException( SR.Format(SR.UnableToRetrieveTokenInfo, getTokenInfoError)); } // Allocate the necessary buffer. Debug.Assert(neededBufferSize > 0); pBuffer = Marshal.AllocHGlobal(neededBufferSize); // Load the user info into the buffer success = UnsafeNativeMethods.GetTokenInformation( pTokenHandle, 1, // TokenUser pBuffer, neededBufferSize, ref neededBufferSize); if (!success) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: GetTokenInformation (2nd try) failed, neededBufferSize=" + neededBufferSize + ", gle=" + lastError); throw new PrincipalOperationException( SR.Format(SR.UnableToRetrieveTokenInfo, lastError)); } // Retrieve the user's SID from the user info UnsafeNativeMethods.TOKEN_USER tokenUser = (UnsafeNativeMethods.TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.TOKEN_USER)); IntPtr pUserSid = tokenUser.sidAndAttributes.pSid; // this is a reference into the NATIVE memory (into pBuffer) Debug.Assert(UnsafeNativeMethods.IsValidSid(pUserSid)); // Now we make a copy of the SID to return int userSidLength = UnsafeNativeMethods.GetLengthSid(pUserSid); IntPtr pCopyOfUserSid = Marshal.AllocHGlobal(userSidLength); success = UnsafeNativeMethods.CopySid(userSidLength, pCopyOfUserSid, pUserSid); if (!success) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: CopySid failed, errorcode=" + lastError); throw new PrincipalOperationException( SR.Format(SR.UnableToRetrieveTokenInfo, lastError)); } return pCopyOfUserSid; } finally { if (pTokenHandle != IntPtr.Zero) UnsafeNativeMethods.CloseHandle(pTokenHandle); if (pBuffer != IntPtr.Zero) Marshal.FreeHGlobal(pBuffer); } } internal static IntPtr GetMachineDomainSid() { IntPtr pPolicyHandle = IntPtr.Zero; IntPtr pBuffer = IntPtr.Zero; IntPtr pOA = IntPtr.Zero; try { UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES oa = new UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES(); pOA = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES))); Marshal.StructureToPtr(oa, pOA, false); int err = UnsafeNativeMethods.LsaOpenPolicy( IntPtr.Zero, pOA, 1, // POLICY_VIEW_LOCAL_INFORMATION ref pPolicyHandle); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: LsaOpenPolicy failed, gle=" + SafeNativeMethods.LsaNtStatusToWinError(err)); throw new PrincipalOperationException(SR.Format( SR.UnableToRetrievePolicy, SafeNativeMethods.LsaNtStatusToWinError(err))); } Debug.Assert(pPolicyHandle != IntPtr.Zero); err = UnsafeNativeMethods.LsaQueryInformationPolicy( pPolicyHandle, 5, // PolicyAccountDomainInformation ref pBuffer); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: LsaQueryInformationPolicy failed, gle=" + SafeNativeMethods.LsaNtStatusToWinError(err)); throw new PrincipalOperationException(SR.Format( SR.UnableToRetrievePolicy, SafeNativeMethods.LsaNtStatusToWinError(err))); } Debug.Assert(pBuffer != IntPtr.Zero); UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO info = (UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO) Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO)); Debug.Assert(UnsafeNativeMethods.IsValidSid(info.domainSid)); // Now we make a copy of the SID to return int sidLength = UnsafeNativeMethods.GetLengthSid(info.domainSid); IntPtr pCopyOfSid = Marshal.AllocHGlobal(sidLength); bool success = UnsafeNativeMethods.CopySid(sidLength, pCopyOfSid, info.domainSid); if (!success) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: CopySid failed, errorcode=" + lastError); throw new PrincipalOperationException( SR.Format(SR.UnableToRetrievePolicy, lastError)); } return pCopyOfSid; } finally { if (pPolicyHandle != IntPtr.Zero) UnsafeNativeMethods.LsaClose(pPolicyHandle); if (pBuffer != IntPtr.Zero) UnsafeNativeMethods.LsaFreeMemory(pBuffer); if (pOA != IntPtr.Zero) Marshal.FreeHGlobal(pOA); } } // Returns name in the form "domain\user" internal static string GetNT4UserName() { using (WindowsIdentity currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()) { string s = currentIdentity.Name; GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "GetNT4UserName: name is " + s); return s; } } internal static string GetComputerFlatName() { //string s = System.Windows.Forms.SystemInformation.ComputerName; string s = Environment.MachineName; GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "GetComputerFlatName: name is " + s); return s; } // // Interop support // internal static UnsafeNativeMethods.DomainControllerInfo GetDcName(string computerName, string domainName, string siteName, int flags) { IntPtr domainControllerInfoPtr = IntPtr.Zero; try { int err = UnsafeNativeMethods.DsGetDcName(computerName, domainName, IntPtr.Zero, siteName, flags, out domainControllerInfoPtr); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetDcName: DsGetDcName failed, err=" + err); throw new PrincipalOperationException( SR.Format( SR.UnableToRetrieveDomainInfo, err), err); } UnsafeNativeMethods.DomainControllerInfo domainControllerInfo = (UnsafeNativeMethods.DomainControllerInfo)Marshal.PtrToStructure(domainControllerInfoPtr, typeof(UnsafeNativeMethods.DomainControllerInfo)); return domainControllerInfo; } finally { if (domainControllerInfoPtr != IntPtr.Zero) UnsafeNativeMethods.NetApiBufferFree(domainControllerInfoPtr); } } internal static unsafe int LookupSid(string serverName, NetCred credentials, byte[] sid, out string name, out string domainName, out int accountUsage) { int nameLength = 0; int domainNameLength = 0; accountUsage = 0; name = null; domainName = null; IntPtr hUser = IntPtr.Zero; try { Utils.BeginImpersonation(credentials, out hUser); // hUser could be null if no credentials were specified Debug.Assert(hUser != IntPtr.Zero || (credentials == null || (credentials.UserName == null && credentials.Password == null))); int f = Interop.Advapi32.LookupAccountSid(serverName, sid, null, ref nameLength, null, ref domainNameLength, out accountUsage); int lastErr = Marshal.GetLastWin32Error(); if (lastErr != 122) // ERROR_INSUFFICIENT_BUFFER { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "LookupSid: LookupAccountSid (1st try) failed, gle=" + lastErr); return lastErr; } Debug.Assert(f == 0); // should never succeed, with a 0 buffer size Debug.Assert(nameLength > 0); Debug.Assert(domainNameLength > 0); fixed (char* sbName = new char[nameLength]) fixed (char* sbDomainName = new char[domainNameLength]) { f = Interop.Advapi32.LookupAccountSid(serverName, sid, sbName, ref nameLength, sbDomainName, ref domainNameLength, out accountUsage); if (f == 0) { lastErr = Marshal.GetLastWin32Error(); Debug.Assert(lastErr != 0); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "LookupSid: LookupAccountSid (2nd try) failed, gle=" + lastErr); return lastErr; } name = new string(sbName); domainName = new string(sbDomainName); } return 0; } finally { if (hUser != IntPtr.Zero) Utils.EndImpersonation(hUser); } } internal static Principal ConstructFakePrincipalFromSID( byte[] sid, PrincipalContext ctx, string serverName, NetCred credentials, string authorityName) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "Utils", "ConstructFakePrincipalFromSID: Build principal for SID={0}, server={1}, authority={2}", Utils.ByteArrayToString(sid), (serverName != null ? serverName : "NULL"), (authorityName != null ? authorityName : "NULL")); Debug.Assert(ClassifySID(sid) == SidType.FakeObject); // Get the name for it string nt4Name = ""; int accountUsage = 0; string name; string domainName; int err = Utils.LookupSid(serverName, credentials, sid, out name, out domainName, out accountUsage); if (err == 0) { // If it failed, we'll just live without a name //Debug.Assert(accountUsage == 5 /*WellKnownGroup*/); nt4Name = (!string.IsNullOrEmpty(domainName) ? domainName + "\\" : "") + name; } else { GlobalDebug.WriteLineIf( GlobalDebug.Warn, "Utils", "ConstructFakePrincipalFromSID: LookupSid failed (ignoring), serverName=" + serverName + ", err=" + err); } // Since LookupAccountSid indicates all of the NT AUTHORITY, etc., SIDs are WellKnownGroups, // we'll map them all to Group. // Create a Principal object to represent it GroupPrincipal g = GroupPrincipal.MakeGroup(ctx); g.fakePrincipal = true; g.unpersisted = false; // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalDisplayName, nt4Name); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalName, name); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalSamAccountName, name); // SID IdentityClaim SecurityIdentifier sidObj = new SecurityIdentifier(Utils.ConvertSidToSDDL(sid)); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalSid, sidObj); g.LoadValueIntoProperty(PropertyNames.GroupIsSecurityGroup, true); return g; } // // Impersonation // internal static bool BeginImpersonation(NetCred credential, out IntPtr hUserToken) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "Entering BeginImpersonation"); hUserToken = IntPtr.Zero; IntPtr hToken = IntPtr.Zero; // default credential is specified, no need to do impersonation if (credential == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "BeginImpersonation: nothing to impersonate"); return false; } // Retrive the parsed username which has had the domain removed because LogonUser // expects creds this way. string userName = credential.ParsedUserName; string password = credential.Password; string domainName = credential.Domain; // no need to do impersonation as username and password are both null if (userName == null && password == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "BeginImpersonation: nothing to impersonate (2)"); return false; } GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "BeginImpersonation: trying to impersonate " + userName); int result = UnsafeNativeMethods.LogonUser( userName, domainName, password, 9, /* LOGON32_LOGON_NEW_CREDENTIALS */ 3, /* LOGON32_PROVIDER_WINNT50 */ ref hToken); // check the result if (result == 0) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "BeginImpersonation: LogonUser failed, gle=" + lastError); throw new PrincipalOperationException( SR.Format(SR.UnableToImpersonateCredentials, lastError)); } result = UnsafeNativeMethods.ImpersonateLoggedOnUser(hToken); if (result == 0) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "BeginImpersonation: ImpersonateLoggedOnUser failed, gle=" + lastError); // Close the token the was created above.... UnsafeNativeMethods.CloseHandle(hToken); throw new PrincipalOperationException( SR.Format(SR.UnableToImpersonateCredentials, lastError)); } hUserToken = hToken; return true; } internal static void EndImpersonation(IntPtr hUserToken) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "Entering EndImpersonation"); UnsafeNativeMethods.RevertToSelf(); UnsafeNativeMethods.CloseHandle(hUserToken); } internal static bool IsMachineDC(string computerName) { IntPtr dsRoleInfoPtr = IntPtr.Zero; int err = -1; try { if (null == computerName) err = UnsafeNativeMethods.DsRoleGetPrimaryDomainInformation(null, UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic, out dsRoleInfoPtr); else err = UnsafeNativeMethods.DsRoleGetPrimaryDomainInformation(computerName, UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic, out dsRoleInfoPtr); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "IsMachineDC: DsRoleGetPrimaryDomainInformation failed, err=" + err); throw new PrincipalOperationException( SR.Format( SR.UnableToRetrieveDomainInfo, err)); } UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC dsRolePrimaryDomainInfo = (UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC)Marshal.PtrToStructure(dsRoleInfoPtr, typeof(UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC)); return (dsRolePrimaryDomainInfo.MachineRole == UnsafeNativeMethods.DSROLE_MACHINE_ROLE.DsRole_RoleBackupDomainController || dsRolePrimaryDomainInfo.MachineRole == UnsafeNativeMethods.DSROLE_MACHINE_ROLE.DsRole_RolePrimaryDomainController); } finally { if (dsRoleInfoPtr != IntPtr.Zero) UnsafeNativeMethods.DsRoleFreeMemory(dsRoleInfoPtr); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/metric_service.proto // Original file comments: // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Google.Monitoring.V3 { /// <summary> /// Manages metric descriptors, monitored resource descriptors, and /// time series data. /// </summary> public static class MetricService { static readonly string __ServiceName = "google.monitoring.v3.MetricService"; static readonly Marshaller<global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsRequest> __Marshaller_ListMonitoredResourceDescriptorsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> __Marshaller_ListMonitoredResourceDescriptorsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Monitoring.V3.GetMonitoredResourceDescriptorRequest> __Marshaller_GetMonitoredResourceDescriptorRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Monitoring.V3.GetMonitoredResourceDescriptorRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Api.MonitoredResourceDescriptor> __Marshaller_MonitoredResourceDescriptor = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Api.MonitoredResourceDescriptor.Parser.ParseFrom); static readonly Marshaller<global::Google.Monitoring.V3.ListMetricDescriptorsRequest> __Marshaller_ListMetricDescriptorsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Monitoring.V3.ListMetricDescriptorsRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Monitoring.V3.ListMetricDescriptorsResponse> __Marshaller_ListMetricDescriptorsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Monitoring.V3.ListMetricDescriptorsResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Monitoring.V3.GetMetricDescriptorRequest> __Marshaller_GetMetricDescriptorRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Monitoring.V3.GetMetricDescriptorRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Api.MetricDescriptor> __Marshaller_MetricDescriptor = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Api.MetricDescriptor.Parser.ParseFrom); static readonly Marshaller<global::Google.Monitoring.V3.CreateMetricDescriptorRequest> __Marshaller_CreateMetricDescriptorRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Monitoring.V3.CreateMetricDescriptorRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Monitoring.V3.DeleteMetricDescriptorRequest> __Marshaller_DeleteMetricDescriptorRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Monitoring.V3.DeleteMetricDescriptorRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly Marshaller<global::Google.Monitoring.V3.ListTimeSeriesRequest> __Marshaller_ListTimeSeriesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Monitoring.V3.ListTimeSeriesRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Monitoring.V3.ListTimeSeriesResponse> __Marshaller_ListTimeSeriesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Monitoring.V3.ListTimeSeriesResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Monitoring.V3.CreateTimeSeriesRequest> __Marshaller_CreateTimeSeriesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Monitoring.V3.CreateTimeSeriesRequest.Parser.ParseFrom); static readonly Method<global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsRequest, global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> __Method_ListMonitoredResourceDescriptors = new Method<global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsRequest, global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsResponse>( MethodType.Unary, __ServiceName, "ListMonitoredResourceDescriptors", __Marshaller_ListMonitoredResourceDescriptorsRequest, __Marshaller_ListMonitoredResourceDescriptorsResponse); static readonly Method<global::Google.Monitoring.V3.GetMonitoredResourceDescriptorRequest, global::Google.Api.MonitoredResourceDescriptor> __Method_GetMonitoredResourceDescriptor = new Method<global::Google.Monitoring.V3.GetMonitoredResourceDescriptorRequest, global::Google.Api.MonitoredResourceDescriptor>( MethodType.Unary, __ServiceName, "GetMonitoredResourceDescriptor", __Marshaller_GetMonitoredResourceDescriptorRequest, __Marshaller_MonitoredResourceDescriptor); static readonly Method<global::Google.Monitoring.V3.ListMetricDescriptorsRequest, global::Google.Monitoring.V3.ListMetricDescriptorsResponse> __Method_ListMetricDescriptors = new Method<global::Google.Monitoring.V3.ListMetricDescriptorsRequest, global::Google.Monitoring.V3.ListMetricDescriptorsResponse>( MethodType.Unary, __ServiceName, "ListMetricDescriptors", __Marshaller_ListMetricDescriptorsRequest, __Marshaller_ListMetricDescriptorsResponse); static readonly Method<global::Google.Monitoring.V3.GetMetricDescriptorRequest, global::Google.Api.MetricDescriptor> __Method_GetMetricDescriptor = new Method<global::Google.Monitoring.V3.GetMetricDescriptorRequest, global::Google.Api.MetricDescriptor>( MethodType.Unary, __ServiceName, "GetMetricDescriptor", __Marshaller_GetMetricDescriptorRequest, __Marshaller_MetricDescriptor); static readonly Method<global::Google.Monitoring.V3.CreateMetricDescriptorRequest, global::Google.Api.MetricDescriptor> __Method_CreateMetricDescriptor = new Method<global::Google.Monitoring.V3.CreateMetricDescriptorRequest, global::Google.Api.MetricDescriptor>( MethodType.Unary, __ServiceName, "CreateMetricDescriptor", __Marshaller_CreateMetricDescriptorRequest, __Marshaller_MetricDescriptor); static readonly Method<global::Google.Monitoring.V3.DeleteMetricDescriptorRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteMetricDescriptor = new Method<global::Google.Monitoring.V3.DeleteMetricDescriptorRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "DeleteMetricDescriptor", __Marshaller_DeleteMetricDescriptorRequest, __Marshaller_Empty); static readonly Method<global::Google.Monitoring.V3.ListTimeSeriesRequest, global::Google.Monitoring.V3.ListTimeSeriesResponse> __Method_ListTimeSeries = new Method<global::Google.Monitoring.V3.ListTimeSeriesRequest, global::Google.Monitoring.V3.ListTimeSeriesResponse>( MethodType.Unary, __ServiceName, "ListTimeSeries", __Marshaller_ListTimeSeriesRequest, __Marshaller_ListTimeSeriesResponse); static readonly Method<global::Google.Monitoring.V3.CreateTimeSeriesRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_CreateTimeSeries = new Method<global::Google.Monitoring.V3.CreateTimeSeriesRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "CreateTimeSeries", __Marshaller_CreateTimeSeriesRequest, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Monitoring.V3.MetricServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of MetricService</summary> public abstract class MetricServiceBase { /// <summary> /// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptors(global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets a single monitored resource descriptor. This method does not require a Stackdriver account. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Api.MonitoredResourceDescriptor> GetMonitoredResourceDescriptor(global::Google.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Lists metric descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Monitoring.V3.ListMetricDescriptorsResponse> ListMetricDescriptors(global::Google.Monitoring.V3.ListMetricDescriptorsRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets a single metric descriptor. This method does not require a Stackdriver account. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Api.MetricDescriptor> GetMetricDescriptor(global::Google.Monitoring.V3.GetMetricDescriptorRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Creates a new metric descriptor. /// User-created metric descriptors define /// [custom metrics](/monitoring/custom-metrics). /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Api.MetricDescriptor> CreateMetricDescriptor(global::Google.Monitoring.V3.CreateMetricDescriptorRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a metric descriptor. Only user-created /// [custom metrics](/monitoring/custom-metrics) can be deleted. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMetricDescriptor(global::Google.Monitoring.V3.DeleteMetricDescriptorRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Lists time series that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Monitoring.V3.ListTimeSeriesResponse> ListTimeSeries(global::Google.Monitoring.V3.ListTimeSeriesRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Creates or adds data to one or more time series. /// The response is empty if all time series in the request were written. /// If any time series could not be written, a corresponding failure message is /// included in the error response. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> CreateTimeSeries(global::Google.Monitoring.V3.CreateTimeSeriesRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for MetricService</summary> public class MetricServiceClient : ClientBase<MetricServiceClient> { /// <summary>Creates a new client for MetricService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public MetricServiceClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for MetricService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public MetricServiceClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected MetricServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected MetricServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsResponse ListMonitoredResourceDescriptors(global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListMonitoredResourceDescriptors(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsResponse ListMonitoredResourceDescriptors(global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListMonitoredResourceDescriptors, null, options, request); } /// <summary> /// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual AsyncUnaryCall<global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptorsAsync(global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListMonitoredResourceDescriptorsAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual AsyncUnaryCall<global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptorsAsync(global::Google.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListMonitoredResourceDescriptors, null, options, request); } /// <summary> /// Gets a single monitored resource descriptor. This method does not require a Stackdriver account. /// </summary> public virtual global::Google.Api.MonitoredResourceDescriptor GetMonitoredResourceDescriptor(global::Google.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetMonitoredResourceDescriptor(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single monitored resource descriptor. This method does not require a Stackdriver account. /// </summary> public virtual global::Google.Api.MonitoredResourceDescriptor GetMonitoredResourceDescriptor(global::Google.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetMonitoredResourceDescriptor, null, options, request); } /// <summary> /// Gets a single monitored resource descriptor. This method does not require a Stackdriver account. /// </summary> public virtual AsyncUnaryCall<global::Google.Api.MonitoredResourceDescriptor> GetMonitoredResourceDescriptorAsync(global::Google.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetMonitoredResourceDescriptorAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single monitored resource descriptor. This method does not require a Stackdriver account. /// </summary> public virtual AsyncUnaryCall<global::Google.Api.MonitoredResourceDescriptor> GetMonitoredResourceDescriptorAsync(global::Google.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetMonitoredResourceDescriptor, null, options, request); } /// <summary> /// Lists metric descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual global::Google.Monitoring.V3.ListMetricDescriptorsResponse ListMetricDescriptors(global::Google.Monitoring.V3.ListMetricDescriptorsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListMetricDescriptors(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists metric descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual global::Google.Monitoring.V3.ListMetricDescriptorsResponse ListMetricDescriptors(global::Google.Monitoring.V3.ListMetricDescriptorsRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListMetricDescriptors, null, options, request); } /// <summary> /// Lists metric descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual AsyncUnaryCall<global::Google.Monitoring.V3.ListMetricDescriptorsResponse> ListMetricDescriptorsAsync(global::Google.Monitoring.V3.ListMetricDescriptorsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListMetricDescriptorsAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists metric descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual AsyncUnaryCall<global::Google.Monitoring.V3.ListMetricDescriptorsResponse> ListMetricDescriptorsAsync(global::Google.Monitoring.V3.ListMetricDescriptorsRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListMetricDescriptors, null, options, request); } /// <summary> /// Gets a single metric descriptor. This method does not require a Stackdriver account. /// </summary> public virtual global::Google.Api.MetricDescriptor GetMetricDescriptor(global::Google.Monitoring.V3.GetMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetMetricDescriptor(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single metric descriptor. This method does not require a Stackdriver account. /// </summary> public virtual global::Google.Api.MetricDescriptor GetMetricDescriptor(global::Google.Monitoring.V3.GetMetricDescriptorRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetMetricDescriptor, null, options, request); } /// <summary> /// Gets a single metric descriptor. This method does not require a Stackdriver account. /// </summary> public virtual AsyncUnaryCall<global::Google.Api.MetricDescriptor> GetMetricDescriptorAsync(global::Google.Monitoring.V3.GetMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetMetricDescriptorAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single metric descriptor. This method does not require a Stackdriver account. /// </summary> public virtual AsyncUnaryCall<global::Google.Api.MetricDescriptor> GetMetricDescriptorAsync(global::Google.Monitoring.V3.GetMetricDescriptorRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetMetricDescriptor, null, options, request); } /// <summary> /// Creates a new metric descriptor. /// User-created metric descriptors define /// [custom metrics](/monitoring/custom-metrics). /// </summary> public virtual global::Google.Api.MetricDescriptor CreateMetricDescriptor(global::Google.Monitoring.V3.CreateMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateMetricDescriptor(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new metric descriptor. /// User-created metric descriptors define /// [custom metrics](/monitoring/custom-metrics). /// </summary> public virtual global::Google.Api.MetricDescriptor CreateMetricDescriptor(global::Google.Monitoring.V3.CreateMetricDescriptorRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateMetricDescriptor, null, options, request); } /// <summary> /// Creates a new metric descriptor. /// User-created metric descriptors define /// [custom metrics](/monitoring/custom-metrics). /// </summary> public virtual AsyncUnaryCall<global::Google.Api.MetricDescriptor> CreateMetricDescriptorAsync(global::Google.Monitoring.V3.CreateMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateMetricDescriptorAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new metric descriptor. /// User-created metric descriptors define /// [custom metrics](/monitoring/custom-metrics). /// </summary> public virtual AsyncUnaryCall<global::Google.Api.MetricDescriptor> CreateMetricDescriptorAsync(global::Google.Monitoring.V3.CreateMetricDescriptorRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateMetricDescriptor, null, options, request); } /// <summary> /// Deletes a metric descriptor. Only user-created /// [custom metrics](/monitoring/custom-metrics) can be deleted. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteMetricDescriptor(global::Google.Monitoring.V3.DeleteMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteMetricDescriptor(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a metric descriptor. Only user-created /// [custom metrics](/monitoring/custom-metrics) can be deleted. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteMetricDescriptor(global::Google.Monitoring.V3.DeleteMetricDescriptorRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteMetricDescriptor, null, options, request); } /// <summary> /// Deletes a metric descriptor. Only user-created /// [custom metrics](/monitoring/custom-metrics) can be deleted. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMetricDescriptorAsync(global::Google.Monitoring.V3.DeleteMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteMetricDescriptorAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a metric descriptor. Only user-created /// [custom metrics](/monitoring/custom-metrics) can be deleted. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMetricDescriptorAsync(global::Google.Monitoring.V3.DeleteMetricDescriptorRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteMetricDescriptor, null, options, request); } /// <summary> /// Lists time series that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual global::Google.Monitoring.V3.ListTimeSeriesResponse ListTimeSeries(global::Google.Monitoring.V3.ListTimeSeriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListTimeSeries(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists time series that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual global::Google.Monitoring.V3.ListTimeSeriesResponse ListTimeSeries(global::Google.Monitoring.V3.ListTimeSeriesRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListTimeSeries, null, options, request); } /// <summary> /// Lists time series that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual AsyncUnaryCall<global::Google.Monitoring.V3.ListTimeSeriesResponse> ListTimeSeriesAsync(global::Google.Monitoring.V3.ListTimeSeriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListTimeSeriesAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists time series that match a filter. This method does not require a Stackdriver account. /// </summary> public virtual AsyncUnaryCall<global::Google.Monitoring.V3.ListTimeSeriesResponse> ListTimeSeriesAsync(global::Google.Monitoring.V3.ListTimeSeriesRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListTimeSeries, null, options, request); } /// <summary> /// Creates or adds data to one or more time series. /// The response is empty if all time series in the request were written. /// If any time series could not be written, a corresponding failure message is /// included in the error response. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty CreateTimeSeries(global::Google.Monitoring.V3.CreateTimeSeriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateTimeSeries(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates or adds data to one or more time series. /// The response is empty if all time series in the request were written. /// If any time series could not be written, a corresponding failure message is /// included in the error response. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty CreateTimeSeries(global::Google.Monitoring.V3.CreateTimeSeriesRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateTimeSeries, null, options, request); } /// <summary> /// Creates or adds data to one or more time series. /// The response is empty if all time series in the request were written. /// If any time series could not be written, a corresponding failure message is /// included in the error response. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CreateTimeSeriesAsync(global::Google.Monitoring.V3.CreateTimeSeriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateTimeSeriesAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates or adds data to one or more time series. /// The response is empty if all time series in the request were written. /// If any time series could not be written, a corresponding failure message is /// included in the error response. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CreateTimeSeriesAsync(global::Google.Monitoring.V3.CreateTimeSeriesRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateTimeSeries, null, options, request); } protected override MetricServiceClient NewInstance(ClientBaseConfiguration configuration) { return new MetricServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(MetricServiceBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_ListMonitoredResourceDescriptors, serviceImpl.ListMonitoredResourceDescriptors) .AddMethod(__Method_GetMonitoredResourceDescriptor, serviceImpl.GetMonitoredResourceDescriptor) .AddMethod(__Method_ListMetricDescriptors, serviceImpl.ListMetricDescriptors) .AddMethod(__Method_GetMetricDescriptor, serviceImpl.GetMetricDescriptor) .AddMethod(__Method_CreateMetricDescriptor, serviceImpl.CreateMetricDescriptor) .AddMethod(__Method_DeleteMetricDescriptor, serviceImpl.DeleteMetricDescriptor) .AddMethod(__Method_ListTimeSeries, serviceImpl.ListTimeSeries) .AddMethod(__Method_CreateTimeSeries, serviceImpl.CreateTimeSeries).Build(); } } } #endregion
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using CommandLine; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.Util; using Google.Ads.GoogleAds.V10.Common; using Google.Ads.GoogleAds.V10.Enums; using Google.Ads.GoogleAds.V10.Errors; using Google.Ads.GoogleAds.V10.Resources; using Google.Ads.GoogleAds.V10.Services; using Google.Protobuf; using System; using System.Collections.Generic; using System.Linq; using static Google.Ads.GoogleAds.V10.Enums.DisplayUploadProductTypeEnum.Types; namespace Google.Ads.GoogleAds.Examples.V10 { /// <summary> /// This code example adds a display upload ad to a given ad group. To get ad groups, /// run GetAdGroups.cs. /// </summary> public class AddDisplayUploadAd : ExampleBase { /// <summary> /// Command line options for running the <see cref="AddDisplayUploadAd"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The Google Ads customer ID for which the call is made. /// </summary> [Option("customerId", Required = true, HelpText = "The Google Ads customer ID for which the call is made.")] public long CustomerId { get; set; } /// <summary> /// The ID of the ad group to which the new ad will be added. /// </summary> [Option("adGroupId", Required = true, HelpText = "The ID of the ad group to which the new ad will be added.")] public long AdGroupId { get; set; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { Options options = new Options(); CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult( delegate (Options o) { options = o; return 0; }, delegate (IEnumerable<Error> errors) { // The Google Ads customer ID for which the call is made. options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE"); // The ID of the ad group to which the new ad will be added. options.AdGroupId = long.Parse("INSERT_AD_GROUP_ID_HERE"); return 0; }); AddDisplayUploadAd codeExample = new AddDisplayUploadAd(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.AdGroupId); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This code example adds a display upload ad to a given ad group. To get ad groups, " + "run GetAdGroups.cs."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="adGroupId">The ID of the ad group to which the new ad will be /// added.</param> public void Run(GoogleAdsClient client, long customerId, long adGroupId) { try { // There are several types of display upload ads. For this example, we will create // an HTML5 upload ad, which requires a media bundle. // This feature is only available to allowlisted accounts. // See https://support.google.com/google-ads/answer/1722096 for more details. // The DisplayUploadProductType field lists the available display upload types: // https://developers.google.com/google-ads/api/reference/rpc/latest/DisplayUploadAdInfo // Creates a new media bundle asset and returns the resource name. string adAssetResourceName = CreateMediaBundleAsset(client, customerId); // Creates a new display upload ad and associates it with the specified ad group. CreateDisplayUploadAdGroupAd(client, customerId, adGroupId, adAssetResourceName); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } /// <summary> /// Creates a media bundle from the assets in a zip file. The zip file contains the /// HTML5 components. /// </summary> /// <param name="client">The Google Ads API client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <returns>The string resource name of the newly uploaded media bundle.</returns> private string CreateMediaBundleAsset(GoogleAdsClient client, long customerId) { // Gets the AssetService. AssetServiceClient assetServiceClient = client.GetService(Services.V10.AssetService); // The HTML5 zip file contains all the HTML, CSS, and images needed for the // HTML5 ad. For help on creating an HTML5 zip file, check out Google Web // Designer (https://www.google.com/webdesigner/). byte[] html5Zip = MediaUtilities.GetAssetDataFromUrl("https://gaagl.page.link/ib87", client.Config); // Creates the media bundle asset. Asset mediaBundleAsset = new Asset() { Type = AssetTypeEnum.Types.AssetType.MediaBundle, MediaBundleAsset = new MediaBundleAsset() { Data = ByteString.CopyFrom(html5Zip) }, Name = "Ad Media Bundle" }; // Creates the asset operation. AssetOperation operation = new AssetOperation() { Create = mediaBundleAsset }; // Adds the asset to the client account. MutateAssetsResponse response = assetServiceClient.MutateAssets(customerId.ToString(), new[] { operation }); // Displays the resulting resource name. string uploadedAssetResourceName = response.Results.First().ResourceName; Console.WriteLine($"Uploaded media bundle: {uploadedAssetResourceName}"); return uploadedAssetResourceName; } /// <summary> /// Creates a new HTML5 display upload ad and adds it to the specified ad group. /// </summary> /// <param name="client">The Google Ads API client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="adGroupId">The ID of the ad group to which the new ad will be /// added.</param> /// <param name="adAssetResourceName">The resource name of the media bundle containing /// the HTML5 components.</param> private void CreateDisplayUploadAdGroupAd(GoogleAdsClient client, long customerId, long adGroupId, string adAssetResourceName) { // Get the AdGroupAdService. AdGroupAdServiceClient adGroupAdServiceClient = client.GetService(Services.V10.AdGroupAdService); // Creates the ad with the required fields. Ad displayUploadAd = new Ad() { Name = "Ad for HTML5", FinalUrls = { "http://example.com/html5" }, // Exactly one ad data field must be included to specify the ad type. See // https://developers.google.com/google-ads/api/reference/rpc/latest/Ad for the // full list of available types. DisplayUploadAd = new DisplayUploadAdInfo() { DisplayUploadProductType = DisplayUploadProductType.Html5UploadAd, MediaBundle = new AdMediaBundleAsset() { Asset = adAssetResourceName } } }; // Creates an ad group ad for the new ad. AdGroupAd adGroupAd = new AdGroupAd() { Ad = displayUploadAd, Status = AdGroupAdStatusEnum.Types.AdGroupAdStatus.Paused, AdGroup = ResourceNames.AdGroup(customerId, adGroupId), }; // Creates the ad group ad operation. AdGroupAdOperation operation = new AdGroupAdOperation() { Create = adGroupAd }; // Adds the ad group ad to the client account. MutateAdGroupAdsResponse response = adGroupAdServiceClient.MutateAdGroupAds (customerId.ToString(), new[] { operation }); // Displays the resulting ad group ad's resource name. Console.WriteLine($"Created new ad group ad{response.Results.First().ResourceName}."); } } }
// 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.Xml; using System.Text; using System.Collections; using System.Globalization; using System.Diagnostics; using System.Reflection; namespace System.Xml.Schema { // This is an atomic value converted for Silverlight XML core that knows only how to convert to and from string. // It does not recognize XmlAtomicValue or XPathItemType. internal class XmlUntypedStringConverter { // Fields private bool _listsAllowed; private XmlUntypedStringConverter _listItemConverter; // Cached types private static readonly Type s_decimalType = typeof(decimal); private static readonly Type s_int32Type = typeof(int); private static readonly Type s_int64Type = typeof(long); private static readonly Type s_stringType = typeof(string); private static readonly Type s_objectType = typeof(object); private static readonly Type s_byteType = typeof(byte); private static readonly Type s_int16Type = typeof(short); private static readonly Type s_SByteType = typeof(sbyte); private static readonly Type s_UInt16Type = typeof(ushort); private static readonly Type s_UInt32Type = typeof(uint); private static readonly Type s_UInt64Type = typeof(ulong); private static readonly Type s_doubleType = typeof(double); private static readonly Type s_singleType = typeof(float); private static readonly Type s_dateTimeType = typeof(DateTime); private static readonly Type s_dateTimeOffsetType = typeof(DateTimeOffset); private static readonly Type s_booleanType = typeof(bool); private static readonly Type s_byteArrayType = typeof(Byte[]); private static readonly Type s_xmlQualifiedNameType = typeof(XmlQualifiedName); private static readonly Type s_uriType = typeof(Uri); private static readonly Type s_timeSpanType = typeof(TimeSpan); private static readonly string s_untypedStringTypeName = "xdt:untypedAtomic"; // Static convertor instance internal static XmlUntypedStringConverter Instance = new XmlUntypedStringConverter(true); private XmlUntypedStringConverter(bool listsAllowed) { _listsAllowed = listsAllowed; if (listsAllowed) { _listItemConverter = new XmlUntypedStringConverter(false); } } internal object FromString(string value, Type destinationType, IXmlNamespaceResolver nsResolver) { if (value == null) throw new ArgumentNullException(nameof(value)); if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == s_objectType) destinationType = typeof(string); if (destinationType == s_booleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == s_byteType) return Int32ToByte(XmlConvert.ToInt32((string)value)); if (destinationType == s_byteArrayType) return StringToBase64Binary((string)value); if (destinationType == s_dateTimeType) return StringToDateTime((string)value); if (destinationType == s_dateTimeOffsetType) return StringToDateTimeOffset((string)value); if (destinationType == s_decimalType) return XmlConvert.ToDecimal((string)value); if (destinationType == s_doubleType) return XmlConvert.ToDouble((string)value); if (destinationType == s_int16Type) return Int32ToInt16(XmlConvert.ToInt32((string)value)); if (destinationType == s_int32Type) return XmlConvert.ToInt32((string)value); if (destinationType == s_int64Type) return XmlConvert.ToInt64((string)value); if (destinationType == s_SByteType) return Int32ToSByte(XmlConvert.ToInt32((string)value)); if (destinationType == s_singleType) return XmlConvert.ToSingle((string)value); if (destinationType == s_timeSpanType) return StringToDuration((string)value); if (destinationType == s_UInt16Type) return Int32ToUInt16(XmlConvert.ToInt32((string)value)); if (destinationType == s_UInt32Type) return Int64ToUInt32(XmlConvert.ToInt64((string)value)); if (destinationType == s_UInt64Type) return DecimalToUInt64(XmlConvert.ToDecimal((string)value)); if (destinationType == s_uriType) return XmlConvert.ToUri((string)value); if (destinationType == s_xmlQualifiedNameType) return StringToQName((string)value, nsResolver); if (destinationType == s_stringType) return ((string)value); return StringToListType(value, destinationType, nsResolver); } private byte Int32ToByte(int value) { if (value < (int)Byte.MinValue || value > (int)Byte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Byte" })); return (byte)value; } private short Int32ToInt16(int value) { if (value < (int)Int16.MinValue || value > (int)Int16.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int16" })); return (short)value; } private sbyte Int32ToSByte(int value) { if (value < (int)SByte.MinValue || value > (int)SByte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "SByte" })); return (sbyte)value; } private ushort Int32ToUInt16(int value) { if (value < (int)UInt16.MinValue || value > (int)UInt16.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt16" })); return (ushort)value; } private uint Int64ToUInt32(long value) { if (value < (long)UInt32.MinValue || value > (long)UInt32.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt32" })); return (uint)value; } private ulong DecimalToUInt64(decimal value) { if (value < (decimal)UInt64.MinValue || value > (decimal)UInt64.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt64" })); return (ulong)value; } private byte[] StringToBase64Binary(string value) { return Convert.FromBase64String(XmlConvert.TrimString(value)); } private static DateTime StringToDateTime(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } private static DateTimeOffset StringToDateTimeOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } private TimeSpan StringToDuration(string value) { return new XsdDuration(value, XsdDuration.DurationType.Duration).ToTimeSpan(XsdDuration.DurationType.Duration); } private static XmlQualifiedName StringToQName(string value, IXmlNamespaceResolver nsResolver) { string prefix, localName, ns; value = value.Trim(); // Parse prefix:localName try { ValidateNames.ParseQNameThrow(value, out prefix, out localName); } catch (XmlException e) { throw new FormatException(e.Message); } // Throw error if no namespaces are in scope if (nsResolver == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Lookup namespace ns = nsResolver.LookupNamespace(prefix); if (ns == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Create XmlQualfiedName return new XmlQualifiedName(localName, ns); } private object StringToListType(string value, Type destinationType, IXmlNamespaceResolver nsResolver) { if (_listsAllowed && destinationType.IsArray) { Type itemTypeDst = destinationType.GetElementType(); // Different StringSplitOption needs to be used because of following bugs: // 566053: Behavior change between SL2 and Dev10 in the way string arrays are deserialized by the XmlReader.ReadContentsAs method // 643697: Deserialization of typed arrays by the XmlReader.ReadContentsAs method fails // // In Silverligt 2 the XmlConvert.SplitString was not using the StringSplitOptions, which is the same as using StringSplitOptions.None. // What it meant is that whenever there is a double space between two values in the input string it turned into // an string.Empty entry in the intermediate string array. In Dev10 empty entries were always removed (StringSplitOptions.RemoveEmptyEntries). // // Moving forward in coreclr we'll use Dev10 behavior which empty entries were always removed (StringSplitOptions.RemoveEmptyEntries). // we didn't quirk the change because we discover not many apps using ReadContentAs with string array type parameter // // The types Object, Byte[], String and Uri can be successfully deserialized from string.Empty, so we need to preserve the // Silverlight 2 behavior for back-compat (=use StringSplitOptions.None). All the other array types failed to deserialize // from string.Empty in Silverlight 2 (threw an exception), so we can fix all of these as they are not breaking changes // (=use StringSplitOptions.RemoveEmptyEntries). if (itemTypeDst == s_objectType) return ToArray<object>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_booleanType) return ToArray<bool>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_byteType) return ToArray<byte>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_byteArrayType) return ToArray<byte[]>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_dateTimeType) return ToArray<DateTime>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_dateTimeOffsetType) return ToArray<DateTimeOffset>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_decimalType) return ToArray<decimal>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_doubleType) return ToArray<double>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int16Type) return ToArray<short>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int32Type) return ToArray<int>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int64Type) return ToArray<long>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_SByteType) return ToArray<sbyte>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_singleType) return ToArray<float>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_stringType) return ToArray<string>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_timeSpanType) return ToArray<TimeSpan>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt16Type) return ToArray<ushort>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt32Type) return ToArray<uint>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt64Type) return ToArray<ulong>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_uriType) return ToArray<Uri>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_xmlQualifiedNameType) return ToArray<XmlQualifiedName>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); } throw CreateInvalidClrMappingException(typeof(string), destinationType); } private T[] ToArray<T>(string[] stringArray, IXmlNamespaceResolver nsResolver) { T[] arrDst = new T[stringArray.Length]; for (int i = 0; i < stringArray.Length; i++) { arrDst[i] = (T)_listItemConverter.FromString(stringArray[i], typeof(T), nsResolver); } return arrDst; } private Exception CreateInvalidClrMappingException(Type sourceType, Type destinationType) { return new InvalidCastException(SR.Format(SR.XmlConvert_TypeListBadMapping2, s_untypedStringTypeName, sourceType.Name, destinationType.Name)); } } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.IO; using Reflection = System.Reflection; using Reporting.Rdl; namespace Reporting.Rdl.Utility { public sealed class Assembly { /// <summary> /// Loads assembly from file; tries up to 3 time; load with name, load from BaseDirectory, /// and load from BaseDirectory concatenated with Relative directory. /// </summary> /// <param name="s"></param> /// <returns></returns> static internal Reflection.Assembly AssemblyLoadFrom(string s) { Reflection.Assembly ra = null; try { // try 1) loading just from name ra = Reflection.Assembly.LoadFrom(s); } catch { // try 2) loading from the various directories available string d0 = RdlEngineConfig.DirectoryLoadedFrom; string d1 = AppDomain.CurrentDomain.BaseDirectory; string d2 = AppDomain.CurrentDomain.RelativeSearchPath; if (d2 == null || d2 == string.Empty) ra = AssemblyLoadFromPvt(Path.GetFileName(s), d0, d1); else ra = AssemblyLoadFromPvt(Path.GetFileName(s), d0, d1, d2); } return ra; } static Reflection.Assembly AssemblyLoadFromPvt(string file, params string[] dir) { Reflection.Assembly ra = null; for (int i = 0; i < dir.Length; i++) { if (dir[i] == null) continue; //Josh: 6:23:10 Changed to System.IO.Path.Combine() string f = System.IO.Path.Combine(dir[i], file); try { ra = Reflection.Assembly.LoadFrom(f); if (ra != null) // don't really need this as call will throw exception when it fails break; } catch { if (i + 1 == dir.Length) { // on last try just plain load of the file ra = Reflection.Assembly.Load(file); } } } return ra; } static internal Reflection.MethodInfo GetMethod(Type t, string method, Type[] argTypes) { if (t == null || method == null) return null; Reflection.MethodInfo mInfo = t.GetMethod(method, Reflection.BindingFlags.IgnoreCase | Reflection.BindingFlags.Public | Reflection.BindingFlags.Static, null, // TODO: use Laxbinder class argTypes, null); if (mInfo == null) mInfo = t.GetMethod(method, argTypes); // be less specific and try again (Code VB functions don't always get caught?) if (mInfo == null) { // Try to find method in base classes --- fix thanks to jonh Type b = t.BaseType; while (b != null) { // mInfo = b.GetMethod(method, argTypes); mInfo = b.GetMethod(method, Reflection.BindingFlags.IgnoreCase | Reflection.BindingFlags.Public | Reflection.BindingFlags.Static | Reflection.BindingFlags.DeclaredOnly, null, argTypes, null); if (mInfo != null) break; b = b.BaseType; } } return mInfo; } static internal Type GetTypeFromTypeCode(TypeCode tc) { Type t = null; switch (tc) { case TypeCode.Boolean: t = Type.GetType("System.Boolean"); break; case TypeCode.Byte: t = Type.GetType("System.Byte"); break; case TypeCode.Char: t = Type.GetType("System.Char"); break; case TypeCode.DateTime: t = Type.GetType("System.DateTime"); break; case TypeCode.Decimal: t = Type.GetType("System.Decimal"); break; case TypeCode.Double: t = Type.GetType("System.Double"); break; case TypeCode.Int16: t = Type.GetType("System.Int16"); break; case TypeCode.Int32: t = Type.GetType("System.Int32"); break; case TypeCode.Int64: t = Type.GetType("System.Int64"); break; case TypeCode.Object: t = Type.GetType("System.Object"); break; case TypeCode.SByte: t = Type.GetType("System.SByte"); break; case TypeCode.Single: t = Type.GetType("System.Single"); break; case TypeCode.String: t = Type.GetType("System.String"); break; case TypeCode.UInt16: t = Type.GetType("System.UInt16"); break; case TypeCode.UInt32: t = Type.GetType("System.UInt32"); break; case TypeCode.UInt64: t = Type.GetType("System.UInt64"); break; default: t = Type.GetType("Object"); break; } return t; } static internal object GetConstFromTypeCode(TypeCode tc) { object t = null; switch (tc) { case TypeCode.Boolean: t = (object)true; break; case TypeCode.Byte: t = (object)Byte.MinValue; break; case TypeCode.Char: t = (object)Char.MinValue; break; case TypeCode.DateTime: t = (object)DateTime.MinValue; break; case TypeCode.Decimal: t = (object)Decimal.MinValue; break; case TypeCode.Double: t = (object)Double.MinValue; break; case TypeCode.Int16: t = (object)Int16.MinValue; break; case TypeCode.Int32: t = (object)Int32.MinValue; break; case TypeCode.Int64: t = (object)Int64.MinValue; break; case TypeCode.Object: t = (object)""; break; case TypeCode.SByte: t = (object)SByte.MinValue; break; case TypeCode.Single: t = (object)Single.MinValue; break; case TypeCode.String: t = (object)""; break; case TypeCode.UInt16: t = (object)UInt16.MinValue; break; case TypeCode.UInt32: t = (object)UInt32.MinValue; break; case TypeCode.UInt64: t = (object)UInt64.MinValue; break; default: t = (object)""; break; } return t; } } }
using System; using System.Linq; namespace NetGore { /// <summary> /// Extensions for multiple numeric types to check if the given number is between two other numbers. /// </summary> public static class IsBetweenExtensions { /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this int num, int min, int max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this uint num, uint min, uint max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this short num, short min, short max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this ushort num, ushort min, ushort max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this byte num, byte min, byte max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this sbyte num, sbyte min, sbyte max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this float num, float min, float max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this double num, double min, double max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this long num, long min, long max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this ulong num, ulong min, ulong max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this decimal num, decimal min, decimal max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Checks if a number is between two other numbers. This check is inclusive to the <paramref name="min"/> /// and <paramref name="max"/> numbers, so will be considered valid if <paramref name="num"/> is /// equal to either the <paramref name="min"/> or <paramref name="max"/> numbers. /// </summary> /// <param name="num">Number to check.</param> /// <param name="min">Minimum </param> /// <param name="max"></param> /// <returns>True if <paramref name="num"/> is between or equal to <paramref name="min"/> and /// <paramref name="max"/>, else false.</returns> public static bool IsBetween(this DateTime num, DateTime min, DateTime max) { if (min > max) Swap(ref min, ref max); return num >= min && num <= max; } /// <summary> /// Swaps two objects, so that <paramref name="a"/> will equal <paramref name="b"/> and /// <paramref name="b"/> will equal <paramref name="a"/>. /// </summary> /// <typeparam name="T">Type of object to swap.</typeparam> /// <param name="a">First object to swap.</param> /// <param name="b">Second object to swap.</param> static void Swap<T>(ref T a, ref T b) { var temp = a; a = b; b = temp; } } }
using System; using System.Reflection; namespace Epi { /// <summary> /// Application Identity class /// </summary> public class ApplicationIdentity { readonly Version assemblyVersion; readonly Version assemblyInformationalVersion; readonly Version assemblyFileVersion; readonly string company; readonly string product; readonly string copyright; readonly string releaseDate; /// <summary> /// Constructor /// </summary> /// <param name="a">CLR Application</param> public ApplicationIdentity(Assembly a) { assemblyVersion = a.GetName().Version; object[] customAttributes; customAttributes = a.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); if (customAttributes.Length == 1) { assemblyInformationalVersion = new Version(((AssemblyInformationalVersionAttribute)customAttributes[0]).InformationalVersion); } customAttributes = a.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false); if (customAttributes.Length == 1) { assemblyFileVersion = new Version(((AssemblyFileVersionAttribute)customAttributes[0]).Version); } customAttributes = a.GetCustomAttributes(typeof(AssemblyProductAttribute), false); if (customAttributes.Length == 1) { product = ((AssemblyProductAttribute)customAttributes[0]).Product; } customAttributes = a.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); if (customAttributes.Length == 1) { company = ((AssemblyCompanyAttribute)customAttributes[0]).Company; } customAttributes = a.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (customAttributes.Length == 1) { copyright = ((AssemblyCopyrightAttribute)customAttributes[0]).Copyright; } customAttributes = a.GetCustomAttributes(typeof(AssemblyReleaseDateAttribute), false); if (customAttributes.Length == 1) { releaseDate = ((AssemblyReleaseDateAttribute)customAttributes[0]).ReleaseDate; } } #region Public Properties /// <summary> /// Gets the version number of the application /// </summary> public string Version { get { return assemblyInformationalVersion.ToString(); } } /// <summary> /// Gets the version as an object /// </summary> public Version VersionObject { get { return assemblyInformationalVersion; } } /// <summary> /// Gets the build number of the application /// </summary> public string Build { get { return assemblyVersion.Build.ToString(); } } /// <summary> /// Gets the revision number of the application /// </summary> public string Revision { get { return assemblyVersion.Revision.ToString(); } } // /// <summary> // /// Gets the version release date if it is a release version. In development, returns today's date. // /// </summary> // public string VersionReleaseDate // { // get // { // //if (Global.IsInDevelopmentMode) // //{ // // return SharedStrings.DEV; // //} // //else // //{ // string releaseDate = System.Configuration.ConfigurationSettings.ApplicationIdentity[AppSettingKeys.VERSION_RELEASE_DATE]; // if (string.IsNullOrEmpty(releaseDate)) // { // return SharedStrings.DEV; // } // else // { //// $$$ TODO this is not locale neutral and will throw an error for other than US locale // return DateTime.Parse(releaseDate).ToShortDateString(); // } // //} // } // } /// <summary> /// App release date /// </summary> public string VersionReleaseDate { get { return releaseDate; } } /// <summary> /// Gets the application name /// </summary> public string AppName { get { return product; } } /// <summary> /// Gets the application suite name /// </summary> public string SuiteName { get { return product; } } /// <summary> /// Gets the company name /// </summary> public string Company { get { return company; } } /// <summary> /// Gets the company name /// </summary> public string Copyright { get { return copyright; } } #endregion Public Properties } /// <summary> /// Assembly Release Date Attribute /// </summary> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public class AssemblyReleaseDateAttribute : Attribute { private string releaseDate; /// <summary> /// Build date of assembly. /// </summary> public string ReleaseDate { get { return releaseDate; } set { releaseDate = value; } } /// <summary> /// Constructor /// </summary> /// <param name="releaseDate">Assembly release date.</param> public AssemblyReleaseDateAttribute(string releaseDate) { this.releaseDate = releaseDate; } } }
// 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 Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal static class ExprFactory { public static ExprCall CreateCall(EXPRFLAG flags, CType type, Expr arguments, ExprMemberGroup memberGroup, MethWithInst method) => new ExprCall(type, flags, arguments, memberGroup, method); public static ExprField CreateField(CType type, Expr optionalObject, FieldWithType field) => new ExprField(type, optionalObject, field); public static ExprArrayInit CreateArrayInit(CType type, Expr arguments, Expr argumentDimensions, int[] dimSizes, int dimSize) => new ExprArrayInit(type, arguments, argumentDimensions, dimSizes, dimSize); public static ExprProperty CreateProperty(CType type, Expr optionalObjectThrough, Expr arguments, ExprMemberGroup memberGroup, PropWithType property, MethWithType setMethod) => new ExprProperty(type, optionalObjectThrough, arguments, memberGroup, property, setMethod); public static ExprMemberGroup CreateMemGroup(EXPRFLAG flags, Name name, TypeArray typeArgs, SYMKIND symKind, CType parentType, Expr obj, CMemberLookupResults memberLookupResults) => new ExprMemberGroup(flags, name, typeArgs, symKind, parentType, obj, memberLookupResults); public static ExprMemberGroup CreateMemGroup(Expr obj, MethPropWithInst method) { Name name = method.Sym?.name; return CreateMemGroup( 0, name, method.TypeArgs, method.MethProp()?.getKind() ?? SYMKIND.SK_MethodSymbol, method.GetType(), obj, new CMemberLookupResults(TypeArray.Allocate((CType)method.GetType()), name)); } public static ExprUserDefinedConversion CreateUserDefinedConversion(Expr arg, Expr call, MethWithInst method) => new ExprUserDefinedConversion(arg, call, method); public static ExprCast CreateCast(CType type, Expr argument) => CreateCast(0, type, argument); public static ExprCast CreateCast(EXPRFLAG flags, CType type, Expr argument) => new ExprCast(flags, type, argument); public static ExprLocal CreateLocal(LocalVariableSymbol local) => new ExprLocal(local); public static ExprBoundLambda CreateAnonymousMethod(AggregateType delegateType, Scope argumentScope, Expr expression) => new ExprBoundLambda(delegateType, argumentScope, expression); public static ExprMethodInfo CreateMethodInfo(MethPropWithInst mwi) => CreateMethodInfo(mwi.Meth(), mwi.GetType(), mwi.TypeArgs); public static ExprMethodInfo CreateMethodInfo(MethodSymbol method, AggregateType methodType, TypeArray methodParameters) => new ExprMethodInfo( TypeManager.GetPredefAgg(method.IsConstructor() ? PredefinedType.PT_CONSTRUCTORINFO : PredefinedType.PT_METHODINFO).getThisType(), method, methodType, methodParameters); public static ExprPropertyInfo CreatePropertyInfo(PropertySymbol prop, AggregateType propertyType) => new ExprPropertyInfo(TypeManager.GetPredefAgg(PredefinedType.PT_PROPERTYINFO).getThisType(), prop, propertyType); public static ExprFieldInfo CreateFieldInfo(FieldSymbol field, AggregateType fieldType) => new ExprFieldInfo(field, fieldType, TypeManager.GetPredefAgg(PredefinedType.PT_FIELDINFO).getThisType()); public static ExprTypeOf CreateTypeOf(CType sourceType) => new ExprTypeOf(TypeManager.GetPredefAgg(PredefinedType.PT_TYPE).getThisType(), sourceType); public static ExprUserLogicalOp CreateUserLogOp(CType type, Expr trueFalseCall, ExprCall operatorCall) => new ExprUserLogicalOp(type, trueFalseCall, operatorCall); public static ExprConcat CreateConcat(Expr first, Expr second) => new ExprConcat(first, second); public static ExprConstant CreateStringConstant(string str) => CreateConstant(TypeManager.GetPredefAgg(PredefinedType.PT_STRING).getThisType(), ConstVal.Get(str)); public static ExprMultiGet CreateMultiGet(EXPRFLAG flags, CType type, ExprMulti multi) => new ExprMultiGet(type, flags, multi); public static ExprMulti CreateMulti(EXPRFLAG flags, CType type, Expr left, Expr op) => new ExprMulti(type, flags, left, op); //////////////////////////////////////////////////////////////////////////////// // // Precondition: // // type - Non-null // // This returns a null for reference types and an EXPRZEROINIT for all others. public static Expr CreateZeroInit(CType type) { Debug.Assert(type != null); if (type.IsEnumType) { // For enum types, we create a constant that has the default value // as an object pointer. return CreateConstant(type, ConstVal.Get(Activator.CreateInstance(type.AssociatedSystemType))); } Debug.Assert(type.FundamentalType > FUNDTYPE.FT_NONE); Debug.Assert(type.FundamentalType < FUNDTYPE.FT_COUNT); switch (type.FundamentalType) { case FUNDTYPE.FT_PTR: { // Just allocate a new node and fill it in. return CreateCast(0, type, CreateNull()); } case FUNDTYPE.FT_STRUCT: if (type.IsPredefType(PredefinedType.PT_DECIMAL)) { goto default; } goto case FUNDTYPE.FT_VAR; case FUNDTYPE.FT_VAR: return new ExprZeroInit(type); default: return CreateConstant(type, ConstVal.GetDefaultValue(type.ConstValKind)); } } public static ExprConstant CreateConstant(CType type, ConstVal constVal) => new ExprConstant(type, constVal); public static ExprConstant CreateIntegerConstant(int x) => CreateConstant(TypeManager.GetPredefAgg(PredefinedType.PT_INT).getThisType(), ConstVal.Get(x)); public static ExprConstant CreateBoolConstant(bool b) => CreateConstant(TypeManager.GetPredefAgg(PredefinedType.PT_BOOL).getThisType(), ConstVal.Get(b)); public static ExprArrayIndex CreateArrayIndex(CType type, Expr array, Expr index) => new ExprArrayIndex(type, array, index); public static ExprBinOp CreateBinop(ExpressionKind exprKind, CType type, Expr left, Expr right) => new ExprBinOp(exprKind, type, left, right); public static ExprUnaryOp CreateUnaryOp(ExpressionKind exprKind, CType type, Expr operand) => new ExprUnaryOp(exprKind, type, operand); public static ExprOperator CreateOperator(ExpressionKind exprKind, CType type, Expr arg1, Expr arg2) { Debug.Assert(arg1 != null); Debug.Assert(exprKind.IsUnaryOperator() == (arg2 == null)); return exprKind.IsUnaryOperator() ? (ExprOperator)CreateUnaryOp(exprKind, type, arg1) : CreateBinop(exprKind, type, arg1, arg2); } public static ExprBinOp CreateUserDefinedBinop(ExpressionKind exprKind, CType type, Expr left, Expr right, Expr call, MethPropWithInst userMethod) => new ExprBinOp(exprKind, type, left, right, call, userMethod); // The call may be lifted, but we do not mark the outer binop as lifted. public static ExprUnaryOp CreateUserDefinedUnaryOperator(ExpressionKind exprKind, CType type, Expr operand, ExprCall call, MethPropWithInst userMethod) => new ExprUnaryOp(exprKind, type, operand, call, userMethod); public static ExprUnaryOp CreateNeg(EXPRFLAG flags, Expr operand) { Debug.Assert(operand != null); ExprUnaryOp unary = CreateUnaryOp(ExpressionKind.Negate, operand.Type, operand); unary.Flags |= flags; return unary; } //////////////////////////////////////////////////////////////////////////////// // Create a node that evaluates the first, evaluates the second, results in the second. public static ExprBinOp CreateSequence(Expr first, Expr second) => CreateBinop(ExpressionKind.Sequence, second.Type, first, second); //////////////////////////////////////////////////////////////////////////////// // Create a node that evaluates the first, evaluates the second, results in the first. public static ExprAssignment CreateAssignment(Expr left, Expr right) => new ExprAssignment(left, right); //////////////////////////////////////////////////////////////////////////////// public static ExprNamedArgumentSpecification CreateNamedArgumentSpecification(Name name, Expr value) => new ExprNamedArgumentSpecification(name, value); public static ExprWrap CreateWrap(Expr expression) => new ExprWrap(expression); public static ExprBinOp CreateSave(ExprWrap wrap) { Debug.Assert(wrap != null); ExprBinOp expr = CreateBinop(ExpressionKind.Save, wrap.Type, wrap.OptionalExpression, wrap); expr.SetAssignment(); return expr; } public static ExprConstant CreateNull() => CreateConstant(NullType.Instance, default); public static void AppendItemToList(Expr newItem, ref Expr first, ref Expr last) { if (newItem == null) { // Nothing changes. return; } if (first == null) { Debug.Assert(last == first); first = newItem; last = newItem; return; } if (first.Kind != ExpressionKind.List) { Debug.Assert(last == first); first = CreateList(first, newItem); last = first; return; } Debug.Assert((last as ExprList)?.OptionalNextListNode != null); Debug.Assert((last as ExprList).OptionalNextListNode.Kind != ExpressionKind.List); ExprList list = (ExprList)last; list.OptionalNextListNode = CreateList(list.OptionalNextListNode, newItem); last = list.OptionalNextListNode; } public static ExprList CreateList(Expr op1, Expr op2) => new ExprList(op1, op2); public static ExprList CreateList(Expr op1, Expr op2, Expr op3) => CreateList(op1, CreateList(op2, op3)); public static ExprList CreateList(Expr op1, Expr op2, Expr op3, Expr op4) => CreateList(op1, CreateList(op2, CreateList(op3, op4))); public static ExprClass CreateClass(CType type) => new ExprClass(type); } }
namespace Microsoft.ApplicationInsights.DataContracts { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Threading; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.ApplicationInsights.Extensibility.Implementation.External; using Microsoft.ApplicationInsights.Extensibility.Implementation.Metrics; using static System.Threading.LazyInitializer; /// <summary> /// The class that represents information about the collected dependency. /// <a href="https://go.microsoft.com/fwlink/?linkid=839889">Learn more.</a> /// </summary> public sealed class DependencyTelemetry : OperationTelemetry, ITelemetry, ISupportProperties, ISupportAdvancedSampling, ISupportMetrics, IAiSerializableTelemetry { internal const string EtwEnvelopeName = "RemoteDependency"; internal string EnvelopeName = "AppDependencies"; private readonly TelemetryContext context; private IExtension extension; private double? samplingPercentage; private bool successFieldSet; private bool success = true; private IDictionary<string, double> measurementsValue; private RemoteDependencyData internalDataPrivate; /// <summary> /// Initializes a new instance of the <see cref="DependencyTelemetry"/> class. /// </summary> public DependencyTelemetry() { this.successFieldSet = true; this.context = new TelemetryContext(); this.GenerateId(); this.Name = string.Empty; this.ResultCode = string.Empty; this.Duration = TimeSpan.Zero; this.Target = string.Empty; this.Type = string.Empty; this.Data = string.Empty; } /// <summary> /// Initializes a new instance of the <see cref="DependencyTelemetry"/> class with the given <paramref name="dependencyName"/>, <paramref name="data"/>, /// <paramref name="startTime"/>, <paramref name="duration"/> and <paramref name="success"/> property values. /// </summary> [Obsolete("Use other constructors which allows to define dependency call with all the properties.")] public DependencyTelemetry(string dependencyName, string data, DateTimeOffset startTime, TimeSpan duration, bool success) : this() { this.Name = dependencyName; this.Data = data; this.Duration = duration; this.Success = success; this.Timestamp = startTime; } /// <summary> /// Initializes a new instance of the <see cref="DependencyTelemetry"/> class with the given <paramref name="dependencyTypeName"/>, <paramref name="target"/>, /// <paramref name="dependencyName"/>, <paramref name="data"/> property values. /// </summary> public DependencyTelemetry(string dependencyTypeName, string target, string dependencyName, string data) : this() { this.Type = dependencyTypeName; this.Target = target; this.Name = dependencyName; this.Data = data; } /// <summary> /// Initializes a new instance of the <see cref="DependencyTelemetry"/> class with the given <paramref name="dependencyTypeName"/>, <paramref name="target"/>, /// <paramref name="dependencyName"/>, <paramref name="data"/>, <paramref name="startTime"/>, <paramref name="duration"/>, <paramref name="resultCode"/> /// and <paramref name="success"/> and property values. /// </summary> public DependencyTelemetry(string dependencyTypeName, string target, string dependencyName, string data, DateTimeOffset startTime, TimeSpan duration, string resultCode, bool success) : this() { this.Type = dependencyTypeName; this.Target = target; this.Name = dependencyName; this.Data = data; this.Timestamp = startTime; this.Duration = duration; this.ResultCode = resultCode; this.Success = success; } /// <summary> /// Initializes a new instance of the <see cref="DependencyTelemetry"/> class by cloning an existing instance. /// </summary> /// <param name="source">Source instance of <see cref="DependencyTelemetry"/> to clone from.</param> private DependencyTelemetry(DependencyTelemetry source) { if (source.measurementsValue != null) { Utils.CopyDictionary(source.Metrics, this.Metrics); } this.context = source.context.DeepClone(); this.Sequence = source.Sequence; this.Timestamp = source.Timestamp; this.samplingPercentage = source.samplingPercentage; this.ProactiveSamplingDecision = source.ProactiveSamplingDecision; this.successFieldSet = source.successFieldSet; this.extension = source.extension?.DeepClone(); this.Name = source.Name; this.Id = source.Id; this.ResultCode = source.ResultCode; this.Duration = source.Duration; this.Success = source.Success; this.Data = source.Data; this.Target = source.Target; this.Type = source.Type; } /// <inheritdoc /> string IAiSerializableTelemetry.TelemetryName { get { return this.EnvelopeName; } set { this.EnvelopeName = value; } } /// <inheritdoc /> string IAiSerializableTelemetry.BaseType => nameof(RemoteDependencyData); /// <summary> /// Gets or sets date and time when telemetry was recorded. /// </summary> public override DateTimeOffset Timestamp { get; set; } /// <summary> /// Gets or sets the value that defines absolute order of the telemetry item. /// </summary> public override string Sequence { get; set; } /// <summary> /// Gets the context associated with the current telemetry item. /// </summary> public override TelemetryContext Context { get { return this.context; } } /// <summary> /// Gets or sets gets the extension used to extend this telemetry instance using new strongly typed object. /// </summary> public override IExtension Extension { get { return this.extension; } set { this.extension = value; } } /// <summary> /// Gets or sets Dependency ID. /// </summary> public override string Id { get; set; } /// <summary> /// Gets or sets the Result Code. /// </summary> public string ResultCode { get; set; } /// <summary> /// Gets or sets resource name. /// </summary> public override string Name { get; set; } /// <summary> /// Gets or sets text of SQL command or empty it not applicable. /// </summary> [Obsolete("Renamed to Data")] public string CommandName { get { return this.Data; } set { this.Data = value; } } /// <summary> /// Gets or sets data associated with the current dependency instance. Command name/statement for SQL dependency, URL for http dependency. /// </summary> public string Data { get; set; } /// <summary> /// Gets or sets target of dependency call. SQL server name, url host, etc. /// </summary> public string Target { get; set; } /// <summary> /// Gets or sets the dependency type name. /// </summary> [Obsolete("Renamed to Type")] public string DependencyTypeName { get { return this.Type; } set { this.Type = value; } } /// <summary> /// Gets or sets the dependency type name. /// </summary> public string Type { get; set; } /// <summary> /// Gets or sets the amount of time it took the application to handle the request. /// </summary> public override TimeSpan Duration { get; set; } /// <summary> /// Gets or sets a value indicating whether the dependency call was successful or not. /// </summary> public override bool? Success { get { if (this.successFieldSet) { return this.success; } return null; } set { if (value != null && value.HasValue) { this.success = value.Value; this.successFieldSet = true; } else { this.success = true; this.successFieldSet = false; } } } /// <summary> /// Gets a dictionary of application-defined property names and values providing additional information about this remote dependency. /// <a href="https://go.microsoft.com/fwlink/?linkid=525722#properties">Learn more</a> /// </summary> public override IDictionary<string, string> Properties { get { #pragma warning disable CS0618 // Type or member is obsolete if (!string.IsNullOrEmpty(this.MetricExtractorInfo) && !this.Context.Properties.ContainsKey(MetricTerms.Extraction.ProcessedByExtractors.Moniker.Key)) { this.Context.Properties[MetricTerms.Extraction.ProcessedByExtractors.Moniker.Key] = this.MetricExtractorInfo; } return this.Context.Properties; #pragma warning restore CS0618 // Type or member is obsolete } } /// <summary> /// Gets a dictionary of application-defined event metrics. /// <a href="https://go.microsoft.com/fwlink/?linkid=525722#properties">Learn more</a> /// </summary> public override IDictionary<string, double> Metrics { get { return LazyInitializer.EnsureInitialized(ref this.measurementsValue, () => new ConcurrentDictionary<string, double>()); } } /// <summary> /// Gets or sets the dependency kind, like SQL, HTTP, Azure, etc. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Type")] public string DependencyKind { get { return this.DependencyTypeName; } set { this.DependencyTypeName = value; } } /// <summary> /// Gets or sets data sampling percentage (between 0 and 100). /// Should be 100/n where n is an integer. <a href="https://go.microsoft.com/fwlink/?linkid=832969">Learn more</a> /// </summary> double? ISupportSampling.SamplingPercentage { get { return this.samplingPercentage; } set { this.samplingPercentage = value; } } /// <summary> /// Gets item type for sampling evaluation. /// </summary> public SamplingTelemetryItemTypes ItemTypeFlag => SamplingTelemetryItemTypes.RemoteDependency; /// <inheritdoc/> public SamplingDecision ProactiveSamplingDecision { get; set; } /// <summary> /// Gets or sets the MetricExtractorInfo. /// </summary> internal string MetricExtractorInfo { get; set; } /// <summary> /// Gets the InternalData associated with this Telemetry instance. /// This is being served by a singleton instance, so this will /// not pickup changes made to the telemetry after first call to this. /// It is recommended to make all changes (including sanitization) /// to this telemetry before calling InternalData. /// </summary> internal RemoteDependencyData InternalData { get { return LazyInitializer.EnsureInitialized(ref this.internalDataPrivate, () => { var req = new RemoteDependencyData(); req.duration = this.Duration; req.id = this.Id; req.measurements = this.measurementsValue; req.name = this.Name; req.properties = this.context.PropertiesValue; req.resultCode = this.ResultCode; req.target = this.Target; req.success = this.success; req.data = this.Data; req.type = this.Type; return req; }); } private set { this.internalDataPrivate = value; } } /// <summary> /// Deeply clones a <see cref="DependencyTelemetry"/> object. /// </summary> /// <returns>A cloned instance.</returns> public override ITelemetry DeepClone() { return new DependencyTelemetry(this); } /// <summary> /// In specific collectors, objects are added to the dependency telemetry which may be useful /// to enhance DependencyTelemetry telemetry by <see cref="ITelemetryInitializer" /> implementations. /// Objects retrieved here are not automatically serialized and sent to the backend. /// </summary> /// <param name="key">The key of the value to get.</param> /// <param name="detail">When this method returns, contains the object that has the specified key, or the default value of the type if the operation failed.</param> /// <returns>true if the key was found; otherwise, false.</returns> public bool TryGetOperationDetail(string key, out object detail) { return this.Context.TryGetRawObject(key, out detail); } /// <summary> /// Sets the operation detail specific against the key specified. Objects set through this method /// are not automatically serialized and sent to the backend. /// </summary> /// <param name="key">The key to store the detail against.</param> /// <param name="detail">Detailed information collected by the tracked operation.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void SetOperationDetail(string key, object detail) { this.Context.StoreRawObject(key, detail, true); } /// <inheritdoc/> public override void SerializeData(ISerializationWriter serializationWriter) { // To ensure that all changes to telemetry are reflected in serialization, // the underlying field is set to null, which forces it to be re-created. this.internalDataPrivate = null; serializationWriter.WriteProperty(this.InternalData); } /// <summary> /// Sanitizes the properties based on constraints. /// </summary> void ITelemetry.Sanitize() { this.Name = this.Name.SanitizeName(); this.Name = Utils.PopulateRequiredStringValue(this.Name, "name", typeof(DependencyTelemetry).FullName); this.Id.SanitizeName(); this.ResultCode = this.ResultCode.SanitizeResultCode(); this.Type = this.Type.SanitizeDependencyType(); this.Data = this.Data.SanitizeData(); this.Properties.SanitizeProperties(); this.Metrics.SanitizeMeasurements(); } } }
// 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 Xunit; namespace System.Collections.Tests { public class ReadOnlyCollectionBaseTests { [Fact] public void TesReadOnlyCollectionBasBasic() { MyReadOnlyCollectionBase mycol1; MyReadOnlyCollectionBase mycol2; Foo f1; Foo[] arrF1; Foo[] arrF2; IEnumerator enu1; int iCount; object obj1; ReadOnlyCollectionBase collectionBase; //[]ReadOnlyCollectionBase implements IList (which means both ICollection and IEnumerator as well :-() //To test this class, we will implement our own strongly typed ReadOnlyCollectionBase and call its methods //[] SyncRoot property arrF1 = new Foo[100]; for (int i = 0; i < 100; i++) arrF1[i] = new Foo(); mycol1 = new MyReadOnlyCollectionBase(arrF1); Assert.False(mycol1.SyncRoot is ArrayList, "Error SyncRoot returned ArrayList"); //[] Count property arrF1 = new Foo[100]; for (int i = 0; i < 100; i++) arrF1[i] = new Foo(); mycol1 = new MyReadOnlyCollectionBase(arrF1); Assert.Equal(100, mycol1.Count); //[]CopyTo arrF2 = new Foo[100]; for (int i = 0; i < 100; i++) arrF2[i] = new Foo(i, i.ToString()); mycol1 = new MyReadOnlyCollectionBase(arrF2); arrF1 = new Foo[100]; mycol1.CopyTo(arrF1, 0); for (int i = 0; i < 100; i++) { Assert.Equal(i, arrF1[i].IValue); Assert.Equal(i.ToString(), arrF1[i].SValue); } //Argument checking arrF2 = new Foo[100]; for (int i = 0; i < 100; i++) arrF2[i] = new Foo(i, i.ToString()); mycol1 = new MyReadOnlyCollectionBase(arrF2); arrF1 = new Foo[100]; Assert.Throws<ArgumentException>(() => { mycol1.CopyTo(arrF1, 50); } ); Assert.Throws<ArgumentOutOfRangeException>(() => { mycol1.CopyTo(arrF1, -1); } ); arrF1 = new Foo[200]; mycol1.CopyTo(arrF1, 100); for (int i = 0; i < 100; i++) { Assert.Equal(i, arrF1[100 + i].IValue); Assert.Equal(i.ToString(), arrF1[100 + i].SValue); } //[]GetEnumerator arrF2 = new Foo[100]; for (int i = 0; i < 100; i++) arrF2[i] = new Foo(i, i.ToString()); mycol1 = new MyReadOnlyCollectionBase(arrF2); enu1 = mycol1.GetEnumerator(); //Calling current should throw here Assert.Throws<InvalidOperationException>(() => { f1 = (Foo)enu1.Current; } ); iCount = 0; while (enu1.MoveNext()) { f1 = (Foo)enu1.Current; Assert.False((f1.IValue != iCount) || (f1.SValue != iCount.ToString()), "Error, does not match, " + f1.IValue); iCount++; } Assert.Equal(100, iCount); //Calling current should throw here Assert.Throws<InvalidOperationException>(() => { f1 = (Foo)enu1.Current; } ); //[]IsSynchronized arrF2 = new Foo[100]; for (int i = 0; i < 100; i++) arrF2[i] = new Foo(i, i.ToString()); Assert.False(((ICollection)mycol1).IsSynchronized); //[]SyncRoot arrF2 = new Foo[100]; for (int i = 0; i < 100; i++) arrF2[i] = new Foo(i, i.ToString()); obj1 = mycol1.SyncRoot; mycol2 = mycol1; Assert.Equal(obj1, mycol2.SyncRoot); //End of ICollection and IEnumerator methods //Now to IList methods //[]this, Contains, IndexOf arrF2 = new Foo[100]; for (int i = 0; i < 100; i++) arrF2[i] = new Foo(i, i.ToString()); mycol1 = new MyReadOnlyCollectionBase(arrF2); for (int i = 0; i < 100; i++) { Assert.False((mycol1[i].IValue != i) || (mycol1[i].SValue != i.ToString())); Assert.False((mycol1.IndexOf(new Foo(i, i.ToString())) != i)); Assert.False((!mycol1.Contains(new Foo(i, i.ToString())))); } //[]Rest of the IList methods: IsFixedSize, IsReadOnly arrF2 = new Foo[100]; for (int i = 0; i < 100; i++) arrF2[i] = new Foo(i, i.ToString()); mycol1 = new MyReadOnlyCollectionBase(arrF2); Assert.True(mycol1.IsFixedSize); Assert.True(mycol1.IsReadOnly); //The following operations are not allowed by the compiler. Hence, commented out arrF2 = new Foo[100]; for (int i = 0; i < 100; i++) arrF2[i] = new Foo(i, i.ToString()); mycol1 = new MyReadOnlyCollectionBase(arrF2); //[] Verify Count is virtual collectionBase = new VirtualTestReadOnlyCollection(); Assert.Equal(collectionBase.Count, int.MinValue); //[] Verify Count is virtual collectionBase = new VirtualTestReadOnlyCollection(); Assert.Null(collectionBase.GetEnumerator()); } //ReadOnlyCollectionBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here. //This collection only allows the type Foo public class MyReadOnlyCollectionBase : ReadOnlyCollectionBase { //we need a way of initializing this collection public MyReadOnlyCollectionBase(Foo[] values) { InnerList.AddRange(values); } public Foo this[int indx] { get { return (Foo)InnerList[indx]; } } public void CopyTo(Array array, int index) { ((ICollection)this).CopyTo(array, index);// Use the base class explicit implemenation of ICollection.CopyTo } public virtual object SyncRoot { get { return ((ICollection)this).SyncRoot;// Use the base class explicit implemenation of ICollection.SyncRoot } } public int IndexOf(Foo f) { return ((IList)InnerList).IndexOf(f); } public Boolean Contains(Foo f) { return ((IList)InnerList).Contains(f); } public Boolean IsFixedSize { get { return true; } } public Boolean IsReadOnly { get { return true; } } } public class VirtualTestReadOnlyCollection : ReadOnlyCollectionBase { public override int Count { get { return int.MinValue; } } public override IEnumerator GetEnumerator() { return null; } } public class Foo { private int _iValue; private String _strValue; public Foo() { } public Foo(int i, String str) { _iValue = i; _strValue = str; } public int IValue { get { return _iValue; } set { _iValue = value; } } public String SValue { get { return _strValue; } set { _strValue = value; } } public override Boolean Equals(object obj) { if (obj == null) return false; if (!(obj is Foo)) return false; if ((((Foo)obj).IValue == _iValue) && (((Foo)obj).SValue == _strValue)) return true; return false; } public override int GetHashCode() { return _iValue; } } } }
/* * 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.Diagnostics; using System.IO; using System.Reflection; using System.Text; using System.Threading; using log4net; namespace OpenSim.GridLaunch { internal partial class AppExecutor : IDisposable { // How long to wait for process to shut down by itself private static readonly int shutdownWaitSeconds = 10; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); //private StreamWriter Input { get { return process.StandardInput; } } //private StreamReader Output { get { return process.StandardOutput; } } //private StreamReader Error { get { return process.StandardError; } } private StreamWriter Input { get; set; } private StreamReader Output { get; set; } private StreamReader Error { get; set; } private object processLock = new object(); private bool isRunning = false; public bool IsRunning { get { return isRunning; } } private string file; public string File { get { return file; } } Process process; public AppExecutor(string File) { file = File; } #region Dispose of unmanaged resources ~AppExecutor() { Dispose(); } private bool isDisposed = false; public void Dispose() { if (!isDisposed) { isDisposed = true; Stop(); } } #endregion #region Start / Stop process public void Start() { if (isDisposed) throw new ApplicationException("Attempt to start process in Disposed instance of AppExecutor."); // Stop before starting Stop(); lock (processLock) { isRunning = true; m_log.InfoFormat("Starting \"{0}\".", file); // Start the process process = new Process(); process.StartInfo.FileName = file; process.StartInfo.Arguments = ""; process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.StartInfo.ErrorDialog = false; process.EnableRaisingEvents = true; // Redirect all standard input/output/errors process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; // Start process process.Start(); Input = process.StandardInput; Output = process.StandardOutput; Error = process.StandardError; // Start data copying timer_Start(); // We will flush manually //Input.AutoFlush = false; } } public void Stop() { // Shut down process // We will ignore some exceptions here, against good programming practice... :) lock (processLock) { // Running? if (!isRunning) return; isRunning = false; timer_Stop(); m_log.InfoFormat("Stopping \"{0}\".", file); // Send exit command to console try { if (Input != null) { _writeLine(""); _writeLine("exit"); _writeLine("quit"); // Wait for process to exit process.WaitForExit(1000 * shutdownWaitSeconds); } } catch (Exception ex) { m_log.ErrorFormat("Exeption asking \"{0}\" to shut down: {1}", file, ex.ToString()); } try { // Forcefully kill it if (process.HasExited != true) process.Kill(); } catch (Exception ex) { m_log.ErrorFormat("Exeption killing \"{0}\": {1}", file, ex.ToString()); } try { // Free resources process.Close(); } catch (Exception ex) { m_log.ErrorFormat("Exeption freeing resources for \"{0}\": {1}", file, ex.ToString()); } // Dispose of stream and process object //SafeDisposeOf(Input); //SafeDisposeOf(Output); //SafeDisposeOf(Error); Program.SafeDisposeOf(process); } // Done stopping process } #endregion #region Write to stdInput public void Write(string Text) { // Lock so process won't shut down while we write, and that we won't write while proc is shutting down lock (processLock) { _write(Text); } } public void _write(string Text) { if (Input != null) { try { Input.Write(Text); Input.Flush(); } catch (Exception ex) { m_log.ErrorFormat("Exeption sending text \"{0}\" to \"{1}\": {2}", file, Text, ex.ToString()); } } } public void WriteLine(string Text) { // Lock so process won't shut down while we write, and that we won't write while proc is shutting down lock (processLock) { _writeLine(Text); } } public void _writeLine(string Text) { if (Input != null) { try { m_log.DebugFormat("\"{0}\": Sending: \"{1}\"", file, Text); Input.WriteLine(Text); Input.Flush(); } catch (Exception ex) { m_log.ErrorFormat("Exeption sending text \"{0}\" to \"{1}\": {2}", file, Text, ex.ToString()); } } } #endregion } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ------------------------------------------------------------------------------ namespace Microsoft.Live.Operations { using System; using System.IO; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using BT = Windows.Networking.BackgroundTransfer; using Windows.Storage; using Windows.Storage.Streams; /// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> internal class TailoredUploadOperation : ApiOperation { #region Instance member variables private const uint MaxUploadResponseLength = 10240; private BT.UploadOperation uploadOp; /// <summary> /// CancellationTokenSource used when calling the BT.UploadOperation. /// </summary> private CancellationTokenSource uploadOpCts; private bool isAttach; #endregion #region Cosntructors /// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> /// <remarks>This constructor is used when uploading a file from the file system.</remarks> public TailoredUploadOperation( LiveConnectClient client, Uri url, string fileName, IStorageFile inputFile, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) : this(client, url, fileName, option, progress, syncContext) { Debug.Assert(inputFile != null, "inputFile is null."); this.InputFile = inputFile; } /// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> /// <remarks>This constructor is used when uploading a stream created by the application.</remarks> public TailoredUploadOperation( LiveConnectClient client, Uri url, string fileName, IInputStream inputStream, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) : this(client, url, fileName, option, progress, syncContext) { Debug.Assert(inputStream != null, "inputStream is null."); this.InputStream = inputStream; } /// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> /// <remarks>This constructor is used when uploading a stream created by the application.</remarks> internal TailoredUploadOperation( LiveConnectClient client, Uri url, string fileName, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) : base(client, url, ApiMethod.Upload, null, syncContext) { this.FileName = fileName; this.Progress = progress; this.OverwriteOption = option; } /// <summary> /// Creates a new TailoredDownloadOperation instance. /// </summary> /// <remarks>This constructor should only be used when attaching to an pending download.</remarks> internal TailoredUploadOperation() : base(null, null, ApiMethod.Upload, null, null) { } #endregion #region Properties public string FileName { get; private set; } public OverwriteOption OverwriteOption { get; private set; } public IStorageFile InputFile { get; private set; } public IInputStream InputStream { get; private set; } public IProgress<LiveOperationProgress> Progress { get; private set; } #endregion #region Public methods public async void Attach(BT.UploadOperation uploadOp) { Debug.Assert(uploadOp != null); this.uploadOp = uploadOp; this.isAttach = true; this.uploadOpCts = new CancellationTokenSource(); var progressHandler = new Progress<BT.UploadOperation>(this.OnUploadProgress); try { // Since we don't provide API for apps to attach to pending upload operations, we have no // way to invoke the app event handler to provide any feedback. We would just ignore the result here. this.uploadOp = await this.uploadOp.AttachAsync().AsTask(this.uploadOpCts.Token, progressHandler); } catch { // Ignore errors as well. } } public override void Cancel() { if (this.Status == OperationStatus.Cancelled || this.Status == OperationStatus.Completed) { return; } this.Status = OperationStatus.Cancelled; if (this.uploadOp != null) { this.uploadOpCts.Cancel(); } else { base.OnCancel(); } } #endregion #region Protected methods protected override void OnExecute() { var getUploadLinkOp = new GetUploadLinkOperation( this.LiveClient, this.Url, this.FileName, this.OverwriteOption, null); getUploadLinkOp.OperationCompletedCallback = this.OnGetUploadLinkCompleted; getUploadLinkOp.Execute(); } #endregion #region Private methods private async void OnGetUploadLinkCompleted(LiveOperationResult result) { if (this.Status == OperationStatus.Cancelled) { base.OnCancel(); return; } if (result.Error != null || result.IsCancelled) { this.OnOperationCompleted(result); return; } var uploadUrl = new Uri(result.RawResult, UriKind.Absolute); // NOTE: the GetUploadLinkOperation will return a uri with the overwite, suppress_response_codes, // and suppress_redirect query parameters set. Debug.Assert(uploadUrl.Query != null); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.Overwrite)); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressRedirects)); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressResponseCodes)); var uploader = new BT.BackgroundUploader(); uploader.Group = LiveConnectClient.LiveSDKUploadGroup; if (this.LiveClient.Session != null) { uploader.SetRequestHeader( ApiOperation.AuthorizationHeader, AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken); } uploader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue()); uploader.Method = HttpMethods.Put; this.uploadOpCts = new CancellationTokenSource(); Exception webError = null; LiveOperationResult opResult = null; try { if (this.InputStream != null) { this.uploadOp = await uploader.CreateUploadFromStreamAsync(uploadUrl, this.InputStream); } else { this.uploadOp = uploader.CreateUpload(uploadUrl, this.InputFile); } var progressHandler = new Progress<BT.UploadOperation>(this.OnUploadProgress); this.uploadOp = await this.uploadOp.StartAsync().AsTask(this.uploadOpCts.Token, progressHandler); } catch (TaskCanceledException exception) { opResult = new LiveOperationResult(exception, true); } catch (Exception exp) { // This might be an server error. We will read the response to determine the error message. webError = exp; } if (opResult == null) { try { IInputStream responseStream = this.uploadOp == null ? null : this.uploadOp.GetResultStreamAt(0); if (responseStream == null) { var error = new LiveConnectException( ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("ConnectionError")); opResult = new LiveOperationResult(error, false); } else { var reader = new DataReader(responseStream); uint length = await reader.LoadAsync(MaxUploadResponseLength); opResult = ApiOperation.CreateOperationResultFrom(reader.ReadString(length), ApiMethod.Upload); if (webError != null && opResult.Error != null && !(opResult.Error is LiveConnectException)) { // If the error did not come from the api service, // we'll just return the error thrown by the uploader. opResult = new LiveOperationResult(webError, false); } } } catch (COMException exp) { opResult = new LiveOperationResult(exp, false); } catch (FileNotFoundException exp) { opResult = new LiveOperationResult(exp, false); } } this.OnOperationCompleted(opResult); } /// <summary> /// Called when a progress event is raised from the BT.UploadOperation and this /// will call this TailoredUploadOperation's progress handler. /// </summary> private void OnUploadProgress(BT.UploadOperation uploadOp) { Debug.Assert(uploadOp != null); if (uploadOp.Progress.Status == BT.BackgroundTransferStatus.Error || uploadOp.Progress.Status == BT.BackgroundTransferStatus.Canceled || this.isAttach || this.Progress == null) { return; } this.Progress.Report( new LiveOperationProgress( (long)uploadOp.Progress.BytesSent, (long)uploadOp.Progress.TotalBytesToSend)); } #endregion } }
/* * 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 lambda-2015-03-31.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.Lambda.Model; namespace Amazon.Lambda { /// <summary> /// Interface for accessing Lambda /// /// AWS Lambda /// <para> /// <b>Overview</b> /// </para> /// /// <para> /// This is the <i>AWS Lambda API Reference</i>. The AWS Lambda Developer Guide provides /// additional information. For the service overview, go to <a href="http://docs.aws.amazon.com/lambda/latest/dg/welcome.html">What /// is AWS Lambda</a>, and for information about how the service works, go to <a href="http://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html">AWS /// Lambda: How it Works</a> in the <i>AWS Lambda Developer Guide</i>. /// </para> /// </summary> public partial interface IAmazonLambda : IDisposable { #region AddPermission /// <summary> /// Initiates the asynchronous execution of the AddPermission operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AddPermission operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<AddPermissionResponse> AddPermissionAsync(AddPermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateEventSourceMapping /// <summary> /// Initiates the asynchronous execution of the CreateEventSourceMapping operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateEventSourceMapping operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateEventSourceMappingResponse> CreateEventSourceMappingAsync(CreateEventSourceMappingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateFunction /// <summary> /// Initiates the asynchronous execution of the CreateFunction operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateFunction operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateFunctionResponse> CreateFunctionAsync(CreateFunctionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteEventSourceMapping /// <summary> /// Initiates the asynchronous execution of the DeleteEventSourceMapping operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteEventSourceMapping operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteEventSourceMappingResponse> DeleteEventSourceMappingAsync(DeleteEventSourceMappingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteFunction /// <summary> /// Deletes the specified Lambda function code and configuration. /// /// /// <para> /// When you delete a function the associated access policy is also deleted. You will /// need to delete the event source mappings explicitly. /// </para> /// /// <para> /// This operation requires permission for the <code>lambda:DeleteFunction</code> action. /// </para> /// </summary> /// <param name="functionName">The Lambda function to delete. You can specify an unqualified function name (for example, "Thumbnail") or you can specify Amazon Resource Name (ARN) of the function (for example, "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail"). Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 character in length. </param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteFunction service method, as returned by Lambda.</returns> /// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException"> /// The resource (for example, a Lambda function or access policy statement) specified /// in the request does not exist. /// </exception> /// <exception cref="Amazon.Lambda.Model.ServiceException"> /// The AWS Lambda service encountered an internal error. /// </exception> /// <exception cref="Amazon.Lambda.Model.TooManyRequestsException"> /// /// </exception> Task<DeleteFunctionResponse> DeleteFunctionAsync(string functionName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DeleteFunction operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteFunction operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteFunctionResponse> DeleteFunctionAsync(DeleteFunctionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetEventSourceMapping /// <summary> /// Initiates the asynchronous execution of the GetEventSourceMapping operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetEventSourceMapping operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetEventSourceMappingResponse> GetEventSourceMappingAsync(GetEventSourceMappingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetFunction /// <summary> /// Returns the configuration information of the Lambda function and a presigned URL link /// to the .zip file you uploaded with <a>CreateFunction</a> so you can download the .zip /// file. Note that the URL is valid for up to 10 minutes. The configuration information /// is the same information you provided as parameters when uploading the function. /// /// /// <para> /// This operation requires permission for the <code>lambda:GetFunction</code> action. /// </para> /// </summary> /// <param name="functionName">The Lambda function name. You can specify an unqualified function name (for example, "Thumbnail") or you can specify Amazon Resource Name (ARN) of the function (for example, "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail"). Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 character in length. </param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetFunction service method, as returned by Lambda.</returns> /// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException"> /// The resource (for example, a Lambda function or access policy statement) specified /// in the request does not exist. /// </exception> /// <exception cref="Amazon.Lambda.Model.ServiceException"> /// The AWS Lambda service encountered an internal error. /// </exception> /// <exception cref="Amazon.Lambda.Model.TooManyRequestsException"> /// /// </exception> Task<GetFunctionResponse> GetFunctionAsync(string functionName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the GetFunction operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetFunction operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetFunctionResponse> GetFunctionAsync(GetFunctionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetFunctionConfiguration /// <summary> /// Returns the configuration information of the Lambda function. This the same information /// you provided as parameters when uploading the function by using <a>CreateFunction</a>. /// /// /// <para> /// This operation requires permission for the <code>lambda:GetFunctionConfiguration</code> /// operation. /// </para> /// </summary> /// <param name="functionName">The name of the Lambda function for which you want to retrieve the configuration information. You can specify an unqualified function name (for example, "Thumbnail") or you can specify Amazon Resource Name (ARN) of the function (for example, "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail"). Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 character in length. </param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetFunctionConfiguration service method, as returned by Lambda.</returns> /// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException"> /// The resource (for example, a Lambda function or access policy statement) specified /// in the request does not exist. /// </exception> /// <exception cref="Amazon.Lambda.Model.ServiceException"> /// The AWS Lambda service encountered an internal error. /// </exception> /// <exception cref="Amazon.Lambda.Model.TooManyRequestsException"> /// /// </exception> Task<GetFunctionConfigurationResponse> GetFunctionConfigurationAsync(string functionName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the GetFunctionConfiguration operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetFunctionConfiguration operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetFunctionConfigurationResponse> GetFunctionConfigurationAsync(GetFunctionConfigurationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetPolicy /// <summary> /// Initiates the asynchronous execution of the GetPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetPolicy operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetPolicyResponse> GetPolicyAsync(GetPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Invoke /// <summary> /// Initiates the asynchronous execution of the Invoke operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Invoke operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<InvokeResponse> InvokeAsync(InvokeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region InvokeAsync /// <summary> /// Initiates the asynchronous execution of the InvokeAsync operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the InvokeAsync operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> [Obsolete("This API is deprecated. We recommend that you use Invoke API instead.")] Task<InvokeAsyncResponse> InvokeAsyncAsync(InvokeAsyncRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListEventSourceMappings /// <summary> /// Initiates the asynchronous execution of the ListEventSourceMappings operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListEventSourceMappings operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListEventSourceMappingsResponse> ListEventSourceMappingsAsync(ListEventSourceMappingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListFunctions /// <summary> /// Returns a list of your Lambda functions. For each function, the response includes /// the function configuration information. You must use <a>GetFunction</a> to retrieve /// the code for your function. /// /// /// <para> /// This operation requires permission for the <code>lambda:ListFunctions</code> action. /// </para> /// </summary> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListFunctions service method, as returned by Lambda.</returns> /// <exception cref="Amazon.Lambda.Model.ServiceException"> /// The AWS Lambda service encountered an internal error. /// </exception> /// <exception cref="Amazon.Lambda.Model.TooManyRequestsException"> /// /// </exception> Task<ListFunctionsResponse> ListFunctionsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the ListFunctions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListFunctions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListFunctionsResponse> ListFunctionsAsync(ListFunctionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RemovePermission /// <summary> /// Initiates the asynchronous execution of the RemovePermission operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RemovePermission operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RemovePermissionResponse> RemovePermissionAsync(RemovePermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateEventSourceMapping /// <summary> /// Initiates the asynchronous execution of the UpdateEventSourceMapping operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateEventSourceMapping operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<UpdateEventSourceMappingResponse> UpdateEventSourceMappingAsync(UpdateEventSourceMappingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateFunctionCode /// <summary> /// Initiates the asynchronous execution of the UpdateFunctionCode operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateFunctionCode operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<UpdateFunctionCodeResponse> UpdateFunctionCodeAsync(UpdateFunctionCodeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateFunctionConfiguration /// <summary> /// Initiates the asynchronous execution of the UpdateFunctionConfiguration operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateFunctionConfiguration operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<UpdateFunctionConfigurationResponse> UpdateFunctionConfigurationAsync(UpdateFunctionConfigurationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
// KDTree.cs - A Stark, September 2009. // This class implements a data structure that stores a list of points in space. // A common task in game programming is to take a supplied point and discover which // of a stored set of points is nearest to it. For example, in path-plotting, it is often // useful to know which waypoint is nearest to the player's current // position. The kd-tree allows this "nearest neighbour" search to be carried out quickly, // or at least much more quickly than a simple linear search through the list. // At present, the class only allows for construction (using the MakeFromPoints static method) // and nearest-neighbour searching (using FindNearest). More exotic kd-trees are possible, and // this class may be extended in the future if there seems to be a need. // The nearest-neighbour search returns an integer index - it is assumed that the original // array of points is available for the lifetime of the tree, and the index refers to that // array. using UnityEngine; using System.Collections; public class KDTree { public KDTree[] lr; public Vector3 pivot; public int pivotIndex; public int axis; // Change this value to 2 if you only need two-dimensional X,Y points. The search will // be quicker in two dimensions. const int numDims = 3; public KDTree() { lr = new KDTree[2]; } // Make a new tree from a list of points. public static KDTree MakeFromPoints(params Vector3[] points) { int[] indices = Iota(points.Length); return MakeFromPointsInner(0, 0, points.Length - 1, points, indices); } // Recursively build a tree by separating points at plane boundaries. static KDTree MakeFromPointsInner( int depth, int stIndex, int enIndex, Vector3[] points, int[] inds ) { KDTree root = new KDTree(); root.axis = depth % numDims; int splitPoint = FindPivotIndex(points, inds, stIndex, enIndex, root.axis); root.pivotIndex = inds[splitPoint]; root.pivot = points[root.pivotIndex]; int leftEndIndex = splitPoint - 1; if (leftEndIndex >= stIndex) { root.lr[0] = MakeFromPointsInner(depth + 1, stIndex, leftEndIndex, points, inds); } int rightStartIndex = splitPoint + 1; if (rightStartIndex <= enIndex) { root.lr[1] = MakeFromPointsInner(depth + 1, rightStartIndex, enIndex, points, inds); } return root; } static void SwapElements(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } // Simple "median of three" heuristic to find a reasonable splitting plane. static int FindSplitPoint(Vector3[] points, int[] inds, int stIndex, int enIndex, int axis) { float a = points[inds[stIndex]][axis]; float b = points[inds[enIndex]][axis]; int midIndex = (stIndex + enIndex) / 2; float m = points[inds[midIndex]][axis]; if (a > b) { if (m > a) { return stIndex; } if (b > m) { return enIndex; } return midIndex; } else { if (a > m) { return stIndex; } if (m > b) { return enIndex; } return midIndex; } } // Find a new pivot index from the range by splitting the points that fall either side // of its plane. public static int FindPivotIndex(Vector3[] points, int[] inds, int stIndex, int enIndex, int axis) { int splitPoint = FindSplitPoint(points, inds, stIndex, enIndex, axis); // int splitPoint = Random.Range(stIndex, enIndex); Vector3 pivot = points[inds[splitPoint]]; SwapElements(inds, stIndex, splitPoint); int currPt = stIndex + 1; int endPt = enIndex; while (currPt <= endPt) { Vector3 curr = points[inds[currPt]]; if ((curr[axis] > pivot[axis])) { SwapElements(inds, currPt, endPt); endPt--; } else { SwapElements(inds, currPt - 1, currPt); currPt++; } } return currPt - 1; } public static int[] Iota(int num) { int[] result = new int[num]; for (int i = 0; i < num; i++) { result[i] = i; } return result; } // Find the nearest point in the set to the supplied point. public int FindNearest(Vector3 pt) { float bestSqDist = 1000000000f; int bestIndex = -1; Search(pt, ref bestSqDist, ref bestIndex); return bestIndex; } // Recursively search the tree. void Search(Vector3 pt, ref float bestSqSoFar, ref int bestIndex) { float mySqDist = (pivot - pt).sqrMagnitude; if (mySqDist < bestSqSoFar) { bestSqSoFar = mySqDist; bestIndex = pivotIndex; } float planeDist = pt[axis] - pivot[axis]; //DistFromSplitPlane(pt, pivot, axis); int selector = planeDist <= 0 ? 0 : 1; if (lr[selector] != null) { lr[selector].Search(pt, ref bestSqSoFar, ref bestIndex); } selector = (selector + 1) % 2; float sqPlaneDist = planeDist * planeDist; if ((lr[selector] != null) && (bestSqSoFar > sqPlaneDist)) { lr[selector].Search(pt, ref bestSqSoFar, ref bestIndex); } } // Get a point's distance from an axis-aligned plane. float DistFromSplitPlane(Vector3 pt, Vector3 planePt, int axis) { return pt[axis] - planePt[axis]; } // Simple output of tree structure - mainly useful for getting a rough // idea of how deep the tree is (and therefore how well the splitting // heuristic is performing). public string Dump(int level) { string result = pivotIndex.ToString().PadLeft(level) + "\n"; if (lr[0] != null) { result += lr[0].Dump(level + 2); } if (lr[1] != null) { result += lr[1].Dump(level + 2); } return result; } }
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace SharpGoogleCharts { public class GoogleChart { public ChartOptions ChartDefinition { get; set; } public Dictionary<string, List<PlotPoint>> CurveData { get; set; } public GoogleChart() { CurveData = new Dictionary<string, List<PlotPoint>>(); } private string ConvertDateTimeToJs(DateTime dt) { return $"Date({dt.Year},{dt.Month - 1},{dt.Day},{dt.Hour},{dt.Minute},0,0)"; } public Dictionary<string, object> GetGoogleDataTable() { Dictionary<string, object> resultDict = new Dictionary<string, object>(); //Create data rows List<List<object>> curvesArray = new List<List<object>>(); foreach (List<PlotPoint> curvePoints in CurveData.Values) { foreach (PlotPoint pp in curvePoints) { string xvalue; if (pp.X is DateTime) xvalue = ConvertDateTimeToJs((DateTime)pp.X); else xvalue = pp.X.ToString(); if (!curvesArray.Exists(x => x[0].ToString() == xvalue)) { //X-Value don't exists yet so create it curvesArray.Add(new List<object> { xvalue }); } curvesArray.First(x => x[0].ToString() == xvalue).Add(pp); } } List<Dictionary<string, object>> dataRows = new List<Dictionary<string, object>>(); int nbrDataCurves = 0; if (curvesArray.Count > 0) nbrDataCurves = curvesArray.Max(x => x.Count) - 1; //create rows foreach (List<object> row in curvesArray) { var rowValues = new List<Dictionary<string, object>>(); foreach (object cellValue in row) { PlotPoint cellPoint = cellValue as PlotPoint; if (cellPoint != null) { rowValues.Add(new Dictionary<string, object> { {"v", cellPoint.Y}, {"f", cellPoint.PrettyY} }); } else { string prettyValue = cellValue.ToString(); rowValues.Add(new Dictionary<string, object> { {"v", cellValue}, {"f", prettyValue} }); } } dataRows.Add(new Dictionary<string, object> { { "c", rowValues } }); } resultDict["rows"] = dataRows; //create columns List<Dictionary<string, string>> cols = new List<Dictionary<string, string>> { new Dictionary<string, string> { {"id", "xaxis"}, {"label", ChartDefinition.XAxis.Label}, {"pattern", ChartDefinition.XAxis.Dataformat}, {"type", ChartDefinition.XAxis.Datatype.ToGoogleCharts()} } }; int i = 0; foreach (var c in CurveData) { //Dont add more columns than we have data if (i >= nbrDataCurves) break; var col = new Dictionary<string, string> { {"id", "yaxis_" + i++}, {"label", c.Key}, {"pattern", ""}, {"type", "number"} }; cols.Add(col); } resultDict["cols"] = cols; return resultDict; } public Dictionary<string, object> GetGoogleOptions() { Dictionary<string, object> optionsDict = new Dictionary<string, object> { ["hAxis"] = new Dictionary<string, object> { {"title", ChartDefinition.XAxis.Label} }, ["vAxis"] = new Dictionary<string, object> { {"title", ChartDefinition.YAxis.Label} } }; if (!ChartDefinition.Showgrid) { ((Dictionary<string, object>)optionsDict["hAxis"])["gridlines"] = new Dictionary<string, object> { {"color", "transparent"} }; ((Dictionary<string, object>)optionsDict["vAxis"])["gridlines"] = new Dictionary<string, object> { {"color", "transparent"} }; } //Legend handling if (ChartDefinition.Showlegend) { if (ChartDefinition.ChartType == PlotChartType.Donut || ChartDefinition.ChartType == PlotChartType.Pie) { optionsDict["legend"] = new Dictionary<string, object> { {"position", "right"} }; optionsDict["chartArea"] = new Dictionary<string, object> { {"height", "100%"} }; } else { optionsDict["legend"] = new Dictionary<string, object> { {"position", "top"}, {"maxLines", 3} }; } } else //hide legend { optionsDict["legend"] = new Dictionary<string, object> { {"position", "none"} }; } switch (ChartDefinition.ChartType) { case PlotChartType.BarStacked: optionsDict["isStacked"] = "true"; optionsDict["bar"] = new Dictionary<string, string> { {"groupWidth", "75%"} }; break; case PlotChartType.Donut: optionsDict["pieHole"] = 0.4; break; case PlotChartType.Table: optionsDict["width"] = "100%"; optionsDict["sortAscending"] = false; optionsDict["sortColumn"] = 1; break; case PlotChartType.GeoMap: string color = ChartDefinition.Curves[0].Color; if (!string.IsNullOrWhiteSpace(color) && color != "auto") { optionsDict["colorAxis"] = new Dictionary<string, object> { {"colors", new List<string> { "#eeeeee", ChartDefinition.Curves[0].Color}} }; } break; } if (ChartDefinition.ChartType == PlotChartType.Pie || ChartDefinition.ChartType == PlotChartType.Donut) { var sliceOptions = new Dictionary<string, object>(); for (int i = 0; i < ChartDefinition.Curves.Count; i++) { var curve = ChartDefinition.Curves[i]; if (curve.Color == "auto" || string.IsNullOrWhiteSpace(curve.Color)) continue; sliceOptions.Add(i.ToString(), new Dictionary<string, object> { { "color", curve.Color } }); } optionsDict["slices"] = sliceOptions; } Dictionary<int, object> series = new Dictionary<int, object>(); //create curve options for (int i = 0; i < ChartDefinition.Curves.Count; i++) { var curve = ChartDefinition.Curves[i]; Dictionary<string, object> curveOptions = new Dictionary<string, object>(); switch (curve.Linemarker) { case PlotLineMarker.Diamond: curveOptions.Add("pointShape", "diamond"); curveOptions.Add("pointSize", 10); break; case PlotLineMarker.Dot: curveOptions.Add("pointShape", "circle"); curveOptions.Add("pointSize", 10); break; case PlotLineMarker.Square: curveOptions.Add("pointShape", "square"); curveOptions.Add("pointSize", 10); break; case PlotLineMarker.Triangle: curveOptions.Add("pointShape", "triangle"); curveOptions.Add("pointSize", 10); break; } if (!string.IsNullOrWhiteSpace(curve.Color) && curve.Color != "auto") { curveOptions.Add("color", curve.Color); } series.Add(i, curveOptions); } optionsDict["series"] = series; return optionsDict; } public string GetGoogleFunctionName() { switch (ChartDefinition.ChartType) { case PlotChartType.Bar: return "ColumnChart"; case PlotChartType.GeoMap: return "GeoChart"; case PlotChartType.BarStacked: return "ColumnChart"; case PlotChartType.Donut: return "PieChart"; case PlotChartType.Line: return "LineChart"; case PlotChartType.Pie: return "PieChart"; case PlotChartType.Table: return "Table"; } return ""; } public List<GoogleChartFormatter> GetGoogleFormatters() { List<GoogleChartFormatter> formatters = new List<GoogleChartFormatter>(); switch (ChartDefinition.Resolution) { case PlotResolution.Day: case PlotResolution.Week: case PlotResolution.Month: GoogleChartFormatter ccfa = new GoogleChartFormatter { Name = "DateFormat", ColumnIdx = 0 }; ccfa.Options.Add("pattern", "MMM dd, yyyy"); formatters.Add(ccfa); break; case PlotResolution.Hour: GoogleChartFormatter ccfb = new GoogleChartFormatter { Name = "DateFormat", ColumnIdx = 0 }; ccfb.Options.Add("pattern", "MMM dd, HH:mm"); formatters.Add(ccfb); break; } if (ChartDefinition.ChartType == PlotChartType.Table) { int i = 0; foreach (var curve in ChartDefinition.Curves) { i++; if (!curve.DrawTablebars) continue; GoogleChartFormatter ccf = new GoogleChartFormatter { Name = "BarFormat", ColumnIdx = i }; ccf.Options.Add("width", 120); ccf.Options.Add("min", 0); if (!string.IsNullOrWhiteSpace(curve.Color)) ccf.Options.Add("colorPositive", curve.Color); formatters.Add(ccf); } } return formatters; } public ChartWrapper GetGoogleChartWrapper(string containerElementId) { ChartWrapper cw = new ChartWrapper(); cw.ChartType = GetGoogleFunctionName(); cw.Options = GetGoogleOptions(); cw.DataTable = GetGoogleDataTable(); cw.ContainerId = containerElementId; return cw; } public string GetGoogleFormattersJson() { return JsonConvert.SerializeObject(GetGoogleFormatters()); } public string GetGoogleOptionsJson() { return JsonConvert.SerializeObject(GetGoogleOptions()); } public string GetGoogleDataTableJson() { return JsonConvert.SerializeObject(GetGoogleDataTable()); } public string GetGoogleChartWrapperJson(string containerElementId) { return JsonConvert.SerializeObject(GetGoogleChartWrapper(containerElementId)); } } public class ChartWrapper { [JsonProperty("chartType")] public string ChartType { get; set; } [JsonProperty("options")] public Dictionary<string, object> Options { get; set; } [JsonProperty("dataTable")] public Dictionary<string, object> DataTable { get; set; } [JsonProperty("containerId")] public string ContainerId { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; namespace System.Globalization { /*=================================ThaiBuddhistCalendar========================== ** ** ThaiBuddhistCalendar is based on Gregorian calendar. Its year value has ** an offset to the Gregorain calendar. ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 0001/01/01 9999/12/31 ** Thai 0544/01/01 10542/12/31 ============================================================================*/ public class ThaiBuddhistCalendar : Calendar { // Initialize our era info. internal static EraInfo[] thaiBuddhistEraInfo = new EraInfo[] { new EraInfo( 1, 1, 1, 1, -543, 544, GregorianCalendar.MaxYear + 543) // era #, start year/month/day, yearOffset, minEraYear }; // // The era value for the current era. // public const int ThaiBuddhistEra = 1; internal GregorianCalendarHelper helper; public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } public ThaiBuddhistCalendar() { helper = new GregorianCalendarHelper(this, thaiBuddhistEraInfo); } internal override CalendarId ID { get { return (CalendarId.THAI); } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } public override int[] Eras { get { return (helper.Eras); } } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2572; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, helper.MaxYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } return (helper.ToFourDigitYear(year, this.TwoDigitYearMax)); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System.Linq; using Microsoft.PythonTools.Analysis.Analyzer; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing.Ast; namespace Microsoft.PythonTools.Analysis.Values { /// <summary> /// Base class for iterables. Not tied to whether the iterable is fixed to /// certain known types (e.g. an iterable for a string) or a user defined /// iterable. /// /// Implementors just need to provide the UnionType and the ability to make /// an iterator for the iterable. /// </summary> internal abstract class BaseIterableValue : BuiltinInstanceInfo { protected IAnalysisSet _unionType; // all types that have been seen private AnalysisValue _iterMethod; public BaseIterableValue(BuiltinClassInfo seqType) : base(seqType) { } public IAnalysisSet UnionType { get { EnsureUnionType(); return _unionType; } set { _unionType = value; } } protected abstract void EnsureUnionType(); protected abstract IAnalysisSet MakeIteratorInfo(Node n, AnalysisUnit unit); public override IAnalysisSet GetEnumeratorTypes(Node node, AnalysisUnit unit) { EnsureUnionType(); return _unionType; } public override IAnalysisSet GetTypeMember(Node node, AnalysisUnit unit, string name) { var res = base.GetTypeMember(node, unit, name); if (name == "__iter__") { return _iterMethod = _iterMethod ?? new SpecializedCallable( res.OfType<BuiltinNamespace<IPythonType>>().FirstOrDefault(), IterableIter, false ); } return res; } private IAnalysisSet IterableIter(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { if (args.Length == 0) { return unit.Scope.GetOrMakeNodeValue( node, NodeValueKind.Iterator, n => MakeIteratorInfo(n, unit) ); } return AnalysisSet.Empty; } public override string Description { get { return MakeDescription("iterable"); } } protected string MakeDescription(string typeName) { EnsureUnionType(); return MakeDescription(this, typeName, UnionType); } internal static string MakeDescription(AnalysisValue type, string typeName, IAnalysisSet indexTypes) { if (type.Push()) { try { if (indexTypes == null || indexTypes.Count == 0) { return typeName; } else if (indexTypes.Count == 1) { return typeName + " of " + indexTypes.First().ShortDescription; } else if (indexTypes.Count < 4) { return typeName + " of {" + string.Join(", ", indexTypes.Select(ns => ns.ShortDescription)) + "}"; } else { return typeName + " of multiple types"; } } finally { type.Pop(); } } return typeName; } public override string ShortDescription { get { return _type.Name; } } } /// <summary> /// Specialized built-in instance for sequences (lists, tuples) which are iterable. /// /// Used for user defined sequence types where we'll track the individual values /// inside of the iterable. /// </summary> internal class IterableValue : BaseIterableValue { private VariableDef[] _indexTypes; // types for known indices internal readonly Node _node; public IterableValue(VariableDef[] indexTypes, BuiltinClassInfo seqType, Node node) : base(seqType) { _indexTypes = indexTypes; _node = node; } public VariableDef[] IndexTypes { get { return _indexTypes; } set { _indexTypes = value; } } public override IAnalysisSet GetEnumeratorTypes(Node node, AnalysisUnit unit) { if (_indexTypes.Length == 0) { _indexTypes = new[] { new VariableDef() }; _indexTypes[0].AddDependency(unit); return AnalysisSet.Empty; } else { _indexTypes[0].AddDependency(unit); } return base.GetEnumeratorTypes(node, unit); } internal bool AddTypes(AnalysisUnit unit, IAnalysisSet[] types) { if (_indexTypes.Length < types.Length) { _indexTypes = _indexTypes.Concat(VariableDef.Generator).Take(types.Length).ToArray(); } bool added = false; for (int i = 0; i < types.Length; i++) { added |= _indexTypes[i].MakeUnionStrongerIfMoreThan(ProjectState.Limits.IndexTypes, types[i]); added |= _indexTypes[i].AddTypes(unit, types[i], true, DeclaringModule); } if (added) { _unionType = null; } return added; } protected override IAnalysisSet MakeIteratorInfo(Node n, AnalysisUnit unit) { return new IteratorValue( this, BaseIteratorValue.GetIteratorTypeFromType(ClassInfo, unit) ); } protected override void EnsureUnionType() { if (_unionType == null) { IAnalysisSet unionType = AnalysisSet.EmptyUnion; if (Push()) { try { foreach (var set in _indexTypes) { unionType = unionType.Union(set.TypesNoCopy); } } finally { Pop(); } } _unionType = unionType; } } internal override bool UnionEquals(AnalysisValue ns, int strength) { if (strength < MergeStrength.IgnoreIterableNode) { var si = ns as IterableValue; if (si != null && !_node.Equals(_node)) { // If nodes are not equal, iterables cannot be merged. return false; } } return base.UnionEquals(ns, strength); } } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations { /// <summary> /// Enumeration values for PduType (pduheader.pdutype, PDU Type, /// section 3.2) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public enum PduType : byte { /// <summary> /// Other. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Other.")] Other = 0, /// <summary> /// Entity State. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Entity State.")] EntityState = 1, /// <summary> /// Fire. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Fire.")] Fire = 2, /// <summary> /// Detonation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Detonation.")] Detonation = 3, /// <summary> /// Collision. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Collision.")] Collision = 4, /// <summary> /// Service Request. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Service Request.")] ServiceRequest = 5, /// <summary> /// Resupply Offer. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Resupply Offer.")] ResupplyOffer = 6, /// <summary> /// Resupply Received. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Resupply Received.")] ResupplyReceived = 7, /// <summary> /// Resupply Cancel. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Resupply Cancel.")] ResupplyCancel = 8, /// <summary> /// Repair Complete. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Repair Complete.")] RepairComplete = 9, /// <summary> /// Repair Response. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Repair Response.")] RepairResponse = 10, /// <summary> /// Create Entity. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Create Entity.")] CreateEntity = 11, /// <summary> /// Remove Entity. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Remove Entity.")] RemoveEntity = 12, /// <summary> /// Start/Resume. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Start/Resume.")] StartResume = 13, /// <summary> /// Stop/Freeze. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Stop/Freeze.")] StopFreeze = 14, /// <summary> /// Acknowledge. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Acknowledge.")] Acknowledge = 15, /// <summary> /// Action Request. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Action Request.")] ActionRequest = 16, /// <summary> /// Action Response. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Action Response.")] ActionResponse = 17, /// <summary> /// Data Query. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Data Query.")] DataQuery = 18, /// <summary> /// Set Data. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Set Data.")] SetData = 19, /// <summary> /// Data. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Data.")] Data = 20, /// <summary> /// Event Report. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Event Report.")] EventReport = 21, /// <summary> /// Comment. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Comment.")] Comment = 22, /// <summary> /// Electromagnetic Emission. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Electromagnetic Emission.")] ElectromagneticEmission = 23, /// <summary> /// Designator. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Designator.")] Designator = 24, /// <summary> /// Transmitter. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Transmitter.")] Transmitter = 25, /// <summary> /// Signal. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Signal.")] Signal = 26, /// <summary> /// Receiver. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Receiver.")] Receiver = 27, /// <summary> /// IFF/ATC/NAVAIDS. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("IFF/ATC/NAVAIDS.")] IFF_ATC_NAVAIDS = 28, /// <summary> /// Underwater Acoustic. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Underwater Acoustic.")] UnderwaterAcoustic = 29, /// <summary> /// Supplemental Emission / Entity State. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Supplemental Emission / Entity State.")] SupplementalEmissionEntityState = 30, /// <summary> /// Intercom Signal. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Intercom Signal.")] IntercomSignal = 31, /// <summary> /// Intercom Control. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Intercom Control.")] IntercomControl = 32, /// <summary> /// Aggregate State. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Aggregate State.")] AggregateState = 33, /// <summary> /// IsGroupOf. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("IsGroupOf.")] IsGroupOf = 34, /// <summary> /// Transfer Control. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Transfer Control.")] TransferControl = 35, /// <summary> /// IsPartOf. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("IsPartOf.")] IsPartOf = 36, /// <summary> /// Minefield State. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Minefield State.")] MinefieldState = 37, /// <summary> /// Minefield Query. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Minefield Query.")] MinefieldQuery = 38, /// <summary> /// Minefield Data. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Minefield Data.")] MinefieldData = 39, /// <summary> /// Minefield Response NAK. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Minefield Response NAK.")] MinefieldResponseNAK = 40, /// <summary> /// Environmental Process. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Environmental Process.")] EnvironmentalProcess = 41, /// <summary> /// Gridded Data. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Gridded Data.")] GriddedData = 42, /// <summary> /// Point Object State. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Point Object State.")] PointObjectState = 43, /// <summary> /// Linear Object State. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Linear Object State.")] LinearObjectState = 44, /// <summary> /// Areal Object State. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Areal Object State.")] ArealObjectState = 45, /// <summary> /// TSPI. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("TSPI.")] TSPI = 46, /// <summary> /// Appearance. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Appearance.")] Appearance = 47, /// <summary> /// Articulated Parts. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Articulated Parts.")] ArticulatedParts = 48, /// <summary> /// LE Fire. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("LE Fire.")] LEFire = 49, /// <summary> /// LE Detonation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("LE Detonation.")] LEDetonation = 50, /// <summary> /// Create Entity-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Create Entity-R.")] CreateEntityR = 51, /// <summary> /// Remove Entity-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Remove Entity-R.")] RemoveEntityR = 52, /// <summary> /// Start/Resume-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Start/Resume-R.")] StartResumeR = 53, /// <summary> /// Stop/Freeze-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Stop/Freeze-R.")] StopFreezeR = 54, /// <summary> /// Acknowledge-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Acknowledge-R.")] AcknowledgeR = 55, /// <summary> /// Action Request-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Action Request-R.")] ActionRequestR = 56, /// <summary> /// Action Response-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Action Response-R.")] ActionResponseR = 57, /// <summary> /// Data Query-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Data Query-R.")] DataQueryR = 58, /// <summary> /// Set Data-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Set Data-R.")] SetDataR = 59, /// <summary> /// Data-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Data-R.")] DataR = 60, /// <summary> /// Event Report-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Event Report-R.")] EventReportR = 61, /// <summary> /// Comment-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Comment-R.")] CommentR = 62, /// <summary> /// Record-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Record-R.")] RecordR = 63, /// <summary> /// Set Record-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Set Record-R.")] SetRecordR = 64, /// <summary> /// Record Query-R. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Record Query-R.")] RecordQueryR = 65, /// <summary> /// Collision-Elastic. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Collision-Elastic.")] CollisionElastic = 66, /// <summary> /// Entity State Update. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Entity State Update.")] EntityStateUpdate = 67 } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Referensi_JenisPemeriksaan_List : System.Web.UI.Page { public int NoKe = 0; protected string dsReportSessionName = "dsListRefJenisPemeriksaan"; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["JenisPemeriksaanManagement"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } else { btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddJenisPemeriksaan"); } btnSearch.Text = Resources.GetString("", "Search"); ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif"; ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif"; ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif"; ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif"; UpdateDataView(true); } } #region .Update View Data ////////////////////////////////////////////////////////////////////// // PhysicalDataRead // ------------------------------------------------------------------ /// <summary> /// This function is responsible for loading data from database. /// </summary> /// <returns>DataSet</returns> public DataSet PhysicalDataRead() { // Local variables DataSet oDS = new DataSet(); // Get Data SIMRS.DataAccess.RS_JenisPemeriksaan myObj = new SIMRS.DataAccess.RS_JenisPemeriksaan(); DataTable myData = myObj.SelectAll(); oDS.Tables.Add(myData); return oDS; } /// <summary> /// This function is responsible for binding data to Datagrid. /// </summary> /// <param name="dv"></param> private void BindData(DataView dv) { // Sets the sorting order dv.Sort = DataGridList.Attributes["SortField"]; if (DataGridList.Attributes["SortAscending"] == "no") dv.Sort += " DESC"; if (dv.Count > 0) { DataGridList.ShowFooter = false; int intRowCount = dv.Count; int intPageSaze = DataGridList.PageSize; int intPageCount = intRowCount / intPageSaze; if (intRowCount - (intPageCount * intPageSaze) > 0) intPageCount = intPageCount + 1; if (DataGridList.CurrentPageIndex >= intPageCount) DataGridList.CurrentPageIndex = intPageCount - 1; } else { DataGridList.ShowFooter = true; DataGridList.CurrentPageIndex = 0; } // Re-binds the grid NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex; DataGridList.DataSource = dv; DataGridList.DataBind(); int CurrentPage = DataGridList.CurrentPageIndex + 1; lblCurrentPage.Text = CurrentPage.ToString(); lblTotalPage.Text = DataGridList.PageCount.ToString(); lblTotalRecord.Text = dv.Count.ToString(); } /// <summary> /// This function is responsible for loading data from database and store to Session. /// </summary> /// <param name="strDataSessionName"></param> public void DataFromSourceToMemory(String strDataSessionName) { // Gets rows from the data source DataSet oDS = PhysicalDataRead(); // Stores it in the session cache Session[strDataSessionName] = oDS; } /// <summary> /// This function is responsible for update data view from datagrid. /// </summary> /// <param name="requery">true = get data from database, false= get data from session</param> public void UpdateDataView(bool requery) { // Retrieves the data if ((Session[dsReportSessionName] == null) || (requery)) { if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString()); DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } public void UpdateDataView() { // Retrieves the data if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } #endregion #region .Event DataGridList ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // HANDLERs // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageChanged(Object sender, DataGridPageChangedEventArgs e) { DataGridList.CurrentPageIndex = e.NewPageIndex; DataGridList.SelectedIndex = -1; UpdateDataView(); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="nPageIndex"></param> public void GoToPage(Object sender, int nPageIndex) { DataGridPageChangedEventArgs evPage; evPage = new DataGridPageChangedEventArgs(sender, nPageIndex); PageChanged(sender, evPage); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a first page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToFirst(Object sender, ImageClickEventArgs e) { GoToPage(sender, 0); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a previous page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToPrev(Object sender, ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex > 0) { GoToPage(sender, DataGridList.CurrentPageIndex - 1); } else { GoToPage(sender, 0); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a next page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1)) { GoToPage(sender, DataGridList.CurrentPageIndex + 1); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a last page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToLast(Object sender, ImageClickEventArgs e) { GoToPage(sender, DataGridList.PageCount - 1); } /// <summary> /// This function is invoked when you click on a column's header to /// sort by that. It just saves the current sort field name and /// refreshes the grid. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void SortByColumn(Object sender, DataGridSortCommandEventArgs e) { String strSortBy = DataGridList.Attributes["SortField"]; String strSortAscending = DataGridList.Attributes["SortAscending"]; // Sets the new sorting field DataGridList.Attributes["SortField"] = e.SortExpression; // Sets the order (defaults to ascending). If you click on the // sorted column, the order reverts. DataGridList.Attributes["SortAscending"] = "yes"; if (e.SortExpression == strSortBy) DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes"); // Refreshes the view OnClearSelection(null, null); UpdateDataView(); } /// <summary> /// The function gets invoked when a new item is being created in /// the datagrid. This applies to pager, header, footer, regular /// and alternating items. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageItemCreated(Object sender, DataGridItemEventArgs e) { // Get the newly created item ListItemType itemType = e.Item.ItemType; ////////////////////////////////////////////////////////// // Is it the HEADER? if (itemType == ListItemType.Header) { for (int i = 0; i < DataGridList.Columns.Count; i++) { // draw to reflect sorting if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression) { ////////////////////////////////////////////// // Should be much easier this way: // ------------------------------------------ // TableCell cell = e.Item.Cells[i]; // Label lblSorted = new Label(); // lblSorted.Font = "webdings"; // lblSorted.Text = strOrder; // cell.Controls.Add(lblSorted); // // but it seems it doesn't work <g> ////////////////////////////////////////////// // Add a non-clickable triangle to mean desc or asc. // The </a> ensures that what follows is non-clickable TableCell cell = e.Item.Cells[i]; LinkButton lb = (LinkButton)cell.Controls[0]; //lb.Text += "</a>&nbsp;<span style=font-family:webdings;>" + GetOrderSymbol() + "</span>"; lb.Text += "</a>&nbsp;<img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >"; } } } ////////////////////////////////////////////////////////// // Is it the PAGER? if (itemType == ListItemType.Pager) { // There's just one control in the list... TableCell pager = (TableCell)e.Item.Controls[0]; // Enumerates all the items in the pager... for (int i = 0; i < pager.Controls.Count; i += 2) { // It can be either a Label or a Link button try { Label l = (Label)pager.Controls[i]; l.Text = "Hal " + l.Text; l.CssClass = "CurrentPage"; } catch { LinkButton h = (LinkButton)pager.Controls[i]; h.Text = "[ " + h.Text + " ]"; h.CssClass = "HotLink"; } } } } /// <summary> /// Verifies whether the current sort is ascending or descending and /// returns an appropriate display text (i.e., a webding) /// </summary> /// <returns></returns> private String GetOrderSymbol() { bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no"); //return (bDescending ? " 6" : " 5"); return (bDescending ? "downbr.gif" : "upbr.gif"); } /// <summary> /// When clicked clears the current selection if any /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnClearSelection(Object sender, EventArgs e) { DataGridList.SelectedIndex = -1; } #endregion #region .Event Button /// <summary> /// When clicked, redirect to form add for inserts a new record to the database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnNewRecord(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); Response.Redirect("Add.aspx?CurrentPage=" + CurrentPage); } /// <summary> /// When clicked, filter data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnSearch(Object sender, System.EventArgs e) { if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; DataView dv = ds.Tables[0].DefaultView; if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Nama") dv.RowFilter = " Nama LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Keterangan") dv.RowFilter = " Keterangan LIKE '%" + txtSearch.Text + "%'"; else dv.RowFilter = ""; BindData(dv); } #endregion #region .Update Link Item Butom /// <summary> /// The function is responsible for get link button form. /// </summary> /// <param name="szId"></param> /// <param name="CurrentPage"></param> /// <returns></returns> public string GetLinkButton(string Id, string Nama, string CurrentPage) { string szResult = ""; if (Session["JenisPemeriksaanManagement"] != null) { szResult += "<a class=\"toolbar\" href=\"Edit.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" "; szResult += ">" + Resources.GetString("", "Edit") + "</a>"; if (Id != "16" && Id != "26" && Id != "34" && Id != "41" && Id != "42") { szResult += "<a class=\"toolbar\" href=\"Delete.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" "; szResult += ">" + Resources.GetString("", "Delete") + "</a>"; } } return szResult; } #endregion }
//------------------------------------------------------------------------------ // <copyright file="HtmlControlAdapter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Collections; using System.Diagnostics; using System.Web.UI.MobileControls; using System.Web.UI.MobileControls.Adapters; using System.Security.Permissions; #if COMPILING_FOR_SHIPPED_SOURCE namespace System.Web.UI.MobileControls.ShippedAdapterSource #else namespace System.Web.UI.MobileControls.Adapters #endif { /* * HtmlControlAdapter base class contains html specific methods. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class HtmlControlAdapter : System.Web.UI.MobileControls.Adapters.ControlAdapter { /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.PageAdapter"]/*' /> protected HtmlPageAdapter PageAdapter { get { return ((HtmlPageAdapter)Page.Adapter); } } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.FormAdapter"]/*' /> protected HtmlFormAdapter FormAdapter { get { return (HtmlFormAdapter)Control.Form.Adapter; } } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.RequiresFormTag"]/*' /> public virtual bool RequiresFormTag { get { return false; } } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.Render"]/*' /> public override void Render(HtmlTextWriter writer) { HtmlMobileTextWriter htmlWriter = (HtmlMobileTextWriter)writer; Render(htmlWriter); } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.Render1"]/*' /> public virtual void Render(HtmlMobileTextWriter writer) { RenderChildren(writer); } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.RenderPostBackEventReference"]/*' /> protected void RenderPostBackEventReference(HtmlMobileTextWriter writer, String argument) { PageAdapter.RenderPostBackEvent(writer, Control.UniqueID, argument); } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.RenderPostBackEventAsAttribute"]/*' /> protected void RenderPostBackEventAsAttribute( HtmlMobileTextWriter writer, String attributeName, String argument) { writer.Write(" "); writer.Write(attributeName); writer.Write("=\""); RenderPostBackEventReference(writer, argument); writer.Write("\" "); } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.RenderPostBackEventAsAnchor"]/*' /> protected void RenderPostBackEventAsAnchor( HtmlMobileTextWriter writer, String argument, String linkText) { writer.EnterStyle(Style); writer.WriteBeginTag("a"); RenderPostBackEventAsAttribute(writer, "href", argument); writer.Write(">"); writer.WriteText(linkText, true); writer.WriteEndTag("a"); writer.ExitStyle(Style); } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.RenderBeginLink"]/*' /> protected void RenderBeginLink(HtmlMobileTextWriter writer, String target) { bool queryStringWritten = false; bool appendCookieless = (PageAdapter.PersistCookielessData) && (!( (target.StartsWith("http:", StringComparison.Ordinal)) || (target.StartsWith("https:", StringComparison.Ordinal)) )); writer.WriteBeginTag("a"); writer.Write(" href=\""); String targetUrl = null; String prefix = Constants.FormIDPrefix; if (target.StartsWith(prefix, StringComparison.Ordinal)) { String name = target.Substring(prefix.Length); Form form = Control.ResolveFormReference(name); if (writer.SupportsMultiPart) { if (form != null && PageAdapter.IsFormRendered(form)) { targetUrl = PageAdapter.GetFormUrl(form); } } if (targetUrl == null) { RenderPostBackEventReference(writer, form.UniqueID); appendCookieless = false; } else { writer.Write(targetUrl); queryStringWritten = targetUrl.IndexOf('?') != -1; } } else { MobileControl control = Control; // There is some adapter that Control is not set. And we // don't do any url resolution then. E.g. a page adapter if (control != null) { // AUI 3652 target = control.ResolveUrl(target); } writer.Write(target); queryStringWritten = target.IndexOf('?') != -1; } IDictionary dictionary = PageAdapter.CookielessDataDictionary; if((dictionary != null) && (appendCookieless)) { foreach(String name in dictionary.Keys) { if(queryStringWritten) { writer.Write('&'); } else { writer.Write('?'); queryStringWritten = true; } writer.Write(name); writer.Write('='); writer.Write(dictionary[name]); } } writer.Write("\""); AddAttributes(writer); writer.Write(">"); } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.RenderEndLink"]/*' /> protected void RenderEndLink(HtmlMobileTextWriter writer) { writer.WriteEndTag("a"); } // Can be used by adapter that allow its subclass to add more // specific attributes /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.AddAttributes"]/*' /> protected virtual void AddAttributes(HtmlMobileTextWriter writer) { } // Can be used by adapter that adds the custom attribute "accesskey" /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.AddAccesskeyAttribute"]/*' /> protected virtual void AddAccesskeyAttribute(HtmlMobileTextWriter writer) { if (Device.SupportsAccesskeyAttribute) { AddCustomAttribute(writer, "accesskey"); } } // Can be used by adapter that adds custom attributes for // multi-media functionalities private readonly static String [] _multiMediaAttributes = { "src", "soundstart", "loop", "volume", "vibration", "viblength" }; /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.AddJPhoneMultiMediaAttributes"]/*' /> protected virtual void AddJPhoneMultiMediaAttributes( HtmlMobileTextWriter writer) { if (Device.SupportsJPhoneMultiMediaAttributes) { for (int i = 0; i < _multiMediaAttributes.Length; i++) { AddCustomAttribute(writer, _multiMediaAttributes[i]); } } } private void AddCustomAttribute(HtmlMobileTextWriter writer, String attributeName) { String attributeValue = ((IAttributeAccessor)Control).GetAttribute(attributeName); if (!String.IsNullOrEmpty(attributeValue)) { writer.WriteAttribute(attributeName, attributeValue); } } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.RenderAsHiddenInputField"]/*' /> protected virtual void RenderAsHiddenInputField(HtmlMobileTextWriter writer) { } // Renders hidden variables for IPostBackDataHandlers which are // not displayed due to pagination or secondary UI. internal void RenderOffPageVariables(HtmlMobileTextWriter writer, Control ctl, int page) { if (ctl.HasControls()) { foreach (Control child in ctl.Controls) { // Note: Control.Form != null. if (!child.Visible || child == Control.Form.Header || child == Control.Form.Footer) { continue; } MobileControl mobileCtl = child as MobileControl; if (mobileCtl != null) { if (mobileCtl.IsVisibleOnPage(page) && (mobileCtl == ((HtmlFormAdapter)mobileCtl.Form.Adapter).SecondaryUIControl || null == ((HtmlFormAdapter)mobileCtl.Form.Adapter).SecondaryUIControl)) { if (mobileCtl.FirstPage == mobileCtl.LastPage) { // Entire control is visible on this page, so no need to look // into children. continue; } // Control takes up more than one page, so it may be possible that // its children are on a different page, so we'll continue to // fall through into children. } else if (mobileCtl is IPostBackDataHandler) { HtmlControlAdapter adapter = mobileCtl.Adapter as HtmlControlAdapter; if (adapter != null) { adapter.RenderAsHiddenInputField(writer); } } } RenderOffPageVariables(writer, child, page); } } } ///////////////////////////////////////////////////////////////////// // SECONDARY UI SUPPORT ///////////////////////////////////////////////////////////////////// internal const int NotSecondaryUIInit = -1; // For initialization of private consts in derived classes. /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.NotSecondaryUI"]/*' /> protected static readonly int NotSecondaryUI = NotSecondaryUIInit; /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.SecondaryUIMode"]/*' /> protected int SecondaryUIMode { get { if (Control == null || Control.Form == null) { return NotSecondaryUI; } else { return ((HtmlFormAdapter)Control.Form.Adapter).GetSecondaryUIMode(Control); } } set { ((HtmlFormAdapter)Control.Form.Adapter).SetSecondaryUIMode(Control, value); } } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.ExitSecondaryUIMode"]/*' /> protected void ExitSecondaryUIMode() { SecondaryUIMode = NotSecondaryUI; } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.LoadAdapterState"]/*' /> public override void LoadAdapterState(Object state) { if (state != null) { SecondaryUIMode = (int)state; } } /// <include file='doc\HtmlControlAdapter.uex' path='docs/doc[@for="HtmlControlAdapter.SaveAdapterState"]/*' /> public override Object SaveAdapterState() { int mode = SecondaryUIMode; if (mode != NotSecondaryUI) { return mode; } else { return null; } } } }
// ZlibStream.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: <2011-July-31 14:53:33> // // ------------------------------------------------------------------ // // This module defines the ZlibStream class, which is similar in idea to // the System.IO.Compression.DeflateStream and // System.IO.Compression.GZipStream classes in the .NET BCL. // // ------------------------------------------------------------------ using System; using System.IO; namespace Cimbalino.Phone.Toolkit.Compression { /// <summary> /// Represents a Zlib stream for compression or decompression. /// </summary> /// <remarks> /// /// <para> /// The ZlibStream is a <see /// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see /// cref="System.IO.Stream"/>. It adds ZLIB compression or decompression to any /// stream. /// </para> /// /// <para> Using this stream, applications can compress or decompress data via /// stream <c>Read()</c> and <c>Write()</c> operations. Either compresssion or /// decompression can occur through either reading or writing. The compression /// format used is ZLIB, which is documented in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">IETF RFC 1950</see>, "ZLIB Compressed /// Data Format Specification version 3.3". This implementation of ZLIB always uses /// DEFLATE as the compression method. (see <see /// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE /// Compressed Data Format Specification version 1.3.") </para> /// /// <para> /// The ZLIB format allows for varying compression methods, window sizes, and dictionaries. /// This implementation always uses the DEFLATE compression method, a preset dictionary, /// and 15 window bits by default. /// </para> /// /// <para> /// This class is similar to <see cref="DeflateStream"/>, except that it adds the /// RFC1950 header and trailer bytes to a compressed stream when compressing, or expects /// the RFC1950 header and trailer bytes when decompressing. It is also similar to the /// <see cref="GZipStream"/>. /// </para> /// </remarks> /// <seealso cref="DeflateStream" /> /// <seealso cref="GZipStream" /> public class ZlibStream : System.IO.Stream { internal ZlibBaseStream _baseStream; bool _disposed; /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>. /// </summary> /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> /// will use the default compression level. The "captive" stream will be /// closed when the <c>ZlibStream</c> is closed. /// </para> /// /// </remarks> /// /// <example> /// This example uses a <c>ZlibStream</c> to compress a file, and writes the /// compressed data to another file. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (Stream compressor = new ZlibStream(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"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".zlib") /// Using compressor As Stream = New ZlibStream(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> /// /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, false) { } /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> and /// the specified <c>CompressionLevel</c>. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored. /// The "captive" stream will be closed when the <c>ZlibStream</c> is closed. /// </para> /// /// </remarks> /// /// <example> /// This example uses a <c>ZlibStream</c> to compress data from a file, and writes the /// compressed data to another file. /// /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (Stream compressor = new ZlibStream(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; ".zlib") /// Using compressor As Stream = New ZlibStream(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 ZlibStream will compress or decompress.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, false) { } /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>, and /// explicitly specify whether the captive stream should be left open after /// Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> will use /// the default compression level. /// </para> /// /// <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 /// <see cref="System.IO.MemoryStream"/> that will be re-read after /// compression. Specify true for the <paramref name="leaveOpen"/> parameter to leave the stream /// open. /// </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 ZlibStream will compress or decompress.</param> /// <param name="leaveOpen">true if the application would like the stream to remain /// open after inflation/deflation.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { } /// <summary> /// Create a <c>ZlibStream</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 <see cref="System.IO.MemoryStream"/> that will be /// re-read after compression. Specify true for the <paramref /// name="leaveOpen"/> parameter to leave the stream open. /// </para> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is /// ignored. /// </para> /// /// </remarks> /// /// <example> /// /// This example shows how to use a ZlibStream to compress the data from a file, /// and store the result into another file. The filestream remains open to allow /// additional data to be written to it. /// /// <code> /// using (var output = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (Stream compressor = new ZlibStream(output, 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); /// } /// } /// } /// // can write additional data to the output stream here /// } /// </code> /// <code lang="VB"> /// Using output As FileStream = File.Create(fileToCompress &amp; ".zlib") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using compressor As Stream = New ZlibStream(output, 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 /// ' can write additional data to the output stream here. /// End Using /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// /// <param name="mode">Indicates whether the ZlibStream 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. This parameter is /// effective only when mode is <c>CompressionMode.Compress</c>. /// </param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.ZLIB, leaveOpen); } #region Zlib properties /// <summary> /// This property sets the flush behavior on the stream. /// Sorry, though, not sure exactly how to describe all the various settings. /// </summary> virtual public FlushType FlushMode { get { return (this._baseStream._flushMode); } set { if (_disposed) throw new ObjectDisposedException("ZlibStream"); 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("ZlibStream"); 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 System.IO.Stream methods /// <summary> /// Dispose the stream. /// </summary> /// <remarks> /// <para> /// This may or may not result in a <c>Close()</c> call on the captive /// stream. See the constructors that have a <c>leaveOpen</c> parameter /// for more information. /// </para> /// <para> /// This method may be invoked in two distinct scenarios. If disposing /// == true, the method has been called directly or indirectly by a /// user's code, for example via the public Dispose() method. In this /// case, both managed and unmanaged resources can be referenced and /// disposed. If disposing == false, the method has been called by the /// runtime from inside the object finalizer and this method should not /// reference other objects; in that case only unmanaged resources must /// be referenced or disposed. /// </para> /// </remarks> /// <param name="disposing"> /// indicates whether the Dispose method was invoked by user code. /// </param> protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && (this._baseStream != null)) this._baseStream.Close(); _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("ZlibStream"); 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("ZlibStream"); return _baseStream._stream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { if (_disposed) throw new ObjectDisposedException("ZlibStream"); _baseStream.Flush(); } /// <summary> /// Reading this property always throws a <see cref="NotSupportedException"/>. /// </summary> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// The position of the stream pointer. /// </summary> /// /// <remarks> /// Setting this property always throws a <see /// cref="NotSupportedException"/>. 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 == ZlibBaseStream.StreamMode.Writer) return this._baseStream._z.TotalBytesOut; if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Reader) return this._baseStream._z.TotalBytesIn; return 0; } set { throw new NotSupportedException(); } } /// <summary> /// Read data from the stream. /// </summary> /// /// <remarks> /// /// <para> /// If you wish to use the <c>ZlibStream</c> to compress data while reading, /// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>, /// providing an uncompressed data stream. Then call <c>Read()</c> on that /// <c>ZlibStream</c>, and the data read will be compressed. If you wish to /// use the <c>ZlibStream</c> to decompress data while reading, you can create /// a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, providing a /// readable compressed data stream. Then call <c>Read()</c> on that /// <c>ZlibStream</c>, and the data will be decompressed as it is read. /// </para> /// /// <para> /// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but /// not both. /// </para> /// /// </remarks> /// /// <param name="buffer"> /// The buffer into which the read 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 read</returns> public override int Read(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("ZlibStream"); return _baseStream.Read(buffer, offset, count); } /// <summary> /// Calling this method always throws a <see cref="NotSupportedException"/>. /// </summary> /// <param name="offset"> /// The offset to seek to.... /// IF THIS METHOD ACTUALLY DID ANYTHING. /// </param> /// <param name="origin"> /// The reference specifying how to apply the offset.... IF /// THIS METHOD ACTUALLY DID ANYTHING. /// </param> /// /// <returns>nothing. This method always throws.</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Calling this method always throws a <see cref="NotSupportedException"/>. /// </summary> /// <param name="value"> /// The new value for the stream length.... IF /// THIS METHOD ACTUALLY DID ANYTHING. /// </param> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Write data to the stream. /// </summary> /// /// <remarks> /// /// <para> /// If you wish to use the <c>ZlibStream</c> to compress data while writing, /// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>, /// and a writable output stream. Then call <c>Write()</c> on that /// <c>ZlibStream</c>, providing uncompressed data as input. The data sent to /// the output stream will be the compressed form of the data written. If you /// wish to use the <c>ZlibStream</c> to decompress data while writing, you /// can create a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, and a /// writable output stream. Then call <c>Write()</c> on that stream, /// providing previously compressed data. The data sent to the output stream /// will be the decompressed form of the data written. /// </para> /// /// <para> /// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both. /// </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("ZlibStream"); _baseStream.Write(buffer, offset, count); } #endregion /// <summary> /// Compress a string into a byte array using ZLIB. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="ZlibStream.UncompressString(byte[])"/>. /// </remarks> /// /// <seealso cref="ZlibStream.UncompressString(byte[])"/> /// <seealso cref="ZlibStream.CompressBuffer(byte[])"/> /// <seealso cref="GZipStream.CompressString(string)"/> /// /// <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()) { Stream compressor = new ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressString(s, compressor); return ms.ToArray(); } } /// <summary> /// Compress a byte array into a new byte array using ZLIB. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="ZlibStream.UncompressBuffer(byte[])"/>. /// </remarks> /// /// <seealso cref="ZlibStream.CompressString(string)"/> /// <seealso cref="ZlibStream.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()) { Stream compressor = new ZlibStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression ); ZlibBaseStream.CompressBuffer(b, compressor); return ms.ToArray(); } } /// <summary> /// Uncompress a ZLIB-compressed byte array into a single string. /// </summary> /// /// <seealso cref="ZlibStream.CompressString(String)"/> /// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/> /// /// <param name="compressed"> /// A buffer containing ZLIB-compressed data. /// </param> /// /// <returns>The uncompressed string</returns> public static String UncompressString(byte[] compressed) { using (var input = new MemoryStream(compressed)) { Stream decompressor = new ZlibStream(input, CompressionMode.Decompress); return ZlibBaseStream.UncompressString(compressed, decompressor); } } /// <summary> /// Uncompress a ZLIB-compressed byte array into a byte array. /// </summary> /// /// <seealso cref="ZlibStream.CompressBuffer(byte[])"/> /// <seealso cref="ZlibStream.UncompressString(byte[])"/> /// /// <param name="compressed"> /// A buffer containing ZLIB-compressed data. /// </param> /// /// <returns>The data in uncompressed form</returns> public static byte[] UncompressBuffer(byte[] compressed) { using (var input = new MemoryStream(compressed)) { Stream decompressor = new ZlibStream( input, CompressionMode.Decompress ); return ZlibBaseStream.UncompressBuffer(compressed, decompressor); } } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// CurrencyPlanPrice /// </summary> [DataContract] public partial class CurrencyPlanPrice : IEquatable<CurrencyPlanPrice>, IValidatableObject { public CurrencyPlanPrice() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="CurrencyPlanPrice" /> class. /// </summary> /// <param name="CurrencyCode">Specifies the ISO currency code for the account..</param> /// <param name="CurrencySymbol">Specifies the currency symbol for the account..</param> /// <param name="PerSeatPrice">PerSeatPrice.</param> /// <param name="SupportedCardTypes">SupportedCardTypes.</param> /// <param name="SupportIncidentFee">The support incident fee charged for each support incident..</param> /// <param name="SupportPlanFee">The support plan fee charged for this plan..</param> public CurrencyPlanPrice(string CurrencyCode = default(string), string CurrencySymbol = default(string), string PerSeatPrice = default(string), CreditCardTypes SupportedCardTypes = default(CreditCardTypes), string SupportIncidentFee = default(string), string SupportPlanFee = default(string)) { this.CurrencyCode = CurrencyCode; this.CurrencySymbol = CurrencySymbol; this.PerSeatPrice = PerSeatPrice; this.SupportedCardTypes = SupportedCardTypes; this.SupportIncidentFee = SupportIncidentFee; this.SupportPlanFee = SupportPlanFee; } /// <summary> /// Specifies the ISO currency code for the account. /// </summary> /// <value>Specifies the ISO currency code for the account.</value> [DataMember(Name="currencyCode", EmitDefaultValue=false)] public string CurrencyCode { get; set; } /// <summary> /// Specifies the currency symbol for the account. /// </summary> /// <value>Specifies the currency symbol for the account.</value> [DataMember(Name="currencySymbol", EmitDefaultValue=false)] public string CurrencySymbol { get; set; } /// <summary> /// Gets or Sets PerSeatPrice /// </summary> [DataMember(Name="perSeatPrice", EmitDefaultValue=false)] public string PerSeatPrice { get; set; } /// <summary> /// Gets or Sets SupportedCardTypes /// </summary> [DataMember(Name="supportedCardTypes", EmitDefaultValue=false)] public CreditCardTypes SupportedCardTypes { get; set; } /// <summary> /// The support incident fee charged for each support incident. /// </summary> /// <value>The support incident fee charged for each support incident.</value> [DataMember(Name="supportIncidentFee", EmitDefaultValue=false)] public string SupportIncidentFee { get; set; } /// <summary> /// The support plan fee charged for this plan. /// </summary> /// <value>The support plan fee charged for this plan.</value> [DataMember(Name="supportPlanFee", EmitDefaultValue=false)] public string SupportPlanFee { 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 CurrencyPlanPrice {\n"); sb.Append(" CurrencyCode: ").Append(CurrencyCode).Append("\n"); sb.Append(" CurrencySymbol: ").Append(CurrencySymbol).Append("\n"); sb.Append(" PerSeatPrice: ").Append(PerSeatPrice).Append("\n"); sb.Append(" SupportedCardTypes: ").Append(SupportedCardTypes).Append("\n"); sb.Append(" SupportIncidentFee: ").Append(SupportIncidentFee).Append("\n"); sb.Append(" SupportPlanFee: ").Append(SupportPlanFee).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 CurrencyPlanPrice); } /// <summary> /// Returns true if CurrencyPlanPrice instances are equal /// </summary> /// <param name="other">Instance of CurrencyPlanPrice to be compared</param> /// <returns>Boolean</returns> public bool Equals(CurrencyPlanPrice other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.CurrencyCode == other.CurrencyCode || this.CurrencyCode != null && this.CurrencyCode.Equals(other.CurrencyCode) ) && ( this.CurrencySymbol == other.CurrencySymbol || this.CurrencySymbol != null && this.CurrencySymbol.Equals(other.CurrencySymbol) ) && ( this.PerSeatPrice == other.PerSeatPrice || this.PerSeatPrice != null && this.PerSeatPrice.Equals(other.PerSeatPrice) ) && ( this.SupportedCardTypes == other.SupportedCardTypes || this.SupportedCardTypes != null && this.SupportedCardTypes.Equals(other.SupportedCardTypes) ) && ( this.SupportIncidentFee == other.SupportIncidentFee || this.SupportIncidentFee != null && this.SupportIncidentFee.Equals(other.SupportIncidentFee) ) && ( this.SupportPlanFee == other.SupportPlanFee || this.SupportPlanFee != null && this.SupportPlanFee.Equals(other.SupportPlanFee) ); } /// <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.CurrencyCode != null) hash = hash * 59 + this.CurrencyCode.GetHashCode(); if (this.CurrencySymbol != null) hash = hash * 59 + this.CurrencySymbol.GetHashCode(); if (this.PerSeatPrice != null) hash = hash * 59 + this.PerSeatPrice.GetHashCode(); if (this.SupportedCardTypes != null) hash = hash * 59 + this.SupportedCardTypes.GetHashCode(); if (this.SupportIncidentFee != null) hash = hash * 59 + this.SupportIncidentFee.GetHashCode(); if (this.SupportPlanFee != null) hash = hash * 59 + this.SupportPlanFee.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.CodeAnalysis.Scripting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Interactive { internal partial class InteractiveHost { /// <summary> /// A remote singleton server-activated object that lives in the interactive host process and controls it. /// </summary> internal sealed class Service : MarshalByRefObject, IDisposable { private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false); private static TaskScheduler s_UIThreadScheduler; internal static readonly ImmutableArray<string> DefaultSourceSearchPaths = ImmutableArray.Create(FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))); internal static readonly ImmutableArray<string> DefaultReferenceSearchPaths = ImmutableArray.Create(FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory())); private readonly InteractiveAssemblyLoader _assemblyLoader; private readonly MetadataShadowCopyProvider _metadataFileProvider; // the search paths - updated from the hostObject private ImmutableArray<string> _sourceSearchPaths; private ObjectFormatter _objectFormatter; private IRepl _repl; private InteractiveHostObject _hostObject; private ObjectFormattingOptions _formattingOptions; // Session is not thread-safe by itself, and the compilation // and execution of scripts are asynchronous operations. // However since the operations are executed serially, it // is sufficient to lock when creating the async tasks. private readonly object _lastTaskGuard = new object(); private Task<TaskResult> _lastTask; private struct TaskResult { internal readonly ScriptOptions Options; internal readonly ScriptState<object> State; internal TaskResult(ScriptOptions options, ScriptState<object> state) { Debug.Assert(options != null); this.Options = options; this.State = state; } internal TaskResult With(ScriptOptions options) { return new TaskResult(options, State); } internal TaskResult With(ScriptState<object> state) { return new TaskResult(Options, state); } } private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create( FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)), FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory())); #region Setup public Service() { // TODO (tomat): we should share the copied files with the host _metadataFileProvider = new MetadataShadowCopyProvider( Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"), noShadowCopyDirectories: s_systemNoShadowCopyDirectories); _assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider); _formattingOptions = new ObjectFormattingOptions( memberFormat: MemberDisplayFormat.Inline, quoteStrings: true, useHexadecimalNumbers: false, maxOutputLength: 200, memberIndentation: " "); // We want to be sure to delete the shadow-copied files when the process goes away. Frankly // there's nothing we can do if the process is forcefully quit or goes down in a completely // uncontrolled manner (like a stack overflow). When the process goes down in a controlled // manned, we should generally expect this event to be called. AppDomain.CurrentDomain.ProcessExit += HandleProcessExit; } private void HandleProcessExit(object sender, EventArgs e) { Dispose(); AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit; } public void Dispose() { _metadataFileProvider.Dispose(); } public override object InitializeLifetimeService() { return null; } public void Initialize(Type replType) { Contract.ThrowIfNull(replType); _repl = (IRepl)Activator.CreateInstance(replType); _objectFormatter = _repl.CreateObjectFormatter(); _hostObject = new InteractiveHostObject(); var options = ScriptOptions.Default .WithSearchPaths(DefaultReferenceSearchPaths) .WithBaseDirectory(Directory.GetCurrentDirectory()) .AddReferences(_hostObject.GetType().Assembly); _sourceSearchPaths = DefaultSourceSearchPaths; _hostObject.ReferencePaths.AddRange(options.SearchPaths); _hostObject.SourcePaths.AddRange(_sourceSearchPaths); _lastTask = Task.FromResult(new TaskResult(options, null)); Console.OutputEncoding = Encoding.UTF8; } private static bool AttachToClientProcess(int clientProcessId) { Process clientProcess; try { clientProcess = Process.GetProcessById(clientProcessId); } catch (ArgumentException) { return false; } clientProcess.EnableRaisingEvents = true; clientProcess.Exited += new EventHandler((_, __) => { s_clientExited.Set(); }); return clientProcess.IsAlive(); } // for testing purposes public void EmulateClientExit() { s_clientExited.Set(); } internal static void RunServer(string[] args) { if (args.Length != 3) { throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>"); } RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture)); } /// <summary> /// Implements remote server. /// </summary> private static void RunServer(string serverPort, string semaphoreName, int clientProcessId) { if (!AttachToClientProcess(clientProcessId)) { return; } // Disables Windows Error Reporting for the process, so that the process fails fast. // Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) // Note that GetErrorMode is not available on XP at all. if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0)) { SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX); } IpcServerChannel serverChannel = null; IpcClientChannel clientChannel = null; try { using (var semaphore = Semaphore.OpenExisting(semaphoreName)) { // DEBUG: semaphore.WaitOne(); var serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; var clientProvider = new BinaryClientFormatterSinkProvider(); clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider); ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false); serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider); ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(Service), ServiceName, WellKnownObjectMode.Singleton); using (var resetEvent = new ManualResetEventSlim(false)) { var uiThread = new Thread(() => { var c = new Control(); c.CreateControl(); s_UIThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext(); resetEvent.Set(); Application.Run(); }); uiThread.SetApartmentState(ApartmentState.STA); uiThread.IsBackground = true; uiThread.Start(); resetEvent.Wait(); } // the client can instantiate interactive host now: semaphore.Release(); } s_clientExited.Wait(); } finally { if (serverChannel != null) { ChannelServices.UnregisterChannel(serverChannel); } if (clientChannel != null) { ChannelServices.UnregisterChannel(clientChannel); } } // force exit even if there are foreground threads running: Environment.Exit(0); } internal static string ServiceName { get { return typeof(Service).Name; } } private static string GenerateUniqueChannelLocalName() { return typeof(Service).FullName + Guid.NewGuid(); } #endregion #region Remote Async Entry Points // Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.) [OneWay] public void SetPathsAsync( RemoteAsyncOperation<object> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { Debug.Assert(operation != null); Debug.Assert(referenceSearchPaths != null); Debug.Assert(sourceSearchPaths != null); Debug.Assert(baseDirectory != null); lock (_lastTaskGuard) { _lastTask = SetPathsAsync(_lastTask, operation, referenceSearchPaths, sourceSearchPaths, baseDirectory); } } private async Task<TaskResult> SetPathsAsync( Task<TaskResult> lastTask, RemoteAsyncOperation<object> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { var result = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); var options = result.Options; try { Directory.SetCurrentDirectory(baseDirectory); _hostObject.ReferencePaths.Clear(); _hostObject.ReferencePaths.AddRange(referenceSearchPaths); options = options.WithSearchPaths(referenceSearchPaths).WithBaseDirectory(baseDirectory); _hostObject.SourcePaths.Clear(); _hostObject.SourcePaths.AddRange(sourceSearchPaths); _sourceSearchPaths = sourceSearchPaths.AsImmutable(); } finally { operation.Completed(null); } return result.With(options); } /// <summary> /// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it. /// Execution is performed on the UI thread. /// </summary> [OneWay] public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting) { Debug.Assert(operation != null); lock (_lastTaskGuard) { _lastTask = InitializeContextAsync(_lastTask, operation, initializationFile, isRestarting); } } private static string ResolveReferencePath(ScriptOptions options, string reference, string baseFilePath) { var references = options.ReferenceResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (references.IsDefaultOrEmpty) { return null; } return references.Single().FilePath; } /// <summary> /// Adds an assembly reference to the current session. /// </summary> [OneWay] public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference) { Debug.Assert(operation != null); Debug.Assert(reference != null); lock (_lastTaskGuard) { _lastTask = AddReferenceAsync(_lastTask, operation, reference); } } private async Task<TaskResult> AddReferenceAsync(Task<TaskResult> lastTask, RemoteAsyncOperation<bool> operation, string reference) { var result = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); var success = false; var options = result.Options; try { string fullPath = ResolveReferencePath(options, reference, baseFilePath: null); if (fullPath != null) { success = LoadReference(fullPath, suppressWarnings: false, addReference: true, options: ref options); } else { Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference)); } } catch (Exception e) { ReportUnhandledException(e); } finally { operation.Completed(success); } return result.With(options); } /// <summary> /// Executes given script snippet on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text) { Debug.Assert(operation != null); Debug.Assert(text != null); lock (_lastTaskGuard) { _lastTask = ExecuteAsync(_lastTask, operation, text); } } private async Task<TaskResult> ExecuteAsync(Task<TaskResult> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string text) { var result = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); var success = false; try { Script<object> script; try { var options = result.Options; var state = result.State; script = Compile(state?.Script, text, null, ref options); result = new TaskResult(options, state); } catch (CompilationErrorException e) { DisplayInteractiveErrors(e.Diagnostics, Console.Error); script = null; } if (script != null) { success = true; // successful if compiled var executeResult = await ExecuteOnUIThread(result, script).ConfigureAwait(false); result = executeResult.Result; if (executeResult.Success) { bool hasValue; var resultType = script.GetCompilation().GetSubmissionResultType(out hasValue); if (hasValue) { if (resultType != null && resultType.SpecialType == SpecialType.System_Void) { Console.Out.WriteLine(_objectFormatter.VoidDisplayString); } else { Console.Out.WriteLine(_objectFormatter.FormatObject(executeResult.Value, _formattingOptions)); } } } } } catch (Exception e) { ReportUnhandledException(e); } finally { result = CompleteExecution(result, operation, success); } return result; } /// <summary> /// Executes given script file on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path) { Debug.Assert(operation != null); Debug.Assert(path != null); lock (_lastTaskGuard) { _lastTask = ExecuteFileAsync(operation, _lastTask, options => ResolveRelativePath(path, options.BaseDirectory, displayPath: false)); } } private TaskResult CompleteExecution(TaskResult result, RemoteAsyncOperation<RemoteExecutionResult> operation, bool success, string resolvedPath = null) { // TODO (tomat): we should be resetting this info just before the execution to ensure that the services see the same // as the next execution. // send any updates to the host object and current directory back to the client: var options = result.Options; var newSourcePaths = _hostObject.SourcePaths.List.GetNewContent(); var newReferencePaths = _hostObject.ReferencePaths.List.GetNewContent(); var currentDirectory = Directory.GetCurrentDirectory(); var oldWorkingDirectory = options.BaseDirectory; var newWorkingDirectory = (oldWorkingDirectory != currentDirectory) ? currentDirectory : null; // update local search paths, the client updates theirs on operation completion: if (newSourcePaths != null) { _sourceSearchPaths = newSourcePaths.AsImmutable(); } if (newReferencePaths != null) { options = options.WithSearchPaths(newReferencePaths); } options = options.WithBaseDirectory(currentDirectory); operation.Completed(new RemoteExecutionResult(success, newSourcePaths, newReferencePaths, newWorkingDirectory, resolvedPath)); return result.With(options); } private static async Task<TaskResult> ReportUnhandledExceptionIfAny(Task<TaskResult> lastTask) { try { return await lastTask.ConfigureAwait(false); } catch (Exception e) { ReportUnhandledException(e); return lastTask.Result; } } private static void ReportUnhandledException(Exception e) { Console.Error.WriteLine("Unexpected error:"); Console.Error.WriteLine(e); Debug.Fail("Unexpected error"); Debug.WriteLine(e); } #endregion #region Operations // TODO (tomat): testing only public void SetTestObjectFormattingOptions() { _formattingOptions = new ObjectFormattingOptions( memberFormat: MemberDisplayFormat.Inline, quoteStrings: true, useHexadecimalNumbers: false, maxOutputLength: int.MaxValue, memberIndentation: " "); } /// <summary> /// Loads references, set options and execute files specified in the initialization file. /// Also prints logo unless <paramref name="isRestarting"/> is true. /// </summary> private async Task<TaskResult> InitializeContextAsync( Task<TaskResult> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFileOpt, bool isRestarting) { Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt)); var result = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here? if (!isRestarting) { Console.Out.WriteLine(_repl.GetLogo()); } if (File.Exists(initializationFileOpt)) { Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt))); var parser = _repl.GetCommandLineParser(); // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var rspDirectory = Path.GetDirectoryName(initializationFileOpt); var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/); foreach (var error in args.Errors) { var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out; writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture)); } if (args.Errors.Length == 0) { // TODO (tomat): other arguments // TODO (tomat): parse options var referencePaths = args.ReferencePaths; result = result.With(result.Options.AddSearchPaths(referencePaths)); _hostObject.ReferencePaths.Clear(); _hostObject.ReferencePaths.AddRange(referencePaths); // TODO (tomat): consolidate with other reference resolving foreach (CommandLineReference cmdLineReference in args.MetadataReferences) { // interactive command line parser doesn't accept modules or linked assemblies Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes); var options = result.Options; string fullPath = ResolveReferencePath(options, cmdLineReference.Reference, baseFilePath: null); LoadReference(fullPath, suppressWarnings: true, addReference: true, options: ref options); result = result.With(options); } foreach (CommandLineSourceFile file in args.SourceFiles) { // execute all files as scripts (matches csi/vbi semantics) string fullPath = ResolveRelativePath(file.Path, rspDirectory, displayPath: true); if (fullPath != null) { var executeResult = await ExecuteFileAsync(result, fullPath).ConfigureAwait(false); result = executeResult.Result; } } } } if (!isRestarting) { Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation); } } catch (Exception e) { ReportUnhandledException(e); } finally { result = CompleteExecution(result, operation, true); } return result; } private string ResolveRelativePath(string path, string baseDirectory, bool displayPath) { List<string> attempts = new List<string>(); Func<string, bool> fileExists = file => { attempts.Add(file); return File.Exists(file); }; string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, _sourceSearchPaths, fileExists); if (fullPath == null) { if (displayPath) { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path); } else { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound); } if (attempts.Count > 0) { DisplaySearchPaths(Console.Error, attempts); } } return fullPath; } private bool LoadReference(string fullOriginalPath, bool suppressWarnings, bool addReference, ref ScriptOptions options) { AssemblyLoadResult result; try { result = LoadFromPathThrowing(fullOriginalPath, addReference, ref options); } catch (FileNotFoundException e) { Console.Error.WriteLine(e.Message); return false; } catch (ArgumentException e) { Console.Error.WriteLine((e.InnerException ?? e).Message); return false; } catch (TargetInvocationException e) { // The user might have hooked AssemblyResolve event, which might have thrown an exception. // Display stack trace in this case. Console.Error.WriteLine(e.InnerException.ToString()); return false; } if (!result.IsSuccessful && !suppressWarnings) { Console.Out.WriteLine(string.Format(CultureInfo.CurrentCulture, FeaturesResources.RequestedAssemblyAlreadyLoaded, result.OriginalPath)); } return true; } // Testing utility. // TODO (tomat): needed since MetadataReference is not serializable . // Has to be public to be callable via remoting. public SerializableAssemblyLoadResult LoadReferenceThrowing(string reference, bool addReference) { lock (_lastTaskGuard) { var result = ReportUnhandledExceptionIfAny(_lastTask).Result; var options = result.Options; var fullPath = ResolveReferencePath(options, reference, baseFilePath: null); if (fullPath == null) { throw new FileNotFoundException(message: null, fileName: reference); } var loadResult = LoadFromPathThrowing(fullPath, addReference, ref options); _lastTask = Task.FromResult(result.With(options)); return loadResult; } } private AssemblyLoadResult LoadFromPathThrowing(string fullOriginalPath, bool addReference, ref ScriptOptions options) { var result = _assemblyLoader.LoadFromPath(fullOriginalPath); if (addReference && result.IsSuccessful) { var reference = _metadataFileProvider.GetReference(fullOriginalPath); options = options.AddReferences(reference); } return result; } private Script<object> Compile(Script previousScript, string text, string path, ref ScriptOptions options) { Script script; var scriptOptions = options.WithPath(path).WithIsInteractive(path == null); if (previousScript != null) { script = previousScript.ContinueWith(text, scriptOptions); } else { script = _repl.CreateScript(text).WithOptions(scriptOptions).WithGlobalsType(_hostObject.GetType()); } // force build so exception is thrown now if errors are found. script.Build(); // load all references specified in #r's -- they will all be PE references (may be shadow copied): foreach (PortableExecutableReference reference in script.GetCompilation().DirectiveReferences) { // FullPath refers to the original reference path, not the copy: LoadReference(reference.FilePath, suppressWarnings: false, addReference: false, options: ref options); } return (Script<object>)script; } private async Task<TaskResult> ExecuteFileAsync( RemoteAsyncOperation<RemoteExecutionResult> operation, Task<TaskResult> lastTask, Func<ScriptOptions, string> getFullPath) { var result = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); var success = false; try { var fullPath = getFullPath(result.Options); var executeResult = await ExecuteFileAsync(result, fullPath).ConfigureAwait(false); result = executeResult.Result; success = executeResult.Success; } finally { result = CompleteExecution(result, operation, success); } return result; } /// <summary> /// Executes specified script file as a submission. /// </summary> /// <returns>True if the code has been executed. False if the code doesn't compile.</returns> /// <remarks> /// All errors are written to the error output stream. /// Uses source search paths to resolve unrooted paths. /// </remarks> private async Task<ExecuteResult> ExecuteFileAsync(TaskResult result, string fullPath) { string content = null; if (fullPath != null) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); try { content = File.ReadAllText(fullPath); } catch (Exception e) { Console.Error.WriteLine(e.Message); } } var success = false; if (content != null) { try { Script<object> script; try { var options = result.Options; var state = result.State; script = Compile(state?.Script, content, fullPath, ref options); result = new TaskResult(options, state); } catch (CompilationErrorException e) { DisplayInteractiveErrors(e.Diagnostics, Console.Error); script = null; } if (script != null) { success = true; // successful if compiled var executeResult = await ExecuteOnUIThread(result, script).ConfigureAwait(false); result = executeResult.Result; } } catch (Exception e) { ReportUnhandledException(e); } } return new ExecuteResult(result, null, null, success); } private static void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths) { writer.WriteLine(attemptedFilePaths.Count == 1 ? FeaturesResources.SearchedInDirectory : FeaturesResources.SearchedInDirectories); foreach (string path in attemptedFilePaths) { writer.Write(" "); writer.WriteLine(Path.GetDirectoryName(path)); } } private struct ExecuteResult { internal readonly TaskResult Result; internal readonly object Value; internal readonly Exception Exception; internal readonly bool Success; internal ExecuteResult(TaskResult result, object value, Exception exception, bool success) { this.Result = result; this.Value = value; this.Exception = exception; this.Success = success; } } private async Task<ExecuteResult> ExecuteOnUIThread(TaskResult result, Script<object> script) { var executeResult = await Task.Factory.StartNew(async () => { try { var state = result.State; var task = (state == null) ? script.RunAsync(_hostObject, CancellationToken.None) : script.ContinueAsync(state, CancellationToken.None); state = await task.ConfigureAwait(false); return new ExecuteResult(result.With(state), state.ReturnValue, null, true); } catch (Exception e) { return new ExecuteResult(result, null, e, false); } }, CancellationToken.None, TaskCreationOptions.None, s_UIThreadScheduler).Unwrap().ConfigureAwait(false); var exception = executeResult.Exception; if (exception != null) { // TODO (tomat): format exception Console.Error.WriteLine(exception); } return executeResult; } private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output) { var displayedDiagnostics = new List<Diagnostic>(); const int MaxErrorCount = 5; for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++) { displayedDiagnostics.Add(diagnostics[i]); } displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start); var formatter = _repl.GetDiagnosticFormatter(); foreach (var diagnostic in displayedDiagnostics) { output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo)); } if (diagnostics.Length > MaxErrorCount) { int notShown = diagnostics.Length - MaxErrorCount; output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors")); } } #endregion #region Win32 API [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode SetErrorMode(ErrorMode mode); [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode GetErrorMode(); [Flags] internal enum ErrorMode : int { /// <summary> /// Use the system default, which is to display all error dialog boxes. /// </summary> SEM_FAILCRITICALERRORS = 0x0001, /// <summary> /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process. /// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup. /// This is to prevent error mode dialogs from hanging the application. /// </summary> SEM_NOGPFAULTERRORBOX = 0x0002, /// <summary> /// The system automatically fixes memory alignment faults and makes them invisible to the application. /// It does this for the calling process and any descendant processes. This feature is only supported by /// certain processor architectures. For more information, see the Remarks section. /// After this value is set for a process, subsequent attempts to clear the value are ignored. /// </summary> SEM_NOALIGNMENTFAULTEXCEPT = 0x0004, /// <summary> /// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process. /// </summary> SEM_NOOPENFILEERRORBOX = 0x8000, } #endregion #region Testing // TODO(tomat): remove when the compiler supports events // For testing purposes only! public void HookMaliciousAssemblyResolve() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) => { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { Console.Error.WriteLine("in the loop"); i = i + 1; } } }); } public void RemoteConsoleWrite(byte[] data, bool isError) { using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput()) { stream.Write(data, 0, data.Length); stream.Flush(); } } public bool IsShadowCopy(string path) { return _metadataFileProvider.IsShadowCopy(path); } #endregion } } }
// ***************************************************************************** // // Copyright 2004, Weifen Luo // All rights reserved. The software and associated documentation // supplied hereunder are the proprietary information of Weifen Luo // and are supplied subject to licence terms. // // WinFormsUI Library Version 1.0 // ***************************************************************************** using System; using System.Windows.Forms; using System.Drawing; namespace WeifenLuo.WinFormsUI { internal class AutoHideWindow : Panel { #region consts private const int ANIMATE_TIME = 100; // in mini-seconds private const string _ExceptionInvalidActiveContent = "DockPanel.ActiveAutoHideContent.InvalidValue"; #endregion private Timer m_timerMouseTrack; private AutoHideWindowSplitter m_splitter; public AutoHideWindow(DockPanel dockPanel) { m_dockPanel = dockPanel; m_timerMouseTrack = new Timer(); m_timerMouseTrack.Tick += new EventHandler(TimerMouseTrack_Tick); Visible = false; m_splitter = new AutoHideWindowSplitter(); Controls.Add(m_splitter); } protected override void Dispose(bool disposing) { if (disposing) { m_timerMouseTrack.Dispose(); } base.Dispose(disposing); } private DockPanel m_dockPanel = null; public DockPanel DockPanel { get { return m_dockPanel; } } private DockPane m_activePane = null; public DockPane ActivePane { get { return m_activePane; } } private void SetActivePane() { DockPane value = (ActiveContent == null ? null : ActiveContent.Pane); if (value == m_activePane) return; if (m_activePane != null) if (m_activePane.IsActivated) DockPanel.Focus(); m_activePane = value; } private DockContent m_activeContent = null; public DockContent ActiveContent { get { return m_activeContent; } set { if (value == m_activeContent) return; if (value != null) { if (!DockHelper.IsDockStateAutoHide(value.DockState) || value.DockPanel != DockPanel) throw(new InvalidOperationException(ResourceHelper.GetString(_ExceptionInvalidActiveContent))); } DockPanel.SuspendLayout(); if (m_activeContent != null) AnimateWindow(false); m_activeContent = value; SetActivePane(); if (ActivePane != null) ActivePane.ActiveContent = m_activeContent; if (m_activeContent != null) AnimateWindow(true); DockPanel.ResumeLayout(); DockPanel.RefreshAutoHideStrip(); SetTimerMouseTrack(); } } public DockState DockState { get { return ActiveContent == null ? DockState.Unknown : ActiveContent.DockState; } } private bool m_flagAnimate = true; private bool FlagAnimate { get { return m_flagAnimate; } set { m_flagAnimate = value; } } private void AnimateWindow(bool show) { if (!FlagAnimate) { Visible = show; return; } Rectangle rectSource = GetBounds(!show); Rectangle rectTarget = GetBounds(show); int dxLoc, dyLoc; int dWidth, dHeight; dxLoc = dyLoc = dWidth = dHeight = 0; if (DockState == DockState.DockTopAutoHide) dHeight = show ? 1 : -1; else if (DockState == DockState.DockLeftAutoHide) dWidth = show ? 1 : -1; else if (DockState == DockState.DockRightAutoHide) { dxLoc = show ? -1 : 1; dWidth = show ? 1 : -1; } else if (DockState == DockState.DockBottomAutoHide) { dyLoc = (show ? -1 : 1); dHeight = (show ? 1 : -1); } if (show) { Bounds = new Rectangle(-rectTarget.Width, -rectTarget.Height, rectTarget.Width, rectTarget.Height); Visible = true; PerformLayout(); } SuspendLayout(); LayoutAnimateWindow(rectSource); Visible = true; int speedFactor = 1; int totalPixels = (rectSource.Width != rectTarget.Width) ? Math.Abs(rectSource.Width - rectTarget.Width) : Math.Abs(rectSource.Height - rectTarget.Height); int remainPixels = totalPixels; DateTime startingTime = DateTime.Now; while (rectSource != rectTarget) { DateTime startPerMove = DateTime.Now; rectSource.X += dxLoc * speedFactor; rectSource.Y += dyLoc * speedFactor; rectSource.Width += dWidth * speedFactor; rectSource.Height += dHeight * speedFactor; if (Math.Sign(rectTarget.X - rectSource.X) != Math.Sign(dxLoc)) rectSource.X = rectTarget.X; if (Math.Sign(rectTarget.Y - rectSource.Y) != Math.Sign(dyLoc)) rectSource.Y = rectTarget.Y; if (Math.Sign(rectTarget.Width - rectSource.Width) != Math.Sign(dWidth)) rectSource.Width = rectTarget.Width; if (Math.Sign(rectTarget.Height - rectSource.Height) != Math.Sign(dHeight)) rectSource.Height = rectTarget.Height; LayoutAnimateWindow(rectSource); DockPanel.Update(); remainPixels -= speedFactor; while (true) { TimeSpan time = new TimeSpan(0, 0, 0, 0, ANIMATE_TIME); TimeSpan elapsedPerMove = DateTime.Now - startPerMove; TimeSpan elapsedTime = DateTime.Now - startingTime; if (((int)((time - elapsedTime).TotalMilliseconds)) <= 0) { speedFactor = remainPixels; break; } else speedFactor = remainPixels * (int)elapsedPerMove.TotalMilliseconds / (int)((time - elapsedTime).TotalMilliseconds); if (speedFactor >= 1) break; } } ResumeLayout(); } private void LayoutAnimateWindow(Rectangle rect) { Bounds = rect; Rectangle rectClient = ClientRectangle; if (DockState == DockState.DockLeftAutoHide) ActivePane.Location = new Point(rectClient.Right - 2 - MeasureAutoHideWindow.SplitterSize - ActivePane.Width, ActivePane.Location.Y); else if (DockState == DockState.DockTopAutoHide) ActivePane.Location = new Point(ActivePane.Location.X, rectClient.Bottom - 2 - MeasureAutoHideWindow.SplitterSize - ActivePane.Height); } private Rectangle GetBounds(bool show) { if (DockState == DockState.Unknown) return Rectangle.Empty; Rectangle rect = DockPanel.AutoHideWindowBounds; if (show) return rect; if (DockState == DockState.DockLeftAutoHide) rect.Width = 0; else if (DockState == DockState.DockRightAutoHide) { rect.X += rect.Width; rect.Width = 0; } else if (DockState == DockState.DockTopAutoHide) rect.Height = 0; else { rect.Y += rect.Height; rect.Height = 0; } return rect; } private void SetTimerMouseTrack() { if (ActivePane == null || ActivePane.IsActivated) { m_timerMouseTrack.Enabled = false; return; } // start the timer uint hovertime = 0; User32.SystemParametersInfo(Win32.SystemParametersInfoActions.GetMouseHoverTime, 0, ref hovertime, 0); // assign a default value 400 in case of setting Timer.Interval invalid value exception if (((int)hovertime) <= 0) hovertime = 400; m_timerMouseTrack.Interval = 2 * (int)hovertime; m_timerMouseTrack.Enabled = true; } protected virtual Rectangle DisplayingRectangle { get { Rectangle rect = ClientRectangle; // exclude the border and the splitter if (DockState == DockState.DockBottomAutoHide) { rect.Y += 2 + MeasureAutoHideWindow.SplitterSize; rect.Height -= 2 + MeasureAutoHideWindow.SplitterSize; } else if (DockState == DockState.DockRightAutoHide) { rect.X += 2 + MeasureAutoHideWindow.SplitterSize; rect.Width -= 2 + MeasureAutoHideWindow.SplitterSize; } else if (DockState == DockState.DockTopAutoHide) rect.Height -= 2 + MeasureAutoHideWindow.SplitterSize; else if (DockState == DockState.DockLeftAutoHide) rect.Width -= 2 + MeasureAutoHideWindow.SplitterSize; return rect; } } protected override void OnLayout(LayoutEventArgs levent) { DockPadding.All = 0; if (DockState == DockState.DockLeftAutoHide) { DockPadding.Right = 2; m_splitter.Dock = DockStyle.Right; } else if (DockState == DockState.DockRightAutoHide) { DockPadding.Left = 2; m_splitter.Dock = DockStyle.Left; } else if (DockState == DockState.DockTopAutoHide) { DockPadding.Bottom = 2; m_splitter.Dock = DockStyle.Bottom; } else if (DockState == DockState.DockBottomAutoHide) { DockPadding.Top = 2; m_splitter.Dock = DockStyle.Top; } foreach (Control c in Controls) { DockPane pane = c as DockPane; if (pane == null) continue; if (pane == ActivePane) pane.Bounds = DisplayingRectangle; else pane.Bounds = Rectangle.Empty; } base.OnLayout(levent); } protected override void OnPaint(PaintEventArgs e) { // Draw the border Graphics g = e.Graphics; if (DockState == DockState.DockBottomAutoHide) g.DrawLine(SystemPens.ControlLightLight, 0, 1, ClientRectangle.Right, 1); else if (DockState == DockState.DockRightAutoHide) g.DrawLine(SystemPens.ControlLightLight, 1, 0, 1, ClientRectangle.Bottom); else if (DockState == DockState.DockTopAutoHide) { g.DrawLine(SystemPens.ControlDark, 0, ClientRectangle.Height - 2, ClientRectangle.Right, ClientRectangle.Height - 2); g.DrawLine(SystemPens.ControlDarkDark, 0, ClientRectangle.Height - 1, ClientRectangle.Right, ClientRectangle.Height - 1); } else if (DockState == DockState.DockLeftAutoHide) { g.DrawLine(SystemPens.ControlDark, ClientRectangle.Width - 2, 0, ClientRectangle.Width - 2, ClientRectangle.Bottom); g.DrawLine(SystemPens.ControlDarkDark, ClientRectangle.Width - 1, 0, ClientRectangle.Width - 1, ClientRectangle.Bottom); } base.OnPaint (e); } public void RefreshActiveContent() { if (ActiveContent == null) return; if (!DockHelper.IsDockStateAutoHide(ActiveContent.DockState)) { FlagAnimate = false; ActiveContent = null; FlagAnimate = true; } } public void RefreshActivePane() { SetTimerMouseTrack(); } private void TimerMouseTrack_Tick(object sender, EventArgs e) { if (ActivePane == null || ActivePane.IsActivated) { m_timerMouseTrack.Enabled = false; return; } DockPane pane = ActivePane; Point ptMouseInAutoHideWindow = PointToClient(Control.MousePosition); Point ptMouseInDockPanel = DockPanel.PointToClient(Control.MousePosition); Rectangle rectTabStrip = DockPanel.GetTabStripRectangle(pane.DockState); if (!ClientRectangle.Contains(ptMouseInAutoHideWindow) && !rectTabStrip.Contains(ptMouseInDockPanel)) { ActiveContent = null; m_timerMouseTrack.Enabled = false; } } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Amazon.Util.Internal { public interface ITypeInfo { Type BaseType { get; } Type Type { get; } Assembly Assembly { get; } bool IsArray { get; } Array ArrayCreateInstance(int length); Type GetInterface(string name); Type[] GetInterfaces(); IEnumerable<PropertyInfo> GetProperties(); IEnumerable<FieldInfo> GetFields(); FieldInfo GetField(string name); MethodInfo GetMethod(string name); MethodInfo GetMethod(string name, ITypeInfo[] paramTypes); MemberInfo[] GetMembers(); ConstructorInfo GetConstructor(ITypeInfo[] paramTypes); PropertyInfo GetProperty(string name); bool IsAssignableFrom(ITypeInfo typeInfo); bool IsEnum {get;} bool IsClass { get; } bool IsValueType { get; } bool IsInterface { get; } bool IsAbstract { get; } object EnumToObject(object value); ITypeInfo EnumGetUnderlyingType(); object CreateInstance(); ITypeInfo GetElementType(); bool IsType(Type type); string FullName { get; } string Name { get; } bool IsGenericTypeDefinition { get; } bool IsGenericType { get; } bool ContainsGenericParameters { get; } Type GetGenericTypeDefinition(); Type[] GetGenericArguments(); object[] GetCustomAttributes(bool inherit); object[] GetCustomAttributes(ITypeInfo attributeType, bool inherit); } public static partial class TypeFactory { public static readonly ITypeInfo[] EmptyTypes = new ITypeInfo[] { }; public static ITypeInfo GetTypeInfo(Type type) { if (type == null) return null; return new TypeInfoWrapper(type); } abstract class AbstractTypeInfo : ITypeInfo { protected Type _type; internal AbstractTypeInfo(Type type) { this._type = type; } public Type Type { get{return this._type;} } public override int GetHashCode() { return this._type.GetHashCode(); } public override bool Equals(object obj) { var typeWrapper = obj as AbstractTypeInfo; if (typeWrapper == null) return false; return this._type.Equals(typeWrapper._type); } public bool IsType(Type type) { return this._type == type; } public abstract Type BaseType { get; } public abstract Assembly Assembly { get; } public abstract Type GetInterface(string name); public abstract Type[] GetInterfaces(); public abstract IEnumerable<PropertyInfo> GetProperties(); public abstract IEnumerable<FieldInfo> GetFields(); public abstract FieldInfo GetField(string name); public abstract MethodInfo GetMethod(string name); public abstract MethodInfo GetMethod(string name, ITypeInfo[] paramTypes); public abstract MemberInfo[] GetMembers(); public abstract PropertyInfo GetProperty(string name); public abstract bool IsAssignableFrom(ITypeInfo typeInfo); public abstract bool IsClass { get; } public abstract bool IsInterface { get; } public abstract bool IsAbstract { get; } public abstract bool IsEnum { get; } public abstract bool IsValueType { get; } public abstract ConstructorInfo GetConstructor(ITypeInfo[] paramTypes); public abstract object[] GetCustomAttributes(bool inherit); public abstract object[] GetCustomAttributes(ITypeInfo attributeType, bool inherit); public abstract bool ContainsGenericParameters { get; } public abstract bool IsGenericTypeDefinition { get; } public abstract bool IsGenericType {get;} public abstract Type GetGenericTypeDefinition(); public abstract Type[] GetGenericArguments(); public bool IsArray { get { return this._type.IsArray; } } public object EnumToObject(object value) { return Enum.ToObject(this._type, value); } public ITypeInfo EnumGetUnderlyingType() { return TypeFactory.GetTypeInfo(Enum.GetUnderlyingType(this._type)); } public object CreateInstance() { return Activator.CreateInstance(this._type); } public Array ArrayCreateInstance(int length) { return Array.CreateInstance(this._type, length); } public ITypeInfo GetElementType() { return TypeFactory.GetTypeInfo(this._type.GetElementType()); } public string FullName { get { return this._type.FullName; } } public string Name { get { return this._type.Name; } } } } }
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define UNSAFE_BYTEBUFFER // uncomment this line to use faster ByteBuffer using System; namespace FlatBuffers { /// <summary> /// Class to mimic Java's ByteBuffer which is used heavily in Flatbuffers. /// If your execution environment allows unsafe code, you should enable /// unsafe code in your project and #define UNSAFE_BYTEBUFFER to use a /// MUCH faster version of ByteBuffer. /// </summary> public class ByteBuffer { private readonly byte[] _buffer; private int _pos; // Must track start of the buffer. public int Length { get { return _buffer.Length; } } public byte[] Data { get { return _buffer; } } public ByteBuffer(byte[] buffer) : this(buffer, 0) { } public ByteBuffer(byte[] buffer, int pos) { _buffer = buffer; _pos = pos; } public int Position { get { return _pos; } set { _pos = value; } } public void Reset() { _pos = 0; } // Pre-allocated helper arrays for convertion. private float[] floathelper = new[] { 0.0f }; private int[] inthelper = new[] { 0 }; private double[] doublehelper = new[] { 0.0 }; private ulong[] ulonghelper = new[] { 0UL }; // Helper functions for the unsafe version. static public ushort ReverseBytes(ushort input) { return (ushort)(((input & 0x00FFU) << 8) | ((input & 0xFF00U) >> 8)); } static public uint ReverseBytes(uint input) { return ((input & 0x000000FFU) << 24) | ((input & 0x0000FF00U) << 8) | ((input & 0x00FF0000U) >> 8) | ((input & 0xFF000000U) >> 24); } static public ulong ReverseBytes(ulong input) { return (((input & 0x00000000000000FFUL) << 56) | ((input & 0x000000000000FF00UL) << 40) | ((input & 0x0000000000FF0000UL) << 24) | ((input & 0x00000000FF000000UL) << 8) | ((input & 0x000000FF00000000UL) >> 8) | ((input & 0x0000FF0000000000UL) >> 24) | ((input & 0x00FF000000000000UL) >> 40) | ((input & 0xFF00000000000000UL) >> 56)); } #if !UNSAFE_BYTEBUFFER // Helper functions for the safe (but slower) version. protected void WriteLittleEndian(int offset, int count, ulong data) { if (BitConverter.IsLittleEndian) { for (int i = 0; i < count; i++) { _buffer[offset + i] = (byte)(data >> i * 8); } } else { for (int i = 0; i < count; i++) { _buffer[offset + count - 1 - i] = (byte)(data >> i * 8); } } } protected ulong ReadLittleEndian(int offset, int count) { AssertOffsetAndLength(offset, count); ulong r = 0; if (BitConverter.IsLittleEndian) { for (int i = 0; i < count; i++) { r |= (ulong)_buffer[offset + i] << i * 8; } } else { for (int i = 0; i < count; i++) { r |= (ulong)_buffer[offset + count - 1 - i] << i * 8; } } return r; } #endif // !UNSAFE_BYTEBUFFER private void AssertOffsetAndLength(int offset, int length) { if (offset < 0 || offset > _buffer.Length - length) throw new ArgumentOutOfRangeException(); } public void PutSbyte(int offset, sbyte value) { AssertOffsetAndLength(offset, sizeof(sbyte)); _buffer[offset] = (byte)value; } public void PutByte(int offset, byte value) { AssertOffsetAndLength(offset, sizeof(byte)); _buffer[offset] = value; } public void PutByte(int offset, byte value, int count) { AssertOffsetAndLength(offset, sizeof(byte) * count); for (var i = 0; i < count; ++i) _buffer[offset + i] = value; } // this method exists in order to conform with Java ByteBuffer standards public void Put(int offset, byte value) { PutByte(offset, value); } #if UNSAFE_BYTEBUFFER // Unsafe but more efficient versions of Put*. public void PutShort(int offset, short value) { PutUshort(offset, (ushort)value); } public unsafe void PutUshort(int offset, ushort value) { AssertOffsetAndLength(offset, sizeof(ushort)); fixed (byte* ptr = _buffer) { *(ushort*)(ptr + offset) = BitConverter.IsLittleEndian ? value : ReverseBytes(value); } } public void PutInt(int offset, int value) { PutUint(offset, (uint)value); } public unsafe void PutUint(int offset, uint value) { AssertOffsetAndLength(offset, sizeof(uint)); fixed (byte* ptr = _buffer) { *(uint*)(ptr + offset) = BitConverter.IsLittleEndian ? value : ReverseBytes(value); } } public unsafe void PutLong(int offset, long value) { PutUlong(offset, (ulong)value); } public unsafe void PutUlong(int offset, ulong value) { AssertOffsetAndLength(offset, sizeof(ulong)); fixed (byte* ptr = _buffer) { *(ulong*)(ptr + offset) = BitConverter.IsLittleEndian ? value : ReverseBytes(value); } } public unsafe void PutFloat(int offset, float value) { AssertOffsetAndLength(offset, sizeof(float)); fixed (byte* ptr = _buffer) { if (BitConverter.IsLittleEndian) { *(float*)(ptr + offset) = value; } else { *(uint*)(ptr + offset) = ReverseBytes(*(uint*)(&value)); } } } public unsafe void PutDouble(int offset, double value) { AssertOffsetAndLength(offset, sizeof(double)); fixed (byte* ptr = _buffer) { if (BitConverter.IsLittleEndian) { *(double*)(ptr + offset) = value; } else { *(ulong*)(ptr + offset) = ReverseBytes(*(ulong*)(ptr + offset)); } } } #else // !UNSAFE_BYTEBUFFER // Slower versions of Put* for when unsafe code is not allowed. public void PutShort(int offset, short value) { AssertOffsetAndLength(offset, sizeof(short)); WriteLittleEndian(offset, sizeof(short), (ulong)value); } public void PutUshort(int offset, ushort value) { AssertOffsetAndLength(offset, sizeof(ushort)); WriteLittleEndian(offset, sizeof(ushort), (ulong)value); } public void PutInt(int offset, int value) { AssertOffsetAndLength(offset, sizeof(int)); WriteLittleEndian(offset, sizeof(int), (ulong)value); } public void PutUint(int offset, uint value) { AssertOffsetAndLength(offset, sizeof(uint)); WriteLittleEndian(offset, sizeof(uint), (ulong)value); } public void PutLong(int offset, long value) { AssertOffsetAndLength(offset, sizeof(long)); WriteLittleEndian(offset, sizeof(long), (ulong)value); } public void PutUlong(int offset, ulong value) { AssertOffsetAndLength(offset, sizeof(ulong)); WriteLittleEndian(offset, sizeof(ulong), value); } public void PutFloat(int offset, float value) { AssertOffsetAndLength(offset, sizeof(float)); floathelper[0] = value; Buffer.BlockCopy(floathelper, 0, inthelper, 0, sizeof(float)); WriteLittleEndian(offset, sizeof(float), (ulong)inthelper[0]); } public void PutDouble(int offset, double value) { AssertOffsetAndLength(offset, sizeof(double)); doublehelper[0] = value; Buffer.BlockCopy(doublehelper, 0, ulonghelper, 0, sizeof(double)); WriteLittleEndian(offset, sizeof(double), ulonghelper[0]); } #endif // UNSAFE_BYTEBUFFER public sbyte GetSbyte(int index) { AssertOffsetAndLength(index, sizeof(sbyte)); return (sbyte)_buffer[index]; } public byte Get(int index) { AssertOffsetAndLength(index, sizeof(byte)); return _buffer[index]; } #if UNSAFE_BYTEBUFFER // Unsafe but more efficient versions of Get*. public short GetShort(int offset) { return (short)GetUshort(offset); } public unsafe ushort GetUshort(int offset) { AssertOffsetAndLength(offset, sizeof(ushort)); fixed (byte* ptr = _buffer) { return BitConverter.IsLittleEndian ? *(ushort*)(ptr + offset) : ReverseBytes(*(ushort*)(ptr + offset)); } } public int GetInt(int offset) { return (int)GetUint(offset); } public unsafe uint GetUint(int offset) { AssertOffsetAndLength(offset, sizeof(uint)); fixed (byte* ptr = _buffer) { return BitConverter.IsLittleEndian ? *(uint*)(ptr + offset) : ReverseBytes(*(uint*)(ptr + offset)); } } public long GetLong(int offset) { return (long)GetUlong(offset); } public unsafe ulong GetUlong(int offset) { AssertOffsetAndLength(offset, sizeof(ulong)); fixed (byte* ptr = _buffer) { return BitConverter.IsLittleEndian ? *(ulong*)(ptr + offset) : ReverseBytes(*(ulong*)(ptr + offset)); } } public unsafe float GetFloat(int offset) { AssertOffsetAndLength(offset, sizeof(float)); fixed (byte* ptr = _buffer) { if (BitConverter.IsLittleEndian) { return *(float*)(ptr + offset); } else { uint uvalue = ReverseBytes(*(uint*)(ptr + offset)); return *(float*)(&uvalue); } } } public unsafe double GetDouble(int offset) { AssertOffsetAndLength(offset, sizeof(double)); fixed (byte* ptr = _buffer) { if (BitConverter.IsLittleEndian) { return *(double*)(ptr + offset); } else { ulong uvalue = ReverseBytes(*(ulong*)(ptr + offset)); return *(double*)(&uvalue); } } } #else // !UNSAFE_BYTEBUFFER // Slower versions of Get* for when unsafe code is not allowed. public short GetShort(int index) { return (short)ReadLittleEndian(index, sizeof(short)); } public ushort GetUshort(int index) { return (ushort)ReadLittleEndian(index, sizeof(ushort)); } public int GetInt(int index) { return (int)ReadLittleEndian(index, sizeof(int)); } public uint GetUint(int index) { return (uint)ReadLittleEndian(index, sizeof(uint)); } public long GetLong(int index) { return (long)ReadLittleEndian(index, sizeof(long)); } public ulong GetUlong(int index) { return ReadLittleEndian(index, sizeof(ulong)); } public float GetFloat(int index) { int i = (int)ReadLittleEndian(index, sizeof(float)); inthelper[0] = i; Buffer.BlockCopy(inthelper, 0, floathelper, 0, sizeof(float)); return floathelper[0]; } public double GetDouble(int index) { ulong i = ReadLittleEndian(index, sizeof(double)); // There's Int64Bits To Double but it uses unsafe code internally. ulonghelper[0] = i; Buffer.BlockCopy(ulonghelper, 0, doublehelper, 0, sizeof(double)); return doublehelper[0]; } #endif // UNSAFE_BYTEBUFFER } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoad.Business.ERLevel { /// <summary> /// A09Level11111Child (editable child object).<br/> /// This is a generated base class of <see cref="A09Level11111Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="A08Level1111"/> collection. /// </remarks> [Serializable] public partial class A09Level11111Child : BusinessBase<A09Level11111Child> { #region State Fields [NotUndoable] [NonSerialized] internal int cNarentID1 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1_1_1 Child Name.</value> public string Level_1_1_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="A09Level11111Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="A09Level11111Child"/> object.</returns> internal static A09Level11111Child NewA09Level11111Child() { return DataPortal.CreateChild<A09Level11111Child>(); } /// <summary> /// Factory method. Loads a <see cref="A09Level11111Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="A09Level11111Child"/> object.</returns> internal static A09Level11111Child GetA09Level11111Child(SafeDataReader dr) { A09Level11111Child obj = new A09Level11111Child(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="A09Level11111Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private A09Level11111Child() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="A09Level11111Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="A09Level11111Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_Child_Name")); cNarentID1 = dr.GetInt32("CNarentID1"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="A09Level11111Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(A08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddA09Level11111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="A09Level11111Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(A08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateA09Level11111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="A09Level11111Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(A08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteA09Level11111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/* * SETTE - Symbolic Execution based Test Tool Evaluator * * SETTE is a tool to help the evaluation and comparison of symbolic execution * based test input generator tools. * * Budapest University of Technology and Economics (BME) * * Authors: Lajos Cseppento <lajos.cseppento@inf.mit.bme.hu>, Zoltan Micskei * <micskeiz@mit.bme.hu> * * Copyright 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ using System; namespace BME.MIT.SETTE.Library { public static class L2_Strings { //@SetteRequiredStatementCoverage(value = 80) public static int equality(String s) { if (s == null) { return -1; } else if (s.Equals("test")) { return 1; } else if (s.Equals("TeStInG")) { return 2; } else if (s.Equals("test") && s.Equals("TeStInG")) { // impossible throw new Exception(); } else { return 0; } } //@SetteRequiredStatementCoverage(value = 80) public static int equalityIgnoreCase(String s) { if (s == null) { return -1; } else if (String.Compare(s, "test", true) == 0) { return 1; } else if (String.Compare(s, "TeStInG", true) == 0) { return 2; } else if (String.Compare(s, "test", true) == 0 && String.Compare(s, "TeStInG", true) == 0) { // impossible throw new Exception(); } else { return 0; } } public static String add(String a, String b) { if (a == null && b == null) { return "both null"; } else if (a == null) { return "a null"; } else if (b == null) { return "b null"; } else { return a + b; } } //@SetteRequiredStatementCoverage(value = 83) public static int addWithCondition(String a, String b) { if (a == null && b == null) { return 0; } else if (a == null) { return -1; } else if (b == null) { return -2; } else if ((a + b).Equals("ab") && a.Equals("a")) { return 2; } else if ((a + b).Equals("ab")) { return 1; } else if ((a + b).Equals("ab") && a.Equals("c")) { // impossible throw new Exception(); } else { return -3; } } //@SetteRequiredStatementCoverage(value = 75) public static int length(String s) { if (s == null) { return -1; } else if (s.Length == 10) { return 1; } else if (s.Length == 5 && s.Length == 10) { // impossible branch throw new Exception(); } else { return 0; } } //@SetteRequiredStatementCoverage(value = 75) public static int charAt(String s) { if (s == null) { return -1; } else if (s[10] == 'X') { return 1; } else if (s[10] == 'X' && s[10] == 'Y') { // impossible branch throw new Exception(); } else { return 0; } } //@SetteRequiredStatementCoverage(value = 75) public static int regionEquality(String s) { if (s == null) { return -1; } else if (String.Compare(s, 10, "part", 0, 4, false) == 0) { return 1; } else if (String.Compare(s, 10, "part", 0, 4, false) == 0 && String.Compare(s, 10, "test", 0, 4, false) == 0) { // impossible branch throw new Exception(); } else { return 0; } } //@SetteRequiredStatementCoverage(value = 80) public static int compareTo(String s) { if (s == null) { return -1; } else if (s.CompareTo("abcdd") > 0 && s.CompareTo("abcdf") < 0) { return 1; } else if (s.CompareTo("efghh") > 0 && s.CompareTo("efghj") < 0) { return 2; } else if (s.CompareTo("bbb") > 0 && s.CompareTo("aaa") < 0) { // impossible branch throw new Exception(); } else { return 0; } } //@SetteRequiredStatementCoverage(value = 80) public static int compareToIgnoreCase(String s) { if (s == null) { return -1; } else if (String.Compare(s, "abcdd", true) > 0 && String.Compare(s, "abcdf", true) < 0) { return 1; } else if (String.Compare(s, "EfGhH", true) > 0 && String.Compare(s, "eFgHj", true) < 0) { return 2; } else if (String.Compare(s, "bbb", true) > 0 && String.Compare(s, "aaa", true) < 0) { // impossible branch throw new Exception(); } else { return 0; } } public static int startsEnds(String s) { if (s == null) { return -1; } else if (s.StartsWith("test")) { if (s.EndsWith("error")) { return 1; } else { return 2; } } else { return 0; } } //@SetteRequiredStatementCoverage(value = 75) public static int indexOf(String s) { if (s == null) { return -1; } else if (s.IndexOf("test") == 0 && s.IndexOf("test", 1) == 10 && s.LastIndexOf("test") == 20) { return 1; } else if (s.IndexOf("test") == 0 && s.IndexOf("test", 1) == 1) { // impossible branch throw new Exception(); } else { return 0; } } //@SetteRequiredStatementCoverage(value = 75) public static int substring(String s) { if (s == null) { return -1; } else if (s.Substring(0, 2).Equals("ab") && (s.Substring(6, 8).Equals("xy"))) { return 1; } else if (s.Substring(0, 2).Equals("ab") && s.Substring(1, 3).Equals("xy")) { // impossible branch throw new Exception(); } else { return 0; } } } }
using System; using System.Collections; using System.IO; using PlayFab.Json; using PlayFab.SharedModels; using UnityEngine; #if UNITY_5_4_OR_NEWER using UnityEngine.Networking; #else using UnityEngine.Experimental.Networking; #endif #if !UNITY_WSA && !UNITY_WP8 using Ionic.Zlib; #endif namespace PlayFab.Internal { public class PlayFabWww : IPlayFabTransportPlugin { private bool _isInitialized = false; private int _pendingWwwMessages = 0; public string AuthKey { get; set; } public string EntityToken { get; set; } public bool IsInitialized { get { return _isInitialized; } } public void Initialize() { _isInitialized = true; } public void Update() { } public void OnDestroy() { } public void SimpleGetCall(string fullUrl, Action<byte[]> successCallback, Action<string> errorCallback) { PlayFabHttp.instance.StartCoroutine(SimpleCallCoroutine(fullUrl, null, successCallback, errorCallback)); } public void SimplePutCall(string fullUrl, byte[] payload, Action successCallback, Action<string> errorCallback) { PlayFabHttp.instance.StartCoroutine(SimpleCallCoroutine(fullUrl, payload, (result) => { successCallback(); }, errorCallback)); } private static IEnumerator SimpleCallCoroutine(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback) { if (payload == null) { var www = new WWW(fullUrl); yield return www; if (!string.IsNullOrEmpty(www.error)) errorCallback(www.error); else successCallback(www.bytes); } else { var putRequest = UnityWebRequest.Put(fullUrl, payload); #if UNITY_2017_2_OR_NEWER putRequest.chunkedTransfer = false; // can be removed after Unity's PUT will be more stable putRequest.SendWebRequest(); #else putRequest.Send(); #endif #if !UNITY_WEBGL while (putRequest.uploadProgress < 1 && putRequest.downloadProgress < 1) { yield return 1; } #else while (!putRequest.isDone) { yield return 1; } #endif if (!string.IsNullOrEmpty(putRequest.error)) errorCallback(putRequest.error); else successCallback(null); } } public void MakeApiCall(object reqContainerObj) { CallRequestContainer reqContainer = (CallRequestContainer)reqContainerObj; reqContainer.RequestHeaders["Content-Type"] = "application/json"; #if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL if (PlayFabSettings.CompressApiData) { reqContainer.RequestHeaders["Content-Encoding"] = "GZIP"; reqContainer.RequestHeaders["Accept-Encoding"] = "GZIP"; using (var stream = new MemoryStream()) { using (var zipstream = new GZipStream(stream, CompressionMode.Compress, Ionic.Zlib.CompressionLevel.BestCompression)) { zipstream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length); } reqContainer.Payload = stream.ToArray(); } } #endif //Debug.LogFormat("Posting {0} to Url: {1}", req.Trim(), url); var www = new WWW(reqContainer.FullUrl, reqContainer.Payload, reqContainer.RequestHeaders); #if PLAYFAB_REQUEST_TIMING var stopwatch = System.Diagnostics.Stopwatch.StartNew(); #endif // Start the www corouting to Post, and get a response or error which is then passed to the callbacks. Action<string> wwwSuccessCallback = (response) => { try { #if PLAYFAB_REQUEST_TIMING var startTime = DateTime.UtcNow; #endif var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer); var httpResult = serializer.DeserializeObject<HttpResponseObject>(response); if (httpResult.code == 200) { // We have a good response from the server reqContainer.JsonResponse = serializer.SerializeObject(httpResult.data); reqContainer.DeserializeResultJson(); reqContainer.ApiResult.Request = reqContainer.ApiRequest; reqContainer.ApiResult.CustomData = reqContainer.CustomData; PlayFabHttp.instance.OnPlayFabApiResult(reqContainer.ApiResult); #if !DISABLE_PLAYFABCLIENT_API PlayFabDeviceUtil.OnPlayFabLogin(reqContainer.ApiResult); #endif try { PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post); } catch (Exception e) { Debug.LogException(e); } #if PLAYFAB_REQUEST_TIMING stopwatch.Stop(); var timing = new PlayFabHttp.RequestTiming { StartTimeUtc = startTime, ApiEndpoint = reqContainer.ApiEndpoint, WorkerRequestMs = (int)stopwatch.ElapsedMilliseconds, MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds }; PlayFabHttp.SendRequestTiming(timing); #endif try { reqContainer.InvokeSuccessCallback(); } catch (Exception e) { Debug.LogException(e); } } else { if (reqContainer.ErrorCallback != null) { reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, response, reqContainer.CustomData); PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error); reqContainer.ErrorCallback(reqContainer.Error); } } } catch (Exception e) { Debug.LogException(e); } }; Action<string> wwwErrorCallback = (errorCb) => { reqContainer.JsonResponse = errorCb; if (reqContainer.ErrorCallback != null) { reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, reqContainer.JsonResponse, reqContainer.CustomData); PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error); reqContainer.ErrorCallback(reqContainer.Error); } }; PlayFabHttp.instance.StartCoroutine(PostPlayFabApiCall(www, wwwSuccessCallback, wwwErrorCallback)); } private IEnumerator PostPlayFabApiCall(WWW www, Action<string> wwwSuccessCallback, Action<string> wwwErrorCallback) { yield return www; if (!string.IsNullOrEmpty(www.error)) { wwwErrorCallback(www.error); } else { try { byte[] responseBytes = www.bytes; bool isGzipCompressed = responseBytes != null && responseBytes[0] == 31 && responseBytes[1] == 139; string responseText = "Unexpected error: cannot decompress GZIP stream."; if (!isGzipCompressed && responseBytes != null) responseText = System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length); #if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL if (isGzipCompressed) { var stream = new MemoryStream(responseBytes); using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress, false)) { var buffer = new byte[4096]; using (var output = new MemoryStream()) { int read; while ((read = gZipStream.Read(buffer, 0, buffer.Length)) > 0) output.Write(buffer, 0, read); output.Seek(0, SeekOrigin.Begin); var streamReader = new StreamReader(output); var jsonResponse = streamReader.ReadToEnd(); //Debug.Log(jsonResponse); wwwSuccessCallback(jsonResponse); } } } else #endif { wwwSuccessCallback(responseText); } } catch (Exception e) { wwwErrorCallback("Unhandled error in PlayFabWWW: " + e); } } www.Dispose(); } public int GetPendingMessages() { return _pendingWwwMessages; } } }
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 WebApiApplication.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; } } }
// Copyright (c) 2013-2014 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file). // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE using System; using System.Runtime.InteropServices; namespace SharpNav { /// <summary> /// Represents a voxel span in a <see cref="CompactHeightfield"/>. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct CompactSpan { /// <summary> /// The span minimum. /// </summary> public int Minimum; /// <summary> /// The number of voxels contained in the span. /// </summary> public int Height; /// <summary> /// A byte representing the index of the connected span in the cell directly to the west. /// </summary> public byte ConnectionWest; /// <summary> /// A byte representing the index of the connected span in the cell directly to the north. /// </summary> public byte ConnectionNorth; /// <summary> /// A byte representing the index of the connected span in the cell directly to the east. /// </summary> public byte ConnectionEast; /// <summary> /// A byte representing the index of the connected span in the cell directly to the south. /// </summary> public byte ConnectionSouth; /// <summary> /// The region the span belongs to. /// </summary> public RegionId Region; /// <summary> /// A constant that means there is no connection for the values <see cref="ConnectionWest"/>, /// <see cref="ConnectionNorth"/>, <see cref="ConnectionEast"/>, and <see cref="ConnectionSouth"/>. /// </summary> private const byte NotConnected = 0xff; /// <summary> /// Initializes a new instance of the <see cref="CompactSpan"/> struct. /// </summary> /// <param name="minimum">The span minimum.</param> /// <param name="height">The number of voxels the span contains.</param> public CompactSpan(int minimum, int height) { this.Minimum = minimum; this.Height = height; this.ConnectionWest = NotConnected; this.ConnectionNorth = NotConnected; this.ConnectionEast = NotConnected; this.ConnectionSouth = NotConnected; this.Region = RegionId.Null; } /// <summary> /// Gets a value indicating whether the span has an upper bound or goes to "infinity". /// </summary> public bool HasUpperBound { get { return Height != int.MaxValue; } } /// <summary> /// Gets the upper bound of the span. /// </summary> public int Maximum { get { return Minimum + Height; } } /// <summary> /// Gets the number of connections the current CompactSpan has with its neighbors. /// </summary> public int ConnectionCount { get { int count = 0; if (ConnectionWest != NotConnected) count++; if (ConnectionNorth != NotConnected) count++; if (ConnectionEast != NotConnected) count++; if (ConnectionSouth != NotConnected) count++; return count; } } /// <summary> /// If two CompactSpans overlap, find the minimum of the new overlapping CompactSpans. /// </summary> /// <param name="left">The first CompactSpan</param> /// <param name="right">The second CompactSpan</param> /// <param name="min">The minimum of the overlapping ComapctSpans</param> public static void OverlapMin(ref CompactSpan left, ref CompactSpan right, out int min) { min = Math.Max(left.Minimum, right.Minimum); } /// <summary> /// If two CompactSpans overlap, find the maximum of the new overlapping CompactSpans. /// </summary> /// <param name="left">The first CompactSpan</param> /// <param name="right">The second CompactSpan</param> /// <param name="max">The maximum of the overlapping CompactSpans</param> public static void OverlapMax(ref CompactSpan left, ref CompactSpan right, out int max) { if (left.Height == int.MaxValue) { if (right.Height == int.MaxValue) max = int.MaxValue; else max = right.Minimum + right.Height; } else if (right.Height == int.MaxValue) max = left.Minimum + left.Height; else max = Math.Min(left.Minimum + left.Height, right.Minimum + right.Height); } /// <summary> /// Creates a <see cref="CompactSpan"/> from a minimum boundary and a maximum boundary. /// </summary> /// <param name="min">The minimum.</param> /// <param name="max">The maximum.</param> /// <returns>A <see cref="CompactSpan"/>.</returns> public static CompactSpan FromMinMax(int min, int max) { CompactSpan s; FromMinMax(min, max, out s); return s; } /// <summary> /// Creates a <see cref="CompactSpan"/> from a minimum boundary and a maximum boundary. /// </summary> /// <param name="min">The minimum.</param> /// <param name="max">The maximum.</param> /// <param name="span">A <see cref="CompactSpan"/>.</param> public static void FromMinMax(int min, int max, out CompactSpan span) { span.Minimum = min; span.Height = max - min; span.ConnectionWest = NotConnected; span.ConnectionNorth = NotConnected; span.ConnectionEast = NotConnected; span.ConnectionSouth = NotConnected; span.Region = RegionId.Null; } /// <summary> /// Sets connection data to a span contained in a neighboring cell. /// </summary> /// <param name="dir">The direction of the cell.</param> /// <param name="i">The index of the span in the neighboring cell.</param> /// <param name="s">The <see cref="CompactSpan"/> to set the data for.</param> public static void SetConnection(Direction dir, int i, ref CompactSpan s) { if (i >= NotConnected) throw new ArgumentOutOfRangeException("Index of connecting span is too high to be stored. Try increasing cell height.", "i"); switch (dir) { case Direction.West: s.ConnectionWest = (byte)i; break; case Direction.North: s.ConnectionNorth = (byte)i; break; case Direction.East: s.ConnectionEast = (byte)i; break; case Direction.South: s.ConnectionSouth = (byte)i; break; default: throw new ArgumentException("dir isn't a valid Direction."); } } /// <summary> /// Un-sets connection data from a neighboring cell. /// </summary> /// <param name="dir">The direction of the cell.</param> /// <param name="s">The <see cref="CompactSpan"/> to set the data for.</param> public static void UnsetConnection(Direction dir, ref CompactSpan s) { switch (dir) { case Direction.West: s.ConnectionWest = NotConnected; break; case Direction.North: s.ConnectionNorth = NotConnected; break; case Direction.East: s.ConnectionEast = NotConnected; break; case Direction.South: s.ConnectionSouth = NotConnected; break; default: throw new ArgumentException("dir isn't a valid Direction."); } } /// <summary> /// Gets the connection data for a neighboring cell in a specified direction. /// </summary> /// <param name="s">The <see cref="CompactSpan"/> to get the connection data from.</param> /// <param name="dir">The direction.</param> /// <returns>The index of the span in the neighboring cell.</returns> public static int GetConnection(ref CompactSpan s, Direction dir) { switch (dir) { case Direction.West: return s.ConnectionWest; case Direction.North: return s.ConnectionNorth; case Direction.East: return s.ConnectionEast; case Direction.South: return s.ConnectionSouth; default: throw new ArgumentException("dir isn't a valid Direction."); } } /// <summary> /// Gets the connection data for a neighboring call in a specified direction. /// </summary> /// <param name="dir">The direction.</param> /// <returns>The index of the span in the neighboring cell.</returns> public int GetConnection(Direction dir) { return GetConnection(ref this, dir); } /// <summary> /// Gets a value indicating whether the span is connected to another span in a specified direction. /// </summary> /// <param name="dir">The direction.</param> /// <returns>A value indicating whether the specified direction has a connected span.</returns> public bool IsConnected(Direction dir) { switch (dir) { case Direction.West: return ConnectionWest != NotConnected; case Direction.North: return ConnectionNorth != NotConnected; case Direction.East: return ConnectionEast != NotConnected; case Direction.South: return ConnectionSouth != NotConnected; default: throw new ArgumentException("dir isn't a valid Direction."); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; namespace OpenSim.Framework.Serialization.External { /// <summary> /// Serialize and deserialize user inventory items as an external format. /// </summary> public class UserInventoryItemSerializer { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static Dictionary<string, Action<InventoryItemBase, XmlTextReader>> m_InventoryItemXmlProcessors = new Dictionary<string, Action<InventoryItemBase, XmlTextReader>>(); #region InventoryItemBase Processor initialization static UserInventoryItemSerializer() { m_InventoryItemXmlProcessors.Add("Name", ProcessName); m_InventoryItemXmlProcessors.Add("ID", ProcessID); m_InventoryItemXmlProcessors.Add("InvType", ProcessInvType); m_InventoryItemXmlProcessors.Add("CreatorUUID", ProcessCreatorUUID); m_InventoryItemXmlProcessors.Add("CreatorID", ProcessCreatorID); m_InventoryItemXmlProcessors.Add("CreatorData", ProcessCreatorData); m_InventoryItemXmlProcessors.Add("CreationDate", ProcessCreationDate); m_InventoryItemXmlProcessors.Add("Owner", ProcessOwner); m_InventoryItemXmlProcessors.Add("Description", ProcessDescription); m_InventoryItemXmlProcessors.Add("AssetType", ProcessAssetType); m_InventoryItemXmlProcessors.Add("AssetID", ProcessAssetID); m_InventoryItemXmlProcessors.Add("SaleType", ProcessSaleType); m_InventoryItemXmlProcessors.Add("SalePrice", ProcessSalePrice); m_InventoryItemXmlProcessors.Add("BasePermissions", ProcessBasePermissions); m_InventoryItemXmlProcessors.Add("CurrentPermissions", ProcessCurrentPermissions); m_InventoryItemXmlProcessors.Add("EveryOnePermissions", ProcessEveryOnePermissions); m_InventoryItemXmlProcessors.Add("NextPermissions", ProcessNextPermissions); m_InventoryItemXmlProcessors.Add("Flags", ProcessFlags); m_InventoryItemXmlProcessors.Add("GroupID", ProcessGroupID); m_InventoryItemXmlProcessors.Add("GroupOwned", ProcessGroupOwned); } #endregion InventoryItemBase Processor initialization #region InventoryItemBase Processors private static void ProcessAssetID(InventoryItemBase item, XmlTextReader reader) { item.AssetID = Util.ReadUUID(reader, "AssetID"); } private static void ProcessAssetType(InventoryItemBase item, XmlTextReader reader) { item.AssetType = reader.ReadElementContentAsInt("AssetType", String.Empty); } private static void ProcessBasePermissions(InventoryItemBase item, XmlTextReader reader) { item.BasePermissions = (uint)reader.ReadElementContentAsInt("BasePermissions", String.Empty); } private static void ProcessCreationDate(InventoryItemBase item, XmlTextReader reader) { item.CreationDate = reader.ReadElementContentAsInt("CreationDate", String.Empty); } private static void ProcessCreatorData(InventoryItemBase item, XmlTextReader reader) { item.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty); } private static void ProcessCreatorID(InventoryItemBase item, XmlTextReader reader) { // when it exists, this overrides the previous item.CreatorId = reader.ReadElementContentAsString("CreatorID", String.Empty); } private static void ProcessCreatorUUID(InventoryItemBase item, XmlTextReader reader) { item.CreatorId = reader.ReadElementContentAsString("CreatorUUID", String.Empty); } private static void ProcessCurrentPermissions(InventoryItemBase item, XmlTextReader reader) { item.CurrentPermissions = (uint)reader.ReadElementContentAsInt("CurrentPermissions", String.Empty); } private static void ProcessDescription(InventoryItemBase item, XmlTextReader reader) { item.Description = reader.ReadElementContentAsString("Description", String.Empty); } private static void ProcessEveryOnePermissions(InventoryItemBase item, XmlTextReader reader) { item.EveryOnePermissions = (uint)reader.ReadElementContentAsInt("EveryOnePermissions", String.Empty); } private static void ProcessFlags(InventoryItemBase item, XmlTextReader reader) { item.Flags = (uint)reader.ReadElementContentAsInt("Flags", String.Empty); } private static void ProcessGroupID(InventoryItemBase item, XmlTextReader reader) { item.GroupID = Util.ReadUUID(reader, "GroupID"); } private static void ProcessGroupOwned(InventoryItemBase item, XmlTextReader reader) { item.GroupOwned = Util.ReadBoolean(reader); } private static void ProcessID(InventoryItemBase item, XmlTextReader reader) { item.ID = Util.ReadUUID(reader, "ID"); } private static void ProcessInvType(InventoryItemBase item, XmlTextReader reader) { item.InvType = reader.ReadElementContentAsInt("InvType", String.Empty); } private static void ProcessName(InventoryItemBase item, XmlTextReader reader) { item.Name = reader.ReadElementContentAsString("Name", String.Empty); } private static void ProcessNextPermissions(InventoryItemBase item, XmlTextReader reader) { item.NextPermissions = (uint)reader.ReadElementContentAsInt("NextPermissions", String.Empty); } private static void ProcessOwner(InventoryItemBase item, XmlTextReader reader) { item.Owner = Util.ReadUUID(reader, "Owner"); } private static void ProcessSalePrice(InventoryItemBase item, XmlTextReader reader) { item.SalePrice = reader.ReadElementContentAsInt("SalePrice", String.Empty); } private static void ProcessSaleType(InventoryItemBase item, XmlTextReader reader) { item.SaleType = (byte)reader.ReadElementContentAsInt("SaleType", String.Empty); } #endregion InventoryItemBase Processors /// <summary> /// Deserialize item /// </summary> /// <param name="serializedSettings"></param> /// <returns></returns> /// <exception cref="System.Xml.XmlException"></exception> public static InventoryItemBase Deserialize(byte[] serialization) { return Deserialize(Encoding.ASCII.GetString(serialization, 0, serialization.Length)); } /// <summary> /// Deserialize settings /// </summary> /// <param name="serializedSettings"></param> /// <returns></returns> /// <exception cref="System.Xml.XmlException"></exception> public static InventoryItemBase Deserialize(string serialization) { InventoryItemBase item = new InventoryItemBase(); using (XmlTextReader reader = new XmlTextReader(new StringReader(serialization))) { reader.ReadStartElement("InventoryItem"); ExternalRepresentationUtils.ExecuteReadProcessors<InventoryItemBase>( item, m_InventoryItemXmlProcessors, reader); reader.ReadEndElement(); // InventoryItem } //m_log.DebugFormat("[XXX]: parsed InventoryItemBase {0} - {1}", obj.Name, obj.UUID); return item; } public static string Serialize(InventoryItemBase inventoryItem, Dictionary<string, object> options, IUserAccountService userAccountService) { StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("InventoryItem"); writer.WriteStartElement("Name"); writer.WriteString(inventoryItem.Name); writer.WriteEndElement(); writer.WriteStartElement("ID"); writer.WriteString(inventoryItem.ID.ToString()); writer.WriteEndElement(); writer.WriteStartElement("InvType"); writer.WriteString(inventoryItem.InvType.ToString()); writer.WriteEndElement(); writer.WriteStartElement("CreatorUUID"); writer.WriteString(OspResolver.MakeOspa(inventoryItem.CreatorIdAsUuid, userAccountService)); writer.WriteEndElement(); writer.WriteStartElement("CreationDate"); writer.WriteString(inventoryItem.CreationDate.ToString()); writer.WriteEndElement(); writer.WriteStartElement("Owner"); writer.WriteString(inventoryItem.Owner.ToString()); writer.WriteEndElement(); writer.WriteStartElement("Description"); writer.WriteString(inventoryItem.Description); writer.WriteEndElement(); writer.WriteStartElement("AssetType"); writer.WriteString(inventoryItem.AssetType.ToString()); writer.WriteEndElement(); writer.WriteStartElement("AssetID"); writer.WriteString(inventoryItem.AssetID.ToString()); writer.WriteEndElement(); writer.WriteStartElement("SaleType"); writer.WriteString(inventoryItem.SaleType.ToString()); writer.WriteEndElement(); writer.WriteStartElement("SalePrice"); writer.WriteString(inventoryItem.SalePrice.ToString()); writer.WriteEndElement(); writer.WriteStartElement("BasePermissions"); writer.WriteString(inventoryItem.BasePermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("CurrentPermissions"); writer.WriteString(inventoryItem.CurrentPermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("EveryOnePermissions"); writer.WriteString(inventoryItem.EveryOnePermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("NextPermissions"); writer.WriteString(inventoryItem.NextPermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("Flags"); writer.WriteString(inventoryItem.Flags.ToString()); writer.WriteEndElement(); writer.WriteStartElement("GroupID"); writer.WriteString(inventoryItem.GroupID.ToString()); writer.WriteEndElement(); writer.WriteStartElement("GroupOwned"); writer.WriteString(inventoryItem.GroupOwned.ToString()); writer.WriteEndElement(); if (options.ContainsKey("creators") && !string.IsNullOrEmpty(inventoryItem.CreatorData)) writer.WriteElementString("CreatorData", inventoryItem.CreatorData); else if (options.ContainsKey("home")) { if (userAccountService != null) { UserAccount account = userAccountService.GetUserAccount(UUID.Zero, inventoryItem.CreatorIdAsUuid); if (account != null) { string creatorData = ExternalRepresentationUtils.CalcCreatorData((string)options["home"], inventoryItem.CreatorIdAsUuid, account.FirstName + " " + account.LastName); writer.WriteElementString("CreatorData", creatorData); } writer.WriteElementString("CreatorID", inventoryItem.CreatorId); } } writer.WriteEndElement(); writer.Close(); sw.Close(); return sw.ToString(); } } }
// <copyright file="BiCgStab.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2013 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra.Solvers; using MathNet.Numerics.Properties; namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// A Bi-Conjugate Gradient stabilized iterative matrix solver. /// </summary> /// <remarks> /// <para> /// The Bi-Conjugate Gradient Stabilized (BiCGStab) solver is an 'improvement' /// of the standard Conjugate Gradient (CG) solver. Unlike the CG solver the /// BiCGStab can be used on non-symmetric matrices. <br/> /// Note that much of the success of the solver depends on the selection of the /// proper preconditioner. /// </para> /// <para> /// The Bi-CGSTAB algorithm was taken from: <br/> /// Templates for the solution of linear systems: Building blocks /// for iterative methods /// <br/> /// Richard Barrett, Michael Berry, Tony F. Chan, James Demmel, /// June M. Donato, Jack Dongarra, Victor Eijkhout, Roldan Pozo, /// Charles Romine and Henk van der Vorst /// <br/> /// Url: <a href="http://www.netlib.org/templates/Templates.html">http://www.netlib.org/templates/Templates.html</a> /// <br/> /// Algorithm is described in Chapter 2, section 2.3.8, page 27 /// </para> /// <para> /// The example code below provides an indication of the possible use of the /// solver. /// </para> /// </remarks> public sealed class BiCgStab : IIterativeSolver<Complex> { /// <summary> /// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax /// </summary> /// <param name="matrix">Instance of the <see cref="Matrix"/> A.</param> /// <param name="residual">Residual values in <see cref="Vector"/>.</param> /// <param name="x">Instance of the <see cref="Vector"/> x.</param> /// <param name="b">Instance of the <see cref="Vector"/> b.</param> static void CalculateTrueResidual(Matrix<Complex> matrix, Vector<Complex> residual, Vector<Complex> x, Vector<Complex> b) { // -Ax = residual matrix.Multiply(x, residual); // Do not use residual = residual.Negate() because it creates another object residual.Multiply(-1, residual); // residual + b residual.Add(b, residual); } /// <summary> /// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the /// solution vector and x is the unknown vector. /// </summary> /// <param name="matrix">The coefficient <see cref="Matrix"/>, <c>A</c>.</param> /// <param name="input">The solution <see cref="Vector"/>, <c>b</c>.</param> /// <param name="result">The result <see cref="Vector"/>, <c>x</c>.</param> /// <param name="iterator">The iterator to use to control when to stop iterating.</param> /// <param name="preconditioner">The preconditioner to use for approximations.</param> public void Solve(Matrix<Complex> matrix, Vector<Complex> input, Vector<Complex> result, Iterator<Complex> iterator, IPreconditioner<Complex> preconditioner) { if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix"); } if (result.Count != input.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength); } if (input.Count != matrix.RowCount) { throw Matrix.DimensionsDontMatch<ArgumentException>(input, result); } if (iterator == null) { iterator = new Iterator<Complex>(); } if (preconditioner == null) { preconditioner = new UnitPreconditioner<Complex>(); } preconditioner.Initialize(matrix); // Compute r_0 = b - Ax_0 for some initial guess x_0 // In this case we take x_0 = vector // This is basically a SAXPY so it could be made a lot faster var residuals = new DenseVector(matrix.RowCount); CalculateTrueResidual(matrix, residuals, result, input); // Choose r~ (for example, r~ = r_0) var tempResiduals = residuals.Clone(); // create seven temporary vectors needed to hold temporary // coefficients. All vectors are mangled in each iteration. // These are defined here to prevent stressing the garbage collector var vecP = new DenseVector(residuals.Count); var vecPdash = new DenseVector(residuals.Count); var nu = new DenseVector(residuals.Count); var vecS = new DenseVector(residuals.Count); var vecSdash = new DenseVector(residuals.Count); var temp = new DenseVector(residuals.Count); var temp2 = new DenseVector(residuals.Count); // create some temporary double variables that are needed // to hold values in between iterations Complex currentRho = 0; Complex alpha = 0; Complex omega = 0; var iterationNumber = 0; while (iterator.DetermineStatus(iterationNumber, result, input, residuals) == IterationStatus.Continue) { // rho_(i-1) = r~^T r_(i-1) // dotproduct r~ and r_(i-1) var oldRho = currentRho; currentRho = tempResiduals.ConjugateDotProduct(residuals); // if (rho_(i-1) == 0) // METHOD FAILS // If rho is only 1 ULP from zero then we fail. if (currentRho.Real.AlmostEqualNumbersBetween(0, 1) && currentRho.Imaginary.AlmostEqualNumbersBetween(0, 1)) { // Rho-type breakdown throw new NumericalBreakdownException(); } if (iterationNumber != 0) { // beta_(i-1) = (rho_(i-1)/rho_(i-2))(alpha_(i-1)/omega(i-1)) var beta = (currentRho/oldRho)*(alpha/omega); // p_i = r_(i-1) + beta_(i-1)(p_(i-1) - omega_(i-1) * nu_(i-1)) nu.Multiply(-omega, temp); vecP.Add(temp, temp2); temp2.CopyTo(vecP); vecP.Multiply(beta, vecP); vecP.Add(residuals, temp2); temp2.CopyTo(vecP); } else { // p_i = r_(i-1) residuals.CopyTo(vecP); } // SOLVE Mp~ = p_i // M = preconditioner preconditioner.Approximate(vecP, vecPdash); // nu_i = Ap~ matrix.Multiply(vecPdash, nu); // alpha_i = rho_(i-1)/ (r~^T nu_i) = rho / dotproduct(r~ and nu_i) alpha = currentRho*1/tempResiduals.ConjugateDotProduct(nu); // s = r_(i-1) - alpha_i nu_i nu.Multiply(-alpha, temp); residuals.Add(temp, vecS); // Check if we're converged. If so then stop. Otherwise continue; // Calculate the temporary result. // Be careful not to change any of the temp vectors, except for // temp. Others will be used in the calculation later on. // x_i = x_(i-1) + alpha_i * p^_i + s^_i vecPdash.Multiply(alpha, temp); temp.Add(vecSdash, temp2); temp2.CopyTo(temp); temp.Add(result, temp2); temp2.CopyTo(temp); // Check convergence and stop if we are converged. if (iterator.DetermineStatus(iterationNumber, temp, input, vecS) != IterationStatus.Continue) { temp.CopyTo(result); // Calculate the true residual CalculateTrueResidual(matrix, residuals, result, input); // Now recheck the convergence if (iterator.DetermineStatus(iterationNumber, result, input, residuals) != IterationStatus.Continue) { // We're all good now. return; } // Continue the calculation iterationNumber++; continue; } // SOLVE Ms~ = s preconditioner.Approximate(vecS, vecSdash); // temp = As~ matrix.Multiply(vecSdash, temp); // omega_i = temp^T s / temp^T temp omega = temp.ConjugateDotProduct(vecS)/temp.ConjugateDotProduct(temp); // x_i = x_(i-1) + alpha_i p^ + omega_i s^ temp.Multiply(-omega, residuals); residuals.Add(vecS, temp2); temp2.CopyTo(residuals); vecSdash.Multiply(omega, temp); result.Add(temp, temp2); temp2.CopyTo(result); vecPdash.Multiply(alpha, temp); result.Add(temp, temp2); temp2.CopyTo(result); // for continuation it is necessary that omega_i != 0.0 // If omega is only 1 ULP from zero then we fail. if (omega.Real.AlmostEqualNumbersBetween(0, 1) && omega.Imaginary.AlmostEqualNumbersBetween(0, 1)) { // Omega-type breakdown throw new NumericalBreakdownException(); } if (iterator.DetermineStatus(iterationNumber, result, input, residuals) != IterationStatus.Continue) { // Recalculate the residuals and go round again. This is done to ensure that // we have the proper residuals. // The residual calculation based on omega_i * s can be off by a factor 10. So here // we calculate the real residual (which can be expensive) but we only do it if we're // sufficiently close to the finish. CalculateTrueResidual(matrix, residuals, result, input); } iterationNumber++; } } } }
////////////////////////////////////////////////////////////////////////// // Code Named: VG-Ripper // Function : Extracts Images posted on RiP forums and attempts to fetch // them to disk. // // This software is licensed under the MIT license. See license.txt for // details. // // Copyright (c) The Watcher // Partial Rights Reserved. // ////////////////////////////////////////////////////////////////////////// // This file is part of the RiP Ripper project base. using System; using System.Collections; using System.Web; using System.Net; using System.IO; using System.Text; using System.Threading; using System.Drawing; using System.Windows.Forms; namespace Ripper { using Ripper.Core.Components; using Ripper.Core.Objects; /// <summary> /// Worker class to get images from ImageHigh.com /// </summary> public class ImageHigh : ServiceTemplate { public ImageHigh(ref string sSavePath, ref string strURL, ref string thumbURL, ref string imageName, ref int imageNumber, ref Hashtable hashtable) : base(sSavePath, strURL, thumbURL, imageName, imageNumber, ref hashtable) { } protected override bool DoDownload() { string strImgURL = ImageLinkURL; if (EventTable.ContainsKey(strImgURL)) { return true; } string strFilePath = string.Empty; strFilePath = strImgURL.Substring(0, strImgURL.IndexOf("/", 8) + 1); int iStartIMG = 0; int iEndIMG = 0; iStartIMG = strImgURL.IndexOf("?id="); if (iStartIMG < 0) { return false; } iStartIMG += 4; iEndIMG = strImgURL.IndexOf(".jpg&path", iStartIMG); if (iEndIMG < 0) { return false; } strFilePath = strImgURL.Substring(iStartIMG, iEndIMG - iStartIMG); try { if (!Directory.Exists(SavePath)) Directory.CreateDirectory(SavePath); } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; return false; } strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath)); CacheObject CCObj = new CacheObject(); CCObj.IsDownloaded = false; CCObj.FilePath = strFilePath; CCObj.Url = strImgURL; try { EventTable.Add(strImgURL, CCObj); } catch (ThreadAbortException) { return true; } catch (Exception) { if (EventTable.ContainsKey(strImgURL)) { return false; } else { EventTable.Add(strImgURL, CCObj); } } string strIVPage = GetImageHostPage(ref strImgURL); if (strIVPage.Length < 10) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return false; } string strNewURL = string.Empty; strNewURL = strImgURL.Substring(0, strImgURL.IndexOf("/", 8) + 1); int iStartSRC = 0; int iEndSRC = 0; iStartSRC = strIVPage.IndexOf("<img src=\""); if (iStartSRC < 0) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return false; } iStartSRC += 10; iEndSRC = strIVPage.IndexOf("\" alt=\"Image Hosted By Imagehigh.com\"", iStartSRC); if (iEndSRC < 0) { return false; } strNewURL = strIVPage.Substring(iStartSRC, iEndSRC - iStartSRC); ////////////////////////////////////////////////////////////////////////// HttpWebRequest lHttpWebRequest; HttpWebResponse lHttpWebResponse; Stream lHttpWebResponseStream; //FileStream lFileStream = new FileStream(strFilePath, FileMode.Create); //int bytesRead; try { lHttpWebRequest = (HttpWebRequest)WebRequest.Create(strNewURL); lHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"; lHttpWebRequest.Headers.Add("Accept-Language: en-us,en;q=0.5"); lHttpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate"); lHttpWebRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"); lHttpWebRequest.Referer = strImgURL; lHttpWebRequest.Accept = "image/png,*/*;q=0.5"; lHttpWebRequest.KeepAlive = true; lHttpWebResponse = (HttpWebResponse)lHttpWebRequest.GetResponse(); lHttpWebResponseStream = lHttpWebRequest.GetResponse().GetResponseStream(); if (lHttpWebResponse.ContentType.IndexOf("image") < 0) { //if (lFileStream != null) // lFileStream.Close(); return false; } if (lHttpWebResponse.ContentType.ToLower() == "image/jpeg") strFilePath += ".jpg"; else if (lHttpWebResponse.ContentType.ToLower() == "image/gif") strFilePath += ".gif"; else if (lHttpWebResponse.ContentType.ToLower() == "image/png") strFilePath += ".png"; string NewAlteredPath = Utility.GetSuitableName(strFilePath); if (strFilePath != NewAlteredPath) { strFilePath = NewAlteredPath; ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; } lHttpWebResponseStream.Close(); System.Net.WebClient client = new WebClient(); client.Headers.Add("Accept-Language: en-us,en;q=0.5"); client.Headers.Add("Accept-Encoding: gzip,deflate"); client.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"); client.Headers.Add("Referer: " + strImgURL); client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"); client.DownloadFile(strNewURL, strFilePath); client.Dispose(); } catch (ThreadAbortException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return true; } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return true; } catch (WebException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return false; } ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true; //CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath; CacheController.Instance().LastPic =((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; return true; } ////////////////////////////////////////////////////////////////////////// } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; namespace Its.Log.Instrumentation.UnitTests { public class Widget<T> : Widget { public override void DoStuff() { using (Log.Enter(() => { })) { base.DoStuff(); } } } public class Widget { public Widget() { Name = "Default"; } public string Name { get; set; } public List<Part> Parts { get; set; } public virtual void DoStuff() { using (Log.Enter(() => { })) { Log.Write("Doing some stuff..."); } } public virtual void DoStuff(int widgetParam) { using (Log.Enter(() => new { widgetParam })) { Log.Write("Doing some stuff..."); } } public virtual void DoStuff(string widgetParam) { var activity = Log.Enter(() => new { widgetParam }); Log.Write("Doing some stuff..."); Log.Exit(activity); } public static void DoStuffStatically() { using (Log.Enter(() => { })) { Log.Write("Doing some stuff..."); } } public static void DoStuffStatically(string widgetStaticParam) { using (Log.Enter(() => new { widgetStaticParam })) { Log.Write("Doing some stuff..."); } } public void DoStuff(string inheritedWidgetParam, ref string outParam) { using (Log.Enter(() => new { inheritedWidgetParam })) { Log.Write("Doing some stuff..."); outParam = "Done doing stuff"; } } public void DoStuffThatThrows() { throw new InvalidOperationException("Why'd you call this method? You knew it was going to throw."); } } public class InheritedWidget : Widget { public override void DoStuff() { using (Log.Enter(() => { })) { Log.Write("Doing some stuff..."); } } public override void DoStuff(string inheritedWidgetParam) { using (Log.Enter(() => new { inheritedWidgetParam })) { Log.Write("Doing some stuff..."); } } } public class InheritedWidgetNoOverride : Widget { } public static class WidgetExtensions { private static Action actionField = () => { using (Log.Enter(() => { })) { } }; public static void ExtensionWithLoggingInLocallyScopedLambda(this Widget widget) { Action action = () => { using (Log.Enter(() => { })) { } }; action(); } public static void ExtensionWithLoggingInStaticallyScopedLambda(this Widget widget) { actionField(); } } public class Part { public string PartNumber { get; set; } public Widget Widget { get; set; } } public struct SomeStruct { public DateTime DateField; public DateTime DateProperty { get; set; } } public class SomethingWithLotsOfProperties { public DateTime DateProperty { get; set; } public string StringProperty { get; set; } public int IntProperty { get; set; } public bool BoolProperty { get; set; } public Uri UriProperty { get; set; } } public struct EntityId { public EntityId(string typeName, string id) : this() { TypeName = typeName; Id = id; } public string TypeName { get; private set; } public string Id { get; private set; } } public class Node { // ReSharper disable InconsistentNaming private string _id; // ReSharper restore InconsistentNaming // ReSharper disable ConvertToAutoProperty public string Id // ReSharper restore ConvertToAutoProperty { get { return _id; } set { _id = value; } } public IEnumerable<Node> Nodes { get; set; } public Node[] NodesArray { get; set; } internal string InternalId { get { return Id; } } } public class SomePropertyThrows { public string Fine { get { return "Fine"; } } public string NotOk { get { throw new Exception("not ok"); } } public string Ok { get { return "ok"; } } public string PerfectlyFine { get { return "PerfectlyFine"; } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions; using NuGet.Packaging; using NuGet.Test.Helpers; using Xunit; namespace NupkgWrench.Tests { public class CopySymbolsCommandTests { [Fact] public async Task GivenThatICopySymbolsVerifyFirstSymbolPackageUsed() { using (var workingDir = new TestFolder()) { // Arrange var log = new TestLogger(); var nuspec = new TestNuspec() { Id = "a", Version = "1.0.0" }; var nupkg = nuspec.CreateNupkg(); nupkg.Files.Clear(); nupkg.AddFile("lib/net45/a.dll"); var path = nupkg.Save(workingDir); var nuspecSymbols = new TestNuspec() { Id = "a", Version = "1.0.0", IsSymbolPackage = true }; var nupkgSymbols = nuspecSymbols.CreateNupkg(); nupkgSymbols.Files.Clear(); nupkgSymbols.AddFile("lib/net45/a.dll"); nupkgSymbols.AddFile("lib/net45/a.pdb"); nupkgSymbols.Save(workingDir); var nuspecSymbols2 = new TestNuspec() { Id = "a", Version = "1.0", IsSymbolPackage = true }; var nupkgSymbols2 = nuspecSymbols2.CreateNupkg(); nupkgSymbols2.Files.Clear(); nupkgSymbols2.AddFile("lib/net45/a.dll"); nupkgSymbols2.Save(workingDir); // Act var before = GetNupkgFiles(path.FullName); var exitCode = await Program.MainCore(new[] { "files", "copysymbols", workingDir }, log); var after = GetNupkgFiles(path.FullName); var diff = new SortedSet<string>(after, StringComparer.OrdinalIgnoreCase); diff.ExceptWith(before); // Assert exitCode.Should().Be(0, log.GetMessages()); after.Should().Contain("lib/net45/a.dll"); diff.ShouldBeEquivalentTo(new string[] { "lib/net45/a.pdb" }); } } [Fact] public async Task GivenThatICopySymbolsVerifyNoMismatchedSymbolsNotAdded() { using (var workingDir = new TestFolder()) { // Arrange var log = new TestLogger(); var nuspec = new TestNuspec() { Id = "a", Version = "1.0.0" }; var nupkg = nuspec.CreateNupkg(); nupkg.Files.Clear(); nupkg.AddFile("lib/net45/a.dll"); var path = nupkg.Save(workingDir); var nuspecSymbols = new TestNuspec() { Id = "a", Version = "1.0.0", IsSymbolPackage = true }; var nupkgSymbols = nuspecSymbols.CreateNupkg(); nupkgSymbols.Files.Clear(); nupkgSymbols.AddFile("lib/net45/a.dll"); nupkgSymbols.AddFile("lib/net45/b.pdb"); nupkgSymbols.Save(workingDir); // Act var before = GetNupkgFiles(path.FullName); var exitCode = await Program.MainCore(new[] { "files", "copysymbols", workingDir }, log); var after = GetNupkgFiles(path.FullName); var diff = new SortedSet<string>(after, StringComparer.OrdinalIgnoreCase); diff.ExceptWith(before); // Assert exitCode.Should().Be(0, log.GetMessages()); after.Should().Contain("lib/net45/a.dll"); diff.ShouldBeEquivalentTo(new string[] { }); } } [Fact] public async Task GivenThatICopySymbolsVerifyTheyAreAddedToTheNupkg() { using (var workingDir = new TestFolder()) { // Arrange var log = new TestLogger(); var nuspec = new TestNuspec() { Id = "a", Version = "1.0.0" }; var nupkg = nuspec.CreateNupkg(); nupkg.Files.Clear(); nupkg.AddFile("lib/net45/a.dll"); var path = nupkg.Save(workingDir); var nuspecSymbols = new TestNuspec() { Id = "a", Version = "1.0.0", IsSymbolPackage = true }; var nupkgSymbols = nuspecSymbols.CreateNupkg(); nupkgSymbols.Files.Clear(); nupkgSymbols.AddFile("lib/net45/a.dll"); nupkgSymbols.AddFile("lib/net45/a.pdb"); nupkgSymbols.Save(workingDir); // Act var before = GetNupkgFiles(path.FullName); var exitCode = await Program.MainCore(new[] { "files", "copysymbols", workingDir }, log); var after = GetNupkgFiles(path.FullName); var diff = new SortedSet<string>(after, StringComparer.OrdinalIgnoreCase); diff.ExceptWith(before); // Assert exitCode.Should().Be(0, log.GetMessages()); after.Should().Contain("lib/net45/a.dll"); diff.ShouldBeEquivalentTo(new[] { "lib/net45/a.pdb" }); } } [Fact] public async Task GivenThatICopySymbolsAndTheyAlreadyExistVerifyNoErrors() { using (var workingDir = new TestFolder()) { // Arrange var log = new TestLogger(); var nuspec = new TestNuspec() { Id = "a", Version = "1.0.0" }; var nupkg = nuspec.CreateNupkg(); nupkg.Files.Clear(); nupkg.AddFile("lib/net45/a.dll"); nupkg.AddFile("lib/net45/a.pdb"); var path = nupkg.Save(workingDir); var nuspecSymbols = new TestNuspec() { Id = "a", Version = "1.0.0", IsSymbolPackage = true }; var nupkgSymbols = nuspecSymbols.CreateNupkg(); nupkgSymbols.Files.Clear(); nupkgSymbols.AddFile("lib/net45/a.dll"); nupkgSymbols.AddFile("lib/net45/a.pdb"); nupkgSymbols.Save(workingDir); // Act var before = GetNupkgFiles(path.FullName); var exitCode = await Program.MainCore(new[] { "files", "copysymbols", workingDir }, log); var after = GetNupkgFiles(path.FullName); var diff = new SortedSet<string>(after, StringComparer.OrdinalIgnoreCase); diff.ExceptWith(before); // Assert exitCode.Should().Be(0, log.GetMessages()); after.Should().Contain("lib/net45/a.dll"); after.Should().Contain("lib/net45/a.pdb"); } } [Fact] public async Task GivenThatICopySymbolsWithNoSymbolsVerifyWarning() { using (var workingDir = new TestFolder()) { // Arrange var log = new TestLogger(); var nuspec = new TestNuspec() { Id = "a", Version = "1.0.0" }; var nupkg = nuspec.CreateNupkg(); nupkg.Files.Clear(); nupkg.AddFile("lib/net45/a.dll"); var path = nupkg.Save(workingDir); // Act var before = GetNupkgFiles(path.FullName); var exitCode = await Program.MainCore(new[] { "files", "copysymbols", workingDir }, log); var after = GetNupkgFiles(path.FullName); var diff = new SortedSet<string>(after, StringComparer.OrdinalIgnoreCase); diff.ExceptWith(before); // Assert exitCode.Should().Be(0, log.GetMessages()); log.GetMessages().Should().Contain("Missing symbols package for a.1.0.0"); } } [Fact] public async Task GivenThatICopySymbolsWithNoPrimaryVerifyWarning() { using (var workingDir = new TestFolder()) { // Arrange var log = new TestLogger(); var nuspec = new TestNuspec() { Id = "a", Version = "1.0.0", IsSymbolPackage = true }; var nupkg = nuspec.CreateNupkg(); nupkg.Files.Clear(); nupkg.AddFile("lib/net45/a.dll"); var path = nupkg.Save(workingDir); // Act var before = GetNupkgFiles(path.FullName); var exitCode = await Program.MainCore(new[] { "files", "copysymbols", workingDir }, log); var after = GetNupkgFiles(path.FullName); var diff = new SortedSet<string>(after, StringComparer.OrdinalIgnoreCase); diff.ExceptWith(before); // Assert exitCode.Should().Be(0, log.GetMessages()); log.GetMessages().Should().Be("Missing primary package for a.1.0.0"); } } [Fact] public async Task GivenThatICopySymbolsWithNoFilesVerifyNoErrors() { using (var workingDir = new TestFolder()) { // Arrange var log = new TestLogger(); // Act var exitCode = await Program.MainCore(new[] { "files", "copysymbols", workingDir }, log); // Assert exitCode.Should().Be(0, log.GetMessages()); } } private static SortedSet<string> GetNupkgFiles(string path) { using (var reader = new PackageArchiveReader(path)) { return new SortedSet<string>(reader.GetFiles(), StringComparer.OrdinalIgnoreCase); } } } }
// 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.Threading.Tasks; using System.Threading; using System.Runtime.ExceptionServices; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class ConnectionPoolTest { private static readonly string _tcpConnStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = false }).ConnectionString; private static readonly string _tcpMarsConnStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString; [CheckConnStrSetupFact] public static void ConnectionPool_NonMars() { RunDataTestForSingleConnString(_tcpConnStr); } [CheckConnStrSetupFact] public static void ConnectionPool_Mars() { RunDataTestForSingleConnString(_tcpMarsConnStr); } private static void RunDataTestForSingleConnString(string tcpConnectionString) { BasicConnectionPoolingTest(tcpConnectionString); ClearAllPoolsTest(tcpConnectionString); ReclaimEmancipatedOnOpenTest(tcpConnectionString); if (DataTestUtility.IsUsingManagedSNI()) { KillConnectionTest(tcpConnectionString); } } /// <summary> /// Tests that using the same connection string results in the same pool\internal connection and a different string results in a different pool\internal connection /// </summary> /// <param name="connectionString"></param> private static void BasicConnectionPoolingTest(string connectionString) { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); InternalConnectionWrapper internalConnection = new InternalConnectionWrapper(connection); ConnectionPoolWrapper connectionPool = new ConnectionPoolWrapper(connection); connection.Close(); SqlConnection connection2 = new SqlConnection(connectionString); connection2.Open(); Assert.True(internalConnection.IsInternalConnectionOf(connection2), "New connection does not use same internal connection"); Assert.True(connectionPool.ContainsConnection(connection2), "New connection is in a different pool"); connection2.Close(); SqlConnection connection3 = new SqlConnection(connectionString + ";App=SqlConnectionPoolUnitTest;"); connection3.Open(); Assert.False(internalConnection.IsInternalConnectionOf(connection3), "Connection with different connection string uses same internal connection"); Assert.False(connectionPool.ContainsConnection(connection3), "Connection with different connection string uses same connection pool"); connection3.Close(); connectionPool.Cleanup(); SqlConnection connection4 = new SqlConnection(connectionString); connection4.Open(); Assert.True(internalConnection.IsInternalConnectionOf(connection4), "New connection does not use same internal connection"); Assert.True(connectionPool.ContainsConnection(connection4), "New connection is in a different pool"); connection4.Close(); } /// <summary> /// Tests if killing the connection using the InternalConnectionWrapper is working /// </summary> /// <param name="connectionString"></param> private static void KillConnectionTest(string connectionString) { #if DEBUG InternalConnectionWrapper wrapper = null; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); wrapper = new InternalConnectionWrapper(connection); using (SqlCommand command = new SqlCommand("SELECT 5;", connection)) { DataTestUtility.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result."); } wrapper.KillConnection(); } using (SqlConnection connection2 = new SqlConnection(connectionString)) { connection2.Open(); Assert.False(wrapper.IsInternalConnectionOf(connection2), "New connection has internal connection that was just killed"); using (SqlCommand command = new SqlCommand("SELECT 5;", connection2)) { DataTestUtility.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result."); } } #endif } /// <summary> /// Tests if clearing all of the pools does actually remove the pools /// </summary> /// <param name="connectionString"></param> private static void ClearAllPoolsTest(string connectionString) { SqlConnection.ClearAllPools(); Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools"); SqlConnection connection = new SqlConnection(connectionString); connection.Open(); ConnectionPoolWrapper pool = new ConnectionPoolWrapper(connection); connection.Close(); ConnectionPoolWrapper[] allPools = ConnectionPoolWrapper.AllConnectionPools(); DataTestUtility.AssertEqualsWithDescription(1, allPools.Length, "Incorrect number of pools exist."); Assert.True(allPools[0].Equals(pool), "Saved pool is not in the list of all pools"); DataTestUtility.AssertEqualsWithDescription(1, pool.ConnectionCount, "Saved pool has incorrect number of connections"); SqlConnection.ClearAllPools(); Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools"); DataTestUtility.AssertEqualsWithDescription(0, pool.ConnectionCount, "Saved pool has incorrect number of connections."); } /// <summary> /// Checks if an 'emancipated' internal connection is reclaimed when a new connection is opened AND we hit max pool size /// NOTE: 'emancipated' means that the internal connection's SqlConnection has fallen out of scope and has no references, but was not explicitly disposed\closed /// </summary> /// <param name="connectionString"></param> private static void ReclaimEmancipatedOnOpenTest(string connectionString) { string newConnectionString = (new SqlConnectionStringBuilder(connectionString) { MaxPoolSize = 1 }).ConnectionString; SqlConnection.ClearAllPools(); InternalConnectionWrapper internalConnection = CreateEmancipatedConnection(newConnectionString); ConnectionPoolWrapper connectionPool = internalConnection.ConnectionPool; GC.Collect(); GC.WaitForPendingFinalizers(); DataTestUtility.AssertEqualsWithDescription(1, connectionPool.ConnectionCount, "Wrong number of connections in the pool."); DataTestUtility.AssertEqualsWithDescription(0, connectionPool.FreeConnectionCount, "Wrong number of free connections in the pool."); using (SqlConnection connection = new SqlConnection(newConnectionString)) { connection.Open(); Assert.True(internalConnection.IsInternalConnectionOf(connection), "Connection has wrong internal connection"); Assert.True(connectionPool.ContainsConnection(connection), "Connection is in wrong connection pool"); } } private static void ReplacementConnectionUsesSemaphoreTest(string connectionString) { string newConnectionString = (new SqlConnectionStringBuilder(connectionString) { MaxPoolSize = 2, ConnectTimeout = 5 }).ConnectionString; SqlConnection.ClearAllPools(); SqlConnection liveConnection = new SqlConnection(newConnectionString); SqlConnection deadConnection = new SqlConnection(newConnectionString); liveConnection.Open(); deadConnection.Open(); InternalConnectionWrapper deadConnectionInternal = new InternalConnectionWrapper(deadConnection); InternalConnectionWrapper liveConnectionInternal = new InternalConnectionWrapper(liveConnection); deadConnectionInternal.KillConnection(); deadConnection.Close(); liveConnection.Close(); Task<InternalConnectionWrapper>[] tasks = new Task<InternalConnectionWrapper>[3]; Barrier syncBarrier = new Barrier(tasks.Length); Func<InternalConnectionWrapper> taskFunction = (() => ReplacementConnectionUsesSemaphoreTask(newConnectionString, syncBarrier)); for (int i = 0; i < tasks.Length; i++) { tasks[i] = Task.Factory.StartNew<InternalConnectionWrapper>(taskFunction); } bool taskWithLiveConnection = false; bool taskWithNewConnection = false; bool taskWithCorrectException = false; Task waitAllTask = Task.Factory.ContinueWhenAll(tasks, (completedTasks) => { foreach (var item in completedTasks) { if (item.Status == TaskStatus.Faulted) { // One task should have a timeout exception if ((!taskWithCorrectException) && (item.Exception.InnerException is InvalidOperationException) && (item.Exception.InnerException.Message.StartsWith(SystemDataResourceManager.Instance.ADP_PooledOpenTimeout))) taskWithCorrectException = true; else if (!taskWithCorrectException) { // Rethrow the unknown exception ExceptionDispatchInfo exceptionInfo = ExceptionDispatchInfo.Capture(item.Exception); exceptionInfo.Throw(); } } else if (item.Status == TaskStatus.RanToCompletion) { // One task should get the live connection if (item.Result.Equals(liveConnectionInternal)) { if (!taskWithLiveConnection) taskWithLiveConnection = true; } else if (!item.Result.Equals(deadConnectionInternal) && !taskWithNewConnection) taskWithNewConnection = true; } else Console.WriteLine("ERROR: Task in unknown state: {0}", item.Status); } }); waitAllTask.Wait(); Assert.True(taskWithLiveConnection && taskWithNewConnection && taskWithCorrectException, string.Format("Tasks didn't finish as expected.\nTask with live connection: {0}\nTask with new connection: {1}\nTask with correct exception: {2}\n", taskWithLiveConnection, taskWithNewConnection, taskWithCorrectException)); } private static InternalConnectionWrapper ReplacementConnectionUsesSemaphoreTask(string connectionString, Barrier syncBarrier) { InternalConnectionWrapper internalConnection = null; using (SqlConnection connection = new SqlConnection(connectionString)) { try { connection.Open(); internalConnection = new InternalConnectionWrapper(connection); } catch { syncBarrier.SignalAndWait(); throw; } syncBarrier.SignalAndWait(); } return internalConnection; } private static InternalConnectionWrapper CreateEmancipatedConnection(string connectionString) { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); return new InternalConnectionWrapper(connection); } } }
#pragma warning disable 162,108,618 using Casanova.Prelude; using System.Linq; using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using System; using Utilities; namespace AsteroidShooter { public class World { public static int frame; public bool JustEntered = true; public int ID; public void Start() { State = Microsoft.Xna.Framework.Input.Keyboard.GetState(); ID = GetHashCode(); Ships = ( (new Cons<Ship>(new Ship(new Microsoft.Xna.Framework.Vector2(Utilities.Random.RandFloat(250f, 1500f), 1000f)), (new Empty<Ship>()).ToList<Ship>())).ToList<Ship>()).ToList<Ship>(); CollidingProjectiles = ( Enumerable.Empty<Projectile>()).ToList<Projectile>(); CollidingAsteroids = ( Enumerable.Empty<Asteroid>()).ToList<Asteroid>(); ColliderShipAsteroid = ( Enumerable.Empty<Casanova.Prelude.Tuple<Ship, Asteroid>>()).ToList<Casanova.Prelude.Tuple<Ship, Asteroid>>(); Asteroids = ( Enumerable.Empty<Asteroid>()).ToList<Asteroid>(); } public List<Asteroid> Asteroids; public List<Casanova.Prelude.Tuple<Ship, Asteroid>> ColliderShipAsteroid; public List<Asteroid> CollidingAsteroids; public List<Projectile> CollidingProjectiles; public List<Ship> Ships; public Microsoft.Xna.Framework.Input.KeyboardState State; public List<Asteroid> ___updatedAsteroids20; public Microsoft.Xna.Framework.Vector2 ___randomPos70; public System.Single ___randomWait70; public System.Single count_down1; System.DateTime init_time = System.DateTime.Now; public void Update(float dt, World world) { var t = System.DateTime.Now; this.Rule0(dt, world); this.Rule1(dt, world); this.Rule3(dt, world); this.Rule4(dt, world); this.Rule6(dt, world); this.Rule8(dt, world); for (int x0 = 0; x0 < Asteroids.Count; x0++) { Asteroids[x0].Update(dt, world); } for (int x0 = 0; x0 < Ships.Count; x0++) { Ships[x0].Update(dt, world); } this.Rule2(dt, world); this.Rule5(dt, world); this.Rule7(dt, world); } public void Rule0(float dt, World world) { CollidingProjectiles = ( (Asteroids).Select(__ContextSymbol5 => new { ___a00 = __ContextSymbol5 }) .SelectMany(__ContextSymbol6 => (Ships).Select(__ContextSymbol7 => new { ___s00 = __ContextSymbol7, prev = __ContextSymbol6 }) .SelectMany(__ContextSymbol8 => (__ContextSymbol8.___s00.Projectiles).Select(__ContextSymbol9 => new { ___p00 = __ContextSymbol9, prev = __ContextSymbol8 }) .Where(__ContextSymbol10 => ((150f) > (Microsoft.Xna.Framework.Vector2.Distance(__ContextSymbol10.prev.prev.___a00.Position, __ContextSymbol10.___p00.Position)))) .Select(__ContextSymbol11 => __ContextSymbol11.___p00) .ToList<Projectile>()))).ToList<Projectile>(); } public void Rule1(float dt, World world) { Ships = ( (Ships).Select(__ContextSymbol12 => new { ___s11 = __ContextSymbol12 }) .Where(__ContextSymbol13 => ((__ContextSymbol13.___s11.Health) > (0))) .Select(__ContextSymbol14 => __ContextSymbol14.___s11) .ToList<Ship>()).ToList<Ship>(); } public void Rule3(float dt, World world) { ColliderShipAsteroid = ( (Asteroids).Select(__ContextSymbol15 => new { ___a32 = __ContextSymbol15 }) .SelectMany(__ContextSymbol16 => (Ships).Select(__ContextSymbol17 => new { ___s32 = __ContextSymbol17, prev = __ContextSymbol16 }) .Where(__ContextSymbol18 => ((150f) > (Microsoft.Xna.Framework.Vector2.Distance(__ContextSymbol18.prev.___a32.Position, __ContextSymbol18.___s32.Position)))) .Select(__ContextSymbol19 => new Casanova.Prelude.Tuple<Ship, Asteroid>(__ContextSymbol19.___s32, __ContextSymbol19.prev.___a32)) .ToList<Casanova.Prelude.Tuple<Ship, Asteroid>>())).ToList<Casanova.Prelude.Tuple<Ship, Asteroid>>(); } public void Rule4(float dt, World world) { CollidingAsteroids = ( (Asteroids).Select(__ContextSymbol20 => new { ___a43 = __ContextSymbol20 }) .SelectMany(__ContextSymbol21 => (Ships).Select(__ContextSymbol22 => new { ___s43 = __ContextSymbol22, prev = __ContextSymbol21 }) .SelectMany(__ContextSymbol23 => (__ContextSymbol23.___s43.Projectiles).Select(__ContextSymbol24 => new { ___p41 = __ContextSymbol24, prev = __ContextSymbol23 }) .Where(__ContextSymbol25 => ((150f) > (Microsoft.Xna.Framework.Vector2.Distance(__ContextSymbol25.prev.prev.___a43.Position, __ContextSymbol25.___p41.Position)))) .Select(__ContextSymbol26 => __ContextSymbol26.prev.prev.___a43) .ToList<Asteroid>()))).ToList<Asteroid>(); } public void Rule6(float dt, World world) { Asteroids = ( (Asteroids).Select(__ContextSymbol27 => new { ___a65 = __ContextSymbol27 }) .Where(__ContextSymbol28 => ((1500f) > (__ContextSymbol28.___a65.Position.Y))) .Select(__ContextSymbol29 => __ContextSymbol29.___a65) .ToList<Asteroid>()).ToList<Asteroid>(); } public void Rule8(float dt, World world) { State = Microsoft.Xna.Framework.Input.Keyboard.GetState(); } int s2 = -1; public void Rule2(float dt, World world) { switch (s2) { case -1: if (!(((ColliderShipAsteroid.Count) > (0)))) { s2 = -1; return; } else { goto case 1; } case 1: ___updatedAsteroids20 = ( (Asteroids).Select(__ContextSymbol30 => new { ___a21 = __ContextSymbol30 }) .Select(__ContextSymbol31 => new { ___colliders20 = ( (ColliderShipAsteroid).Select(__ContextSymbol32 => new { ___c20 = __ContextSymbol32, prev = __ContextSymbol31 }) .Where(__ContextSymbol33 => ((__ContextSymbol33.___c20.Item2) == (__ContextSymbol33.prev.___a21))) .Select(__ContextSymbol34 => __ContextSymbol34.___c20.Item2) .ToList<Asteroid>()).ToList<Asteroid>(), prev = __ContextSymbol31 }) .Where(__ContextSymbol35 => ((__ContextSymbol35.___colliders20.Count) == (0))) .Select(__ContextSymbol36 => __ContextSymbol36.prev.___a21) .ToList<Asteroid>()).ToList<Asteroid>(); ColliderShipAsteroid = ( Enumerable.Empty<Casanova.Prelude.Tuple<Ship, Asteroid>>()).ToList<Casanova.Prelude.Tuple<Ship, Asteroid>>(); Asteroids = ___updatedAsteroids20; s2 = -1; return; default: return; } } int s5 = -1; public void Rule5(float dt, World world) { switch (s5) { case -1: if (!(((CollidingAsteroids.Count) > (0)))) { s5 = -1; return; } else { goto case 0; } case 0: Asteroids = ( (Asteroids).Select(__ContextSymbol38 => new { ___a54 = __ContextSymbol38 }) .SelectMany(__ContextSymbol39 => (CollidingAsteroids).Select(__ContextSymbol40 => new { ___ca50 = __ContextSymbol40, prev = __ContextSymbol39 }) .Where(__ContextSymbol41 => !(((__ContextSymbol41.prev.___a54) == (__ContextSymbol41.___ca50)))) .Select(__ContextSymbol42 => __ContextSymbol42.prev.___a54) .ToList<Asteroid>())).ToList<Asteroid>(); s5 = -1; return; default: return; } } int s7 = -1; public void Rule7(float dt, World world) { switch (s7) { case -1: ___randomPos70 = new Microsoft.Xna.Framework.Vector2(Utilities.Random.RandFloat(0f, 1500f), -50f); ___randomWait70 = Utilities.Random.RandFloat(0.5f, 3f); Asteroids = new Cons<Asteroid>(new Asteroid(___randomPos70), (Asteroids)).ToList<Asteroid>(); s7 = 0; return; case 0: count_down1 = ___randomWait70; goto case 1; case 1: if (((count_down1) > (0f))) { count_down1 = ((count_down1) - (dt)); s7 = 1; return; } else { s7 = -1; return; } default: return; } } } public class Ship { public int frame; public bool JustEntered = true; private Microsoft.Xna.Framework.Vector2 p; public int ID; public Ship(Microsoft.Xna.Framework.Vector2 p) { JustEntered = false; frame = World.frame; Score = 0; ID = GetHashCode(); Projectiles = ( Enumerable.Empty<Projectile>()).ToList<Projectile>(); Position = p; Health = 100; Color = new Microsoft.Xna.Framework.Color(Utilities.Random.RandInt(0, 256), Utilities.Random.RandInt(0, 256), Utilities.Random.RandInt(0, 256)); } public Microsoft.Xna.Framework.Color Color; public System.Int32 Health; public Microsoft.Xna.Framework.Vector2 Position; public List<Projectile> Projectiles; public System.Int32 Score; public List<Projectile> ___hits00; public List<Projectile> ___updatedProjs00; public List<Casanova.Prelude.Tuple<Ship, Asteroid>> ___colliders11; public Microsoft.Xna.Framework.Vector2 ___vy40; public Microsoft.Xna.Framework.Vector2 ___vy51; public void Update(float dt, World world) { frame = World.frame; this.Rule3(dt, world); this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule4(dt, world); this.Rule5(dt, world); for (int x0 = 0; x0 < Projectiles.Count; x0++) { Projectiles[x0].Update(dt, world); } } public void Rule3(float dt, World world) { Projectiles = ( (Projectiles).Select(__ContextSymbol45 => new { ___p34 = __ContextSymbol45 }) .Where(__ContextSymbol46 => ((__ContextSymbol46.___p34.Position.Y) > (-50f))) .Select(__ContextSymbol47 => __ContextSymbol47.___p34) .ToList<Projectile>()).ToList<Projectile>(); } int s0 = -1; public void Rule0(float dt, World world) { switch (s0) { case -1: if (!(((world.CollidingProjectiles.Count) > (0)))) { s0 = -1; return; } else { goto case 2; } case 2: ___hits00 = ( (Projectiles).Select(__ContextSymbol48 => new { ___p02 = __ContextSymbol48 }) .SelectMany(__ContextSymbol49 => (world.CollidingProjectiles).Select(__ContextSymbol50 => new { ___cp00 = __ContextSymbol50, prev = __ContextSymbol49 }) .Where(__ContextSymbol51 => ((((__ContextSymbol51.prev.___p02) == (__ContextSymbol51.___cp00))) && (((__ContextSymbol51.prev.___p02.Owner) == (this))))) .Select(__ContextSymbol52 => __ContextSymbol52.prev.___p02) .ToList<Projectile>())).ToList<Projectile>(); ___updatedProjs00 = ( (Projectiles).Select(__ContextSymbol53 => new { ___p03 = __ContextSymbol53 }) .Select(__ContextSymbol54 => new { ___hits01 = ( (world.CollidingProjectiles).Select(__ContextSymbol55 => new { ___cp01 = __ContextSymbol55, prev = __ContextSymbol54 }) .Where(__ContextSymbol56 => ((((__ContextSymbol56.prev.___p03) == (__ContextSymbol56.___cp01))) && (((__ContextSymbol56.prev.___p03.Owner) == (this))))) .Select(__ContextSymbol57 => __ContextSymbol57.prev.___p03) .ToList<Projectile>()).ToList<Projectile>(), prev = __ContextSymbol54 }) .Where(__ContextSymbol58 => ((__ContextSymbol58.___hits01.Count) == (0))) .Select(__ContextSymbol59 => __ContextSymbol59.prev.___p03) .ToList<Projectile>()).ToList<Projectile>(); Projectiles = ___updatedProjs00; Score = ((Score) + (___hits00.Count)); s0 = -1; return; default: return; } } int s1 = -1; public void Rule1(float dt, World world) { switch (s1) { case -1: if (!(((world.ColliderShipAsteroid.Count) > (0)))) { s1 = -1; return; } else { goto case 5; } case 5: ___colliders11 = ( (world.ColliderShipAsteroid).Select(__ContextSymbol60 => new { ___c11 = __ContextSymbol60 }) .Where(__ContextSymbol61 => ((__ContextSymbol61.___c11.Item1) == (this))) .Select(__ContextSymbol62 => __ContextSymbol62.___c11) .ToList<Casanova.Prelude.Tuple<Ship, Asteroid>>()).ToList<Casanova.Prelude.Tuple<Ship, Asteroid>>(); if (((___colliders11.Count) > (0))) { goto case 0; } else { goto case 1; } case 0: Health = ((Health) - (___colliders11.Head().Item2.Damage)); s1 = -1; return; case 1: Health = Health; s1 = -1; return; default: return; } } int s2 = -1; public void Rule2(float dt, World world) { switch (s2) { case -1: if (!(world.State.IsKeyDown(Keys.Space))) { s2 = -1; return; } else { goto case 1; } case 1: Projectiles = new Cons<Projectile>(new Projectile(Position, this), (Projectiles)).ToList<Projectile>(); s2 = 0; return; case 0: if (!(!(world.State.IsKeyDown(Keys.Space)))) { s2 = 0; return; } else { s2 = -1; return; } default: return; } } int s4 = -1; public void Rule4(float dt, World world) { switch (s4) { case -1: ___vy40 = new Microsoft.Xna.Framework.Vector2(300f, 0f); goto case 1; case 1: if (!(world.State.IsKeyDown(Keys.D))) { s4 = 1; return; } else { goto case 0; } case 0: Position = ((Position) + (((___vy40) * (dt)))); s4 = -1; return; default: return; } } int s5 = -1; public void Rule5(float dt, World world) { switch (s5) { case -1: ___vy51 = new Microsoft.Xna.Framework.Vector2(-300f, 0f); goto case 1; case 1: if (!(world.State.IsKeyDown(Keys.A))) { s5 = 1; return; } else { goto case 0; } case 0: Position = ((Position) + (((___vy51) * (dt)))); s5 = -1; return; default: return; } } } public class Projectile { public int frame; public bool JustEntered = true; private Microsoft.Xna.Framework.Vector2 p; private Ship owner; public int ID; public Projectile(Microsoft.Xna.Framework.Vector2 p, Ship owner) { JustEntered = false; frame = World.frame; Position = p; Owner = owner; ID = GetHashCode(); } public Ship Owner; public Microsoft.Xna.Framework.Vector2 Position; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); } public void Rule0(float dt, World world) { Position = (Position) + ((new Microsoft.Xna.Framework.Vector2(0f, -500f)) * (dt)); } } public class Asteroid { public int frame; public bool JustEntered = true; private Microsoft.Xna.Framework.Vector2 p; public int ID; public Asteroid(Microsoft.Xna.Framework.Vector2 p) { JustEntered = false; frame = World.frame; Position = p; Damage = Utilities.Random.RandInt(10, 31); ID = GetHashCode(); } public System.Int32 Damage; public Microsoft.Xna.Framework.Vector2 Position; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); } public void Rule0(float dt, World world) { Position = (Position) + ((new Microsoft.Xna.Framework.Vector2(0f, 250f)) * (dt)); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Concurrency; using Orleans.Runtime; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans.Streams.Core; namespace Orleans.Streams { internal interface IStreamSubscriptionHandle { Task<StreamHandshakeToken> DeliverItem(object item, StreamSequenceToken currentToken, StreamHandshakeToken handshakeToken); Task<StreamHandshakeToken> DeliverBatch(IBatchContainer item, StreamHandshakeToken handshakeToken); Task CompleteStream(); Task ErrorInStream(Exception exc); StreamHandshakeToken GetSequenceToken(); } /// <summary> /// The extension multiplexes all stream related messages to this grain between different streams and their stream observers. /// /// On the silo, we have one extension object per activation and this extension multiplexes all streams on this activation /// (streams of all types and ids: different stream ids and different stream providers). /// On the client, we have one extension per stream (we bind an extension for every StreamConsumer, therefore every stream has its own extension). /// </summary> [Serializable] internal class StreamConsumerExtension : IStreamConsumerExtension { private readonly IStreamProviderRuntime providerRuntime; private readonly ConcurrentDictionary<GuidId, IStreamSubscriptionHandle> allStreamObservers = new(); // map to different ObserversCollection<T> of different Ts. private readonly ILogger logger; private const int MAXIMUM_ITEM_STRING_LOG_LENGTH = 128; // if this extension is attached to a cosnumer grain which implements IOnSubscriptionActioner, // then this will be not null, otherwise, it will be null [NonSerialized] private readonly IStreamSubscriptionObserver streamSubscriptionObserver; internal StreamConsumerExtension(IStreamProviderRuntime providerRt, IStreamSubscriptionObserver streamSubscriptionObserver = null) { this.streamSubscriptionObserver = streamSubscriptionObserver; providerRuntime = providerRt; logger = providerRt.ServiceProvider.GetRequiredService<ILogger<StreamConsumerExtension>>(); } internal StreamSubscriptionHandleImpl<T> SetObserver<T>( GuidId subscriptionId, StreamImpl<T> stream, IAsyncObserver<T> observer, IAsyncBatchObserver<T> batchObserver, StreamSequenceToken token, string filterData) { if (null == stream) throw new ArgumentNullException("stream"); try { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("{0} AddObserver for stream {1}", providerRuntime.ExecutingEntityIdentity(), stream.InternalStreamId); // Note: The caller [StreamConsumer] already handles locking for Add/Remove operations, so we don't need to repeat here. var handle = new StreamSubscriptionHandleImpl<T>(subscriptionId, observer, batchObserver, stream, token, filterData); allStreamObservers[subscriptionId] = handle; return handle; } catch (Exception exc) { logger.Error(ErrorCode.StreamProvider_AddObserverException, $"{providerRuntime.ExecutingEntityIdentity()} StreamConsumerExtension.AddObserver({stream.InternalStreamId}) caugth exception.", exc); throw; } } public bool RemoveObserver(GuidId subscriptionId) { return allStreamObservers.TryRemove(subscriptionId, out _); } public Task<StreamHandshakeToken> DeliverImmutable(GuidId subscriptionId, InternalStreamId streamId, Immutable<object> item, StreamSequenceToken currentToken, StreamHandshakeToken handshakeToken) { return DeliverMutable(subscriptionId, streamId, item.Value, currentToken, handshakeToken); } public async Task<StreamHandshakeToken> DeliverMutable(GuidId subscriptionId, InternalStreamId streamId, object item, StreamSequenceToken currentToken, StreamHandshakeToken handshakeToken) { if (logger.IsEnabled(LogLevel.Trace)) { var itemString = item.ToString(); itemString = (itemString.Length > MAXIMUM_ITEM_STRING_LOG_LENGTH) ? itemString.Substring(0, MAXIMUM_ITEM_STRING_LOG_LENGTH) + "..." : itemString; logger.Trace("DeliverItem {0} for subscription {1}", itemString, subscriptionId); } IStreamSubscriptionHandle observer; if (allStreamObservers.TryGetValue(subscriptionId, out observer)) { return await observer.DeliverItem(item, currentToken, handshakeToken); } else if(this.streamSubscriptionObserver != null) { var streamProvider = this.providerRuntime.ServiceProvider.GetServiceByName<IStreamProvider>(streamId.ProviderName); if(streamProvider != null) { var subscriptionHandlerFactory = new StreamSubscriptionHandlerFactory(streamProvider, streamId, streamId.ProviderName, subscriptionId); await this.streamSubscriptionObserver.OnSubscribed(subscriptionHandlerFactory); //check if an observer were attached after handling the new subscription, deliver on it if attached if (allStreamObservers.TryGetValue(subscriptionId, out observer)) { return await observer.DeliverItem(item, currentToken, handshakeToken); } } } logger.Warn((int)(ErrorCode.StreamProvider_NoStreamForItem), "{0} got an item for subscription {1}, but I don't have any subscriber for that stream. Dropping on the floor.", providerRuntime.ExecutingEntityIdentity(), subscriptionId); // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or ... return default(StreamHandshakeToken); } public async Task<StreamHandshakeToken> DeliverBatch(GuidId subscriptionId, InternalStreamId streamId, Immutable<IBatchContainer> batch, StreamHandshakeToken handshakeToken) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("DeliverBatch {0} for subscription {1}", batch.Value, subscriptionId); IStreamSubscriptionHandle observer; if (allStreamObservers.TryGetValue(subscriptionId, out observer)) { return await observer.DeliverBatch(batch.Value, handshakeToken); } else if(this.streamSubscriptionObserver != null) { var streamProvider = this.providerRuntime.ServiceProvider.GetServiceByName<IStreamProvider>(streamId.ProviderName); if (streamProvider != null) { var subscriptionHandlerFactory = new StreamSubscriptionHandlerFactory(streamProvider, streamId, streamId.ProviderName, subscriptionId); await this.streamSubscriptionObserver.OnSubscribed(subscriptionHandlerFactory); // check if an observer were attached after handling the new subscription, deliver on it if attached if (allStreamObservers.TryGetValue(subscriptionId, out observer)) { return await observer.DeliverBatch(batch.Value, handshakeToken); } } } logger.Warn((int)(ErrorCode.StreamProvider_NoStreamForBatch), "{0} got an item for subscription {1}, but I don't have any subscriber for that stream. Dropping on the floor.", providerRuntime.ExecutingEntityIdentity(), subscriptionId); // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or ... return default(StreamHandshakeToken); } public Task CompleteStream(GuidId subscriptionId) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("CompleteStream for subscription {0}", subscriptionId); IStreamSubscriptionHandle observer; if (allStreamObservers.TryGetValue(subscriptionId, out observer)) return observer.CompleteStream(); logger.Warn((int)(ErrorCode.StreamProvider_NoStreamForItem), "{0} got a Complete for subscription {1}, but I don't have any subscriber for that stream. Dropping on the floor.", providerRuntime.ExecutingEntityIdentity(), subscriptionId); // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or ... return Task.CompletedTask; } public Task ErrorInStream(GuidId subscriptionId, Exception exc) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("ErrorInStream {0} for subscription {1}", exc, subscriptionId); IStreamSubscriptionHandle observer; if (allStreamObservers.TryGetValue(subscriptionId, out observer)) return observer.ErrorInStream(exc); logger.Warn((int)(ErrorCode.StreamProvider_NoStreamForItem), "{0} got an Error for subscription {1}, but I don't have any subscriber for that stream. Dropping on the floor.", providerRuntime.ExecutingEntityIdentity(), subscriptionId); // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or ... return Task.CompletedTask; } public Task<StreamHandshakeToken> GetSequenceToken(GuidId subscriptionId) { IStreamSubscriptionHandle observer; return Task.FromResult(allStreamObservers.TryGetValue(subscriptionId, out observer) ? observer.GetSequenceToken() : null); } internal int DiagCountStreamObservers<T>(InternalStreamId streamId) { return allStreamObservers.Count(o => o.Value is StreamSubscriptionHandleImpl<T> i && i.SameStreamId(streamId)); } internal List<StreamSubscriptionHandleImpl<T>> GetAllStreamHandles<T>() { var ls = new List<StreamSubscriptionHandleImpl<T>>(); foreach (var o in allStreamObservers) { if (o.Value is StreamSubscriptionHandleImpl<T> i) ls.Add(i); } return ls; } } }
//--------------------------------------------------------------------------- // // File: IconHelper.cs // // Description: Static internal class implements utility functions for icon // implementation for the Window class. // // Created: 07/27/05 // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Security; using System.Security.Permissions; using System.Diagnostics; using System.Collections.ObjectModel; using System.Runtime.InteropServices; using System.ComponentModel; using System.Windows; using System.Windows.Interop; using System.Windows.Media.Imaging; using System.Windows.Media; using MS.Internal; using MS.Internal.Interop; using MS.Internal.PresentationFramework; // SecurityHelper using MS.Win32; namespace MS.Internal.AppModel { internal static class IconHelper { private static Size s_smallIconSize; private static Size s_iconSize; private static int s_systemBitDepth; /// Lazy init of static fields. Call this at the beginning of any external entrypoint. /// <SecurityNote> /// Critical: Calls GetDC, ReleaseDC and GetDeviceCaps that are marked SecurityCritical /// TreatAsSafe: These set local static fields that aren't directly exposed outside this class. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private static void EnsureSystemMetrics() { if (s_systemBitDepth == 0) { // The values here *may* change, but it's not worthwhile to requery. // We need to release the DC to correctly track our native handles. var hdcDesktop = new HandleRef(null, UnsafeNativeMethods.GetDC(new HandleRef())); try { int sysBitDepth = UnsafeNativeMethods.GetDeviceCaps(hdcDesktop, NativeMethods.BITSPIXEL); sysBitDepth *= UnsafeNativeMethods.GetDeviceCaps(hdcDesktop, NativeMethods.PLANES); // If the s_systemBitDepth is 8, make it 4. Why? Because windows does not // choose a 256 color icon if the display is running in 256 color mode // because of palette flicker. if (sysBitDepth == 8) { sysBitDepth = 4; } // We really want to be pixel aware here. Don't use the SystemParameters class. int cxSmallIcon = UnsafeNativeMethods.GetSystemMetrics(SM.CXSMICON); int cySmallIcon = UnsafeNativeMethods.GetSystemMetrics(SM.CYSMICON); int cxIcon = UnsafeNativeMethods.GetSystemMetrics(SM.CXICON); int cyIcon = UnsafeNativeMethods.GetSystemMetrics(SM.CYICON); s_smallIconSize = new Size(cxSmallIcon, cySmallIcon); s_iconSize = new Size(cxIcon, cyIcon); s_systemBitDepth = sysBitDepth; } finally { UnsafeNativeMethods.ReleaseDC(new HandleRef(), hdcDesktop); } } } /// <SecurityNote> /// Critical: This code elevates to unmanaged Code permission /// TreatAsSafe: There is a demand here /// </SecurityNote> /// <returns></returns> [SecurityCritical, SecurityTreatAsSafe] public static void GetDefaultIconHandles(out NativeMethods.IconHandle largeIconHandle, out NativeMethods.IconHandle smallIconHandle) { largeIconHandle = null; smallIconHandle = null; SecurityHelper.DemandUIWindowPermission(); // Get the handle of the module that created the running process. string iconModuleFile = UnsafeNativeMethods.GetModuleFileName(new HandleRef()); // We don't really care about the return value. Handles will be invalid on error. int extractedCount = UnsafeNativeMethods.ExtractIconEx(iconModuleFile, 0, out largeIconHandle, out smallIconHandle, 1); } /// <SecurityNote> /// Critical: Since it calls CreateIconHandleFromImageSource /// TAS: Since it creates icons with known h/w i.e. IconWidth/Height or SmallIconWidth/Height /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] public static void GetIconHandlesFromImageSource(ImageSource image, out NativeMethods.IconHandle largeIconHandle, out NativeMethods.IconHandle smallIconHandle) { EnsureSystemMetrics(); largeIconHandle = CreateIconHandleFromImageSource(image, s_iconSize); smallIconHandle = CreateIconHandleFromImageSource(image, s_smallIconSize); } /// <SecurityNote> /// Critical: Since it calls CreateIconHandleFromBitmapFrame /// </SecurityNote> /// <returns>A new HICON based on the image source</returns> [SecurityCritical] public static NativeMethods.IconHandle CreateIconHandleFromImageSource(ImageSource image, Size size) { EnsureSystemMetrics(); bool asGoodAsItGets = false; var bf = image as BitmapFrame; if (bf != null) { Invariant.Assert(bf.Decoder != null, "The BitmapFrame's Decoder should never be null"); Invariant.Assert(bf.Decoder.Frames != null, "The BitmapFrame's Decoder.Frames should never be null"); bf = GetBestMatch(bf.Decoder.Frames, size); // If this was actually a multi-framed icon then we don't want to do any corrections. // Let Windows do its thing. We don't want to unnecessarily deviate from the system. // If this was a jpeg or png, then we're doing something Windows doesn't do, // and we can be better. (unless it was a perfect match :) asGoodAsItGets = bf.Decoder is IconBitmapDecoder // i.e. was this a .ico? || bf.PixelWidth == size.Width && bf.PixelHeight == size.Height; image = bf; } if (!asGoodAsItGets) { // Unless this was a .ico, render it into a new BitmapFrame with the appropriate dimensions // to preserve the aspect ratio in the HICON and do the appropriate padding. bf = BitmapFrame.Create(GenerateBitmapSource(image, size)); } return CreateIconHandleFromBitmapFrame(bf); } /// <summary> /// Creates a BitmapSource from an arbitrary ImageSource. /// </summary> private static BitmapSource GenerateBitmapSource(ImageSource img, Size renderSize) { // By now we should just assume it's a vector image that we need to rasterize. // We want to keep the aspect ratio, but one of the dimensions will go the full length. var drawingDimensions = new Rect(0, 0, renderSize.Width, renderSize.Height); // There's no reason to assume that the requested image dimensions are square. double renderRatio = renderSize.Width / renderSize.Height; double aspectRatio = img.Width / img.Height; // If it's smaller than the requested size, then place it in the middle and pad the image. if (img.Width <= renderSize.Width && img.Height <= renderSize.Height) { drawingDimensions = new Rect((renderSize.Width - img.Width) / 2, (renderSize.Height - img.Height) / 2, img.Width, img.Height); } else if (renderRatio > aspectRatio) { double scaledRenderWidth = (img.Width / img.Height) * renderSize.Width; drawingDimensions = new Rect((renderSize.Width - scaledRenderWidth) / 2, 0, scaledRenderWidth, renderSize.Height); } else if (renderRatio < aspectRatio) { double scaledRenderHeight = (img.Height / img.Width) * renderSize.Height; drawingDimensions = new Rect(0, (renderSize.Height - scaledRenderHeight) / 2, renderSize.Width, scaledRenderHeight); } var dv = new DrawingVisual(); DrawingContext dc = dv.RenderOpen(); dc.DrawImage(img, drawingDimensions); dc.Close(); // Need to use Pbgra32 because that's all that RenderTargetBitmap currently supports. // 96 is the right DPI to use here because we're being very pixel aware. var bmp = new RenderTargetBitmap((int)renderSize.Width, (int)renderSize.Height, 96, 96, PixelFormats.Pbgra32); bmp.Render(dv); return bmp; } /// <SecurityNote> /// Critical: Since it calls CreateIconCursor which is SecurityCritical. CreateIconCursor is SecurityCritical b/c /// it creates bitmaps with the input w/h etc. That width/height is passed by this method using /// sourceBitmapFrame.Pixel[Width/Height] and is not guarded. /// </SecurityNote> /// <returns></returns> // // Creates and HICON from a bitmap frame [SecurityCritical] private static NativeMethods.IconHandle CreateIconHandleFromBitmapFrame(BitmapFrame sourceBitmapFrame) { Invariant.Assert(sourceBitmapFrame != null, "sourceBitmapFrame cannot be null here"); BitmapSource bitmapSource = sourceBitmapFrame; if (bitmapSource.Format != PixelFormats.Bgra32 && bitmapSource.Format != PixelFormats.Pbgra32) { bitmapSource = new FormatConvertedBitmap(bitmapSource, PixelFormats.Bgra32, null, 0.0); } // data used by CopyPixels int w = bitmapSource.PixelWidth; int h = bitmapSource.PixelHeight; int bpp = bitmapSource.Format.BitsPerPixel; // ensuring it is in 4 byte increments since we're dealing // with ARGB fromat int stride = (bpp * w + 31) / 32 * 4; int sizeCopyPixels = stride * h; byte[] xor = new byte[sizeCopyPixels]; bitmapSource.CopyPixels(xor, stride, 0); return CreateIconCursor(xor, w, h, 0, 0, true); } // Also used by PenCursorManager // Creates a 32 bit per pixel Icon or cursor. This code is moved from framework\ms\internal\ink\pencursormanager.cs /// <SecurityNote> /// Critical: Critical as this code create a DIB section and writes data to it /// </SecurityNote> [SecurityCritical] internal static NativeMethods.IconHandle CreateIconCursor( byte[] colorArray, int width, int height, int xHotspot, int yHotspot, bool isIcon) { // 1. We are going to generate a WIN32 color bitmap which represents the color cursor. // 2. Then we need to create a monochrome bitmap which is used as the cursor mask. // 3. At last we create a WIN32 HICON from the above two bitmaps NativeMethods.BitmapHandle colorBitmap = null; NativeMethods.BitmapHandle maskBitmap = null; try { // 1) Create the color bitmap using colorArray // Fill in the header information NativeMethods.BITMAPINFO bi = new NativeMethods.BITMAPINFO( width, // width -height, // A negative value indicates the bitmap is top-down DIB 32 // biBitCount ); bi.bmiHeader_biCompression = NativeMethods.BI_RGB; IntPtr bits = IntPtr.Zero; colorBitmap = MS.Win32.UnsafeNativeMethods.CreateDIBSection( new HandleRef(null, IntPtr.Zero), // A device context. Pass null in if no DIB_PAL_COLORS is used. ref bi, // A BITMAPINFO structure which specifies the dimensions and colors. NativeMethods.DIB_RGB_COLORS, // Specifies the type of data contained in the bmiColors array member of the BITMAPINFO structure ref bits, // An out Pointer to a variable that receives a pointer to the location of the DIB bit values null, // Handle to a file-mapping object that the function will use to create the DIB. This parameter can be null. 0 // dwOffset. This value is ignored if hSection is NULL ); if ( colorBitmap.IsInvalid || bits == IntPtr.Zero) { // Note we will release the GDI resources in the finally block. return NativeMethods.IconHandle.GetInvalidIcon(); } // Copy the color bits to the win32 bitmap Marshal.Copy(colorArray, 0, bits, colorArray.Length); // 2) Now create the mask bitmap which is monochrome byte[] maskArray = GenerateMaskArray(width, height, colorArray); Invariant.Assert(maskArray != null); maskBitmap = UnsafeNativeMethods.CreateBitmap(width, height, 1, 1, maskArray); if ( maskBitmap.IsInvalid ) { // Note we will release the GDI resources in the finally block. return NativeMethods.IconHandle.GetInvalidIcon(); } // Now create HICON from two bitmaps. NativeMethods.ICONINFO iconInfo = new NativeMethods.ICONINFO(); iconInfo.fIcon = isIcon; // fIcon == ture means creating an Icon, otherwise Cursor iconInfo.xHotspot = xHotspot; iconInfo.yHotspot = yHotspot; iconInfo.hbmMask = maskBitmap; iconInfo.hbmColor = colorBitmap; return UnsafeNativeMethods.CreateIconIndirect(iconInfo); } finally { if (colorBitmap != null) { colorBitmap.Dispose(); colorBitmap = null; } if (maskBitmap != null) { maskBitmap.Dispose(); maskBitmap = null; } } } // generates the mask array for the input colorArray. // The mask array is 1 bpp private static byte[] GenerateMaskArray(int width, int height, byte[] colorArray) { int nCount = width * height; // NOTICE-2005/04/26-WAYNEZEN, // Check out the notes in CreateBitmap in MSDN. The scan line has to be aliged to WORD. int bytesPerScanLine = AlignToBytes(width, 2) / 8; byte[] bitsMask = new byte[bytesPerScanLine * height]; // We are scaning all pixels in color bitmap. // If the alpha value is 0, we should set the corresponding mask bit to 1. So the pixel will show // the screen pixel. Otherwise, we should set the mask bit to 0 which causes the cursor to display // the color bitmap pixel. for ( int i = 0; i < nCount; i++ ) { // Get the i-th pixel position (hPos, vPos) int hPos = i % width; int vPos = i / width; // For each byte in 2-bit color bitmap, the lowest the bit represents the right-most display pixel. // For example the bollow mask - // 1 1 1 0 0 0 0 1 // ^ ^ // offsetBit = 0x80 offsetBit = 0x01 int byteIndex = hPos / 8; byte offsetBit = (byte)( 0x80 >> ( hPos % 8 ) ); // Now we turn the mask on or off accordingly. if ( colorArray[i * 4 + 3] /* Alpha value since it's in Argb32 Format */ == 0x00 ) { // Set the mask bit to 1. bitsMask[byteIndex + bytesPerScanLine * vPos] |= (byte)offsetBit; } else { // Reset the mask bit to 0 bitsMask[byteIndex + bytesPerScanLine * vPos] &= (byte)( ~offsetBit ); } // Since the scan line of the mask bitmap has to be aligned to word. We have set all padding bits to 1. // So the extra pixel can be seen through. if ( hPos == width - 1 && width == 8 ) { bitsMask[1 + bytesPerScanLine * vPos] = 0xff; } } return bitsMask; } // Also used by PenCursorManager /// <summary> /// Calculate the bits count aligned to N-Byte based on the input count /// </summary> /// <param name="original">The original value</param> /// <param name="nBytesCount">N-Byte</param> /// <returns>the nearest bit count which is aligned to N-Byte</returns> internal static int AlignToBytes(double original, int nBytesCount) { Debug.Assert(nBytesCount > 0, "The N-Byte has to be greater than 0!"); int nBitsCount = 8 << (nBytesCount - 1); return (((int)Math.Ceiling(original) + (nBitsCount - 1)) / nBitsCount) * nBitsCount; } /// /// We're copying the algorithm Windows uses to pick icons. /// The comments and implementation are based on core\ntuser\client\clres.c /// /// MatchImage /// /// This function takes LPINTs for width & height in case of "real size". /// For this option, we use dimensions of 1st icon in resdir as size to /// load, instead of system metrics. /// Returns a number that measures how "far away" the given image is /// from a desired one. The value is 0 for an exact match. Note that our /// formula has the following properties: /// (1) Differences in width/height count much more than differences in /// color format. /// (2) Bigger images are better than smaller, since shrinking produces /// better results than stretching. /// (3) Color matching is done by the difference in bit depth. No /// preference is given to having a candidate equally different /// above and below the target. /// /// The formula is the sum of the following terms: /// abs(bppCandidate - bppTarget) /// abs(cxCandidate - cxTarget), times 2 if the image is /// narrower than what we'd like. This is because we will get a /// better result when consolidating more information into a smaller /// space, than when extrapolating from less information to more. /// abs(cxCandidate - cxTarget), times 2 if the image is /// shorter than what we'd like. This is for the same reason as /// the width. /// /// Let's step through an example. Suppose we want a 4bpp (16 color), /// 32x32 image. We would choose the various candidates in the following order: /// /// Candidate Score Formula /// /// 32x32x4bpp = 0 abs(32-32)*1 + abs(32-32)*1 + 2*abs(4-4)*1 /// 32x32x2bpp = 4 /// 32x32x8bpp = 8 /// 32x32x16bpp = 24 /// 48x48x4bpp = 32 /// 48x48x2bpp = 36 /// 48x48x8bpp = 40 /// 32x32x32bpp = 56 /// 48x48x16bpp = 56 abs(48-32)*1 + abs(48-32)*1 + 2*abs(16-4)*1 /// 16x16x4bpp = 64 /// 16x16x2bpp = 68 abs(16-32)*2 + abs(16-32)*2 + 2*abs(2-4)*1 /// 16x16x8bpp = 72 /// 48x48x32bpp = 88 abs(48-32)*1 + abs(48-32)*1 + 2*abs(32-4)*1 /// 16x16x16bpp = 88 /// 16x16x32bpp = 104 private static int MatchImage(BitmapFrame frame, Size size, int bpp) { /* * Here are the rules for our "match" formula: * (1) A close size match is much preferable to a color match * (2) Bigger icons are better than smaller * (3) The smaller the difference in bit depths the better */ int score = 2 * MyAbs(bpp, s_systemBitDepth, false) + MyAbs(frame.PixelWidth, (int)size.Width, true) + MyAbs(frame.PixelHeight, (int)size.Height, true); return score; } /// /// MyAbs (also from core\ntuser\client\clres.c) /// /// Calcules my weighted absolute value of the difference between 2 nums. /// This of course normalizes values to >= zero. But it can also "punish" the /// returned value by a factor of two if valueHave < valueWant. This is /// because you get worse results trying to extrapolate from less info up then /// interpolating from more info down. /// private static int MyAbs(int valueHave, int valueWant, bool fPunish) { int diff = (valueHave - valueWant); if (diff < 0) { diff = (fPunish ? -2 : -1) * diff; } return diff; } /// From a list of BitmapFrames find the one that best matches the requested dimensions. /// The methods used here are copied from Win32 sources. We want to be consistent with /// system behaviors. private static BitmapFrame GetBestMatch(ReadOnlyCollection<BitmapFrame> frames, Size size) { Invariant.Assert(size.Width != 0, "input param width should not be zero"); Invariant.Assert(size.Height != 0, "input param height should not be zero"); int bestScore = int.MaxValue; int bestBpp = 0; int bestIndex = 0; bool isBitmapIconDecoder = frames[0].Decoder is IconBitmapDecoder; for (int i = 0; i < frames.Count && bestScore != 0; ++i) { // determine the bit-depth (# of colors) in the // current frame // // if the icon is palettized, Format.BitsPerPixel gives // the # of bits required to index into the palette (thus, // the # of colors in the palette). If it is a true // color icon, it gives the # of bits required to support // true colors. // For icons, get the Format from the Thumbnail rather than from the // BitmapFrame directly because the unmanaged icon decoder // converts every icon to 32-bit. Thumbnail.Format.BitsPerPixel // will give us the original bit depth. int currentIconBitDepth = isBitmapIconDecoder ? frames[i].Thumbnail.Format.BitsPerPixel : frames[i].Format.BitsPerPixel; // If it looks like nothing is specified at this point, assume a bpp of 8. if (currentIconBitDepth == 0) { currentIconBitDepth = 8; } int score = MatchImage(frames[i], size, currentIconBitDepth); if (score < bestScore) { bestIndex = i; bestBpp = currentIconBitDepth; bestScore = score; } else if (score == bestScore) { // Tie breaker: choose the higher color depth. If that fails, choose first one. if (bestBpp < currentIconBitDepth) { bestIndex = i; bestBpp = currentIconBitDepth; } } } return frames[bestIndex]; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.Extensions.Logging; using OrchardCore.DisplayManagement.Descriptors; using OrchardCore.DisplayManagement.Shapes; using OrchardCore.DisplayManagement.Theming; using OrchardCore.Modules; namespace OrchardCore.DisplayManagement.Implementation { public class DefaultHtmlDisplay : IHtmlDisplay { private readonly IShapeTableManager _shapeTableManager; private readonly IEnumerable<IShapeDisplayEvents> _shapeDisplayEvents; private readonly IEnumerable<IShapeBindingResolver> _shapeBindingResolvers; private readonly IThemeManager _themeManager; private readonly IServiceProvider _serviceProvider; private readonly ILogger _logger; public DefaultHtmlDisplay( IEnumerable<IShapeDisplayEvents> shapeDisplayEvents, IEnumerable<IShapeBindingResolver> shapeBindingResolvers, IShapeTableManager shapeTableManager, IServiceProvider serviceProvider, ILogger<DefaultHtmlDisplay> logger, IThemeManager themeManager) { _shapeTableManager = shapeTableManager; _shapeDisplayEvents = shapeDisplayEvents; _shapeBindingResolvers = shapeBindingResolvers; _themeManager = themeManager; _serviceProvider = serviceProvider; _logger = logger; } public async Task<IHtmlContent> ExecuteAsync(DisplayContext context) { var shape = context.Value as IShape; // non-shape arguments are returned as a no-op if (shape == null) { return CoerceHtmlString(context.Value); } var shapeMetadata = shape.Metadata; // can't really cope with a shape that has no type information if (shapeMetadata == null || string.IsNullOrEmpty(shapeMetadata.Type)) { return CoerceHtmlString(context.Value); } // Copy the current context such that the rendering can customize it if necessary // For instance to change the HtmlFieldPrefix var localContext = new DisplayContext(context); localContext.HtmlFieldPrefix = shapeMetadata.Prefix ?? ""; var displayContext = new ShapeDisplayContext { Shape = shape, DisplayContext = localContext, ServiceProvider = _serviceProvider }; try { var theme = await _themeManager.GetThemeAsync(); var shapeTable = _shapeTableManager.GetShapeTable(theme?.Id); // Evaluate global Shape Display Events await _shapeDisplayEvents.InvokeAsync((e, displayContext) => e.DisplayingAsync(displayContext), displayContext, _logger); // Find base shape association using only the fundamental shape type. // Alternates that may already be registered do not affect the "displaying" event calls. var shapeDescriptor = GetShapeDescriptor(shapeMetadata.Type, shapeTable); if (shapeDescriptor != null) { await shapeDescriptor.DisplayingAsync.InvokeAsync((action, displayContext) => action(displayContext), displayContext, _logger); // copy all binding sources (all templates for this shape) in order to use them as Localization scopes shapeMetadata.BindingSources = shapeDescriptor.BindingSources.Where(x => x != null).ToList(); if (!shapeMetadata.BindingSources.Any()) { shapeMetadata.BindingSources.Add(shapeDescriptor.BindingSource); } } // invoking ShapeMetadata displaying events shapeMetadata.Displaying.Invoke(action => action(displayContext), _logger); // use pre-fetched content if available (e.g. coming from specific cache implementation) if (displayContext.ChildContent != null) { shape.Metadata.ChildContent = displayContext.ChildContent; } if (shape.Metadata.ChildContent == null) { // There might be no shape binding for the main shape, and only for its alternates. if (shapeDescriptor != null) { await shapeDescriptor.ProcessingAsync.InvokeAsync((action, displayContext) => action(displayContext), displayContext, _logger); } // now find the actual binding to render, taking alternates into account var actualBinding = await GetShapeBindingAsync(shapeMetadata.Type, shapeMetadata.Alternates, shapeTable); if (actualBinding != null) { await shapeMetadata.ProcessingAsync.InvokeAsync((action, displayContext) => action(displayContext.Shape), displayContext, _logger); shape.Metadata.ChildContent = await ProcessAsync(actualBinding, shape, localContext); } else { throw new Exception($"Shape type '{shapeMetadata.Type}' not found"); } } // Process wrappers if (shape.Metadata.Wrappers.Count > 0) { foreach (var frameType in shape.Metadata.Wrappers) { var frameBinding = await GetShapeBindingAsync(frameType, AlternatesCollection.Empty, shapeTable); if (frameBinding != null) { shape.Metadata.ChildContent = await ProcessAsync(frameBinding, shape, localContext); } } // Clear wrappers to prevent the child content from rendering them again shape.Metadata.Wrappers.Clear(); } await _shapeDisplayEvents.InvokeAsync(async (e, displayContext) => { var prior = displayContext.ChildContent = displayContext.Shape.Metadata.ChildContent; await e.DisplayedAsync(displayContext); // update the child content if the context variable has been reassigned if (prior != displayContext.ChildContent) { displayContext.Shape.Metadata.ChildContent = displayContext.ChildContent; } }, displayContext, _logger); if (shapeDescriptor != null) { await shapeDescriptor.DisplayedAsync.InvokeAsync(async (action, displayContext) => { var prior = displayContext.ChildContent = displayContext.Shape.Metadata.ChildContent; await action(displayContext); // update the child content if the context variable has been reassigned if (prior != displayContext.ChildContent) { displayContext.Shape.Metadata.ChildContent = displayContext.ChildContent; } }, displayContext, _logger); } // invoking ShapeMetadata displayed events shapeMetadata.Displayed.Invoke((action, displayContext) => action(displayContext), displayContext, _logger); } finally { await _shapeDisplayEvents.InvokeAsync((e, displayContext) => e.DisplayingFinalizedAsync(displayContext), displayContext, _logger); } return shape.Metadata.ChildContent; } private static ShapeDescriptor GetShapeDescriptor(string shapeType, ShapeTable shapeTable) { // Note: The shape type of a descriptor is a fundamental shape type that never contains // any '__' separator. If a shape type contains some '__' separators, its fundamental // shape type is the left part just before the 1st occurrence of the '__' separator. // As a fast path we 1st use the shapeType as is but it may contain some '__'. if (!shapeTable.Descriptors.TryGetValue(shapeType, out var shapeDescriptor)) { // Check if not a fundamental type. var index = shapeType.IndexOf("__", StringComparison.Ordinal); if (index > 0) { // Try again by using the fundamental shape type without any '__' separator. shapeTable.Descriptors.TryGetValue(shapeType.Substring(0, index), out shapeDescriptor); } } return shapeDescriptor; } private async Task<ShapeBinding> GetShapeBindingAsync(string shapeType, AlternatesCollection shapeAlternates, ShapeTable shapeTable) { // shape alternates are optional, fully qualified binding names // the earliest added alternates have the lowest priority // the descriptor returned is based on the binding that is matched, so it may be an entirely // different descriptor if the alternate has a different base name for (var i = shapeAlternates.Count - 1; i >= 0; i--) { var shapeAlternate = shapeAlternates[i]; foreach (var shapeBindingResolver in _shapeBindingResolvers) { var binding = await shapeBindingResolver.GetShapeBindingAsync(shapeAlternate); if (binding != null) { return binding; } } if (shapeTable.Bindings.TryGetValue(shapeAlternate, out var shapeBinding)) { return shapeBinding; } } // when no alternates match, the shapeType is used to find the longest matching binding // the shapetype name can break itself into shorter fallbacks at double-underscore marks // so the shapetype itself may contain a longer alternate forms that falls back to a shorter one var shapeTypeScan = shapeType; do { foreach (var shapeBindingResolver in _shapeBindingResolvers) { var binding = await shapeBindingResolver.GetShapeBindingAsync(shapeTypeScan); if (binding != null) { return binding; } } if (shapeTable.Bindings.TryGetValue(shapeTypeScan, out var shapeBinding)) { return shapeBinding; } } while (TryGetParentShapeTypeName(ref shapeTypeScan)); return null; } private static IHtmlContent CoerceHtmlString(object value) { if (value == null) { return null; } if (value is IHtmlContent result) { return result; // To prevent the result from being rendered lately, we can // serialize it right away. But performance seems to be better // like this, until we find this is an issue. //using (var html = new StringWriter()) //{ // result.WriteTo(html, htmlEncoder); // return new HtmlString(html.ToString()); //} } // Convert to a string and HTML-encode it return new StringHtmlContent(value.ToString()); } private static bool TryGetParentShapeTypeName(ref string shapeTypeScan) { var delimiterIndex = shapeTypeScan.LastIndexOf("__", StringComparison.Ordinal); if (delimiterIndex > 0) { shapeTypeScan = shapeTypeScan.Substring(0, delimiterIndex); return true; } return false; } private static ValueTask<IHtmlContent> ProcessAsync(ShapeBinding shapeBinding, IShape shape, DisplayContext context) { async ValueTask<IHtmlContent> Awaited(Task<IHtmlContent> task) { return CoerceHtmlString(await task); } if (shapeBinding?.BindingAsync == null) { // todo: create result from all child shapes return new ValueTask<IHtmlContent>(shape.Metadata.ChildContent ?? HtmlString.Empty); } var task = shapeBinding.BindingAsync(context); if (!task.IsCompletedSuccessfully) { return Awaited(task); } return new ValueTask<IHtmlContent>(CoerceHtmlString(task.Result)); } } }
using System; using System.Diagnostics; using Axiom.Core; using Axiom.Graphics; using Tao.Cg; namespace Axiom.CgPrograms { /// <summary> /// Specialization of HighLevelGpuProgram to provide support for nVidia's Cg language. /// </summary> /// <remarks> /// Cg can be used to compile common, high-level, C-like code down to assembler /// language for both GL and Direct3D, for multiple graphics cards. You must /// supply a list of profiles which your program must support using /// SetProfiles() before the program is loaded in order for this to work. The /// program will then negotiate with the renderer to compile the appropriate program /// for the API and graphics card capabilities. /// </remarks> public class CgProgram : HighLevelGpuProgram { #region Fields /// <summary> /// Current Cg context id. /// </summary> protected IntPtr cgContext; /// <summary> /// Current Cg program id. /// </summary> protected IntPtr cgProgram; /// <summary> /// Entry point of the Cg program. /// </summary> protected string entry; /// <summary> /// List of requested profiles for this program. /// </summary> protected string[] profiles; /// <summary> /// Chosen profile for this program. /// </summary> protected string selectedProfile; protected int selectedCgProfile; #endregion Fields #region Constructors /// <summary> /// Constructor. /// </summary> /// <param name="name">Name of this program.</param> /// <param name="type">Type of this program, vertex or fragment program.</param> /// <param name="language">HLSL language of this program.</param> /// <param name="context">CG context id.</param> public CgProgram(string name, GpuProgramType type, string language, IntPtr context) : base(name, type, language) { this.cgContext = context; } #endregion #region Methods protected void SelectProfile() { selectedProfile = ""; selectedCgProfile = Cg.CG_PROFILE_UNKNOWN; for(int i = 0; i < profiles.Length; i++) { if(GpuProgramManager.Instance.IsSyntaxSupported(profiles[i])) { selectedProfile = profiles[i]; selectedCgProfile = Cg.cgGetProfile(selectedProfile); CgHelper.CheckCgError("Unable to find Cg profile enum for program " + name, cgContext); break; } } } /// <summary> /// /// </summary> protected override void LoadFromSource() { SelectProfile(); string[] args = null; // This option causes an error with the CG 1.3 compiler if(selectedCgProfile == Cg.CG_PROFILE_VS_1_1) { args = new string[] {"-profileopts", "dcls", null}; } // create the Cg program cgProgram = Cg.cgCreateProgram(cgContext, Cg.CG_SOURCE, source, selectedCgProfile, entry, args); string cgErrStr = CgHelper.FormatCgError("Unable to compile Cg program " + name, cgContext); if (cgErrStr != null) { LogManager.Instance.Write("Unable to compile CG program {0}:\n{1}", name, cgErrStr); CgHelper.CheckCgError("Unable to compile Cg program " + name, cgContext); } } /// <summary> /// Create as assembler program from the compiled source supplied by the Cg compiler. /// </summary> protected override void CreateLowLevelImpl() { // retreive the string lowLevelSource = Cg.cgGetProgramString(cgProgram, Cg.CG_COMPILED_PROGRAM); // create a low-level program, with the same name as this one assemblerProgram = GpuProgramManager.Instance.CreateProgramFromString(name, lowLevelSource, type, selectedProfile); } /// <summary> /// /// </summary> /// <param name="parms"></param> protected override void PopulateParameterNames(GpuProgramParameters parms) { Debug.Assert(cgProgram != IntPtr.Zero); // Note use of 'leaf' format so we only get bottom-level params, not structs IntPtr param = Cg.cgGetFirstLeafParameter(cgProgram, Cg.CG_PROGRAM); int index = 0; // loop through the rest of the params while(param != IntPtr.Zero) { // get the type of this param up front int paramType = Cg.cgGetParameterType(param); // Look for uniform parameters only // Don't bother enumerating unused parameters, especially since they will // be optimized out and therefore not in the indexed versions if(Cg.cgIsParameterReferenced(param) != 0 && Cg.cgGetParameterVariability(param) == Cg.CG_UNIFORM && Cg.cgGetParameterDirection(param) != Cg.CG_OUT && paramType != Cg.CG_SAMPLER1D && paramType != Cg.CG_SAMPLER2D && paramType != Cg.CG_SAMPLER3D && paramType != Cg.CG_SAMPLERCUBE && paramType != Cg.CG_SAMPLERRECT) { // get the name and index of the program param string name = Cg.cgGetParameterName(param); // fp30 uses named rather than indexed params, so Cg returns // 0 for the index. However, we need the index to be unique here // Resource type 3256 doesn't have a define in the Cg header, so I assume // it means an unused or non-indexed params, since it is also returned // for programs that have a param that is not referenced in the program // and ends up getting pruned by the Cg compiler if(selectedCgProfile == Cg.CG_PROFILE_FP30) { // use a fake index just to order the named fp30 params index++; } else { // get the param constant index the normal way index = Cg.cgGetParameterResourceIndex(param); } // get the underlying resource type of this param // we need a special case for the register combiner // stage constants. int resource = Cg.cgGetParameterResource(param); // Get the parameter resource, so we know what type we're dealing with switch(resource) { case Cg.CG_COMBINER_STAGE_CONST0: // register combiner, const 0 // the index relates to the texture stage; store this as (stage * 2) + 0 index = index * 2; break; case Cg.CG_COMBINER_STAGE_CONST1: // register combiner, const 1 // the index relates to the texture stage; store this as (stage * 2) + 1 index = (index * 2) + 1; break; } // map the param to the index parms.MapParamNameToIndex(name, index); } // get the next param param = Cg.cgGetNextLeafParameter(param); } } /// <summary> /// Unloads the Cg program. /// </summary> protected override void UnloadHighLevelImpl() { // destroy this program if it had been loaded if (cgProgram != IntPtr.Zero) { Cg.cgDestroyProgram(cgProgram); CgHelper.CheckCgError(string.Format("Error unloading CgProgram named '{0}'", this.name), cgContext); cgProgram = IntPtr.Zero; } } /// <summary> /// Only bother with supported programs. /// </summary> public override void Touch() { if(this.IsSupported) { base.Touch (); } } #endregion #region Properties /// <summary> /// Returns whether or not this high level gpu program is supported on the current hardware. /// </summary> public override bool IsSupported { get { // If skeletal animation is being done, we need support for UBYTE4 if(this.IsSkeletalAnimationIncluded && !Root.Instance.RenderSystem.Caps.CheckCap(Capabilities.VertexFormatUByte4)) { return false; } // see if any profiles are supported for(int i = 0; i < profiles.Length; i++) { if(GpuProgramManager.Instance.IsSyntaxSupported(profiles[i])) { return true; } } // nope, SOL return false; } } public override int SamplerCount { get { switch (selectedProfile) { case "ps_1_1": case "ps_1_2": case "ps_1_3": case "fp20": return 4; case "ps_1_4": return 6; case "ps_2_0": case "ps_2_x": case "ps_3_0": case "ps_3_x": case "arbfp1": case "fp30": case "fp40": return 16; default: throw new AxiomException("Attempted to query sample count for unknown shader profile({0}).", selectedProfile); } } } #endregion #region IConfigurable Members /// <summary> /// Method for passing parameters into the CgProgram. /// </summary> /// <param name="name"> /// Param name. /// </param> /// <param name="val"> /// Param value. /// </param> public override bool SetParam(string name, string val) { bool handled = true; switch(name) { case "entry_point": entry = val; break; case "profiles": profiles = val.Split(' '); break; default: LogManager.Instance.Write("CgProgram: Unrecognized parameter '{0}'", name); handled = false; break; } return handled; } #endregion IConfigurable Members } }
// This file has been modified based on forum user suggestions. /* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * 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.Xml; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Collections; using System.Collections.Specialized; using System.Threading; using System.Net; namespace Reporting.Rdl { ///<summary> /// Represents an image. Source of image can from database, external or embedded. ///</summary> [Serializable] internal class Image : ReportItem { ImageSourceEnum _ImageSource; // Identifies the source of the image: Expression _Value; // See Source. Expected datatype is string or // binary, depending on Source. If the Value is // null, no image is displayed. Expression _MIMEType; // (string) An expression, the value of which is the // MIMEType for the image. // Valid values are: image/bmp, image/jpeg, // image/gif, image/png, image/x-png // Required if Source = Database. Ignored otherwise. ImageSizingEnum _Sizing; // Defines the behavior if the image does not fit within the specified size. bool _ConstantImage; // true if Image is a constant at runtime private string imageUrl; //Added from forum, User: solidstate http://www.fyireporting.com/forum/viewtopic.php?t=905 /// <summary> /// Only gets set for Images which contain urls rather than coming from the database etc.. /// </summary> public string ImageUrl { get { return imageUrl; } private set { imageUrl = value; } } internal Image(ReportDefn r, ReportLink p, XmlNode xNode):base(r,p,xNode) { _ImageSource=ImageSourceEnum.Unknown; _Value=null; _MIMEType=null; _Sizing=ImageSizingEnum.AutoSize; _ConstantImage = false; // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; switch (xNodeLoop.Name) { case "Source": _ImageSource = Reporting.Rdl.ImageSource.GetStyle(xNodeLoop.InnerText); break; case "Value": _Value = new Expression(r, this, xNodeLoop, ExpressionType.Variant); break; case "MIMEType": _MIMEType = new Expression(r, this, xNodeLoop, ExpressionType.String); break; case "Sizing": _Sizing = ImageSizing.GetStyle(xNodeLoop.InnerText, OwnerReport.rl); break; default: if (ReportItemElement(xNodeLoop)) // try at ReportItem level break; // don't know this element - log it OwnerReport.rl.LogError(4, "Unknown Image element " + xNodeLoop.Name + " ignored."); break; } } if (_ImageSource==ImageSourceEnum.Unknown) OwnerReport.rl.LogError(8, "Image requires a Source element."); if (_Value == null) OwnerReport.rl.LogError(8, "Image requires the Value element."); } // Handle parsing of function in final pass override internal void FinalPass() { base.FinalPass(); _Value.FinalPass(); if (_MIMEType != null) _MIMEType.FinalPass(); _ConstantImage = this.IsConstant(); return; } // Returns true if the image and style remain constant at runtime bool IsConstant() { if (_Value.IsConstant()) { if (_MIMEType == null || _MIMEType.IsConstant()) { // if (this.Style == null || this.Style.ConstantStyle) // return true; return true; // ok if style changes } } return false; } override internal void Run(IPresent ip, Row row) { base.Run(ip, row); string mtype=null; Stream strm=null; try { strm = GetImageStream(ip.Report(), row, out mtype); ip.Image(this, row, mtype, strm); } catch { // image failed to load; continue processing } finally { if (strm != null) strm.Close(); } return; } override internal void RunPage(Pages pgs, Row row) { Report r = pgs.Report; bool bHidden = IsHidden(r, row); WorkClass wc = GetWC(r); string mtype=null; Stream strm=null; System.Drawing.Image im=null; SetPagePositionBegin(pgs); if (bHidden) { PageImage pi = new PageImage(ImageFormat.Jpeg, null, 0, 0); this.SetPagePositionAndStyle(r, pi, row); SetPagePositionEnd(pgs, pi.Y + pi.H); return; } if (wc.PgImage != null) { // have we already generated this one // reuse most of the work; only position will likely change PageImage pi = new PageImage(wc.PgImage.ImgFormat, wc.PgImage.ImageData, wc.PgImage.SamplesW, wc.PgImage.SamplesH); pi.Name = wc.PgImage.Name; // this is name it will be shared under pi.Sizing = this._Sizing; this.SetPagePositionAndStyle(r, pi, row); pgs.CurrentPage.AddObject(pi); SetPagePositionEnd(pgs, pi.Y + pi.H); return; } try { strm = GetImageStream(r, row, out mtype); if (strm == null) { r.rl.LogError(4, string.Format("Unable to load image {0}.", this.Name.Nm)); return; } im = System.Drawing.Image.FromStream(strm); int height = im.Height; int width = im.Width; MemoryStream ostrm = new MemoryStream(); // 140208AJM Better JPEG Encoding ImageFormat imf; // if (mtype.ToLower() == "image/jpeg") //TODO: how do we get png to work // imf = ImageFormat.Jpeg; // else imf = ImageFormat.Jpeg; System.Drawing.Imaging.ImageCodecInfo[] info; info = ImageCodecInfo.GetImageEncoders(); EncoderParameters encoderParameters; encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, ImageQualityManager.EmbeddedImageQuality); System.Drawing.Imaging.ImageCodecInfo codec = null; for (int i = 0; i < info.Length; i++) { if (info[i].FormatDescription == "JPEG") { codec = info[i]; break; } } im.Save(ostrm, codec, encoderParameters); // im.Save(ostrm, imf, encoderParameters); //END 140208AJM byte[] ba = ostrm.ToArray(); ostrm.Close(); PageImage pi = new PageImage(imf, ba, width, height); pi.Sizing = this._Sizing; this.SetPagePositionAndStyle(r, pi, row); pgs.CurrentPage.AddObject(pi); if (_ConstantImage) { wc.PgImage = pi; // create unique name; PDF generation uses this to optimize the saving of the image only once pi.Name = "pi" + Interlocked.Increment(ref Parser.Counter).ToString(); // create unique name } SetPagePositionEnd(pgs, pi.Y + pi.H); } catch (Exception e) { // image failed to load, continue processing r.rl.LogError(4, "Image load failed. " + e.Message); } finally { if (strm != null) strm.Close(); if (im != null) im.Dispose(); } return; } Stream GetImageStream(Report rpt, Row row, out string mtype) { mtype=null; Stream strm=null; try { switch (this.ImageSource) { case ImageSourceEnum.Database: if (_MIMEType == null) return null; mtype = _MIMEType.EvaluateString(rpt, row); object o = _Value.Evaluate(rpt, row); strm = new MemoryStream((byte[]) o); break; case ImageSourceEnum.Embedded: string name = _Value.EvaluateString(rpt, row); EmbeddedImage ei = (EmbeddedImage) OwnerReport.LUEmbeddedImages[name]; mtype = ei.MIMEType; byte[] ba = Convert.FromBase64String(ei.ImageData); strm = new MemoryStream(ba); break; case ImageSourceEnum.External: //Added Image URL from forum, User: solidstate http://www.fyireporting.com/forum/viewtopic.php?t=905 string fname = this.ImageUrl = _Value.EvaluateString(rpt, row); mtype = GetMimeType(fname); if (fname.StartsWith("http:") || fname.StartsWith("file:") || fname.StartsWith("https:")) { WebRequest wreq = WebRequest.Create(fname); WebResponse wres = wreq.GetResponse(); strm = wres.GetResponseStream(); } else strm = new FileStream(fname, System.IO.FileMode.Open, FileAccess.Read); break; default: return null; } } catch (Exception e) { if (strm != null) { strm.Close(); strm = null; } rpt.rl.LogError(4, string.Format("Unable to load image. {0}", e.Message)); } return strm; } internal ImageSourceEnum ImageSource { get { return _ImageSource; } set { _ImageSource = value; } } internal Expression Value { get { return _Value; } set { _Value = value; } } internal Expression MIMEType { get { return _MIMEType; } set { _MIMEType = value; } } internal ImageSizingEnum Sizing { get { return _Sizing; } set { _Sizing = value; } } internal bool ConstantImage { get { return _ConstantImage; } } static internal string GetMimeType(string file) { String fileExt; int startPos = file.LastIndexOf(".") + 1; fileExt = file.Substring(startPos).ToLower(); switch (fileExt) { case "bmp": return "image/bmp"; case "jpeg": case "jpe": case "jpg": case "jfif": return "image/jpeg"; case "gif": return "image/gif"; case "png": return "image/png"; case "tif": case "tiff": return "image/tiff"; default: return null; } } private WorkClass GetWC(Report rpt) { WorkClass wc = rpt.Cache.Get(this, "wc") as WorkClass; if (wc == null) { wc = new WorkClass(); rpt.Cache.Add(this, "wc", wc); } return wc; } private void RemoveImageWC(Report rpt) { rpt.Cache.Remove(this, "wc"); } class WorkClass { internal PageImage PgImage; // When ConstantImage is true this will save the PageImage for reuse internal WorkClass() { PgImage=null; } } } }
using System.Collections.Generic; using System.Collections; using System.Text.RegularExpressions; using System.IO; using System.Linq; using System; namespace MixpanelSDK.UnityEditor.iOS.Xcode.PBX { internal class PBXObjectData { public string guid; protected PBXElementDict m_Properties = new PBXElementDict(); internal void SetPropertiesWhenSerializing(PBXElementDict props) { m_Properties = props; } internal PBXElementDict GetPropertiesWhenSerializing() { return m_Properties; } // returns null if it does not exist protected string GetPropertyString(string name) { var prop = m_Properties[name]; if (prop == null) return null; return prop.AsString(); } protected void SetPropertyString(string name, string value) { if (value == null) m_Properties.Remove(name); else m_Properties.SetString(name, value); } protected List<string> GetPropertyList(string name) { var prop = m_Properties[name]; if (prop == null) return null; var list = new List<string>(); foreach (var el in prop.AsArray().values) list.Add(el.AsString()); return list; } protected void SetPropertyList(string name, List<string> value) { if (value == null) m_Properties.Remove(name); else { var array = m_Properties.CreateArray(name); foreach (string val in value) array.AddString(val); } } private static PropertyCommentChecker checkerData = new PropertyCommentChecker(); internal virtual PropertyCommentChecker checker { get { return checkerData; } } internal virtual bool shouldCompact { get { return false; } } public virtual void UpdateProps() {} // Updates the props from cached variables public virtual void UpdateVars() {} // Updates the cached variables from underlying props } internal class PBXBuildFileData : PBXObjectData { public string fileRef; public string compileFlags; public bool weak; public List<string> assetTags; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "fileRef/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } internal override bool shouldCompact { get { return true; } } public static PBXBuildFileData CreateFromFile(string fileRefGUID, bool weak, string compileFlags) { PBXBuildFileData buildFile = new PBXBuildFileData(); buildFile.guid = PBXGUID.Generate(); buildFile.SetPropertyString("isa", "PBXBuildFile"); buildFile.fileRef = fileRefGUID; buildFile.compileFlags = compileFlags; buildFile.weak = weak; buildFile.assetTags = new List<string>(); return buildFile; } public override void UpdateProps() { SetPropertyString("fileRef", fileRef); PBXElementDict settings = null; if (m_Properties.Contains("settings")) settings = m_Properties["settings"].AsDict(); if (compileFlags != null && compileFlags != "") { if (settings == null) settings = m_Properties.CreateDict("settings"); settings.SetString("COMPILER_FLAGS", compileFlags); } else { if (settings != null) settings.Remove("COMPILER_FLAGS"); } if (weak) { if (settings == null) settings = m_Properties.CreateDict("settings"); PBXElementArray attrs = null; if (settings.Contains("ATTRIBUTES")) attrs = settings["ATTRIBUTES"].AsArray(); else attrs = settings.CreateArray("ATTRIBUTES"); bool exists = false; foreach (var value in attrs.values) { if (value is PBXElementString && value.AsString() == "Weak") exists = true; } if (!exists) attrs.AddString("Weak"); } else { if (settings != null && settings.Contains("ATTRIBUTES")) { var attrs = settings["ATTRIBUTES"].AsArray(); attrs.values.RemoveAll(el => (el is PBXElementString && el.AsString() == "Weak")); if (attrs.values.Count == 0) settings.Remove("ATTRIBUTES"); } } if (assetTags.Count > 0) { if (settings == null) settings = m_Properties.CreateDict("settings"); var tagsArray = settings.CreateArray("ASSET_TAGS"); foreach (string tag in assetTags) tagsArray.AddString(tag); } else { if (settings != null) settings.Remove("ASSET_TAGS"); } if (settings != null && settings.values.Count == 0) m_Properties.Remove("settings"); } public override void UpdateVars() { fileRef = GetPropertyString("fileRef"); compileFlags = null; weak = false; assetTags = new List<string>(); if (m_Properties.Contains("settings")) { var dict = m_Properties["settings"].AsDict(); if (dict.Contains("COMPILER_FLAGS")) compileFlags = dict["COMPILER_FLAGS"].AsString(); if (dict.Contains("ATTRIBUTES")) { var attrs = dict["ATTRIBUTES"].AsArray(); foreach (var value in attrs.values) { if (value is PBXElementString && value.AsString() == "Weak") weak = true; } } if (dict.Contains("ASSET_TAGS")) { var tags = dict["ASSET_TAGS"].AsArray(); foreach (var value in tags.values) assetTags.Add(value.AsString()); } } } } internal class PBXFileReferenceData : PBXObjectData { string m_Path = null; string m_ExplicitFileType = null; string m_LastKnownFileType = null; public string path { get { return m_Path; } set { m_ExplicitFileType = null; m_LastKnownFileType = null; m_Path = value; } } public string name; public PBXSourceTree tree; public bool isFolderReference { get { return m_LastKnownFileType != null && m_LastKnownFileType == "folder"; } } internal override bool shouldCompact { get { return true; } } public static PBXFileReferenceData CreateFromFile(string path, string projectFileName, PBXSourceTree tree) { string guid = PBXGUID.Generate(); PBXFileReferenceData fileRef = new PBXFileReferenceData(); fileRef.SetPropertyString("isa", "PBXFileReference"); fileRef.guid = guid; fileRef.path = path; fileRef.name = projectFileName; fileRef.tree = tree; return fileRef; } public static PBXFileReferenceData CreateFromFolderReference(string path, string projectFileName, PBXSourceTree tree) { var fileRef = CreateFromFile(path, projectFileName, tree); fileRef.m_LastKnownFileType = "folder"; return fileRef; } public override void UpdateProps() { string ext = null; if (m_ExplicitFileType != null) SetPropertyString("explicitFileType", m_ExplicitFileType); else if (m_LastKnownFileType != null) SetPropertyString("lastKnownFileType", m_LastKnownFileType); else { if (name != null) ext = Path.GetExtension(name); else if (m_Path != null) ext = Path.GetExtension(m_Path); if (ext != null) { if (FileTypeUtils.IsFileTypeExplicit(ext)) SetPropertyString("explicitFileType", FileTypeUtils.GetTypeName(ext)); else SetPropertyString("lastKnownFileType", FileTypeUtils.GetTypeName(ext)); } } if (m_Path == name) SetPropertyString("name", null); else SetPropertyString("name", name); if (m_Path == null) SetPropertyString("path", ""); else SetPropertyString("path", m_Path); SetPropertyString("sourceTree", FileTypeUtils.SourceTreeDesc(tree)); } public override void UpdateVars() { name = GetPropertyString("name"); m_Path = GetPropertyString("path"); if (name == null) name = m_Path; if (m_Path == null) m_Path = ""; tree = FileTypeUtils.ParseSourceTree(GetPropertyString("sourceTree")); m_ExplicitFileType = GetPropertyString("explicitFileType"); m_LastKnownFileType = GetPropertyString("lastKnownFileType"); } } class GUIDList : IEnumerable<string> { private List<string> m_List = new List<string>(); public GUIDList() {} public GUIDList(List<string> data) { m_List = data; } public static implicit operator List<string>(GUIDList list) { return list.m_List; } public static implicit operator GUIDList(List<string> data) { return new GUIDList(data); } public void AddGUID(string guid) { m_List.Add(guid); } public void RemoveGUID(string guid) { m_List.RemoveAll(x => x == guid); } public bool Contains(string guid) { return m_List.Contains(guid); } public int Count { get { return m_List.Count; } } public void Clear() { m_List.Clear(); } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return m_List.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return m_List.GetEnumerator(); } } internal class XCConfigurationListData : PBXObjectData { public GUIDList buildConfigs; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildConfigurations/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static XCConfigurationListData Create() { var res = new XCConfigurationListData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "XCConfigurationList"); res.buildConfigs = new GUIDList(); res.SetPropertyString("defaultConfigurationIsVisible", "0"); return res; } public override void UpdateProps() { SetPropertyList("buildConfigurations", buildConfigs); } public override void UpdateVars() { buildConfigs = GetPropertyList("buildConfigurations"); } } internal class PBXGroupData : PBXObjectData { public GUIDList children; public PBXSourceTree tree; public string name, path; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "children/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } // name must not contain '/' public static PBXGroupData Create(string name, string path, PBXSourceTree tree) { if (name.Contains("/")) throw new Exception("Group name must not contain '/'"); PBXGroupData gr = new PBXGroupData(); gr.guid = PBXGUID.Generate(); gr.SetPropertyString("isa", "PBXGroup"); gr.name = name; gr.path = path; gr.tree = PBXSourceTree.Group; gr.children = new GUIDList(); return gr; } public static PBXGroupData CreateRelative(string name) { return Create(name, name, PBXSourceTree.Group); } public override void UpdateProps() { // The name property is set only if it is different from the path property SetPropertyList("children", children); if (name == path) SetPropertyString("name", null); else SetPropertyString("name", name); if (path == "") SetPropertyString("path", null); else SetPropertyString("path", path); SetPropertyString("sourceTree", FileTypeUtils.SourceTreeDesc(tree)); } public override void UpdateVars() { children = GetPropertyList("children"); path = GetPropertyString("path"); name = GetPropertyString("name"); if (name == null) name = path; if (path == null) path = ""; tree = FileTypeUtils.ParseSourceTree(GetPropertyString("sourceTree")); } } internal class PBXVariantGroupData : PBXGroupData { } internal class PBXNativeTargetData : PBXObjectData { public GUIDList phases; public string buildConfigList; // guid public string name; public GUIDList dependencies; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildPhases/*", "buildRules/*", "dependencies/*", "productReference/*", "buildConfigurationList/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXNativeTargetData Create(string name, string productRef, string productType, string buildConfigList) { var res = new PBXNativeTargetData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXNativeTarget"); res.buildConfigList = buildConfigList; res.phases = new GUIDList(); res.SetPropertyList("buildRules", new List<string>()); res.dependencies = new GUIDList(); res.name = name; res.SetPropertyString("productName", name); res.SetPropertyString("productReference", productRef); res.SetPropertyString("productType", productType); return res; } public override void UpdateProps() { SetPropertyString("buildConfigurationList", buildConfigList); SetPropertyString("name", name); SetPropertyList("buildPhases", phases); SetPropertyList("dependencies", dependencies); } public override void UpdateVars() { buildConfigList = GetPropertyString("buildConfigurationList"); name = GetPropertyString("name"); phases = GetPropertyList("buildPhases"); dependencies = GetPropertyList("dependencies"); } } internal class FileGUIDListBase : PBXObjectData { public GUIDList files; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "files/*", }); internal override PropertyCommentChecker checker { get { return checkerData; } } public override void UpdateProps() { SetPropertyList("files", files); } public override void UpdateVars() { files = GetPropertyList("files"); } } internal class PBXSourcesBuildPhaseData : FileGUIDListBase { public static PBXSourcesBuildPhaseData Create() { var res = new PBXSourcesBuildPhaseData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXSourcesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXFrameworksBuildPhaseData : FileGUIDListBase { public static PBXFrameworksBuildPhaseData Create() { var res = new PBXFrameworksBuildPhaseData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXFrameworksBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXResourcesBuildPhaseData : FileGUIDListBase { public static PBXResourcesBuildPhaseData Create() { var res = new PBXResourcesBuildPhaseData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXResourcesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXCopyFilesBuildPhaseData : FileGUIDListBase { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "files/*", }); internal override PropertyCommentChecker checker { get { return checkerData; } } public string name; // name may be null public static PBXCopyFilesBuildPhaseData Create(string name, string subfolderSpec) { var res = new PBXCopyFilesBuildPhaseData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXCopyFilesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.SetPropertyString("dstPath", ""); res.SetPropertyString("dstSubfolderSpec", subfolderSpec); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); res.name = name; return res; } public override void UpdateProps() { SetPropertyList("files", files); SetPropertyString("name", name); } public override void UpdateVars() { files = GetPropertyList("files"); name = GetPropertyString("name"); } } internal class PBXShellScriptBuildPhaseData : PBXObjectData { public GUIDList files; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "files/*", }); internal override PropertyCommentChecker checker { get { return checkerData; } } public override void UpdateProps() { SetPropertyList("files", files); } public override void UpdateVars() { files = GetPropertyList("files"); } } internal class BuildConfigEntryData { public string name; public List<string> val = new List<string>(); public static string ExtractValue(string src) { return PBXStream.UnquoteString(src.Trim().TrimEnd(',')); } public void AddValue(string value) { if (!val.Contains(value)) val.Add(value); } public void RemoveValue(string value) { val.RemoveAll(v => v == value); } public static BuildConfigEntryData FromNameValue(string name, string value) { BuildConfigEntryData ret = new BuildConfigEntryData(); ret.name = name; ret.AddValue(value); return ret; } } internal class XCBuildConfigurationData : PBXObjectData { protected SortedDictionary<string, BuildConfigEntryData> entries = new SortedDictionary<string, BuildConfigEntryData>(); public string name { get { return GetPropertyString("name"); } } // Note that QuoteStringIfNeeded does its own escaping. Double-escaping with quotes is // required to please Xcode that does not handle paths with spaces if they are not // enclosed in quotes. static string EscapeWithQuotesIfNeeded(string name, string value) { if (name != "LIBRARY_SEARCH_PATHS") return value; if (!value.Contains(" ")) return value; if (value.First() == '\"' && value.Last() == '\"') return value; return "\"" + value + "\""; } public void SetProperty(string name, string value) { entries[name] = BuildConfigEntryData.FromNameValue(name, EscapeWithQuotesIfNeeded(name, value)); } public void AddProperty(string name, string value) { if (entries.ContainsKey(name)) entries[name].AddValue(EscapeWithQuotesIfNeeded(name, value)); else SetProperty(name, value); } public void RemoveProperty(string name) { if (entries.ContainsKey(name)) entries.Remove(name); } public void RemovePropertyValue(string name, string value) { if (entries.ContainsKey(name)) entries[name].RemoveValue(EscapeWithQuotesIfNeeded(name, value)); } // name should be either release or debug public static XCBuildConfigurationData Create(string name) { var res = new XCBuildConfigurationData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "XCBuildConfiguration"); res.SetPropertyString("name", name); return res; } public override void UpdateProps() { var dict = m_Properties.CreateDict("buildSettings"); foreach (var kv in entries) { if (kv.Value.val.Count == 0) continue; else if (kv.Value.val.Count == 1) dict.SetString(kv.Key, kv.Value.val[0]); else // kv.Value.val.Count > 1 { var array = dict.CreateArray(kv.Key); foreach (var value in kv.Value.val) array.AddString(value); } } } public override void UpdateVars() { entries = new SortedDictionary<string, BuildConfigEntryData>(); if (m_Properties.Contains("buildSettings")) { var dict = m_Properties["buildSettings"].AsDict(); foreach (var key in dict.values.Keys) { var value = dict[key]; if (value is PBXElementString) { if (entries.ContainsKey(key)) entries[key].val.Add(value.AsString()); else entries.Add(key, BuildConfigEntryData.FromNameValue(key, value.AsString())); } else if (value is PBXElementArray) { foreach (var pvalue in value.AsArray().values) { if (pvalue is PBXElementString) { if (entries.ContainsKey(key)) entries[key].val.Add(pvalue.AsString()); else entries.Add(key, BuildConfigEntryData.FromNameValue(key, pvalue.AsString())); } } } } } } } internal class PBXContainerItemProxyData : PBXObjectData { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "containerPortal/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXContainerItemProxyData Create(string containerRef, string proxyType, string remoteGlobalGUID, string remoteInfo) { var res = new PBXContainerItemProxyData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXContainerItemProxy"); res.SetPropertyString("containerPortal", containerRef); // guid res.SetPropertyString("proxyType", proxyType); res.SetPropertyString("remoteGlobalIDString", remoteGlobalGUID); // guid res.SetPropertyString("remoteInfo", remoteInfo); return res; } } internal class PBXReferenceProxyData : PBXObjectData { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "remoteRef/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public string path { get { return GetPropertyString("path"); } } public static PBXReferenceProxyData Create(string path, string fileType, string remoteRef, string sourceTree) { var res = new PBXReferenceProxyData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXReferenceProxy"); res.SetPropertyString("path", path); res.SetPropertyString("fileType", fileType); res.SetPropertyString("remoteRef", remoteRef); res.SetPropertyString("sourceTree", sourceTree); return res; } } internal class PBXTargetDependencyData : PBXObjectData { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "target/*", "targetProxy/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXTargetDependencyData Create(string target, string targetProxy) { var res = new PBXTargetDependencyData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXTargetDependency"); res.SetPropertyString("target", target); res.SetPropertyString("targetProxy", targetProxy); return res; } } internal class ProjectReference { public string group; // guid public string projectRef; // guid public static ProjectReference Create(string group, string projectRef) { var res = new ProjectReference(); res.group = group; res.projectRef = projectRef; return res; } } internal class PBXProjectObjectData : PBXObjectData { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildConfigurationList/*", "mainGroup/*", "projectReferences/*/ProductGroup/*", "projectReferences/*/ProjectRef/*", "targets/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public List<ProjectReference> projectReferences = new List<ProjectReference>(); public string mainGroup { get { return GetPropertyString("mainGroup"); } } public List<string> targets = new List<string>(); public List<string> knownAssetTags = new List<string>(); public string buildConfigList; public void AddReference(string productGroup, string projectRef) { projectReferences.Add(ProjectReference.Create(productGroup, projectRef)); } public override void UpdateProps() { m_Properties.values.Remove("projectReferences"); if (projectReferences.Count > 0) { var array = m_Properties.CreateArray("projectReferences"); foreach (var value in projectReferences) { var dict = array.AddDict(); dict.SetString("ProductGroup", value.group); dict.SetString("ProjectRef", value.projectRef); } }; SetPropertyList("targets", targets); SetPropertyString("buildConfigurationList", buildConfigList); if (knownAssetTags.Count > 0) { PBXElementDict attrs; if (m_Properties.Contains("attributes")) attrs = m_Properties["attributes"].AsDict(); else attrs = m_Properties.CreateDict("attributes"); var tags = attrs.CreateArray("knownAssetTags"); foreach (var tag in knownAssetTags) tags.AddString(tag); } } public override void UpdateVars() { projectReferences = new List<ProjectReference>(); if (m_Properties.Contains("projectReferences")) { var el = m_Properties["projectReferences"].AsArray(); foreach (var value in el.values) { PBXElementDict dict = value.AsDict(); if (dict.Contains("ProductGroup") && dict.Contains("ProjectRef")) { string group = dict["ProductGroup"].AsString(); string projectRef = dict["ProjectRef"].AsString(); projectReferences.Add(ProjectReference.Create(group, projectRef)); } } } targets = GetPropertyList("targets"); buildConfigList = GetPropertyString("buildConfigurationList"); // update knownAssetTags knownAssetTags = new List<string>(); if (m_Properties.Contains("attributes")) { var el = m_Properties["attributes"].AsDict(); if (el.Contains("knownAssetTags")) { var tags = el["knownAssetTags"].AsArray(); foreach (var tag in tags.values) knownAssetTags.Add(tag.AsString()); } } } } } // namespace MixpanelSDK.UnityEditor.iOS.Xcode
using System; using System.ComponentModel.DataAnnotations; using Dongle.Web.ModelAttributes; using NUnit.Framework; namespace Dongle.Web.Tests.Mvc.ModelAttributes { [TestFixture] public class RequiredIfAttributeTests { public class TestClass { public string DependentPropertyString { get; set; } public int DependentPropertyInt32 { get; set; } public int? DependentPropertyNullableInt32 { get; set; } public bool DependentPropertyBool { get; set; } public bool? DependentPropertyNullableBool { get; set; } } #region Null values passed in [Test] public void Validate_DependentStringMatches_NullValue_Throws() { var instance = new TestClass { DependentPropertyString = "ConditionalValue" }; var attr = new WRequiredIfAttribute("DependentPropertyString", "ConditionalValue"); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(null, validationContext)); } [Test] public void Validate_DependentNullMatches_NullValue_Throws() { var instance = new TestClass { DependentPropertyString = null }; var attr = new WRequiredIfAttribute("DependentPropertyString", null); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(null, validationContext)); } [Test] public void Validate_DependentInt32Matches_NullValue_Throws() { var instance = new TestClass { DependentPropertyInt32 = 123 }; var attr = new WRequiredIfAttribute("DependentPropertyInt32", 123); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(null, validationContext)); } [Test] public void Validate_DependentNullableInt32Matches_NullValue_Throws() { var instance = new TestClass { DependentPropertyNullableInt32 = 123 }; var attr = new WRequiredIfAttribute("DependentPropertyNullableInt32", 123); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(null, validationContext)); } [Test] public void Validate_DependentNullableInt32NullMatches_NullValue_Throws() { var instance = new TestClass { DependentPropertyNullableInt32 = null }; var attr = new WRequiredIfAttribute("DependentPropertyNullableInt32", null); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(null, validationContext)); } [Test] public void Validate_DependentBoolMatches_NullValue_Throws() { var instance = new TestClass { DependentPropertyBool = true }; var attr = new WRequiredIfAttribute("DependentPropertyBool", true); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(null, validationContext)); } [Test] public void Validate_DependentNullableBoolMatches_NullValue_Throws() { var instance = new TestClass { DependentPropertyNullableBool = true }; var attr = new WRequiredIfAttribute("DependentPropertyNullableBool", true); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(null, validationContext)); } [Test] public void Validate_DependentNullableBoolNullMatches_NullValue_Throws() { var instance = new TestClass { DependentPropertyNullableBool = null }; var attr = new WRequiredIfAttribute("DependentPropertyNullableBool", null); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(null, validationContext)); } #endregion #region String.Empty passed in [Test] public void Validate_DependentStringMatches_EmptyStringValue_Throws() { var instance = new TestClass { DependentPropertyString = "ConditionalValue" }; var attr = new WRequiredIfAttribute("DependentPropertyString", "ConditionalValue"); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(String.Empty, validationContext)); } [Test] public void Validate_DependentNullMatches_EmptyStringValue_Throws() { var instance = new TestClass { DependentPropertyString = null }; var attr = new WRequiredIfAttribute("DependentPropertyString", null); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(String.Empty, validationContext)); } [Test] public void Validate_DependentInt32Matches_EmptyStringValue_Throws() { var instance = new TestClass { DependentPropertyInt32 = 123 }; var attr = new WRequiredIfAttribute("DependentPropertyInt32", 123); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(String.Empty, validationContext)); } [Test] public void Validate_DependentNullableInt32Matches_EmptyStringValue_Throws() { var instance = new TestClass { DependentPropertyNullableInt32 = 123 }; var attr = new WRequiredIfAttribute("DependentPropertyNullableInt32", 123); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(String.Empty, validationContext)); } [Test] public void Validate_DependentNullableInt32NullMatches_EmptyStringValue_Throws() { var instance = new TestClass { DependentPropertyNullableInt32 = null }; var attr = new WRequiredIfAttribute("DependentPropertyNullableInt32", null); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(String.Empty, validationContext)); } [Test] public void Validate_DependentBoolMatches_EmptyStringValue_Throws() { var instance = new TestClass { DependentPropertyBool = true }; var attr = new WRequiredIfAttribute("DependentPropertyBool", true); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(String.Empty, validationContext)); } [Test] public void Validate_DependentNullableBoolMatches_EmptyStringValue_Throws() { var instance = new TestClass { DependentPropertyNullableBool = true }; var attr = new WRequiredIfAttribute("DependentPropertyNullableBool", true); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(String.Empty, validationContext)); } [Test] public void Validate_DependentNullableBoolNullMatches_EmptyStringValue_Throws() { var instance = new TestClass { DependentPropertyNullableBool = null }; var attr = new WRequiredIfAttribute("DependentPropertyNullableBool", null); var validationContext = new ValidationContext(instance, null, null); Assert.Throws<ValidationException>(() => attr.Validate(String.Empty, validationContext)); } #endregion #region Non-null values passed in [Test] public void Validate_DependentStringMatches_NonNullValue_DoesNotThrow() { var instance = new TestClass { DependentPropertyString = "ConditionalValue" }; var attr = new WRequiredIfAttribute("DependentPropertyString", "ConditionalValue"); var validationContext = new ValidationContext(instance, null, null); attr.Validate("Non null text", validationContext); } [Test] public void Validate_DependentNullMatches_NonNullValue_DoesNotThrow() { var instance = new TestClass { DependentPropertyString = null }; var attr = new WRequiredIfAttribute("DependentPropertyString", null); var validationContext = new ValidationContext(instance, null, null); attr.Validate("Non null text", validationContext); } [Test] public void Validate_DependentInt32Matches_NonNullValue_DoesNotThrow() { var instance = new TestClass { DependentPropertyInt32 = 123 }; var attr = new WRequiredIfAttribute("DependentPropertyInt32", 123); var validationContext = new ValidationContext(instance, null, null); attr.Validate("Non null text", validationContext); } [Test] public void Validate_DependentNullableInt32Matches_NonNullValue_DoesNotThrow() { var instance = new TestClass { DependentPropertyNullableInt32 = 123 }; var attr = new WRequiredIfAttribute("DependentPropertyNullableInt32", 123); var validationContext = new ValidationContext(instance, null, null); attr.Validate("Non null text", validationContext); } [Test] public void Validate_DependentNullableInt32NullMatches_NonNullValue_DoesNotThrow() { var instance = new TestClass { DependentPropertyNullableInt32 = null }; var attr = new WRequiredIfAttribute("DependentPropertyNullableInt32", null); var validationContext = new ValidationContext(instance, null, null); attr.Validate("Non null text", validationContext); } [Test] public void Validate_DependentBoolMatches_NonNullValue_DoesNotThrow() { var instance = new TestClass { DependentPropertyBool = true }; var attr = new WRequiredIfAttribute("DependentPropertyBool", true); var validationContext = new ValidationContext(instance, null, null); attr.Validate("Non null text", validationContext); } [Test] public void Validate_DependentNullableBoolMatches_NonNullValue_DoesNotThrow() { var instance = new TestClass { DependentPropertyNullableBool = true }; var attr = new WRequiredIfAttribute("DependentPropertyNullableBool", true); var validationContext = new ValidationContext(instance, null, null); attr.Validate("Non null text", validationContext); } [Test] public void Validate_DependentNullableBoolNullMatches_NonNullValue_DoesNotThrow() { var instance = new TestClass { DependentPropertyNullableBool = null }; var attr = new WRequiredIfAttribute("DependentPropertyNullableBool", null); var validationContext = new ValidationContext(instance, null, null); attr.Validate("Non null text", validationContext); } #endregion #region Error messages [Test] public void FormatErrorMessage_CustomMessage_MatchesSpecifiedMessage() { var message = "{0} custom message"; var attr = new WRequiredIfAttribute("Dummy", "Dummy") { ErrorMessage = message }; var custommsg = attr.FormatErrorMessage("NAME"); Assert.AreEqual(String.Format(message, "NAME"), custommsg); } #endregion } }
// 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 Roslyn.Test.Utilities; using Roslyn.Test.Utilities.Parallel; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { [ParallelFixture] public class IfKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AtRoot_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterClass_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalStatement_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalVariableDeclaration_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInUsingAlias() { VerifyAbsence( @"using Foo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInPreprocessor1() { VerifyAbsence(AddInsideMethod( "#if $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void EmptyStatement() { VerifyKeyword(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterHash() { VerifyKeyword( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterHashFollowedBySkippedTokens() { VerifyKeyword( @"#$$ aeu"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterHashAndSpace() { VerifyKeyword( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideMethod() { VerifyKeyword(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void BeforeStatement() { VerifyKeyword(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterStatement() { VerifyKeyword(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterBlock() { VerifyKeyword(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterIf() { VerifyAbsence(AddInsideMethod( @"if $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCase() { VerifyKeyword(AddInsideMethod( @"switch (true) { case 0: $$ }")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCaseBlock() { VerifyKeyword(AddInsideMethod( @"switch (true) { case 0: { $$ } }")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDefaultCase() { VerifyKeyword(AddInsideMethod( @"switch (true) { default: $$ }")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDefaultCaseBlock() { VerifyKeyword(AddInsideMethod( @"switch (true) { default: { $$ } }")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterLabel() { VerifyKeyword(AddInsideMethod( @"label: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterDoBlock() { VerifyAbsence(AddInsideMethod( @"do { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InActiveRegion1() { VerifyKeyword(AddInsideMethod( @"#if true $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InActiveRegion2() { VerifyKeyword(AddInsideMethod( @"#if true $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterElse() { VerifyKeyword(AddInsideMethod( @"if (foo) { } else $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterCatch() { VerifyAbsence(AddInsideMethod( @"try {} catch $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterCatchDeclaration1() { VerifyAbsence(AddInsideMethod( @"try {} catch (Exception) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterCatchDeclaration2() { VerifyAbsence(AddInsideMethod( @"try {} catch (Exception e) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterCatchDeclarationEmpty() { VerifyAbsence(AddInsideMethod( @"try {} catch () $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterTryBlock() { VerifyAbsence(AddInsideMethod( @"try {} $$")); } } }
namespace AxiomCoders.PdfTemplateEditor { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form 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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.pnlProperties = new System.Windows.Forms.Panel(); this.PropertySplitContainer = new System.Windows.Forms.SplitContainer(); this.propertyGrid = new System.Windows.Forms.PropertyGrid(); this.tvItems = new System.Windows.Forms.TreeView(); this.cmbObjects = new System.Windows.Forms.ComboBox(); this.AutoSaveTimer = new System.Windows.Forms.Timer(this.components); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.mainToolContainer = new System.Windows.Forms.ToolStripContainer(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.miFile = new System.Windows.Forms.ToolStripMenuItem(); this.miNewProject = new System.Windows.Forms.ToolStripMenuItem(); this.miOpenProject = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.miSave = new System.Windows.Forms.ToolStripMenuItem(); this.miSaveAs = new System.Windows.Forms.ToolStripMenuItem(); this.miClose = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.editProjectInformationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.miExit = new System.Windows.Forms.ToolStripMenuItem(); this.miEdit = new System.Windows.Forms.ToolStripMenuItem(); this.miUndo = new System.Windows.Forms.ToolStripMenuItem(); this.miRedo = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.miCut = new System.Windows.Forms.ToolStripMenuItem(); this.miCopy = new System.Windows.Forms.ToolStripMenuItem(); this.miPaste = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator(); this.miPreferences = new System.Windows.Forms.ToolStripMenuItem(); this.miGeneral = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator(); this.miUnitsRulers = new System.Windows.Forms.ToolStripMenuItem(); this.miGuidesGrids = new System.Windows.Forms.ToolStripMenuItem(); this.miTools = new System.Windows.Forms.ToolStripMenuItem(); this.miDataStreams = new System.Windows.Forms.ToolStripMenuItem(); this.miView = new System.Windows.Forms.ToolStripMenuItem(); this.miShowGrid = new System.Windows.Forms.ToolStripMenuItem(); this.miShowRulers = new System.Windows.Forms.ToolStripMenuItem(); this.miShowBalloonBorders = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator18 = new System.Windows.Forms.ToolStripSeparator(); this.themesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.professionalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.systemToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.miHelp = new System.Windows.Forms.ToolStripMenuItem(); this.pdfReportsHelpContentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pdfReportsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.axiomCodersOnlineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.axiomCodersWebsiteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pdfReportsWebsiteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pdfReportsSuportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator17 = new System.Windows.Forms.ToolStripSeparator(); this.purchaseALicenseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator15 = new System.Windows.Forms.ToolStripSeparator(); this.releaseNotesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator16 = new System.Windows.Forms.ToolStripSeparator(); this.miAbout = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip2 = new System.Windows.Forms.ToolStrip(); this.tbbNewProject = new System.Windows.Forms.ToolStripButton(); this.tbbOpenProject = new System.Windows.Forms.ToolStripButton(); this.tbbSaveProject = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator13 = new System.Windows.Forms.ToolStripSeparator(); this.tbbCut = new System.Windows.Forms.ToolStripButton(); this.tbbCopy = new System.Windows.Forms.ToolStripButton(); this.tbbPaste = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator14 = new System.Windows.Forms.ToolStripSeparator(); this.tbbUndo = new System.Windows.Forms.ToolStripButton(); this.tbbRedo = new System.Windows.Forms.ToolStripButton(); this.AlignStrip = new System.Windows.Forms.ToolStrip(); this.toolSnapToGrid = new System.Windows.Forms.ToolStripButton(); this.toolLeftAlign = new System.Windows.Forms.ToolStripButton(); this.toolAlignCentarV = new System.Windows.Forms.ToolStripButton(); this.toolAlignRight = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.toolAlignTop = new System.Windows.Forms.ToolStripButton(); this.toolAlignCentarH = new System.Windows.Forms.ToolStripButton(); this.toolAlignBottom = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.toolSameWidth = new System.Windows.Forms.ToolStripButton(); this.toolSameHeight = new System.Windows.Forms.ToolStripButton(); this.toolSameSize = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.toolSameHSpacing = new System.Windows.Forms.ToolStripButton(); this.toolncHSpacing = new System.Windows.Forms.ToolStripButton(); this.toolDecHSpacing = new System.Windows.Forms.ToolStripButton(); this.toolNoHSpacing = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.toolSameVSpacing = new System.Windows.Forms.ToolStripButton(); this.toolIncVSpacing = new System.Windows.Forms.ToolStripButton(); this.toolDecVSpacing = new System.Windows.Forms.ToolStripButton(); this.toolNoVSpacing = new System.Windows.Forms.ToolStripButton(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.tbbHeight2 = new System.Windows.Forms.ToolStripButton(); this.tbbHeight3 = new System.Windows.Forms.ToolStripButton(); this.tbbHeight4 = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator(); this.tbbWidth2 = new System.Windows.Forms.ToolStripButton(); this.tbbWidth3 = new System.Windows.Forms.ToolStripButton(); this.tbbWidth4 = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator(); this.tbbSendToBack = new System.Windows.Forms.ToolStripButton(); this.tbbBringToFront = new System.Windows.Forms.ToolStripButton(); this.tbbStripOne = new System.Windows.Forms.ToolStrip(); this.tbbArrowItem = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.tbbZoom = new System.Windows.Forms.ToolStripSplitButton(); this.miZoom50 = new System.Windows.Forms.ToolStripMenuItem(); this.miZoom100 = new System.Windows.Forms.ToolStripMenuItem(); this.miZoom150 = new System.Windows.Forms.ToolStripMenuItem(); this.miZoom200 = new System.Windows.Forms.ToolStripMenuItem(); this.tbbPreviewButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton3 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton4 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton5 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton6 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton7 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton11 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton8 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton9 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton10 = new System.Windows.Forms.ToolStripButton(); this.pnlProperties.SuspendLayout(); this.PropertySplitContainer.Panel1.SuspendLayout(); this.PropertySplitContainer.Panel2.SuspendLayout(); this.PropertySplitContainer.SuspendLayout(); this.mainToolContainer.TopToolStripPanel.SuspendLayout(); this.mainToolContainer.SuspendLayout(); this.menuStrip1.SuspendLayout(); this.toolStrip2.SuspendLayout(); this.AlignStrip.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.tbbStripOne.SuspendLayout(); this.SuspendLayout(); // // pnlProperties // this.pnlProperties.Controls.Add(this.PropertySplitContainer); this.pnlProperties.Controls.Add(this.cmbObjects); this.pnlProperties.Dock = System.Windows.Forms.DockStyle.Right; this.pnlProperties.Location = new System.Drawing.Point(898, 133); this.pnlProperties.Name = "pnlProperties"; this.pnlProperties.Size = new System.Drawing.Size(292, 461); this.pnlProperties.TabIndex = 2; // // PropertySplitContainer // this.PropertySplitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.PropertySplitContainer.Location = new System.Drawing.Point(0, 21); this.PropertySplitContainer.Name = "PropertySplitContainer"; this.PropertySplitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal; // // PropertySplitContainer.Panel1 // this.PropertySplitContainer.Panel1.Controls.Add(this.propertyGrid); // // PropertySplitContainer.Panel2 // this.PropertySplitContainer.Panel2.Controls.Add(this.tvItems); this.PropertySplitContainer.Size = new System.Drawing.Size(292, 440); this.PropertySplitContainer.SplitterDistance = 233; this.PropertySplitContainer.TabIndex = 2; // // propertyGrid // this.propertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.propertyGrid.Location = new System.Drawing.Point(0, 0); this.propertyGrid.Name = "propertyGrid"; this.propertyGrid.Size = new System.Drawing.Size(292, 233); this.propertyGrid.TabIndex = 1; this.propertyGrid.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.propertyGrid_PropertyValueChanged); // // tvItems // this.tvItems.Dock = System.Windows.Forms.DockStyle.Fill; this.tvItems.HideSelection = false; this.tvItems.Location = new System.Drawing.Point(0, 0); this.tvItems.Name = "tvItems"; this.tvItems.Size = new System.Drawing.Size(292, 203); this.tvItems.TabIndex = 0; this.tvItems.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvItems_AfterSelect); this.tvItems.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tvItems_KeyDown); // // cmbObjects // this.cmbObjects.Dock = System.Windows.Forms.DockStyle.Top; this.cmbObjects.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbObjects.FlatStyle = System.Windows.Forms.FlatStyle.System; this.cmbObjects.FormattingEnabled = true; this.cmbObjects.Location = new System.Drawing.Point(0, 0); this.cmbObjects.Name = "cmbObjects"; this.cmbObjects.Size = new System.Drawing.Size(292, 21); this.cmbObjects.TabIndex = 1; this.cmbObjects.SelectedValueChanged += new System.EventHandler(this.cmbObjects_SelectedValueChanged); // // AutoSaveTimer // this.AutoSaveTimer.Enabled = true; this.AutoSaveTimer.Interval = 1000; this.AutoSaveTimer.Tick += new System.EventHandler(this.myTimer_Tick); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "magnifying-glass-search-find.png"); // // mainToolContainer // this.mainToolContainer.BottomToolStripPanelVisible = false; // // mainToolContainer.ContentPanel // this.mainToolContainer.ContentPanel.BackColor = System.Drawing.SystemColors.Control; this.mainToolContainer.ContentPanel.Size = new System.Drawing.Size(1190, 9); this.mainToolContainer.ContentPanel.Visible = false; this.mainToolContainer.Dock = System.Windows.Forms.DockStyle.Top; this.mainToolContainer.LeftToolStripPanelVisible = false; this.mainToolContainer.Location = new System.Drawing.Point(0, 0); this.mainToolContainer.Name = "mainToolContainer"; this.mainToolContainer.RightToolStripPanelVisible = false; this.mainToolContainer.Size = new System.Drawing.Size(1190, 133); this.mainToolContainer.TabIndex = 11; this.mainToolContainer.Text = "toolStripContainer1"; // // mainToolContainer.TopToolStripPanel // this.mainToolContainer.TopToolStripPanel.BackColor = System.Drawing.Color.Transparent; this.mainToolContainer.TopToolStripPanel.Controls.Add(this.menuStrip1); this.mainToolContainer.TopToolStripPanel.Controls.Add(this.toolStrip2); this.mainToolContainer.TopToolStripPanel.Controls.Add(this.AlignStrip); this.mainToolContainer.TopToolStripPanel.Controls.Add(this.toolStrip1); this.mainToolContainer.TopToolStripPanel.Controls.Add(this.tbbStripOne); // // menuStrip1 // this.menuStrip1.Dock = System.Windows.Forms.DockStyle.None; this.menuStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible; this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miFile, this.miEdit, this.miTools, this.miView, this.miHelp}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1190, 24); this.menuStrip1.TabIndex = 12; this.menuStrip1.Text = "menuStrip1"; // // miFile // this.miFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miNewProject, this.miOpenProject, this.toolStripSeparator2, this.miSave, this.miSaveAs, this.miClose, this.toolStripMenuItem1, this.editProjectInformationToolStripMenuItem, this.toolStripMenuItem2, this.miExit}); this.miFile.Name = "miFile"; this.miFile.Size = new System.Drawing.Size(37, 20); this.miFile.Text = "&File"; // // miNewProject // this.miNewProject.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.NewProject; this.miNewProject.Name = "miNewProject"; this.miNewProject.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.miNewProject.Size = new System.Drawing.Size(249, 22); this.miNewProject.Text = "&New Project..."; this.miNewProject.Click += new System.EventHandler(this.miNewProject_Click); // // miOpenProject // this.miOpenProject.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Open; this.miOpenProject.Name = "miOpenProject"; this.miOpenProject.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.miOpenProject.Size = new System.Drawing.Size(249, 22); this.miOpenProject.Text = "&Open Project..."; this.miOpenProject.Click += new System.EventHandler(this.miOpenProject_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(246, 6); // // miSave // this.miSave.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.SaveAs; this.miSave.Name = "miSave"; this.miSave.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.miSave.Size = new System.Drawing.Size(249, 22); this.miSave.Text = "&Save"; this.miSave.Click += new System.EventHandler(this.miSave_Click); // // miSaveAs // this.miSaveAs.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Save; this.miSaveAs.Name = "miSaveAs"; this.miSaveAs.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift) | System.Windows.Forms.Keys.S))); this.miSaveAs.Size = new System.Drawing.Size(249, 22); this.miSaveAs.Text = "Save &As..."; this.miSaveAs.Click += new System.EventHandler(this.miSaveAs_Click); // // miClose // this.miClose.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Close; this.miClose.Name = "miClose"; this.miClose.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F4))); this.miClose.Size = new System.Drawing.Size(249, 22); this.miClose.Text = "&Close"; this.miClose.Click += new System.EventHandler(this.miClose_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(246, 6); // // editProjectInformationToolStripMenuItem // this.editProjectInformationToolStripMenuItem.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.application_edit; this.editProjectInformationToolStripMenuItem.Name = "editProjectInformationToolStripMenuItem"; this.editProjectInformationToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.E))); this.editProjectInformationToolStripMenuItem.Size = new System.Drawing.Size(249, 22); this.editProjectInformationToolStripMenuItem.Text = "&Edit Project Information..."; this.editProjectInformationToolStripMenuItem.Click += new System.EventHandler(this.editProjectInformationToolStripMenuItem_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(246, 6); // // miExit // this.miExit.Image = ((System.Drawing.Image)(resources.GetObject("miExit.Image"))); this.miExit.Name = "miExit"; this.miExit.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F4))); this.miExit.Size = new System.Drawing.Size(249, 22); this.miExit.Text = "E&xit"; this.miExit.Click += new System.EventHandler(this.miExit_Click); // // miEdit // this.miEdit.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miUndo, this.miRedo, this.toolStripMenuItem3, this.miCut, this.miCopy, this.miPaste, this.toolStripSeparator11, this.miPreferences}); this.miEdit.Name = "miEdit"; this.miEdit.Size = new System.Drawing.Size(39, 20); this.miEdit.Text = "&Edit"; // // miUndo // this.miUndo.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Undo; this.miUndo.Name = "miUndo"; this.miUndo.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z))); this.miUndo.Size = new System.Drawing.Size(147, 22); this.miUndo.Text = "&Undo"; this.miUndo.Click += new System.EventHandler(this.miUndo_Click); // // miRedo // this.miRedo.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Redo; this.miRedo.Name = "miRedo"; this.miRedo.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.R))); this.miRedo.Size = new System.Drawing.Size(147, 22); this.miRedo.Text = "&Redo"; this.miRedo.Click += new System.EventHandler(this.miRedo_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(144, 6); // // miCut // this.miCut.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Cut; this.miCut.Name = "miCut"; this.miCut.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.miCut.Size = new System.Drawing.Size(147, 22); this.miCut.Text = "Cu&t"; this.miCut.Click += new System.EventHandler(this.miCut_Click); // // miCopy // this.miCopy.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Copy; this.miCopy.Name = "miCopy"; this.miCopy.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C))); this.miCopy.Size = new System.Drawing.Size(147, 22); this.miCopy.Text = "&Copy "; this.miCopy.Click += new System.EventHandler(this.miCopy_Click); // // miPaste // this.miPaste.Enabled = false; this.miPaste.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Paste; this.miPaste.Name = "miPaste"; this.miPaste.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V))); this.miPaste.Size = new System.Drawing.Size(147, 22); this.miPaste.Text = "&Paste"; this.miPaste.Click += new System.EventHandler(this.miPaste_Click); // // toolStripSeparator11 // this.toolStripSeparator11.Name = "toolStripSeparator11"; this.toolStripSeparator11.Size = new System.Drawing.Size(144, 6); // // miPreferences // this.miPreferences.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miGeneral, this.toolStripSeparator12, this.miUnitsRulers, this.miGuidesGrids}); this.miPreferences.Enabled = false; this.miPreferences.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Preferences; this.miPreferences.Name = "miPreferences"; this.miPreferences.Size = new System.Drawing.Size(147, 22); this.miPreferences.Text = "&Preferences"; // // miGeneral // this.miGeneral.Name = "miGeneral"; this.miGeneral.Size = new System.Drawing.Size(148, 22); this.miGeneral.Text = "&General"; this.miGeneral.Click += new System.EventHandler(this.miGeneral_Click); // // toolStripSeparator12 // this.toolStripSeparator12.Name = "toolStripSeparator12"; this.toolStripSeparator12.Size = new System.Drawing.Size(145, 6); // // miUnitsRulers // this.miUnitsRulers.Name = "miUnitsRulers"; this.miUnitsRulers.Size = new System.Drawing.Size(148, 22); this.miUnitsRulers.Text = "&Units, Rulers..."; this.miUnitsRulers.Click += new System.EventHandler(this.miUnitsRulers_Click); // // miGuidesGrids // this.miGuidesGrids.Name = "miGuidesGrids"; this.miGuidesGrids.Size = new System.Drawing.Size(148, 22); this.miGuidesGrids.Text = "Guides, G&rid..."; this.miGuidesGrids.Click += new System.EventHandler(this.miGuidesGrids_Click); // // miTools // this.miTools.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miDataStreams}); this.miTools.Name = "miTools"; this.miTools.Size = new System.Drawing.Size(48, 20); this.miTools.Text = "&Tools"; // // miDataStreams // this.miDataStreams.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.DataStream; this.miDataStreams.Name = "miDataStreams"; this.miDataStreams.Size = new System.Drawing.Size(143, 22); this.miDataStreams.Text = "&Data Streams"; this.miDataStreams.Click += new System.EventHandler(this.miDataStreams_Click); // // miView // this.miView.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miShowGrid, this.miShowRulers, this.miShowBalloonBorders, this.toolStripSeparator18, this.themesToolStripMenuItem}); this.miView.Name = "miView"; this.miView.Size = new System.Drawing.Size(44, 20); this.miView.Text = "&View"; // // miShowGrid // this.miShowGrid.CheckOnClick = true; this.miShowGrid.Name = "miShowGrid"; this.miShowGrid.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.G))); this.miShowGrid.Size = new System.Drawing.Size(230, 22); this.miShowGrid.Text = "Show &Grid"; this.miShowGrid.Click += new System.EventHandler(this.miShowGrid_Click); // // miShowRulers // this.miShowRulers.CheckOnClick = true; this.miShowRulers.Enabled = false; this.miShowRulers.Name = "miShowRulers"; this.miShowRulers.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.R))); this.miShowRulers.Size = new System.Drawing.Size(230, 22); this.miShowRulers.Text = "Show &Ruler"; this.miShowRulers.Click += new System.EventHandler(this.miShowRulers_Click); // // miShowBalloonBorders // this.miShowBalloonBorders.CheckOnClick = true; this.miShowBalloonBorders.Name = "miShowBalloonBorders"; this.miShowBalloonBorders.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.B))); this.miShowBalloonBorders.Size = new System.Drawing.Size(230, 22); this.miShowBalloonBorders.Text = "Show &Balloon Borders"; this.miShowBalloonBorders.Click += new System.EventHandler(this.miShowBalloonBorders_Click); // // toolStripSeparator18 // this.toolStripSeparator18.Name = "toolStripSeparator18"; this.toolStripSeparator18.Size = new System.Drawing.Size(227, 6); // // themesToolStripMenuItem // this.themesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.professionalToolStripMenuItem, this.systemToolStripMenuItem}); this.themesToolStripMenuItem.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.palette; this.themesToolStripMenuItem.Name = "themesToolStripMenuItem"; this.themesToolStripMenuItem.Size = new System.Drawing.Size(230, 22); this.themesToolStripMenuItem.Text = "&Themes"; // // professionalToolStripMenuItem // this.professionalToolStripMenuItem.Checked = true; this.professionalToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.professionalToolStripMenuItem.Name = "professionalToolStripMenuItem"; this.professionalToolStripMenuItem.Size = new System.Drawing.Size(138, 22); this.professionalToolStripMenuItem.Text = "&Professional"; this.professionalToolStripMenuItem.Click += new System.EventHandler(this.professionalToolStripMenuItem_Click); // // systemToolStripMenuItem // this.systemToolStripMenuItem.Name = "systemToolStripMenuItem"; this.systemToolStripMenuItem.Size = new System.Drawing.Size(138, 22); this.systemToolStripMenuItem.Text = "&System"; this.systemToolStripMenuItem.Click += new System.EventHandler(this.systemToolStripMenuItem_Click); // // miHelp // this.miHelp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.pdfReportsHelpContentsToolStripMenuItem, this.pdfReportsToolStripMenuItem, this.toolStripSeparator8, this.axiomCodersOnlineToolStripMenuItem, this.toolStripSeparator15, this.releaseNotesToolStripMenuItem, this.toolStripSeparator16, this.miAbout}); this.miHelp.Name = "miHelp"; this.miHelp.Size = new System.Drawing.Size(44, 20); this.miHelp.Text = "&Help"; // // pdfReportsHelpContentsToolStripMenuItem // this.pdfReportsHelpContentsToolStripMenuItem.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.book_help; this.pdfReportsHelpContentsToolStripMenuItem.Name = "pdfReportsHelpContentsToolStripMenuItem"; this.pdfReportsHelpContentsToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F1; this.pdfReportsHelpContentsToolStripMenuItem.Size = new System.Drawing.Size(242, 22); this.pdfReportsHelpContentsToolStripMenuItem.Text = "Pdf Reports Help &Contents..."; this.pdfReportsHelpContentsToolStripMenuItem.Click += new System.EventHandler(this.pdfReportsHelpContentsToolStripMenuItem_Click); // // pdfReportsToolStripMenuItem // this.pdfReportsToolStripMenuItem.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.book_open_help; this.pdfReportsToolStripMenuItem.Name = "pdfReportsToolStripMenuItem"; this.pdfReportsToolStripMenuItem.Size = new System.Drawing.Size(242, 22); this.pdfReportsToolStripMenuItem.Text = "Pdf Reports Help &Index..."; this.pdfReportsToolStripMenuItem.Click += new System.EventHandler(this.pdfReportsToolStripMenuItem_Click); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; this.toolStripSeparator8.Size = new System.Drawing.Size(239, 6); // // axiomCodersOnlineToolStripMenuItem // this.axiomCodersOnlineToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.axiomCodersWebsiteToolStripMenuItem, this.pdfReportsWebsiteToolStripMenuItem, this.pdfReportsSuportToolStripMenuItem, this.toolStripSeparator17, this.purchaseALicenseToolStripMenuItem}); this.axiomCodersOnlineToolStripMenuItem.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Online; this.axiomCodersOnlineToolStripMenuItem.Name = "axiomCodersOnlineToolStripMenuItem"; this.axiomCodersOnlineToolStripMenuItem.Size = new System.Drawing.Size(242, 22); this.axiomCodersOnlineToolStripMenuItem.Text = "AxiomCoders &Online"; // // axiomCodersWebsiteToolStripMenuItem // this.axiomCodersWebsiteToolStripMenuItem.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.OnLineLink; this.axiomCodersWebsiteToolStripMenuItem.Name = "axiomCodersWebsiteToolStripMenuItem"; this.axiomCodersWebsiteToolStripMenuItem.Size = new System.Drawing.Size(199, 22); this.axiomCodersWebsiteToolStripMenuItem.Text = "AxiomCoders &Website..."; this.axiomCodersWebsiteToolStripMenuItem.Click += new System.EventHandler(this.axiomCodersWebsiteToolStripMenuItem_Click); // // pdfReportsWebsiteToolStripMenuItem // this.pdfReportsWebsiteToolStripMenuItem.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.OnLineLink; this.pdfReportsWebsiteToolStripMenuItem.Name = "pdfReportsWebsiteToolStripMenuItem"; this.pdfReportsWebsiteToolStripMenuItem.Size = new System.Drawing.Size(199, 22); this.pdfReportsWebsiteToolStripMenuItem.Text = "&Pdf Reports Website..."; this.pdfReportsWebsiteToolStripMenuItem.Click += new System.EventHandler(this.pdfReportsWebsiteToolStripMenuItem_Click); // // pdfReportsSuportToolStripMenuItem // this.pdfReportsSuportToolStripMenuItem.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.OnLineLink; this.pdfReportsSuportToolStripMenuItem.Name = "pdfReportsSuportToolStripMenuItem"; this.pdfReportsSuportToolStripMenuItem.Size = new System.Drawing.Size(199, 22); this.pdfReportsSuportToolStripMenuItem.Text = "Pdf Reports &Suport..."; this.pdfReportsSuportToolStripMenuItem.Click += new System.EventHandler(this.pdfReportsSuportToolStripMenuItem_Click); // // toolStripSeparator17 // this.toolStripSeparator17.Name = "toolStripSeparator17"; this.toolStripSeparator17.Size = new System.Drawing.Size(196, 6); // // purchaseALicenseToolStripMenuItem // this.purchaseALicenseToolStripMenuItem.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.OnLineLink; this.purchaseALicenseToolStripMenuItem.Name = "purchaseALicenseToolStripMenuItem"; this.purchaseALicenseToolStripMenuItem.Size = new System.Drawing.Size(199, 22); this.purchaseALicenseToolStripMenuItem.Text = "&Purchase a License..."; this.purchaseALicenseToolStripMenuItem.Click += new System.EventHandler(this.purchaseALicenseToolStripMenuItem_Click); // // toolStripSeparator15 // this.toolStripSeparator15.Name = "toolStripSeparator15"; this.toolStripSeparator15.Size = new System.Drawing.Size(239, 6); // // releaseNotesToolStripMenuItem // this.releaseNotesToolStripMenuItem.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.note; this.releaseNotesToolStripMenuItem.Name = "releaseNotesToolStripMenuItem"; this.releaseNotesToolStripMenuItem.Size = new System.Drawing.Size(242, 22); this.releaseNotesToolStripMenuItem.Text = "&Release Notes..."; this.releaseNotesToolStripMenuItem.Click += new System.EventHandler(this.releaseNotesToolStripMenuItem_Click); // // toolStripSeparator16 // this.toolStripSeparator16.Name = "toolStripSeparator16"; this.toolStripSeparator16.Size = new System.Drawing.Size(239, 6); // // miAbout // this.miAbout.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.About; this.miAbout.Name = "miAbout"; this.miAbout.Size = new System.Drawing.Size(242, 22); this.miAbout.Text = "&About..."; this.miAbout.Click += new System.EventHandler(this.miAbout_Click); // // toolStrip2 // this.toolStrip2.Dock = System.Windows.Forms.DockStyle.None; this.toolStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tbbNewProject, this.tbbOpenProject, this.tbbSaveProject, this.toolStripSeparator13, this.tbbCut, this.tbbCopy, this.tbbPaste, this.toolStripSeparator14, this.tbbUndo, this.tbbRedo}); this.toolStrip2.Location = new System.Drawing.Point(3, 24); this.toolStrip2.Name = "toolStrip2"; this.toolStrip2.Size = new System.Drawing.Size(208, 25); this.toolStrip2.TabIndex = 10; this.toolStrip2.Text = "toolStrip2"; // // tbbNewProject // this.tbbNewProject.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbNewProject.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.NewProject; this.tbbNewProject.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbNewProject.Name = "tbbNewProject"; this.tbbNewProject.Size = new System.Drawing.Size(23, 22); this.tbbNewProject.Text = "New"; this.tbbNewProject.Click += new System.EventHandler(this.tbbNewProject_Click); // // tbbOpenProject // this.tbbOpenProject.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbOpenProject.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Open; this.tbbOpenProject.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbOpenProject.Name = "tbbOpenProject"; this.tbbOpenProject.Size = new System.Drawing.Size(23, 22); this.tbbOpenProject.Text = "Open"; this.tbbOpenProject.Click += new System.EventHandler(this.tbbOpenProject_Click); // // tbbSaveProject // this.tbbSaveProject.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbSaveProject.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.SaveAs; this.tbbSaveProject.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbSaveProject.Name = "tbbSaveProject"; this.tbbSaveProject.Size = new System.Drawing.Size(23, 22); this.tbbSaveProject.Text = "Save"; this.tbbSaveProject.Click += new System.EventHandler(this.tbbSaveProject_Click); // // toolStripSeparator13 // this.toolStripSeparator13.Name = "toolStripSeparator13"; this.toolStripSeparator13.Size = new System.Drawing.Size(6, 25); // // tbbCut // this.tbbCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbCut.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Cut; this.tbbCut.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbCut.Name = "tbbCut"; this.tbbCut.Size = new System.Drawing.Size(23, 22); this.tbbCut.Text = "Cut"; this.tbbCut.Click += new System.EventHandler(this.tbbCut_Click); // // tbbCopy // this.tbbCopy.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbCopy.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Copy; this.tbbCopy.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbCopy.Name = "tbbCopy"; this.tbbCopy.Size = new System.Drawing.Size(23, 22); this.tbbCopy.Text = "Copy"; this.tbbCopy.Click += new System.EventHandler(this.tbbCopy_Click); // // tbbPaste // this.tbbPaste.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbPaste.Enabled = false; this.tbbPaste.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Paste; this.tbbPaste.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbPaste.Name = "tbbPaste"; this.tbbPaste.Size = new System.Drawing.Size(23, 22); this.tbbPaste.Text = "Paste"; this.tbbPaste.Click += new System.EventHandler(this.tbbPaste_Click); // // toolStripSeparator14 // this.toolStripSeparator14.Name = "toolStripSeparator14"; this.toolStripSeparator14.Size = new System.Drawing.Size(6, 25); // // tbbUndo // this.tbbUndo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbUndo.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Undo; this.tbbUndo.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbUndo.Name = "tbbUndo"; this.tbbUndo.Size = new System.Drawing.Size(23, 22); this.tbbUndo.Text = "Undo"; this.tbbUndo.Click += new System.EventHandler(this.tbbUndo_Click); // // tbbRedo // this.tbbRedo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbRedo.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Redo; this.tbbRedo.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbRedo.Name = "tbbRedo"; this.tbbRedo.Size = new System.Drawing.Size(23, 22); this.tbbRedo.Text = "Redo"; this.tbbRedo.Click += new System.EventHandler(this.tbbRedo_Click); // // AlignStrip // this.AlignStrip.Dock = System.Windows.Forms.DockStyle.None; this.AlignStrip.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.AlignStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolSnapToGrid, this.toolLeftAlign, this.toolAlignCentarV, this.toolAlignRight, this.toolStripSeparator4, this.toolAlignTop, this.toolAlignCentarH, this.toolAlignBottom, this.toolStripSeparator5, this.toolSameWidth, this.toolSameHeight, this.toolSameSize, this.toolStripSeparator6, this.toolSameHSpacing, this.toolncHSpacing, this.toolDecHSpacing, this.toolNoHSpacing, this.toolStripSeparator7, this.toolSameVSpacing, this.toolIncVSpacing, this.toolDecVSpacing, this.toolNoVSpacing}); this.AlignStrip.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow; this.AlignStrip.Location = new System.Drawing.Point(3, 49); this.AlignStrip.Name = "AlignStrip"; this.AlignStrip.Size = new System.Drawing.Size(427, 25); this.AlignStrip.TabIndex = 11; // // toolSnapToGrid // this.toolSnapToGrid.CheckOnClick = true; this.toolSnapToGrid.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolSnapToGrid.Enabled = false; this.toolSnapToGrid.Image = ((System.Drawing.Image)(resources.GetObject("toolSnapToGrid.Image"))); this.toolSnapToGrid.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolSnapToGrid.Name = "toolSnapToGrid"; this.toolSnapToGrid.Size = new System.Drawing.Size(62, 22); this.toolSnapToGrid.Text = "Snap tp G"; this.toolSnapToGrid.ToolTipText = "Snaps object to grid"; this.toolSnapToGrid.Visible = false; // // toolLeftAlign // this.toolLeftAlign.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolLeftAlign.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.AlignLeft; this.toolLeftAlign.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolLeftAlign.Name = "toolLeftAlign"; this.toolLeftAlign.Size = new System.Drawing.Size(23, 22); this.toolLeftAlign.Text = "Left"; this.toolLeftAlign.Click += new System.EventHandler(this.toolLeftAlign_Click); // // toolAlignCentarV // this.toolAlignCentarV.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolAlignCentarV.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.AlignCenter; this.toolAlignCentarV.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolAlignCentarV.Name = "toolAlignCentarV"; this.toolAlignCentarV.Size = new System.Drawing.Size(23, 22); this.toolAlignCentarV.Text = "Centar (V)"; this.toolAlignCentarV.Click += new System.EventHandler(this.toolAlignCentarV_Click); // // toolAlignRight // this.toolAlignRight.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolAlignRight.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.AlignRight; this.toolAlignRight.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolAlignRight.Name = "toolAlignRight"; this.toolAlignRight.Size = new System.Drawing.Size(23, 22); this.toolAlignRight.Text = "Right"; this.toolAlignRight.Click += new System.EventHandler(this.toolAlignRight_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25); // // toolAlignTop // this.toolAlignTop.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolAlignTop.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.AlignTop; this.toolAlignTop.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolAlignTop.Name = "toolAlignTop"; this.toolAlignTop.Size = new System.Drawing.Size(23, 22); this.toolAlignTop.Text = "Top"; this.toolAlignTop.Click += new System.EventHandler(this.toolAlignTop_Click); // // toolAlignCentarH // this.toolAlignCentarH.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolAlignCentarH.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.AlignMiddle; this.toolAlignCentarH.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolAlignCentarH.Name = "toolAlignCentarH"; this.toolAlignCentarH.Size = new System.Drawing.Size(23, 22); this.toolAlignCentarH.Text = "Centar (H)"; this.toolAlignCentarH.Click += new System.EventHandler(this.toolAlignCentarH_Click); // // toolAlignBottom // this.toolAlignBottom.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolAlignBottom.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.AlignBottom; this.toolAlignBottom.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolAlignBottom.Name = "toolAlignBottom"; this.toolAlignBottom.Size = new System.Drawing.Size(23, 22); this.toolAlignBottom.Text = "Bottom"; this.toolAlignBottom.Click += new System.EventHandler(this.toolAlignBottom_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25); // // toolSameWidth // this.toolSameWidth.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolSameWidth.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.make_same_width; this.toolSameWidth.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolSameWidth.Name = "toolSameWidth"; this.toolSameWidth.Size = new System.Drawing.Size(23, 22); this.toolSameWidth.Text = "Make Same Width"; this.toolSameWidth.Click += new System.EventHandler(this.toolSameWidth_Click); // // toolSameHeight // this.toolSameHeight.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolSameHeight.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.make_same_height; this.toolSameHeight.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolSameHeight.Name = "toolSameHeight"; this.toolSameHeight.Size = new System.Drawing.Size(23, 22); this.toolSameHeight.Text = "Make Same Height"; this.toolSameHeight.Click += new System.EventHandler(this.toolSameHeight_Click); // // toolSameSize // this.toolSameSize.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolSameSize.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.make_same_sizes; this.toolSameSize.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolSameSize.Name = "toolSameSize"; this.toolSameSize.Size = new System.Drawing.Size(23, 22); this.toolSameSize.Text = "Make Same Sizes"; this.toolSameSize.Click += new System.EventHandler(this.toolSameSize_Click); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25); // // toolSameHSpacing // this.toolSameHSpacing.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolSameHSpacing.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.make_same_h_space; this.toolSameHSpacing.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolSameHSpacing.Name = "toolSameHSpacing"; this.toolSameHSpacing.Size = new System.Drawing.Size(23, 22); this.toolSameHSpacing.Text = "Same H Space"; this.toolSameHSpacing.ToolTipText = "Same Horizontal Spacing"; this.toolSameHSpacing.Click += new System.EventHandler(this.toolSameHSpacing_Click); // // toolncHSpacing // this.toolncHSpacing.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolncHSpacing.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.increase_h_space; this.toolncHSpacing.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolncHSpacing.Name = "toolncHSpacing"; this.toolncHSpacing.Size = new System.Drawing.Size(23, 22); this.toolncHSpacing.Text = "Inc H Space"; this.toolncHSpacing.ToolTipText = "Increase Horizontal Spacing"; this.toolncHSpacing.Click += new System.EventHandler(this.toolncHSpacing_Click); // // toolDecHSpacing // this.toolDecHSpacing.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolDecHSpacing.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.decrease_h_space; this.toolDecHSpacing.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolDecHSpacing.Name = "toolDecHSpacing"; this.toolDecHSpacing.Size = new System.Drawing.Size(23, 22); this.toolDecHSpacing.Text = "Dec H Space"; this.toolDecHSpacing.ToolTipText = "Decrease Horizontal Spacing"; this.toolDecHSpacing.Click += new System.EventHandler(this.toolDecHSpacing_Click); // // toolNoHSpacing // this.toolNoHSpacing.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolNoHSpacing.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.make_no_h_space; this.toolNoHSpacing.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolNoHSpacing.Name = "toolNoHSpacing"; this.toolNoHSpacing.Size = new System.Drawing.Size(23, 22); this.toolNoHSpacing.Text = "No Horizontal Spacing"; this.toolNoHSpacing.Click += new System.EventHandler(this.toolNoHSpacing_Click); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25); // // toolSameVSpacing // this.toolSameVSpacing.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolSameVSpacing.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.make_same_v_space; this.toolSameVSpacing.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolSameVSpacing.Name = "toolSameVSpacing"; this.toolSameVSpacing.Size = new System.Drawing.Size(23, 22); this.toolSameVSpacing.Text = "Same V Spacing"; this.toolSameVSpacing.ToolTipText = "Same Vertical Spacing"; this.toolSameVSpacing.Click += new System.EventHandler(this.toolSameVSpacing_Click); // // toolIncVSpacing // this.toolIncVSpacing.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolIncVSpacing.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.increase_w_space; this.toolIncVSpacing.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolIncVSpacing.Name = "toolIncVSpacing"; this.toolIncVSpacing.Size = new System.Drawing.Size(23, 22); this.toolIncVSpacing.Text = "Inc V Spacing"; this.toolIncVSpacing.ToolTipText = "Increase Vertical Spacing"; this.toolIncVSpacing.Click += new System.EventHandler(this.toolIncVSpacing_Click); // // toolDecVSpacing // this.toolDecVSpacing.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolDecVSpacing.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.decrease_w_space; this.toolDecVSpacing.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolDecVSpacing.Name = "toolDecVSpacing"; this.toolDecVSpacing.Size = new System.Drawing.Size(23, 22); this.toolDecVSpacing.Text = "Dec V Spacing"; this.toolDecVSpacing.ToolTipText = "Decrease Vertical Spacing"; this.toolDecVSpacing.Click += new System.EventHandler(this.toolDecVSpacing_Click); // // toolNoVSpacing // this.toolNoVSpacing.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolNoVSpacing.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.make_no_v_space; this.toolNoVSpacing.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolNoVSpacing.Name = "toolNoVSpacing"; this.toolNoVSpacing.Size = new System.Drawing.Size(23, 22); this.toolNoVSpacing.Text = "No Vertical Spacing"; this.toolNoVSpacing.Click += new System.EventHandler(this.toolNoVSpacing_Click); // // toolStrip1 // this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tbbHeight2, this.tbbHeight3, this.tbbHeight4, this.toolStripSeparator10, this.tbbWidth2, this.tbbWidth3, this.tbbWidth4, this.toolStripSeparator9, this.tbbSendToBack, this.tbbBringToFront}); this.toolStrip1.Location = new System.Drawing.Point(3, 74); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(208, 25); this.toolStrip1.TabIndex = 8; this.toolStrip1.Text = "toolStrip1"; // // tbbHeight2 // this.tbbHeight2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbHeight2.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.height_1_2; this.tbbHeight2.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbHeight2.Name = "tbbHeight2"; this.tbbHeight2.Size = new System.Drawing.Size(23, 22); this.tbbHeight2.Text = "1/2 Height"; this.tbbHeight2.Click += new System.EventHandler(this.tbbHeight2_Click); // // tbbHeight3 // this.tbbHeight3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbHeight3.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.height_1_3; this.tbbHeight3.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbHeight3.Name = "tbbHeight3"; this.tbbHeight3.Size = new System.Drawing.Size(23, 22); this.tbbHeight3.Text = "1/3 Height"; this.tbbHeight3.Click += new System.EventHandler(this.tbbHeight3_Click); // // tbbHeight4 // this.tbbHeight4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbHeight4.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.height_1_4; this.tbbHeight4.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbHeight4.Name = "tbbHeight4"; this.tbbHeight4.Size = new System.Drawing.Size(23, 22); this.tbbHeight4.Text = "1/4 Height"; this.tbbHeight4.Click += new System.EventHandler(this.tbbHeight4_Click); // // toolStripSeparator10 // this.toolStripSeparator10.Name = "toolStripSeparator10"; this.toolStripSeparator10.Size = new System.Drawing.Size(6, 25); // // tbbWidth2 // this.tbbWidth2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbWidth2.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.width_1_2; this.tbbWidth2.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbWidth2.Name = "tbbWidth2"; this.tbbWidth2.Size = new System.Drawing.Size(23, 22); this.tbbWidth2.Text = "1/2 Width"; this.tbbWidth2.Click += new System.EventHandler(this.tbbWidth2_Click); // // tbbWidth3 // this.tbbWidth3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbWidth3.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.width_1_3; this.tbbWidth3.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbWidth3.Name = "tbbWidth3"; this.tbbWidth3.Size = new System.Drawing.Size(23, 22); this.tbbWidth3.Text = "1/3 Width"; this.tbbWidth3.Click += new System.EventHandler(this.tbbWidth6_Click); // // tbbWidth4 // this.tbbWidth4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbWidth4.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.width_1_4; this.tbbWidth4.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbWidth4.Name = "tbbWidth4"; this.tbbWidth4.Size = new System.Drawing.Size(23, 22); this.tbbWidth4.Text = "1/4 Width"; this.tbbWidth4.Click += new System.EventHandler(this.tbbWidth4_Click); // // toolStripSeparator9 // this.toolStripSeparator9.Name = "toolStripSeparator9"; this.toolStripSeparator9.Size = new System.Drawing.Size(6, 25); // // tbbSendToBack // this.tbbSendToBack.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbSendToBack.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.MoveBack; this.tbbSendToBack.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbSendToBack.Name = "tbbSendToBack"; this.tbbSendToBack.Size = new System.Drawing.Size(23, 22); this.tbbSendToBack.Text = "STB <<-"; this.tbbSendToBack.ToolTipText = "Send to back"; this.tbbSendToBack.Click += new System.EventHandler(this.tbbSendToBack_Click); // // tbbBringToFront // this.tbbBringToFront.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbBringToFront.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.MoveFront; this.tbbBringToFront.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbBringToFront.Name = "tbbBringToFront"; this.tbbBringToFront.Size = new System.Drawing.Size(23, 22); this.tbbBringToFront.Text = "->> BTF"; this.tbbBringToFront.ToolTipText = "Bring to front"; this.tbbBringToFront.Click += new System.EventHandler(this.tbbBringToFront_Click); // // tbbStripOne // this.tbbStripOne.Dock = System.Windows.Forms.DockStyle.None; this.tbbStripOne.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tbbArrowItem, this.toolStripSeparator3, this.tbbZoom, this.tbbPreviewButton, this.toolStripSeparator1, this.toolStripButton1, this.toolStripButton2, this.toolStripButton3, this.toolStripButton4, this.toolStripButton5, this.toolStripButton6, this.toolStripButton7, this.toolStripButton11, this.toolStripButton8, this.toolStripButton9, this.toolStripButton10}); this.tbbStripOne.Location = new System.Drawing.Point(3, 99); this.tbbStripOne.Name = "tbbStripOne"; this.tbbStripOne.Size = new System.Drawing.Size(355, 25); this.tbbStripOne.TabIndex = 13; // // tbbArrowItem // this.tbbArrowItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbArrowItem.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Cursor; this.tbbArrowItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbArrowItem.Name = "tbbArrowItem"; this.tbbArrowItem.Size = new System.Drawing.Size(23, 22); this.tbbArrowItem.Text = "Arrow item"; this.tbbArrowItem.Click += new System.EventHandler(this.tbbArrowItem_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25); // // tbbZoom // this.tbbZoom.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbZoom.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miZoom50, this.miZoom100, this.miZoom150, this.miZoom200}); this.tbbZoom.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.MagnifyingGlass; this.tbbZoom.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbZoom.Name = "tbbZoom"; this.tbbZoom.Size = new System.Drawing.Size(32, 22); this.tbbZoom.Text = "Zoom..."; // // miZoom50 // this.miZoom50.Name = "miZoom50"; this.miZoom50.Size = new System.Drawing.Size(105, 22); this.miZoom50.Text = "50 %"; this.miZoom50.Click += new System.EventHandler(this.miZoom50_Click); // // miZoom100 // this.miZoom100.Name = "miZoom100"; this.miZoom100.Size = new System.Drawing.Size(105, 22); this.miZoom100.Text = "100 %"; this.miZoom100.Click += new System.EventHandler(this.miZoom100_Click); // // miZoom150 // this.miZoom150.Name = "miZoom150"; this.miZoom150.Size = new System.Drawing.Size(105, 22); this.miZoom150.Text = "150 %"; this.miZoom150.Click += new System.EventHandler(this.miZoom150_Click); // // miZoom200 // this.miZoom200.Name = "miZoom200"; this.miZoom200.Size = new System.Drawing.Size(105, 22); this.miZoom200.Text = "200 %"; this.miZoom200.Click += new System.EventHandler(this.miZoom200_Click); // // tbbPreviewButton // this.tbbPreviewButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tbbPreviewButton.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Preview; this.tbbPreviewButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.tbbPreviewButton.Name = "tbbPreviewButton"; this.tbbPreviewButton.Size = new System.Drawing.Size(23, 22); this.tbbPreviewButton.Text = "Preview is OFF"; this.tbbPreviewButton.Click += new System.EventHandler(this.tbbPreview_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.StaticBalloon; this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(23, 22); this.toolStripButton1.Text = "Static Balloon"; this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click); // // toolStripButton2 // this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton2.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.DynamicBalloon; this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size(23, 22); this.toolStripButton2.Text = "Dynamic Balloon"; this.toolStripButton2.Click += new System.EventHandler(this.toolStripButton2_Click); // // toolStripButton3 // this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton3.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.StaticText; this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton3.Name = "toolStripButton3"; this.toolStripButton3.Size = new System.Drawing.Size(23, 22); this.toolStripButton3.Text = "Static Text"; this.toolStripButton3.Click += new System.EventHandler(this.toolStripButton3_Click); // // toolStripButton4 // this.toolStripButton4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton4.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.DynamicText; this.toolStripButton4.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton4.Name = "toolStripButton4"; this.toolStripButton4.Size = new System.Drawing.Size(23, 22); this.toolStripButton4.Text = "Dynamic Text"; this.toolStripButton4.Click += new System.EventHandler(this.toolStripButton4_Click); // // toolStripButton5 // this.toolStripButton5.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton5.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.picture; this.toolStripButton5.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton5.Name = "toolStripButton5"; this.toolStripButton5.Size = new System.Drawing.Size(23, 22); this.toolStripButton5.Text = "Static Image"; this.toolStripButton5.Click += new System.EventHandler(this.toolStripButton5_Click); // // toolStripButton6 // this.toolStripButton6.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton6.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.DynamicImage; this.toolStripButton6.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton6.Name = "toolStripButton6"; this.toolStripButton6.Size = new System.Drawing.Size(23, 22); this.toolStripButton6.Text = "Dynamic Image"; this.toolStripButton6.Click += new System.EventHandler(this.toolStripButton6_Click); // // toolStripButton7 // this.toolStripButton7.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton7.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Counter; this.toolStripButton7.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton7.Name = "toolStripButton7"; this.toolStripButton7.Size = new System.Drawing.Size(23, 22); this.toolStripButton7.Text = "Counter"; this.toolStripButton7.Click += new System.EventHandler(this.toolStripButton7_Click); // // toolStripButton11 // this.toolStripButton11.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton11.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Precalculated; this.toolStripButton11.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton11.Name = "toolStripButton11"; this.toolStripButton11.Size = new System.Drawing.Size(23, 22); this.toolStripButton11.Text = "Precalculated"; this.toolStripButton11.Click += new System.EventHandler(this.toolStripButton11_Click); // // toolStripButton8 // this.toolStripButton8.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton8.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.Date; this.toolStripButton8.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton8.Name = "toolStripButton8"; this.toolStripButton8.Size = new System.Drawing.Size(23, 22); this.toolStripButton8.Text = "Date Time"; this.toolStripButton8.Click += new System.EventHandler(this.toolStripButton8_Click); // // toolStripButton9 // this.toolStripButton9.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton9.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.PageNum; this.toolStripButton9.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton9.Name = "toolStripButton9"; this.toolStripButton9.Size = new System.Drawing.Size(23, 22); this.toolStripButton9.Text = "Page Number"; this.toolStripButton9.Click += new System.EventHandler(this.toolStripButton9_Click); // // toolStripButton10 // this.toolStripButton10.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton10.Image = global::AxiomCoders.PdfTemplateEditor.Properties.Resources.RectangleShape; this.toolStripButton10.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton10.Name = "toolStripButton10"; this.toolStripButton10.Size = new System.Drawing.Size(23, 22); this.toolStripButton10.Text = "Rectangle Shape"; this.toolStripButton10.Click += new System.EventHandler(this.toolStripButton10_Click); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1190, 594); this.Controls.Add(this.pnlProperties); this.Controls.Add(this.mainToolContainer); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.IsMdiContainer = true; this.Name = "MainForm"; this.ShowInTaskbar = true; this.Text = "PdfReports Template Editor"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.MainForm_Load); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainForm_FormClosed); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MainForm_KeyDown); this.pnlProperties.ResumeLayout(false); this.PropertySplitContainer.Panel1.ResumeLayout(false); this.PropertySplitContainer.Panel2.ResumeLayout(false); this.PropertySplitContainer.ResumeLayout(false); this.mainToolContainer.TopToolStripPanel.ResumeLayout(false); this.mainToolContainer.TopToolStripPanel.PerformLayout(); this.mainToolContainer.ResumeLayout(false); this.mainToolContainer.PerformLayout(); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.toolStrip2.ResumeLayout(false); this.toolStrip2.PerformLayout(); this.AlignStrip.ResumeLayout(false); this.AlignStrip.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.tbbStripOne.ResumeLayout(false); this.tbbStripOne.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel pnlProperties; private System.Windows.Forms.ComboBox cmbObjects; private System.Windows.Forms.Timer AutoSaveTimer; private System.Windows.Forms.SplitContainer PropertySplitContainer; private System.Windows.Forms.PropertyGrid propertyGrid; private System.Windows.Forms.TreeView tvItems; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.ToolStripContainer mainToolContainer; private System.Windows.Forms.ToolStrip toolStrip2; private System.Windows.Forms.ToolStripButton tbbNewProject; private System.Windows.Forms.ToolStripButton tbbOpenProject; private System.Windows.Forms.ToolStripButton tbbSaveProject; private System.Windows.Forms.ToolStripSeparator toolStripSeparator13; private System.Windows.Forms.ToolStripButton tbbCut; private System.Windows.Forms.ToolStripButton tbbCopy; private System.Windows.Forms.ToolStripButton tbbPaste; private System.Windows.Forms.ToolStripSeparator toolStripSeparator14; private System.Windows.Forms.ToolStripButton tbbUndo; private System.Windows.Forms.ToolStripButton tbbRedo; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton tbbHeight2; private System.Windows.Forms.ToolStripButton tbbHeight3; private System.Windows.Forms.ToolStripButton tbbHeight4; private System.Windows.Forms.ToolStripSeparator toolStripSeparator10; private System.Windows.Forms.ToolStripButton tbbWidth2; private System.Windows.Forms.ToolStripButton tbbWidth3; private System.Windows.Forms.ToolStripButton tbbWidth4; private System.Windows.Forms.ToolStripSeparator toolStripSeparator9; private System.Windows.Forms.ToolStripButton tbbSendToBack; private System.Windows.Forms.ToolStripButton tbbBringToFront; private System.Windows.Forms.ToolStrip AlignStrip; private System.Windows.Forms.ToolStripButton toolSnapToGrid; private System.Windows.Forms.ToolStripButton toolLeftAlign; private System.Windows.Forms.ToolStripButton toolAlignCentarV; private System.Windows.Forms.ToolStripButton toolAlignRight; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripButton toolAlignTop; private System.Windows.Forms.ToolStripButton toolAlignCentarH; private System.Windows.Forms.ToolStripButton toolAlignBottom; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripButton toolSameWidth; private System.Windows.Forms.ToolStripButton toolSameHeight; private System.Windows.Forms.ToolStripButton toolSameSize; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripButton toolSameHSpacing; private System.Windows.Forms.ToolStripButton toolncHSpacing; private System.Windows.Forms.ToolStripButton toolDecHSpacing; private System.Windows.Forms.ToolStripButton toolNoHSpacing; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripButton toolSameVSpacing; private System.Windows.Forms.ToolStripButton toolIncVSpacing; private System.Windows.Forms.ToolStripButton toolDecVSpacing; private System.Windows.Forms.ToolStripButton toolNoVSpacing; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem miFile; private System.Windows.Forms.ToolStripMenuItem miNewProject; private System.Windows.Forms.ToolStripMenuItem miOpenProject; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem miSave; private System.Windows.Forms.ToolStripMenuItem miSaveAs; private System.Windows.Forms.ToolStripMenuItem miClose; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem miExit; private System.Windows.Forms.ToolStripMenuItem miEdit; private System.Windows.Forms.ToolStripMenuItem miUndo; private System.Windows.Forms.ToolStripMenuItem miRedo; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem miCut; private System.Windows.Forms.ToolStripMenuItem miCopy; private System.Windows.Forms.ToolStripMenuItem miPaste; private System.Windows.Forms.ToolStripSeparator toolStripSeparator11; private System.Windows.Forms.ToolStripMenuItem miPreferences; private System.Windows.Forms.ToolStripMenuItem miGeneral; private System.Windows.Forms.ToolStripSeparator toolStripSeparator12; private System.Windows.Forms.ToolStripMenuItem miUnitsRulers; private System.Windows.Forms.ToolStripMenuItem miGuidesGrids; private System.Windows.Forms.ToolStripMenuItem miTools; private System.Windows.Forms.ToolStripMenuItem miDataStreams; private System.Windows.Forms.ToolStripMenuItem miView; private System.Windows.Forms.ToolStripMenuItem miShowGrid; private System.Windows.Forms.ToolStripMenuItem miShowRulers; private System.Windows.Forms.ToolStripMenuItem miShowBalloonBorders; private System.Windows.Forms.ToolStripMenuItem miHelp; private System.Windows.Forms.ToolStripMenuItem miAbout; private System.Windows.Forms.ToolStrip tbbStripOne; private System.Windows.Forms.ToolStripButton tbbArrowItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripSplitButton tbbZoom; private System.Windows.Forms.ToolStripMenuItem miZoom50; private System.Windows.Forms.ToolStripMenuItem miZoom100; private System.Windows.Forms.ToolStripMenuItem miZoom150; private System.Windows.Forms.ToolStripMenuItem miZoom200; private System.Windows.Forms.ToolStripButton tbbPreviewButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.ToolStripButton toolStripButton2; private System.Windows.Forms.ToolStripButton toolStripButton3; private System.Windows.Forms.ToolStripButton toolStripButton4; private System.Windows.Forms.ToolStripButton toolStripButton5; private System.Windows.Forms.ToolStripButton toolStripButton6; private System.Windows.Forms.ToolStripButton toolStripButton7; private System.Windows.Forms.ToolStripButton toolStripButton8; private System.Windows.Forms.ToolStripButton toolStripButton9; private System.Windows.Forms.ToolStripButton toolStripButton10; private System.Windows.Forms.ToolStripMenuItem pdfReportsHelpContentsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pdfReportsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.ToolStripMenuItem axiomCodersOnlineToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem axiomCodersWebsiteToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pdfReportsWebsiteToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pdfReportsSuportToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator17; private System.Windows.Forms.ToolStripMenuItem purchaseALicenseToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator15; private System.Windows.Forms.ToolStripMenuItem releaseNotesToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator16; private System.Windows.Forms.ToolStripSeparator toolStripSeparator18; private System.Windows.Forms.ToolStripMenuItem themesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem professionalToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem systemToolStripMenuItem; private System.Windows.Forms.ToolStripButton toolStripButton11; private System.Windows.Forms.ToolStripMenuItem editProjectInformationToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; } }
// 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.StubHelpers; using System.Reflection; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Security; namespace System.Runtime.InteropServices.WindowsRuntime { [ComImport] [Guid("7C925755-3E48-42B4-8677-76372267033F")] [WindowsRuntimeImport] internal interface ICustomPropertyProvider { [Pure] ICustomProperty GetCustomProperty(string name); [Pure] ICustomProperty GetIndexedProperty(string name, Type indexParameterType); [Pure] string GetStringRepresentation(); Type Type { [Pure] get; } } // // Implementation helpers // internal static class ICustomPropertyProviderImpl { // // Creates a ICustomProperty implementation for Jupiter // Called from ICustomPropertyProvider_GetProperty from within runtime // static internal ICustomProperty CreateProperty(object target, string propertyName) { Contract.Requires(target != null); Contract.Requires(propertyName != null); // Only return public instance/static properties PropertyInfo propertyInfo = target.GetType().GetProperty( propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); if (propertyInfo == null) return null; else return new CustomPropertyImpl(propertyInfo); } // // Creates a ICustomProperty implementation for Jupiter // Called from ICustomPropertyProvider_GetIndexedProperty from within runtime // [System.Security.SecurityCritical] static internal unsafe ICustomProperty CreateIndexedProperty(object target, string propertyName, TypeNameNative *pIndexedParamType) { Contract.Requires(target != null); Contract.Requires(propertyName != null); Type indexedParamType = null; SystemTypeMarshaler.ConvertToManaged(pIndexedParamType, ref indexedParamType); return CreateIndexedProperty(target, propertyName, indexedParamType); } static internal ICustomProperty CreateIndexedProperty(object target, string propertyName, Type indexedParamType) { Contract.Requires(target != null); Contract.Requires(propertyName != null); // Only return public instance/static properties PropertyInfo propertyInfo = target.GetType().GetProperty( propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, // default binder null, // ignore return type new Type[] { indexedParamType }, // indexed parameter type null // ignore type modifier ); if (propertyInfo == null) return null; else return new CustomPropertyImpl(propertyInfo); } [System.Security.SecurityCritical] static internal unsafe void GetType(object target, TypeNameNative *pIndexedParamType) { SystemTypeMarshaler.ConvertToNative(target.GetType(), pIndexedParamType); } } [Flags] enum InterfaceForwardingSupport { None = 0, IBindableVector = 0x1, // IBindableVector -> IBindableVector IVector = 0x2, // IBindableVector -> IVector<T> IBindableVectorView = 0x4, // IBindableVectorView -> IBindableVectorView IVectorView = 0x8, // IBindableVectorView -> IVectorView<T> IBindableIterableOrIIterable= 0x10 // IBindableIterable -> IBindableIterable/IIterable<T> } // // Interface for data binding code (CustomPropertyImpl) to retreive the target object // See CustomPropertyImpl.InvokeInternal for details // internal interface IGetProxyTarget { object GetTarget(); } // // Proxy that supports data binding on another object // // This serves two purposes: // // 1. Delegate data binding interfaces to another object // Note that this proxy implements the native interfaces directly to avoid unnecessary overhead // (such as the adapter code that addresses behavior differences between IBindableVector & List // as well as simplify forwarding code (except for IEnumerable) // // 2. ICLRServices.CreateManagedReference will hand out ICCW* of a new instance of this object // and will hold the other object alive // // internal class ICustomPropertyProviderProxy<T1, T2> : IGetProxyTarget, ICustomPropertyProvider, ICustomQueryInterface, IEnumerable, // IBindableIterable -> IBindableIterable/IIterable<T> IBindableVector, // IBindableVector -> IBindableVector/IVector<T> IBindableVectorView // IBindableVectorView -> IBindableVectorView/IVectorView<T> { private object _target; private InterfaceForwardingSupport _flags; internal ICustomPropertyProviderProxy(object target, InterfaceForwardingSupport flags) { _target = target; _flags = flags; } // // Creates a new instance of ICustomPropertyProviderProxy<T1, T2> and assign appropriate // flags // internal static object CreateInstance(object target) { InterfaceForwardingSupport supportFlags = InterfaceForwardingSupport.None; // // QI and figure out the right flags // if (target as IList != null) supportFlags |= InterfaceForwardingSupport.IBindableVector; // NOTE: We need to use the directed type here // If we use IVector_Raw<T1> here, it derives from a different IIterable<T> which the runtime // doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI if (target as IList<T1> != null) supportFlags |= InterfaceForwardingSupport.IVector; if (target as IBindableVectorView != null) supportFlags |= InterfaceForwardingSupport.IBindableVectorView; // NOTE: We need to use the redirected type here // If we use IVector_Raw<T1> here, it derives from a different IIterable<T> which the runtime // doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI if (target as IReadOnlyList<T2> != null) supportFlags |= InterfaceForwardingSupport.IVectorView; // Verify IEnumerable last because the first few QIs might succeed and we need // IEnumerable cast to use that cache (instead of having ICustomPropertyProvider to // forward it manually) // For example, if we try to shoot in the dark by trying IVector<IInspectable> and it // succeeded, IEnumerable needs to know that if (target as IEnumerable != null) supportFlags |= InterfaceForwardingSupport.IBindableIterableOrIIterable; return new ICustomPropertyProviderProxy<T1, T2>(target, supportFlags); } // // ICustomPropertyProvider implementation // ICustomProperty ICustomPropertyProvider.GetCustomProperty(string name) { return ICustomPropertyProviderImpl.CreateProperty(_target, name); } ICustomProperty ICustomPropertyProvider.GetIndexedProperty(string name, Type indexParameterType) { return ICustomPropertyProviderImpl.CreateIndexedProperty(_target, name, indexParameterType); } string ICustomPropertyProvider.GetStringRepresentation() { return WindowsRuntime.IStringableHelper.ToString(_target); } Type ICustomPropertyProvider.Type { get { return _target.GetType(); } } // // override ToString() to make sure callers get correct IStringable.ToString() behavior in native code // public override string ToString() { return WindowsRuntime.IStringableHelper.ToString(_target); } // // IGetProxyTarget - unwraps the target object and use it for data binding // object IGetProxyTarget.GetTarget() { return _target; } // // ICustomQueryInterface methods // [System.Security.SecurityCritical] public CustomQueryInterfaceResult GetInterface([In]ref Guid iid, out IntPtr ppv) { ppv = IntPtr.Zero; if (iid == typeof(IBindableIterable).GUID) { // Reject the QI if target doesn't implement IEnumerable if ((_flags & (InterfaceForwardingSupport.IBindableIterableOrIIterable)) == 0) return CustomQueryInterfaceResult.Failed; } if (iid == typeof(IBindableVector).GUID) { // Reject the QI if target doesn't implement IBindableVector/IVector if ((_flags & (InterfaceForwardingSupport.IBindableVector | InterfaceForwardingSupport.IVector)) == 0) return CustomQueryInterfaceResult.Failed; } if (iid == typeof(IBindableVectorView).GUID) { // Reject the QI if target doesn't implement IBindableVectorView/IVectorView if ((_flags & (InterfaceForwardingSupport.IBindableVectorView | InterfaceForwardingSupport.IVectorView)) == 0) return CustomQueryInterfaceResult.Failed; } return CustomQueryInterfaceResult.NotHandled; } // // IEnumerable methods // public IEnumerator GetEnumerator() { return ((IEnumerable)_target).GetEnumerator(); } // // IBindableVector implementation (forwards to IBindableVector / IVector<T>) // [Pure] object IBindableVector.GetAt(uint index) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector return bindableVector.GetAt(index); } else { // IBindableVector -> IVector<T> return GetVectorOfT().GetAt(index); } } [Pure] uint IBindableVector.Size { get { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector return bindableVector.Size; } else { // IBindableVector -> IVector<T> return GetVectorOfT().Size; } } } [Pure] IBindableVectorView IBindableVector.GetView() { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector return bindableVector.GetView(); } else { // IBindableVector -> IVector<T> return new IVectorViewToIBindableVectorViewAdapter<T1>(GetVectorOfT().GetView()); } } private sealed class IVectorViewToIBindableVectorViewAdapter<T> : IBindableVectorView { private IVectorView<T> _vectorView; public IVectorViewToIBindableVectorViewAdapter(IVectorView<T> vectorView) { this._vectorView = vectorView; } [Pure] object IBindableVectorView.GetAt(uint index) { return _vectorView.GetAt(index); } [Pure] uint IBindableVectorView.Size { get { return _vectorView.Size; } } [Pure] bool IBindableVectorView.IndexOf(object value, out uint index) { return _vectorView.IndexOf(ConvertTo<T>(value), out index); } IBindableIterator IBindableIterable.First() { return new IteratorOfTToIteratorAdapter<T>(_vectorView.First()); } } [Pure] bool IBindableVector.IndexOf(object value, out uint index) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector return bindableVector.IndexOf(value, out index); } else { // IBindableVector -> IVector<T> return GetVectorOfT().IndexOf(ConvertTo<T1>(value), out index); } } void IBindableVector.SetAt(uint index, object value) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.SetAt(index, value); } else { // IBindableVector -> IVector<T> GetVectorOfT().SetAt(index, ConvertTo<T1>(value)); } } void IBindableVector.InsertAt(uint index, object value) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.InsertAt(index, value); } else { // IBindableVector -> IVector<T> GetVectorOfT().InsertAt(index, ConvertTo<T1>(value)); } } void IBindableVector.RemoveAt(uint index) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.RemoveAt(index); } else { // IBindableVector -> IVector<T> GetVectorOfT().RemoveAt(index); } } void IBindableVector.Append(object value) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.Append(value); } else { // IBindableVector -> IVector<T> GetVectorOfT().Append(ConvertTo<T1>(value)); } } void IBindableVector.RemoveAtEnd() { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.RemoveAtEnd(); } else { // IBindableVector -> IVector<T> GetVectorOfT().RemoveAtEnd(); } } void IBindableVector.Clear() { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.Clear(); } else { // IBindableVector -> IVector<T> GetVectorOfT().Clear(); } } [SecuritySafeCritical] private IBindableVector GetIBindableVectorNoThrow() { if ((_flags & InterfaceForwardingSupport.IBindableVector) != 0) return JitHelpers.UnsafeCast<IBindableVector>(_target); else return null; } [SecuritySafeCritical] private IVector_Raw<T1> GetVectorOfT() { if ((_flags & InterfaceForwardingSupport.IVector) != 0) return JitHelpers.UnsafeCast<IVector_Raw<T1>>(_target); else throw new InvalidOperationException(); // We should not go down this path, unless Jupiter pass this out to managed code // and managed code use reflection to do the cast } // // IBindableVectorView implementation (forwarding to IBindableVectorView or IVectorView<T>) // [Pure] object IBindableVectorView.GetAt(uint index) { IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.GetAt(index); else return GetVectorViewOfT().GetAt(index); } [Pure] uint IBindableVectorView.Size { get { IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.Size; else return GetVectorViewOfT().Size; } } [Pure] bool IBindableVectorView.IndexOf(object value, out uint index) { IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.IndexOf(value, out index); else return GetVectorViewOfT().IndexOf(ConvertTo<T2>(value), out index); } IBindableIterator IBindableIterable.First() { IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.First(); else return new IteratorOfTToIteratorAdapter<T2>(GetVectorViewOfT().First()); } private sealed class IteratorOfTToIteratorAdapter<T> : IBindableIterator { private IIterator<T> _iterator; public IteratorOfTToIteratorAdapter(IIterator<T> iterator) { this._iterator = iterator; } public bool HasCurrent { get { return _iterator.HasCurrent; } } public object Current { get { return (object)_iterator.Current; } } public bool MoveNext() { return _iterator.MoveNext(); } } [SecuritySafeCritical] private IBindableVectorView GetIBindableVectorViewNoThrow() { if ((_flags & InterfaceForwardingSupport.IBindableVectorView) != 0) return JitHelpers.UnsafeCast<IBindableVectorView>(_target); else return null; } [SecuritySafeCritical] private IVectorView<T2> GetVectorViewOfT() { if ((_flags & InterfaceForwardingSupport.IVectorView) != 0) return JitHelpers.UnsafeCast<IVectorView<T2>>(_target); else throw new InvalidOperationException(); // We should not go down this path, unless Jupiter pass this out to managed code // and managed code use reflection to do the cast } // // Convert to type T // private static T ConvertTo<T>(object value) { // Throw ArgumentNullException if value is null (otherwise we'll throw NullReferenceException // when casting value to T) ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); // No coersion support needed. If we need coersion later, this is the place return (T) value; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gcscv = Google.Cloud.Spanner.Common.V1; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Spanner.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedSpannerClientTest { [xunit::FactAttribute] public void CreateSessionRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CreateSessionRequest request = new CreateSessionRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), Session = new Session(), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.CreateSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session response = client.CreateSession(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateSessionRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CreateSessionRequest request = new CreateSessionRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), Session = new Session(), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.CreateSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Session>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session responseCallSettings = await client.CreateSessionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Session responseCancellationToken = await client.CreateSessionAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateSession() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CreateSessionRequest request = new CreateSessionRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.CreateSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session response = client.CreateSession(request.Database); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateSessionAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CreateSessionRequest request = new CreateSessionRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.CreateSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Session>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session responseCallSettings = await client.CreateSessionAsync(request.Database, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Session responseCancellationToken = await client.CreateSessionAsync(request.Database, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateSessionResourceNames() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CreateSessionRequest request = new CreateSessionRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.CreateSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session response = client.CreateSession(request.DatabaseAsDatabaseName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateSessionResourceNamesAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CreateSessionRequest request = new CreateSessionRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.CreateSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Session>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session responseCallSettings = await client.CreateSessionAsync(request.DatabaseAsDatabaseName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Session responseCancellationToken = await client.CreateSessionAsync(request.DatabaseAsDatabaseName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchCreateSessionsRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BatchCreateSessionsRequest request = new BatchCreateSessionsRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), SessionTemplate = new Session(), SessionCount = 418101156, }; BatchCreateSessionsResponse expectedResponse = new BatchCreateSessionsResponse { Session = { new Session(), }, }; mockGrpcClient.Setup(x => x.BatchCreateSessions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); BatchCreateSessionsResponse response = client.BatchCreateSessions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchCreateSessionsRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BatchCreateSessionsRequest request = new BatchCreateSessionsRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), SessionTemplate = new Session(), SessionCount = 418101156, }; BatchCreateSessionsResponse expectedResponse = new BatchCreateSessionsResponse { Session = { new Session(), }, }; mockGrpcClient.Setup(x => x.BatchCreateSessionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BatchCreateSessionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); BatchCreateSessionsResponse responseCallSettings = await client.BatchCreateSessionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); BatchCreateSessionsResponse responseCancellationToken = await client.BatchCreateSessionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchCreateSessions() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BatchCreateSessionsRequest request = new BatchCreateSessionsRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), SessionCount = 418101156, }; BatchCreateSessionsResponse expectedResponse = new BatchCreateSessionsResponse { Session = { new Session(), }, }; mockGrpcClient.Setup(x => x.BatchCreateSessions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); BatchCreateSessionsResponse response = client.BatchCreateSessions(request.Database, request.SessionCount); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchCreateSessionsAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BatchCreateSessionsRequest request = new BatchCreateSessionsRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), SessionCount = 418101156, }; BatchCreateSessionsResponse expectedResponse = new BatchCreateSessionsResponse { Session = { new Session(), }, }; mockGrpcClient.Setup(x => x.BatchCreateSessionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BatchCreateSessionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); BatchCreateSessionsResponse responseCallSettings = await client.BatchCreateSessionsAsync(request.Database, request.SessionCount, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); BatchCreateSessionsResponse responseCancellationToken = await client.BatchCreateSessionsAsync(request.Database, request.SessionCount, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchCreateSessionsResourceNames() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BatchCreateSessionsRequest request = new BatchCreateSessionsRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), SessionCount = 418101156, }; BatchCreateSessionsResponse expectedResponse = new BatchCreateSessionsResponse { Session = { new Session(), }, }; mockGrpcClient.Setup(x => x.BatchCreateSessions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); BatchCreateSessionsResponse response = client.BatchCreateSessions(request.DatabaseAsDatabaseName, request.SessionCount); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchCreateSessionsResourceNamesAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BatchCreateSessionsRequest request = new BatchCreateSessionsRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), SessionCount = 418101156, }; BatchCreateSessionsResponse expectedResponse = new BatchCreateSessionsResponse { Session = { new Session(), }, }; mockGrpcClient.Setup(x => x.BatchCreateSessionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BatchCreateSessionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); BatchCreateSessionsResponse responseCallSettings = await client.BatchCreateSessionsAsync(request.DatabaseAsDatabaseName, request.SessionCount, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); BatchCreateSessionsResponse responseCancellationToken = await client.BatchCreateSessionsAsync(request.DatabaseAsDatabaseName, request.SessionCount, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSessionRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); GetSessionRequest request = new GetSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session response = client.GetSession(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSessionRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); GetSessionRequest request = new GetSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Session>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session responseCallSettings = await client.GetSessionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Session responseCancellationToken = await client.GetSessionAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSession() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); GetSessionRequest request = new GetSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session response = client.GetSession(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSessionAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); GetSessionRequest request = new GetSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Session>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session responseCallSettings = await client.GetSessionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Session responseCancellationToken = await client.GetSessionAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSessionResourceNames() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); GetSessionRequest request = new GetSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session response = client.GetSession(request.SessionName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSessionResourceNamesAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); GetSessionRequest request = new GetSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; Session expectedResponse = new Session { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproximateLastUseTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Session>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Session responseCallSettings = await client.GetSessionAsync(request.SessionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Session responseCancellationToken = await client.GetSessionAsync(request.SessionName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteSessionRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); DeleteSessionRequest request = new DeleteSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); client.DeleteSession(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteSessionRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); DeleteSessionRequest request = new DeleteSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); await client.DeleteSessionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteSessionAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteSession() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); DeleteSessionRequest request = new DeleteSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); client.DeleteSession(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteSessionAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); DeleteSessionRequest request = new DeleteSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); await client.DeleteSessionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteSessionAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteSessionResourceNames() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); DeleteSessionRequest request = new DeleteSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); client.DeleteSession(request.SessionName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteSessionResourceNamesAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); DeleteSessionRequest request = new DeleteSessionRequest { SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); await client.DeleteSessionAsync(request.SessionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteSessionAsync(request.SessionName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ExecuteSqlRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); ExecuteSqlRequest request = new ExecuteSqlRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Transaction = new TransactionSelector(), Sql = "sqlb6745cac", Params = new wkt::Struct(), ParamTypes = { { "key8a0b6e3c", new Type() }, }, ResumeToken = proto::ByteString.CopyFromUtf8("resume_tokena048d43b"), QueryMode = ExecuteSqlRequest.Types.QueryMode.Normal, PartitionToken = proto::ByteString.CopyFromUtf8("partition_token1309778b"), Seqno = 4367695630312265944L, QueryOptions = new ExecuteSqlRequest.Types.QueryOptions(), RequestOptions = new RequestOptions(), }; ResultSet expectedResponse = new ResultSet { Metadata = new ResultSetMetadata(), Rows = { new wkt::ListValue(), }, Stats = new ResultSetStats(), }; mockGrpcClient.Setup(x => x.ExecuteSql(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); ResultSet response = client.ExecuteSql(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ExecuteSqlRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); ExecuteSqlRequest request = new ExecuteSqlRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Transaction = new TransactionSelector(), Sql = "sqlb6745cac", Params = new wkt::Struct(), ParamTypes = { { "key8a0b6e3c", new Type() }, }, ResumeToken = proto::ByteString.CopyFromUtf8("resume_tokena048d43b"), QueryMode = ExecuteSqlRequest.Types.QueryMode.Normal, PartitionToken = proto::ByteString.CopyFromUtf8("partition_token1309778b"), Seqno = 4367695630312265944L, QueryOptions = new ExecuteSqlRequest.Types.QueryOptions(), RequestOptions = new RequestOptions(), }; ResultSet expectedResponse = new ResultSet { Metadata = new ResultSetMetadata(), Rows = { new wkt::ListValue(), }, Stats = new ResultSetStats(), }; mockGrpcClient.Setup(x => x.ExecuteSqlAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ResultSet>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); ResultSet responseCallSettings = await client.ExecuteSqlAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ResultSet responseCancellationToken = await client.ExecuteSqlAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ExecuteBatchDmlRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); ExecuteBatchDmlRequest request = new ExecuteBatchDmlRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Transaction = new TransactionSelector(), Statements = { new ExecuteBatchDmlRequest.Types.Statement(), }, Seqno = 4367695630312265944L, RequestOptions = new RequestOptions(), }; ExecuteBatchDmlResponse expectedResponse = new ExecuteBatchDmlResponse { ResultSets = { new ResultSet(), }, Status = new gr::Status(), }; mockGrpcClient.Setup(x => x.ExecuteBatchDml(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); ExecuteBatchDmlResponse response = client.ExecuteBatchDml(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ExecuteBatchDmlRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); ExecuteBatchDmlRequest request = new ExecuteBatchDmlRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Transaction = new TransactionSelector(), Statements = { new ExecuteBatchDmlRequest.Types.Statement(), }, Seqno = 4367695630312265944L, RequestOptions = new RequestOptions(), }; ExecuteBatchDmlResponse expectedResponse = new ExecuteBatchDmlResponse { ResultSets = { new ResultSet(), }, Status = new gr::Status(), }; mockGrpcClient.Setup(x => x.ExecuteBatchDmlAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ExecuteBatchDmlResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); ExecuteBatchDmlResponse responseCallSettings = await client.ExecuteBatchDmlAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ExecuteBatchDmlResponse responseCancellationToken = await client.ExecuteBatchDmlAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ReadRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); ReadRequest request = new ReadRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Transaction = new TransactionSelector(), Table = "tabledee1b9aa", Index = "index552d996a", Columns = { "columnsa784ca54", }, KeySet = new KeySet(), Limit = 7494001492025909162L, ResumeToken = proto::ByteString.CopyFromUtf8("resume_tokena048d43b"), PartitionToken = proto::ByteString.CopyFromUtf8("partition_token1309778b"), RequestOptions = new RequestOptions(), }; ResultSet expectedResponse = new ResultSet { Metadata = new ResultSetMetadata(), Rows = { new wkt::ListValue(), }, Stats = new ResultSetStats(), }; mockGrpcClient.Setup(x => x.Read(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); ResultSet response = client.Read(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ReadRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); ReadRequest request = new ReadRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Transaction = new TransactionSelector(), Table = "tabledee1b9aa", Index = "index552d996a", Columns = { "columnsa784ca54", }, KeySet = new KeySet(), Limit = 7494001492025909162L, ResumeToken = proto::ByteString.CopyFromUtf8("resume_tokena048d43b"), PartitionToken = proto::ByteString.CopyFromUtf8("partition_token1309778b"), RequestOptions = new RequestOptions(), }; ResultSet expectedResponse = new ResultSet { Metadata = new ResultSetMetadata(), Rows = { new wkt::ListValue(), }, Stats = new ResultSetStats(), }; mockGrpcClient.Setup(x => x.ReadAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ResultSet>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); ResultSet responseCallSettings = await client.ReadAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ResultSet responseCancellationToken = await client.ReadAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BeginTransactionRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BeginTransactionRequest request = new BeginTransactionRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Options = new TransactionOptions(), RequestOptions = new RequestOptions(), }; Transaction expectedResponse = new Transaction { Id = proto::ByteString.CopyFromUtf8("id74b70bb8"), ReadTimestamp = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.BeginTransaction(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Transaction response = client.BeginTransaction(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BeginTransactionRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BeginTransactionRequest request = new BeginTransactionRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Options = new TransactionOptions(), RequestOptions = new RequestOptions(), }; Transaction expectedResponse = new Transaction { Id = proto::ByteString.CopyFromUtf8("id74b70bb8"), ReadTimestamp = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.BeginTransactionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Transaction>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Transaction responseCallSettings = await client.BeginTransactionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Transaction responseCancellationToken = await client.BeginTransactionAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BeginTransaction() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BeginTransactionRequest request = new BeginTransactionRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Options = new TransactionOptions(), }; Transaction expectedResponse = new Transaction { Id = proto::ByteString.CopyFromUtf8("id74b70bb8"), ReadTimestamp = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.BeginTransaction(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Transaction response = client.BeginTransaction(request.Session, request.Options); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BeginTransactionAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BeginTransactionRequest request = new BeginTransactionRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Options = new TransactionOptions(), }; Transaction expectedResponse = new Transaction { Id = proto::ByteString.CopyFromUtf8("id74b70bb8"), ReadTimestamp = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.BeginTransactionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Transaction>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Transaction responseCallSettings = await client.BeginTransactionAsync(request.Session, request.Options, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Transaction responseCancellationToken = await client.BeginTransactionAsync(request.Session, request.Options, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BeginTransactionResourceNames() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BeginTransactionRequest request = new BeginTransactionRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Options = new TransactionOptions(), }; Transaction expectedResponse = new Transaction { Id = proto::ByteString.CopyFromUtf8("id74b70bb8"), ReadTimestamp = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.BeginTransaction(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Transaction response = client.BeginTransaction(request.SessionAsSessionName, request.Options); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BeginTransactionResourceNamesAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); BeginTransactionRequest request = new BeginTransactionRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Options = new TransactionOptions(), }; Transaction expectedResponse = new Transaction { Id = proto::ByteString.CopyFromUtf8("id74b70bb8"), ReadTimestamp = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.BeginTransactionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Transaction>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); Transaction responseCallSettings = await client.BeginTransactionAsync(request.SessionAsSessionName, request.Options, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Transaction responseCancellationToken = await client.BeginTransactionAsync(request.SessionAsSessionName, request.Options, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CommitRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), SingleUseTransaction = new TransactionOptions(), Mutations = { new Mutation(), }, ReturnCommitStats = false, RequestOptions = new RequestOptions(), }; CommitResponse expectedResponse = new CommitResponse { CommitTimestamp = new wkt::Timestamp(), CommitStats = new CommitResponse.Types.CommitStats(), }; mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse response = client.Commit(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CommitRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), SingleUseTransaction = new TransactionOptions(), Mutations = { new Mutation(), }, ReturnCommitStats = false, RequestOptions = new RequestOptions(), }; CommitResponse expectedResponse = new CommitResponse { CommitTimestamp = new wkt::Timestamp(), CommitStats = new CommitResponse.Types.CommitStats(), }; mockGrpcClient.Setup(x => x.CommitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CommitResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse responseCallSettings = await client.CommitAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); CommitResponse responseCancellationToken = await client.CommitAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Commit1() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), Mutations = { new Mutation(), }, }; CommitResponse expectedResponse = new CommitResponse { CommitTimestamp = new wkt::Timestamp(), CommitStats = new CommitResponse.Types.CommitStats(), }; mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse response = client.Commit(request.Session, request.TransactionId, request.Mutations); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task Commit1Async() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), Mutations = { new Mutation(), }, }; CommitResponse expectedResponse = new CommitResponse { CommitTimestamp = new wkt::Timestamp(), CommitStats = new CommitResponse.Types.CommitStats(), }; mockGrpcClient.Setup(x => x.CommitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CommitResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse responseCallSettings = await client.CommitAsync(request.Session, request.TransactionId, request.Mutations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); CommitResponse responseCancellationToken = await client.CommitAsync(request.Session, request.TransactionId, request.Mutations, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Commit1ResourceNames() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), Mutations = { new Mutation(), }, }; CommitResponse expectedResponse = new CommitResponse { CommitTimestamp = new wkt::Timestamp(), CommitStats = new CommitResponse.Types.CommitStats(), }; mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse response = client.Commit(request.SessionAsSessionName, request.TransactionId, request.Mutations); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task Commit1ResourceNamesAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), Mutations = { new Mutation(), }, }; CommitResponse expectedResponse = new CommitResponse { CommitTimestamp = new wkt::Timestamp(), CommitStats = new CommitResponse.Types.CommitStats(), }; mockGrpcClient.Setup(x => x.CommitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CommitResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse responseCallSettings = await client.CommitAsync(request.SessionAsSessionName, request.TransactionId, request.Mutations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); CommitResponse responseCancellationToken = await client.CommitAsync(request.SessionAsSessionName, request.TransactionId, request.Mutations, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Commit2() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), SingleUseTransaction = new TransactionOptions(), Mutations = { new Mutation(), }, }; CommitResponse expectedResponse = new CommitResponse { CommitTimestamp = new wkt::Timestamp(), CommitStats = new CommitResponse.Types.CommitStats(), }; mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse response = client.Commit(request.Session, request.SingleUseTransaction, request.Mutations); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task Commit2Async() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), SingleUseTransaction = new TransactionOptions(), Mutations = { new Mutation(), }, }; CommitResponse expectedResponse = new CommitResponse { CommitTimestamp = new wkt::Timestamp(), CommitStats = new CommitResponse.Types.CommitStats(), }; mockGrpcClient.Setup(x => x.CommitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CommitResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse responseCallSettings = await client.CommitAsync(request.Session, request.SingleUseTransaction, request.Mutations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); CommitResponse responseCancellationToken = await client.CommitAsync(request.Session, request.SingleUseTransaction, request.Mutations, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Commit2ResourceNames() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), SingleUseTransaction = new TransactionOptions(), Mutations = { new Mutation(), }, }; CommitResponse expectedResponse = new CommitResponse { CommitTimestamp = new wkt::Timestamp(), CommitStats = new CommitResponse.Types.CommitStats(), }; mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse response = client.Commit(request.SessionAsSessionName, request.SingleUseTransaction, request.Mutations); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task Commit2ResourceNamesAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), SingleUseTransaction = new TransactionOptions(), Mutations = { new Mutation(), }, }; CommitResponse expectedResponse = new CommitResponse { CommitTimestamp = new wkt::Timestamp(), CommitStats = new CommitResponse.Types.CommitStats(), }; mockGrpcClient.Setup(x => x.CommitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CommitResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse responseCallSettings = await client.CommitAsync(request.SessionAsSessionName, request.SingleUseTransaction, request.Mutations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); CommitResponse responseCancellationToken = await client.CommitAsync(request.SessionAsSessionName, request.SingleUseTransaction, request.Mutations, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RollbackRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); RollbackRequest request = new RollbackRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.Rollback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); client.Rollback(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RollbackRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); RollbackRequest request = new RollbackRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.RollbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); await client.RollbackAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.RollbackAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Rollback() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); RollbackRequest request = new RollbackRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.Rollback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); client.Rollback(request.Session, request.TransactionId); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RollbackAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); RollbackRequest request = new RollbackRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.RollbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); await client.RollbackAsync(request.Session, request.TransactionId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.RollbackAsync(request.Session, request.TransactionId, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RollbackResourceNames() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); RollbackRequest request = new RollbackRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.Rollback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); client.Rollback(request.SessionAsSessionName, request.TransactionId); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RollbackResourceNamesAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); RollbackRequest request = new RollbackRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = proto::ByteString.CopyFromUtf8("transaction_id52de47f8"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.RollbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); await client.RollbackAsync(request.SessionAsSessionName, request.TransactionId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.RollbackAsync(request.SessionAsSessionName, request.TransactionId, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void PartitionQueryRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); PartitionQueryRequest request = new PartitionQueryRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Transaction = new TransactionSelector(), Sql = "sqlb6745cac", Params = new wkt::Struct(), ParamTypes = { { "key8a0b6e3c", new Type() }, }, PartitionOptions = new PartitionOptions(), }; PartitionResponse expectedResponse = new PartitionResponse { Partitions = { new Partition(), }, Transaction = new Transaction(), }; mockGrpcClient.Setup(x => x.PartitionQuery(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); PartitionResponse response = client.PartitionQuery(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task PartitionQueryRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); PartitionQueryRequest request = new PartitionQueryRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Transaction = new TransactionSelector(), Sql = "sqlb6745cac", Params = new wkt::Struct(), ParamTypes = { { "key8a0b6e3c", new Type() }, }, PartitionOptions = new PartitionOptions(), }; PartitionResponse expectedResponse = new PartitionResponse { Partitions = { new Partition(), }, Transaction = new Transaction(), }; mockGrpcClient.Setup(x => x.PartitionQueryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PartitionResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); PartitionResponse responseCallSettings = await client.PartitionQueryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PartitionResponse responseCancellationToken = await client.PartitionQueryAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void PartitionReadRequestObject() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); PartitionReadRequest request = new PartitionReadRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Transaction = new TransactionSelector(), Table = "tabledee1b9aa", Index = "index552d996a", Columns = { "columnsa784ca54", }, KeySet = new KeySet(), PartitionOptions = new PartitionOptions(), }; PartitionResponse expectedResponse = new PartitionResponse { Partitions = { new Partition(), }, Transaction = new Transaction(), }; mockGrpcClient.Setup(x => x.PartitionRead(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); PartitionResponse response = client.PartitionRead(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task PartitionReadRequestObjectAsync() { moq::Mock<Spanner.SpannerClient> mockGrpcClient = new moq::Mock<Spanner.SpannerClient>(moq::MockBehavior.Strict); PartitionReadRequest request = new PartitionReadRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Transaction = new TransactionSelector(), Table = "tabledee1b9aa", Index = "index552d996a", Columns = { "columnsa784ca54", }, KeySet = new KeySet(), PartitionOptions = new PartitionOptions(), }; PartitionResponse expectedResponse = new PartitionResponse { Partitions = { new Partition(), }, Transaction = new Transaction(), }; mockGrpcClient.Setup(x => x.PartitionReadAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PartitionResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); PartitionResponse responseCallSettings = await client.PartitionReadAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PartitionResponse responseCancellationToken = await client.PartitionReadAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
#region License /* * ChunkedRequestStream.cs * * This code is derived from ChunkedInputStream.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2022 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.IO; namespace WebSocketSharp.Net { internal class ChunkedRequestStream : RequestStream { #region Private Fields private static readonly int _bufferLength; private HttpListenerContext _context; private ChunkStream _decoder; private bool _disposed; private bool _noMoreData; #endregion #region Static Constructor static ChunkedRequestStream () { _bufferLength = 8192; } #endregion #region Internal Constructors internal ChunkedRequestStream ( Stream innerStream, byte[] initialBuffer, int offset, int count, HttpListenerContext context ) : base (innerStream, initialBuffer, offset, count, -1) { _context = context; _decoder = new ChunkStream ( (WebHeaderCollection) context.Request.Headers ); } #endregion #region Internal Properties internal bool HasRemainingBuffer { get { return _decoder.Count + Count > 0; } } internal byte[] RemainingBuffer { get { using (var buff = new MemoryStream ()) { var cnt = _decoder.Count; if (cnt > 0) buff.Write (_decoder.EndBuffer, _decoder.Offset, cnt); cnt = Count; if (cnt > 0) buff.Write (InitialBuffer, Offset, cnt); buff.Close (); return buff.ToArray (); } } } #endregion #region Private Methods private void onRead (IAsyncResult asyncResult) { var rstate = (ReadBufferState) asyncResult.AsyncState; var ares = rstate.AsyncResult; try { var nread = base.EndRead (asyncResult); _decoder.Write (ares.Buffer, ares.Offset, nread); nread = _decoder.Read (rstate.Buffer, rstate.Offset, rstate.Count); rstate.Offset += nread; rstate.Count -= nread; if (rstate.Count == 0 || !_decoder.WantsMore || nread == 0) { _noMoreData = !_decoder.WantsMore && nread == 0; ares.Count = rstate.InitialCount - rstate.Count; ares.Complete (); return; } base.BeginRead (ares.Buffer, ares.Offset, ares.Count, onRead, rstate); } catch (Exception ex) { _context.ErrorMessage = "I/O operation aborted"; _context.SendError (); ares.Complete (ex); } } #endregion #region Public Methods public override IAsyncResult BeginRead ( byte[] buffer, int offset, int count, AsyncCallback callback, object state ) { if (_disposed) { var name = GetType ().ToString (); throw new ObjectDisposedException (name); } if (buffer == null) throw new ArgumentNullException ("buffer"); if (offset < 0) { var msg = "A negative value."; throw new ArgumentOutOfRangeException ("offset", msg); } if (count < 0) { var msg = "A negative value."; throw new ArgumentOutOfRangeException ("count", msg); } var len = buffer.Length; if (offset + count > len) { var msg = "The sum of 'offset' and 'count' is greater than the length of 'buffer'."; throw new ArgumentException (msg); } var ares = new HttpStreamAsyncResult (callback, state); if (_noMoreData) { ares.Complete (); return ares; } var nread = _decoder.Read (buffer, offset, count); offset += nread; count -= nread; if (count == 0) { ares.Count = nread; ares.Complete (); return ares; } if (!_decoder.WantsMore) { _noMoreData = nread == 0; ares.Count = nread; ares.Complete (); return ares; } ares.Buffer = new byte[_bufferLength]; ares.Offset = 0; ares.Count = _bufferLength; var rstate = new ReadBufferState (buffer, offset, count, ares); rstate.InitialCount += nread; base.BeginRead (ares.Buffer, ares.Offset, ares.Count, onRead, rstate); return ares; } public override void Close () { if (_disposed) return; base.Close (); _disposed = true; } public override int EndRead (IAsyncResult asyncResult) { if (_disposed) { var name = GetType ().ToString (); throw new ObjectDisposedException (name); } if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); var ares = asyncResult as HttpStreamAsyncResult; if (ares == null) { var msg = "A wrong IAsyncResult instance."; throw new ArgumentException (msg, "asyncResult"); } if (!ares.IsCompleted) ares.AsyncWaitHandle.WaitOne (); if (ares.HasException) { var msg = "The I/O operation has been aborted."; throw new HttpListenerException (995, msg); } return ares.Count; } public override int Read (byte[] buffer, int offset, int count) { var ares = BeginRead (buffer, offset, count, null, null); return EndRead (ares); } #endregion } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Storages.Algo File: IStorageRegistry.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Storages { using System; using StockSharp.Algo.Candles; using StockSharp.BusinessEntities; using StockSharp.Messages; /// <summary> /// The interface describing the storage of market data. /// </summary> public interface IStorageRegistry { /// <summary> /// The storage used by default. /// </summary> IMarketDataDrive DefaultDrive { get; } /// <summary> /// To get news storage. /// </summary> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The news storage.</returns> IMarketDataStorage<News> GetNewsStorage(IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get news storage. /// </summary> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The news storage.</returns> IMarketDataStorage<NewsMessage> GetNewsMessageStorage(IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the storage of tick trades for the specified instrument. /// </summary> /// <param name="security">Security.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The storage of tick trades.</returns> IMarketDataStorage<Trade> GetTradeStorage(Security security, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the storage of order books for the specified instrument. /// </summary> /// <param name="security">Security.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The order books storage.</returns> IMarketDataStorage<MarketDepth> GetMarketDepthStorage(Security security, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the storage of orders log for the specified instrument. /// </summary> /// <param name="security">Security.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The storage of orders log.</returns> IMarketDataStorage<OrderLogItem> GetOrderLogStorage(Security security, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the candles storage the specified instrument. /// </summary> /// <param name="candleType">The candle type.</param> /// <param name="security">Security.</param> /// <param name="arg">Candle arg.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The candles storage.</returns> IMarketDataStorage<Candle> GetCandleStorage(Type candleType, Security security, object arg, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the storage of tick trades for the specified instrument. /// </summary> /// <param name="security">Security.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The storage of tick trades.</returns> IMarketDataStorage<ExecutionMessage> GetTickMessageStorage(Security security, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the storage of order books for the specified instrument. /// </summary> /// <param name="security">Security.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The order books storage.</returns> IMarketDataStorage<QuoteChangeMessage> GetQuoteMessageStorage(Security security, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the storage of orders log for the specified instrument. /// </summary> /// <param name="security">Security.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The storage of orders log.</returns> IMarketDataStorage<ExecutionMessage> GetOrderLogMessageStorage(Security security, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the storage of level1 data. /// </summary> /// <param name="security">Security.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The storage of level1 data.</returns> IMarketDataStorage<Level1ChangeMessage> GetLevel1MessageStorage(Security security, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the candles storage the specified instrument. /// </summary> /// <param name="candleType">The candle type.</param> /// <param name="security">Security.</param> /// <param name="arg">Candle arg.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The candles storage.</returns> IMarketDataStorage<CandleMessage> GetCandleMessageStorage(Type candleType, Security security, object arg, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the <see cref="ExecutionMessage"/> storage the specified instrument. /// </summary> /// <param name="security">Security.</param> /// <param name="type">Data type, information about which is contained in the <see cref="ExecutionMessage"/>.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The <see cref="ExecutionMessage"/> storage.</returns> IMarketDataStorage<ExecutionMessage> GetExecutionMessageStorage(Security security, ExecutionTypes type, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the transactions storage the specified instrument. /// </summary> /// <param name="security">Security.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The transactions storage.</returns> IMarketDataStorage<ExecutionMessage> GetTransactionStorage(Security security, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the market-data storage. /// </summary> /// <param name="security">Security.</param> /// <param name="dataType">Market data type.</param> /// <param name="arg">The parameter associated with the <paramref name="dataType" /> type. For example, <see cref="Candle.Arg"/>.</param> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>Market-data storage.</returns> IMarketDataStorage GetStorage(Security security, Type dataType, object arg, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To get the instruments storage. /// </summary> /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param> /// <param name="format">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param> /// <returns>The instruments storage.</returns> ISecurityStorage GetSecurityStorage(IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary); /// <summary> /// To register tick trades storage. /// </summary> /// <param name="storage">The storage of tick trades.</param> void RegisterTradeStorage(IMarketDataStorage<Trade> storage); /// <summary> /// To register the order books storage. /// </summary> /// <param name="storage">The order books storage.</param> void RegisterMarketDepthStorage(IMarketDataStorage<MarketDepth> storage); /// <summary> /// To register the order log storage. /// </summary> /// <param name="storage">The storage of orders log.</param> void RegisterOrderLogStorage(IMarketDataStorage<OrderLogItem> storage); /// <summary> /// To register the candles storage. /// </summary> /// <param name="storage">The candles storage.</param> void RegisterCandleStorage(IMarketDataStorage<Candle> storage); /// <summary> /// To register tick trades storage. /// </summary> /// <param name="storage">The storage of tick trades.</param> void RegisterTradeStorage(IMarketDataStorage<ExecutionMessage> storage); /// <summary> /// To register the order books storage. /// </summary> /// <param name="storage">The order books storage.</param> void RegisterMarketDepthStorage(IMarketDataStorage<QuoteChangeMessage> storage); /// <summary> /// To register the order log storage. /// </summary> /// <param name="storage">The storage of orders log.</param> void RegisterOrderLogStorage(IMarketDataStorage<ExecutionMessage> storage); /// <summary> /// To register the storage of level1 data. /// </summary> /// <param name="storage">The storage of level1 data.</param> void RegisterLevel1Storage(IMarketDataStorage<Level1ChangeMessage> storage); /// <summary> /// To register the candles storage. /// </summary> /// <param name="storage">The candles storage.</param> void RegisterCandleStorage(IMarketDataStorage<CandleMessage> storage); } }
/* Copyright (c) 2010 by Genstein This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; using System.Text; using System.IO; using System.Runtime.InteropServices; using System.Diagnostics; using System.Threading; using PdfSharp.Drawing; using PdfSharp.Pdf; using Trizbort.Export; namespace Trizbort { internal partial class MainForm : Form { public MainForm() { InitializeComponent(); m_caption = Text; Application.Idle += OnIdle; m_lastUpdateUITime = DateTime.MinValue; m_automapBar.StopClick += delegate(object sender, EventArgs e) { m_canvas.StopAutomapping(); }; } private void MainForm_Load(object sender, EventArgs e) { m_canvas.MinimapVisible = Settings.ShowMiniMap; var args = Environment.GetCommandLineArgs(); if (args.Length > 1 && File.Exists(args[1])) { try { BeginInvoke((MethodInvoker)delegate { OpenProject(args[1]); }); } catch (Exception) { } } NewVersionDialog.CheckForUpdatesAsync(this, false); } public Canvas Canvas { get { return m_canvas; } } private void FileNewMenuItem_Click(object sender, EventArgs e) { if (!CheckLoseProject()) return; Project.Current = new Project(); Settings.Reset(); } protected override void OnClosing(CancelEventArgs e) { if (!CheckLoseProject()) { e.Cancel = true; return; } Settings.SaveApplicationSettings(); m_canvas.StopAutomapping(); base.OnClosing(e); } private bool CheckLoseProject() { if (Project.Current.IsDirty) { // see if the user would like to save var result = MessageBox.Show(this, string.Format("Do you want to save changes to {0}?", Project.Current.Name), Text, MessageBoxButtons.YesNoCancel); switch (result) { case DialogResult.Yes: // user would like to save if (!SaveProject()) { // didn't actually save; treat as cancel return false; } // user saved; carry on return true; case DialogResult.No: // user wouldn't like to save; carry on return true; default: // user cancelled; cancel return false; } } // project doesn't need saving; carry on return true; } private bool OpenProject() { if (!CheckLoseProject()) return false; using (var dialog = new OpenFileDialog()) { dialog.InitialDirectory = PathHelper.SafeGetDirectoryName(Settings.LastProjectFileName); dialog.Filter = string.Format("{0}|All Files|*.*||", Project.FilterString); if (dialog.ShowDialog() == DialogResult.OK) { Settings.LastProjectFileName = dialog.FileName; return OpenProject(dialog.FileName); } } return false; } private bool OpenProject(string fileName) { var project = new Project(); project.FileName = fileName; if (project.Load()) { Project.Current = project; //AboutMap(); Settings.RecentProjects.Add(fileName); return true; } return false; } private void AboutMap() { var project = Project.Current; if (!string.IsNullOrEmpty(project.Title) || !string.IsNullOrEmpty(project.Author) || !string.IsNullOrEmpty(project.Description)) { var builder = new StringBuilder(); if (!string.IsNullOrEmpty(project.Title)) { builder.AppendLine(project.Title); } if (!string.IsNullOrEmpty(project.Author)) { if (builder.Length > 0) { builder.AppendLine(); } builder.AppendLine(string.Format("by {0}", project.Author)); } if (!string.IsNullOrEmpty(project.Description)) { if (builder.Length > 0) { builder.AppendLine(); } builder.AppendLine(project.Description); } MessageBox.Show(builder.ToString(), Application.ProductName, MessageBoxButtons.OK); } } private bool SaveProject() { if (!Project.Current.HasFileName) { return SaveAsProject(); } if (Project.Current.Save()) { Settings.RecentProjects.Add(Project.Current.FileName); return true; } return false; } private bool SaveAsProject() { using (var dialog = new SaveFileDialog()) { if (!string.IsNullOrEmpty(Project.Current.FileName)) { dialog.FileName = Project.Current.FileName; } else { dialog.InitialDirectory = PathHelper.SafeGetDirectoryName(Settings.LastProjectFileName); } dialog.Filter = string.Format("{0}|All Files|*.*||", Project.FilterString); if (dialog.ShowDialog() == DialogResult.OK) { Settings.LastProjectFileName = dialog.FileName; Project.Current.FileName = dialog.FileName; if (Project.Current.Save()) { Settings.RecentProjects.Add(Project.Current.FileName); return true; } } } return false; } private void FileOpenMenuItem_Click(object sender, EventArgs e) { OpenProject(); } private void FileSaveMenuItem_Click(object sender, EventArgs e) { SaveProject(); } private void FileSaveAsMenuItem_Click(object sender, EventArgs e) { SaveAsProject(); } private void FileExportPDFMenuItem_Click(object sender, EventArgs e) { using (var dialog = new SaveFileDialog()) { dialog.Filter = "PDF Files|*.pdf|All Files|*.*||"; dialog.Title = "Export PDF"; dialog.InitialDirectory = PathHelper.SafeGetDirectoryName(Settings.LastExportImageFileName); if (dialog.ShowDialog() == DialogResult.OK) { try { Settings.LastExportImageFileName = dialog.FileName; var doc = new PdfDocument(); doc.Info.Title = Project.Current.Title; doc.Info.Author = Project.Current.Author; doc.Info.Creator = Application.ProductName; doc.Info.CreationDate = DateTime.Now; doc.Info.Subject = Project.Current.Description; var page = doc.AddPage(); var size = m_canvas.ComputeCanvasBounds(true).Size; page.Width = new XUnit(size.X); page.Height = new XUnit(size.Y); using (var graphics = XGraphics.FromPdfPage(page)) { m_canvas.Draw(graphics, true, size.X, size.Y); } doc.Save(dialog.FileName); } catch (Exception ex) { MessageBox.Show(Program.MainForm, string.Format("There was a problem exporting the map:\n\n{0}", ex.Message), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } private void FileExportImageMenuItem_Click(object sender, EventArgs e) { using (var dialog = new SaveFileDialog()) { dialog.Filter = "PNG Images|*.png|JPEG Images|*.jpg|BMP Images|*.bmp|Enhanced Metafiles (EMF)|*.emf|All Files|*.*||"; dialog.Title = "Export Image"; dialog.InitialDirectory = PathHelper.SafeGetDirectoryName(Settings.LastExportImageFileName); if (dialog.ShowDialog() == DialogResult.OK) { Settings.LastExportImageFileName = dialog.InitialDirectory; var format = ImageFormat.Png; var ext = Path.GetExtension(dialog.FileName); if (StringComparer.InvariantCultureIgnoreCase.Compare(ext, ".jpg") == 0 || StringComparer.InvariantCultureIgnoreCase.Compare(ext, ".jpeg") == 0) { format = ImageFormat.Jpeg; } else if (StringComparer.InvariantCultureIgnoreCase.Compare(ext, ".bmp") == 0) { format = ImageFormat.Bmp; } else if (StringComparer.InvariantCultureIgnoreCase.Compare(ext, ".emf") == 0) { format = ImageFormat.Emf; } var size = m_canvas.ComputeCanvasBounds(true).Size * m_canvas.ZoomFactor; size.X = Numeric.Clamp(size.X, 16, 8192); size.Y = Numeric.Clamp(size.Y, 16, 8192); try { if (format == ImageFormat.Emf) { // export as a metafile using (var nativeGraphics = Graphics.FromHwnd(m_canvas.Handle)) { using (var stream = new MemoryStream()) { try { var dc = nativeGraphics.GetHdc(); using (var metafile = new Metafile(stream, dc)) { using (var imageGraphics = Graphics.FromImage(metafile)) { using (var graphics = XGraphics.FromGraphics(imageGraphics, new XSize(size.X, size.Y))) { m_canvas.Draw(graphics, true, size.X, size.Y); } } var handle = metafile.GetHenhmetafile(); var copy = CopyEnhMetaFile(handle, dialog.FileName); DeleteEnhMetaFile(copy); } } finally { nativeGraphics.ReleaseHdc(); } } } } else { // export as an image using (var bitmap = new Bitmap((int)Math.Ceiling(size.X), (int)Math.Ceiling(size.Y))) { using (var imageGraphics = Graphics.FromImage(bitmap)) { using (var graphics = XGraphics.FromGraphics(imageGraphics, new XSize(size.X, size.Y))) { m_canvas.Draw(graphics, true, size.X, size.Y); } } bitmap.Save(dialog.FileName, format); } } } catch (Exception ex) { MessageBox.Show(Program.MainForm, string.Format("There was a problem exporting the map:\n\n{0}", ex.Message), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } private void FileExportInform7MenuItem_Click(object sender, EventArgs e) { var fileName = Settings.LastExportInform7FileName; if (ExportCode<Inform7Exporter>(ref fileName)) { Settings.LastExportInform7FileName = fileName; } } private void FileExportInform6MenuItem_Click(object sender, EventArgs e) { var fileName = Settings.LastExportInform6FileName; if (ExportCode<Inform6Exporter>(ref fileName)) { Settings.LastExportInform6FileName = fileName; } } private void FileExportTadsMenuItem_Click(object sender, EventArgs e) { var fileName = Settings.LastExportTadsFileName; if (ExportCode<TadsExporter>(ref fileName)) { Settings.LastExportTadsFileName = fileName; } } private bool ExportCode<T>(ref string lastExportFileName) where T : CodeExporter, new() { using (var exporter = new T()) { using (var dialog = new SaveFileDialog()) { // compose filter string for file dialog var filterString = string.Empty; var filters = exporter.FileDialogFilters; foreach (var filter in filters) { if (!string.IsNullOrEmpty(filterString)) { filterString += "|"; } filterString += string.Format("{0}|*{1}", filter.Key, filter.Value); } if (!string.IsNullOrEmpty(filterString)) { filterString += "|"; } filterString += "All Files|*.*||"; dialog.Filter = filterString; // set default filter by extension var extension = PathHelper.SafeGetExtension(lastExportFileName); for (var filterIndex = 0; filterIndex < filters.Count; ++filterIndex) { if (StringComparer.InvariantCultureIgnoreCase.Compare(extension, filters[filterIndex].Value) == 0) { dialog.FilterIndex = filterIndex + 1; // 1 based index break; } } // show dialog dialog.Title = exporter.FileDialogTitle; dialog.InitialDirectory = PathHelper.SafeGetDirectoryName(lastExportFileName); if (dialog.ShowDialog() == DialogResult.OK) { try { // export source code exporter.Export(dialog.FileName); lastExportFileName = dialog.FileName; return true; } catch (Exception ex) { MessageBox.Show(Program.MainForm, string.Format("There was a problem exporting the map:\n\n{0}", ex.Message), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } return false; } private void FileExitMenuItem_Click(object sender, EventArgs e) { Close(); } private void EditAddRoomMenuItem_Click(object sender, EventArgs e) { m_canvas.AddRoom(false); } private void EditDeleteMenuItem_Click(object sender, EventArgs e) { m_canvas.DeleteSelection(); } private void EditPropertiesMenuItem_Click(object sender, EventArgs e) { if (m_canvas.HasSingleSelectedElement && m_canvas.SelectedElement.HasDialog) { m_canvas.SelectedElement.ShowDialog(); } } private void PlainLinesMenuItem_Click(object sender, EventArgs e) { m_canvas.ApplyNewPlainConnectionSettings(); } private void ToggleDottedLines_Click(object sender, EventArgs e) { switch (m_canvas.NewConnectionStyle) { case ConnectionStyle.Solid: m_canvas.NewConnectionStyle = ConnectionStyle.Dashed; break; case ConnectionStyle.Dashed: m_canvas.NewConnectionStyle = ConnectionStyle.Solid; break; } m_canvas.ApplyConnectionStyle(m_canvas.NewConnectionStyle); } private void ToggleDirectionalLines_Click(object sender, EventArgs e) { switch (m_canvas.NewConnectionFlow) { case ConnectionFlow.TwoWay: m_canvas.NewConnectionFlow = ConnectionFlow.OneWay; break; case ConnectionFlow.OneWay: m_canvas.NewConnectionFlow = ConnectionFlow.TwoWay; break; } m_canvas.ApplyConnectionFlow(m_canvas.NewConnectionFlow); } private void UpLinesMenuItem_Click(object sender, EventArgs e) { m_canvas.NewConnectionLabel = ConnectionLabel.Up; m_canvas.ApplyConnectionLabel(m_canvas.NewConnectionLabel); } private void DownLinesMenuItem_Click(object sender, EventArgs e) { m_canvas.NewConnectionLabel = ConnectionLabel.Down; m_canvas.ApplyConnectionLabel(m_canvas.NewConnectionLabel); } private void InLinesMenuItem_Click(object sender, EventArgs e) { m_canvas.NewConnectionLabel = ConnectionLabel.In; m_canvas.ApplyConnectionLabel(m_canvas.NewConnectionLabel); } private void OutLinesMenuItem_Click(object sender, EventArgs e) { m_canvas.NewConnectionLabel = ConnectionLabel.Out; m_canvas.ApplyConnectionLabel(m_canvas.NewConnectionLabel); } private void ReverseLineMenuItem_Click(object sender, EventArgs e) { m_canvas.ReverseLineDirection(); } private void OnIdle(object sender, EventArgs e) { var now = DateTime.Now; if (now - m_lastUpdateUITime > IdleProcessingEveryNSeconds) { m_lastUpdateUITime = now; UpdateCommandUI(); } } private void UpdateCommandUI() { // caption Text = string.Format("{0}{1} - {2}", Project.Current.Name, Project.Current.IsDirty ? "*" : string.Empty, m_caption); // line drawing options m_toggleDottedLinesButton.Checked = m_canvas.NewConnectionStyle == ConnectionStyle.Dashed; m_toggleDottedLinesMenuItem.Checked = m_toggleDottedLinesButton.Checked; m_toggleDirectionalLinesButton.Checked = m_canvas.NewConnectionFlow == ConnectionFlow.OneWay; m_toggleDirectionalLinesMenuItem.Checked = m_toggleDirectionalLinesButton.Checked; m_plainLinesMenuItem.Checked = !m_toggleDirectionalLinesMenuItem.Checked && !m_toggleDottedLinesMenuItem.Checked && m_canvas.NewConnectionLabel == ConnectionLabel.None; m_upLinesMenuItem.Checked = m_canvas.NewConnectionLabel == ConnectionLabel.Up; m_downLinesMenuItem.Checked = m_canvas.NewConnectionLabel == ConnectionLabel.Down; m_inLinesMenuItem.Checked = m_canvas.NewConnectionLabel == ConnectionLabel.In; m_outLinesMenuItem.Checked = m_canvas.NewConnectionLabel == ConnectionLabel.Out; // selection-specific commands bool hasSelectedElement = m_canvas.SelectedElement != null; m_editDeleteMenuItem.Enabled = hasSelectedElement; m_editPropertiesMenuItem.Enabled = m_canvas.HasSingleSelectedElement; m_editIsDarkMenuItem.Enabled = hasSelectedElement; m_editSelectNoneMenuItem.Enabled = hasSelectedElement; m_editSelectAllMenuItem.Enabled = m_canvas.SelectedElementCount < Project.Current.Elements.Count; m_editCopyMenuItem.Enabled = m_canvas.SelectedElement != null; m_editCopyColorToolMenuItem.Enabled = m_canvas.HasSingleSelectedElement && (m_canvas.SelectedElement is Room); m_editPasteMenuItem.Enabled = (!String.IsNullOrEmpty(Clipboard.GetText())) && ((Clipboard.GetText().Replace("\r\n", "|").Split('|')[0] == "Elements") || (Clipboard.GetText().Replace("\r\n", "|").Split('|')[0] == "Colors")); m_editRenameMenuItem.Enabled = m_canvas.HasSingleSelectedElement && (m_canvas.SelectedElement is Room); m_editIsDarkMenuItem.Checked = m_canvas.HasSingleSelectedElement && (m_canvas.SelectedElement is Room) && ((Room)m_canvas.SelectedElement).IsDark; m_reverseLineMenuItem.Enabled = m_canvas.HasSelectedElement<Connection>(); // automapping m_automapStartMenuItem.Enabled = !m_canvas.IsAutomapping; m_automapStopMenuItem.Enabled = m_canvas.IsAutomapping; m_automapBar.Visible = m_canvas.IsAutomapping; m_automapBar.Status = m_canvas.AutomappingStatus; // minimap m_viewMinimapMenuItem.Checked = m_canvas.MinimapVisible; UpdateToolStripImages(); m_canvas.UpdateScrollBars(); Debug.WriteLine(m_canvas.Focused ? "Focused!" : "NOT FOCUSED"); } private void FileRecentProject_Click(object sender, EventArgs e) { if (!CheckLoseProject()) { return; } var fileName = (string)((ToolStripMenuItem)sender).Tag; OpenProject(fileName); } private void UpdateToolStripImages() { foreach (ToolStripItem item in m_toolStrip.Items) { if (!(item is ToolStripButton)) continue; var button = (ToolStripButton)item; button.BackgroundImage = button.Checked ? Properties.Resources.ToolStripBackground2 : Properties.Resources.ToolStripBackground; } } private void ViewResetMenuItem_Click(object sender, EventArgs e) { m_canvas.ResetZoomOrigin(); } private void ViewZoomInMenuItem_Click(object sender, EventArgs e) { m_canvas.ZoomIn(); } private void ViewZoomOutMenuItem_Click(object sender, EventArgs e) { m_canvas.ZoomOut(); } private void ViewZoomFiftyPercentMenuItem_Click(object sender, EventArgs e) { m_canvas.ZoomFactor = 0.5f; } private void ViewZoomOneHundredPercentMenuItem_Click(object sender, EventArgs e) { m_canvas.ZoomFactor = 1.0f; } private void ViewZoomTwoHundredPercentMenuItem_Click(object sender, EventArgs e) { m_canvas.ZoomFactor = 2.0f; } private void EditRenameMenuItem_Click(object sender, EventArgs e) { if (m_canvas.HasSingleSelectedElement && m_canvas.SelectedElement.HasDialog) { m_canvas.SelectedElement.ShowDialog(); } } private void EditIsDarkMenuItem_Click(object sender, EventArgs e) { foreach (var element in m_canvas.SelectedElements) { if (element is Room) { var room = (Room)element; room.IsDark = !room.IsDark; } } } private void ProjectSettingsMenuItem_Click(object sender, EventArgs e) { Settings.ShowDialog(); } private void ProjectResetToDefaultSettingsMenuItem_Click(object sender, EventArgs e) { if (MessageBox.Show("Restore default settings?\n\nThis will revert any changes to settings in this project.", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { Settings.Reset(); } } private void HelpAndSupportMenuItem_Click(object sender, EventArgs e) { try { Process.Start("http://trizbort.genstein.net/?help"); } catch (Exception) { NewVersionDialog.CannotLaunchWebSite(); } } private void CheckForUpdatesMenuItem_Click(object sender, EventArgs e) { NewVersionDialog.CheckForUpdatesAsync(this, true); } private void HelpAboutMenuItem_Click(object sender, EventArgs e) { using (var dialog = new AboutDialog()) { dialog.ShowDialog(); } } private void AutomapStartMenuItem_Click(object sender, EventArgs e) { using (var dialog = new AutomapDialog()) { if (dialog.ShowDialog() == DialogResult.OK) { m_canvas.StartAutomapping(dialog.Data); } } } private void AutomapStopMenuItem_Click(object sender, EventArgs e) { m_canvas.StopAutomapping(); } private void ViewMinimapMenuItem_Click(object sender, EventArgs e) { m_canvas.MinimapVisible = !m_canvas.MinimapVisible; Settings.ShowMiniMap = m_canvas.MinimapVisible; } private void FileMenu_DropDownOpening(object sender, EventArgs e) { // MRU list var existingItems = new List<ToolStripItem>(); foreach (ToolStripItem existingItem in m_fileRecentMapsMenuItem.DropDownItems) { existingItems.Add(existingItem); } foreach (var existingItem in existingItems) { existingItem.Click -= FileRecentProject_Click; existingItem.Dispose(); } if (Settings.RecentProjects.Count == 0) { m_fileRecentMapsMenuItem.Enabled = false; } else { m_fileRecentMapsMenuItem.Enabled = true; var index = 1; foreach (var recentProject in Settings.RecentProjects) { var menuItem = new ToolStripMenuItem(string.Format("&{0} {1}", index++, recentProject)); menuItem.Tag = recentProject; menuItem.Click += FileRecentProject_Click; m_fileRecentMapsMenuItem.DropDownItems.Add(menuItem); } } } private void EditSelectAllMenuItem_Click(object sender, EventArgs e) { m_canvas.SelectAll(); } private void EditSelectNoneMenuItem_Click(object sender, EventArgs e) { m_canvas.SelectedElement = null; } private void ViewEntireMapMenuItem_Click(object sender, EventArgs e) { m_canvas.ZoomToFit(); } [DllImport("gdi32.dll")] private static extern IntPtr CopyEnhMetaFile(IntPtr hemfSrc, string lpszFile); [DllImport("gdi32.dll")] private static extern int DeleteEnhMetaFile(IntPtr hemf); private string m_caption; private DateTime m_lastUpdateUITime; private static readonly TimeSpan IdleProcessingEveryNSeconds = TimeSpan.FromSeconds(0.2); private void m_editCopyMenuItem_Click(object sender, EventArgs e) { m_canvas.CopySelectedElements(); } private void m_editCopyColorToolMenuItem_Click(object sender, EventArgs e) { m_canvas.CopySelectedColor(); } private void m_editPasteMenuItem_Click(object sender, EventArgs e) { m_canvas.Paste(false); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Threading; using System.Threading.Tasks; namespace System.Net.Sockets { // The System.Net.Sockets.TcpClient class provide TCP services at a higher level // of abstraction than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpClient // is used to create a Client connection to a remote host. public class TcpClient : IDisposable { private Socket _clientSocket; private bool _active; private NetworkStream _dataStream; // IPv6: Maintain address family for the client. private AddressFamily _family = AddressFamily.InterNetwork; // Initializes a new instance of the System.Net.Sockets.TcpClient // class with the specified end point. public TcpClient(IPEndPoint localEP) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "TcpClient", localEP); } if (localEP == null) { throw new ArgumentNullException("localEP"); } // IPv6: Establish address family before creating a socket _family = localEP.AddressFamily; initialize(); Client.Bind(localEP); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "TcpClient", ""); } } // Initializes a new instance of the System.Net.Sockets.TcpClient class. public TcpClient() : this(AddressFamily.InterNetwork) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "TcpClient", null); } if (Logging.On) { Logging.Exit(Logging.Sockets, this, "TcpClient", null); } } // Initializes a new instance of the System.Net.Sockets.TcpClient class. public TcpClient(AddressFamily family) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "TcpClient", family); } // Validate parameter if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6) { throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "TCP"), "family"); } _family = family; initialize(); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "TcpClient", null); } } // Initializes a new instance of the System.Net.Sockets.TcpClient class and connects to the // specified port on the specified host. public TcpClient(string hostname, int port) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "TcpClient", hostname); } if (hostname == null) { throw new ArgumentNullException("hostname"); } if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException("port"); } // IPv6: Delay creating the client socket until we have // performed DNS resolution and know which address // families we can use. try { Connect(hostname, port); } catch (Exception e) { if (e is OutOfMemoryException) { throw; } if (_clientSocket != null) { _clientSocket.Dispose(); } throw e; } if (Logging.On) { Logging.Exit(Logging.Sockets, this, "TcpClient", null); } } // Used by TcpListener.Accept(). internal TcpClient(Socket acceptedSocket) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "TcpClient", acceptedSocket); } Client = acceptedSocket; _active = true; if (Logging.On) { Logging.Exit(Logging.Sockets, this, "TcpClient", null); } } // Used by the class to provide the underlying network socket. public Socket Client { get { return _clientSocket; } set { _clientSocket = value; } } // Used by the class to indicate that a connection has been made. protected bool Active { get { return _active; } set { _active = value; } } public int Available { get { return _clientSocket.Available; } } public bool Connected { get { return _clientSocket.Connected; } } public bool ExclusiveAddressUse { get { return _clientSocket.ExclusiveAddressUse; } set { _clientSocket.ExclusiveAddressUse = value; } } // Connects the Client to the specified port on the specified host. public void Connect(string hostname, int port) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "Connect", hostname); } if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (hostname == null) { throw new ArgumentNullException("hostname"); } if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException("port"); } // Check for already connected and throw here. This check // is not required in the other connect methods as they // will throw from WinSock. Here, the situation is more // complex since we have to resolve a hostname so it's // easier to simply block the request up front. if (_active) { throw new SocketException((int)SocketError.IsConnected); } // IPv6: We need to process each of the addresses return from // DNS when trying to connect. Use of AddressList[0] is // bad form. IPAddress[] addresses = Dns.GetHostAddressesAsync(hostname).GetAwaiter().GetResult(); Exception lastex = null; Socket ipv6Socket = null; Socket ipv4Socket = null; try { if (_clientSocket == null) { if (Socket.OSSupportsIPv4) { ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } if (Socket.OSSupportsIPv6) { ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); } } foreach (IPAddress address in addresses) { try { if (_clientSocket == null) { // We came via the <hostname,port> constructor. Set the // address family appropriately, create the socket and // try to connect. if (address.AddressFamily == AddressFamily.InterNetwork && ipv4Socket != null) { ipv4Socket.Connect(address, port); _clientSocket = ipv4Socket; if (ipv6Socket != null) { ipv6Socket.Dispose(); } } else if (ipv6Socket != null) { ipv6Socket.Connect(address, port); _clientSocket = ipv6Socket; if (ipv4Socket != null) { ipv4Socket.Dispose(); } } _family = address.AddressFamily; _active = true; break; } else if (address.AddressFamily == _family) { // Only use addresses with a matching family. Connect(new IPEndPoint(address, port)); _active = true; break; } } catch (Exception ex) { if (ex is OutOfMemoryException) { throw; } lastex = ex; } } } catch (Exception ex) { if (ex is OutOfMemoryException) { throw; } lastex = ex; } finally { // Cleanup temp sockets if failed. Main socket gets closed when TCPClient gets closed. // Did we connect? if (!_active) { if (ipv6Socket != null) { ipv6Socket.Dispose(); } if (ipv4Socket != null) { ipv4Socket.Dispose(); } // The connect failed - rethrow the last error we had. if (lastex != null) { throw lastex; } else { throw new SocketException((int)SocketError.NotConnected); } } } if (Logging.On) { Logging.Exit(Logging.Sockets, this, "Connect", null); } } // Connects the Client to the specified port on the specified host. public void Connect(IPAddress address, int port) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "Connect", address); } if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (address == null) { throw new ArgumentNullException("address"); } if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException("port"); } IPEndPoint remoteEP = new IPEndPoint(address, port); Connect(remoteEP); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "Connect", null); } } // Connect the Client to the specified end point. public void Connect(IPEndPoint remoteEP) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "Connect", remoteEP); } if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } Client.Connect(remoteEP); _active = true; if (Logging.On) { Logging.Exit(Logging.Sockets, this, "Connect", null); } } public void Connect(IPAddress[] ipAddresses, int port) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "Connect", ipAddresses); } Client.Connect(ipAddresses, port); _active = true; if (Logging.On) { Logging.Exit(Logging.Sockets, this, "Connect", null); } } public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "BeginConnect", host); } IAsyncResult result = Client.BeginConnect(host, port, requestCallback, state); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "BeginConnect", null); } return result; } public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "BeginConnect", address); } IAsyncResult result = Client.BeginConnect(address, port, requestCallback, state); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "BeginConnect", null); } return result; } public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "BeginConnect", addresses); } IAsyncResult result = Client.BeginConnect(addresses, port, requestCallback, state); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "BeginConnect", null); } return result; } public void EndConnect(IAsyncResult asyncResult) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "EndConnect", asyncResult); } Client.EndConnect(asyncResult); _active = true; if (Logging.On) { Logging.Exit(Logging.Sockets, this, "EndConnect", null); } } public Task ConnectAsync(IPAddress address, int port) { return Task.Factory.FromAsync(BeginConnect, EndConnect, address, port, null); } public Task ConnectAsync(string host, int port) { return Task.Factory.FromAsync(BeginConnect, EndConnect, host, port, null); } public Task ConnectAsync(IPAddress[] addresses, int port) { return Task.Factory.FromAsync(BeginConnect, EndConnect, addresses, port, null); } // Returns the stream used to read and write data to the remote host. public NetworkStream GetStream() { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "GetStream", ""); } if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!Client.Connected) { throw new InvalidOperationException(SR.net_notconnected); } if (_dataStream == null) { _dataStream = new NetworkStream(Client, true); } if (Logging.On) { Logging.Exit(Logging.Sockets, this, "GetStream", _dataStream); } return _dataStream; } private bool _cleanedUp = false; // Disposes the Tcp connection. protected virtual void Dispose(bool disposing) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "Dispose", ""); } if (_cleanedUp) { if (Logging.On) { Logging.Exit(Logging.Sockets, this, "Dispose", ""); } return; } if (disposing) { IDisposable dataStream = _dataStream; if (dataStream != null) { dataStream.Dispose(); } else { // If the NetworkStream wasn't created, the Socket might // still be there and needs to be closed. In the case in which // we are bound to a local IPEndPoint this will remove the // binding and free up the IPEndPoint for later uses. Socket chkClientSocket = Client; if (chkClientSocket != null) { try { chkClientSocket.InternalShutdown(SocketShutdown.Both); } finally { chkClientSocket.Dispose(); Client = null; } } } GC.SuppressFinalize(this); } _cleanedUp = true; if (Logging.On) { Logging.Exit(Logging.Sockets, this, "Dispose", ""); } } public void Dispose() { Dispose(true); } ~TcpClient() { #if DEBUG GlobalLog.SetThreadSource(ThreadKinds.Finalization); using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async)) { #endif Dispose(false); #if DEBUG } #endif } // Gets or sets the size of the receive buffer in bytes. public int ReceiveBufferSize { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); } } // Gets or sets the size of the send buffer in bytes. public int SendBufferSize { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value); } } // Gets or sets the receive time out value of the connection in seconds. public int ReceiveTimeout { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); } } // Gets or sets the send time out value of the connection in seconds. public int SendTimeout { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value); } } // Gets or sets the value of the connection's linger option. public LingerOption LingerState { get { return (LingerOption)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value); } } // Enables or disables delay when send or receive buffers are full. public bool NoDelay { get { return numericOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay) != 0 ? true : false; } set { Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0); } } private void initialize() { // IPv6: Use the address family from the constructor (or Connect method). Client = new Socket(_family, SocketType.Stream, ProtocolType.Tcp); _active = false; } private int numericOption(SocketOptionLevel optionLevel, SocketOptionName optionName) { return (int)Client.GetSocketOption(optionLevel, optionName); } } }
/* * 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. */ using Amazon.Util; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Linq; using UnityEngine; using Amazon.Runtime.Internal.Util; using Logger = Amazon.Runtime.Internal.Util.Logger; using ILogger = Amazon.Runtime.Internal.Util.ILogger; using UnityEngine.Experimental.Networking; using System.Text; namespace Amazon.Runtime.Internal.Transform { /// <summary> /// Implementation of response interface for WWW/UnityWebRequest API. /// </summary> public sealed class UnityWebResponseData : IWebResponseData, IHttpResponseBody { private Dictionary<string, string> _headers; private string[] _headerNames; private HashSet<string> _headerNamesSet; private Stream _responseStream; private byte[] _responseBody; private ILogger _logger; public UnityWebResponseData(UnityWebRequestWrapper unityWebRequest) { CopyHeaderValues(unityWebRequest.ResponseHeaders); if (!unityWebRequest.IsError) { _responseBody = unityWebRequest.DownloadHandler.Data; if (_responseBody == null) { _responseBody = new byte[0]; } _responseStream = new MemoryStream(_responseBody); this.ContentLength = _responseBody.LongLength; string contentType = null; this._headers.TryGetValue(HeaderKeys.ContentTypeHeader, out contentType); this.ContentType = contentType; if (unityWebRequest.StatusCode.HasValue) this.StatusCode = unityWebRequest.StatusCode.Value; this.IsSuccessStatusCode = this.StatusCode >= HttpStatusCode.OK && this.StatusCode <= (HttpStatusCode)299; } else { this.IsSuccessStatusCode = false; this._responseBody = UTF8Encoding.UTF8.GetBytes(unityWebRequest.Error); _responseStream = new MemoryStream(_responseBody); if (unityWebRequest.DownloadedBytes > 0) { this.ContentLength = (long)unityWebRequest.DownloadedBytes; } else { string contentLength = null; if (this._headers.TryGetValue(HeaderKeys.ContentLengthHeader, out contentLength)) { long cl; if(long.TryParse(contentLength,out cl)) this.ContentLength = cl; else this.ContentLength = 0; } else { this.ContentLength = this._responseBody.Length; } } if (unityWebRequest.StatusCode.HasValue) { this.StatusCode = unityWebRequest.StatusCode.Value; } else { string statusCode = null; if (this._headers.TryGetValue(HeaderKeys.StatusHeader, out statusCode)) { this.StatusCode = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), statusCode); } else { this.StatusCode = 0; } } } } /// <summary> /// The constructor for UnityWebResponseData. /// </summary> /// <param name="wwwRequest"> /// An instance of WWW after the web request has /// completed and response fields are set /// </param> public UnityWebResponseData(WWW wwwRequest) { _logger = Logger.GetLogger(this.GetType()); CopyHeaderValues(wwwRequest.responseHeaders); try { _responseBody = wwwRequest.bytes; } catch (Exception) { _responseBody = null; } if ((_responseBody != null && _responseBody.Length > 0) || (_responseBody.Length == 0 && wwwRequest.error == null)) { _responseStream = new MemoryStream(_responseBody); } this.ContentLength = wwwRequest.bytesDownloaded; string contentType = null; this._headers.TryGetValue( HeaderKeys.ContentTypeHeader, out contentType); this.ContentType = contentType; try { if (string.IsNullOrEmpty(wwwRequest.error)) { string statusHeader = string.Empty; if (this._headers.TryGetValue(HeaderKeys.StatusHeader, out statusHeader)) { this.StatusCode = (HttpStatusCode)Enum.Parse( typeof(HttpStatusCode), statusHeader.Substring(9, 3).Trim()); } else { this.StatusCode = 0; } } else { int statusCode; if (Int32.TryParse(wwwRequest.error.Substring(0, 3), out statusCode)) this.StatusCode = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), wwwRequest.error.Substring(3).Replace(" ", "").Replace(":", "").Trim(), true);//ignored case else this.StatusCode = 0; } } catch { this.StatusCode = 0; } this.IsSuccessStatusCode = wwwRequest.error == null ? true : false; } /// <summary> /// Content length on the response. /// </summary> public long ContentLength { get; private set; } /// <summary> /// The content type of the response. /// </summary> public string ContentType { get; private set; } /// <summary> /// The HTTP status code for the response. /// </summary> public HttpStatusCode StatusCode { get; private set; } /// <summary> /// Returns a boolean value indicating if the status code /// indicated a success. /// </summary> public bool IsSuccessStatusCode { get; private set; } public bool IsHeaderPresent(string headerName) { return _headerNamesSet.Contains(headerName); } public string[] GetHeaderNames() { return _headerNames; } public string GetHeaderValue(string name) { string headerValue; if (_headers.TryGetValue(name, out headerValue)) return headerValue; return string.Empty; } private void CopyHeaderValues(Dictionary<string, string> headers) { _headers = new Dictionary<string, string>(headers, StringComparer.OrdinalIgnoreCase); _headerNames = headers.Keys.ToArray<string>(); _headerNamesSet = new HashSet<string>(_headerNames, StringComparer.OrdinalIgnoreCase); } /// <summary> /// Instance of IHttpResponseBody. /// </summary> public IHttpResponseBody ResponseBody { get { return this; } } /// <summary> /// Bool value which is returned if there is response body present /// </summary> public bool IsResponseBodyPresent { get { return _responseBody != null && _responseBody.Length > 0; } } #region IHttpResponseBody implementation /// <summary> /// Returns a stream that allows reading the response body. /// </summary> /// <returns>A stream representing the response body.</returns> public Stream OpenResponse() { return _responseStream; } /// <summary> /// Disposes the response stream. /// </summary> public void Dispose() { if (_responseStream != null) { _responseStream.Dispose(); _responseStream = null; } } #endregion } }
using NetApp.Tests.Helpers; using Microsoft.Azure.Management.NetApp; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System.IO; using System.Linq; using System.Net; using System.Reflection; using Xunit; using System; using Microsoft.Azure.Management.NetApp.Models; using System.Collections.Generic; using Microsoft.Rest.Azure; namespace NetApp.Tests.ResourceTests { public class AccountTests : TestBase { [Fact] public void CreateDeleteAccount() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var accountsInitial = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); int initialCount = accountsInitial.Count(); // create the account with only the one required property var netAppAccount = new NetAppAccount() { Location = ResourceUtils.location }; var resource = netAppMgmtClient.Accounts.CreateOrUpdate(netAppAccount, ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.Equal(resource.Name, ResourceUtils.accountName1); Assert.Null(resource.ActiveDirectories); // get all accounts and check var accountsBefore = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); Assert.Equal(initialCount + 1, accountsBefore.Count()); // remove the account and check netAppMgmtClient.Accounts.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1); // get all accounts and check var accountsAfter = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); Assert.Equal(initialCount, accountsAfter.Count()); } } [Fact] public void CreateAccountWithProperties() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var dict = new Dictionary<string, string>(); dict.Add("Tag1", "Value1"); // create the account var resource = ResourceUtils.CreateAccount(netAppMgmtClient, tags: dict, activeDirectory: ResourceUtils.activeDirectory); Assert.True(resource.Tags.ContainsKey("Tag1")); Assert.Equal("Value1", resource.Tags["Tag1"]); Assert.NotNull(resource.ActiveDirectories); // remove the account netAppMgmtClient.Accounts.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1); } } [Fact] public void UpdateAccount() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the account ResourceUtils.CreateAccount(netAppMgmtClient); // perform create/update operation again for same account // this should be treated as an update and accepted // could equally do this with some property fields added var dict = new Dictionary<string, string>(); dict.Add("Tag1", "Value2"); var resource = ResourceUtils.CreateAccount(netAppMgmtClient, tags: dict); Assert.True(resource.Tags.ContainsKey("Tag1")); Assert.Equal("Value2", resource.Tags["Tag1"]); } } [Fact] public void ListAccounts() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var accountsBefore = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); int count = accountsBefore.Count(); // create two accounts ResourceUtils.CreateAccount(netAppMgmtClient); ResourceUtils.CreateAccount(netAppMgmtClient, ResourceUtils.accountName2); // get the account list and check var accounts = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); Assert.Contains(accounts, item => item.Name == ResourceUtils.accountName1); Assert.Contains(accounts, item => item.Name == ResourceUtils.accountName2); // clean up - delete the two accounts ResourceUtils.DeleteAccount(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient, ResourceUtils.accountName2); } } [Fact] public void ListAccountsBySubscription() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var accountsBefore = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); int count = accountsBefore.Count(); // create two accounts ResourceUtils.CreateAccount(netAppMgmtClient); ResourceUtils.CreateAccount(netAppMgmtClient, ResourceUtils.accountName2); // get the account list and check var accounts = netAppMgmtClient.Accounts.ListBySubscription(); Assert.Contains(accounts, item => item.Name == ResourceUtils.accountName1); Assert.Contains(accounts, item => item.Name == ResourceUtils.accountName2); // clean up - delete the two accounts ResourceUtils.DeleteAccount(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient, ResourceUtils.accountName2); } } [Fact] public void GetAccountByName() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the account ResourceUtils.CreateAccount(netAppMgmtClient, ResourceUtils.accountName1); // get and check the account var account = netAppMgmtClient.Accounts.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.Equal(account.Name, ResourceUtils.accountName1); // clean up - delete the account ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void GetAccountByNameNotFound() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); string expectedErrorCode = "ResourceNotFound"; using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // get and check the account try { var account = netAppMgmtClient.Accounts.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.True(false); // expecting exception } catch (CloudException cex) { Assert.Equal(cex.Body.Code, expectedErrorCode); } } } [Fact] public void PatchAccount() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the account ResourceUtils.CreateAccount(netAppMgmtClient, activeDirectory: ResourceUtils.activeDirectory); var dict = new Dictionary<string, string>(); dict.Add("Tag2", "Value1"); // Now try and modify it var netAppAccountPatch = new NetAppAccountPatch() { Tags = dict }; // tag changes but active directory still present var resource = netAppMgmtClient.Accounts.Update(netAppAccountPatch, ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.True(resource.Tags.ContainsKey("Tag2")); Assert.Equal("Value1", resource.Tags["Tag2"]); Assert.NotNull(resource.ActiveDirectories); Assert.Equal("sdkuser", resource.ActiveDirectories.First().Username); // so deleting the active directory requires the put operation // but changing an active directory can be done but requires the id ResourceUtils.activeDirectory2.ActiveDirectoryId = resource.ActiveDirectories.First().ActiveDirectoryId; var activeDirectories = new List<ActiveDirectory> { ResourceUtils.activeDirectory2 }; dict.Add("Tag3", "Value3"); // Now try and modify it var netAppAccountPatch2 = new NetAppAccountPatch() { ActiveDirectories = activeDirectories, Tags = dict }; var resource2 = netAppMgmtClient.Accounts.Update(netAppAccountPatch2, ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.True(resource2.Tags.ContainsKey("Tag2")); Assert.Equal("Value1", resource2.Tags["Tag2"]); Assert.True(resource2.Tags.ContainsKey("Tag3")); Assert.Equal("Value3", resource2.Tags["Tag3"]); Assert.NotNull(resource2.ActiveDirectories); Assert.Equal("sdkuser1", resource2.ActiveDirectories.First().Username); // cleanup - remove the account ResourceUtils.DeleteAccount(netAppMgmtClient); } } private static string GetSessionsDirectoryPath() { string executingAssemblyPath = typeof(NetApp.Tests.ResourceTests.AccountTests).GetTypeInfo().Assembly.Location; return Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords"); } } }
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System; using System.Collections.Generic; using System.Linq; using System.Numerics; namespace Geb.Image.Formats.Jpeg.Components.Decoder.ColorConverters { /// <summary> /// Encapsulates the conversion of Jpeg channels to RGBA values packed in <see cref="Vector4"/> buffer. /// </summary> internal abstract partial class JpegColorConverter { /// <summary> /// The avalilable converters /// </summary> private static readonly JpegColorConverter[] Converters = { GetYCbCrConverter(), new FromYccK(), new FromCmyk(), new FromGrayscale(), new FromRgb() }; /// <summary> /// Initializes a new instance of the <see cref="JpegColorConverter"/> class. /// </summary> protected JpegColorConverter(JpegColorSpace colorSpace) { this.ColorSpace = colorSpace; } /// <summary> /// Gets the <see cref="JpegColorSpace"/> of this converter. /// </summary> public JpegColorSpace ColorSpace { get; } /// <summary> /// Returns the <see cref="JpegColorConverter"/> corresponding to the given <see cref="JpegColorSpace"/> /// </summary> public static JpegColorConverter GetConverter(JpegColorSpace colorSpace) { JpegColorConverter converter = Converters.FirstOrDefault(c => c.ColorSpace == colorSpace); if (converter == null) { throw new Exception($"Could not find any converter for JpegColorSpace {colorSpace}!"); } return converter; } /// <summary> /// He implementation of the conversion. /// </summary> /// <param name="values">The input as a stack-only <see cref="ComponentValues"/> struct</param> /// <param name="result">The destination buffer of <see cref="Vector4"/> values</param> public abstract void ConvertToRgba(ComponentValues values, Span<Vector4> result); /// <summary> /// Returns the <see cref="JpegColorConverter"/> for the YCbCr colorspace that matches the current CPU architecture. /// </summary> private static JpegColorConverter GetYCbCrConverter() => JpegColorConverter.FromYCbCrSimdAvx2.IsAvailable ? (JpegColorConverter)new JpegColorConverter.FromYCbCrSimdAvx2() : new JpegColorConverter.FromYCbCrSimd(); /// <summary> /// A stack-only struct to reference the input buffers using <see cref="ReadOnlySpan{T}"/>-s. /// </summary> #pragma warning disable SA1206 // Declaration keywords should follow order public readonly ref struct ComponentValues #pragma warning restore SA1206 // Declaration keywords should follow order { /// <summary> /// The component count /// </summary> public readonly int ComponentCount; /// <summary> /// The component 0 (eg. Y) /// </summary> public readonly ReadOnlySpan<float> Component0; /// <summary> /// The component 1 (eg. Cb) /// </summary> public readonly ReadOnlySpan<float> Component1; /// <summary> /// The component 2 (eg. Cr) /// </summary> public readonly ReadOnlySpan<float> Component2; /// <summary> /// The component 4 /// </summary> public readonly ReadOnlySpan<float> Component3; /// <summary> /// Initializes a new instance of the <see cref="ComponentValues"/> struct. /// </summary> /// <param name="componentBuffers">The 1-4 sized list of component buffers.</param> /// <param name="row">The row to convert</param> public ComponentValues(IReadOnlyList<IBuffer2D<float>> componentBuffers, int row) { this.ComponentCount = componentBuffers.Count; this.Component0 = componentBuffers[0].GetRowSpan(row); this.Component1 = Span<float>.Empty; this.Component2 = Span<float>.Empty; this.Component3 = Span<float>.Empty; if (this.ComponentCount > 1) { this.Component1 = componentBuffers[1].GetRowSpan(row); if (this.ComponentCount > 2) { this.Component2 = componentBuffers[2].GetRowSpan(row); if (this.ComponentCount > 3) { this.Component3 = componentBuffers[3].GetRowSpan(row); } } } } private ComponentValues( int componentCount, ReadOnlySpan<float> c0, ReadOnlySpan<float> c1, ReadOnlySpan<float> c2, ReadOnlySpan<float> c3) { this.ComponentCount = componentCount; this.Component0 = c0; this.Component1 = c1; this.Component2 = c2; this.Component3 = c3; } public ComponentValues Slice(int start, int length) { ReadOnlySpan<float> c0 = this.Component0.Slice(start, length); ReadOnlySpan<float> c1 = this.ComponentCount > 1 ? this.Component1.Slice(start, length) : ReadOnlySpan<float>.Empty; ReadOnlySpan<float> c2 = this.ComponentCount > 2 ? this.Component2.Slice(start, length) : ReadOnlySpan<float>.Empty; ReadOnlySpan<float> c3 = this.ComponentCount > 3 ? this.Component3.Slice(start, length) : ReadOnlySpan<float>.Empty; return new ComponentValues(this.ComponentCount, c0, c1, c2, c3); } } internal struct Vector4Octet { #pragma warning disable SA1132 // Do not combine fields public Vector4 V0, V1, V2, V3, V4, V5, V6, V7; /// <summary> /// Collect (r0,r1...r8) (g0,g1...g8) (b0,b1...b8) vector values in the expected (r0,g0,g1,1), (r1,g1,g2,1) ... order. /// </summary> public void Collect(ref Vector4Pair r, ref Vector4Pair g, ref Vector4Pair b) { this.V0.X = r.A.X; this.V0.Y = g.A.X; this.V0.Z = b.A.X; this.V0.W = 1f; this.V1.X = r.A.Y; this.V1.Y = g.A.Y; this.V1.Z = b.A.Y; this.V1.W = 1f; this.V2.X = r.A.Z; this.V2.Y = g.A.Z; this.V2.Z = b.A.Z; this.V2.W = 1f; this.V3.X = r.A.W; this.V3.Y = g.A.W; this.V3.Z = b.A.W; this.V3.W = 1f; this.V4.X = r.B.X; this.V4.Y = g.B.X; this.V4.Z = b.B.X; this.V4.W = 1f; this.V5.X = r.B.Y; this.V5.Y = g.B.Y; this.V5.Z = b.B.Y; this.V5.W = 1f; this.V6.X = r.B.Z; this.V6.Y = g.B.Z; this.V6.Z = b.B.Z; this.V6.W = 1f; this.V7.X = r.B.W; this.V7.Y = g.B.W; this.V7.Z = b.B.W; this.V7.W = 1f; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Inheritance operations. /// </summary> public partial class Inheritance : IServiceOperations<AutoRestComplexTestService>, IInheritance { /// <summary> /// Initializes a new instance of the Inheritance class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Inheritance(AutoRestComplexTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestComplexTestService /// </summary> public AutoRestComplexTestService Client { get; private set; } /// <summary> /// Get complex types that extend others /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Siamese>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Siamese>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Siamese>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types that extend others /// </summary> /// <param name='complexBody'> /// Please put a siamese with id=2, name="Siameee", color=green, /// breed=persion, which hates 2 dogs, the 1st one named "Potato" with id=1 /// and food="tomato", and the 2nd one named "Tomato" with id=-1 and /// food="french fries". /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Siamese complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } 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. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Sse2.IsSupported) { { double* inArray = stackalloc double[2]; byte* outBuffer = stackalloc byte[32]; double* outArray = (double*)Align(outBuffer, 16); var vf = Unsafe.Read<Vector128<double>>(inArray); Sse2.StoreAligned(outArray, vf); for (var i = 0; i < 2; i++) { if (BitConverter.DoubleToInt64Bits(inArray[i]) != BitConverter.DoubleToInt64Bits(outArray[i])) { Console.WriteLine("Sse2 StoreAligned failed on double:"); for (var n = 0; n < 2; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { long* inArray = stackalloc long[2]; byte* outBuffer = stackalloc byte[32]; long* outArray = (long*)Align(outBuffer, 16); var vf = Unsafe.Read<Vector128<long>>(inArray); Sse2.StoreAligned(outArray, vf); for (var i = 0; i < 2; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Sse2 StoreAligned failed on long:"); for (var n = 0; n < 2; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { ulong* inArray = stackalloc ulong[2]; byte* outBuffer = stackalloc byte[32]; ulong* outArray = (ulong*)Align(outBuffer, 16); var vf = Unsafe.Read<Vector128<ulong>>(inArray); Sse2.StoreAligned(outArray, vf); for (var i = 0; i < 2; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Sse2 StoreAligned failed on ulong:"); for (var n = 0; n < 2; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { int* inArray = stackalloc int[4]; byte* outBuffer = stackalloc byte[32]; int* outArray = (int*)Align(outBuffer, 16); var vf = Unsafe.Read<Vector128<int>>(inArray); Sse2.StoreAligned(outArray, vf); for (var i = 0; i < 4; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Sse2 StoreAligned failed on int:"); for (var n = 0; n < 4; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { uint* inArray = stackalloc uint[4]; byte* outBuffer = stackalloc byte[32]; uint* outArray = (uint*)Align(outBuffer, 16); var vf = Unsafe.Read<Vector128<uint>>(inArray); Sse2.StoreAligned(outArray, vf); for (var i = 0; i < 4; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Sse2 StoreAligned failed on uint:"); for (var n = 0; n < 4; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { short* inArray = stackalloc short[8]; byte* outBuffer = stackalloc byte[32]; short* outArray = (short*)Align(outBuffer, 16); var vf = Unsafe.Read<Vector128<short>>(inArray); Sse2.StoreAligned(outArray, vf); for (var i = 0; i < 8; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Sse2 StoreAligned failed on short:"); for (var n = 0; n < 8; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { ushort* inArray = stackalloc ushort[8]; byte* outBuffer = stackalloc byte[32]; ushort* outArray = (ushort*)Align(outBuffer, 16); var vf = Unsafe.Read<Vector128<ushort>>(inArray); Sse2.StoreAligned(outArray, vf); for (var i = 0; i < 8; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Sse2 StoreAligned failed on ushort:"); for (var n = 0; n < 8; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { byte* inArray = stackalloc byte[16]; byte* outBuffer = stackalloc byte[32]; byte* outArray = (byte*)Align(outBuffer, 16); var vf = Unsafe.Read<Vector128<byte>>(inArray); Sse2.StoreAligned(outArray, vf); for (var i = 0; i < 16; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Sse2 StoreAligned failed on byte:"); for (var n = 0; n < 16; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { sbyte* inArray = stackalloc sbyte[16]; byte* outBuffer = stackalloc byte[32]; sbyte* outArray = (sbyte*)Align(outBuffer, 16); var vf = Unsafe.Read<Vector128<sbyte>>(inArray); Sse2.StoreAligned(outArray, vf); for (var i = 0; i < 16; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Sse2 StoreAligned failed on byte:"); for (var n = 0; n < 16; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } } return testResult; } static unsafe void* Align(byte* buffer, byte expectedAlignment) { // Compute how bad the misalignment is, which is at most (expectedAlignment - 1). // Then subtract that from the expectedAlignment and add it to the original address // to compute the aligned address. var misalignment = expectedAlignment - ((ulong)(buffer) % expectedAlignment); return (void*)(buffer + misalignment); } } }
// // SaslMechanism.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.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.Net; using System.Text; #if NETFX_CORE using Encoding = Portable.Text.Encoding; #endif namespace MailKit.Security { /// <summary> /// A SASL authentication mechanism. /// </summary> /// <remarks> /// Authenticating via a SASL mechanism may be a multi-step process. /// To determine if the mechanism has completed the necessary steps /// to authentication, check the <see cref="IsAuthenticated"/> after /// each call to <see cref="Challenge(string)"/>. /// </remarks> public abstract class SaslMechanism { /// <summary> /// The supported authentication mechanisms in order of strongest to weakest. /// </summary> /// <remarks> /// Used by the various clients when authenticating via SASL to determine /// which order the SASL mechanisms supported by the server should be tried. /// </remarks> public static readonly string[] AuthMechanismRank = { "XOAUTH2", "SCRAM-SHA-256", "SCRAM-SHA-1", "NTLM", "CRAM-MD5", "DIGEST-MD5", "PLAIN", "LOGIN" }; /// <summary> /// Initializes a new instance of the <see cref="MailKit.Security.SaslMechanism"/> class. /// </summary> /// <remarks> /// Creates a new SASL context. /// </remarks> /// <param name="uri">The URI of the service.</param> /// <param name="credentials">The user's credentials.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="uri"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="credentials"/> is <c>null</c>.</para> /// </exception> protected SaslMechanism (Uri uri, ICredentials credentials) { if (uri == null) throw new ArgumentNullException ("uri"); if (credentials == null) throw new ArgumentNullException ("credentials"); Credentials = credentials; Uri = uri; } /// <summary> /// Gets the name of the mechanism. /// </summary> /// <remarks> /// Gets the name of the mechanism. /// </remarks> /// <value>The name of the mechanism.</value> public abstract string MechanismName { get; } /// <summary> /// Gets the user's credentials. /// </summary> /// <remarks> /// Gets the user's credentials. /// </remarks> /// <value>The user's credentials.</value> public ICredentials Credentials { get; private set; } /// <summary> /// Gets whether or not the mechanism supports an initial response (SASL-IR). /// </summary> /// <remarks> /// SASL mechanisms that support sending an initial client response to the server /// should return <value>true</value>. /// </remarks> /// <value><c>true</c> if the mechanism supports an initial response; otherwise, <c>false</c>.</value> public virtual bool SupportsInitialResponse { get { return false; } } /// <summary> /// Gets or sets whether the SASL mechanism has finished authenticating. /// </summary> /// <remarks> /// Gets or sets whether the SASL mechanism has finished authenticating. /// </remarks> /// <value><c>true</c> if the SASL mechanism has finished authenticating; otherwise, <c>false</c>.</value> public bool IsAuthenticated { get; protected set; } /// <summary> /// Gets or sets the URI of the service. /// </summary> /// <remarks> /// Gets or sets the URI of the service. /// </remarks> /// <value>The URI of the service.</value> public Uri Uri { get; protected set; } /// <summary> /// Parses the server's challenge token and returns the next challenge response. /// </summary> /// <remarks> /// Parses the server's challenge token and returns the next challenge response. /// </remarks> /// <returns>The next challenge response.</returns> /// <param name="token">The server's challenge token.</param> /// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param> /// <param name="length">The length of the server's challenge.</param> /// <exception cref="System.InvalidOperationException"> /// The SASL mechanism is already authenticated. /// </exception> /// <exception cref="System.NotSupportedException"> /// THe SASL mechanism does not support SASL-IR. /// </exception> /// <exception cref="SaslException"> /// An error has occurred while parsing the server's challenge token. /// </exception> protected abstract byte[] Challenge (byte[] token, int startIndex, int length); /// <summary> /// Decodes the base64-encoded server challenge and returns the next challenge response encoded in base64. /// </summary> /// <remarks> /// Decodes the base64-encoded server challenge and returns the next challenge response encoded in base64. /// </remarks> /// <returns>The next base64-encoded challenge response.</returns> /// <param name="token">The server's base64-encoded challenge token.</param> /// <exception cref="System.InvalidOperationException"> /// The SASL mechanism is already authenticated. /// </exception> /// <exception cref="System.NotSupportedException"> /// THe SASL mechanism does not support SASL-IR. /// </exception> /// <exception cref="SaslException"> /// An error has occurred while parsing the server's challenge token. /// </exception> public string Challenge (string token) { byte[] decoded = null; int length = 0; if (token != null) { try { decoded = Convert.FromBase64String (token.Trim ()); length = decoded.Length; } catch (FormatException) { } } var challenge = Challenge (decoded, 0, length); if (challenge == null) return null; return Convert.ToBase64String (challenge); } /// <summary> /// Resets the state of the SASL mechanism. /// </summary> /// <remarks> /// Resets the state of the SASL mechanism. /// </remarks> public virtual void Reset () { IsAuthenticated = false; } /// <summary> /// Determines if the specified SASL mechanism is supported by MailKit. /// </summary> /// <remarks> /// Use this method to make sure that a SASL mechanism is supported before calling /// <see cref="Create(string,Uri,ICredentials)"/>. /// </remarks> /// <returns><c>true</c> if the specified SASL mechanism is supported; otherwise, <c>false</c>.</returns> /// <param name="mechanism">The name of the SASL mechanism.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="mechanism"/> is <c>null</c>. /// </exception> public static bool IsSupported (string mechanism) { if (mechanism == null) throw new ArgumentNullException ("mechanism"); switch (mechanism) { case "SCRAM-SHA-256": return true; case "SCRAM-SHA-1": return true; case "DIGEST-MD5": return true; case "CRAM-MD5": return true; case "XOAUTH2": return true; case "PLAIN": return true; case "LOGIN": return true; case "NTLM": return true; default: return false; } } /// <summary> /// Create an instance of the specified SASL mechanism using the uri and credentials. /// </summary> /// <remarks> /// If unsure that a particular SASL mechanism is supported, you should first call /// <see cref="IsSupported"/>. /// </remarks> /// <returns>An instance of the requested SASL mechanism if supported; otherwise <c>null</c>.</returns> /// <param name="mechanism">The name of the SASL mechanism.</param> /// <param name="uri">The URI of the service to authenticate against.</param> /// <param name="encoding">The text encoding to use for the credentials.</param> /// <param name="credentials">The user's credentials.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="mechanism"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="uri"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="encoding"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="credentials"/> is <c>null</c>.</para> /// </exception> public static SaslMechanism Create (string mechanism, Uri uri, Encoding encoding, ICredentials credentials) { if (mechanism == null) throw new ArgumentNullException ("mechanism"); if (uri == null) throw new ArgumentNullException ("uri"); if (encoding == null) throw new ArgumentNullException ("encoding"); if (credentials == null) throw new ArgumentNullException ("credentials"); switch (mechanism) { //case "KERBEROS_V4": return null; case "SCRAM-SHA-256": return new SaslMechanismScramSha256 (uri, credentials); case "SCRAM-SHA-1": return new SaslMechanismScramSha1 (uri, credentials); case "DIGEST-MD5": return new SaslMechanismDigestMd5 (uri, credentials); case "CRAM-MD5": return new SaslMechanismCramMd5 (uri, credentials); //case "GSSAPI": return null; case "XOAUTH2": return new SaslMechanismOAuth2 (uri, credentials); case "PLAIN": return new SaslMechanismPlain (uri, encoding, credentials); case "LOGIN": return new SaslMechanismLogin (uri, encoding, credentials); case "NTLM": return new SaslMechanismNtlm (uri, credentials); default: return null; } } /// <summary> /// Create an instance of the specified SASL mechanism using the uri and credentials. /// </summary> /// <remarks> /// If unsure that a particular SASL mechanism is supported, you should first call /// <see cref="IsSupported"/>. /// </remarks> /// <returns>An instance of the requested SASL mechanism if supported; otherwise <c>null</c>.</returns> /// <param name="mechanism">The name of the SASL mechanism.</param> /// <param name="uri">The URI of the service to authenticate against.</param> /// <param name="credentials">The user's credentials.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="mechanism"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="uri"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="credentials"/> is <c>null</c>.</para> /// </exception> public static SaslMechanism Create (string mechanism, Uri uri, ICredentials credentials) { return Create (mechanism, uri, Encoding.UTF8, credentials); } /// <summary> /// Determines if the character is a non-ASCII space. /// </summary> /// <remarks> /// This list was obtained from http://tools.ietf.org/html/rfc3454#appendix-C.1.2 /// </remarks> /// <returns><c>true</c> if the character is a non-ASCII space; otherwise, <c>false</c>.</returns> /// <param name="c">The character.</param> static bool IsNonAsciiSpace (char c) { switch (c) { case '\u00A0': // NO-BREAK SPACE case '\u1680': // OGHAM SPACE MARK case '\u2000': // EN QUAD case '\u2001': // EM QUAD case '\u2002': // EN SPACE case '\u2003': // EM SPACE case '\u2004': // THREE-PER-EM SPACE case '\u2005': // FOUR-PER-EM SPACE case '\u2006': // SIX-PER-EM SPACE case '\u2007': // FIGURE SPACE case '\u2008': // PUNCTUATION SPACE case '\u2009': // THIN SPACE case '\u200A': // HAIR SPACE case '\u200B': // ZERO WIDTH SPACE case '\u202F': // NARROW NO-BREAK SPACE case '\u205F': // MEDIUM MATHEMATICAL SPACE case '\u3000': // IDEOGRAPHIC SPACE return true; default: return false; } } /// <summary> /// Determines if the character is commonly mapped to nothing. /// </summary> /// <remarks> /// This list was obtained from http://tools.ietf.org/html/rfc3454#appendix-B.1 /// </remarks> /// <returns><c>true</c> if the character is commonly mapped to nothing; otherwise, <c>false</c>.</returns> /// <param name="c">The character.</param> static bool IsCommonlyMappedToNothing (char c) { switch (c) { case '\u00AD': case '\u034F': case '\u1806': case '\u180B': case '\u180C': case '\u180D': case '\u200B': case '\u200C': case '\u200D': case '\u2060': case '\uFE00': case '\uFE01': case '\uFE02': case '\uFE03': case '\uFE04': case '\uFE05': case '\uFE06': case '\uFE07': case '\uFE08': case '\uFE09': case '\uFE0A': case '\uFE0B': case '\uFE0C': case '\uFE0D': case '\uFE0E': case '\uFE0F': case '\uFEFF': return true; default: return false; } } /// <summary> /// Determines if the character is prohibited. /// </summary> /// <remarks> /// This list was obtained from http://tools.ietf.org/html/rfc3454#appendix-C.3 /// </remarks> /// <returns><c>true</c> if the character is prohibited; otherwise, <c>false</c>.</returns> /// <param name="s">The string.</param> /// <param name="index">The character index.</param> static bool IsProhibited (string s, int index) { int u = char.ConvertToUtf32 (s, index); // Private Use characters: http://tools.ietf.org/html/rfc3454#appendix-C.3 if ((u >= 0xE000 && u <= 0xF8FF) || (u >= 0xF0000 && u <= 0xFFFFD) || (u >= 0x100000 && u <= 0x10FFFD)) return true; // Non-character code points: http://tools.ietf.org/html/rfc3454#appendix-C.4 if ((u >= 0xFDD0 && u <= 0xFDEF) || (u >= 0xFFFE && u <= 0xFFFF) || (u >= 0x1FFFE & u <= 0x1FFFF) || (u >= 0x2FFFE & u <= 0x2FFFF) || (u >= 0x3FFFE & u <= 0x3FFFF) || (u >= 0x4FFFE & u <= 0x4FFFF) || (u >= 0x5FFFE & u <= 0x5FFFF) || (u >= 0x6FFFE & u <= 0x6FFFF) || (u >= 0x7FFFE & u <= 0x7FFFF) || (u >= 0x8FFFE & u <= 0x8FFFF) || (u >= 0x9FFFE & u <= 0x9FFFF) || (u >= 0xAFFFE & u <= 0xAFFFF) || (u >= 0xBFFFE & u <= 0xBFFFF) || (u >= 0xCFFFE & u <= 0xCFFFF) || (u >= 0xDFFFE & u <= 0xDFFFF) || (u >= 0xEFFFE & u <= 0xEFFFF) || (u >= 0xFFFFE & u <= 0xFFFFF) || (u >= 0x10FFFE & u <= 0x10FFFF)) return true; // Surrogate code points: http://tools.ietf.org/html/rfc3454#appendix-C.5 if (u >= 0xD800 && u <= 0xDFFF) return true; // Inappropriate for plain text characters: http://tools.ietf.org/html/rfc3454#appendix-C.6 switch (u) { case 0xFFF9: // INTERLINEAR ANNOTATION ANCHOR case 0xFFFA: // INTERLINEAR ANNOTATION SEPARATOR case 0xFFFB: // INTERLINEAR ANNOTATION TERMINATOR case 0xFFFC: // OBJECT REPLACEMENT CHARACTER case 0xFFFD: // REPLACEMENT CHARACTER return true; } // Inappropriate for canonical representation: http://tools.ietf.org/html/rfc3454#appendix-C.7 if (u >= 0x2FF0 && u <= 0x2FFB) return true; // Change display properties or are deprecated: http://tools.ietf.org/html/rfc3454#appendix-C.8 switch (u) { case 0x0340: // COMBINING GRAVE TONE MARK case 0x0341: // COMBINING ACUTE TONE MARK case 0x200E: // LEFT-TO-RIGHT MARK case 0x200F: // RIGHT-TO-LEFT MARK case 0x202A: // LEFT-TO-RIGHT EMBEDDING case 0x202B: // RIGHT-TO-LEFT EMBEDDING case 0x202C: // POP DIRECTIONAL FORMATTING case 0x202D: // LEFT-TO-RIGHT OVERRIDE case 0x202E: // RIGHT-TO-LEFT OVERRIDE case 0x206A: // INHIBIT SYMMETRIC SWAPPING case 0x206B: // ACTIVATE SYMMETRIC SWAPPING case 0x206C: // INHIBIT ARABIC FORM SHAPING case 0x206D: // ACTIVATE ARABIC FORM SHAPING case 0x206E: // NATIONAL DIGIT SHAPES case 0x206F: // NOMINAL DIGIT SHAPES return true; } // Tagging characters: http://tools.ietf.org/html/rfc3454#appendix-C.9 if (u == 0xE0001 || (u >= 0xE0020 & u <= 0xE007F)) return true; return false; } /// <summary> /// Prepares the user name or password string. /// </summary> /// <remarks> /// Prepares a user name or password string according to the rules of rfc4013. /// </remarks> /// <returns>The prepared string.</returns> /// <param name="s">The string to prepare.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="s"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="s"/> contains prohibited characters. /// </exception> public static string SaslPrep (string s) { if (s == null) throw new ArgumentNullException ("s"); if (s.Length == 0) return s; var builder = new StringBuilder (s.Length); for (int i = 0; i < s.Length; i++) { if (IsNonAsciiSpace (s[i])) { // non-ASII space characters [StringPrep, C.1.2] that can be // mapped to SPACE (U+0020). builder.Append (' '); } else if (IsCommonlyMappedToNothing (s[i])) { // the "commonly mapped to nothing" characters [StringPrep, B.1] // that can be mapped to nothing. } else if (char.IsControl (s[i])) { throw new ArgumentException ("Control characters are prohibited.", "s"); } else if (IsProhibited (s, i)) { throw new ArgumentException ("One or more characters in the string are prohibited.", "s"); } else { builder.Append (s[i]); } } #if !NETFX_CORE && !COREFX return builder.ToString ().Normalize (NormalizationForm.FormKC); #else return builder.ToString (); #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestCUInt32() { var test = new BooleanBinaryOpTest__TestCUInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestCUInt32 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt32); private const int Op2ElementCount = VectorSize / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private BooleanBinaryOpTest__DataTable<UInt32, UInt32> _dataTable; static BooleanBinaryOpTest__TestCUInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); } public BooleanBinaryOpTest__TestCUInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } _dataTable = new BooleanBinaryOpTest__DataTable<UInt32, UInt32>(_data1, _data2, VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.TestC( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Sse41.TestC( Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Sse41.TestC( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Sse41.TestC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = Sse41.TestC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Sse41.TestC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Sse41.TestC(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanBinaryOpTest__TestCUInt32(); var result = Sse41.TestC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Sse41.TestC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt32> left, Vector128<UInt32> right, bool result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt32[] left, UInt32[] right, bool result, [CallerMemberName] string method = "") { var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((~left[i] & right[i]) == 0); } if (expectedResult != result) { Succeeded = false; Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestC)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
#region Copyright notice and license // 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. #endregion using System.Collections; using System.Collections.Generic; using System.IO; using Google.ProtocolBuffers.Collections; using Google.ProtocolBuffers.Descriptors; namespace Google.ProtocolBuffers { /// <summary> /// Implementation of the non-generic IMessage interface as far as possible. /// </summary> public abstract class AbstractMessage<TMessage, TBuilder> : IMessage<TMessage, TBuilder> where TMessage : AbstractMessage<TMessage, TBuilder> where TBuilder : AbstractBuilder<TMessage, TBuilder> { /// <summary> /// The serialized size if it's already been computed, or null /// if we haven't computed it yet. /// </summary> private int? memoizedSize = null; #region Unimplemented members of IMessage public abstract MessageDescriptor DescriptorForType { get; } public abstract IDictionary<FieldDescriptor, object> AllFields { get; } public abstract bool HasField(FieldDescriptor field); public abstract object this[FieldDescriptor field] { get; } public abstract int GetRepeatedFieldCount(FieldDescriptor field); public abstract object this[FieldDescriptor field, int index] { get; } public abstract UnknownFieldSet UnknownFields { get; } public abstract TMessage DefaultInstanceForType { get; } public abstract TBuilder CreateBuilderForType(); public abstract TBuilder ToBuilder(); #endregion public IBuilder WeakCreateBuilderForType() { return CreateBuilderForType(); } public IBuilder WeakToBuilder() { return ToBuilder(); } public IMessage WeakDefaultInstanceForType { get { return DefaultInstanceForType; } } public virtual bool IsInitialized { get { // Check that all required fields are present. foreach (FieldDescriptor field in DescriptorForType.Fields) { if (field.IsRequired && !HasField(field)) { return false; } } // Check that embedded messages are initialized. foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields) { FieldDescriptor field = entry.Key; if (field.MappedType == MappedType.Message) { if (field.IsRepeated) { // We know it's an IList<T>, but not the exact type - so // IEnumerable is the best we can do. (C# generics aren't covariant yet.) foreach (IMessage element in (IEnumerable) entry.Value) { if (!element.IsInitialized) { return false; } } } else { if (!((IMessage)entry.Value).IsInitialized) { return false; } } } } return true; } } public sealed override string ToString() { return TextFormat.PrintToString(this); } public virtual void WriteTo(CodedOutputStream output) { foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields) { FieldDescriptor field = entry.Key; if (field.IsRepeated) { // We know it's an IList<T>, but not the exact type - so // IEnumerable is the best we can do. (C# generics aren't covariant yet.) IEnumerable valueList = (IEnumerable) entry.Value; if (field.IsPacked) { output.WriteTag(field.FieldNumber, WireFormat.WireType.LengthDelimited); int dataSize = 0; foreach (object element in valueList) { dataSize += CodedOutputStream.ComputeFieldSizeNoTag(field.FieldType, element); } output.WriteRawVarint32((uint)dataSize); foreach (object element in valueList) { output.WriteFieldNoTag(field.FieldType, element); } } else { foreach (object element in valueList) { output.WriteField(field.FieldType, field.FieldNumber, element); } } } else { output.WriteField(field.FieldType, field.FieldNumber, entry.Value); } } UnknownFieldSet unknownFields = UnknownFields; if (DescriptorForType.Options.MessageSetWireFormat) { unknownFields.WriteAsMessageSetTo(output); } else { unknownFields.WriteTo(output); } } public virtual int SerializedSize { get { if (memoizedSize != null) { return memoizedSize.Value; } int size = 0; foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields) { FieldDescriptor field = entry.Key; if (field.IsRepeated) { IEnumerable valueList = (IEnumerable) entry.Value; if (field.IsPacked) { int dataSize = 0; foreach (object element in valueList) { dataSize += CodedOutputStream.ComputeFieldSizeNoTag(field.FieldType, element); } size += dataSize; size += CodedOutputStream.ComputeTagSize(field.FieldNumber); size += CodedOutputStream.ComputeRawVarint32Size((uint)dataSize); } else { foreach (object element in valueList) { size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, element); } } } else { size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, entry.Value); } } UnknownFieldSet unknownFields = UnknownFields; if (DescriptorForType.Options.MessageSetWireFormat) { size += unknownFields.SerializedSizeAsMessageSet; } else { size += unknownFields.SerializedSize; } memoizedSize = size; return size; } } public ByteString ToByteString() { ByteString.CodedBuilder output = new ByteString.CodedBuilder(SerializedSize); WriteTo(output.CodedOutput); return output.Build(); } public byte[] ToByteArray() { byte[] result = new byte[SerializedSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(result); WriteTo(output); output.CheckNoSpaceLeft(); return result; } public void WriteTo(Stream output) { CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output); WriteTo(codedOutput); codedOutput.Flush(); } public void WriteDelimitedTo(Stream output) { CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output); codedOutput.WriteRawVarint32((uint) SerializedSize); WriteTo(codedOutput); codedOutput.Flush(); } public override bool Equals(object other) { if (other == this) { return true; } IMessage otherMessage = other as IMessage; if (otherMessage == null || otherMessage.DescriptorForType != DescriptorForType) { return false; } return Dictionaries.Equals(AllFields, otherMessage.AllFields) && UnknownFields.Equals(otherMessage.UnknownFields); } public override int GetHashCode() { int hash = 41; hash = (19 * hash) + DescriptorForType.GetHashCode(); hash = (53 * hash) + Dictionaries.GetHashCode(AllFields); hash = (29 * hash) + UnknownFields.GetHashCode(); return hash; } } }
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 MediaUpload.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; } } }
/* * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace FlatBuffers.Test { [FlatBuffersTestClass] public class FlatBuffersFuzzTests { private readonly Lcg _lcg = new Lcg(); [FlatBuffersTestMethod] public void TestObjects() { CheckObjects(11, 100); } [FlatBuffersTestMethod] public void TestNumbers() { var builder = new FlatBufferBuilder(1); Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.Data); builder.AddBool(true); Assert.ArrayEqual(new byte[] { 1 }, builder.DataBuffer.Data); builder.AddSbyte(-127); Assert.ArrayEqual(new byte[] { 129, 1 }, builder.DataBuffer.Data); builder.AddByte(255); Assert.ArrayEqual(new byte[] { 0, 255, 129, 1 }, builder.DataBuffer.Data); // First pad builder.AddShort(-32222); Assert.ArrayEqual(new byte[] { 0, 0, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.Data); // Second pad builder.AddUshort(0xFEEE); Assert.ArrayEqual(new byte[] { 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.Data); // no pad builder.AddInt(-53687092); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.Data); // third pad builder.AddUint(0x98765432); Assert.ArrayEqual(new byte[] { 0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.Data); // no pad } [FlatBuffersTestMethod] public void TestNumbers64() { var builder = new FlatBufferBuilder(1); builder.AddUlong(0x1122334455667788); Assert.ArrayEqual(new byte[] { 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 }, builder.DataBuffer.Data); builder = new FlatBufferBuilder(1); builder.AddLong(0x1122334455667788); Assert.ArrayEqual(new byte[] { 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVector_1xUInt8() { var builder = new FlatBufferBuilder(1); builder.StartVector(sizeof(byte), 1, 1); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.Data); builder.AddByte(1); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.Data); builder.EndVector(); Assert.ArrayEqual(new byte[] { 1, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVector_2xUint8() { var builder = new FlatBufferBuilder(1); builder.StartVector(sizeof(byte), 2, 1); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.Data); builder.AddByte(1); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 1, 0, 0 }, builder.DataBuffer.Data); builder.AddByte(2); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 2, 1, 0, 0 }, builder.DataBuffer.Data); builder.EndVector(); Assert.ArrayEqual(new byte[] { 2, 0, 0, 0, 2, 1, 0, 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVector_1xUInt16() { var builder = new FlatBufferBuilder(1); builder.StartVector(sizeof(ushort), 1, 1); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.Data); builder.AddUshort(1); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.Data); builder.EndVector(); Assert.ArrayEqual(new byte[] { 1, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVector_2xUInt16() { var builder = new FlatBufferBuilder(1); builder.StartVector(sizeof(ushort), 2, 1); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.Data); builder.AddUshort(0xABCD); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0xCD, 0xAB }, builder.DataBuffer.Data); builder.AddUshort(0xDCBA); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB }, builder.DataBuffer.Data); builder.EndVector(); Assert.ArrayEqual(new byte[] { 2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestCreateAsciiString() { var builder = new FlatBufferBuilder(1); builder.CreateString("foo"); Assert.ArrayEqual(new byte[] { 3, 0, 0, 0, (byte)'f', (byte)'o', (byte)'o', 0 }, builder.DataBuffer.Data); builder.CreateString("moop"); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // Padding to 32 bytes 4, 0, 0, 0, (byte)'m', (byte)'o', (byte)'o', (byte)'p', 0, 0, 0, 0, // zero terminator with 3 byte pad 3, 0, 0, 0, (byte)'f', (byte)'o', (byte)'o', 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestCreateArbitarytring() { var builder = new FlatBufferBuilder(1); builder.CreateString("\x01\x02\x03"); Assert.ArrayEqual(new byte[] { 3, 0, 0, 0, 0x01, 0x02, 0x03, 0 }, builder.DataBuffer.Data); // No padding builder.CreateString("\x04\x05\x06\x07"); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // Padding to 32 bytes 4, 0, 0, 0, 0x04, 0x05, 0x06, 0x07, 0, 0, 0, 0, // zero terminator with 3 byte pad 3, 0, 0, 0, 0x01, 0x02, 0x03, 0 }, builder.DataBuffer.Data); // No padding } [FlatBuffersTestMethod] public void TestEmptyVTable() { var builder = new FlatBufferBuilder(1); builder.StartObject(0); Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.Data); builder.EndObject(); Assert.ArrayEqual(new byte[] { 4, 0, 4, 0, 4, 0, 0, 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVTableWithOneBool() { var builder = new FlatBufferBuilder(1); builder.StartObject(1); Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.Data); builder.AddBool(0, true, false); builder.EndObject(); Assert.ArrayEqual(new byte[] { 0, 0, // padding to 16 bytes 6, 0, // vtable bytes 8, 0, // object length inc vtable offset 7, 0, // start of bool value 6, 0, 0, 0, // int32 offset for start of vtable 0, 0, 0, // padding 1, // value 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVTableWithOneBool_DefaultValue() { var builder = new FlatBufferBuilder(1); builder.StartObject(1); Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.Data); builder.AddBool(0, false, false); builder.EndObject(); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, // padding to 16 bytes 6, 0, // vtable bytes 4, 0, // end of object from here 0, 0, // entry 0 is empty (default value) 6, 0, 0, 0, // int32 offset for start of vtable }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVTableWithOneInt16() { var builder = new FlatBufferBuilder(1); builder.StartObject(1); Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.Data); builder.AddShort(0, 0x789A, 0); builder.EndObject(); Assert.ArrayEqual(new byte[] { 0, 0, // padding to 16 bytes 6, 0, // vtable bytes 8, 0, // object length inc vtable offset 6, 0, // start of int16 value 6, 0, 0, 0, // int32 offset for start of vtable 0, 0, // padding 0x9A, 0x78, //value 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVTableWithTwoInt16() { var builder = new FlatBufferBuilder(1); builder.StartObject(2); Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.Data); builder.AddShort(0, 0x3456, 0); builder.AddShort(1, 0x789A, 0); builder.EndObject(); Assert.ArrayEqual(new byte[] { 8, 0, // vtable bytes 8, 0, // object length inc vtable offset 6, 0, // start of int16 value 0 4, 0, // start of int16 value 1 8, 0, 0, 0, // int32 offset for start of vtable 0x9A, 0x78, // value 1 0x56, 0x34, // value 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVTableWithInt16AndBool() { var builder = new FlatBufferBuilder(1); builder.StartObject(2); Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.Data); builder.AddShort(0, 0x3456, 0); builder.AddBool(1, true, false); builder.EndObject(); Assert.ArrayEqual(new byte[] { 8, 0, // vtable bytes 8, 0, // object length inc vtable offset 6, 0, // start of int16 value 0 5, 0, // start of bool value 1 8, 0, 0, 0, // int32 offset for start of vtable 0, 1, // padding + value 1 0x56, 0x34, // value 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVTableWithEmptyVector() { var builder = new FlatBufferBuilder(1); builder.StartVector(sizeof(byte), 0, 1); var vecEnd = builder.EndVector(); builder.StartObject(1); builder.AddOffset(0, vecEnd.Value, 0); builder.EndObject(); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // Padding to 32 bytes 6, 0, // vtable bytes 8, 0, // object length inc vtable offset 4, 0, // start of vector offset value 0 6, 0, 0, 0, // int32 offset for start of vtable 4, 0, 0, 0, 0, 0, 0, 0, }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVTableWithEmptyVectorAndScalars() { var builder = new FlatBufferBuilder(1); builder.StartVector(sizeof(byte), 0, 1); var vecEnd = builder.EndVector(); builder.StartObject(2); builder.AddShort(0, 55, 0); builder.AddOffset(1, vecEnd.Value, 0); builder.EndObject(); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, // Padding to 32 bytes 8, 0, // vtable bytes 12, 0, // object length inc vtable offset 10, 0, // offset to int16 value 0 4, 0, // start of vector offset value 1 8, 0, 0, 0, // int32 offset for start of vtable 8, 0, 0, 0, // value 1 0, 0, 55, 0, // value 0 0, 0, 0, 0, // length of vector (not in sctruc) }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVTableWith_1xInt16_and_Vector_or_2xInt16() { var builder = new FlatBufferBuilder(1); builder.StartVector(sizeof(short), 2, 1); builder.AddShort(0x1234); builder.AddShort(0x5678); var vecEnd = builder.EndVector(); builder.StartObject(2); builder.AddOffset(1, vecEnd.Value, 0); builder.AddShort(0, 55, 0); builder.EndObject(); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, // Padding to 32 bytes 8, 0, // vtable bytes 12, 0, // object length 6, 0, // start of value 0 from end of vtable 8, 0, // start of value 1 from end of buffer 8, 0, 0, 0, // int32 offset for start of vtable 0, 0, 55, 0, // padding + value 0 4, 0, 0, 0, // position of vector from here 2, 0, 0, 0, // length of vector 0x78, 0x56, // vector value 0 0x34, 0x12, // vector value 1 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVTableWithAStruct_of_int8_int16_int32() { var builder = new FlatBufferBuilder(1); builder.StartObject(1); builder.Prep(4+4+4, 0); builder.AddSbyte(55); builder.Pad(3); builder.AddShort(0x1234); builder.Pad(2); builder.AddInt(0x12345678); var structStart = builder.Offset; builder.AddStruct(0, structStart, 0); builder.EndObject(); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // Padding to 32 bytes 6, 0, // vtable bytes 16, 0, // object length 4, 0, // start of struct from here 6, 0, 0, 0, // int32 offset for start of vtable 0x78, 0x56, 0x34, 0x12, // struct value 2 0x00, 0x00, 0x34, 0x12, // struct value 1 0x00, 0x00, 0x00, 55, // struct value 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVTableWithAVectorOf_2xStructOf_2xInt8() { var builder = new FlatBufferBuilder(1); builder.StartVector(sizeof(byte)*2, 2, 1); builder.AddByte(33); builder.AddByte(44); builder.AddByte(55); builder.AddByte(66); var vecEnd = builder.EndVector(); builder.StartObject(1); builder.AddOffset(0, vecEnd.Value, 0); builder.EndObject(); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // Padding to 32 bytes 6, 0, // vtable bytes 8, 0, // object length 4, 0, // offset of vector offset 6, 0, 0, 0, // int32 offset for start of vtable 4, 0, 0, 0, // Vector start offset 2, 0, 0, 0, // Vector len 66, // vector 1, 1 55, // vector 1, 0 44, // vector 0, 1 33, // vector 0, 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestVTableWithSomeElements() { var builder = new FlatBufferBuilder(1); builder.StartObject(2); builder.AddByte(0, 33, 0); builder.AddShort(1, 66, 0); var off = builder.EndObject(); builder.Finish(off); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //Padding to 32 bytes 12, 0, 0, 0, // root of table, pointing to vtable offset 8, 0, // vtable bytes 8, 0, // object length 7, 0, // start of value 0 4, 0, // start of value 1 8, 0, 0, 0, // int32 offset for start of vtable 66, 0, // value 1 0, 33, // value 0 }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestTwoFinishTable() { var builder = new FlatBufferBuilder(1); builder.StartObject(2); builder.AddByte(0, 33, 0); builder.AddByte(1, 44, 0); var off0 = builder.EndObject(); builder.Finish(off0); builder.StartObject(3); builder.AddByte(0, 55, 0); builder.AddByte(1, 66, 0); builder.AddByte(2, 77, 0); var off1 = builder.EndObject(); builder.Finish(off1); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // padding to 64 bytes 16, 0, 0, 0, // root of table, pointing to vtable offset (obj1) 0, 0, // padding 10, 0, // vtable bytes 8, 0, // object length 7, 0, // start of value 0 6, 0, // start of value 1 5, 0, // start of value 2 10, 0, 0, 0, // int32 offset for start of vtable 0, // pad 77, // values 2, 1, 0 66, 55, 12, 0, 0, 0, // root of table, pointing to vtable offset (obj0) 8, 0, // vtable bytes 8, 0, // object length 7, 0, // start of value 0 6, 0, // start of value 1 8, 0, 0, 0, // int32 offset for start of vtable 0, 0, // pad 44, // value 1, 0 33, }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestBunchOfBools() { var builder = new FlatBufferBuilder(1); builder.StartObject(8); for (var i = 0; i < 8; i++) { builder.AddBool(i, true, false); } var off = builder.EndObject(); builder.Finish(off); Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // padding to 64 bytes 24, 0, 0, 0, // root of table, pointing to vtable offset (obj0) 20, 0, // vtable bytes 12, 0, // object length 11, 0, // start of value 0 10, 0, // start of value 1 9, 0, // start of value 2 8, 0, // start of value 3 7, 0, // start of value 4 6, 0, // start of value 5 5, 0, // start of value 6 4, 0, // start of value 7 20, 0, 0, 0, // int32 offset for start of vtable 1, 1, 1, 1, // values 1, 1, 1, 1, }, builder.DataBuffer.Data); } [FlatBuffersTestMethod] public void TestWithFloat() { var builder = new FlatBufferBuilder(1); builder.StartObject(1); builder.AddFloat(0, 1, 0); builder.EndObject(); Assert.ArrayEqual(new byte[] { 0, 0, 6, 0, // vtable bytes 8, 0, // object length 4, 0, // start of value 0 6, 0, 0, 0, // int32 offset for start of vtable 0, 0, 128, 63, // value }, builder.DataBuffer.Data); } private void CheckObjects(int fieldCount, int objectCount) { _lcg.Reset(); const int testValuesMax = 11; var builder = new FlatBufferBuilder(1); var objects = new int[objectCount]; for (var i = 0; i < objectCount; ++i) { builder.StartObject(fieldCount); for (var j = 0; j < fieldCount; ++j) { var fieldType = _lcg.Next()%testValuesMax; switch (fieldType) { case 0: { builder.AddBool(j, FuzzTestData.BoolValue, false); break; } case 1: { builder.AddSbyte(j, FuzzTestData.Int8Value, 0); break; } case 2: { builder.AddByte(j, FuzzTestData.UInt8Value, 0); break; } case 3: { builder.AddShort(j, FuzzTestData.Int16Value, 0); break; } case 4: { builder.AddUshort(j, FuzzTestData.UInt16Value, 0); break; } case 5: { builder.AddInt(j, FuzzTestData.Int32Value, 0); break; } case 6: { builder.AddUint(j, FuzzTestData.UInt32Value, 0); break; } case 7: { builder.AddLong(j, FuzzTestData.Int64Value, 0); break; } case 8: { builder.AddUlong(j, FuzzTestData.UInt64Value, 0); break; } case 9: { builder.AddFloat(j, FuzzTestData.Float32Value, 0); break; } case 10: { builder.AddDouble(j, FuzzTestData.Float64Value, 0); break; } default: throw new Exception("Unreachable"); } } var offset = builder.EndObject(); // Store the object offset objects[i] = offset; } _lcg.Reset(); // Test all objects are readable and return expected values... for (var i = 0; i < objectCount; ++i) { var table = new TestTable(builder.DataBuffer, builder.DataBuffer.Length - objects[i]); for (var j = 0; j < fieldCount; ++j) { var fieldType = _lcg.Next() % testValuesMax; var fc = 2 + j; // 2 == VtableMetadataFields var f = fc * 2; switch (fieldType) { case 0: { Assert.AreEqual(FuzzTestData.BoolValue, table.GetSlot(f, false)); break; } case 1: { Assert.AreEqual(FuzzTestData.Int8Value, table.GetSlot(f, (sbyte)0)); break; } case 2: { Assert.AreEqual(FuzzTestData.UInt8Value, table.GetSlot(f, (byte)0)); break; } case 3: { Assert.AreEqual(FuzzTestData.Int16Value, table.GetSlot(f, (short)0)); break; } case 4: { Assert.AreEqual(FuzzTestData.UInt16Value, table.GetSlot(f, (ushort)0)); break; } case 5: { Assert.AreEqual(FuzzTestData.Int32Value, table.GetSlot(f, (int)0)); break; } case 6: { Assert.AreEqual(FuzzTestData.UInt32Value, table.GetSlot(f, (uint)0)); break; } case 7: { Assert.AreEqual(FuzzTestData.Int64Value, table.GetSlot(f, (long)0)); break; } case 8: { Assert.AreEqual(FuzzTestData.UInt64Value, table.GetSlot(f, (ulong)0)); break; } case 9: { Assert.AreEqual(FuzzTestData.Float32Value, table.GetSlot(f, (float)0)); break; } case 10: { Assert.AreEqual(FuzzTestData.Float64Value, table.GetSlot(f, (double)0)); break; } default: throw new Exception("Unreachable"); } } } } } }
// // 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.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.RecoveryServices.Backup; using Microsoft.Azure.Management.RecoveryServices.Backup.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.RecoveryServices.Backup { /// <summary> /// The Resource Manager API includes operations for triggering and /// managing the backups of items protected by your Recovery Services /// Vault. /// </summary> internal partial class BackupOperations : IServiceOperations<RecoveryServicesBackupManagementClient>, IBackupOperations { /// <summary> /// Initializes a new instance of the BackupOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal BackupOperations(RecoveryServicesBackupManagementClient client) { this._client = client; } private RecoveryServicesBackupManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.RecoveryServices.Backup.RecoveryServicesBackupManagementClient. /// </summary> public RecoveryServicesBackupManagementClient Client { get { return this._client; } } /// <summary> /// The Trigger Backup Operation starts an operation in the service /// which triggers the backup of the specified item in the specified /// container in your Recovery Services Vault. This is an asynchronous /// operation. To determine whether the backend service has finished /// processing the request, call Get Protected Item Operation Result /// API. /// </summary> /// <param name='resourceGroupName'> /// Required. Resource group name of your recovery services vault. /// </param> /// <param name='resourceName'> /// Required. Name of your recovery services vault. /// </param> /// <param name='customRequestHeaders'> /// Required. Request header parameters. /// </param> /// <param name='fabricName'> /// Optional. Fabric name of the protected item. /// </param> /// <param name='containerName'> /// Optional. Name of the container where the protected item belongs to. /// </param> /// <param name='protectedItemName'> /// Optional. Name of the protected item which has to be backed up. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Base recovery job response for all the asynchronous operations. /// </returns> public async Task<BaseRecoveryServicesJobResponse> TriggerBackupAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName, string containerName, string protectedItemName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // 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("resourceName", resourceName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); TracingAdapter.Enter(invocationId, this, "TriggerBackupAsync", 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 + "/"; url = url + "vaults"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/backupFabrics/"; if (fabricName != null) { url = url + Uri.EscapeDataString(fabricName); } url = url + "/protectionContainers/"; if (containerName != null) { url = url + Uri.EscapeDataString(containerName); } url = url + "/protectedItems/"; if (protectedItemName != null) { url = url + Uri.EscapeDataString(protectedItemName); } url = url + "/backup"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-05-01"); 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.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); // 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.Accepted) { 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 BaseRecoveryServicesJobResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new BaseRecoveryServicesJobResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); result.Location = locationInstance; } JToken azureAsyncOperationValue = responseDoc["azureAsyncOperation"]; if (azureAsyncOperationValue != null && azureAsyncOperationValue.Type != JTokenType.Null) { string azureAsyncOperationInstance = ((string)azureAsyncOperationValue); result.AzureAsyncOperation = azureAsyncOperationInstance; } JToken retryAfterValue = responseDoc["retryAfter"]; if (retryAfterValue != null && retryAfterValue.Type != JTokenType.Null) { string retryAfterInstance = ((string)retryAfterValue); result.RetryAfter = retryAfterInstance; } JToken statusValue = responseDoc["Status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true)); result.Status = statusInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Headers.Contains("Location")) { result.Location = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy) /// </summary> public static swizzle_hvec2 swizzle(hvec2 v) => v.swizzle; /// <summary> /// Returns an array with all values /// </summary> public static Half[] Values(hvec2 v) => v.Values; /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> public static IEnumerator<Half> GetEnumerator(hvec2 v) => v.GetEnumerator(); /// <summary> /// Returns a string representation of this vector using ', ' as a seperator. /// </summary> public static string ToString(hvec2 v) => v.ToString(); /// <summary> /// Returns a string representation of this vector using a provided seperator. /// </summary> public static string ToString(hvec2 v, string sep) => v.ToString(sep); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format provider for each component. /// </summary> public static string ToString(hvec2 v, string sep, IFormatProvider provider) => v.ToString(sep, provider); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format for each component. /// </summary> public static string ToString(hvec2 v, string sep, string format) => v.ToString(sep, format); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format and format provider for each component. /// </summary> public static string ToString(hvec2 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider); /// <summary> /// Returns the number of components (2). /// </summary> public static int Count(hvec2 v) => v.Count; /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool Equals(hvec2 v, hvec2 rhs) => v.Equals(rhs); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public static bool Equals(hvec2 v, object obj) => v.Equals(obj); /// <summary> /// Returns a hash code for this instance. /// </summary> public static int GetHashCode(hvec2 v) => v.GetHashCode(); /// <summary> /// Returns true iff distance between lhs and rhs is less than or equal to epsilon /// </summary> public static bool ApproxEqual(hvec2 lhs, hvec2 rhs, float eps = 0.1f) => hvec2.ApproxEqual(lhs, rhs, eps); /// <summary> /// Returns a bvec2 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec2 Equal(hvec2 lhs, hvec2 rhs) => hvec2.Equal(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec2 NotEqual(hvec2 lhs, hvec2 rhs) => hvec2.NotEqual(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec2 GreaterThan(hvec2 lhs, hvec2 rhs) => hvec2.GreaterThan(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec2 GreaterThanEqual(hvec2 lhs, hvec2 rhs) => hvec2.GreaterThanEqual(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec2 LesserThan(hvec2 lhs, hvec2 rhs) => hvec2.LesserThan(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec2 LesserThanEqual(hvec2 lhs, hvec2 rhs) => hvec2.LesserThanEqual(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of IsInfinity (Half.IsInfinity(v)). /// </summary> public static bvec2 IsInfinity(hvec2 v) => hvec2.IsInfinity(v); /// <summary> /// Returns a bvec2 from component-wise application of IsFinite (!Half.IsNaN(v) &amp;&amp; !Half.IsInfinity(v)). /// </summary> public static bvec2 IsFinite(hvec2 v) => hvec2.IsFinite(v); /// <summary> /// Returns a bvec2 from component-wise application of IsNaN (Half.IsNaN(v)). /// </summary> public static bvec2 IsNaN(hvec2 v) => hvec2.IsNaN(v); /// <summary> /// Returns a bvec2 from component-wise application of IsNegativeInfinity (Half.IsNegativeInfinity(v)). /// </summary> public static bvec2 IsNegativeInfinity(hvec2 v) => hvec2.IsNegativeInfinity(v); /// <summary> /// Returns a bvec2 from component-wise application of IsPositiveInfinity (Half.IsPositiveInfinity(v)). /// </summary> public static bvec2 IsPositiveInfinity(hvec2 v) => hvec2.IsPositiveInfinity(v); /// <summary> /// Returns a hvec2 from component-wise application of Abs (Half.Abs(v)). /// </summary> public static hvec2 Abs(hvec2 v) => hvec2.Abs(v); /// <summary> /// Returns a hvec2 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v). /// </summary> public static hvec2 HermiteInterpolationOrder3(hvec2 v) => hvec2.HermiteInterpolationOrder3(v); /// <summary> /// Returns a hvec2 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v). /// </summary> public static hvec2 HermiteInterpolationOrder5(hvec2 v) => hvec2.HermiteInterpolationOrder5(v); /// <summary> /// Returns a hvec2 from component-wise application of Sqr (v * v). /// </summary> public static hvec2 Sqr(hvec2 v) => hvec2.Sqr(v); /// <summary> /// Returns a hvec2 from component-wise application of Pow2 (v * v). /// </summary> public static hvec2 Pow2(hvec2 v) => hvec2.Pow2(v); /// <summary> /// Returns a hvec2 from component-wise application of Pow3 (v * v * v). /// </summary> public static hvec2 Pow3(hvec2 v) => hvec2.Pow3(v); /// <summary> /// Returns a hvec2 from component-wise application of Step (v &gt;= Half.Zero ? Half.One : Half.Zero). /// </summary> public static hvec2 Step(hvec2 v) => hvec2.Step(v); /// <summary> /// Returns a hvec2 from component-wise application of Sqrt ((Half)Math.Sqrt((double)v)). /// </summary> public static hvec2 Sqrt(hvec2 v) => hvec2.Sqrt(v); /// <summary> /// Returns a hvec2 from component-wise application of InverseSqrt ((Half)(1.0 / Math.Sqrt((double)v))). /// </summary> public static hvec2 InverseSqrt(hvec2 v) => hvec2.InverseSqrt(v); /// <summary> /// Returns a ivec2 from component-wise application of Sign (Math.Sign(v)). /// </summary> public static ivec2 Sign(hvec2 v) => hvec2.Sign(v); /// <summary> /// Returns a hvec2 from component-wise application of Max (Half.Max(lhs, rhs)). /// </summary> public static hvec2 Max(hvec2 lhs, hvec2 rhs) => hvec2.Max(lhs, rhs); /// <summary> /// Returns a hvec2 from component-wise application of Min (Half.Min(lhs, rhs)). /// </summary> public static hvec2 Min(hvec2 lhs, hvec2 rhs) => hvec2.Min(lhs, rhs); /// <summary> /// Returns a hvec2 from component-wise application of Pow ((Half)Math.Pow((double)lhs, (double)rhs)). /// </summary> public static hvec2 Pow(hvec2 lhs, hvec2 rhs) => hvec2.Pow(lhs, rhs); /// <summary> /// Returns a hvec2 from component-wise application of Log ((Half)Math.Log((double)lhs, (double)rhs)). /// </summary> public static hvec2 Log(hvec2 lhs, hvec2 rhs) => hvec2.Log(lhs, rhs); /// <summary> /// Returns a hvec2 from component-wise application of Clamp (Half.Min(Half.Max(v, min), max)). /// </summary> public static hvec2 Clamp(hvec2 v, hvec2 min, hvec2 max) => hvec2.Clamp(v, min, max); /// <summary> /// Returns a hvec2 from component-wise application of Mix (min * (1-a) + max * a). /// </summary> public static hvec2 Mix(hvec2 min, hvec2 max, hvec2 a) => hvec2.Mix(min, max, a); /// <summary> /// Returns a hvec2 from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static hvec2 Lerp(hvec2 min, hvec2 max, hvec2 a) => hvec2.Lerp(min, max, a); /// <summary> /// Returns a hvec2 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()). /// </summary> public static hvec2 Smoothstep(hvec2 edge0, hvec2 edge1, hvec2 v) => hvec2.Smoothstep(edge0, edge1, v); /// <summary> /// Returns a hvec2 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()). /// </summary> public static hvec2 Smootherstep(hvec2 edge0, hvec2 edge1, hvec2 v) => hvec2.Smootherstep(edge0, edge1, v); /// <summary> /// Returns a hvec2 from component-wise application of Fma (a * b + c). /// </summary> public static hvec2 Fma(hvec2 a, hvec2 b, hvec2 c) => hvec2.Fma(a, b, c); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static hmat2 OuterProduct(hvec2 c, hvec2 r) => hvec2.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static hmat3x2 OuterProduct(hvec2 c, hvec3 r) => hvec2.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static hmat4x2 OuterProduct(hvec2 c, hvec4 r) => hvec2.OuterProduct(c, r); /// <summary> /// Returns a hvec2 from component-wise application of Add (lhs + rhs). /// </summary> public static hvec2 Add(hvec2 lhs, hvec2 rhs) => hvec2.Add(lhs, rhs); /// <summary> /// Returns a hvec2 from component-wise application of Sub (lhs - rhs). /// </summary> public static hvec2 Sub(hvec2 lhs, hvec2 rhs) => hvec2.Sub(lhs, rhs); /// <summary> /// Returns a hvec2 from component-wise application of Mul (lhs * rhs). /// </summary> public static hvec2 Mul(hvec2 lhs, hvec2 rhs) => hvec2.Mul(lhs, rhs); /// <summary> /// Returns a hvec2 from component-wise application of Div (lhs / rhs). /// </summary> public static hvec2 Div(hvec2 lhs, hvec2 rhs) => hvec2.Div(lhs, rhs); /// <summary> /// Returns a hvec2 from component-wise application of Modulo (lhs % rhs). /// </summary> public static hvec2 Modulo(hvec2 lhs, hvec2 rhs) => hvec2.Modulo(lhs, rhs); /// <summary> /// Returns a hvec2 from component-wise application of Degrees (Radians-To-Degrees Conversion). /// </summary> public static hvec2 Degrees(hvec2 v) => hvec2.Degrees(v); /// <summary> /// Returns a hvec2 from component-wise application of Radians (Degrees-To-Radians Conversion). /// </summary> public static hvec2 Radians(hvec2 v) => hvec2.Radians(v); /// <summary> /// Returns a hvec2 from component-wise application of Acos ((Half)Math.Acos((double)v)). /// </summary> public static hvec2 Acos(hvec2 v) => hvec2.Acos(v); /// <summary> /// Returns a hvec2 from component-wise application of Asin ((Half)Math.Asin((double)v)). /// </summary> public static hvec2 Asin(hvec2 v) => hvec2.Asin(v); /// <summary> /// Returns a hvec2 from component-wise application of Atan ((Half)Math.Atan((double)v)). /// </summary> public static hvec2 Atan(hvec2 v) => hvec2.Atan(v); /// <summary> /// Returns a hvec2 from component-wise application of Cos ((Half)Math.Cos((double)v)). /// </summary> public static hvec2 Cos(hvec2 v) => hvec2.Cos(v); /// <summary> /// Returns a hvec2 from component-wise application of Cosh ((Half)Math.Cosh((double)v)). /// </summary> public static hvec2 Cosh(hvec2 v) => hvec2.Cosh(v); /// <summary> /// Returns a hvec2 from component-wise application of Exp ((Half)Math.Exp((double)v)). /// </summary> public static hvec2 Exp(hvec2 v) => hvec2.Exp(v); /// <summary> /// Returns a hvec2 from component-wise application of Log ((Half)Math.Log((double)v)). /// </summary> public static hvec2 Log(hvec2 v) => hvec2.Log(v); /// <summary> /// Returns a hvec2 from component-wise application of Log2 ((Half)Math.Log((double)v, 2)). /// </summary> public static hvec2 Log2(hvec2 v) => hvec2.Log2(v); /// <summary> /// Returns a hvec2 from component-wise application of Log10 ((Half)Math.Log10((double)v)). /// </summary> public static hvec2 Log10(hvec2 v) => hvec2.Log10(v); /// <summary> /// Returns a hvec2 from component-wise application of Floor ((Half)Math.Floor(v)). /// </summary> public static hvec2 Floor(hvec2 v) => hvec2.Floor(v); /// <summary> /// Returns a hvec2 from component-wise application of Ceiling ((Half)Math.Ceiling(v)). /// </summary> public static hvec2 Ceiling(hvec2 v) => hvec2.Ceiling(v); /// <summary> /// Returns a hvec2 from component-wise application of Round ((Half)Math.Round(v)). /// </summary> public static hvec2 Round(hvec2 v) => hvec2.Round(v); /// <summary> /// Returns a hvec2 from component-wise application of Sin ((Half)Math.Sin((double)v)). /// </summary> public static hvec2 Sin(hvec2 v) => hvec2.Sin(v); /// <summary> /// Returns a hvec2 from component-wise application of Sinh ((Half)Math.Sinh((double)v)). /// </summary> public static hvec2 Sinh(hvec2 v) => hvec2.Sinh(v); /// <summary> /// Returns a hvec2 from component-wise application of Tan ((Half)Math.Tan((double)v)). /// </summary> public static hvec2 Tan(hvec2 v) => hvec2.Tan(v); /// <summary> /// Returns a hvec2 from component-wise application of Tanh ((Half)Math.Tanh((double)v)). /// </summary> public static hvec2 Tanh(hvec2 v) => hvec2.Tanh(v); /// <summary> /// Returns a hvec2 from component-wise application of Truncate ((Half)Math.Truncate((double)v)). /// </summary> public static hvec2 Truncate(hvec2 v) => hvec2.Truncate(v); /// <summary> /// Returns a hvec2 from component-wise application of Fract ((Half)(v - Math.Floor(v))). /// </summary> public static hvec2 Fract(hvec2 v) => hvec2.Fract(v); /// <summary> /// Returns a hvec2 from component-wise application of Trunc ((long)(v)). /// </summary> public static hvec2 Trunc(hvec2 v) => hvec2.Trunc(v); /// <summary> /// Returns the minimal component of this vector. /// </summary> public static Half MinElement(hvec2 v) => v.MinElement; /// <summary> /// Returns the maximal component of this vector. /// </summary> public static Half MaxElement(hvec2 v) => v.MaxElement; /// <summary> /// Returns the euclidean length of this vector. /// </summary> public static float Length(hvec2 v) => v.Length; /// <summary> /// Returns the squared euclidean length of this vector. /// </summary> public static float LengthSqr(hvec2 v) => v.LengthSqr; /// <summary> /// Returns the sum of all components. /// </summary> public static Half Sum(hvec2 v) => v.Sum; /// <summary> /// Returns the euclidean norm of this vector. /// </summary> public static float Norm(hvec2 v) => v.Norm; /// <summary> /// Returns the one-norm of this vector. /// </summary> public static float Norm1(hvec2 v) => v.Norm1; /// <summary> /// Returns the two-norm (euclidean length) of this vector. /// </summary> public static float Norm2(hvec2 v) => v.Norm2; /// <summary> /// Returns the max-norm of this vector. /// </summary> public static float NormMax(hvec2 v) => v.NormMax; /// <summary> /// Returns the p-norm of this vector. /// </summary> public static double NormP(hvec2 v, double p) => v.NormP(p); /// <summary> /// Returns a copy of this vector with length one (undefined if this has zero length). /// </summary> public static hvec2 Normalized(hvec2 v) => v.Normalized; /// <summary> /// Returns a copy of this vector with length one (returns zero if length is zero). /// </summary> public static hvec2 NormalizedSafe(hvec2 v) => v.NormalizedSafe; /// <summary> /// Returns the vector angle (atan2(y, x)) in radians. /// </summary> public static double Angle(hvec2 v) => v.Angle; /// <summary> /// Returns a 2D vector that was rotated by a given angle in radians (CAUTION: result is casted and may be truncated). /// </summary> public static hvec2 Rotated(hvec2 v, double angleInRad) => v.Rotated(angleInRad); /// <summary> /// Returns the inner product (dot product, scalar product) of the two vectors. /// </summary> public static Half Dot(hvec2 lhs, hvec2 rhs) => hvec2.Dot(lhs, rhs); /// <summary> /// Returns the euclidean distance between the two vectors. /// </summary> public static float Distance(hvec2 lhs, hvec2 rhs) => hvec2.Distance(lhs, rhs); /// <summary> /// Returns the squared euclidean distance between the two vectors. /// </summary> public static float DistanceSqr(hvec2 lhs, hvec2 rhs) => hvec2.DistanceSqr(lhs, rhs); /// <summary> /// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result). /// </summary> public static hvec2 Reflect(hvec2 I, hvec2 N) => hvec2.Reflect(I, N); /// <summary> /// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result). /// </summary> public static hvec2 Refract(hvec2 I, hvec2 N, Half eta) => hvec2.Refract(I, N, eta); /// <summary> /// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N). /// </summary> public static hvec2 FaceForward(hvec2 N, hvec2 I, hvec2 Nref) => hvec2.FaceForward(N, I, Nref); /// <summary> /// Returns the length of the outer product (cross product, vector product) of the two vectors. /// </summary> public static Half Cross(hvec2 l, hvec2 r) => hvec2.Cross(l, r); /// <summary> /// Returns a hvec2 with independent and identically distributed uniform values between 'minValue' and 'maxValue'. /// </summary> public static hvec2 Random(Random random, hvec2 minValue, hvec2 maxValue) => hvec2.Random(random, minValue, maxValue); /// <summary> /// Returns a hvec2 with independent and identically distributed uniform values between 'minValue' and 'maxValue'. /// </summary> public static hvec2 RandomUniform(Random random, hvec2 minValue, hvec2 maxValue) => hvec2.RandomUniform(random, minValue, maxValue); /// <summary> /// Returns a hvec2 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance. /// </summary> public static hvec2 RandomNormal(Random random, hvec2 mean, hvec2 variance) => hvec2.RandomNormal(random, mean, variance); /// <summary> /// Returns a hvec2 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance. /// </summary> public static hvec2 RandomGaussian(Random random, hvec2 mean, hvec2 variance) => hvec2.RandomGaussian(random, mean, variance); } }
// /* // SharpNative - C# to D Transpiler // (C) 2014 Irio Systems // */ #region Imports using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; #endregion namespace SharpNative.Compiler { public static class RoslynExtensions { public static string GetYieldClassName(this ISymbol symbol) { if(symbol is IMethodSymbol) return "__YieldEnumerator_" + ((IMethodSymbol) symbol).Name; else { return "__YieldEnumerator_" + ((IPropertySymbol)symbol).Name; } } public static string GetAssemblyAnonymousTypesArray(this IAssemblySymbol assembly) { return "_" + assembly.Name + "_AnonymousTypes"; } private static int anonymousTypeNameCounter = 1; private static Dictionary<ITypeSymbol, string> anonymousTypeNames = new Dictionary<ITypeSymbol, string>(); public static string GetTypeName(this ITypeSymbol type) { // var nameOverride = type.GetAttributeValue<string>(Context.Instance.JsAttributeType, "Name"); // if (nameOverride != null) // return nameOverride; if (type.IsAnonymousType) { string name; if (!anonymousTypeNames.TryGetValue(type, out name)) { var index = anonymousTypeNameCounter++; name = type.ContainingAssembly.GetAssemblyAnonymousTypesArray() + "[" + index + "]"; anonymousTypeNames[type] = name; } return name; } var namedTypeSymbol = type as INamedTypeSymbol; if (namedTypeSymbol != null) { var result = GetTypeName(type.GetFullName()).Replace('`', '_'); return result; } else if (type is IArrayTypeSymbol) { var arrayType = (IArrayTypeSymbol)type; return GetTypeName(arrayType.ElementType) + "_1"; } else if (type is ITypeParameterSymbol) { var typeParameter = (ITypeParameterSymbol)type; return typeParameter.Name; } else { throw new Exception(); } } public static string GetTypeName(string typeName) { return typeName;//typeName.Replace(".", "$"); } public static string GetFullName(this TypeInfo typeInfo) { return typeInfo.ConvertedType.GetFullName(); } public static string GetFullName(this INamespaceSymbol namespaceSymbol) { string result = namespaceSymbol.MetadataName; if (!namespaceSymbol.IsGlobalNamespace && !namespaceSymbol.ContainingNamespace.IsGlobalNamespace) result = Context.Instance.SymbolNames[namespaceSymbol.ContainingNamespace, namespaceSymbol.ContainingNamespace.GetFullName()] + "." + result; return result; } public static string GetFullName(this ITypeSymbol type) { if (type.IsAnonymousType) { return type.GetTypeName(); } if (type is IArrayTypeSymbol) { var arrayType = (IArrayTypeSymbol)type; return arrayType.ElementType.GetFullName() + "[]"; } var typeParameter = type as ITypeParameterSymbol; if (typeParameter != null) { return typeParameter.Name; } else { string result = type.MetadataName; if (type.ContainingType != null) result = type.ContainingType.GetFullName() + "." + result; else if (!type.ContainingNamespace.IsGlobalNamespace) result = type.ContainingNamespace.GetFullName() + "." + result; return result; } } public static string GetCSharpName(this MemberDeclarationSyntax member) { var method = member as MethodDeclarationSyntax; var field = member as FieldDeclarationSyntax; var property = member as PropertyDeclarationSyntax; var _eventField = member as EventFieldDeclarationSyntax; var _event = member as EventDeclarationSyntax; var _operator = member as OperatorDeclarationSyntax; var _convoperator = member as ConversionOperatorDeclarationSyntax; var indexer = member as IndexerDeclarationSyntax; var destructor = member as DestructorDeclarationSyntax; var constructor = member as ConstructorDeclarationSyntax; //TODO: might have to add support for parameters if (method != null) { return WriteIdentifierName.TransformIdentifier(method.Identifier.Text); } if (field != null) { return field.Declaration.Variables.Select(j=> WriteIdentifierName.TransformIdentifier(j.Identifier.Text)).Aggregate((a,b)=>a+","+b); } if (property != null) { return WriteIdentifierName.TransformIdentifier(property.Identifier.Text); } if (_eventField != null) { return _eventField.Declaration.Variables.Select(j => WriteIdentifierName.TransformIdentifier(j.Identifier.Text)).Aggregate((a, b) => a + "," + b); } if (_event != null) { return WriteIdentifierName.TransformIdentifier(_event.Identifier.Text); } if (_operator != null) { return "operator"+_operator.OperatorToken; } if (_convoperator != null) { return "operator"; } if (indexer != null) { return ("[]"); } if (destructor != null) { return "~this()"; //destructor.Identifier.Text; } if (constructor != null) { return "this()"; //destructor.Identifier.Text; } throw new NotImplementedException(member.ToFullString()); } public static bool IsSubclassOf(this ITypeSymbol type, ITypeSymbol baseTypeSymbol) { if (type == null || type.BaseType == null) return false; if (type.BaseType == baseTypeSymbol || type.AllInterfaces.Contains(baseTypeSymbol)) return true; return IsSubclassOf(type.BaseType, baseTypeSymbol); } // // public static string GetFullName(this INamespaceSymbol namespaceSymbol) // { // string result = namespaceSymbol.MetadataName; // if (!namespaceSymbol.IsGlobalNamespace && !namespaceSymbol.ContainingNamespace.IsGlobalNamespace) // { // result = // Context.Instance.SymbolNames[ // namespaceSymbol.ContainingNamespace, namespaceSymbol.ContainingNamespace.GetFullName()] + "." + // result; // } // return result; // } public static bool IsAssignableFrom(this ITypeSymbol baseType, ITypeSymbol type) { if (IsImplicitNumericCast(baseType, type)) return true; var current = type; while (current != null) { if (Equals(current, baseType)) return true; current = current.BaseType; } foreach (var intf in type.AllInterfaces) { if (Equals(intf, baseType)) return true; } return false; } private static bool IsImplicitNumericCast(ITypeSymbol baseType, ITypeSymbol type) { if (type.SpecialType == SpecialType.System_SByte) { switch (baseType.SpecialType) { case SpecialType.System_SByte: // Safety precaution? case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Char) { switch (baseType.SpecialType) { case SpecialType.System_Char: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Byte) { switch (baseType.SpecialType) { case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Int16) { switch (baseType.SpecialType) { case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_UInt16) { switch (baseType.SpecialType) { case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Int32) { switch (baseType.SpecialType) { case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_UInt32) { switch (baseType.SpecialType) { case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Int64) { switch (baseType.SpecialType) { case SpecialType.System_Int64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Single) { switch (baseType.SpecialType) { case SpecialType.System_Single: case SpecialType.System_Double: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_UInt64) { switch (baseType.SpecialType) { case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } return false; } public static ITypeSymbol GetGenericArgument(this ITypeSymbol type, ITypeSymbol unconstructedType, int argumentIndex) { var current = type; while (current != null) { if (Equals(current.OriginalDefinition, unconstructedType)) return ((INamedTypeSymbol)current).TypeArguments[argumentIndex]; current = current.BaseType; } if (type is INamedTypeSymbol) { var namedTypeSymbol = (INamedTypeSymbol)type; foreach (var intf in namedTypeSymbol.AllInterfaces) { if (Equals(intf.OriginalDefinition, unconstructedType)) return intf.TypeArguments[argumentIndex]; } } return null; } public static T GetAttributeValue<T>(this ISymbol type, INamedTypeSymbol attributeType, string propertyName, T defaultValue = default(T)) { var jsAttribute = type.GetAttributes().SingleOrDefault(x => Equals(x.AttributeClass, attributeType)); if (jsAttribute != null) { // If the type is inlined, all the methods of the class will be written // at the same (root) level as the class declaration would have. This is useful // for creating Javascript-Global functions. var isInlinedArgument = jsAttribute.NamedArguments.SingleOrDefault(x => x.Key == propertyName); if (isInlinedArgument.Value.Value != null) return (T)isInlinedArgument.Value.Value; } return defaultValue; } public static ISymbol[] GetAllMembers(this INamedTypeSymbol type, string name) { if (type.BaseType != null) return type.BaseType.GetAllMembers(name).Concat(type.GetMembers(name).ToArray()).ToArray(); return type.GetMembers(name).ToArray(); } public static ISymbol[] GetAllMembers(this INamedTypeSymbol type) { if (type.BaseType != null) return type.BaseType.GetAllMembers().Concat(type.GetMembers().ToArray()).ToArray(); return type.GetMembers().ToArray(); } public static ITypeSymbol GetContainingType(this SyntaxNode node) { var classDeclaration = node.FirstAncestorOrSelf<ClassDeclarationSyntax>(x => true); if (classDeclaration == null) return null; return (ITypeSymbol)ModelExtensions.GetDeclaredSymbol(Context.Compilation.GetSemanticModel(classDeclaration.SyntaxTree), classDeclaration); } public static IMethodSymbol GetContainingMethod(this SyntaxNode node) { var method = node.FirstAncestorOrSelf<SyntaxNode>( x => x is ConstructorDeclarationSyntax || x is MethodDeclarationSyntax); if (method == null) return null; if (method is ConstructorDeclarationSyntax) { return (IMethodSymbol)ModelExtensions.GetDeclaredSymbol(Context.Compilation.GetSemanticModel(method.SyntaxTree), (ConstructorDeclarationSyntax)method); } return (IMethodSymbol)ModelExtensions.GetDeclaredSymbol(Context.Compilation.GetSemanticModel(method.SyntaxTree), (MethodDeclarationSyntax)method); } public static IMethodSymbol GetRootOverride(this IMethodSymbol method) { if (method.OverriddenMethod == null) return method; return method.OverriddenMethod.GetRootOverride(); } public static IPropertySymbol GetRootOverride(this IPropertySymbol property) { if (property.OverriddenProperty == null) return property; return property.OverriddenProperty.GetRootOverride(); } public static bool HasOrIsEnclosedInGenericParameters(this INamedTypeSymbol type) { return type.TypeParameters.Any() || (type.ContainingType != null && type.ContainingType.HasOrIsEnclosedInGenericParameters()); } /* public static bool HasOrIsEnclosedInUnconstructedType(this NamedTypeSymbol type) { return (type.TypeParameters.Count > 0 && type.TypeArguments.Any(x => IsUnconstructedType(x))) || (type.ContainingType != null && type.ContainingType.HasOrIsEnclosedInGenericParameters()); } */ public static bool IsUnconstructedType(this ITypeSymbol type) { var namedTypeSymbol = type as INamedTypeSymbol; if (type is ITypeParameterSymbol) return true; if (namedTypeSymbol != null) { return (namedTypeSymbol.TypeParameters.Any() && namedTypeSymbol.TypeArguments.Any(x => IsUnconstructedType(x))) || (type.ContainingType != null && type.ContainingType.IsUnconstructedType()); } return false; // namedTypeSymbol.ConstructedFrom.ToString() != namedTypeSymbol.ToString() && namedTypeSymbol.ConstructedFrom.ConstructedFrom.ToString() == namedTypeSymbol.ConstructedFrom.ToString() && namedTypeSymbol.HasOrIsEnclosedInGenericParameters() } public static ParameterSyntax[] GetParameters(this ExpressionSyntax lambda) { if (lambda is SimpleLambdaExpressionSyntax) return new[] { ((SimpleLambdaExpressionSyntax)lambda).Parameter }; if (lambda is ParenthesizedLambdaExpressionSyntax) return ((ParenthesizedLambdaExpressionSyntax)lambda).ParameterList.Parameters.ToArray(); throw new Exception(); } public static CSharpSyntaxNode GetBody(this ExpressionSyntax lambda) { if (lambda is SimpleLambdaExpressionSyntax) return ((SimpleLambdaExpressionSyntax)lambda).Body; if (lambda is ParenthesizedLambdaExpressionSyntax) return ((ParenthesizedLambdaExpressionSyntax)lambda).Body; throw new Exception(); } /* public static bool IsAssignment(this SyntaxKind type) { switch (type) { case SyntaxKind.AssignExpression: case SyntaxKind.AddAssignExpression: case SyntaxKind.AndAssignExpression: case SyntaxKind.DivideAssignExpression: case SyntaxKind.ExclusiveOrAssignExpression: case SyntaxKind.LeftShiftAssignExpression: case SyntaxKind.RightShiftAssignExpression: case SyntaxKind.ModuloAssignExpression: case SyntaxKind.MultiplyAssignExpression: case SyntaxKind.OrAssignExpression: case SyntaxKind.SubtractAssignExpression: return true; default: return false; } } */ public static StatementSyntax GetNextStatement(this StatementSyntax statement) { if (statement.Parent is BlockSyntax) { var block = (BlockSyntax)statement.Parent; var indexOfStatement = block.Statements.IndexOf(statement); if (indexOfStatement == -1) throw new Exception(); if (indexOfStatement < block.Statements.Count - 1) return block.Statements[indexOfStatement + 1]; return null; } if (statement.Parent is SwitchSectionSyntax) { var section = (SwitchSectionSyntax)statement.Parent; var indexOfStatement = section.Statements.IndexOf(statement); if (indexOfStatement == -1) throw new Exception(); if (indexOfStatement < section.Statements.Count - 1) return section.Statements[indexOfStatement + 1]; return null; } return null; } public static IMethodSymbol GetMethodByName(this INamedTypeSymbol type, string name) { return type.GetMembers(name).OfType<IMethodSymbol>().Single(); } public static IMethodSymbol GetMethod(this INamedTypeSymbol type, string name, params ITypeSymbol[] parameterTypes) { IMethodSymbol method; if (!TryGetMethod(type, name, out method, parameterTypes)) throw new Exception(); return method; } public static bool TryGetMethod(this INamedTypeSymbol type, string name, out IMethodSymbol method, params ITypeSymbol[] parameterTypes) { var candidates = type.GetMembers(name).OfType<IMethodSymbol>().ToArray(); if (candidates.Length == 1) { method = candidates[0]; return true; } foreach (var candidate in candidates) { if (candidate.Parameters.Count() != parameterTypes.Length) continue; bool valid = true; foreach ( var item in parameterTypes.Zip(candidate.Parameters.Select(x => x.Type), (x, y) => new {ParameterType = x, Candidate = y})) { if (!Equals(item.Candidate, item.ParameterType)) { valid = false; break; } } if (valid) { method = candidate; return true; } } method = null; return false; } public static TypeSyntax ToTypeSyntax(this ITypeSymbol symbol) { return SyntaxFactory.ParseTypeName(symbol.ToDisplayString()); } public static InvocationExpressionSyntax Invoke(this IMethodSymbol method, params ExpressionSyntax[] arguments) { var methodTarget = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, method.ContainingType.ToTypeSyntax(), SyntaxFactory.IdentifierName(method.Name)); return arguments.Any() ? SyntaxFactory.InvocationExpression(methodTarget, SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList(arguments.Select(x => SyntaxFactory.Argument(x)), arguments.Skip(1).Select(_ => SyntaxFactory.Token(SyntaxKind.CommaToken))))) : SyntaxFactory.InvocationExpression(methodTarget); } public static bool IsTrue(this ExpressionSyntax expression) { var literal = (LiteralExpressionSyntax)expression; return literal.Token.IsKind(SyntaxKind.TrueKeyword); } public static Compilation Recompile(this Compilation compilation, CompilationUnitSyntax compilationUnit) { var document = Context.Instance.Project.GetDocument(compilationUnit.SyntaxTree); document = document.WithSyntaxRoot(compilationUnit); SyntaxTree syntaxTree; document.TryGetSyntaxTree(out syntaxTree); compilation = compilation.ReplaceSyntaxTree(compilationUnit.SyntaxTree, syntaxTree); return compilation; } public static Compilation Recompile(this Compilation compilation, SyntaxNode oldNode, SyntaxNode newNode) { while (oldNode != null) { var oldParent = oldNode.Parent; var newParent = oldParent.ReplaceNode(oldNode, newNode); oldNode = oldParent; newNode = newParent; if (oldNode is CompilationUnitSyntax) break; } return compilation.Recompile((CompilationUnitSyntax)newNode); } public static INamedTypeSymbol FindType(this Compilation compilation, string fullName) { var result = compilation.GetTypeByMetadataName(fullName); if (result == null) { foreach ( var assembly in Context.Instance.Project.MetadataReferences.Select(compilation.GetAssemblyOrModuleSymbol) .Cast<IAssemblySymbol>()) { result = assembly.GetTypeByMetadataName(fullName); if (result != null) break; } } return result; } public static IEnumerable<ITypeSymbol> GetAllInnerTypes(this ITypeSymbol type) { foreach (var innerType in type.GetMembers().OfType<ITypeSymbol>()) { yield return innerType; foreach (var inner in innerType.GetAllInnerTypes()) yield return inner; } } public static string GetDetails(this SyntaxNode node) { var fileName = node.SyntaxTree.FilePath; var text = node.SyntaxTree.GetText(); var span = node.GetLocation().SourceSpan; var startLine = text.Lines.GetLinePosition(span.Start); var endLine = text.Lines.GetLinePosition(span.End); return String.Format("{0} (Line {1}:{2}, Line {3}:{4}) node: {5}, Type: {6}", fileName, startLine.Line + 1, startLine.Character + 1, endLine.Line + 1, endLine.Character + 1, node.ToFullString(), node.GetType().Name); } public static bool IsPrimitive(this ITypeSymbol type) { if (type == null) return false; switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Decimal: case SpecialType.System_Double: case SpecialType.System_Enum: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Nullable_T: case SpecialType.System_SByte: case SpecialType.System_Single: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_Void: case SpecialType.System_String: return true; default: return false; } } public static bool IsPrimitiveInteger(this ITypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Decimal: case SpecialType.System_Double: case SpecialType.System_Enum: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_SByte: case SpecialType.System_Single: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: return true; default: return false; } } public static bool IsAsync(this MemberDeclarationSyntax method) { if(method is MethodDeclarationSyntax) return (method as MethodDeclarationSyntax).Modifiers.Any(x => x.IsKind(SyntaxKind.AsyncKeyword)); else if(method is PropertyDeclarationSyntax) { return (method as PropertyDeclarationSyntax).Modifiers.Any(x => x.IsKind(SyntaxKind.AsyncKeyword)); } return false; } public static bool IsPointer(this ITypeSymbol type) { return type != null && type.IsValueType; } } }
//! \file ArcMGPK.cs //! \date Mon Nov 03 20:03:36 2014 //! \brief MGPK archive format. // // Copyright (C) 2014 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Text; namespace GameRes.Formats.Mg { [Export(typeof(ArchiveFormat))] public class MgpkOpener : ArchiveFormat { public override string Tag { get { return "MGPK"; } } public override string Description { get { return "MG resource archive"; } } public override uint Signature { get { return 0x4b50474d; } } // MGPK public override bool IsHierarchic { get { return false; } } public override bool CanCreate { get { return false; } } public override ArcFile TryOpen (ArcView file) { uint count = file.View.ReadUInt32 (8); if (count > 0xffffff) return null; long cur_offset = 0x0c; var dir = new List<Entry> ((int)count); for (uint i = 0; i < count; ++i) { uint name_length = file.View.ReadByte (cur_offset); string name = file.View.ReadString (cur_offset+1, name_length, Encoding.UTF8); var entry = FormatCatalog.Instance.Create<Entry> (name); entry.Offset = file.View.ReadUInt32 (cur_offset+0x20); entry.Size = file.View.ReadUInt32 (cur_offset+0x24); if (!entry.CheckPlacement (file.MaxOffset)) return null; dir.Add (entry); cur_offset += 0x30; } return new ArcFile (file, this, dir); } public override Stream OpenEntry (ArcFile arc, Entry entry) { Stream input = arc.File.CreateStream (entry.Offset, entry.Size); string ext = Path.GetExtension (entry.Name).ToLowerInvariant(); if (".png" == ext) { byte[] data = new byte[entry.Size]; input.Read (data, 0, data.Length); input.Dispose(); DecryptBlock (data); return new MemoryStream (data, false); } else if (".txt" == ext) { byte[] data = new byte[entry.Size]; input.Read (data, 0, data.Length); input.Dispose(); DecryptBlock (data); return DecompressStream (data); } else return input; } public static readonly byte[] Key = new byte[] { 229, 101, 186, 26, 61, 198, 127, 158, 70, 21, 137 }; private byte[] DecryptBlock (byte[] input) { byte[] key = (byte[])Key.Clone(); for (int i = 0; i < input.Length; i++) { input[i] ^= key[i % key.Length]; key[i % key.Length] += 27; } return input; } private Stream DecompressStream (byte[] input) { int num = input.Length * 2; byte[] src = new byte[num]; int num2; for (num2 = lzf_decompress (input, ref src); num2 == 0; num2 = lzf_decompress (input, ref src)) { num *= 2; src = new byte[num]; } return new MemoryStream (src, 0, num2, false); } private static int lzf_decompress (byte[] input, ref byte[] output) { int num = input.Length; int num2 = output.Length; uint num3 = 0u; uint num4 = 0u; do { uint num5 = (uint)input[(int)((UIntPtr)(num3++))]; if (num5 < 32u) { num5 += 1u; if ((ulong)(num4 + num5) > (ulong)((long)num2)) { return 0; } do { output[(int)((UIntPtr)(num4++))] = input[(int)((UIntPtr)(num3++))]; } while (--num5 != 0u); } else { uint num6 = num5 >> 5; int num7 = (int)(num4 - ((num5 & 31u) << 8) - 1u); if (num6 == 7u) { num6 += (uint)input[(int)((UIntPtr)(num3++))]; } num7 -= (int)input[(int)((UIntPtr)(num3++))]; if ((ulong)(num4 + num6 + 2u) > (ulong)((long)num2)) { return 0; } if (num7 < 0) { return 0; } output[(int)((UIntPtr)(num4++))] = output[num7++]; output[(int)((UIntPtr)(num4++))] = output[num7++]; do { output[(int)((UIntPtr)(num4++))] = output[num7++]; } while (--num6 != 0u); } } while ((ulong)num3 < (ulong)((long)num)); return (int)num4; } private static readonly uint uint_0 = 14u; private static readonly uint uint_1 = 16384u; private static readonly uint uint_2 = 32u; private static readonly uint uint_3 = 8192u; private static readonly uint uint_4 = 264u; private static readonly long[] long_0 = new long[uint_1]; private static int lzf_compress (byte[] input, ref byte[] output) { int num = input.Length; int num2 = output.Length; Array.Clear (long_0, 0, (int)uint_1); uint num3 = 0u; uint num4 = 0u; uint num5 = (uint)((int)input[(int)((UIntPtr)0)] << 8 | (int)input[(int)((UIntPtr)(0 + 1))]); int num6 = 0; while (true) { if ((ulong)num3 < (ulong)((long)(num - 2))) { num5 = (num5 << 8 | (uint)input[(int)((UIntPtr)(num3 + 2u))]); long num7 = (long)((ulong)((num5 ^ num5 << 5) >> (int)(24u - uint_0 - num5 * 5u) & uint_1 - 1u)); long num8 = long_0[(int)checked((IntPtr)num7)]; long_0[(int)checked((IntPtr)num7)] = (long)((ulong)num3); long num9; if ((num9 = (long)((ulong)num3 - (ulong)num8 - 1uL)) < (long)((ulong)uint_3) && (ulong)(num3 + 4u) < (ulong)((long)num) && num8 > 0L && input[(int)checked((IntPtr)num8)] == input[(int)((UIntPtr)num3)] && input[(int)checked((IntPtr)unchecked(num8 + 1L))] == input[(int)((UIntPtr)(num3 + 1u))] && input[(int)checked((IntPtr)unchecked(num8 + 2L))] == input[(int)((UIntPtr)(num3 + 2u))]) { uint num10 = 2u; uint num11 = (uint)(num - (int)num3 - 2); num11 = ((num11 <= uint_4) ? num11 : uint_4); if ((ulong)num4 + (ulong)((long)num6) + 1uL + 3uL >= (ulong)((long)num2)) { return 0; } do { num10 += 1u; if (num10 >= num11) { break; } } while (input[(int)checked((IntPtr)unchecked(num8 + (long)((ulong)num10)))] == input[(int)((UIntPtr)(num3 + num10))]); // IL_199: if (num6 != 0) { output[(int)((UIntPtr)(num4++))] = (byte)(num6 - 1); num6 = -num6; do { output[(int)((UIntPtr)(num4++))] = input[(int)checked((IntPtr)unchecked((ulong)num3 + (ulong)((long)num6)))]; } while (++num6 != 0); } num10 -= 2u; num3 += 1u; if (num10 < 7u) { output[(int)((UIntPtr)(num4++))] = (byte)((num9 >> 8) + (long)((ulong)((ulong)num10 << 5))); } else { output[(int)((UIntPtr)(num4++))] = (byte)((num9 >> 8) + 224L); output[(int)((UIntPtr)(num4++))] = (byte)(num10 - 7u); } output[(int)((UIntPtr)(num4++))] = (byte)num9; num3 += num10 - 1u; num5 = (uint)((int)input[(int)((UIntPtr)num3)] << 8 | (int)input[(int)((UIntPtr)(num3 + 1u))]); num5 = (num5 << 8 | (uint)input[(int)((UIntPtr)(num3 + 2u))]); long_0[(int)((UIntPtr)((num5 ^ num5 << 5) >> (int)(24u - uint_0 - num5 * 5u) & uint_1 - 1u))] = (long)((ulong)num3); num3 += 1u; num5 = (num5 << 8 | (uint)input[(int)((UIntPtr)(num3 + 2u))]); long_0[(int)((UIntPtr)((num5 ^ num5 << 5) >> (int)(24u - uint_0 - num5 * 5u) & uint_1 - 1u))] = (long)((ulong)num3); num3 += 1u; continue; // goto IL_199; } } else { if ((ulong)num3 == (ulong)((long)num)) { break; } } num6++; num3 += 1u; if ((long)num6 == (long)((ulong)uint_2)) { if ((ulong)(num4 + 1u + uint_2) >= (ulong)((long)num2)) { return 0; } output[(int)((UIntPtr)(num4++))] = (byte)(uint_2 - 1u); num6 = -num6; do { output[(int)((UIntPtr)(num4++))] = input[(int)checked((IntPtr)unchecked((ulong)num3 + (ulong)((long)num6)))]; } while (++num6 != 0); } } if (num6 != 0) { if ((ulong)num4 + (ulong)((long)num6) + 1uL >= (ulong)((long)num2)) { return 0; } output[(int)((UIntPtr)(num4++))] = (byte)(num6 - 1); num6 = -num6; do { output[(int)((UIntPtr)(num4++))] = input[(int)checked((IntPtr)unchecked((ulong)num3 + (ulong)((long)num6)))]; } while (++num6 != 0); } return (int)num4; } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.Gui; using FlatRedBall.Input; #if FRB_MDX using Keys = Microsoft.DirectX.DirectInput.Key; #else using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Graphics; #endif namespace EditorObjects.Gui { public class ToolsWindow : CollapseWindow { #region Enums public enum ToolsButton { Attach, Copy, Detach, Move, Play, Rotate, Scale, Stop, Rewind } #endregion #region Fields float mNumberOfRows = 3; float mChildrenButtonScale = 1.3f; float mBorderWidth = .5f; WindowArray mButtons = new WindowArray(); // This dicationary holds elements which have keyboard keys associated with them Dictionary<Keys, Button> mShortcutAssociation = new Dictionary<Keys, Button>(); #endregion #region Properties public float ExtraSpacingBetweenSameRowButtons { get; set; } public float NumberOfRows { get { return mNumberOfRows; } set { mNumberOfRows = value; UpdateDimensions(); } } #region XML Docs /// <summary> /// Controls the distance from the edge of the ToolWindow to the edge of Buttons. /// </summary> #endregion public float BorderWidth { get { return mBorderWidth; } set { // Right now this needs to be set before buttons are added - but we could potentially // reposition all buttons when this value is set if we want to allow users to change this // after buttons are positioned. mBorderWidth = value; } } #endregion #region Methods #region Constructor #region XML Docs /// <summary> /// Creates a new ToolsWindow and adds it to the GuiManager. /// </summary> #endregion public ToolsWindow() : base(GuiManager.Cursor) { GuiManager.AddWindow(this); base.mName = "Tools"; UpdateDimensions(); this.X = SpriteManager.Camera.XEdge * 2 - this.ScaleX; } #endregion #region Public Methods public Button AddButton() { Button button = new Button(mCursor); AddWindow(button); button.ScaleX = button.ScaleY = mChildrenButtonScale; SetPositionForNewUIElement(button); mButtons.Add(button); UpdateDimensions(); return button; } public Button AddButton(Keys shortcutKey) { Button button = this.AddButton(); mShortcutAssociation.Add(shortcutKey, button); return button; } public Button AddButton(ToolsButton toolsButton) { // since MDX doesn't have the .None enum for Key, code duplication is happening: Button button = this.AddButton(); int row, column; string text; GetRowAndColumnFor(toolsButton, out row, out column, out text); button.Text = text; button.SetOverlayTextures(column, row); return button; } public Button AddButton(ToolsButton toolsButton, Keys shortcutKey) { Button button = button = this.AddButton(toolsButton); #if FRB_XNA if (shortcutKey != Keys.None) #endif { mShortcutAssociation.Add(shortcutKey, button); } return button; } public ToggleButton AddToggleButton() { ToggleButton toggleButton = new ToggleButton(mCursor); AddWindow(toggleButton); toggleButton.ScaleX = toggleButton.ScaleY = mChildrenButtonScale; SetPositionForNewUIElement(toggleButton); mButtons.Add(toggleButton); UpdateDimensions(); return toggleButton; } public ToggleButton AddToggleButton(string textureToUse, string contentManagerName) { ToggleButton button = this.AddToggleButton(); Texture2D newTexture = FlatRedBallServices.Load<Texture2D>(textureToUse, contentManagerName); button.SetOverlayTextures( newTexture, newTexture); return button; } public ToggleButton AddToggleButton(Keys shortcutKey) { ToggleButton button = this.AddToggleButton(); mShortcutAssociation.Add(shortcutKey, button); return button; } public ToggleButton AddToggleButton(ToolsButton toolsButton) { // since MDX doesn't have the .None enum for Key, code duplication is happening: ToggleButton button = this.AddToggleButton(); int row, column; string text; GetRowAndColumnFor(toolsButton, out row, out column, out text); button.Text = text; button.SetOverlayTextures(column, row); return button; } public ToggleButton AddToggleButton(ToolsButton toolsButton, Keys shortcutKey) { ToggleButton button = this.AddToggleButton(toolsButton); #if FRB_XNA if (shortcutKey != Keys.None) #endif { mShortcutAssociation.Add(shortcutKey, button); } return button; } public void ListenForShortcuts() { foreach (KeyValuePair<Keys, Button> kvp in mShortcutAssociation) { if (InputManager.Keyboard.KeyPushedConsideringInputReceiver(kvp.Key)) { kvp.Value.Press(); } } } #endregion #region Private Methods private void GetRowAndColumnFor(ToolsButton toolsButton, out int row, out int column, out string buttonText) { switch (toolsButton) { case ToolsButton.Move: row = 0; column = 2; buttonText = "Move"; break; case ToolsButton.Rotate: row = 0; column = 0; buttonText = "Rotate"; break; case ToolsButton.Scale: row = 0; column = 1; buttonText = "Scale"; break; case ToolsButton.Attach: row = 0; column = 7; buttonText = "Attach"; break; case ToolsButton.Detach: row = 0; column = 10; buttonText = "Detach"; break; case ToolsButton.Copy: row = 0; column = 9; buttonText = "Duplicate"; break; case ToolsButton.Play: row = 1; column = 9; buttonText = "Play"; break; case ToolsButton.Stop: row = 1; column = 11; buttonText = "Stop"; break; case ToolsButton.Rewind: row = 1; column = 10; buttonText = "Rewind"; break; default: row = 0; column = 0; buttonText = ""; break; } } private void SetPositionForNewUIElement(Window window) { float x = mBorderWidth + mChildrenButtonScale; float y = mBorderWidth + mChildrenButtonScale; // If there are already buttons here then place the new button appropriately if (mButtons.Count != 0) { if (mButtons[mButtons.Count - 1].X > 2 * ScaleX - mBorderWidth - mChildrenButtonScale * 2) { // Place the new button on a new row y = mButtons[mButtons.Count - 1].Y + 2 * mChildrenButtonScale; } else { // place the button on the same row, column to the right x = mButtons[mButtons.Count - 1].X + 2 * mChildrenButtonScale + ExtraSpacingBetweenSameRowButtons; y = mButtons[mButtons.Count - 1].Y; } } window.X = x; window.Y = y; } private void UpdateDimensions() { float bottomY = 0; float largestScaleY = 0; foreach (Window window in mChildren) { bottomY = Math.Max(bottomY, window.Y); largestScaleY = Math.Max(largestScaleY, window.ScaleY); } SetScaleTL(mBorderWidth + mChildrenButtonScale * mNumberOfRows + (ExtraSpacingBetweenSameRowButtons * (mNumberOfRows - 1)), (bottomY + largestScaleY + mBorderWidth) / 2.0f); //this.MinimumScaleX = ScaleX; //this.MinimumScaleY = ScaleY; // mScaleY = (bottomY + largestScaleY + mBorderWidth) / 2.0f; } #endregion #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /* State Template * // IDLE STATE bool enterIDLE () { return true; } bool updateIDLE () { float x = Input.GetAxisRaw("Horizontal"); if(x != 0) stateMachine.ChangeState(enterWALK, updateWALK, exitWALK); return false; } bool exitIDLE () { return true; } */ /* * Lovingly copy-pasted from: * https://gist.github.com/SteveSwink/5120612 * Credit goes to Steve Swink and Mike Stevenson * Changes have been made from there */ // Defines the required parameters and return value type for a StateMachine state. // Returns a bool representing whether or not the state has finished running. public delegate bool StateDelegate (); // To use, create an instance of StateMachine inside of a MonoBehaviour, load it up with // references to state methods with ChangeState(), then call its Execute() method during the // MonoBehaviour's Update cycle. An example MonoBehaviour is included at the bottom of this file. public class StateMachine { // Keep track of the currently running state enum MState { None, Entering, Updating, Exiting } MState mState = MState.None; // List<State> stateList = new List<State>(); // Hashtable<int, State> stateList = new Hashtable<int, State>(); Dictionary<int, State> stateList = new Dictionary<int, State>(); // IDictionary<int, State> stateList = new IDictionary<int, State>(); // These states will be cached when calling ChangeState(). They'll be copied into // currentStateMethod in succession as each state finishes running. The Execute() // method will execute currentStateMethod on each update, running whatever method // is stored there. StateDelegate enter; StateDelegate update; StateDelegate exit; // After being called by the Execute() method, the current state will be replaced with // the next most appropriate state if the current state returns 'true', signifying that // it has finished running. StateDelegate currentStateMethod; // This controls whether or not the state machine will immediately exit the previous state and // enter the new state upon a change state call public bool immediateMode = true; public void AddState(State newState){ stateList.Add(newState.key, newState); } // A single state may be stored at any given time. If you need to queue more than // one state, you could conceivably replace ChangeState() with AddState() and append // the three state parameters to a list. As its currently written, changing the state // immediatley calls the current 'exit' state, then overwrites the cached enter/run/exit // states with these new states. public void ChangeState (StateDelegate enter, StateDelegate update, StateDelegate exit) { bool isStateCurrentlyRunning = currentStateMethod != null; // If a state is currently running, it should be allowed to gracefully exit // before the next state takes over if (isStateCurrentlyRunning) { SwitchCurrentState (MState.Exiting); } // Cache the given state values this.enter = enter; this.update = update; this.exit = exit; // If a state isn't currently running, we can immediately switch to our entering // state using the state delegates we cached a few lines above if (!isStateCurrentlyRunning) { SwitchCurrentState (MState.Entering); } if (immediateMode) { Execute(); } } public void ChangeState(State state){ ChangeState(state.enter, state.update, state.exit); } public void ChangeState(int state) { if (!stateList.ContainsKey(state) || stateList[state] == null) { Debug.LogError("A statemachine is trying to access an unassigned state by number!"); return; } ChangeState(stateList[state]); } const int maxLoops = 100; private bool _shouldQuit = false; // Call this during public void Execute () { if (currentStateMethod == null) return; _shouldQuit = false; int loops = 0; while(!_shouldQuit) { // Execute the current state method bool finished = currentStateMethod (); // If we've reached the end of the current enter/run/exit, advance to the next one if (finished && !_shouldQuit) { switch (mState) { case MState.None: SwitchCurrentState (MState.Entering); break; case MState.Entering: SwitchCurrentState (MState.Updating); enter = null; _shouldQuit = true; break; case MState.Updating: SwitchCurrentState (MState.Exiting); update = null; break; case MState.Exiting: // If an Enter behavior exists, it must have been added by ChangeState. We should // start running again from the top instead of coming to a halt. if (enter != null) { SwitchCurrentState (MState.Entering); } else { SwitchCurrentState (MState.None); exit = null; _shouldQuit = true; } break; } } else { _shouldQuit = true; } loops++; if (loops >= maxLoops) { _shouldQuit = true; // This keeps us from freezing due to an infinite exit/enter cycle Debug.LogError("A statemachine has reached the maximum loop count!"); } if (!immediateMode) { _shouldQuit = true; } } } // Utility method for performing the state delegate swapping logic based on an enum value void SwitchCurrentState (MState state) { this.mState = state; switch (mState) { case MState.None: currentStateMethod = null; break; case MState.Entering: currentStateMethod = this.enter; break; case MState.Exiting: currentStateMethod = this.exit; break; case MState.Updating: currentStateMethod = this.update; break; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MilkBot.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System.Text; using System.Linq; namespace System.Buffers.Text.Tests { public static partial class FormatterTests { private static void ValidateFormatter<T>(FormatterTestData<T> testData) { // It's useful to do the over-sized buffer test first. If the formatter api has a bug that generates output text that's longer than // the expected string, this test will fail with an "Expected/Actual" diff while the exact-sized buffer test would say "Oops. The api returned 'false' and no output"." FormatterTestData<T> oversizedTestData = new FormatterTestData<T>(testData.Value, testData.Format, testData.Precision, testData.ExpectedOutput) { PassedInBufferLength = testData.ExpectedOutput.Length + 200, }; ValidateFormatterHelper(oversizedTestData); // Now run the test with a buffer that's exactly the right size. ValidateFormatterHelper(testData); // Now run the test with buffers that are too short. for (int truncatedBufferLength = 0; truncatedBufferLength < testData.ExpectedOutput.Length; truncatedBufferLength++) { FormatterTestData<T> newTestData = new FormatterTestData<T>(testData.Value, testData.Format, testData.Precision, testData.ExpectedOutput) { PassedInBufferLength = truncatedBufferLength, }; ValidateFormatterHelper(newTestData); } } private static void ValidateFormatterHelper<T>(FormatterTestData<T> testData) { int spanLength = testData.PassedInBufferLength; string expectedOutput = testData.ExpectedOutput; int expectedOutputLength = expectedOutput.Length; bool expectedSuccess = spanLength >= expectedOutputLength; StandardFormat format = new StandardFormat(testData.FormatSymbol, testData.Precision); T value = testData.Value; const int CanarySize = 100; byte[] backingArray = new byte[spanLength + CanarySize]; Span<byte> span = new Span<byte>(backingArray, 0, spanLength); CanaryFill(backingArray); bool success = TryFormatUtf8<T>(value, span, out int bytesWritten, format); if (success) { if (!expectedSuccess) { if (bytesWritten >= 0 && bytesWritten <= span.Length) { string unexpectedOutput = span.Slice(0, bytesWritten).ToUtf16String(); throw new TestException($"This format attempt ({testData}) was expected to fail due to an undersized buffer. Instead, it generated \"{unexpectedOutput}\""); } else { throw new TestException($"This format attempt ({testData}) was expected to fail due to an undersized buffer. Instead, it succeeded but set 'bytesWritten' to an out of range value: {bytesWritten}"); } } if (bytesWritten < 0 || bytesWritten > span.Length) { throw new TestException($"This format attempt ({testData}) succeeded as expected but set 'bytesWritten' to an out of range value: {bytesWritten}"); } string actual = span.Slice(0, bytesWritten).ToUtf16String(); string expected = testData.ExpectedOutput; if (actual != expected) { // We'll allocate (and not throw) the TestException (so that someone with a breakpoint inside TestException's constructor will break as desired) but // use Assert.Equals() to trigger the actual failure so we get XUnit's more useful comparison output into the log. new TestException($"This format attempt ({testData}) succeeded as expected but generated the wrong text:\n Expected: \"{expected}\"\n Actual: \"{actual}\"\n"); Assert.Equal(expected, actual); } // If the api scribbled into the Span past the reported 'bytesWritten' (but still within the bounds of the Span itself), this should raise eyebrows at least. CanaryCheck(testData, new ReadOnlySpan<byte>(backingArray, span.Length, CanarySize), "the end of the Span itself"); // If the api scribbled beyond the range of the Span itself, it's panic time. CanaryCheck(testData, new ReadOnlySpan<byte>(backingArray, expectedOutputLength, span.Length - expectedOutputLength), "'bytesWritten'"); } else { if (expectedSuccess) { throw new TestException($"This format attempt ({testData}) was expected to succeed. Instead, it failed."); } if (bytesWritten != 0) { throw new TestException($"This format attempt ({testData}) failed as expected but did not set `bytesWritten` to 0"); } // Note: It's not guaranteed that partial (and useless) results will be written to the buffer despite // byteWritten being 0. (In particular, ulong values that are larger than long.MaxValue using the "N" format.) // We can only check the canary portion for overwrites. CanaryCheck(testData, new ReadOnlySpan<byte>(backingArray, span.Length, CanarySize), "the end of the Span itself"); } } private static void CanaryFill(Span<byte> canaries) { for (int i = 0; i < canaries.Length; i++) { canaries[i] = 0xcc; } } private static void CanaryCheck<T>(FormatterTestData<T> testData, ReadOnlySpan<byte> canaries, string pastWhat) { for (int i = 0; i < canaries.Length; i++) { if (canaries[i] != 0xcc) throw new TestException($"BUFFER OVERRUN! This format attempt ({testData}) wrote past {pastWhat}!"); } } private static bool TryFormatUtf8<T>(T value, Span<byte> buffer, out int bytesWritten, StandardFormat format = default) { if (typeof(T) == typeof(bool)) return Utf8Formatter.TryFormat((bool)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(byte)) return Utf8Formatter.TryFormat((byte)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(sbyte)) return Utf8Formatter.TryFormat((sbyte)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(short)) return Utf8Formatter.TryFormat((short)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(ushort)) return Utf8Formatter.TryFormat((ushort)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(int)) return Utf8Formatter.TryFormat((int)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(uint)) return Utf8Formatter.TryFormat((uint)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(long)) return Utf8Formatter.TryFormat((long)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(ulong)) return Utf8Formatter.TryFormat((ulong)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(decimal)) return Utf8Formatter.TryFormat((decimal)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(double)) return Utf8Formatter.TryFormat((double)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(float)) return Utf8Formatter.TryFormat((float)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(Guid)) return Utf8Formatter.TryFormat((Guid)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(DateTime)) return Utf8Formatter.TryFormat((DateTime)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(DateTimeOffset)) return Utf8Formatter.TryFormat((DateTimeOffset)(object)value, buffer, out bytesWritten, format); if (typeof(T) == typeof(TimeSpan)) return Utf8Formatter.TryFormat((TimeSpan)(object)value, buffer, out bytesWritten, format); throw new Exception("No formatter for type " + typeof(T)); } private static bool TryFormatUtf8(object value, Span<byte> buffer, out int bytesWritten, StandardFormat format = default) { Type t = value.GetType(); if (t == typeof(bool)) return Utf8Formatter.TryFormat((bool)value, buffer, out bytesWritten, format); if (t == typeof(byte)) return Utf8Formatter.TryFormat((byte)value, buffer, out bytesWritten, format); if (t == typeof(sbyte)) return Utf8Formatter.TryFormat((sbyte)value, buffer, out bytesWritten, format); if (t == typeof(short)) return Utf8Formatter.TryFormat((short)value, buffer, out bytesWritten, format); if (t == typeof(ushort)) return Utf8Formatter.TryFormat((ushort)value, buffer, out bytesWritten, format); if (t == typeof(int)) return Utf8Formatter.TryFormat((int)value, buffer, out bytesWritten, format); if (t == typeof(uint)) return Utf8Formatter.TryFormat((uint)value, buffer, out bytesWritten, format); if (t == typeof(long)) return Utf8Formatter.TryFormat((long)value, buffer, out bytesWritten, format); if (t == typeof(ulong)) return Utf8Formatter.TryFormat((ulong)value, buffer, out bytesWritten, format); if (t == typeof(decimal)) return Utf8Formatter.TryFormat((decimal)value, buffer, out bytesWritten, format); if (t == typeof(double)) return Utf8Formatter.TryFormat((double)value, buffer, out bytesWritten, format); if (t == typeof(float)) return Utf8Formatter.TryFormat((float)value, buffer, out bytesWritten, format); if (t == typeof(Guid)) return Utf8Formatter.TryFormat((Guid)value, buffer, out bytesWritten, format); if (t == typeof(DateTime)) return Utf8Formatter.TryFormat((DateTime)value, buffer, out bytesWritten, format); if (t == typeof(DateTimeOffset)) return Utf8Formatter.TryFormat((DateTimeOffset)value, buffer, out bytesWritten, format); if (t == typeof(TimeSpan)) return Utf8Formatter.TryFormat((TimeSpan)value, buffer, out bytesWritten, format); throw new Exception("No formatter for type " + t); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Prismactic.Core.Extensions { /// <summary> /// A dictionary of lists. /// </summary> /// <typeparam name="TKey">The key to use for lists.</typeparam> /// <typeparam name="TValue">The type of the value held by lists.</typeparam> public sealed class ListDictionary<TKey, TValue> : IDictionary<TKey, IList<TValue>> { private readonly Dictionary<TKey, IList<TValue>> _innerValues = new Dictionary<TKey, IList<TValue>>(); #region Public Methods /// <summary> /// Removes all entries in the dictionary. /// </summary> public void Clear() { _innerValues.Clear(); } /// <summary> /// Determines whether the dictionary contains the given key. /// </summary> /// <param name="key">The key to locate.</param> /// <returns>true if the dictionary contains the given key; otherwise, false.</returns> public bool ContainsKey(TKey key) { if (key == null) throw new ArgumentNullException("key"); return _innerValues.ContainsKey(key); } /// <summary> /// Removes a list by key. /// </summary> /// <param name="key">The key of the list to remove.</param> /// <returns><see langword="true" /> if the element was removed.</returns> public bool Remove(TKey key) { if (key == null) throw new ArgumentNullException("key"); return _innerValues.Remove(key); } /// <summary> /// If a list does not already exist, it will be created automatically. /// </summary> /// <param name="key">The key of the list that will hold the value.</param> public void Add(TKey key) { if (key == null) throw new ArgumentNullException("key"); CreateNewList(key); } /// <summary> /// Adds a value to a list with the given key. If a list does not already exist, /// it will be created automatically. /// </summary> /// <param name="key">The key of the list that will hold the value.</param> /// <param name="value">The value to add to the list under the given key.</param> public void Add(TKey key, TValue value) { if (key == null) throw new ArgumentNullException("key"); if (value == null) throw new ArgumentNullException("value"); if (_innerValues.ContainsKey(key)) { _innerValues[key].Add(value); } else { List<TValue> values = CreateNewList(key); values.Add(value); } } private List<TValue> CreateNewList(TKey key) { var values = new List<TValue>(); _innerValues.Add(key, values); return values; } /// <summary> /// Determines whether the dictionary contains the specified value. /// </summary> /// <param name="value">The value to locate.</param> /// <returns>true if the dictionary contains the value in any list; otherwise, false.</returns> public bool ContainsValue(TValue value) { return _innerValues.Any(pair => pair.Value.Contains(value)); } /// <summary> /// Retrieves the all the elements from the list which have a key that matches the condition /// defined by the specified predicate. /// </summary> /// <param name="keyFilter">The filter with the condition to use to filter lists by their key.</param> /// <returns>The elements that have a key that matches the condition defined by the specified predicate.</returns> public IEnumerable<TValue> FindAllValuesByKey(Predicate<TKey> keyFilter) { return this.Where(pair => keyFilter(pair.Key)).SelectMany(pair => pair.Value); } /// <summary> /// Retrieves all the elements that match the condition defined by the specified predicate. /// </summary> /// <param name="valueFilter">The filter with the condition to use to filter values.</param> /// <returns>The elements that match the condition defined by the specified predicate.</returns> public IEnumerable<TValue> FindAllValues(Predicate<TValue> valueFilter) { return this.SelectMany(pair => pair.Value.Where(value => valueFilter(value))); } /// <summary> /// Removes a value from the list with the given key. /// </summary> /// <param name="key">The key of the list where the value exists.</param> /// <param name="value">The value to remove.</param> public void Remove(TKey key, TValue value) { if (key == null) throw new ArgumentNullException("key"); if (value == null) throw new ArgumentNullException("value"); if (!_innerValues.ContainsKey(key)) return; var innerList = (List<TValue>) _innerValues[key]; innerList.RemoveAll(item => value.Equals(item)); } /// <summary> /// Removes a value from all lists where it may be found. /// </summary> /// <param name="value">The value to remove.</param> public void Remove(TValue value) { foreach (var pair in _innerValues) { Remove(pair.Key, value); } } #endregion Public Methods #region Properties /// <summary> /// Gets a shallow copy of all values in all lists. /// </summary> /// <value>List of values.</value> public IList<TValue> Values { get { var values = new List<TValue>(); foreach (IEnumerable<TValue> list in _innerValues.Values) { values.AddRange(list); } return values; } } /// <summary> /// Gets the list of keys in the dictionary. /// </summary> /// <value>Collection of keys.</value> public ICollection<TKey> Keys { get { return _innerValues.Keys; } } /// <summary> /// Gets or sets the list associated with the given key. The /// access always succeeds, eventually returning an empty list. /// </summary> /// <param name="key">The key of the list to access.</param> /// <returns>The list associated with the key.</returns> public IList<TValue> this[TKey key] { get { if (_innerValues.ContainsKey(key) == false) { _innerValues.Add(key, new List<TValue>()); } return _innerValues[key]; } set { _innerValues[key] = value; } } /// <summary> /// Gets the number of lists in the dictionary. /// </summary> /// <value>Value indicating the values count.</value> public int Count { get { return _innerValues.Count; } } #endregion Properties #region IDictionary<TKey,List<TValue>> Members /// <summary> /// See <see cref="IDictionary{TKey,TValue}.Add(TKey,TValue)" /> for more information. /// </summary> void IDictionary<TKey, IList<TValue>>.Add(TKey key, IList<TValue> value) { if (key == null) throw new ArgumentNullException("key"); if (value == null) throw new ArgumentNullException("value"); _innerValues.Add(key, value); } /// <summary> /// See <see cref="IDictionary{TKey,TValue}.TryGetValue" /> for more information. /// </summary> bool IDictionary<TKey, IList<TValue>>.TryGetValue(TKey key, out IList<TValue> value) { value = this[key]; return true; } /// <summary> /// See <see cref="IDictionary{TKey,TValue}.Values" /> for more information. /// </summary> ICollection<IList<TValue>> IDictionary<TKey, IList<TValue>>.Values { get { return _innerValues.Values; } } #endregion IDictionary<TKey,List<TValue>> Members #region ICollection<KeyValuePair<TKey,List<TValue>>> Members /// <summary> /// See <see cref="ICollection{TValue}.Add" /> for more information. /// </summary> void ICollection<KeyValuePair<TKey, IList<TValue>>>.Add(KeyValuePair<TKey, IList<TValue>> item) { ((ICollection<KeyValuePair<TKey, IList<TValue>>>) _innerValues).Add(item); } /// <summary> /// See <see cref="ICollection{TValue}.Contains" /> for more information. /// </summary> bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Contains(KeyValuePair<TKey, IList<TValue>> item) { return ((ICollection<KeyValuePair<TKey, IList<TValue>>>) _innerValues).Contains(item); } /// <summary> /// See <see cref="ICollection{TValue}.CopyTo" /> for more information. /// </summary> void ICollection<KeyValuePair<TKey, IList<TValue>>>.CopyTo(KeyValuePair<TKey, IList<TValue>>[] array, int arrayIndex) { ((ICollection<KeyValuePair<TKey, IList<TValue>>>) _innerValues).CopyTo(array, arrayIndex); } /// <summary> /// See <see cref="ICollection{TValue}.IsReadOnly" /> for more information. /// </summary> bool ICollection<KeyValuePair<TKey, IList<TValue>>>.IsReadOnly { get { return ((ICollection<KeyValuePair<TKey, IList<TValue>>>) _innerValues).IsReadOnly; } } /// <summary> /// See <see cref="ICollection{TValue}.Remove" /> for more information. /// </summary> bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Remove(KeyValuePair<TKey, IList<TValue>> item) { return ((ICollection<KeyValuePair<TKey, IList<TValue>>>) _innerValues).Remove(item); } #endregion ICollection<KeyValuePair<TKey,List<TValue>>> Members #region IEnumerable<KeyValuePair<TKey,List<TValue>>> Members /// <summary> /// See <see cref="IEnumerable{TValue}.GetEnumerator" /> for more information. /// </summary> IEnumerator<KeyValuePair<TKey, IList<TValue>>> IEnumerable<KeyValuePair<TKey, IList<TValue>>>.GetEnumerator() { return _innerValues.GetEnumerator(); } #endregion IEnumerable<KeyValuePair<TKey,List<TValue>>> Members #region IEnumerable Members /// <summary> /// See <see cref="System.Collections.IEnumerable.GetEnumerator" /> for more information. /// </summary> IEnumerator IEnumerable.GetEnumerator() { return _innerValues.GetEnumerator(); } #endregion IEnumerable Members } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Common; using Common.Posting; using Common.Sage; using Fairweather.Service; using Line = Fairweather.Service.Pair<Common.Posting.Data_Line, Sage_Int.Line_Data>; namespace Sage_Int { partial class SIT_Engine { void Tell(bool scan, Record_Type mode, object ix, Line_Data line) { sit_exe.Tell(scan, mode, ix, line); } string Get_Errors_Path(Company_Number number) { var dir = Data.STR_Sit_History_Dir.Path.Cpath(number.As_String); var ret = dir + "\\Errors " + Get_Timestamp() + ".log"; return ret; } string Get_Success_Path(Company_Number number) { var dir = Data.STR_Sit_History_Dir.Path.Cpath(number.As_String); var ret = dir + "\\Success " + Get_Timestamp() + ".csv"; return ret; } string Get_Timestamp() { return "({0:yyyy-MM-dd} {0:HH.mm.ss})".spf(now); } // **************************** IEnumerable<Line> Get_Data_Lines_Iterator( Sit_Company_Settings sett_company, string file, Record_Type mode, string[] headers, Field_Count_Validator fcv) { using (var sr = new StreamReader(file)) using (var csv = Get_Csv_Reader(sr, true)) { var s = sr.BaseStream; var len = s.Length; var has_headers = sett_company.Has_Headers == true; if (has_headers) { var rec = csv.Get_Next_Record(); if (rec == null) yield break; } // ****************************** /* Error handling */ // ****************************** // now inlined Func<Csv_Error, bool, Line_Data> get_line_data = (_error, _read_through) => { // 24edb6b0-be82-4489-b2bb-8b5cb563abc8 var _line_no = csv.Line - (sr.EndOfStream ? 0 : _read_through ? 1 : 0); var _rec_no = csv.Record - (has_headers ? 1 : 0); var _perc = (int)((s.Position * 100) / len); return new Line_Data( _line_no, _rec_no, _perc, _error); }; List<string> record; while (true) { XCsv csv_ex = null; try { record = csv.Get_Next_Record(); } catch (XCsv ex) { csv_ex = ex; record = null; } if (csv_ex != null) { var error = new Csv_Error(csv_ex); // 24edb6b0-be82-4489-b2bb-8b5cb563abc8 var line_data = get_line_data(error, false); // // inline verified on 03.06.10 // #region get_line_data(error) //new Line_Data(csv.Line, // csv.Record - (has_headers ? 1 : 0), // (int)((s.Position * 100) / len), // error); // #endregion yield return Pair.Make((Data_Line)null, line_data); if (!csv_ex.Fatal) { csv.Skip_To_Next_Line(); continue; } } if (record == null) yield break; var cnt = record.Count; var end_on_comma = csv.Last_Char_Was_Comma; string desc; if (fcv.Check(cnt, end_on_comma, out desc)) { var data_line = new Data_Line(record.Count); for (int ii = 0; ii < fcv.Min && ii < headers.Length; ++ii) data_line[headers[ii]] = record[ii]; var line_data = get_line_data(null, true); //// inline verified on 03.06.10 //#region get_line_data(null) //new Line_Data(csv.Line, // csv.Record - (has_headers ? 1 : 0), // (int)((s.Position * 100) / len), // null); //#endregion yield return Pair.Make(data_line, line_data); } else { var error = new Csv_Error(Csv_Error_Type.Invalid_Field_Count, desc, csv.Column, false, true); // 24edb6b0-be82-4489-b2bb-8b5cb563abc8 var line_data = get_line_data(error, true); // // inline verified on 03.06.10 // #region get_line_data(error) //new Line_Data(csv.Line, // csv.Record - (has_headers ? 1 : 0), // (int)((s.Position * 100) / len), // error); // #endregion yield return Pair.Make((Data_Line)null, line_data); } } } } IEnumerable<Line> Get_Data_Lines(Sit_Company_Settings sett_company, string file, Record_Type mode, out string[] headers) { headers = null; var fcv = new Field_Count_Validator(); if (sett_company.Has_Headers == true) { using (var sr = new StreamReader(file)) using (var csv = Get_Csv_Reader(sr, false)) { var ok = false; try { var lst = csv.Get_Next_Record(); if (lst != null) { if (lst.Count > 0 && lst.Last().Trim().IsNullOrEmpty()) { // let's pretend the trailing comma wasn't there lst.RemoveAt(lst.Count - 1); } // trailing commas have no influence when we're reading the headers // from the file const bool last_is_comma = false; fcv.Check(lst.Count, last_is_comma); if (lst.Count == 0) lst = null; } headers = lst == null ? null : lst.arr(); ok = (headers != null); } catch (XCsv) { } if (!ok) { headers = null; return new Line[0]; } } } else { headers = Get_Static_Headers(mode); } if (headers != null) headers = headers.Select(_h => _h.ToUpper()).arr(); var seq = Get_Data_Lines_Iterator(sett_company, file, mode, headers, fcv); //*/ return seq; /*/ return new Cached_Enumerable<Line>(seq); //*/ } Csv_Parser Get_Csv_Reader(TextReader base_reader, bool small_buffer) { // http://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules /* In some CSV implementations, leading and trailing spaces or tabs, adjacent to commas, are trimmed. This practice is contentious and in fact is specifically prohibited by RFC 4180, which states, "Spaces are considered part of a field and should not be ignored." */ //const ValueTrimmingOptions trimming = ValueTrimmingOptions.None; var ret = new Csv_Parser(base_reader); // new CsvReader(base_reader, false, ',', '"', '"', '#', trimming, small_buffer ? 0x3 : 0x1000); // ret.SkipEmptyLines = true; // ret.SupportsMultiline = true; // ret.MissingFieldAction = false; // ret.DefaultParseErrorAction = ; return ret; } // string[] //Get_Record(CsvReader csv) { // string[] ret; // csv.CopyCurrentRecordTo(ret = new string[csv.FieldCount]); // return ret; //} //Prepare the headers string[] Get_Static_Headers(Record_Type mode) { switch (mode) { case Record_Type.Sales: case Record_Type.Purchase: case Record_Type.Bank: return SIT_Engine.record_static; case Record_Type.Expense: return SIT_Engine.nominal_static; case Record_Type.Stock: return SIT_Engine.stock_static; } true.tift<ArgumentException>(); return null; } void Maybe_Enter_Defaults(Data_Line data, Record_Type mode, bool is_new, bool auto_date, Dictionary<string, object> defaults) { var dict = data.Dict; #warning verify if (is_new) { if (auto_date) { var key = (string)null; switch (mode) { case Record_Type.Sales: case Record_Type.Purchase: key = "ACCOUNT_OPENED"; break; //case Record_Type.Expense: /* not to be filled manually */ //key = "RECORD_CREATE_DATE"; break; } if (!key.IsNullOrEmpty()) //&& //data[key].strdef().Trim().IsNullOrEmpty()) data[key] = today; } dict.Fill(defaults.Where(_kvp => !dict.ContainsKey(_kvp.Key)), false); } else { dict.Drop(_kvp => _kvp.Value.IsNullOrEmpty()); } } IEnumerable<string> Get_Fields_For_Type(Record_Type type) { return Sage_Fields.Fields(type).Select(_kvp => _kvp.Key).lst(); } Func<Data_Line, Data_Line, bool> Items_Same_Document(Sit_Company_Settings sett_company) { var auto = (sett_company.Documents_Numbering_Auto == true); var relative = (sett_company.Documents_Grouping_Relative == true); var absolute = !auto; (relative && !auto).tift(); return (_dl1, _dl2) => { if (relative || absolute) { return _dl1.INVOICE_NUMBER == _dl2.INVOICE_NUMBER; } if (auto) { return _dl1.ACCOUNT_REF.Clean() == _dl2.ACCOUNT_REF.Clean() && _dl1.INVOICE_DATE == _dl2.INVOICE_DATE && _dl1.INVOICE_TYPE == _dl2.INVOICE_TYPE; } true.tift(); return false; }; } } }
using Lucene.Net.Support; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Reflection; using System.Runtime.CompilerServices; namespace 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 Analyzer = Lucene.Net.Analysis.Analyzer; using BinaryDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.BinaryDocValuesUpdate; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using IEvent = Lucene.Net.Index.IndexWriter.IEvent; using FlushedSegment = Lucene.Net.Index.DocumentsWriterPerThread.FlushedSegment; using InfoStream = Lucene.Net.Util.InfoStream; using NumericDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.NumericDocValuesUpdate; using Query = Lucene.Net.Search.Query; using SegmentFlushTicket = Lucene.Net.Index.DocumentsWriterFlushQueue.SegmentFlushTicket; using ThreadState = Lucene.Net.Index.DocumentsWriterPerThreadPool.ThreadState; /// <summary> /// This class accepts multiple added documents and directly /// writes segment files. /// <para/> /// Each added document is passed to the <see cref="DocConsumer"/>, /// which in turn processes the document and interacts with /// other consumers in the indexing chain. Certain /// consumers, like <see cref="StoredFieldsConsumer"/> and /// <see cref="TermVectorsConsumer"/>, digest a document and /// immediately write bytes to the "doc store" files (ie, /// they do not consume RAM per document, except while they /// are processing the document). /// <para/> /// Other consumers, eg <see cref="FreqProxTermsWriter"/> and /// <see cref="NormsConsumer"/>, buffer bytes in RAM and flush only /// when a new segment is produced. /// <para/> /// Once we have used our allowed RAM buffer, or the number /// of added docs is large enough (in the case we are /// flushing by doc count instead of RAM usage), we create a /// real segment and flush it to the Directory. /// <para/> /// Threads: /// <para/> /// Multiple threads are allowed into AddDocument at once. /// There is an initial synchronized call to <see cref="DocumentsWriterPerThreadPool.GetThreadState(int)"/> /// which allocates a <see cref="ThreadState"/> for this thread. The same /// thread will get the same <see cref="ThreadState"/> over time (thread /// affinity) so that if there are consistent patterns (for /// example each thread is indexing a different content /// source) then we make better use of RAM. Then /// ProcessDocument is called on that <see cref="ThreadState"/> without /// synchronization (most of the "heavy lifting" is in this /// call). Finally the synchronized "finishDocument" is /// called to flush changes to the directory. /// <para/> /// When flush is called by <see cref="IndexWriter"/> we forcefully idle /// all threads and flush only once they are all idle. this /// means you can call flush with a given thread even while /// other threads are actively adding/deleting documents. /// <para/> /// /// Exceptions: /// <para/> /// Because this class directly updates in-memory posting /// lists, and flushes stored fields and term vectors /// directly to files in the directory, there are certain /// limited times when an exception can corrupt this state. /// For example, a disk full while flushing stored fields /// leaves this file in a corrupt state. Or, an OOM /// exception while appending to the in-memory posting lists /// can corrupt that posting list. We call such exceptions /// "aborting exceptions". In these cases we must call /// <see cref="Abort(IndexWriter)"/> to discard all docs added since the last flush. /// <para/> /// All other exceptions ("non-aborting exceptions") can /// still partially update the index structures. These /// updates are consistent, but, they represent only a part /// of the document seen up until the exception was hit. /// When this happens, we immediately mark the document as /// deleted so that the document is always atomically ("all /// or none") added to the index. /// </summary> internal sealed class DocumentsWriter : IDisposable { private readonly Directory directory; private volatile bool closed; private readonly InfoStream infoStream; private readonly LiveIndexWriterConfig config; private readonly AtomicInt32 numDocsInRAM = new AtomicInt32(0); // TODO: cut over to BytesRefHash in BufferedDeletes internal volatile DocumentsWriterDeleteQueue deleteQueue = new DocumentsWriterDeleteQueue(); private readonly DocumentsWriterFlushQueue ticketQueue = new DocumentsWriterFlushQueue(); /// <summary> /// we preserve changes during a full flush since IW might not checkout before /// we release all changes. NRT Readers otherwise suddenly return true from /// IsCurrent() while there are actually changes currently committed. See also /// <see cref="AnyChanges()"/> &amp; <see cref="FlushAllThreads(IndexWriter)"/> /// </summary> private volatile bool pendingChangesInCurrentFullFlush; internal readonly DocumentsWriterPerThreadPool perThreadPool; internal readonly FlushPolicy flushPolicy; internal readonly DocumentsWriterFlushControl flushControl; private readonly IndexWriter writer; private readonly ConcurrentQueue<IEvent> events; internal DocumentsWriter(IndexWriter writer, LiveIndexWriterConfig config, Directory directory) { this.directory = directory; this.config = config; this.infoStream = config.InfoStream; this.perThreadPool = config.IndexerThreadPool; flushPolicy = config.FlushPolicy; this.writer = writer; this.events = new ConcurrentQueue<IEvent>(); flushControl = new DocumentsWriterFlushControl(this, config, writer.bufferedUpdatesStream); } internal bool DeleteQueries(params Query[] queries) { lock (this) { // TODO why is this synchronized? DocumentsWriterDeleteQueue deleteQueue = this.deleteQueue; deleteQueue.AddDelete(queries); flushControl.DoOnDelete(); return ApplyAllDeletes(deleteQueue); } } // TODO: we could check w/ FreqProxTermsWriter: if the // term doesn't exist, don't bother buffering into the // per-DWPT map (but still must go into the global map) internal bool DeleteTerms(params Term[] terms) { lock (this) { // TODO why is this synchronized? DocumentsWriterDeleteQueue deleteQueue = this.deleteQueue; deleteQueue.AddDelete(terms); flushControl.DoOnDelete(); return ApplyAllDeletes(deleteQueue); } } internal bool UpdateNumericDocValue(Term term, string field, long? value) { lock (this) { DocumentsWriterDeleteQueue deleteQueue = this.deleteQueue; deleteQueue.AddNumericUpdate(new NumericDocValuesUpdate(term, field, value)); flushControl.DoOnDelete(); return ApplyAllDeletes(deleteQueue); } } internal bool UpdateBinaryDocValue(Term term, string field, BytesRef value) { lock (this) { DocumentsWriterDeleteQueue deleteQueue = this.deleteQueue; deleteQueue.AddBinaryUpdate(new BinaryDocValuesUpdate(term, field, value)); flushControl.DoOnDelete(); return ApplyAllDeletes(deleteQueue); } } internal DocumentsWriterDeleteQueue CurrentDeleteSession { get { return deleteQueue; } } private bool ApplyAllDeletes(DocumentsWriterDeleteQueue deleteQueue) { if (flushControl.GetAndResetApplyAllDeletes()) { if (deleteQueue != null && !flushControl.IsFullFlush) { ticketQueue.AddDeletes(deleteQueue); } PutEvent(ApplyDeletesEvent.INSTANCE); // apply deletes event forces a purge return true; } return false; } internal int PurgeBuffer(IndexWriter writer, bool forced) { if (forced) { return ticketQueue.ForcePurge(writer); } else { return ticketQueue.TryPurge(writer); } } /// <summary> /// Returns how many docs are currently buffered in RAM. </summary> internal int NumDocs { get { return numDocsInRAM.Get(); } } private void EnsureOpen() { if (closed) { throw new ObjectDisposedException(this.GetType().FullName, "this IndexWriter is closed"); } } /// <summary> /// Called if we hit an exception at a bad time (when /// updating the index files) and must discard all /// currently buffered docs. this resets our state, /// discarding any docs added since last flush. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal void Abort(IndexWriter writer) { lock (this) { //Debug.Assert(!Thread.HoldsLock(writer), "IndexWriter lock should never be hold when aborting"); bool success = false; HashSet<string> newFilesSet = new HashSet<string>(); try { deleteQueue.Clear(); if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "abort"); } int limit = perThreadPool.NumThreadStatesActive; for (int i = 0; i < limit; i++) { ThreadState perThread = perThreadPool.GetThreadState(i); perThread.@Lock(); try { AbortThreadState(perThread, newFilesSet); } finally { perThread.Unlock(); } } flushControl.AbortPendingFlushes(newFilesSet); PutEvent(new DeleteNewFilesEvent(newFilesSet)); flushControl.WaitForFlush(); success = true; } finally { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "done abort; abortedFiles=" + Arrays.ToString(newFilesSet) + " success=" + success); } } } } internal void LockAndAbortAll(IndexWriter indexWriter) { lock (this) { //Debug.Assert(indexWriter.HoldsFullFlushLock()); if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "lockAndAbortAll"); } bool success = false; try { deleteQueue.Clear(); int limit = perThreadPool.MaxThreadStates; HashSet<string> newFilesSet = new HashSet<string>(); for (int i = 0; i < limit; i++) { ThreadState perThread = perThreadPool.GetThreadState(i); perThread.@Lock(); AbortThreadState(perThread, newFilesSet); } deleteQueue.Clear(); flushControl.AbortPendingFlushes(newFilesSet); PutEvent(new DeleteNewFilesEvent(newFilesSet)); flushControl.WaitForFlush(); success = true; } finally { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "finished lockAndAbortAll success=" + success); } if (!success) { // if something happens here we unlock all states again UnlockAllAfterAbortAll(indexWriter); } } } } private void AbortThreadState(ThreadState perThread, ISet<string> newFiles) { //Debug.Assert(perThread.HeldByCurrentThread); if (perThread.IsActive) // we might be closed { if (perThread.IsInitialized) { try { SubtractFlushedNumDocs(perThread.dwpt.NumDocsInRAM); perThread.dwpt.Abort(newFiles); } finally { perThread.dwpt.CheckAndResetHasAborted(); flushControl.DoOnAbort(perThread); } } else { flushControl.DoOnAbort(perThread); } } else { Debug.Assert(closed); } } internal void UnlockAllAfterAbortAll(IndexWriter indexWriter) { lock (this) { //Debug.Assert(indexWriter.HoldsFullFlushLock()); if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "unlockAll"); } int limit = perThreadPool.MaxThreadStates; for (int i = 0; i < limit; i++) { try { ThreadState perThread = perThreadPool.GetThreadState(i); //if (perThread.HeldByCurrentThread) //{ perThread.Unlock(); //} } catch (Exception e) { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "unlockAll: could not unlock state: " + i + " msg:" + e.Message); } // ignore & keep on unlocking } } } } internal bool AnyChanges() { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "anyChanges? numDocsInRam=" + numDocsInRAM.Get() + " deletes=" + AnyDeletions() + " hasTickets:" + ticketQueue.HasTickets + " pendingChangesInFullFlush: " + pendingChangesInCurrentFullFlush); } /* * changes are either in a DWPT or in the deleteQueue. * yet if we currently flush deletes and / or dwpt there * could be a window where all changes are in the ticket queue * before they are published to the IW. ie we need to check if the * ticket queue has any tickets. */ return numDocsInRAM.Get() != 0 || AnyDeletions() || ticketQueue.HasTickets || pendingChangesInCurrentFullFlush; } public int BufferedDeleteTermsSize { get { return deleteQueue.BufferedUpdatesTermsSize; } } //for testing public int NumBufferedDeleteTerms { get { return deleteQueue.NumGlobalTermDeletes; } } public bool AnyDeletions() { return deleteQueue.AnyChanges(); } public void Dispose() { closed = true; flushControl.SetClosed(); } private bool PreUpdate() { EnsureOpen(); bool hasEvents = false; if (flushControl.AnyStalledThreads() || flushControl.NumQueuedFlushes > 0) { // Help out flushing any queued DWPTs so we can un-stall: if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "DocumentsWriter has queued dwpt; will hijack this thread to flush pending segment(s)"); } do { // Try pick up pending threads here if possible DocumentsWriterPerThread flushingDWPT; while ((flushingDWPT = flushControl.NextPendingFlush()) != null) { // Don't push the delete here since the update could fail! hasEvents |= DoFlush(flushingDWPT); } if (infoStream.IsEnabled("DW")) { if (flushControl.AnyStalledThreads()) { infoStream.Message("DW", "WARNING DocumentsWriter has stalled threads; waiting"); } } flushControl.WaitIfStalled(); // block if stalled } while (flushControl.NumQueuedFlushes != 0); // still queued DWPTs try help flushing if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "continue indexing after helping out flushing DocumentsWriter is healthy"); } } return hasEvents; } private bool PostUpdate(DocumentsWriterPerThread flushingDWPT, bool hasEvents) { hasEvents |= ApplyAllDeletes(deleteQueue); if (flushingDWPT != null) { hasEvents |= DoFlush(flushingDWPT); } else { DocumentsWriterPerThread nextPendingFlush = flushControl.NextPendingFlush(); if (nextPendingFlush != null) { hasEvents |= DoFlush(nextPendingFlush); } } return hasEvents; } private void EnsureInitialized(ThreadState state) { if (state.IsActive && state.dwpt == null) { FieldInfos.Builder infos = new FieldInfos.Builder(writer.globalFieldNumberMap); state.dwpt = new DocumentsWriterPerThread(writer.NewSegmentName(), directory, config, infoStream, deleteQueue, infos); } } internal bool UpdateDocuments(IEnumerable<IEnumerable<IIndexableField>> docs, Analyzer analyzer, Term delTerm) { bool hasEvents = PreUpdate(); ThreadState perThread = flushControl.ObtainAndLock(); DocumentsWriterPerThread flushingDWPT; try { if (!perThread.IsActive) { EnsureOpen(); Debug.Assert(false, "perThread is not active but we are still open"); } EnsureInitialized(perThread); Debug.Assert(perThread.IsInitialized); DocumentsWriterPerThread dwpt = perThread.dwpt; int dwptNumDocs = dwpt.NumDocsInRAM; try { int docCount = dwpt.UpdateDocuments(docs, analyzer, delTerm); numDocsInRAM.AddAndGet(docCount); } finally { if (dwpt.CheckAndResetHasAborted()) { if (dwpt.PendingFilesToDelete.Count > 0) { PutEvent(new DeleteNewFilesEvent(dwpt.PendingFilesToDelete)); } SubtractFlushedNumDocs(dwptNumDocs); flushControl.DoOnAbort(perThread); } } bool isUpdate = delTerm != null; flushingDWPT = flushControl.DoAfterDocument(perThread, isUpdate); } finally { perThread.Unlock(); } return PostUpdate(flushingDWPT, hasEvents); } internal bool UpdateDocument(IEnumerable<IIndexableField> doc, Analyzer analyzer, Term delTerm) { bool hasEvents = PreUpdate(); ThreadState perThread = flushControl.ObtainAndLock(); DocumentsWriterPerThread flushingDWPT; try { if (!perThread.IsActive) { EnsureOpen(); Debug.Assert(false, "perThread is not active but we are still open"); } EnsureInitialized(perThread); Debug.Assert(perThread.IsInitialized); DocumentsWriterPerThread dwpt = perThread.dwpt; int dwptNumDocs = dwpt.NumDocsInRAM; try { dwpt.UpdateDocument(doc, analyzer, delTerm); numDocsInRAM.IncrementAndGet(); } finally { if (dwpt.CheckAndResetHasAborted()) { if (dwpt.PendingFilesToDelete.Count > 0) { PutEvent(new DeleteNewFilesEvent(dwpt.PendingFilesToDelete)); } SubtractFlushedNumDocs(dwptNumDocs); flushControl.DoOnAbort(perThread); } } bool isUpdate = delTerm != null; flushingDWPT = flushControl.DoAfterDocument(perThread, isUpdate); } finally { perThread.Unlock(); } return PostUpdate(flushingDWPT, hasEvents); } private bool DoFlush(DocumentsWriterPerThread flushingDWPT) { bool hasEvents = false; while (flushingDWPT != null) { hasEvents = true; bool success = false; SegmentFlushTicket ticket = null; try { Debug.Assert(currentFullFlushDelQueue == null || flushingDWPT.deleteQueue == currentFullFlushDelQueue, "expected: " + currentFullFlushDelQueue + "but was: " + flushingDWPT.deleteQueue + " " + flushControl.IsFullFlush); /* * Since with DWPT the flush process is concurrent and several DWPT * could flush at the same time we must maintain the order of the * flushes before we can apply the flushed segment and the frozen global * deletes it is buffering. The reason for this is that the global * deletes mark a certain point in time where we took a DWPT out of * rotation and freeze the global deletes. * * Example: A flush 'A' starts and freezes the global deletes, then * flush 'B' starts and freezes all deletes occurred since 'A' has * started. if 'B' finishes before 'A' we need to wait until 'A' is done * otherwise the deletes frozen by 'B' are not applied to 'A' and we * might miss to deletes documents in 'A'. */ try { // Each flush is assigned a ticket in the order they acquire the ticketQueue lock ticket = ticketQueue.AddFlushTicket(flushingDWPT); int flushingDocsInRam = flushingDWPT.NumDocsInRAM; bool dwptSuccess = false; try { // flush concurrently without locking FlushedSegment newSegment = flushingDWPT.Flush(); ticketQueue.AddSegment(ticket, newSegment); dwptSuccess = true; } finally { SubtractFlushedNumDocs(flushingDocsInRam); if (flushingDWPT.PendingFilesToDelete.Count > 0) { PutEvent(new DeleteNewFilesEvent(flushingDWPT.PendingFilesToDelete)); hasEvents = true; } if (!dwptSuccess) { PutEvent(new FlushFailedEvent(flushingDWPT.SegmentInfo)); hasEvents = true; } } // flush was successful once we reached this point - new seg. has been assigned to the ticket! success = true; } finally { if (!success && ticket != null) { // In the case of a failure make sure we are making progress and // apply all the deletes since the segment flush failed since the flush // ticket could hold global deletes see FlushTicket#canPublish() ticketQueue.MarkTicketFailed(ticket); } } /* * Now we are done and try to flush the ticket queue if the head of the * queue has already finished the flush. */ if (ticketQueue.TicketCount >= perThreadPool.NumThreadStatesActive) { // this means there is a backlog: the one // thread in innerPurge can't keep up with all // other threads flushing segments. In this case // we forcefully stall the producers. PutEvent(ForcedPurgeEvent.INSTANCE); break; } } finally { flushControl.DoAfterFlush(flushingDWPT); flushingDWPT.CheckAndResetHasAborted(); } flushingDWPT = flushControl.NextPendingFlush(); } if (hasEvents) { PutEvent(MergePendingEvent.INSTANCE); } // If deletes alone are consuming > 1/2 our RAM // buffer, force them all to apply now. this is to // prevent too-frequent flushing of a long tail of // tiny segments: double ramBufferSizeMB = config.RAMBufferSizeMB; if (ramBufferSizeMB != Index.IndexWriterConfig.DISABLE_AUTO_FLUSH && flushControl.DeleteBytesUsed > (1024 * 1024 * ramBufferSizeMB / 2)) { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "force apply deletes bytesUsed=" + flushControl.DeleteBytesUsed + " vs ramBuffer=" + (1024 * 1024 * ramBufferSizeMB)); } hasEvents = true; if (!this.ApplyAllDeletes(deleteQueue)) { PutEvent(ApplyDeletesEvent.INSTANCE); } } return hasEvents; } internal void SubtractFlushedNumDocs(int numFlushed) { int oldValue = numDocsInRAM.Get(); while (!numDocsInRAM.CompareAndSet(oldValue, oldValue - numFlushed)) { oldValue = numDocsInRAM.Get(); } } // for asserts private volatile DocumentsWriterDeleteQueue currentFullFlushDelQueue = null; // for asserts private bool SetFlushingDeleteQueue(DocumentsWriterDeleteQueue session) { lock (this) { currentFullFlushDelQueue = session; return true; } } /* * FlushAllThreads is synced by IW fullFlushLock. Flushing all threads is a * two stage operation; the caller must ensure (in try/finally) that finishFlush * is called after this method, to release the flush lock in DWFlushControl */ internal bool FlushAllThreads(IndexWriter indexWriter) { DocumentsWriterDeleteQueue flushingDeleteQueue; if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "startFullFlush"); } lock (this) { pendingChangesInCurrentFullFlush = AnyChanges(); flushingDeleteQueue = deleteQueue; /* Cutover to a new delete queue. this must be synced on the flush control * otherwise a new DWPT could sneak into the loop with an already flushing * delete queue */ flushControl.MarkForFullFlush(); // swaps the delQueue synced on FlushControl Debug.Assert(SetFlushingDeleteQueue(flushingDeleteQueue)); } Debug.Assert(currentFullFlushDelQueue != null); Debug.Assert(currentFullFlushDelQueue != deleteQueue); bool anythingFlushed = false; try { DocumentsWriterPerThread flushingDWPT; // Help out with flushing: while ((flushingDWPT = flushControl.NextPendingFlush()) != null) { anythingFlushed |= DoFlush(flushingDWPT); } // If a concurrent flush is still in flight wait for it flushControl.WaitForFlush(); if (!anythingFlushed && flushingDeleteQueue.AnyChanges()) // apply deletes if we did not flush any document { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", Thread.CurrentThread.Name + ": flush naked frozen global deletes"); } ticketQueue.AddDeletes(flushingDeleteQueue); } ticketQueue.ForcePurge(indexWriter); Debug.Assert(!flushingDeleteQueue.AnyChanges() && !ticketQueue.HasTickets); } finally { Debug.Assert(flushingDeleteQueue == currentFullFlushDelQueue); } return anythingFlushed; } internal void FinishFullFlush(bool success) { try { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", Thread.CurrentThread.Name + " finishFullFlush success=" + success); } Debug.Assert(SetFlushingDeleteQueue(null)); if (success) { // Release the flush lock flushControl.FinishFullFlush(); } else { HashSet<string> newFilesSet = new HashSet<string>(); flushControl.AbortFullFlushes(newFilesSet); PutEvent(new DeleteNewFilesEvent(newFilesSet)); } } finally { pendingChangesInCurrentFullFlush = false; } } public LiveIndexWriterConfig IndexWriterConfig { get { return config; } } private void PutEvent(IEvent @event) { events.Enqueue(@event); } internal sealed class ApplyDeletesEvent : IEvent { internal static readonly IEvent INSTANCE = new ApplyDeletesEvent(); private int instCount = 0; // LUCENENET TODO: What is this for? It will always be zero when initialized and 1 after the constructor is called. Should it be static? internal ApplyDeletesEvent() { Debug.Assert(instCount == 0); instCount++; } public void Process(IndexWriter writer, bool triggerMerge, bool forcePurge) { writer.ApplyDeletesAndPurge(true); // we always purge! } } internal sealed class MergePendingEvent : IEvent { internal static readonly IEvent INSTANCE = new MergePendingEvent(); private int instCount = 0; // LUCENENET TODO: What is this for? It will always be zero when initialized and 1 after the constructor is called. Should it be static? internal MergePendingEvent() { Debug.Assert(instCount == 0); instCount++; } public void Process(IndexWriter writer, bool triggerMerge, bool forcePurge) { writer.DoAfterSegmentFlushed(triggerMerge, forcePurge); } } internal sealed class ForcedPurgeEvent : IEvent { internal static readonly IEvent INSTANCE = new ForcedPurgeEvent(); private int instCount = 0; // LUCENENET TODO: What is this for? It will always be zero when initialized and 1 after the constructor is called. Should it be static? internal ForcedPurgeEvent() { Debug.Assert(instCount == 0); instCount++; } public void Process(IndexWriter writer, bool triggerMerge, bool forcePurge) { writer.Purge(true); } } internal class FlushFailedEvent : IEvent { private readonly SegmentInfo info; public FlushFailedEvent(SegmentInfo info) { this.info = info; } public void Process(IndexWriter writer, bool triggerMerge, bool forcePurge) { writer.FlushFailed(info); } } internal class DeleteNewFilesEvent : IEvent { private readonly ICollection<string> files; public DeleteNewFilesEvent(ICollection<string> files) { this.files = files; } public void Process(IndexWriter writer, bool triggerMerge, bool forcePurge) { writer.DeleteNewFiles(files); } } public ConcurrentQueue<IEvent> EventQueue { get { return events; } } } }
//------------------------------------------------------------------------------ // <copyright file="FlowLayout.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms.Layout { using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; internal class FlowLayout : LayoutEngine { // Singleton instance shared by all FlowPanels. internal static readonly FlowLayout Instance = new FlowLayout(); private static readonly int _wrapContentsProperty = PropertyStore.CreateKey(); private static readonly int _flowDirectionProperty = PropertyStore.CreateKey(); internal static FlowLayoutSettings CreateSettings(IArrangedElement owner) { return new FlowLayoutSettings(owner); } // Entry point from LayoutEngine internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs args) { #if DEBUG if (CompModSwitches.FlowLayout.TraceInfo) { Debug.WriteLine("FlowLayout::Layout(" + "container=" + container.ToString() + ", " + "displayRect=" + container.DisplayRectangle.ToString() + ", " + "args=" + args.ToString() + ")"); } Debug.Indent(); #endif // ScrollableControl will first try to get the layoutbounds from the derived control when // trying to figure out if ScrollBars should be added. // VSWhidbey #392913 CommonProperties.SetLayoutBounds(container, xLayout(container, container.DisplayRectangle, /* measureOnly = */ false)); #if DEBUG Debug.Unindent(); #endif return CommonProperties.GetAutoSize(container); } internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) { #if DEBUG if (CompModSwitches.FlowLayout.TraceInfo) { Debug.WriteLine("FlowLayout::GetPreferredSize(" + "container=" + container.ToString() + ", " + "proposedConstraints=" + proposedConstraints.ToString() + ")"); Debug.Indent(); } #endif Rectangle measureBounds = new Rectangle(new Point(0, 0), proposedConstraints); Size prefSize = xLayout(container, measureBounds, /* measureOnly = */ true); if(prefSize.Width > proposedConstraints.Width || prefSize.Height> proposedConstraints.Height) { // Controls measured earlier than a control which couldn't be fit to constraints may // shift around with the new bounds. We need to make a 2nd pass through the // controls using these bounds which are gauranteed to fit. measureBounds.Size = prefSize; prefSize = xLayout(container, measureBounds, /* measureOnly = */ true); } #if DEBUG if (CompModSwitches.FlowLayout.TraceInfo) { Debug.Unindent(); Debug.WriteLine("GetPreferredSize returned " + prefSize); } #endif return prefSize; } private static ContainerProxy CreateContainerProxy(IArrangedElement container, FlowDirection flowDirection) { switch (flowDirection) { case FlowDirection.RightToLeft: return new RightToLeftProxy(container); case FlowDirection.TopDown: return new TopDownProxy(container); case FlowDirection.BottomUp: return new BottomUpProxy(container); case FlowDirection.LeftToRight: default: return new ContainerProxy(container); } } // Both LayoutCore and GetPreferredSize forward to this method. The measureOnly flag determines which // behavior we get. private Size xLayout(IArrangedElement container, Rectangle displayRect, bool measureOnly) { FlowDirection flowDirection = GetFlowDirection(container); bool wrapContents = GetWrapContents(container); ContainerProxy containerProxy = CreateContainerProxy(container, flowDirection); containerProxy.DisplayRect = displayRect; // refetch as it's now adjusted for Vertical. displayRect = containerProxy.DisplayRect; ElementProxy elementProxy = containerProxy.ElementProxy; Size layoutSize = Size.Empty; if(!wrapContents) { // pretend that the container is infinitely wide to prevent wrapping. // VSWhidbey 161993: displayRectangle.Right is Width + X - subtract X to prevent overflow. displayRect.Width = Int32.MaxValue - displayRect.X; } for(int i = 0; i < container.Children.Count;) { int breakIndex; Size rowSize = Size.Empty; Rectangle measureBounds = new Rectangle(displayRect.X, displayRect.Y, displayRect.Width, displayRect.Height - layoutSize.Height); rowSize = MeasureRow(containerProxy, elementProxy, i, measureBounds, out breakIndex); // if we are not wrapping contents, then the breakIndex (as set in MeasureRow) // should be equal to the count of child items in the container. Debug.Assert(wrapContents == true || breakIndex == container.Children.Count, "We should not be trying to break the row if we are not wrapping contents."); if(!measureOnly) { Rectangle rowBounds = new Rectangle(displayRect.X, layoutSize.Height + displayRect.Y, rowSize.Width, rowSize.Height); LayoutRow(containerProxy, elementProxy, /* startIndex = */ i, /* endIndex = */ breakIndex, rowBounds); } layoutSize.Width = Math.Max(layoutSize.Width, rowSize.Width); layoutSize.Height += rowSize.Height; i = breakIndex; } //verify that our alignment is correct if (container.Children.Count != 0 && !measureOnly) { Debug_VerifyAlignment(container, flowDirection); } return LayoutUtils.FlipSizeIf(flowDirection == FlowDirection.TopDown || GetFlowDirection(container) == FlowDirection.BottomUp, layoutSize); } // Just forwards to xLayoutRow. This will layout elements from the start index to the end index. RowBounds // was computed by a call to measure row and is used for alignment/boxstretch. See the ElementProxy class // for an explaination of the elementProxy parameter. private void LayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy, int startIndex, int endIndex, Rectangle rowBounds) { int dummy; Size outSize = xLayoutRow(containerProxy, elementProxy, startIndex, endIndex, rowBounds, /* breakIndex = */ out dummy, /* measureOnly = */ false); Debug.Assert(dummy == endIndex, "EndIndex / BreakIndex mismatch."); } // Just forwards to xLayoutRow. breakIndex is the index of the first control not to fit in the displayRectangle. The // returned Size is the size required to layout the controls from startIndex up to but not including breakIndex. See // the ElementProxy class for an explaination of the elementProxy parameter. private Size MeasureRow(ContainerProxy containerProxy, ElementProxy elementProxy, int startIndex, Rectangle displayRectangle, out int breakIndex) { return xLayoutRow(containerProxy, elementProxy, startIndex, /* endIndex = */ containerProxy.Container.Children.Count, displayRectangle, out breakIndex, /* measureOnly = */ true); } // LayoutRow and MeasureRow both forward to this method. The measureOnly flag determines which behavior we get. private Size xLayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy, int startIndex, int endIndex, Rectangle rowBounds, out int breakIndex, bool measureOnly) { Debug.Assert(startIndex < endIndex, "Loop should be in forward Z-order."); Point location = rowBounds.Location; Size rowSize = Size.Empty; int laidOutItems = 0; breakIndex = startIndex; bool wrapContents = GetWrapContents(containerProxy.Container); bool breakOnNextItem = false; ArrangedElementCollection collection = containerProxy.Container.Children; for(int i = startIndex; i < endIndex; i++, breakIndex++) { elementProxy.Element = collection[i]; if(!elementProxy.ParticipatesInLayout) { continue; } // Figure out how much space this element is going to need (requiredSize) // Size prefSize; if(elementProxy.AutoSize) { Size elementConstraints = new Size(Int32.MaxValue, rowBounds.Height - elementProxy.Margin.Size.Height); if(i == startIndex) { // If the element is the first in the row, attempt to pack it to the row width. (If its not 1st, it will wrap // to the first on the next row if its too long and then be packed if needed by the next call to xLayoutRow). elementConstraints.Width = rowBounds.Width - rowSize.Width - elementProxy.Margin.Size.Width; } // Make sure that subtracting the margins does not cause width/height to be <= 0, or we will // size as if we had infinite space when in fact we are trying to be as small as possible. elementConstraints = LayoutUtils.UnionSizes(new Size(1, 1), elementConstraints); prefSize = elementProxy.GetPreferredSize(elementConstraints); } else { // If autosizing is turned off, we just use the element's current size as its preferred size. prefSize = elementProxy.SpecifiedSize; // VSWhidbey 406227 // except if it is stretching - then ignore the affect of the height dimension. if (elementProxy.Stretches) { prefSize.Height = 0; } // Enforce MinimumSize if (prefSize.Height < elementProxy.MinimumSize.Height) { prefSize.Height = elementProxy.MinimumSize.Height; } } Size requiredSize = prefSize + elementProxy.Margin.Size; // Position the element (if applicable). // if(!measureOnly) { // If measureOnly = false, rowBounds.Height = measured row hieght // (otherwise its the remaining displayRect of the container) Rectangle cellBounds = new Rectangle(location, new Size(requiredSize.Width, rowBounds.Height)); // We laid out the rows with the elementProxy's margins included. // We now deflate the rect to get the actual elementProxy bounds. cellBounds = LayoutUtils.DeflateRect(cellBounds, elementProxy.Margin); AnchorStyles anchorStyles = elementProxy.AnchorStyles; containerProxy.Bounds = LayoutUtils.AlignAndStretch(prefSize, cellBounds, anchorStyles); } // Keep track of how much space is being used in this row // location.X += requiredSize.Width; if (laidOutItems > 0) { // If control does not fit on this row, exclude it from row and stop now. // Exception: If row is empty, allow this control to fit on it. So controls // that exceed the maximum row width will end up occupying their own rows. if(location.X > rowBounds.Right) { break; } } // Control fits on this row, so update the row size. // rowSize.Width != location.X because with a scrollable control // we could have started with a location like -100. rowSize.Width = location.X - rowBounds.X; rowSize.Height = Math.Max(rowSize.Height, requiredSize.Height); // check for line breaks. if (wrapContents) { if (breakOnNextItem) { break; } else if (i+1 < endIndex && CommonProperties.GetFlowBreak(elementProxy.Element)) { if (laidOutItems == 0) { breakOnNextItem = true; } else { breakIndex++; break; } } } ++laidOutItems; } return rowSize; } #region Provided properties public static bool GetWrapContents(IArrangedElement container) { int wrapContents = container.Properties.GetInteger(_wrapContentsProperty); return (wrapContents == 0); // if not set return true. } public static void SetWrapContents(IArrangedElement container, bool value) { container.Properties.SetInteger(_wrapContentsProperty, value ? 0 : 1); // set to 0 if true, 1 if false LayoutTransaction.DoLayout(container, container, PropertyNames.WrapContents); Debug.Assert(GetWrapContents(container) == value, "GetWrapContents should return the same value as we set"); } public static FlowDirection GetFlowDirection(IArrangedElement container) { return (FlowDirection) container.Properties.GetInteger(_flowDirectionProperty); } public static void SetFlowDirection(IArrangedElement container, FlowDirection value) { //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlowDirection.LeftToRight, (int)FlowDirection.BottomUp)){ throw new InvalidEnumArgumentException("value", (int)value, typeof(FlowDirection)); } container.Properties.SetInteger(_flowDirectionProperty, (int) value); LayoutTransaction.DoLayout(container, container, PropertyNames.FlowDirection); Debug.Assert(GetFlowDirection(container) == value, "GetFlowDirection should return the same value as we set"); } #endregion Provided properties #region ContainerProxy // What is a ContainerProxy? // // The goal of the FlowLayout Engine is to always layout from left to right. In order to achieve different // flow directions we have "Proxies" for the Container (the thing laying out) and for setting the bounds of the // child elements. // // We have a base ContainerProxy, and derived proxies for all of the flow directions. In order to achieve flow direction of RightToLeft, // the RightToLeft container proxy detects when we're going to set the bounds and translates it to the right. // // In order to do a vertical flow, such as TopDown, we pretend we're laying out horizontally. The main way this is // achieved is through the use of the VerticalElementProxy, which flips all rectangles and sizes. // // In order to do BottomUp, we combine the same techniques of TopDown with the RightToLeft flow. That is, // we override the bounds, and translate from left to right, AND use the VerticalElementProxy. // // A final note: This layout engine does all its RightToLeft translation itself. It does not support // WS_EX_LAYOUTRTL (OS mirroring). private class ContainerProxy { private IArrangedElement _container; private ElementProxy _elementProxy; private Rectangle _displayRect; private bool _isContainerRTL; public ContainerProxy(IArrangedElement container) { this._container = container; this._isContainerRTL = false; if (_container is Control) { _isContainerRTL = ((Control)(_container)).RightToLeft == RightToLeft.Yes; } } // method for setting the bounds of a child element. public virtual Rectangle Bounds { set { if (IsContainerRTL) { // Offset the X coordinate... if (IsVertical) { //Offset the Y value here, since it is really the X value.... value.Y = DisplayRect.Bottom - value.Bottom; } else { value.X = DisplayRect.Right - value.Right; } FlowLayoutPanel flp = Container as FlowLayoutPanel; if (flp != null) { Point ptScroll = flp.AutoScrollPosition; if (ptScroll != Point.Empty) { Point pt = new Point(value.X, value.Y); if (IsVertical) { //Offset the Y value here, since it is really the X value.... pt.Offset(0, ptScroll.X); } else { pt.Offset(ptScroll.X, 0); } value.Location = pt; } } } ElementProxy.Bounds = value; } } // specifies the container laying out public IArrangedElement Container { get { return _container; } } // specifies if we're TopDown or BottomUp and should use the VerticalElementProxy to translate protected virtual bool IsVertical { get { return false; } } // returns true if container is RTL.Yes protected bool IsContainerRTL { get { return _isContainerRTL; } } // returns the display rectangle of the container - this WILL BE FLIPPED if the layout // is a vertical layout. public Rectangle DisplayRect { get { return _displayRect; } set { if (_displayRect != value) { //flip the displayRect since when we do layout direction TopDown/BottomUp, we layout the controls //on the flipped rectangle as if our layout direction were LeftToRight/RightToLeft. In this case //we can save some code bloat _displayRect = LayoutUtils.FlipRectangleIf(IsVertical, value); } } } // returns the element proxy to use. A vertical element proxy will typically // flip all the sizes and rectangles so that it can fake being laid out in a horizontal manner. public ElementProxy ElementProxy { get { if (_elementProxy == null) { _elementProxy = (IsVertical) ? new VerticalElementProxy() : new ElementProxy(); } return _elementProxy; } } // used when you want to translate from right to left, but preserve Margin.Right & Margin.Left. protected Rectangle RTLTranslateNoMarginSwap(Rectangle bounds) { Rectangle newBounds = bounds; newBounds.X = DisplayRect.Right - bounds.X - bounds.Width + ElementProxy.Margin.Left - ElementProxy.Margin.Right; // Since DisplayRect.Right and bounds.X are both adjusted for the AutoScrollPosition, we need add it back here. FlowLayoutPanel flp = Container as FlowLayoutPanel; if (flp != null) { Point ptScroll = flp.AutoScrollPosition; if (ptScroll != Point.Empty) { Point pt = new Point(newBounds.X, newBounds.Y); if (IsVertical) { // TRICKY TRICKY TRICKY.... HACK HACK HACK... // // We need to treat Vertical a litte differently. It really helps if you draw this out. // Remember that when we layout BottomUp, we first layout TopDown, then call this method. // When we layout TopDown we layout in flipped rectangles. I.e. x becomes y, y becomes x, // height becomes width, width becomes height. We do our layout, then when we eventually // set the bounds of the child elements, we flip back. Thus, x will eventually // become y. We need to adjust for scrolling - but only in the y direction - // and since x becomes y, we adjust x. But since AutoScrollPoisition has not been swapped, // we need to use its Y coordinate when offsetting. // // DRAW THIS OUT!!! // // Did I mention you should draw this out? // // Did I mention that everything is flipped? pt.Offset(ptScroll.Y, 0); } else { pt.Offset(ptScroll.X, 0); } newBounds.Location = pt; } } return newBounds; } } // FlowDirection.RightToLeft proxy. private class RightToLeftProxy : ContainerProxy { public RightToLeftProxy(IArrangedElement container) : base(container) { } public override Rectangle Bounds { set { // if the container is RTL, align to the left, otherwise, align to the right. // Do NOT use LayoutUtils.RTLTranslate as we want to preserve the padding.Right on the right... base.Bounds = RTLTranslateNoMarginSwap(value); } } } // FlowDirection.TopDown proxy. // For TopDown we're really still laying out horizontally. The element proxy is the one // which flips all the rectangles and rotates itself into the vertical orientation. // to achieve right to left, we actually have to do something non-intuitive - instead of // sending the control to the right, we have to send the control to the bottom. When the rotation // is complete - that's equivilant to pushing it to the right. private class TopDownProxy : ContainerProxy { public TopDownProxy(IArrangedElement container) : base(container) { } protected override bool IsVertical { get { return true; } } } // FlowDirection.BottomUp proxy. private class BottomUpProxy : ContainerProxy { public BottomUpProxy(IArrangedElement container) : base(container) { } protected override bool IsVertical { get { return true; } } // For BottomUp we're really still laying out horizontally. The element proxy is the one // which flips all the rectangles and rotates itself into the vertical orientation. // BottomUp is the analog of RightToLeft - meaning, in order to place a control at the bottom, // the control has to be placed to the right. When the rotation is complete, that's the equivilant of // pushing it to the right. This must be done all the time. // // To achieve right to left, we actually have to do something non-intuitive - instead of // sending the control to the right, we have to send the control to the bottom. When the rotation // is complete - that's equivilant to pushing it to the right. public override Rectangle Bounds { set { // push the control to the bottom. // Do NOT use LayoutUtils.RTLTranslate as we want to preserve the padding.Right on the right... base.Bounds = RTLTranslateNoMarginSwap(value); } } } #endregion ContainerProxy #region ElementProxy // ElementProxy inserts a level of indirection between the LayoutEngine // and the IArrangedElement that allows us to use the same code path // for Vertical and Horizontal flow layout. (see VerticalElementProxy) private class ElementProxy { private IArrangedElement _element; public virtual AnchorStyles AnchorStyles { get { AnchorStyles anchorStyles = LayoutUtils.GetUnifiedAnchor(Element); bool isStretch = (anchorStyles & LayoutUtils.VerticalAnchorStyles) == LayoutUtils.VerticalAnchorStyles; //whether the control stretches to fill in the whole space bool isTop = (anchorStyles & AnchorStyles.Top) != 0; //whether the control anchors to top and does not stretch; bool isBottom = (anchorStyles & AnchorStyles.Bottom) != 0; //whether the control anchors to bottom and does not stretch; if(isStretch) { //the element stretches to fill in the whole row. Equivalent to AnchorStyles.Top|AnchorStyles.Bottom return LayoutUtils.VerticalAnchorStyles; } if(isTop) { //the element anchors to top and doesn't stretch return AnchorStyles.Top; } if(isBottom) { //the element anchors to bottom and doesn't stretch return AnchorStyles.Bottom; } return AnchorStyles.None; } } public bool AutoSize { get { return CommonProperties.GetAutoSize(_element); } } public virtual Rectangle Bounds { set { _element.SetBounds(value, BoundsSpecified.None); } } public IArrangedElement Element { get { return _element; } set { _element = value; Debug.Assert(Element == value, "Element should be the same as we set it to"); } } public bool Stretches { get { AnchorStyles styles = AnchorStyles; if ((LayoutUtils.VerticalAnchorStyles & styles) == LayoutUtils.VerticalAnchorStyles) { return true; } else { return false; } } } public virtual Padding Margin { get { return CommonProperties.GetMargin(Element); } } public virtual Size MinimumSize { get { return CommonProperties.GetMinimumSize(Element, Size.Empty); } } public bool ParticipatesInLayout { get { return _element.ParticipatesInLayout; } } public virtual Size SpecifiedSize { get { return CommonProperties.GetSpecifiedBounds(_element).Size; } } public virtual Size GetPreferredSize(Size proposedSize) { return _element.GetPreferredSize(proposedSize); } } // VerticalElementProxy swaps Top/Left, Bottom/Right, and other properties // so that the same code path used for horizantal flow can be applied to // vertical flow. private class VerticalElementProxy : ElementProxy { public override AnchorStyles AnchorStyles { get { AnchorStyles anchorStyles = LayoutUtils.GetUnifiedAnchor(Element); bool isStretch = (anchorStyles & LayoutUtils.HorizontalAnchorStyles) == LayoutUtils.HorizontalAnchorStyles; //whether the control stretches to fill in the whole space bool isLeft = (anchorStyles & AnchorStyles.Left) != 0; //whether the control anchors to left and does not stretch; bool isRight = (anchorStyles & AnchorStyles.Right) != 0; //whether the control anchors to right and does not stretch; if(isStretch) { return LayoutUtils.VerticalAnchorStyles; } if(isLeft) { return AnchorStyles.Top; } if(isRight) { return AnchorStyles.Bottom; } return AnchorStyles.None; } } public override Rectangle Bounds { set { base.Bounds = LayoutUtils.FlipRectangle(value); } } public override Padding Margin { get { return LayoutUtils.FlipPadding(base.Margin); } } public override Size MinimumSize { get { return LayoutUtils.FlipSize(base.MinimumSize); } } public override Size SpecifiedSize { get { return LayoutUtils.FlipSize(base.SpecifiedSize); } } public override Size GetPreferredSize(Size proposedSize) { return LayoutUtils.FlipSize(base.GetPreferredSize(LayoutUtils.FlipSize(proposedSize))); } } #endregion ElementProxy #region DEBUG [Conditional("DEBUG_VERIFY_ALIGNMENT")] private void Debug_VerifyAlignment(IArrangedElement container, FlowDirection flowDirection) { #if DEBUG //We cannot apply any of these checks @ design-time since dragging new children into a FlowLayoutPanel //will attempt to set the children at the mouse position when the child was dropped - we rely on the controil //to reposition the children once added. Control flp = container as Control; if (flp != null && flp.Site != null && flp.Site.DesignMode) { return; } //check to see if the first element is in its right place Padding margin = CommonProperties.GetMargin(container.Children[0]); switch (flowDirection) { case FlowDirection.LeftToRight: case FlowDirection.TopDown: Debug.Assert(container.Children[0].Bounds.Y == margin.Top + container.DisplayRectangle.Y); Debug.Assert(container.Children[0].Bounds.X == margin.Left + container.DisplayRectangle.X); break; case FlowDirection.RightToLeft: Debug.Assert(container.Children[0].Bounds.X == container.DisplayRectangle.X + container.DisplayRectangle.Width - container.Children[0].Bounds.Width - margin.Right); Debug.Assert(container.Children[0].Bounds.Y == margin.Top + container.DisplayRectangle.Y); break; case FlowDirection.BottomUp: Debug.Assert(container.Children[0].Bounds.Y == container.DisplayRectangle.Y + container.DisplayRectangle.Height - container.Children[0].Bounds.Height - margin.Bottom); Debug.Assert(container.Children[0].Bounds.X == margin.Left + container.DisplayRectangle.X); break; } //next check to see if everything is in bound ArrangedElementCollection collection = container.Children; for (int i = 1; i < collection.Count; i++) { switch (flowDirection) { case FlowDirection.LeftToRight: case FlowDirection.TopDown: Debug.Assert(collection[i].Bounds.Y >= container.DisplayRectangle.Y); Debug.Assert(collection[i].Bounds.X >= container.DisplayRectangle.X); break; case FlowDirection.RightToLeft: Debug.Assert(collection[i].Bounds.Y >= container.DisplayRectangle.Y); Debug.Assert(collection[i].Bounds.X + collection[i].Bounds.Width <= container.DisplayRectangle.X + container.DisplayRectangle.Width); break; case FlowDirection.BottomUp: Debug.Assert(collection[i].Bounds.Y + collection[i].Bounds.Height <= container.DisplayRectangle.Y + container.DisplayRectangle.Height); Debug.Assert(collection[i].Bounds.X >= container.DisplayRectangle.X); break; } } #endif } #endregion DEBUG } }
//------------------------------------------------------------------------------ // <copyright file="UniqueConstraint.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="false" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data { using System; using System.Diagnostics; using System.ComponentModel; /// <devdoc> /// <para> /// Represents a restriction on a set of columns in which all values must be unique. /// </para> /// </devdoc> [ DefaultProperty("ConstraintName"), Editor("Microsoft.VSDesigner.Data.Design.UniqueConstraintEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), ] public class UniqueConstraint : Constraint { private DataKey key; private Index _constraintIndex; internal bool bPrimaryKey = false; // Design time serialization internal string constraintName = null; internal string[] columnNames = null; /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified name and /// <see cref='System.Data.DataColumn'/>.</para> /// </devdoc> public UniqueConstraint(String name, DataColumn column) { DataColumn[] columns = new DataColumn[1]; columns[0] = column; Create(name, columns); } /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified <see cref='System.Data.DataColumn'/>.</para> /// </devdoc> public UniqueConstraint(DataColumn column) { DataColumn[] columns = new DataColumn[1]; columns[0] = column; Create(null, columns); } /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified name and array /// of <see cref='System.Data.DataColumn'/> objects.</para> /// </devdoc> public UniqueConstraint(String name, DataColumn[] columns) { Create(name, columns); } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the given array of <see cref='System.Data.DataColumn'/> /// objects. /// </para> /// </devdoc> public UniqueConstraint(DataColumn[] columns) { Create(null, columns); } // Construct design time object /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false)] public UniqueConstraint(String name, string[] columnNames, bool isPrimaryKey) { this.constraintName = name; this.columnNames = columnNames; this.bPrimaryKey = isPrimaryKey; } /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified name and /// <see cref='System.Data.DataColumn'/>.</para> /// </devdoc> public UniqueConstraint(String name, DataColumn column, bool isPrimaryKey) { DataColumn[] columns = new DataColumn[1]; columns[0] = column; this.bPrimaryKey = isPrimaryKey; Create(name, columns); } /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified <see cref='System.Data.DataColumn'/>.</para> /// </devdoc> public UniqueConstraint(DataColumn column, bool isPrimaryKey) { DataColumn[] columns = new DataColumn[1]; columns[0] = column; this.bPrimaryKey = isPrimaryKey; Create(null, columns); } /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified name and array /// of <see cref='System.Data.DataColumn'/> objects.</para> /// </devdoc> public UniqueConstraint(String name, DataColumn[] columns, bool isPrimaryKey) { this.bPrimaryKey = isPrimaryKey; Create(name, columns); } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the given array of <see cref='System.Data.DataColumn'/> /// objects. /// </para> /// </devdoc> public UniqueConstraint(DataColumn[] columns, bool isPrimaryKey) { this.bPrimaryKey = isPrimaryKey; Create(null, columns); } // design time serialization only internal string[] ColumnNames { get { return key.GetColumnNames(); } } // VSTFDEVDIV 895693: please note that there are scenarios where ConstraintIndex is not the same as key.GetSortIndex() // Use constraint index only for search operations (and use key.GetSortIndex() when enumeration is needed and/or order is important) internal Index ConstraintIndex { get { AssertConstraintAndKeyIndexes(); return _constraintIndex; } } [Conditional("DEBUG")] private void AssertConstraintAndKeyIndexes() { Debug.Assert(null != _constraintIndex, "null UniqueConstraint index"); // ideally, we would like constraintIndex and key.GetSortIndex to share the same index underneath: Debug.Assert(_constraintIndex == key.GetSortIndex) // but, due to VSTFDEVDIV #895693 there is a scenario where constraint and key indexes are built from the same list of columns but in a different order DataColumn[] sortIndexColumns = new DataColumn[_constraintIndex.IndexFields.Length]; for (int i = 0; i < sortIndexColumns.Length; i++) { sortIndexColumns[i] = _constraintIndex.IndexFields[i].Column; } Debug.Assert(DataKey.ColumnsEqual(key.ColumnsReference, sortIndexColumns), "UniqueConstraint index columns do not match the key sort index"); } internal void ConstraintIndexClear() { if (null != _constraintIndex) { _constraintIndex.RemoveRef(); _constraintIndex = null; } } internal void ConstraintIndexInitialize() { //Debug.Assert(null == _constraintIndex, "non-null UniqueConstraint index"); if (null == _constraintIndex) { _constraintIndex = key.GetSortIndex(); _constraintIndex.AddRef(); } AssertConstraintAndKeyIndexes(); } internal override void CheckState() { NonVirtualCheckState(); } private void NonVirtualCheckState() { key.CheckState(); } internal override void CheckCanAddToCollection(ConstraintCollection constraints) { } internal override bool CanBeRemovedFromCollection(ConstraintCollection constraints, bool fThrowException) { if (this.Equals(constraints.Table.primaryKey)) { Debug.Assert(constraints.Table.primaryKey == this, "If the primary key and this are 'Equal', they should also be '=='"); if (!fThrowException) return false; else throw ExceptionBuilder.RemovePrimaryKey(constraints.Table); } for (ParentForeignKeyConstraintEnumerator cs = new ParentForeignKeyConstraintEnumerator(Table.DataSet, Table); cs.GetNext();) { ForeignKeyConstraint constraint = cs.GetForeignKeyConstraint(); if (!key.ColumnsEqual(constraint.ParentKey)) continue; if (!fThrowException) return false; else throw ExceptionBuilder.NeededForForeignKeyConstraint(this, constraint); } return true; } internal override bool CanEnableConstraint() { if (Table.EnforceConstraints) return ConstraintIndex.CheckUnique(); return true; } internal override bool IsConstraintViolated() { bool result = false; Index index = ConstraintIndex; if (index.HasDuplicates) { // object[] uniqueKeys = index.GetUniqueKeyValues(); for (int i = 0; i < uniqueKeys.Length; i++) { Range r = index.FindRecords((object[])uniqueKeys[i]); if (1 < r.Count) { DataRow[] rows = index.GetRows(r); string error = ExceptionBuilder.UniqueConstraintViolationText(key.ColumnsReference, (object[])uniqueKeys[i]); for (int j = 0; j < rows.Length; j++) { // rows[j].RowError = error; foreach(DataColumn dataColumn in key.ColumnsReference){ rows[j].SetColumnError(dataColumn, error); } } // SQLBU 20011224: set_RowError for all DataRow with a unique constraint violation result = true; } } } return result; } internal override void CheckConstraint(DataRow row, DataRowAction action) { if (Table.EnforceConstraints && (action == DataRowAction.Add || action == DataRowAction.Change || (action == DataRowAction.Rollback && row.tempRecord != -1))) { if (row.HaveValuesChanged(ColumnsReference)) { if (ConstraintIndex.IsKeyRecordInIndex(row.GetDefaultRecord())) { object[] values = row.GetColumnValues(ColumnsReference); throw ExceptionBuilder.ConstraintViolation(ColumnsReference, values); } } } } internal override bool ContainsColumn(DataColumn column) { return key.ContainsColumn(column); } internal override Constraint Clone(DataSet destination) { return Clone(destination, false); } internal override Constraint Clone(DataSet destination, bool ignorNSforTableLookup) { int iDest; if (ignorNSforTableLookup) { iDest = destination.Tables.IndexOf(Table.TableName); } else { iDest = destination.Tables.IndexOf(Table.TableName, Table.Namespace, false);// pass false for last param to be backward compatable } if (iDest < 0) return null; DataTable table = destination.Tables[iDest]; int keys = ColumnsReference.Length; DataColumn[] columns = new DataColumn[keys]; for (int i = 0; i < keys; i++) { DataColumn src = ColumnsReference[i]; iDest = table.Columns.IndexOf(src.ColumnName); if (iDest < 0) return null; columns[i] = table.Columns[iDest]; } UniqueConstraint clone = new UniqueConstraint(ConstraintName, columns); // ...Extended Properties foreach(Object key in this.ExtendedProperties.Keys) { clone.ExtendedProperties[key]=this.ExtendedProperties[key]; } return clone; } internal UniqueConstraint Clone(DataTable table) { int keys = ColumnsReference.Length; DataColumn[] columns = new DataColumn[keys]; for (int i = 0; i < keys; i++) { DataColumn src = ColumnsReference[i]; int iDest = table.Columns.IndexOf(src.ColumnName); if (iDest < 0) return null; columns[i] = table.Columns[iDest]; } UniqueConstraint clone = new UniqueConstraint(ConstraintName, columns); // ...Extended Properties foreach(Object key in this.ExtendedProperties.Keys) { clone.ExtendedProperties[key]=this.ExtendedProperties[key]; } return clone; } /// <devdoc> /// <para>Gets the array of columns that this constraint affects.</para> /// </devdoc> [ ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.KeyConstraintColumnsDescr), ReadOnly(true) ] public virtual DataColumn[] Columns { get { return key.ToArray(); } } internal DataColumn[] ColumnsReference { get { return key.ColumnsReference; } } /// <devdoc> /// <para>Gets /// a value indicating whether or not the constraint is on a primary key.</para> /// </devdoc> [ ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.KeyConstraintIsPrimaryKeyDescr) ] public bool IsPrimaryKey { get { if (Table == null) { return false; } return(this == Table.primaryKey); } } private void Create(String constraintName, DataColumn[] columns) { for (int i = 0; i < columns.Length; i++) { if (columns[i].Computed) { throw ExceptionBuilder.ExpressionInConstraint(columns[i]); } } this.key = new DataKey(columns, true); ConstraintName = constraintName; NonVirtualCheckState(); } /// <devdoc> /// <para>Compares this constraint to a second to /// determine if both are identical.</para> /// </devdoc> public override bool Equals(object key2) { if (!(key2 is UniqueConstraint)) return false; return Key.ColumnsEqual(((UniqueConstraint)key2).Key); } public override Int32 GetHashCode() { return base.GetHashCode(); } internal override bool InCollection { set { base.InCollection = value; if (key.ColumnsReference.Length == 1) { key.ColumnsReference[0].InternalUnique(value); } } } internal DataKey Key { get { return key; } } /// <devdoc> /// <para>Gets the table to which this constraint belongs.</para> /// </devdoc> [ ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.ConstraintTableDescr), ReadOnly(true) ] public override DataTable Table { get { if (key.HasValue) { return key.Table; } return null; } } // misc } }
using System; using System.Collections.Generic; using System.Linq; namespace Script { public struct Pair<A,B> { public A a; public B b; } public struct Either<A,B> { public A a; public B b; public bool has_a; public bool has_b; public static Either<A,B> mk_left(A a) { return new Either<A, B>() { a = a, has_a = true, has_b = false }; } public static Either<A,B> mk_right(B b) { return new Either<A, B>() { b = b, has_a = false, has_b = true }; } } public struct Unit {} public enum ResultType { Result, Wait, Yield } public class ResultValue<T> { public T result; public float wait; public ResultType type; public static ResultValue<T> new_result(T result) { Script.count(); return new ResultValue<T>() { result = result, wait = 0.0f, type = ResultType.Result }; } public static ResultValue<T> new_wait(float t) { Script.count(); return new ResultValue<T>() { result = default(T), wait = t, type = ResultType.Wait }; } public static ResultValue<T> new_yield() { Script.count(); return new ResultValue<T>() { result = default(T), wait = 0.0f, type = ResultType.Yield }; } public ResultValue<T1> Cast<T1>(Func<T,T1> cast) { Script.count(); return new ResultValue<T1>() { result = cast(this.result), wait = this.wait, type = this.type }; } } public static class Script { static private int steps = 0; static private DateTime start = DateTime.Now; static public void reset() {steps = 0; start = DateTime.Now;} static public void count() {steps++;} static public void summarize() { var t = (DateTime.Now - start).TotalSeconds; Console.WriteLine("performed " + steps + " in " + t + " seconds: " + steps / t + " steps/seconds"); } static public T Run<T>(this IEnumerable<ResultValue<T>> p) { reset(); var result = default(T); foreach(var x in p) if(x.type == ResultType.Result) { result = x.result; break; } else if (x.type == ResultType.Wait) { var start = DateTime.Now; while(true) { var now = DateTime.Now; if((now - start).TotalSeconds >= x.wait) break; } } summarize(); return result; } static public IEnumerable<ResultValue<Pair<T1,T2>>> parallel_<T1, T2>(this IEnumerable<ResultValue<T1>> p1, IEnumerable<ResultValue<T2>> p2) { var e1 = p1.GetEnumerator(); var e2 = p2.GetEnumerator(); var result1 = default(T1); var done_e1 = false; var waiting_e1 = 0.0f; var done_e2 = false; var waiting_e2 = 0.0f; var result2 = default(T2); var start = DateTime.Now; while (!done_e1 || !done_e2) { if(waiting_e1 <= 0.0f && done_e1 == false) { if(e1.MoveNext()) { var r1 = e1.Current; if(r1.type == ResultType.Wait) waiting_e1 = r1.wait; else if (r1.type == ResultType.Result) { done_e1 = true; result1 = r1.result; } } else done_e1 = true; } if(waiting_e2 <= 0.0f && done_e2 == false) { if(e2.MoveNext()) { var r2 = e2.Current; if(r2.type == ResultType.Wait) waiting_e2 = r2.wait; else if (r2.type == ResultType.Result) { done_e2 = true; result2 = r2.result; } } else done_e2 = true; } var now = DateTime.Now; var dt = (now - start).TotalSeconds; start = now; waiting_e1 -= (float)dt; waiting_e2 -= (float)dt; yield return ResultValue<Pair<T1,T2>>.new_yield(); } yield return ResultValue<Pair<T1,T2>>.new_result(new Pair<T1,T2>(){ a = result1, b = result2 }); } static public IEnumerable<ResultValue<Either<T1,T2>>> parallel_first_<T1, T2>(this IEnumerable<ResultValue<T1>> p1, IEnumerable<ResultValue<T2>> p2) { var e1 = p1.GetEnumerator(); var e2 = p2.GetEnumerator(); var result1 = default(T1); var done_e1 = false; var waiting_e1 = 0.0f; var done_e2 = false; var waiting_e2 = 0.0f; var result2 = default(T2); var start = DateTime.Now; while (!done_e1 && !done_e2) { if(waiting_e1 <= 0.0f && done_e1 == false) { if(e1.MoveNext()) { var r1 = e1.Current; if(r1.type == ResultType.Wait) waiting_e1 = r1.wait; else if (r1.type == ResultType.Result) { done_e1 = true; result1 = r1.result; } } else done_e1 = true; } yield return ResultValue<Either<T1,T2>>.new_yield(); if(waiting_e2 <= 0.0f && done_e2 == false) { if(e2.MoveNext()) { var r2 = e2.Current; if(r2.type == ResultType.Wait) waiting_e2 = r2.wait; else if (r2.type == ResultType.Result) { done_e2 = true; result2 = r2.result; } } else done_e2 = true; } yield return ResultValue<Either<T1,T2>>.new_yield(); var now = DateTime.Now; var dt = (now - start).TotalSeconds; start = now; waiting_e1 -= (float)dt; waiting_e2 -= (float)dt; } if(done_e1) yield return ResultValue<Either<T1,T2>>.new_result(Either<T1,T2>.mk_left(result1)); else if(done_e2) yield return ResultValue<Either<T1,T2>>.new_result(Either<T1,T2>.mk_right(result2)); } static public IEnumerable<ResultValue<Unit>> ignore_<T>(this IEnumerable<ResultValue<T>> p) { foreach (ResultValue<T> x in p) { yield return x.Cast<Unit>(v => new Unit()); } } static private IEnumerable<ResultValue<Unit>> parallel_many_<T>(this IEnumerable<ResultValue<T>>[] ps, int min) { if(min >= ps.Length) return new ResultValue<Unit>[]{}; else return ignore_(parallel_(ps[min], parallel_many_(ps, min+1))); } static public IEnumerable<ResultValue<Unit>> parallel_many_<T>(this IEnumerable<ResultValue<T>>[] ps) { return parallel_many_(ps,0); } } }